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.
- package/fixtures/invalid/projection-result-applied-incomplete-coverage.json +3 -3
- package/fixtures/valid/archctx-capabilities.json +2 -2
- package/fixtures/valid/flow-selector-check.json +1 -1
- package/fixtures/valid/product-version-manifest.json +5 -11
- package/fixtures/valid/projection-manifest.json +1 -1
- package/fixtures/valid/projection-result.json +3 -3
- package/package.json +4 -1
- package/schemas/repo/refactor-decision.schema.json +283 -37
- package/schemas/runtime/archctx-capabilities.schema.json +144 -20
- package/schemas/runtime/architecture-debt-delta.schema.json +58 -19
- package/schemas/runtime/architecture-debt.schema.json +42 -42
- package/schemas/runtime/architecture-event.schema.json +1 -1
- package/schemas/runtime/architecture-history.schema.json +354 -0
- package/schemas/runtime/capability-dependencies.schema.json +266 -59
- package/schemas/runtime/cli-check.schema.json +197 -0
- package/schemas/runtime/cli-help.schema.json +28 -0
- package/schemas/runtime/dependency-constraint-evaluation.schema.json +67 -68
- package/schemas/runtime/docs-anchors.schema.json +250 -67
- package/schemas/runtime/doctor-code-facts.schema.json +49 -0
- package/schemas/runtime/evidence-binding.schema.json +1 -1
- package/schemas/runtime/flow-selector-check.schema.json +179 -46
- package/schemas/runtime/hook-debt-checkpoint.schema.json +12 -12
- package/schemas/runtime/index-seed.schema.json +56 -0
- package/schemas/runtime/path-context.schema.json +108 -0
- package/schemas/runtime/product-version-manifest.schema.json +142 -54
- package/schemas/runtime/projection-apply-readback.schema.json +2 -2
- package/schemas/runtime/projection-apply-recovery.schema.json +1 -1
- package/schemas/runtime/projection-result.schema.json +1 -1
- package/schemas/runtime/projection-slice.schema.json +34 -34
- package/schemas/runtime/recommendation-v3.schema.json +372 -1
- package/schemas/runtime/ref-impact-batch-request.schema.json +20 -7
- package/schemas/runtime/ref-impact-batch.schema.json +83 -13
- package/schemas/runtime/ref-impact.schema.json +68 -61
- package/schemas/runtime/refactor-scan-v2.schema.json +434 -0
- package/schemas/runtime/refactor-simulate.schema.json +505 -0
- package/schemas/runtime/refactor-verify-v2.schema.json +172 -0
- package/schemas/runtime/resolve-path.schema.json +69 -0
- package/schemas/runtime/runtime-recommendation-show.schema.json +531 -2
- package/schemas/runtime/runtime-refactor-scan.schema.json +498 -2
- package/schemas/runtime/runtime-verify.schema.json +274 -56
- package/schemas/runtime/state-machine-check.schema.json +357 -89
- package/schemas/runtime/structural-observation-payload.schema.json +372 -1
- package/schemas/runtime/sync-check.schema.json +65 -0
- package/src/architecture-debt.ts +125 -38
- package/src/architecture-history.ts +168 -42
- package/src/architecture.ts +100 -0
- package/src/cli-read.ts +228 -0
- package/src/docs-anchors.ts +105 -50
- package/src/explorer-occurrence-ports.ts +175 -0
- package/src/explorer-query-ports.ts +270 -0
- package/src/failure.ts +3 -0
- package/src/index-seed.ts +42 -0
- package/src/index.ts +5 -0
- package/src/ledger-records.ts +262 -0
- package/src/ledger.ts +27 -566
- package/src/ownership-dependencies.ts +115 -5
- package/src/ports.ts +12 -543
- package/src/product-version.ts +75 -56
- package/src/projection-apply-types.ts +216 -0
- package/src/projection-apply-validators.ts +355 -0
- package/src/projection-capabilities.ts +181 -0
- package/src/projection-constants.ts +317 -0
- package/src/projection-manifest-types.ts +298 -0
- package/src/projection-manifest.ts +12 -299
- package/src/projection-recovery-validators.ts +229 -0
- package/src/projection-request-validators.ts +326 -0
- package/src/projection-types.ts +365 -0
- package/src/projection-validation-helpers.ts +15 -0
- package/src/projection.ts +7 -1689
- package/src/ref-impact.ts +225 -33
- package/src/refactor-constants.ts +213 -0
- package/src/refactor-decision-validators.ts +350 -0
- package/src/refactor-evidence-types.ts +286 -0
- package/src/refactor-observation-validators.ts +359 -0
- package/src/refactor-resolution-validators.ts +229 -0
- package/src/refactor-snapshot-validators.ts +368 -0
- package/src/refactor-types.ts +270 -0
- package/src/refactor-v2.ts +389 -0
- package/src/refactor-validation-helpers.ts +195 -0
- package/src/refactor.ts +7 -1849
- package/src/review-guards.ts +3 -23
- package/src/runtime-verify.ts +87 -0
- package/src/schema-kit.ts +183 -0
- package/src/schema-registry.ts +73 -0
- package/src/schema.ts +0 -4
- package/src/state-machine-schemas.ts +192 -0
- package/src/state-machine-types.ts +188 -0
- package/src/state-machine.ts +9 -189
- package/fixtures/boundary/agent-job-expired.json +0 -33
- package/fixtures/invalid/adapter-fidelity-reverse-sync.json +0 -9
- package/fixtures/invalid/agent-job-direct-mutation.json +0 -32
- package/fixtures/invalid/cloud-egress-envelope-private-field.json +0 -12
- package/fixtures/invalid/investigation-report-direct-mutation.json +0 -38
- package/fixtures/invalid/investigation-report-missing-proposed-delta.json +0 -19
- package/fixtures/invalid/notification-event-code-field.json +0 -11
- package/fixtures/valid/adapter-fidelity.json +0 -9
- package/fixtures/valid/agent-job.json +0 -33
- package/fixtures/valid/architecture-candidate-delta-policy.json +0 -45
- package/fixtures/valid/architecture-candidate-delta.json +0 -188
- package/fixtures/valid/chatgpt-ga-tool.json +0 -9
- package/fixtures/valid/cloud-egress-envelope.json +0 -11
- package/fixtures/valid/entitlement.json +0 -12
- package/fixtures/valid/investigation-report.json +0 -38
- package/fixtures/valid/likec4-mapping.json +0 -14
- package/fixtures/valid/notification-event.json +0 -10
- package/fixtures/valid/notification-provider.json +0 -12
- package/fixtures/valid/structurizr-mapping.json +0 -15
- package/schemas/cloud/cloud-egress-envelope.schema.json +0 -19
- package/schemas/cloud/entitlement.schema.json +0 -24
- package/schemas/integrations/adapter-fidelity.schema.json +0 -21
- package/schemas/integrations/chatgpt-ga-tool.schema.json +0 -25
- package/schemas/integrations/likec4-mapping.schema.json +0 -32
- package/schemas/integrations/structurizr-mapping.schema.json +0 -33
- package/schemas/runtime/agent-job.schema.json +0 -63
- package/schemas/runtime/architecture-candidate-delta-policy.schema.json +0 -129
- package/schemas/runtime/architecture-candidate-delta.schema.json +0 -386
- package/schemas/runtime/investigation-report.schema.json +0 -119
- package/schemas/runtime/notification-event.schema.json +0 -18
- package/schemas/runtime/notification-provider.schema.json +0 -26
package/src/refactor.ts
CHANGED
|
@@ -1,1849 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
PracticeRecommendationPayloadV1,
|
|
9
|
-
RecommendationAuthorV1,
|
|
10
|
-
RecommendationCategory,
|
|
11
|
-
RecommendationPayloadV1,
|
|
12
|
-
RecommendationStatus,
|
|
13
|
-
RecommendationV3,
|
|
14
|
-
RecommendationV3Base,
|
|
15
|
-
RefactorProposalPayloadV1,
|
|
16
|
-
StructuralObservationPayloadV1
|
|
17
|
-
} from "./ledger";
|
|
18
|
-
import { ARCHITECTURE_MAJOR_CHANGE_REASON_CODES, type ArchitectureMajorChangeReasonCode } from "./projection";
|
|
19
|
-
import { digestJson, isRepoRelativePosixPath, type Json, type Severity } from "./schema";
|
|
20
|
-
|
|
21
|
-
const DIGEST_PREFIX_LENGTH = "sha256:".length;
|
|
22
|
-
const SHA256_DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;
|
|
23
|
-
const BARE_SHA256_PATTERN = /^[a-f0-9]{64}$/;
|
|
24
|
-
const GIT_HEAD_SHA_PATTERN = /^[a-f0-9]{40}$/;
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* The bounded grammar an execution evidence `locator` must fit: 1..256 characters drawn from the
|
|
28
|
-
* unreserved plus sub-delims/gen-delims set that repo-relative paths and URLs already live in.
|
|
29
|
-
*
|
|
30
|
-
* A locator is a *reference*, not a body. Left unbounded it is a string field on a record whose
|
|
31
|
-
* envelope promises `privacy.rawDiffPersisted: false`, so a caller could park a whole diff, a
|
|
32
|
-
* credential, or a multi-line prompt in it and the digest check would still pass. Whitespace,
|
|
33
|
-
* newlines and control characters are the shapes that only a body has, and the length ceiling is
|
|
34
|
-
* what stops a single-line body from riding through anyway.
|
|
35
|
-
*/
|
|
36
|
-
export const REFACTOR_EXECUTION_EVIDENCE_LOCATOR_PATTERN = /^[A-Za-z0-9._~:\/?#@!$&'()*+,;=%-]{1,256}$/;
|
|
37
|
-
|
|
38
|
-
/** The single sentence every ingress uses to name the locator rule, so they cannot drift apart. */
|
|
39
|
-
export const REFACTOR_EXECUTION_EVIDENCE_LOCATOR_RULE =
|
|
40
|
-
"must be a bounded reference: 1-256 characters from [A-Za-z0-9._~:/?#@!$&'()*+,;=%-], no whitespace or control characters";
|
|
41
|
-
|
|
42
|
-
/** The only top-level keys a verification request may carry; anything else is a caller typo. */
|
|
43
|
-
export const REFACTOR_VERIFICATION_REQUEST_KEYS = [
|
|
44
|
-
"executionEvidenceRefs",
|
|
45
|
-
"expectedHeadSha",
|
|
46
|
-
"expectedWorktreeDigest",
|
|
47
|
-
"importNodeLimit",
|
|
48
|
-
"recommendationId",
|
|
49
|
-
"schemaVersion"
|
|
50
|
-
] as const;
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* The grammar of the refactor identity namespace: the manifest `product.id`, which scopes every
|
|
54
|
-
* refactor subject selector so one subject has one recommendation id in every worktree, branch and
|
|
55
|
-
* clone (ADR-0046). It is the declared-id grammar node ids use, without the cross-repo prefix.
|
|
56
|
-
*/
|
|
57
|
-
export const REFACTOR_NAMESPACE_PATTERN = /^[a-z][a-z0-9]*(\.[a-z0-9][a-z0-9-]*)+$/;
|
|
58
|
-
|
|
59
|
-
/** Issues with a refactor namespace value; empty when it is a well-formed `product.id`. */
|
|
60
|
-
export function refactorNamespaceIssues(value: unknown, label = "product.id"): string[] {
|
|
61
|
-
if (typeof value !== "string") return [`${label} must be a string`];
|
|
62
|
-
if (value.trim() === "") return [`${label} must not be blank`];
|
|
63
|
-
return REFACTOR_NAMESPACE_PATTERN.test(value)
|
|
64
|
-
? []
|
|
65
|
-
: [`${label} must match ${REFACTOR_NAMESPACE_PATTERN.source}`];
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export const REFACTOR_REQUEST_SCHEMA_VERSION = "archcontext.refactor-request/v1" as const;
|
|
69
|
-
export const REFACTOR_PROPOSAL_SCHEMA_VERSION = "archcontext.refactor-proposal/v1" as const;
|
|
70
|
-
export const MODULE_STATISTICS_SCHEMA_VERSION = "archcontext.module-statistics/v1" as const;
|
|
71
|
-
export const REFACTOR_ASSESSMENT_SCHEMA_VERSION = "archcontext.refactor-assessment/v1" as const;
|
|
72
|
-
export const REFACTOR_RESOLUTION_EVIDENCE_SCHEMA_VERSION = "archcontext.refactor-resolution-evidence/v1" as const;
|
|
73
|
-
export const REFACTOR_VERIFICATION_REQUEST_SCHEMA_VERSION = "archcontext.refactor-verification-request/v1" as const;
|
|
74
|
-
|
|
75
|
-
export const REFACTOR_SCALES = [
|
|
76
|
-
"architecture",
|
|
77
|
-
"cross_module",
|
|
78
|
-
"insufficient_evidence",
|
|
79
|
-
"model_adoption_required",
|
|
80
|
-
"module"
|
|
81
|
-
] as const;
|
|
82
|
-
export const REFACTOR_SCALE_REASON_CODES = [
|
|
83
|
-
"caller-coverage-unknown",
|
|
84
|
-
"code-facts-import-limit",
|
|
85
|
-
"code-facts-missing",
|
|
86
|
-
"code-facts-truncated",
|
|
87
|
-
"major-change-detected",
|
|
88
|
-
"multi-node-scope",
|
|
89
|
-
"node-footprint-undeclared",
|
|
90
|
-
"ownership-ambiguous",
|
|
91
|
-
"single-node-scope",
|
|
92
|
-
"target-unresolved",
|
|
93
|
-
"unowned-paths"
|
|
94
|
-
] as const;
|
|
95
|
-
/**
|
|
96
|
-
* `cycle` is one bidirectional module pair; `residual-cycle` is a strongly connected component that
|
|
97
|
-
* survives cutting the thin direction of every pair (ADR-0046).
|
|
98
|
-
*/
|
|
99
|
-
export const REFACTOR_OBSERVATION_KINDS = [
|
|
100
|
-
"cycle",
|
|
101
|
-
"direction-violation",
|
|
102
|
-
"evidence-gap",
|
|
103
|
-
"ownership-ambiguous",
|
|
104
|
-
"residual-cycle",
|
|
105
|
-
"undeclared-footprint",
|
|
106
|
-
"unowned-paths"
|
|
107
|
-
] as const;
|
|
108
|
-
export const REFACTOR_RESOLUTION_DISPOSITIONS = [
|
|
109
|
-
"not_improved",
|
|
110
|
-
"partially_resolved",
|
|
111
|
-
"regressed",
|
|
112
|
-
"resolved",
|
|
113
|
-
"stale"
|
|
114
|
-
] as const;
|
|
115
|
-
export const REFACTOR_OUTCOME_OPERATORS = ["absent", "equals", "greater_than", "less_than", "present"] as const;
|
|
116
|
-
export const REFACTOR_OUTCOME_DIRECTIONS = ["improved", "regressed", "unchanged", "unknown"] as const;
|
|
117
|
-
export const REFACTOR_KILL_LIST_KINDS = ["path", "relation", "symbol"] as const;
|
|
118
|
-
export const REFACTOR_EXECUTION_EVIDENCE_KINDS = [
|
|
119
|
-
"acceptance_receipt",
|
|
120
|
-
"cutover_closure",
|
|
121
|
-
"merge_receipt",
|
|
122
|
-
"task_contract"
|
|
123
|
-
] as const;
|
|
124
|
-
export const REFACTOR_PROPOSAL_AUTHOR_SOURCES = ["cli", "manual", "mcp", "subagent"] as const;
|
|
125
|
-
export const REFACTOR_PROPOSAL_AUTHOR_KINDS = ["cli", "developer", "mcp", "subagent"] as const;
|
|
126
|
-
/**
|
|
127
|
-
* A refactor proposal is authored by an agent surface acting for itself, or by
|
|
128
|
-
* a human acting manually. `daemon`, `system`, `hook`, and `migration` kinds
|
|
129
|
-
* are ArchContext acting on its own behalf and can never author a proposal.
|
|
130
|
-
*/
|
|
131
|
-
export const REFACTOR_PROPOSAL_AUTHOR_PAIRS: Readonly<Record<RefactorProposalAuthorKind, readonly RefactorProposalAuthorSource[]>> = {
|
|
132
|
-
cli: ["cli"],
|
|
133
|
-
developer: ["manual"],
|
|
134
|
-
mcp: ["mcp"],
|
|
135
|
-
subagent: ["subagent"]
|
|
136
|
-
};
|
|
137
|
-
export const MODULE_DYNAMIC_INVOCATION_LEVELS = ["known", "none_observed", "possible", "unknown"] as const;
|
|
138
|
-
export const MODULE_TESTS_COVERAGE_STATUSES = ["measured", "partial", "unknown"] as const;
|
|
139
|
-
|
|
140
|
-
export type RefactorScale = (typeof REFACTOR_SCALES)[number];
|
|
141
|
-
export type RefactorScaleReasonCode = (typeof REFACTOR_SCALE_REASON_CODES)[number];
|
|
142
|
-
export type RefactorObservationKind = (typeof REFACTOR_OBSERVATION_KINDS)[number];
|
|
143
|
-
export type RefactorResolutionDisposition = (typeof REFACTOR_RESOLUTION_DISPOSITIONS)[number];
|
|
144
|
-
export type RefactorOutcomeOperator = (typeof REFACTOR_OUTCOME_OPERATORS)[number];
|
|
145
|
-
export type RefactorOutcomeDirection = (typeof REFACTOR_OUTCOME_DIRECTIONS)[number];
|
|
146
|
-
export type RefactorKillListKind = (typeof REFACTOR_KILL_LIST_KINDS)[number];
|
|
147
|
-
export type RefactorExecutionEvidenceKind = (typeof REFACTOR_EXECUTION_EVIDENCE_KINDS)[number];
|
|
148
|
-
export type RefactorProposalAuthorSource = (typeof REFACTOR_PROPOSAL_AUTHOR_SOURCES)[number];
|
|
149
|
-
export type RefactorProposalAuthorKind = (typeof REFACTOR_PROPOSAL_AUTHOR_KINDS)[number];
|
|
150
|
-
export type ModuleDynamicInvocationLevel = (typeof MODULE_DYNAMIC_INVOCATION_LEVELS)[number];
|
|
151
|
-
export type ModuleTestsCoverageStatus = (typeof MODULE_TESTS_COVERAGE_STATUSES)[number];
|
|
152
|
-
|
|
153
|
-
export type RefactorScopeV1 =
|
|
154
|
-
| { kind: "repository" }
|
|
155
|
-
| { kind: "node"; nodeId: string }
|
|
156
|
-
| { kind: "paths"; paths: string[] };
|
|
157
|
-
|
|
158
|
-
export interface RefactorTargetOutcomeV1 {
|
|
159
|
-
outcomeId: string;
|
|
160
|
-
metric: string;
|
|
161
|
-
subjectSelectorId: string;
|
|
162
|
-
nodeId: string | null;
|
|
163
|
-
/**
|
|
164
|
-
* The module set a `moduleDependencies.*` metric is measured over: the two ends of a pair, or the
|
|
165
|
-
* members of a residual cycle. Present exactly for that metric family, sorted and unique.
|
|
166
|
-
*/
|
|
167
|
-
memberNodeIds?: string[];
|
|
168
|
-
operator: RefactorOutcomeOperator;
|
|
169
|
-
value: number | null;
|
|
170
|
-
required: boolean;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
export interface RefactorObservedOutcomeV1 {
|
|
174
|
-
outcomeId: string;
|
|
175
|
-
observedValue: number | null;
|
|
176
|
-
satisfied: boolean;
|
|
177
|
-
direction: RefactorOutcomeDirection;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
export interface RefactorKillListEntryV1 {
|
|
181
|
-
kind: RefactorKillListKind;
|
|
182
|
-
selectorId: string;
|
|
183
|
-
required: boolean;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export interface ArchitectureTargetDeltaV1 {
|
|
187
|
-
interventionId: string;
|
|
188
|
-
trigger: string[];
|
|
189
|
-
thesis: string;
|
|
190
|
-
targetState: {
|
|
191
|
-
owners: Record<string, string>;
|
|
192
|
-
requiredRelations: string[];
|
|
193
|
-
removedConcepts: string[];
|
|
194
|
-
};
|
|
195
|
-
migrationState: {
|
|
196
|
-
active: boolean;
|
|
197
|
-
compatibilityContracts: string[];
|
|
198
|
-
cleanupBy?: string;
|
|
199
|
-
temporaryRelations: string[];
|
|
200
|
-
};
|
|
201
|
-
completionCriteria: RefactorTargetOutcomeV1[];
|
|
202
|
-
falsifiers: string[];
|
|
203
|
-
benefitLedger: {
|
|
204
|
-
benefits: string[];
|
|
205
|
-
costs: string[];
|
|
206
|
-
rollbackPoint: string;
|
|
207
|
-
};
|
|
208
|
-
unresolvedTargets: string[];
|
|
209
|
-
extensions?: Record<string, Json>;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
export interface RefactorProposalV1 {
|
|
213
|
-
schemaVersion: typeof REFACTOR_PROPOSAL_SCHEMA_VERSION;
|
|
214
|
-
authoredBy: RecommendationAuthorV1;
|
|
215
|
-
intent: string;
|
|
216
|
-
scopePaths: string[];
|
|
217
|
-
targetDelta?: ArchitectureTargetDeltaV1;
|
|
218
|
-
targetOutcomes: RefactorTargetOutcomeV1[];
|
|
219
|
-
killList: RefactorKillListEntryV1[];
|
|
220
|
-
proposalDigest: string;
|
|
221
|
-
extensions?: Record<string, Json>;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
export interface RefactorRequestV1 {
|
|
225
|
-
schemaVersion: typeof REFACTOR_REQUEST_SCHEMA_VERSION;
|
|
226
|
-
scope: RefactorScopeV1;
|
|
227
|
-
proposal?: RefactorProposalV1;
|
|
228
|
-
expectedHeadSha?: string;
|
|
229
|
-
expectedWorktreeDigest?: string;
|
|
230
|
-
task?: string;
|
|
231
|
-
/**
|
|
232
|
-
* The most CodeGraph import nodes the scan reads. Omitted means the runtime default. A larger
|
|
233
|
-
* index gives partial coverage with `code-facts-import-limit`, never `code-facts-truncated`.
|
|
234
|
-
*/
|
|
235
|
-
importNodeLimit?: number;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* The JSON ingress for `refactor verify`. `recommendationId` is the whole subject: a verification
|
|
240
|
-
* always re-measures whatever is at HEAD now, so there is no caller-supplied AFTER state and no
|
|
241
|
-
* outcome override — the recorded recommendation already carries the acceptance test, and letting
|
|
242
|
-
* a caller restate it would let the requester steer its own verdict.
|
|
243
|
-
*
|
|
244
|
-
* `expectedHeadSha` and `expectedWorktreeDigest` are claims about the state the caller believes it
|
|
245
|
-
* is verifying. A claim that no longer holds is refused rather than answered with fresh numbers
|
|
246
|
-
* under the old identity.
|
|
247
|
-
*/
|
|
248
|
-
export interface RefactorVerificationRequestV1 {
|
|
249
|
-
schemaVersion: typeof REFACTOR_VERIFICATION_REQUEST_SCHEMA_VERSION;
|
|
250
|
-
recommendationId: string;
|
|
251
|
-
expectedHeadSha?: string;
|
|
252
|
-
expectedWorktreeDigest?: string;
|
|
253
|
-
executionEvidenceRefs?: RefactorExecutionEvidenceRefV1[];
|
|
254
|
-
/**
|
|
255
|
-
* The most CodeGraph import nodes the re-measure reads. Omitted means the limit the recorded
|
|
256
|
-
* baseline snapshot was measured with, so BEFORE and AFTER read the same import population.
|
|
257
|
-
*/
|
|
258
|
-
importNodeLimit?: number;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
export interface ModuleStatisticsV1 {
|
|
262
|
-
nodeId: string;
|
|
263
|
-
nodeDigest: string;
|
|
264
|
-
parentNodeId: string | null;
|
|
265
|
-
footprintDeclared: boolean;
|
|
266
|
-
footprint: {
|
|
267
|
-
fileCount: number;
|
|
268
|
-
lineCount: number;
|
|
269
|
-
sourceFilesDigest: string;
|
|
270
|
-
includePatterns: string[];
|
|
271
|
-
excludePatterns: string[];
|
|
272
|
-
} | null;
|
|
273
|
-
surfaces: {
|
|
274
|
-
declaredEntrypoints: string[];
|
|
275
|
-
observedEntrypoints: string[];
|
|
276
|
-
lifecycleOwners: string[];
|
|
277
|
-
datastoreSubjects: string[];
|
|
278
|
-
};
|
|
279
|
-
dependencyGraph: {
|
|
280
|
-
internalEdgeCount: number;
|
|
281
|
-
inboundModuleEdges: number;
|
|
282
|
-
outboundModuleEdges: number;
|
|
283
|
-
fanIn: number;
|
|
284
|
-
fanOut: number;
|
|
285
|
-
stronglyConnectedComponentId: string | null;
|
|
286
|
-
cycleCount: number;
|
|
287
|
-
instability: number | null;
|
|
288
|
-
directionViolationCount: number | null;
|
|
289
|
-
} | null;
|
|
290
|
-
/**
|
|
291
|
-
* `callerCoverage` is a graph-boundary resolution ratio (the share of the
|
|
292
|
-
* module's inbound call boundary the index could resolve), not a test
|
|
293
|
-
* measurement, so it is independent of `coverageStatus`: a producer may know
|
|
294
|
-
* the boundary ratio while observing no test evidence at all, and it may know
|
|
295
|
-
* test files while the boundary stays unresolved. Only the 0-1 ratio bound is
|
|
296
|
-
* enforced; the two fields are never coupled (PRD 0.3-16).
|
|
297
|
-
*/
|
|
298
|
-
tests: {
|
|
299
|
-
testFileCount: number | null;
|
|
300
|
-
observedTestEdges: number | null;
|
|
301
|
-
callerCoverage: number | null;
|
|
302
|
-
coverageStatus: ModuleTestsCoverageStatus;
|
|
303
|
-
};
|
|
304
|
-
uncertainty: {
|
|
305
|
-
unresolvedImports: number;
|
|
306
|
-
dynamicInvocation: ModuleDynamicInvocationLevel;
|
|
307
|
-
ambiguousOwnership: boolean;
|
|
308
|
-
};
|
|
309
|
-
moduleDigest: string;
|
|
310
|
-
extensions?: Record<string, Json>;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* One ordered cross-module dependency of the measured graph: `distinctFileEdgeCount` distinct
|
|
315
|
-
* file-to-file import edges whose source file `fromNodeId` owns and whose target `toNodeId` owns.
|
|
316
|
-
* A contested file is attributed to each claimant, exactly as the module counts are.
|
|
317
|
-
*/
|
|
318
|
-
export interface ModuleDependencyV1 {
|
|
319
|
-
fromNodeId: string;
|
|
320
|
-
toNodeId: string;
|
|
321
|
-
distinctFileEdgeCount: number;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
export interface ModuleStatisticsSnapshotV1 {
|
|
325
|
-
schemaVersion: typeof MODULE_STATISTICS_SCHEMA_VERSION;
|
|
326
|
-
/** When present, counts describe the requested files and their direct import neighbors. */
|
|
327
|
-
scope?: Exclude<RefactorScopeV1, { kind: "repository" }>;
|
|
328
|
-
repository: ArchitectureRepositoryIdentityV1;
|
|
329
|
-
worktree: ArchitectureWorktreeIdentityV1;
|
|
330
|
-
modelDigest: string;
|
|
331
|
-
codeFacts: {
|
|
332
|
-
provider: "codegraph";
|
|
333
|
-
version: string;
|
|
334
|
-
binaryDigest: string;
|
|
335
|
-
indexedWorktreeDigest: string | null;
|
|
336
|
-
coverage: EvidenceCoverageLevelV2;
|
|
337
|
-
/**
|
|
338
|
-
* True only when the read is shorter than the population the index reported. A read cut by
|
|
339
|
-
* `edgeLimit` is not truncated: it reports `code-facts-import-limit` instead.
|
|
340
|
-
*/
|
|
341
|
-
truncated: boolean;
|
|
342
|
-
/** The import-node read limit the scan applied. */
|
|
343
|
-
edgeLimit: number | null;
|
|
344
|
-
/**
|
|
345
|
-
* Import nodes the index reported, or `null` when no index gave a count. Absent on snapshots
|
|
346
|
-
* recorded before the field existed.
|
|
347
|
-
*/
|
|
348
|
-
importNodeCount?: number | null;
|
|
349
|
-
reasonCodes: RefactorScaleReasonCode[];
|
|
350
|
-
};
|
|
351
|
-
modules: ModuleStatisticsV1[];
|
|
352
|
-
/**
|
|
353
|
-
* The module dependency table the graph counts were measured from, sorted by
|
|
354
|
-
* `(fromNodeId, toNodeId)`; one entry per `repositorySummary.crossModuleEdgeCount`. Empty when the
|
|
355
|
-
* graph was not measured (`codeFacts.coverage: unknown`).
|
|
356
|
-
*/
|
|
357
|
-
moduleDependencies: ModuleDependencyV1[];
|
|
358
|
-
repositorySummary: {
|
|
359
|
-
moduleCount: number;
|
|
360
|
-
undeclaredFootprintNodeCount: number;
|
|
361
|
-
ownedFileCount: number;
|
|
362
|
-
unownedFileCount: number;
|
|
363
|
-
multiplyOwnedFileCount: number;
|
|
364
|
-
crossModuleEdgeCount: number;
|
|
365
|
-
crossModuleCycleCount: number;
|
|
366
|
-
stronglyConnectedComponentCount: number;
|
|
367
|
-
unresolvedImportCount: number;
|
|
368
|
-
dynamicInvocationRiskCount: number;
|
|
369
|
-
};
|
|
370
|
-
createdAt: string;
|
|
371
|
-
snapshotDigest: string;
|
|
372
|
-
extensions?: Record<string, Json>;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
/**
|
|
376
|
-
* The fixed per-observation bound on sampled evidence entries (edges, violations, paths,
|
|
377
|
-
* unresolved imports). It bounds entry *count* only: a path or a specifier has no fixed byte
|
|
378
|
-
* size, so this bound alone does not keep a recording event under the ledger's persisted-JSON
|
|
379
|
-
* ceiling. The recording planner enforces that separately, by measuring the event it would
|
|
380
|
-
* persist and shrinking every sample to one shared smaller limit until the event fits.
|
|
381
|
-
*/
|
|
382
|
-
export const REFACTOR_OBSERVATION_EVIDENCE_LIMIT = 20;
|
|
383
|
-
/**
|
|
384
|
-
* The fixed bound on every id list inside evidence (`memberNodeIds`, `constraintIds`,
|
|
385
|
-
* `candidateOwnerNodeIds`). Each list is the sorted prefix of its population and carries the true
|
|
386
|
-
* size beside it (`metrics.memberCount`, `constraintCount`, `candidateOwnerCount`). It is no
|
|
387
|
-
* smaller than `REFACTOR_OBSERVATION_EVIDENCE_LIMIT`, so the constraints named by a violation
|
|
388
|
-
* sample — the smallest ids, since violations sort by constraint first — are always listed.
|
|
389
|
-
*/
|
|
390
|
-
export const REFACTOR_EVIDENCE_ID_LIST_LIMIT = 32;
|
|
391
|
-
/** An import specifier is a module reference, not code: one line, bounded like a locator. */
|
|
392
|
-
export const REFACTOR_EVIDENCE_SPECIFIER_MAX_LENGTH = 512;
|
|
393
|
-
|
|
394
|
-
/**
|
|
395
|
-
* One observed file-level import edge, as bounded metadata only: two repo-relative paths, the
|
|
396
|
-
* line the import sits on, the specifier verbatim and the owning nodes. Never a source body.
|
|
397
|
-
* `toPath` carries no line: an import names a module, not a position inside it.
|
|
398
|
-
*/
|
|
399
|
-
export interface RefactorEvidenceImportEdgeV1 {
|
|
400
|
-
fromPath: string;
|
|
401
|
-
/** 1-based line of the import statement in `fromPath`; `null` when the code index reported none. */
|
|
402
|
-
fromLine: number | null;
|
|
403
|
-
toPath: string;
|
|
404
|
-
specifier: string;
|
|
405
|
-
fromNodeId: string;
|
|
406
|
-
toNodeId: string;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
export interface RefactorEvidenceDirectionViolationV1 extends RefactorEvidenceImportEdgeV1 {
|
|
410
|
-
constraintId: string;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
export interface RefactorEvidencePathV1 {
|
|
414
|
-
path: string;
|
|
415
|
-
/**
|
|
416
|
-
* Declared nodes that bear on this path, per kind: for `ownership-ambiguous` every node that
|
|
417
|
-
* claims it; for `unowned-paths` the nodes that own another tracked file in the same directory;
|
|
418
|
-
* for `undeclared-footprint` the nodes that currently own the entrypoint path the node declares.
|
|
419
|
-
*/
|
|
420
|
-
candidateOwnerNodeIds: string[];
|
|
421
|
-
/** How many candidate owners exist; `candidateOwnerNodeIds` is its sorted, bounded prefix. */
|
|
422
|
-
candidateOwnerCount: number;
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
export interface RefactorEvidenceUnresolvedImportV1 {
|
|
426
|
-
fromPath: string;
|
|
427
|
-
fromLine: number | null;
|
|
428
|
-
specifier: string;
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
/** A bounded sample: `totalCount` is the population, `truncated` says the list is a prefix of it. */
|
|
432
|
-
interface RefactorEvidenceSampleV1 {
|
|
433
|
-
totalCount: number;
|
|
434
|
-
truncated: boolean;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Typed evidence per observation kind: the concrete items behind the observation's metrics, so a
|
|
439
|
-
* reader can see *why* it exists without re-running the measurement. Samples are sorted, bounded
|
|
440
|
-
* by `REFACTOR_OBSERVATION_EVIDENCE_LIMIT`, and derived from the same measurement as the snapshot;
|
|
441
|
-
* id lists are sorted prefixes bounded by `REFACTOR_EVIDENCE_ID_LIST_LIMIT`.
|
|
442
|
-
*
|
|
443
|
-
* `memberNodeIds` is the prefix of the component's members; its population is the observation's
|
|
444
|
-
* `metrics.memberCount`.
|
|
445
|
-
*/
|
|
446
|
-
/**
|
|
447
|
-
* One direction of a bidirectional pair: its import-edge population and how many of the sampled
|
|
448
|
-
* `edges` it holds. The thin direction (fewer distinct file edges, ties to the canonical forward
|
|
449
|
-
* direction) is listed first and is sampled first.
|
|
450
|
-
*/
|
|
451
|
-
export interface RefactorEvidencePairDirectionV1 {
|
|
452
|
-
fromNodeId: string;
|
|
453
|
-
toNodeId: string;
|
|
454
|
-
totalCount: number;
|
|
455
|
-
sampledCount: number;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
export type RefactorObservationEvidenceV1 =
|
|
459
|
-
| ({
|
|
460
|
-
kind: "cycle";
|
|
461
|
-
/** The pair, sorted: `[A, B]`. */
|
|
462
|
-
memberNodeIds: string[];
|
|
463
|
-
/** `[thin, thick]`; `totalCount` is their sum. */
|
|
464
|
-
directions: RefactorEvidencePairDirectionV1[];
|
|
465
|
-
edges: RefactorEvidenceImportEdgeV1[];
|
|
466
|
-
} & RefactorEvidenceSampleV1)
|
|
467
|
-
| ({ kind: "residual-cycle"; memberNodeIds: string[]; edges: RefactorEvidenceImportEdgeV1[] } & RefactorEvidenceSampleV1)
|
|
468
|
-
| ({
|
|
469
|
-
kind: "direction-violation";
|
|
470
|
-
constraintIds: string[];
|
|
471
|
-
/** How many distinct constraints the module violates; `constraintIds` is its bounded prefix. */
|
|
472
|
-
constraintCount: number;
|
|
473
|
-
violations: RefactorEvidenceDirectionViolationV1[];
|
|
474
|
-
} & RefactorEvidenceSampleV1)
|
|
475
|
-
| ({ kind: "ownership-ambiguous" | "undeclared-footprint" | "unowned-paths"; paths: RefactorEvidencePathV1[] } & RefactorEvidenceSampleV1)
|
|
476
|
-
| ({
|
|
477
|
-
kind: "evidence-gap";
|
|
478
|
-
coverage: EvidenceCoverageLevelV2;
|
|
479
|
-
reasonCodes: RefactorScaleReasonCode[];
|
|
480
|
-
unresolvedImports: RefactorEvidenceUnresolvedImportV1[];
|
|
481
|
-
} & RefactorEvidenceSampleV1);
|
|
482
|
-
|
|
483
|
-
export interface RefactorObservationV1 {
|
|
484
|
-
kind: RefactorObservationKind;
|
|
485
|
-
subjectSelectorId: string;
|
|
486
|
-
/**
|
|
487
|
-
* The declared nodes this observation is about, sorted and unique, authored by the producer that
|
|
488
|
-
* measured it: a node subject is `[nodeId]`, a pair its two ends, a residual cycle its members, a
|
|
489
|
-
* repository-wide fact `[]`. Scopes filter on it and the planner copies it; nothing re-derives it.
|
|
490
|
-
*/
|
|
491
|
-
affectedNodeIds: string[];
|
|
492
|
-
signalIds: string[];
|
|
493
|
-
metrics: Record<string, number | null>;
|
|
494
|
-
evidence: RefactorObservationEvidenceV1;
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
export interface RefactorAssessmentV1 {
|
|
498
|
-
schemaVersion: typeof REFACTOR_ASSESSMENT_SCHEMA_VERSION;
|
|
499
|
-
requestId: string;
|
|
500
|
-
statisticsSnapshotDigest: string;
|
|
501
|
-
modelDigest: string;
|
|
502
|
-
codeFactsDigest: string;
|
|
503
|
-
requestedScope: RefactorScopeV1;
|
|
504
|
-
proposalDigest: string | null;
|
|
505
|
-
observations: RefactorObservationV1[];
|
|
506
|
-
scale: RefactorScale | null;
|
|
507
|
-
scaleReasonCodes: RefactorScaleReasonCode[];
|
|
508
|
-
affectedNodeIds: string[];
|
|
509
|
-
majorChangeReasons: ArchitectureMajorChangeReasonCode[];
|
|
510
|
-
pressure: {
|
|
511
|
-
level: "low" | "medium" | "high";
|
|
512
|
-
score: number;
|
|
513
|
-
signalIds: string[];
|
|
514
|
-
};
|
|
515
|
-
confidence: {
|
|
516
|
-
level: "low" | "medium" | "high";
|
|
517
|
-
callerCoverage: number | null;
|
|
518
|
-
testsObserved: boolean | null;
|
|
519
|
-
rollbackObserved: boolean | null;
|
|
520
|
-
unresolvedEvidence: string[];
|
|
521
|
-
};
|
|
522
|
-
createdAt: string;
|
|
523
|
-
assessmentDigest: string;
|
|
524
|
-
extensions?: Record<string, Json>;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
export interface RefactorResidualV1 {
|
|
528
|
-
code: string;
|
|
529
|
-
subject: string;
|
|
530
|
-
severity: Severity;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
export interface RefactorExecutionEvidenceRefV1 {
|
|
534
|
-
kind: RefactorExecutionEvidenceKind;
|
|
535
|
-
locator: string;
|
|
536
|
-
sha256: string;
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
export interface RefactorResolutionEvidenceV1 {
|
|
540
|
-
schemaVersion: typeof REFACTOR_RESOLUTION_EVIDENCE_SCHEMA_VERSION;
|
|
541
|
-
recommendationId: string;
|
|
542
|
-
recommendationDigest: string;
|
|
543
|
-
beforeSnapshotDigest: string;
|
|
544
|
-
afterSnapshotDigest: string;
|
|
545
|
-
verifiedHeadSha: string;
|
|
546
|
-
verifiedWorktreeDigest: string;
|
|
547
|
-
expectedOutcomes: RefactorTargetOutcomeV1[];
|
|
548
|
-
observedOutcomes: RefactorObservedOutcomeV1[];
|
|
549
|
-
residuals: RefactorResidualV1[];
|
|
550
|
-
executionEvidenceRefs: RefactorExecutionEvidenceRefV1[];
|
|
551
|
-
disposition: RefactorResolutionDisposition;
|
|
552
|
-
verifiedAt: string;
|
|
553
|
-
resolutionDigest: string;
|
|
554
|
-
extensions?: Record<string, Json>;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
export interface RecommendationV3FingerprintInputV1 {
|
|
558
|
-
category: RecommendationCategory;
|
|
559
|
-
subjectSelectorId: string;
|
|
560
|
-
practiceId: string | null;
|
|
561
|
-
payload: Record<string, Json>;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/**
|
|
565
|
-
* Digest exclusion rule for every helper below: drop the record's own digest
|
|
566
|
-
* field, its top-level `extensions`, and its timestamps. Nested `extensions`
|
|
567
|
-
* (for example `modules[i].extensions`) stay inside the hashed content, so a
|
|
568
|
-
* nested annotation changes the digest. The single exception is the derived
|
|
569
|
-
* `targetDelta` identity below: ArchContext fills `unresolvedTargets` after the
|
|
570
|
-
* agent authored the proposal, so `refactorProposalDigest` hashes the delta
|
|
571
|
-
* under the same exclusions as `architectureTargetDeltaInterventionId`
|
|
572
|
-
* (`interventionId`, `unresolvedTargets`, `extensions`) and the agent-authored
|
|
573
|
-
* identity survives assessment. `authoredBy` stays hashed at the top level:
|
|
574
|
-
* the no-self-authored gate must be digest-bound.
|
|
575
|
-
*/
|
|
576
|
-
export function refactorProposalDigest(proposal: RefactorProposalV1): string {
|
|
577
|
-
const { proposalDigest: _proposalDigest, extensions: _extensions, ...hashable } = proposal;
|
|
578
|
-
return digestJson({
|
|
579
|
-
...hashable,
|
|
580
|
-
...(hashable.targetDelta ? { targetDelta: authoredTargetDelta(hashable.targetDelta) } : {})
|
|
581
|
-
} as unknown as Json);
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
export function architectureTargetDeltaInterventionId(delta: ArchitectureTargetDeltaV1): string {
|
|
585
|
-
const digest = digestJson(authoredTargetDelta(delta) as unknown as Json);
|
|
586
|
-
return `intervention.${digest.slice(DIGEST_PREFIX_LENGTH, DIGEST_PREFIX_LENGTH + 16)}`;
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
export function moduleStatisticsDigest(module: ModuleStatisticsV1): string {
|
|
590
|
-
const { moduleDigest: _moduleDigest, extensions: _extensions, ...hashable } = module;
|
|
591
|
-
return digestJson(hashable as unknown as Json);
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
export function moduleStatisticsSnapshotDigest(snapshot: ModuleStatisticsSnapshotV1): string {
|
|
595
|
-
const { snapshotDigest: _snapshotDigest, createdAt: _createdAt, extensions: _extensions, ...hashable } = snapshot;
|
|
596
|
-
return digestJson(hashable as unknown as Json);
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
/** Repository measurements have no scope digest. Scoped measurements can compare only to the same scope. */
|
|
600
|
-
export function refactorSnapshotScopeDigest(scope: ModuleStatisticsSnapshotV1["scope"]): string | undefined {
|
|
601
|
-
return scope === undefined ? undefined : digestJson(scope);
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
export function refactorAssessmentDigest(assessment: RefactorAssessmentV1): string {
|
|
605
|
-
const {
|
|
606
|
-
assessmentDigest: _assessmentDigest,
|
|
607
|
-
requestId: _requestId,
|
|
608
|
-
createdAt: _createdAt,
|
|
609
|
-
extensions: _extensions,
|
|
610
|
-
...hashable
|
|
611
|
-
} = assessment;
|
|
612
|
-
return digestJson(hashable as unknown as Json);
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
export function refactorResolutionEvidenceDigest(evidence: RefactorResolutionEvidenceV1): string {
|
|
616
|
-
const {
|
|
617
|
-
resolutionDigest: _resolutionDigest,
|
|
618
|
-
verifiedAt: _verifiedAt,
|
|
619
|
-
extensions: _extensions,
|
|
620
|
-
...hashable
|
|
621
|
-
} = evidence;
|
|
622
|
-
return digestJson(hashable as unknown as Json);
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
/**
|
|
626
|
-
* Canonical fingerprint input for a v3 recommendation. It deliberately drops
|
|
627
|
-
* `assessmentDigest` and `baselineSnapshotDigest` so that re-detecting the same
|
|
628
|
-
* structural fact at a new HEAD dedups against the previous recommendation and
|
|
629
|
-
* drives `relations.regressesFrom` instead of creating an unrelated record.
|
|
630
|
-
*/
|
|
631
|
-
export function recommendationV3FingerprintInput(
|
|
632
|
-
recommendation: Pick<RecommendationV3, "category" | "subjectSelectorId" | "practiceId" | "payload">
|
|
633
|
-
): RecommendationV3FingerprintInputV1 {
|
|
634
|
-
return {
|
|
635
|
-
category: recommendation.category,
|
|
636
|
-
subjectSelectorId: recommendation.subjectSelectorId,
|
|
637
|
-
practiceId: recommendation.practiceId ?? null,
|
|
638
|
-
payload: fingerprintPayloadSubset(recommendation.category, recommendation.payload)
|
|
639
|
-
};
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
export function refactorProposalInvariantIssues(proposal: RefactorProposalV1, prefix = "proposal"): string[] {
|
|
643
|
-
const issues = [
|
|
644
|
-
...sortedUniqueIssues(`${prefix}.scopePaths`, proposal.scopePaths),
|
|
645
|
-
...digestIssues(`${prefix}.proposalDigest`, proposal.proposalDigest),
|
|
646
|
-
...outcomeIssues(`${prefix}.targetOutcomes`, proposal.targetOutcomes)
|
|
647
|
-
];
|
|
648
|
-
if (proposal.schemaVersion !== REFACTOR_PROPOSAL_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
649
|
-
if (proposal.intent.trim() === "") issues.push(`${prefix}.intent must not be empty`);
|
|
650
|
-
if (proposal.scopePaths.length === 0) issues.push(`${prefix}.scopePaths must contain at least one path`);
|
|
651
|
-
for (const path of proposal.scopePaths) {
|
|
652
|
-
if (!isRepoRelativePosixPath(path)) issues.push(`${prefix}.scopePaths must be repo-relative POSIX paths: ${path}`);
|
|
653
|
-
}
|
|
654
|
-
issues.push(...refactorProposalAuthorIssues(proposal.authoredBy, prefix));
|
|
655
|
-
issues.push(...sortedUniqueIssues(`${prefix}.killList.selectorId`, proposal.killList.map((entry) => entry.selectorId)));
|
|
656
|
-
if (refactorProposalDigest(proposal) !== proposal.proposalDigest) {
|
|
657
|
-
issues.push(`${prefix}.proposalDigest must bind the authored proposal payload`);
|
|
658
|
-
}
|
|
659
|
-
if (proposal.targetDelta) issues.push(...architectureTargetDeltaInvariantIssues(proposal.targetDelta, `${prefix}.targetDelta`));
|
|
660
|
-
return issues;
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
export function architectureTargetDeltaInvariantIssues(delta: ArchitectureTargetDeltaV1, prefix = "targetDelta"): string[] {
|
|
664
|
-
const issues = [
|
|
665
|
-
...sortedUniqueIssues(`${prefix}.unresolvedTargets`, delta.unresolvedTargets),
|
|
666
|
-
...outcomeIssues(`${prefix}.completionCriteria`, delta.completionCriteria)
|
|
667
|
-
];
|
|
668
|
-
if (delta.thesis.trim() === "") issues.push(`${prefix}.thesis must not be empty`);
|
|
669
|
-
if (delta.trigger.length === 0) issues.push(`${prefix}.trigger must state at least one trigger`);
|
|
670
|
-
if (delta.falsifiers.length === 0) issues.push(`${prefix}.falsifiers must state at least one falsifier`);
|
|
671
|
-
if (delta.completionCriteria.length === 0) issues.push(`${prefix}.completionCriteria must contain at least one outcome`);
|
|
672
|
-
if (delta.benefitLedger.rollbackPoint.trim() === "") issues.push(`${prefix}.benefitLedger.rollbackPoint must not be empty`);
|
|
673
|
-
const temporaryRelations = new Set(delta.migrationState.temporaryRelations);
|
|
674
|
-
for (const relation of delta.targetState.requiredRelations) {
|
|
675
|
-
if (temporaryRelations.has(relation)) {
|
|
676
|
-
issues.push(`${prefix}.targetState.requiredRelations must not contain migration-only relation: ${relation}`);
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
if (architectureTargetDeltaInterventionId(delta) !== delta.interventionId) {
|
|
680
|
-
issues.push(`${prefix}.interventionId must be derived from the authored delta`);
|
|
681
|
-
}
|
|
682
|
-
return issues;
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
export function refactorRequestInvariantIssues(request: RefactorRequestV1, prefix = "request"): string[] {
|
|
686
|
-
const issues: string[] = [];
|
|
687
|
-
if (request.schemaVersion !== REFACTOR_REQUEST_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
688
|
-
if (request.scope.kind === "node" && request.scope.nodeId.trim() === "") issues.push(`${prefix}.scope.nodeId must not be empty`);
|
|
689
|
-
if (request.scope.kind === "paths") {
|
|
690
|
-
issues.push(...sortedUniqueIssues(`${prefix}.scope.paths`, request.scope.paths));
|
|
691
|
-
if (request.scope.paths.length === 0) issues.push(`${prefix}.scope.paths must contain at least one path`);
|
|
692
|
-
for (const path of request.scope.paths) {
|
|
693
|
-
if (!isRepoRelativePosixPath(path)) issues.push(`${prefix}.scope.paths must be repo-relative POSIX paths: ${path}`);
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
if (request.proposal) issues.push(...refactorProposalInvariantIssues(request.proposal, `${prefix}.proposal`));
|
|
697
|
-
if (request.importNodeLimit !== undefined && !(Number.isInteger(request.importNodeLimit) && request.importNodeLimit >= 1)) {
|
|
698
|
-
issues.push(`${prefix}.importNodeLimit must be a positive integer`);
|
|
699
|
-
}
|
|
700
|
-
return issues;
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
/**
|
|
704
|
-
* Validates a `refactor verify` request before anything measures on its behalf.
|
|
705
|
-
*
|
|
706
|
-
* Top-level keys are closed to `REFACTOR_VERIFICATION_REQUEST_KEYS`. Every ingress rebuilds the
|
|
707
|
-
* request from the declared fields, so a typo (`expectedWorktreeDigset`) would otherwise be
|
|
708
|
-
* dropped in silence and the caller's freshness claim would simply cease to exist — the request
|
|
709
|
-
* would be answered under a weaker precondition than the one it stated.
|
|
710
|
-
*
|
|
711
|
-
* `executionEvidenceRefs` are checked under exactly the rules that bind them into the ledger:
|
|
712
|
-
* three declared keys and nothing else, a kind from the frozen vocabulary, and a bare SHA-256.
|
|
713
|
-
* An extra key would ride a cast into a record whose envelope promises no raw bodies, and the
|
|
714
|
-
* resolution-evidence validator only ever inspects `locator` and `sha256`, so it would never see
|
|
715
|
-
* it. Refusing here is the only place that key is still visible.
|
|
716
|
-
*/
|
|
717
|
-
export function refactorVerificationRequestInvariantIssues(
|
|
718
|
-
request: RefactorVerificationRequestV1,
|
|
719
|
-
prefix = "request"
|
|
720
|
-
): string[] {
|
|
721
|
-
const issues: string[] = [];
|
|
722
|
-
const unknownKeys = Object.keys(request as unknown as Record<string, unknown>)
|
|
723
|
-
.filter((key) => !(REFACTOR_VERIFICATION_REQUEST_KEYS as readonly string[]).includes(key))
|
|
724
|
-
.sort();
|
|
725
|
-
if (unknownKeys.length > 0) issues.push(`${prefix} has unsupported key(s): ${unknownKeys.join(", ")}`);
|
|
726
|
-
if (request.schemaVersion !== REFACTOR_VERIFICATION_REQUEST_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
727
|
-
if (typeof request.recommendationId !== "string" || request.recommendationId.trim() === "") {
|
|
728
|
-
issues.push(`${prefix}.recommendationId must be a non-empty string`);
|
|
729
|
-
}
|
|
730
|
-
if (request.expectedHeadSha !== undefined && !GIT_HEAD_SHA_PATTERN.test(request.expectedHeadSha)) {
|
|
731
|
-
issues.push(`${prefix}.expectedHeadSha must be a 40-hex Git commit sha`);
|
|
732
|
-
}
|
|
733
|
-
if (request.expectedWorktreeDigest !== undefined) {
|
|
734
|
-
issues.push(...digestIssues(`${prefix}.expectedWorktreeDigest`, request.expectedWorktreeDigest));
|
|
735
|
-
}
|
|
736
|
-
if (request.importNodeLimit !== undefined && !(Number.isInteger(request.importNodeLimit) && request.importNodeLimit >= 1)) {
|
|
737
|
-
issues.push(`${prefix}.importNodeLimit must be a positive integer`);
|
|
738
|
-
}
|
|
739
|
-
if (request.executionEvidenceRefs !== undefined) {
|
|
740
|
-
if (!Array.isArray(request.executionEvidenceRefs)) {
|
|
741
|
-
issues.push(`${prefix}.executionEvidenceRefs must be an array`);
|
|
742
|
-
return issues;
|
|
743
|
-
}
|
|
744
|
-
request.executionEvidenceRefs.forEach((ref, index) => {
|
|
745
|
-
const label = `${prefix}.executionEvidenceRefs[${index}]`;
|
|
746
|
-
if (!ref || typeof ref !== "object" || Array.isArray(ref)) {
|
|
747
|
-
issues.push(`${label} must be an object`);
|
|
748
|
-
return;
|
|
749
|
-
}
|
|
750
|
-
const extras = Object.keys(ref).filter((key) => key !== "kind" && key !== "locator" && key !== "sha256");
|
|
751
|
-
if (extras.length > 0) issues.push(`${label} has unsupported key(s): ${[...extras].sort().join(", ")}`);
|
|
752
|
-
if (!(REFACTOR_EXECUTION_EVIDENCE_KINDS as readonly string[]).includes(ref.kind)) {
|
|
753
|
-
issues.push(`${label}.kind must be one of ${REFACTOR_EXECUTION_EVIDENCE_KINDS.join(", ")}`);
|
|
754
|
-
}
|
|
755
|
-
if (typeof ref.locator !== "string" || ref.locator.trim() === "") {
|
|
756
|
-
issues.push(`${label}.locator must be a non-empty string`);
|
|
757
|
-
} else if (!REFACTOR_EXECUTION_EVIDENCE_LOCATOR_PATTERN.test(ref.locator)) {
|
|
758
|
-
issues.push(`${label}.locator ${REFACTOR_EXECUTION_EVIDENCE_LOCATOR_RULE}`);
|
|
759
|
-
}
|
|
760
|
-
if (typeof ref.sha256 !== "string" || !BARE_SHA256_PATTERN.test(ref.sha256)) {
|
|
761
|
-
issues.push(`${label}.sha256 must be a bare SHA-256 hex digest`);
|
|
762
|
-
}
|
|
763
|
-
});
|
|
764
|
-
}
|
|
765
|
-
return issues;
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
export function moduleStatisticsInvariantIssues(module: ModuleStatisticsV1, prefix = "module"): string[] {
|
|
769
|
-
const issues = [...digestIssues(`${prefix}.moduleDigest`, module.moduleDigest), ...digestIssues(`${prefix}.nodeDigest`, module.nodeDigest)];
|
|
770
|
-
if (module.nodeId.trim() === "") issues.push(`${prefix}.nodeId must not be empty`);
|
|
771
|
-
if (module.footprintDeclared === (module.footprint === null)) {
|
|
772
|
-
issues.push(`${prefix}.footprint must be present exactly when footprintDeclared is true`);
|
|
773
|
-
}
|
|
774
|
-
if (module.footprint) {
|
|
775
|
-
issues.push(
|
|
776
|
-
...digestIssues(`${prefix}.footprint.sourceFilesDigest`, module.footprint.sourceFilesDigest),
|
|
777
|
-
...nonNegativeIntegerIssues(`${prefix}.footprint.fileCount`, module.footprint.fileCount),
|
|
778
|
-
...nonNegativeIntegerIssues(`${prefix}.footprint.lineCount`, module.footprint.lineCount)
|
|
779
|
-
);
|
|
780
|
-
}
|
|
781
|
-
if (module.dependencyGraph) {
|
|
782
|
-
const graph = module.dependencyGraph;
|
|
783
|
-
issues.push(
|
|
784
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.internalEdgeCount`, graph.internalEdgeCount),
|
|
785
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.inboundModuleEdges`, graph.inboundModuleEdges),
|
|
786
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.outboundModuleEdges`, graph.outboundModuleEdges),
|
|
787
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.fanIn`, graph.fanIn),
|
|
788
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.fanOut`, graph.fanOut),
|
|
789
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.cycleCount`, graph.cycleCount),
|
|
790
|
-
...nonNegativeIntegerIssues(`${prefix}.dependencyGraph.directionViolationCount`, graph.directionViolationCount),
|
|
791
|
-
...ratioIssues(`${prefix}.dependencyGraph.instability`, graph.instability)
|
|
792
|
-
);
|
|
793
|
-
}
|
|
794
|
-
issues.push(
|
|
795
|
-
...nonNegativeIntegerIssues(`${prefix}.tests.testFileCount`, module.tests.testFileCount),
|
|
796
|
-
...nonNegativeIntegerIssues(`${prefix}.tests.observedTestEdges`, module.tests.observedTestEdges),
|
|
797
|
-
...ratioIssues(`${prefix}.tests.callerCoverage`, module.tests.callerCoverage),
|
|
798
|
-
...nonNegativeIntegerIssues(`${prefix}.uncertainty.unresolvedImports`, module.uncertainty.unresolvedImports)
|
|
799
|
-
);
|
|
800
|
-
if (moduleStatisticsDigest(module) !== module.moduleDigest) {
|
|
801
|
-
issues.push(`${prefix}.moduleDigest must bind the measured module payload`);
|
|
802
|
-
}
|
|
803
|
-
return issues;
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
export function moduleStatisticsSnapshotInvariantIssues(snapshot: ModuleStatisticsSnapshotV1, prefix = "snapshot"): string[] {
|
|
807
|
-
const issues = [
|
|
808
|
-
...digestIssues(`${prefix}.snapshotDigest`, snapshot.snapshotDigest),
|
|
809
|
-
...digestIssues(`${prefix}.modelDigest`, snapshot.modelDigest),
|
|
810
|
-
...sortedUniqueIssues(`${prefix}.codeFacts.reasonCodes`, snapshot.codeFacts.reasonCodes),
|
|
811
|
-
...sortedUniqueIssues(`${prefix}.modules.nodeId`, snapshot.modules.map((module) => module.nodeId)),
|
|
812
|
-
...snapshot.modules.flatMap((module, index) => moduleStatisticsInvariantIssues(module, `${prefix}.modules[${index}]`))
|
|
813
|
-
];
|
|
814
|
-
if (snapshot.schemaVersion !== MODULE_STATISTICS_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
815
|
-
if (snapshot.codeFacts.coverage === "unknown") {
|
|
816
|
-
if (!snapshot.codeFacts.truncated) issues.push(`${prefix}.codeFacts.truncated must be true when coverage is unknown`);
|
|
817
|
-
for (const [index, module] of snapshot.modules.entries()) {
|
|
818
|
-
if (module.dependencyGraph !== null) {
|
|
819
|
-
issues.push(`${prefix}.modules[${index}].dependencyGraph must be null when codeFacts.coverage is unknown`);
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
if (snapshot.codeFacts.coverage !== "unknown") {
|
|
824
|
-
if (snapshot.codeFacts.indexedWorktreeDigest === null) {
|
|
825
|
-
issues.push(`${prefix}.codeFacts.indexedWorktreeDigest must be present when coverage is ${snapshot.codeFacts.coverage}`);
|
|
826
|
-
} else if (snapshot.codeFacts.indexedWorktreeDigest !== snapshot.worktree.worktreeDigest) {
|
|
827
|
-
issues.push(`${prefix}.codeFacts.indexedWorktreeDigest must match the measured worktreeDigest`);
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
issues.push(...nonNegativeIntegerIssues(`${prefix}.codeFacts.edgeLimit`, snapshot.codeFacts.edgeLimit));
|
|
831
|
-
const importNodeCount = snapshot.codeFacts.importNodeCount ?? null;
|
|
832
|
-
issues.push(...nonNegativeIntegerIssues(`${prefix}.codeFacts.importNodeCount`, importNodeCount));
|
|
833
|
-
if (snapshot.codeFacts.reasonCodes.includes("code-facts-import-limit")) {
|
|
834
|
-
const { edgeLimit } = snapshot.codeFacts;
|
|
835
|
-
if (snapshot.codeFacts.coverage !== "partial") issues.push(`${prefix}.codeFacts.coverage must be partial when the import limit was reached`);
|
|
836
|
-
if (edgeLimit === null || (importNodeCount !== null && importNodeCount <= edgeLimit)) {
|
|
837
|
-
issues.push(`${prefix}.codeFacts.importNodeCount must exceed edgeLimit when the import limit was reached`);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
for (const [field, value] of Object.entries(snapshot.repositorySummary)) {
|
|
841
|
-
issues.push(...nonNegativeIntegerIssues(`${prefix}.repositorySummary.${field}`, value));
|
|
842
|
-
}
|
|
843
|
-
issues.push(...moduleDependencyIssues(snapshot, prefix));
|
|
844
|
-
if (snapshot.repositorySummary.moduleCount !== snapshot.modules.length) {
|
|
845
|
-
issues.push(`${prefix}.repositorySummary.moduleCount must equal the module count`);
|
|
846
|
-
}
|
|
847
|
-
const undeclared = snapshot.modules.filter((module) => !module.footprintDeclared).length;
|
|
848
|
-
if (snapshot.repositorySummary.undeclaredFootprintNodeCount !== undeclared) {
|
|
849
|
-
issues.push(`${prefix}.repositorySummary.undeclaredFootprintNodeCount must equal the undeclared footprint module count`);
|
|
850
|
-
}
|
|
851
|
-
if (moduleStatisticsSnapshotDigest(snapshot) !== snapshot.snapshotDigest) {
|
|
852
|
-
issues.push(`${prefix}.snapshotDigest must bind the measured snapshot payload`);
|
|
853
|
-
}
|
|
854
|
-
return issues;
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
/**
|
|
858
|
-
* The dependency table binds the graph counts it was measured with: sorted and unique by
|
|
859
|
-
* `(fromNodeId, toNodeId)`, positive counts, no self edge, both ends measured modules, one entry per
|
|
860
|
-
* counted cross-module edge, and nothing at all when the graph was not measured.
|
|
861
|
-
*/
|
|
862
|
-
function moduleDependencyIssues(snapshot: ModuleStatisticsSnapshotV1, prefix: string): string[] {
|
|
863
|
-
const label = `${prefix}.moduleDependencies`;
|
|
864
|
-
const dependencies = (snapshot as { moduleDependencies?: unknown }).moduleDependencies;
|
|
865
|
-
if (!Array.isArray(dependencies)) return [`${label} must be an array`];
|
|
866
|
-
const issues: string[] = [];
|
|
867
|
-
const modules = new Set(snapshot.modules.map((module) => module.nodeId));
|
|
868
|
-
for (const [index, entry] of (dependencies as ModuleDependencyV1[]).entries()) {
|
|
869
|
-
if (!entry || typeof entry !== "object") {
|
|
870
|
-
issues.push(`${label}[${index}] must be an object`);
|
|
871
|
-
continue;
|
|
872
|
-
}
|
|
873
|
-
if (!modules.has(entry.fromNodeId) || !modules.has(entry.toNodeId)) issues.push(`${label}[${index}] must name measured modules`);
|
|
874
|
-
if (entry.fromNodeId === entry.toNodeId) issues.push(`${label}[${index}] must not be a self dependency`);
|
|
875
|
-
if (!Number.isInteger(entry.distinctFileEdgeCount) || entry.distinctFileEdgeCount < 1) {
|
|
876
|
-
issues.push(`${label}[${index}].distinctFileEdgeCount must be a positive integer`);
|
|
877
|
-
}
|
|
878
|
-
const previous = (dependencies as ModuleDependencyV1[])[index - 1];
|
|
879
|
-
if (previous && (compareText(previous.fromNodeId, entry.fromNodeId) || compareText(previous.toNodeId, entry.toNodeId)) >= 0) {
|
|
880
|
-
issues.push(`${label} must be sorted and unique by (fromNodeId, toNodeId)`);
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
if (dependencies.length !== snapshot.repositorySummary.crossModuleEdgeCount) {
|
|
884
|
-
issues.push(`${label} must hold one entry per repositorySummary.crossModuleEdgeCount`);
|
|
885
|
-
}
|
|
886
|
-
if (snapshot.codeFacts.coverage === "unknown" && dependencies.length > 0) {
|
|
887
|
-
issues.push(`${label} must be empty when codeFacts.coverage is unknown`);
|
|
888
|
-
}
|
|
889
|
-
return [...new Set(issues)];
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
/**
|
|
893
|
-
* How a pair's evidence sample of `limit` entries is split: the thin direction first, but one slot
|
|
894
|
-
* is kept for the thick direction whenever there are two or more slots, so both directions are
|
|
895
|
-
* always shown. Taking the thin direction first is what keeps a single thin edge visible beside
|
|
896
|
-
* any number of thick ones. Resampling a sample with a smaller limit gives exactly this split of
|
|
897
|
-
* the population, so the planner's evidence cut stays on the same rule.
|
|
898
|
-
*/
|
|
899
|
-
export function refactorPairSampleAllocation(thinTotal: number, thickTotal: number, limit: number): { thin: number; thick: number } {
|
|
900
|
-
const slots = Math.max(0, Math.min(limit, thinTotal + thickTotal));
|
|
901
|
-
const reserve = thickTotal > 0 && slots >= 2 ? 1 : 0;
|
|
902
|
-
const thin = Math.min(thinTotal, slots - reserve);
|
|
903
|
-
return { thin, thick: Math.min(thickTotal, slots - thin) };
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
/**
|
|
907
|
-
* Cuts a pair's evidence to `limit` entries under `refactorPairSampleAllocation`. `evidence.edges`
|
|
908
|
-
* may be the whole population or an earlier sample of it: each direction keeps its first entries in
|
|
909
|
-
* canonical order, and the result is re-sorted canonically.
|
|
910
|
-
*/
|
|
911
|
-
export function sampleRefactorPairEvidence(
|
|
912
|
-
evidence: Extract<RefactorObservationEvidenceV1, { kind: "cycle" }>,
|
|
913
|
-
limit: number
|
|
914
|
-
): Extract<RefactorObservationEvidenceV1, { kind: "cycle" }> {
|
|
915
|
-
const [thin, thick] = evidence.directions as [RefactorEvidencePairDirectionV1, RefactorEvidencePairDirectionV1];
|
|
916
|
-
const allocation = refactorPairSampleAllocation(thin.totalCount, thick.totalCount, Math.min(limit, REFACTOR_OBSERVATION_EVIDENCE_LIMIT));
|
|
917
|
-
const sorted = [...evidence.edges].sort(compareRefactorEvidenceImportEdges);
|
|
918
|
-
const inDirection = (direction: RefactorEvidencePairDirectionV1) => sorted.filter((edge) =>
|
|
919
|
-
edge.fromNodeId === direction.fromNodeId && edge.toNodeId === direction.toNodeId);
|
|
920
|
-
const thinEdges = inDirection(thin).slice(0, allocation.thin);
|
|
921
|
-
const thickEdges = inDirection(thick).slice(0, allocation.thick);
|
|
922
|
-
const edges = [...thinEdges, ...thickEdges].sort(compareRefactorEvidenceImportEdges);
|
|
923
|
-
return {
|
|
924
|
-
...evidence,
|
|
925
|
-
directions: [
|
|
926
|
-
{ ...thin, sampledCount: thinEdges.length },
|
|
927
|
-
{ ...thick, sampledCount: thickEdges.length }
|
|
928
|
-
],
|
|
929
|
-
edges,
|
|
930
|
-
truncated: evidence.totalCount > edges.length
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
export function refactorAssessmentInvariantIssues(assessment: RefactorAssessmentV1, prefix = "assessment"): string[] {
|
|
935
|
-
const issues = [
|
|
936
|
-
...digestIssues(`${prefix}.assessmentDigest`, assessment.assessmentDigest),
|
|
937
|
-
...digestIssues(`${prefix}.statisticsSnapshotDigest`, assessment.statisticsSnapshotDigest),
|
|
938
|
-
...digestIssues(`${prefix}.modelDigest`, assessment.modelDigest),
|
|
939
|
-
...digestIssues(`${prefix}.codeFactsDigest`, assessment.codeFactsDigest),
|
|
940
|
-
...sortedUniqueIssues(`${prefix}.affectedNodeIds`, assessment.affectedNodeIds),
|
|
941
|
-
...sortedUniqueIssues(`${prefix}.scaleReasonCodes`, assessment.scaleReasonCodes),
|
|
942
|
-
...sortedUniqueIssues(`${prefix}.majorChangeReasons`, assessment.majorChangeReasons)
|
|
943
|
-
];
|
|
944
|
-
if (assessment.schemaVersion !== REFACTOR_ASSESSMENT_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
945
|
-
if (assessment.proposalDigest !== null) issues.push(...digestIssues(`${prefix}.proposalDigest`, assessment.proposalDigest));
|
|
946
|
-
if ((assessment.scale === null) !== (assessment.proposalDigest === null)) {
|
|
947
|
-
issues.push(`${prefix}.scale must be null exactly when proposalDigest is null`);
|
|
948
|
-
}
|
|
949
|
-
if (assessment.scale === "architecture" && assessment.majorChangeReasons.length === 0) {
|
|
950
|
-
issues.push(`${prefix}.architecture scale requires at least one majorChangeReason`);
|
|
951
|
-
}
|
|
952
|
-
const allowedReasons = new Set<string>(ARCHITECTURE_MAJOR_CHANGE_REASON_CODES);
|
|
953
|
-
for (const reason of assessment.majorChangeReasons) {
|
|
954
|
-
if (!allowedReasons.has(reason)) issues.push(`${prefix}.majorChangeReasons contains unsupported reason: ${reason}`);
|
|
955
|
-
}
|
|
956
|
-
for (const [index, observation] of assessment.observations.entries()) {
|
|
957
|
-
if (observation.subjectSelectorId.trim() === "") issues.push(`${prefix}.observations[${index}].subjectSelectorId must not be empty`);
|
|
958
|
-
issues.push(...sortedUniqueIssues(`${prefix}.observations[${index}].signalIds`, observation.signalIds));
|
|
959
|
-
issues.push(...(Array.isArray(observation.affectedNodeIds)
|
|
960
|
-
? sortedUniqueIssues(`${prefix}.observations[${index}].affectedNodeIds`, observation.affectedNodeIds)
|
|
961
|
-
: [`${prefix}.observations[${index}].affectedNodeIds must be an array`]));
|
|
962
|
-
issues.push(...refactorObservationEvidenceIssues(observation, `${prefix}.observations[${index}]`));
|
|
963
|
-
}
|
|
964
|
-
issues.push(...ratioIssues(`${prefix}.confidence.callerCoverage`, assessment.confidence.callerCoverage));
|
|
965
|
-
if (!Number.isInteger(assessment.pressure.score) || assessment.pressure.score < 0 || assessment.pressure.score > 100) {
|
|
966
|
-
issues.push(`${prefix}.pressure.score must be an integer between 0 and 100`);
|
|
967
|
-
}
|
|
968
|
-
issues.push(...sortedUniqueIssues(`${prefix}.pressure.signalIds`, assessment.pressure.signalIds));
|
|
969
|
-
if (refactorAssessmentDigest(assessment) !== assessment.assessmentDigest) {
|
|
970
|
-
issues.push(`${prefix}.assessmentDigest must bind the assessed payload`);
|
|
971
|
-
}
|
|
972
|
-
return issues;
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
/** The one ordering for evidence edges: path, line, target, specifier, then owners. */
|
|
976
|
-
export function compareRefactorEvidenceImportEdges(left: RefactorEvidenceImportEdgeV1, right: RefactorEvidenceImportEdgeV1): number {
|
|
977
|
-
return compareText(left.fromPath, right.fromPath)
|
|
978
|
-
|| compareLine(left.fromLine, right.fromLine)
|
|
979
|
-
|| compareText(left.toPath, right.toPath)
|
|
980
|
-
|| compareText(left.specifier, right.specifier)
|
|
981
|
-
|| compareText(left.fromNodeId, right.fromNodeId)
|
|
982
|
-
|| compareText(left.toNodeId, right.toNodeId);
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
export function compareRefactorEvidenceDirectionViolations(
|
|
986
|
-
left: RefactorEvidenceDirectionViolationV1,
|
|
987
|
-
right: RefactorEvidenceDirectionViolationV1
|
|
988
|
-
): number {
|
|
989
|
-
return compareText(left.constraintId, right.constraintId) || compareRefactorEvidenceImportEdges(left, right);
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
export function compareRefactorEvidenceUnresolvedImports(
|
|
993
|
-
left: RefactorEvidenceUnresolvedImportV1,
|
|
994
|
-
right: RefactorEvidenceUnresolvedImportV1
|
|
995
|
-
): number {
|
|
996
|
-
return compareText(left.fromPath, right.fromPath)
|
|
997
|
-
|| compareLine(left.fromLine, right.fromLine)
|
|
998
|
-
|| compareText(left.specifier, right.specifier);
|
|
999
|
-
}
|
|
1000
|
-
|
|
1001
|
-
/**
|
|
1002
|
-
* Validates one observation's evidence against the observation it explains: matching kind, the
|
|
1003
|
-
* fixed sample and id-list bounds, an honest `truncated` flag and id-list counts, the canonical
|
|
1004
|
-
* order, repo-relative paths, positive lines and one-line bounded specifiers. Where a metric counts exactly the evidence population,
|
|
1005
|
-
* `totalCount` must equal it, so the sample can never describe a different measurement.
|
|
1006
|
-
*/
|
|
1007
|
-
export function refactorObservationEvidenceIssues(observation: RefactorObservationV1, prefix = "observation"): string[] {
|
|
1008
|
-
const evidence = observation.evidence as RefactorObservationEvidenceV1 | undefined;
|
|
1009
|
-
const label = `${prefix}.evidence`;
|
|
1010
|
-
if (!evidence || typeof evidence !== "object") return [`${label} is required`];
|
|
1011
|
-
if (evidence.kind !== observation.kind) return [`${label}.kind must equal the observation kind ${observation.kind}`];
|
|
1012
|
-
const issues: string[] = [];
|
|
1013
|
-
const sample = (entries: readonly unknown[], field: string): void => {
|
|
1014
|
-
if (entries.length > REFACTOR_OBSERVATION_EVIDENCE_LIMIT) {
|
|
1015
|
-
issues.push(`${label}.${field} must hold at most ${REFACTOR_OBSERVATION_EVIDENCE_LIMIT} entries`);
|
|
1016
|
-
}
|
|
1017
|
-
if (!Number.isInteger(evidence.totalCount) || evidence.totalCount < entries.length) {
|
|
1018
|
-
issues.push(`${label}.totalCount must be an integer no smaller than the ${field} length`);
|
|
1019
|
-
}
|
|
1020
|
-
if (evidence.truncated !== evidence.totalCount > entries.length) {
|
|
1021
|
-
issues.push(`${label}.truncated must be true exactly when totalCount exceeds the ${field} length`);
|
|
1022
|
-
}
|
|
1023
|
-
};
|
|
1024
|
-
const ordered = <T>(entries: readonly T[], field: string, compare: (left: T, right: T) => number): void => {
|
|
1025
|
-
for (let index = 1; index < entries.length; index += 1) {
|
|
1026
|
-
if (compare(entries[index - 1]!, entries[index]!) >= 0) {
|
|
1027
|
-
issues.push(`${label}.${field} must be sorted and unique`);
|
|
1028
|
-
return;
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
};
|
|
1032
|
-
const edgeIssues = (edge: RefactorEvidenceImportEdgeV1, field: string): void => {
|
|
1033
|
-
issues.push(...repoPathIssues(`${label}.${field}.fromPath`, edge.fromPath), ...repoPathIssues(`${label}.${field}.toPath`, edge.toPath));
|
|
1034
|
-
issues.push(...lineIssues(`${label}.${field}.fromLine`, edge.fromLine), ...specifierIssues(`${label}.${field}.specifier`, edge.specifier));
|
|
1035
|
-
if (edge.fromNodeId.trim() === "" || edge.toNodeId.trim() === "") issues.push(`${label}.${field} node ids must not be empty`);
|
|
1036
|
-
};
|
|
1037
|
-
// An id list is the sorted prefix of a population of `count`: exactly min(count, limit) long.
|
|
1038
|
-
const idList = (ids: readonly string[], count: unknown, field: string, countField: string): void => {
|
|
1039
|
-
issues.push(...sortedUniqueIssues(`${label}.${field}`, ids));
|
|
1040
|
-
if (!Number.isInteger(count) || (count as number) < 0) {
|
|
1041
|
-
issues.push(`${label}.${countField} must be a non-negative integer`);
|
|
1042
|
-
} else if (ids.length !== Math.min(count as number, REFACTOR_EVIDENCE_ID_LIST_LIMIT)) {
|
|
1043
|
-
issues.push(`${label}.${field} must hold min(${countField}, ${REFACTOR_EVIDENCE_ID_LIST_LIMIT}) entries`);
|
|
1044
|
-
}
|
|
1045
|
-
};
|
|
1046
|
-
switch (evidence.kind) {
|
|
1047
|
-
case "cycle": {
|
|
1048
|
-
sample(evidence.edges, "edges");
|
|
1049
|
-
ordered(evidence.edges, "edges", compareRefactorEvidenceImportEdges);
|
|
1050
|
-
issues.push(...pairEvidenceIssues(observation, evidence, label));
|
|
1051
|
-
for (const edge of evidence.edges) edgeIssues(edge, "edges");
|
|
1052
|
-
break;
|
|
1053
|
-
}
|
|
1054
|
-
case "residual-cycle": {
|
|
1055
|
-
sample(evidence.edges, "edges");
|
|
1056
|
-
ordered(evidence.edges, "edges", compareRefactorEvidenceImportEdges);
|
|
1057
|
-
idList(evidence.memberNodeIds, observation.metrics.memberCount, "memberNodeIds", "metrics.memberCount");
|
|
1058
|
-
// Membership is checkable only against the complete member list.
|
|
1059
|
-
const complete = evidence.memberNodeIds.length === observation.metrics.memberCount;
|
|
1060
|
-
for (const edge of evidence.edges) {
|
|
1061
|
-
edgeIssues(edge, "edges");
|
|
1062
|
-
if (complete && (!evidence.memberNodeIds.includes(edge.fromNodeId) || !evidence.memberNodeIds.includes(edge.toNodeId))) {
|
|
1063
|
-
issues.push(`${label}.edges must stay inside the component's member nodes`);
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
break;
|
|
1067
|
-
}
|
|
1068
|
-
case "direction-violation":
|
|
1069
|
-
sample(evidence.violations, "violations");
|
|
1070
|
-
ordered(evidence.violations, "violations", compareRefactorEvidenceDirectionViolations);
|
|
1071
|
-
idList(evidence.constraintIds, evidence.constraintCount, "constraintIds", "constraintCount");
|
|
1072
|
-
for (const violation of evidence.violations) {
|
|
1073
|
-
edgeIssues(violation, "violations");
|
|
1074
|
-
if (!evidence.constraintIds.includes(violation.constraintId)) issues.push(`${label}.violations must name a listed constraintId`);
|
|
1075
|
-
}
|
|
1076
|
-
if (evidence.totalCount !== observation.metrics.directionViolationCount) {
|
|
1077
|
-
issues.push(`${label}.totalCount must equal metrics.directionViolationCount`);
|
|
1078
|
-
}
|
|
1079
|
-
break;
|
|
1080
|
-
case "ownership-ambiguous":
|
|
1081
|
-
case "undeclared-footprint":
|
|
1082
|
-
case "unowned-paths":
|
|
1083
|
-
sample(evidence.paths, "paths");
|
|
1084
|
-
ordered(evidence.paths, "paths", (left, right) => compareText(left.path, right.path));
|
|
1085
|
-
for (const entry of evidence.paths) {
|
|
1086
|
-
issues.push(...repoPathIssues(`${label}.paths.path`, entry.path));
|
|
1087
|
-
idList(entry.candidateOwnerNodeIds, entry.candidateOwnerCount, "paths.candidateOwnerNodeIds", "paths.candidateOwnerCount");
|
|
1088
|
-
}
|
|
1089
|
-
if (evidence.kind === "unowned-paths" && evidence.totalCount !== observation.metrics.unownedFileCount) {
|
|
1090
|
-
issues.push(`${label}.totalCount must equal metrics.unownedFileCount`);
|
|
1091
|
-
}
|
|
1092
|
-
break;
|
|
1093
|
-
case "evidence-gap":
|
|
1094
|
-
sample(evidence.unresolvedImports, "unresolvedImports");
|
|
1095
|
-
ordered(evidence.unresolvedImports, "unresolvedImports", compareRefactorEvidenceUnresolvedImports);
|
|
1096
|
-
issues.push(...sortedUniqueIssues(`${label}.reasonCodes`, evidence.reasonCodes));
|
|
1097
|
-
for (const entry of evidence.unresolvedImports) {
|
|
1098
|
-
issues.push(...repoPathIssues(`${label}.unresolvedImports.fromPath`, entry.fromPath));
|
|
1099
|
-
issues.push(...lineIssues(`${label}.unresolvedImports.fromLine`, entry.fromLine));
|
|
1100
|
-
issues.push(...specifierIssues(`${label}.unresolvedImports.specifier`, entry.specifier));
|
|
1101
|
-
}
|
|
1102
|
-
if (evidence.totalCount !== observation.metrics.unresolvedImportCount) {
|
|
1103
|
-
issues.push(`${label}.totalCount must equal metrics.unresolvedImportCount`);
|
|
1104
|
-
}
|
|
1105
|
-
break;
|
|
1106
|
-
default:
|
|
1107
|
-
issues.push(`${label}.kind is unsupported`);
|
|
1108
|
-
}
|
|
1109
|
-
return [...new Set(issues)];
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* A pair's evidence explains exactly that pair: its two ends are the observation's affected nodes,
|
|
1114
|
-
* every edge runs between them in one of the two listed directions, the thin direction (by the
|
|
1115
|
-
* observation's own distinct-file-edge counts, ties to the forward direction) comes first, each
|
|
1116
|
-
* direction's `sampledCount` is the number of its edges in the sample, and the split is the one
|
|
1117
|
-
* `refactorPairSampleAllocation` prescribes for the sample size.
|
|
1118
|
-
*/
|
|
1119
|
-
function pairEvidenceIssues(
|
|
1120
|
-
observation: RefactorObservationV1,
|
|
1121
|
-
evidence: Extract<RefactorObservationEvidenceV1, { kind: "cycle" }>,
|
|
1122
|
-
label: string
|
|
1123
|
-
): string[] {
|
|
1124
|
-
const issues: string[] = [];
|
|
1125
|
-
const members = evidence.memberNodeIds;
|
|
1126
|
-
if (!Array.isArray(members) || members.length !== 2 || !(members[0]! < members[1]!)) {
|
|
1127
|
-
return [`${label}.memberNodeIds must be the two pair ends, sorted`];
|
|
1128
|
-
}
|
|
1129
|
-
const [first, second] = members as [string, string];
|
|
1130
|
-
if (Array.isArray(observation.affectedNodeIds) && (observation.affectedNodeIds.length !== 2
|
|
1131
|
-
|| observation.affectedNodeIds[0] !== first || observation.affectedNodeIds[1] !== second)) {
|
|
1132
|
-
issues.push(`${label}.memberNodeIds must equal the observation affectedNodeIds`);
|
|
1133
|
-
}
|
|
1134
|
-
const forward = observation.metrics.forwardEdgeCount;
|
|
1135
|
-
const backward = observation.metrics.backwardEdgeCount;
|
|
1136
|
-
if (!Number.isInteger(forward) || !Number.isInteger(backward) || (forward as number) < 1 || (backward as number) < 1) {
|
|
1137
|
-
issues.push(`${label} requires positive integer metrics.forwardEdgeCount and metrics.backwardEdgeCount`);
|
|
1138
|
-
return issues;
|
|
1139
|
-
}
|
|
1140
|
-
if (observation.metrics.thinDirectionEdgeCount !== Math.min(forward as number, backward as number)) {
|
|
1141
|
-
issues.push(`${label} requires metrics.thinDirectionEdgeCount = min(forwardEdgeCount, backwardEdgeCount)`);
|
|
1142
|
-
}
|
|
1143
|
-
if (observation.metrics.totalEdgeCount !== (forward as number) + (backward as number)) {
|
|
1144
|
-
issues.push(`${label} requires metrics.totalEdgeCount = forwardEdgeCount + backwardEdgeCount`);
|
|
1145
|
-
}
|
|
1146
|
-
const directions = evidence.directions;
|
|
1147
|
-
if (!Array.isArray(directions) || directions.length !== 2) return [...issues, `${label}.directions must list the thin then the thick direction`];
|
|
1148
|
-
const [thin, thick] = directions as [RefactorEvidencePairDirectionV1, RefactorEvidencePairDirectionV1];
|
|
1149
|
-
const forwardIsThin = (forward as number) <= (backward as number);
|
|
1150
|
-
const expectedThin = forwardIsThin ? [first, second] : [second, first];
|
|
1151
|
-
if (thin.fromNodeId !== expectedThin[0] || thin.toNodeId !== expectedThin[1]
|
|
1152
|
-
|| thick.fromNodeId !== expectedThin[1] || thick.toNodeId !== expectedThin[0]) {
|
|
1153
|
-
issues.push(`${label}.directions must be [thin, thick] by the pair's distinct file edge counts`);
|
|
1154
|
-
}
|
|
1155
|
-
for (const direction of directions) {
|
|
1156
|
-
if (!Number.isInteger(direction.totalCount) || direction.totalCount < 1) issues.push(`${label}.directions totalCount must be a positive integer`);
|
|
1157
|
-
const sampled = evidence.edges.filter((edge) => edge.fromNodeId === direction.fromNodeId && edge.toNodeId === direction.toNodeId).length;
|
|
1158
|
-
if (direction.sampledCount !== sampled) issues.push(`${label}.directions sampledCount must count the sampled edges of that direction`);
|
|
1159
|
-
if (sampled > direction.totalCount) issues.push(`${label}.directions sample must not exceed the direction population`);
|
|
1160
|
-
}
|
|
1161
|
-
if (thin.totalCount + thick.totalCount !== evidence.totalCount) issues.push(`${label}.totalCount must be the sum of both directions`);
|
|
1162
|
-
if (evidence.edges.some((edge) => !((edge.fromNodeId === first && edge.toNodeId === second) || (edge.fromNodeId === second && edge.toNodeId === first)))) {
|
|
1163
|
-
issues.push(`${label}.edges must run between the pair's two ends`);
|
|
1164
|
-
}
|
|
1165
|
-
const allocation = refactorPairSampleAllocation(thin.totalCount, thick.totalCount, evidence.edges.length);
|
|
1166
|
-
if (thin.sampledCount !== allocation.thin || thick.sampledCount !== allocation.thick) {
|
|
1167
|
-
issues.push(`${label}.edges must sample the thin direction first and keep one slot for the thick direction`);
|
|
1168
|
-
}
|
|
1169
|
-
return issues;
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
export function refactorResolutionEvidenceInvariantIssues(
|
|
1173
|
-
evidence: RefactorResolutionEvidenceV1,
|
|
1174
|
-
prefix = "resolutionEvidence"
|
|
1175
|
-
): string[] {
|
|
1176
|
-
const issues = [
|
|
1177
|
-
...digestIssues(`${prefix}.resolutionDigest`, evidence.resolutionDigest),
|
|
1178
|
-
...digestIssues(`${prefix}.recommendationDigest`, evidence.recommendationDigest),
|
|
1179
|
-
...digestIssues(`${prefix}.beforeSnapshotDigest`, evidence.beforeSnapshotDigest),
|
|
1180
|
-
...digestIssues(`${prefix}.afterSnapshotDigest`, evidence.afterSnapshotDigest),
|
|
1181
|
-
...outcomeIssues(`${prefix}.expectedOutcomes`, evidence.expectedOutcomes),
|
|
1182
|
-
...sortedUniqueIssues(`${prefix}.observedOutcomes.outcomeId`, evidence.observedOutcomes.map((outcome) => outcome.outcomeId))
|
|
1183
|
-
];
|
|
1184
|
-
if (evidence.schemaVersion !== REFACTOR_RESOLUTION_EVIDENCE_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
1185
|
-
const observedById = new Map(evidence.observedOutcomes.map((outcome) => [outcome.outcomeId, outcome]));
|
|
1186
|
-
for (const expected of evidence.expectedOutcomes) {
|
|
1187
|
-
if (!observedById.has(expected.outcomeId)) issues.push(`${prefix}.observedOutcomes is missing outcome ${expected.outcomeId}`);
|
|
1188
|
-
}
|
|
1189
|
-
for (const ref of evidence.executionEvidenceRefs) {
|
|
1190
|
-
if (!/^[a-f0-9]{64}$/.test(ref.sha256)) issues.push(`${prefix}.executionEvidenceRefs.sha256 must be a bare SHA-256 hex digest`);
|
|
1191
|
-
if (ref.locator.trim() === "") issues.push(`${prefix}.executionEvidenceRefs.locator must not be empty`);
|
|
1192
|
-
}
|
|
1193
|
-
for (const expected of evidence.expectedOutcomes) {
|
|
1194
|
-
const observed = observedById.get(expected.outcomeId);
|
|
1195
|
-
if (!observed) continue;
|
|
1196
|
-
const recomputed = outcomeSatisfied(expected, observed.observedValue);
|
|
1197
|
-
if (observed.satisfied !== recomputed) {
|
|
1198
|
-
issues.push(
|
|
1199
|
-
`${prefix}.observedOutcomes ${expected.outcomeId} claims satisfied=${observed.satisfied} but ${expected.metric} ${expected.operator} ${expected.value} against ${observed.observedValue} is ${recomputed}`
|
|
1200
|
-
);
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
if (evidence.disposition !== "stale") {
|
|
1204
|
-
const required = evidence.expectedOutcomes.filter((outcome) => outcome.required);
|
|
1205
|
-
const observedRequired = required
|
|
1206
|
-
.map((outcome) => {
|
|
1207
|
-
const observed = observedById.get(outcome.outcomeId);
|
|
1208
|
-
return observed ? { outcome, satisfied: outcomeSatisfied(outcome, observed.observedValue) } : undefined;
|
|
1209
|
-
})
|
|
1210
|
-
.filter(isPresent);
|
|
1211
|
-
const regressed = evidence.observedOutcomes.some((outcome) => outcome.direction === "regressed");
|
|
1212
|
-
const satisfiedCount = observedRequired.filter((entry) => entry.satisfied).length;
|
|
1213
|
-
if (regressed && evidence.disposition !== "regressed") {
|
|
1214
|
-
issues.push(`${prefix}.disposition must be regressed when any observed outcome regressed`);
|
|
1215
|
-
}
|
|
1216
|
-
if (!regressed && required.length > 0) {
|
|
1217
|
-
if (satisfiedCount === required.length && evidence.disposition !== "resolved") {
|
|
1218
|
-
issues.push(`${prefix}.disposition must be resolved when every required outcome is satisfied`);
|
|
1219
|
-
}
|
|
1220
|
-
if (satisfiedCount === 0 && evidence.disposition !== "not_improved") {
|
|
1221
|
-
issues.push(`${prefix}.disposition must be not_improved when no required outcome is satisfied`);
|
|
1222
|
-
}
|
|
1223
|
-
if (satisfiedCount > 0 && satisfiedCount < required.length && evidence.disposition !== "partially_resolved") {
|
|
1224
|
-
issues.push(`${prefix}.disposition must be partially_resolved when only some required outcomes are satisfied`);
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
if (refactorResolutionEvidenceDigest(evidence) !== evidence.resolutionDigest) {
|
|
1229
|
-
issues.push(`${prefix}.resolutionDigest must bind the verified payload`);
|
|
1230
|
-
}
|
|
1231
|
-
return issues;
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
/**
|
|
1235
|
-
* Guards the one invariant the `RecommendationV3` union cannot enforce at
|
|
1236
|
-
* runtime: that `payload` matches `category`. A non-object or mismatched
|
|
1237
|
-
* payload yields issues instead of throwing. Every other field is trusted to
|
|
1238
|
-
* match its declared type; structural validation of untrusted ingress is the
|
|
1239
|
-
* job of the JSON Schemas, not of this validator.
|
|
1240
|
-
*
|
|
1241
|
-
* The fingerprint hash itself stays owned by `recommendationFingerprint()` in
|
|
1242
|
-
* `packages/core/recommendation-engine`: contracts must not import core, and
|
|
1243
|
-
* re-deriving the hash here would fork it into two definitions. This validator
|
|
1244
|
-
* therefore checks the fingerprint's shape, not its value.
|
|
1245
|
-
*/
|
|
1246
|
-
export function recommendationV3InvariantIssues(recommendation: RecommendationV3, prefix = "recommendation"): string[] {
|
|
1247
|
-
const issues = [
|
|
1248
|
-
...sortedUniqueIssues(`${prefix}.evidenceBindingIds`, recommendation.evidenceBindingIds),
|
|
1249
|
-
...digestIssues(`${prefix}.fingerprint`, recommendation.fingerprint)
|
|
1250
|
-
];
|
|
1251
|
-
if (recommendation.schemaVersion !== RECOMMENDATION_V3_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
|
|
1252
|
-
if (!(RECOMMENDATION_CATEGORIES as readonly string[]).includes(recommendation.category)) {
|
|
1253
|
-
issues.push(`${prefix}.category is unsupported: ${recommendation.category}`);
|
|
1254
|
-
return issues;
|
|
1255
|
-
}
|
|
1256
|
-
if (recommendation.subjectSelectorId.trim() === "") issues.push(`${prefix}.subjectSelectorId must not be empty`);
|
|
1257
|
-
if (recommendation.authoredBy.id.trim() === "") issues.push(`${prefix}.authoredBy.id must not be empty`);
|
|
1258
|
-
const shapeIssues = recommendationPayloadShapeIssues(recommendation.category, recommendation.payload, prefix);
|
|
1259
|
-
issues.push(...shapeIssues);
|
|
1260
|
-
if (recommendation.category === "practice" && !recommendation.practiceId) {
|
|
1261
|
-
issues.push(`${prefix}.practiceId is required for practice recommendations`);
|
|
1262
|
-
}
|
|
1263
|
-
if (recommendation.category === "structural_observation") {
|
|
1264
|
-
if (recommendation.authoredBy.source !== "daemon") {
|
|
1265
|
-
issues.push(`${prefix}.structural_observation must be authored by the daemon`);
|
|
1266
|
-
}
|
|
1267
|
-
if (recommendation.authoredBy.kind !== "daemon") {
|
|
1268
|
-
issues.push(`${prefix}.structural_observation must be authored by the daemon actor kind`);
|
|
1269
|
-
}
|
|
1270
|
-
if (recommendation.enforcement !== "advisory") {
|
|
1271
|
-
issues.push(`${prefix}.structural_observation enforcement must be advisory`);
|
|
1272
|
-
}
|
|
1273
|
-
if (shapeIssues.length === 0) {
|
|
1274
|
-
// The payload is self-contained: the observation's metrics, signals and evidence travel with
|
|
1275
|
-
// it, so the same evidence rules bind a recorded record and a fresh assessment.
|
|
1276
|
-
const payload = recommendation.payload as StructuralObservationPayloadV1;
|
|
1277
|
-
issues.push(
|
|
1278
|
-
...sortedUniqueIssues(`${prefix}.payload.signalIds`, payload.signalIds),
|
|
1279
|
-
...refactorObservationEvidenceIssues(
|
|
1280
|
-
{
|
|
1281
|
-
kind: payload.kind,
|
|
1282
|
-
subjectSelectorId: recommendation.subject,
|
|
1283
|
-
affectedNodeIds: payload.affectedNodeIds,
|
|
1284
|
-
signalIds: payload.signalIds,
|
|
1285
|
-
metrics: payload.metrics,
|
|
1286
|
-
evidence: payload.evidence
|
|
1287
|
-
},
|
|
1288
|
-
`${prefix}.payload`
|
|
1289
|
-
)
|
|
1290
|
-
);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
if (recommendation.category === "refactor_proposal") {
|
|
1294
|
-
if (!isRefactorProposalAuthorSource(recommendation.authoredBy.source)) {
|
|
1295
|
-
issues.push(`${prefix}.refactor_proposal must not be authored by ${recommendation.authoredBy.source}`);
|
|
1296
|
-
}
|
|
1297
|
-
issues.push(...refactorProposalAuthorIssues(recommendation.authoredBy, prefix));
|
|
1298
|
-
if (shapeIssues.length === 0) {
|
|
1299
|
-
const payload = recommendation.payload as RefactorProposalPayloadV1;
|
|
1300
|
-
const expected = payload.scale === "architecture" ? "complete" : "checkpoint";
|
|
1301
|
-
if (recommendation.enforcement !== expected) {
|
|
1302
|
-
issues.push(`${prefix}.refactor_proposal with scale ${payload.scale} requires ${expected} enforcement`);
|
|
1303
|
-
}
|
|
1304
|
-
issues.push(
|
|
1305
|
-
...digestIssues(`${prefix}.payload.proposalDigest`, payload.proposalDigest),
|
|
1306
|
-
...sortedUniqueIssues(`${prefix}.payload.affectedNodeIds`, payload.affectedNodeIds),
|
|
1307
|
-
...sortedUniqueIssues(`${prefix}.payload.majorChangeReasons`, payload.majorChangeReasons)
|
|
1308
|
-
);
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
return issues;
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
export function refactorScanInvariantIssues(input: {
|
|
1315
|
-
snapshot: ModuleStatisticsSnapshotV1;
|
|
1316
|
-
assessment: RefactorAssessmentV1;
|
|
1317
|
-
proposal?: RefactorProposalV1;
|
|
1318
|
-
}): string[] {
|
|
1319
|
-
const issues = [
|
|
1320
|
-
...moduleStatisticsSnapshotInvariantIssues(input.snapshot),
|
|
1321
|
-
...refactorAssessmentInvariantIssues(input.assessment),
|
|
1322
|
-
...(input.proposal ? refactorProposalInvariantIssues(input.proposal) : [])
|
|
1323
|
-
];
|
|
1324
|
-
if (input.assessment.statisticsSnapshotDigest !== input.snapshot.snapshotDigest) {
|
|
1325
|
-
issues.push("assessment.statisticsSnapshotDigest must reference the measured snapshot");
|
|
1326
|
-
}
|
|
1327
|
-
if (input.snapshot.scope !== undefined && digestJson(input.snapshot.scope) !== digestJson(input.assessment.requestedScope)) {
|
|
1328
|
-
issues.push("assessment.requestedScope must match the measured snapshot scope");
|
|
1329
|
-
}
|
|
1330
|
-
if (input.assessment.modelDigest !== input.snapshot.modelDigest) {
|
|
1331
|
-
issues.push("assessment.modelDigest must match the snapshot modelDigest");
|
|
1332
|
-
}
|
|
1333
|
-
const proposalDigest = input.proposal ? input.proposal.proposalDigest : null;
|
|
1334
|
-
if (input.assessment.proposalDigest !== proposalDigest) {
|
|
1335
|
-
issues.push("assessment.proposalDigest must reference the submitted proposal");
|
|
1336
|
-
}
|
|
1337
|
-
const unresolved = input.proposal?.targetDelta?.unresolvedTargets ?? [];
|
|
1338
|
-
if (unresolved.length > 0 && input.assessment.scale !== "insufficient_evidence") {
|
|
1339
|
-
issues.push("assessment.scale must be insufficient_evidence while targetDelta.unresolvedTargets is non-empty");
|
|
1340
|
-
}
|
|
1341
|
-
if (unresolved.length > 0 && !input.assessment.scaleReasonCodes.includes("target-unresolved")) {
|
|
1342
|
-
issues.push("assessment.scaleReasonCodes must include target-unresolved while targets stay unresolved");
|
|
1343
|
-
}
|
|
1344
|
-
return issues;
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
export function refactorVerifyInvariantIssues(
|
|
1348
|
-
afterSnapshot: ModuleStatisticsSnapshotV1,
|
|
1349
|
-
evidence: RefactorResolutionEvidenceV1
|
|
1350
|
-
): string[] {
|
|
1351
|
-
const issues = [
|
|
1352
|
-
...moduleStatisticsSnapshotInvariantIssues(afterSnapshot, "afterSnapshot"),
|
|
1353
|
-
...refactorResolutionEvidenceInvariantIssues(evidence)
|
|
1354
|
-
];
|
|
1355
|
-
if (evidence.afterSnapshotDigest !== afterSnapshot.snapshotDigest) {
|
|
1356
|
-
issues.push("resolutionEvidence.afterSnapshotDigest must reference the re-measured snapshot");
|
|
1357
|
-
}
|
|
1358
|
-
if (evidence.verifiedHeadSha !== afterSnapshot.worktree.headSha) {
|
|
1359
|
-
issues.push("resolutionEvidence.verifiedHeadSha must match the re-measured worktree HEAD");
|
|
1360
|
-
}
|
|
1361
|
-
if (evidence.verifiedWorktreeDigest !== afterSnapshot.worktree.worktreeDigest) {
|
|
1362
|
-
issues.push("resolutionEvidence.verifiedWorktreeDigest must match the re-measured worktree digest");
|
|
1363
|
-
}
|
|
1364
|
-
if (afterSnapshot.codeFacts.coverage !== "complete" && evidence.disposition === "resolved") {
|
|
1365
|
-
issues.push("resolutionEvidence.disposition must not be resolved while after-snapshot coverage is incomplete");
|
|
1366
|
-
}
|
|
1367
|
-
const indexCoversWorktree =
|
|
1368
|
-
afterSnapshot.codeFacts.indexedWorktreeDigest !== null
|
|
1369
|
-
&& afterSnapshot.codeFacts.indexedWorktreeDigest === afterSnapshot.worktree.worktreeDigest;
|
|
1370
|
-
if (!indexCoversWorktree && evidence.disposition === "resolved") {
|
|
1371
|
-
issues.push("resolutionEvidence.disposition must not be resolved while the after-snapshot index does not cover the verified worktree");
|
|
1372
|
-
}
|
|
1373
|
-
return issues;
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
function authoredTargetDelta(delta: ArchitectureTargetDeltaV1): Omit<ArchitectureTargetDeltaV1, "interventionId" | "unresolvedTargets" | "extensions"> {
|
|
1377
|
-
const {
|
|
1378
|
-
interventionId: _interventionId,
|
|
1379
|
-
unresolvedTargets: _unresolvedTargets,
|
|
1380
|
-
extensions: _extensions,
|
|
1381
|
-
...authored
|
|
1382
|
-
} = delta;
|
|
1383
|
-
return authored;
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
function isRefactorProposalAuthorSource(source: string): source is RefactorProposalAuthorSource {
|
|
1387
|
-
return (REFACTOR_PROPOSAL_AUTHOR_SOURCES as readonly string[]).includes(source);
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
function isRefactorProposalAuthorKind(kind: string): kind is RefactorProposalAuthorKind {
|
|
1391
|
-
return (REFACTOR_PROPOSAL_AUTHOR_KINDS as readonly string[]).includes(kind);
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1394
|
-
function refactorProposalAuthorIssues(author: RecommendationAuthorV1, prefix: string): string[] {
|
|
1395
|
-
const issues: string[] = [];
|
|
1396
|
-
if (author.id.trim() === "") issues.push(`${prefix}.authoredBy.id must not be empty`);
|
|
1397
|
-
if (!isRefactorProposalAuthorSource(author.source)) {
|
|
1398
|
-
issues.push(`${prefix}.authoredBy.source must not be ${author.source}; refactor proposals are agent or human authored`);
|
|
1399
|
-
}
|
|
1400
|
-
if (!isRefactorProposalAuthorKind(author.kind)) {
|
|
1401
|
-
issues.push(`${prefix}.authoredBy.kind must not be ${author.kind}; refactor proposals are agent or human authored`);
|
|
1402
|
-
return issues;
|
|
1403
|
-
}
|
|
1404
|
-
if (isRefactorProposalAuthorSource(author.source) && !REFACTOR_PROPOSAL_AUTHOR_PAIRS[author.kind].includes(author.source)) {
|
|
1405
|
-
issues.push(`${prefix}.authoredBy.kind ${author.kind} is not compatible with source ${author.source}`);
|
|
1406
|
-
}
|
|
1407
|
-
return issues;
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
function outcomeSatisfied(expected: RefactorTargetOutcomeV1, observedValue: number | null): boolean {
|
|
1411
|
-
switch (expected.operator) {
|
|
1412
|
-
case "absent":
|
|
1413
|
-
return observedValue === null || observedValue === 0;
|
|
1414
|
-
case "present":
|
|
1415
|
-
return observedValue !== null && observedValue !== 0;
|
|
1416
|
-
case "equals":
|
|
1417
|
-
return observedValue !== null && expected.value !== null && observedValue === expected.value;
|
|
1418
|
-
case "greater_than":
|
|
1419
|
-
return observedValue !== null && expected.value !== null && observedValue > expected.value;
|
|
1420
|
-
case "less_than":
|
|
1421
|
-
return observedValue !== null && expected.value !== null && observedValue < expected.value;
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
function recommendationPayloadShapeIssues(
|
|
1426
|
-
category: RecommendationCategory,
|
|
1427
|
-
payload: RecommendationPayloadV1,
|
|
1428
|
-
prefix: string
|
|
1429
|
-
): string[] {
|
|
1430
|
-
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
1431
|
-
return [`${prefix}.payload must be an object for category ${category}`];
|
|
1432
|
-
}
|
|
1433
|
-
const record = payload as unknown as Record<string, unknown>;
|
|
1434
|
-
const required = REQUIRED_PAYLOAD_FIELDS[category];
|
|
1435
|
-
const missing = required.filter((field) => !(field in record));
|
|
1436
|
-
return missing.length === 0 ? [] : [`${prefix}.payload does not match category ${category}; missing ${missing.sort().join(", ")}`];
|
|
1437
|
-
}
|
|
1438
|
-
|
|
1439
|
-
function nonNegativeIntegerIssues(label: string, value: number | null): string[] {
|
|
1440
|
-
if (value === null) return [];
|
|
1441
|
-
return Number.isInteger(value) && value >= 0 ? [] : [`${label} must be a non-negative integer`];
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
function ratioIssues(label: string, value: number | null): string[] {
|
|
1445
|
-
if (value === null) return [];
|
|
1446
|
-
return Number.isFinite(value) && value >= 0 && value <= 1 ? [] : [`${label} must be a ratio between 0 and 1`];
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
const REQUIRED_PAYLOAD_FIELDS: Readonly<Record<RecommendationCategory, readonly string[]>> = {
|
|
1450
|
-
practice: ["baselineDigest", "practiceId"],
|
|
1451
|
-
refactor_proposal: [
|
|
1452
|
-
"affectedNodeIds",
|
|
1453
|
-
"assessmentDigest",
|
|
1454
|
-
"baselineSnapshotDigest",
|
|
1455
|
-
"killList",
|
|
1456
|
-
"majorChangeReasons",
|
|
1457
|
-
"proposalDigest",
|
|
1458
|
-
"scale",
|
|
1459
|
-
"targetOutcomes"
|
|
1460
|
-
],
|
|
1461
|
-
structural_observation: [
|
|
1462
|
-
"affectedNodeIds",
|
|
1463
|
-
"assessmentDigest",
|
|
1464
|
-
"baselineSnapshotDigest",
|
|
1465
|
-
"derivedOutcomes",
|
|
1466
|
-
"evidence",
|
|
1467
|
-
"kind",
|
|
1468
|
-
"metrics",
|
|
1469
|
-
"signalIds"
|
|
1470
|
-
]
|
|
1471
|
-
};
|
|
1472
|
-
|
|
1473
|
-
function fingerprintPayloadSubset(category: RecommendationCategory, payload: RecommendationPayloadV1): Record<string, Json> {
|
|
1474
|
-
if (category === "practice") {
|
|
1475
|
-
return { baselineDigest: (payload as PracticeRecommendationPayloadV1).baselineDigest };
|
|
1476
|
-
}
|
|
1477
|
-
if (category === "structural_observation") {
|
|
1478
|
-
const observation = payload as StructuralObservationPayloadV1;
|
|
1479
|
-
return { kind: observation.kind, affectedNodeIds: [...observation.affectedNodeIds].sort() };
|
|
1480
|
-
}
|
|
1481
|
-
const proposal = payload as RefactorProposalPayloadV1;
|
|
1482
|
-
return {
|
|
1483
|
-
proposalDigest: proposal.proposalDigest,
|
|
1484
|
-
scale: proposal.scale,
|
|
1485
|
-
affectedNodeIds: [...proposal.affectedNodeIds].sort(),
|
|
1486
|
-
majorChangeReasons: [...proposal.majorChangeReasons].sort()
|
|
1487
|
-
};
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
function outcomeIssues(label: string, outcomes: readonly RefactorTargetOutcomeV1[]): string[] {
|
|
1491
|
-
const issues = sortedUniqueIssues(`${label}.outcomeId`, outcomes.map((outcome) => outcome.outcomeId));
|
|
1492
|
-
for (const outcome of outcomes) {
|
|
1493
|
-
if (outcome.memberNodeIds !== undefined) {
|
|
1494
|
-
if (!Array.isArray(outcome.memberNodeIds) || outcome.memberNodeIds.length < 2) {
|
|
1495
|
-
issues.push(`${label} memberNodeIds must list at least two modules`);
|
|
1496
|
-
} else {
|
|
1497
|
-
issues.push(...sortedUniqueIssues(`${label}.memberNodeIds`, outcome.memberNodeIds));
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
const valueless = outcome.operator === "absent" || outcome.operator === "present";
|
|
1501
|
-
if (valueless && outcome.value !== null) issues.push(`${label} operator ${outcome.operator} must not carry a value`);
|
|
1502
|
-
if (!valueless && outcome.value === null) issues.push(`${label} operator ${outcome.operator} requires a value`);
|
|
1503
|
-
if (outcome.metric.trim() === "") issues.push(`${label} metric must not be empty`);
|
|
1504
|
-
}
|
|
1505
|
-
return issues;
|
|
1506
|
-
}
|
|
1507
|
-
|
|
1508
|
-
function compareText(left: string, right: string): number {
|
|
1509
|
-
return left < right ? -1 : left > right ? 1 : 0;
|
|
1510
|
-
}
|
|
1511
|
-
|
|
1512
|
-
/** An unknown line sorts before every known one, so the order is total. */
|
|
1513
|
-
function compareLine(left: number | null, right: number | null): number {
|
|
1514
|
-
return (left ?? 0) - (right ?? 0);
|
|
1515
|
-
}
|
|
1516
|
-
|
|
1517
|
-
function repoPathIssues(label: string, path: string): string[] {
|
|
1518
|
-
return typeof path === "string" && isRepoRelativePosixPath(path) ? [] : [`${label} must be a repo-relative POSIX path`];
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
function lineIssues(label: string, line: number | null): string[] {
|
|
1522
|
-
return line === null || (Number.isInteger(line) && line >= 1) ? [] : [`${label} must be null or a positive integer`];
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
function specifierIssues(label: string, specifier: string): string[] {
|
|
1526
|
-
return typeof specifier === "string"
|
|
1527
|
-
&& specifier.length > 0
|
|
1528
|
-
&& specifier.length <= REFACTOR_EVIDENCE_SPECIFIER_MAX_LENGTH
|
|
1529
|
-
&& !/[\u0000-\u001f\u007f]/.test(specifier)
|
|
1530
|
-
? []
|
|
1531
|
-
: [`${label} must be a single-line specifier of 1-${REFACTOR_EVIDENCE_SPECIFIER_MAX_LENGTH} characters`];
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
function digestIssues(label: string, value: string): string[] {
|
|
1535
|
-
return SHA256_DIGEST_PATTERN.test(value) ? [] : [`${label} must be a sha256:<64-hex> digest`];
|
|
1536
|
-
}
|
|
1537
|
-
|
|
1538
|
-
function isPresent<T>(value: T | undefined): value is T {
|
|
1539
|
-
return value !== undefined;
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
function sortedUniqueIssues(label: string, values: readonly string[]): string[] {
|
|
1543
|
-
const expected = [...new Set(values)].sort();
|
|
1544
|
-
return expected.length === values.length && expected.every((value, index) => value === values[index])
|
|
1545
|
-
? []
|
|
1546
|
-
: [`${label} must be sorted and unique`];
|
|
1547
|
-
}
|
|
1548
|
-
|
|
1549
|
-
/**
|
|
1550
|
-
* The fingerprint schema every refactor recommendation id is derived under. v3 is the first whose
|
|
1551
|
-
* subject selector is scoped by the product namespace instead of the worktree path (ADR-0046).
|
|
1552
|
-
* Owned here so the planner and the Git decision contract can never name two different versions.
|
|
1553
|
-
*/
|
|
1554
|
-
export const REFACTOR_RECOMMENDATION_FINGERPRINT_SCHEMA_VERSION = "archcontext.recommendation-fingerprint/v3" as const;
|
|
1555
|
-
|
|
1556
|
-
export const REFACTOR_DECISION_SCHEMA_VERSION = "archcontext.refactor-decision/v1" as const;
|
|
1557
|
-
/** Git-visible home of human refactor decisions; outside `listModelFiles`, so never in `modelDigest`. */
|
|
1558
|
-
export const REFACTOR_DECISION_DIRECTORY = ".archcontext/refactor-decisions" as const;
|
|
1559
|
-
export const REFACTOR_DECISION_FILE_PATTERN = /^\.archcontext\/refactor-decisions\/(recommendation\.[a-f0-9]{16})\.json$/;
|
|
1560
|
-
export const REFACTOR_RECOMMENDATION_ID_PATTERN = /^recommendation\.[a-f0-9]{16}$/;
|
|
1561
|
-
/** The six human statuses. `open` is a machine status and is never a decision. */
|
|
1562
|
-
export const REFACTOR_DECISION_STATUSES = ["acknowledged", "accepted", "deferred", "rejected", "resolved", "waived"] as const;
|
|
1563
|
-
export const REFACTOR_DECISION_REASON_MAX_LENGTH = 1024;
|
|
1564
|
-
export const REFACTOR_DECISION_ACTOR_ID_MAX_LENGTH = 128;
|
|
1565
|
-
export const REFACTOR_DECISION_STABLE_KEY_MAX_LENGTH = 512;
|
|
1566
|
-
const REFACTOR_DECISION_ACTOR_KINDS: readonly ArchitectureActorKind[] = ["cli", "daemon", "developer", "hook", "mcp", "migration", "subagent", "system"];
|
|
1567
|
-
const REFACTOR_DECISION_SELECTOR_KINDS: readonly ArchitectureSubjectSelectorKind[] = ["node", "repository"];
|
|
1568
|
-
const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
|
|
1569
|
-
const GIT_CONFLICT_MARKER_PATTERN = /^(<{7}|={7}|>{7}|\|{7})( |$)/m;
|
|
1570
|
-
|
|
1571
|
-
export type RefactorDecisionStatus = (typeof REFACTOR_DECISION_STATUSES)[number];
|
|
1572
|
-
|
|
1573
|
-
/**
|
|
1574
|
-
* The latest human decision for one refactor recommendation generation, stored in Git at
|
|
1575
|
-
* `.archcontext/refactor-decisions/<recommendationId>.json` (ADR-0046). It carries identity and the
|
|
1576
|
-
* decided measurement only: no absolute path, storage id, source, diff or evidence body.
|
|
1577
|
-
*/
|
|
1578
|
-
export interface RefactorDecisionV1 {
|
|
1579
|
-
schemaVersion: typeof REFACTOR_DECISION_SCHEMA_VERSION;
|
|
1580
|
-
/** The manifest `product.id` the subject selector is scoped by. */
|
|
1581
|
-
namespace: string;
|
|
1582
|
-
recommendationId: string;
|
|
1583
|
-
fingerprint: string;
|
|
1584
|
-
fingerprintSchemaVersion: typeof REFACTOR_RECOMMENDATION_FINGERPRINT_SCHEMA_VERSION;
|
|
1585
|
-
category: "refactor_proposal" | "structural_observation";
|
|
1586
|
-
/** The observation kind; `null` for a refactor proposal. */
|
|
1587
|
-
kind: RefactorObservationKind | null;
|
|
1588
|
-
subject: {
|
|
1589
|
-
selectorKind: ArchitectureSubjectSelectorKind;
|
|
1590
|
-
stableKey: string;
|
|
1591
|
-
subjectSelectorId: string;
|
|
1592
|
-
};
|
|
1593
|
-
/** Sorted prefix of the affected nodes, bounded by `REFACTOR_EVIDENCE_ID_LIST_LIMIT`. */
|
|
1594
|
-
affectedNodeIds: string[];
|
|
1595
|
-
affectedNodeCount: number;
|
|
1596
|
-
regressesFrom: string | null;
|
|
1597
|
-
status: RefactorDecisionStatus;
|
|
1598
|
-
/** The measurement the decision was taken against; `null` when the record carries none. */
|
|
1599
|
-
observationMetrics: Record<string, number | null> | null;
|
|
1600
|
-
/** Scope of the measured observation metrics. Absent for repository baselines. */
|
|
1601
|
-
observationScopeDigest?: string;
|
|
1602
|
-
reason: string;
|
|
1603
|
-
actor: { kind: ArchitectureActorKind; id: string };
|
|
1604
|
-
decidedAt: string;
|
|
1605
|
-
provenance: {
|
|
1606
|
-
headSha: string;
|
|
1607
|
-
assessmentDigest: string;
|
|
1608
|
-
baselineSnapshotDigest: string;
|
|
1609
|
-
};
|
|
1610
|
-
}
|
|
1611
|
-
|
|
1612
|
-
const REFACTOR_DECISION_KEYS = [
|
|
1613
|
-
"actor",
|
|
1614
|
-
"affectedNodeCount",
|
|
1615
|
-
"affectedNodeIds",
|
|
1616
|
-
"category",
|
|
1617
|
-
"decidedAt",
|
|
1618
|
-
"fingerprint",
|
|
1619
|
-
"fingerprintSchemaVersion",
|
|
1620
|
-
"kind",
|
|
1621
|
-
"namespace",
|
|
1622
|
-
"observationMetrics",
|
|
1623
|
-
"provenance",
|
|
1624
|
-
"reason",
|
|
1625
|
-
"recommendationId",
|
|
1626
|
-
"regressesFrom",
|
|
1627
|
-
"schemaVersion",
|
|
1628
|
-
"status",
|
|
1629
|
-
"subject"
|
|
1630
|
-
] as const;
|
|
1631
|
-
const REFACTOR_DECISION_OPTIONAL_KEYS = ["observationScopeDigest"] as const;
|
|
1632
|
-
|
|
1633
|
-
export function isRefactorDecisionStatus(status: RecommendationStatus | string): status is RefactorDecisionStatus {
|
|
1634
|
-
return (REFACTOR_DECISION_STATUSES as readonly string[]).includes(status);
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1637
|
-
/**
|
|
1638
|
-
* Who states a refactor recommendation's status (ADR-0046): its Git decision file
|
|
1639
|
-
* (`git-decision`), a machine status the ledger holds (`ledger`), or nobody — a human status the
|
|
1640
|
-
* ledger recorded whose Git file this checkout does not carry is audit only (`ledger-audit`): it
|
|
1641
|
-
* keeps its recorded status as history, is never reported as the current status of the subject,
|
|
1642
|
-
* and never appears in an open or status listing.
|
|
1643
|
-
*/
|
|
1644
|
-
export type RefactorStatusAuthority = "git-decision" | "ledger" | "ledger-audit";
|
|
1645
|
-
|
|
1646
|
-
/** The one status rule every reader shares. */
|
|
1647
|
-
export function refactorRecommendationStatusView(
|
|
1648
|
-
ledgerStatus: RecommendationStatus,
|
|
1649
|
-
decided: RefactorDecisionStatus | undefined
|
|
1650
|
-
): { status: RecommendationStatus; authority: RefactorStatusAuthority } {
|
|
1651
|
-
if (decided !== undefined) return { status: decided, authority: "git-decision" };
|
|
1652
|
-
return { status: ledgerStatus, authority: isRefactorDecisionStatus(ledgerStatus) ? "ledger-audit" : "ledger" };
|
|
1653
|
-
}
|
|
1654
|
-
|
|
1655
|
-
/** The repository path of the decision file for one recommendation id. */
|
|
1656
|
-
export function refactorDecisionPath(recommendationId: string): string {
|
|
1657
|
-
return `${REFACTOR_DECISION_DIRECTORY}/${recommendationId}.json`;
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
/**
|
|
1661
|
-
* The one serialization the daemon writes: two-space JSON, LF line endings, keys in declaration
|
|
1662
|
-
* order at every level (`observationMetrics` keys sorted), final newline. It does not depend on the
|
|
1663
|
-
* key order of the value it is given, so a parsed file serializes back to its own bytes only when
|
|
1664
|
-
* it is already canonical.
|
|
1665
|
-
*/
|
|
1666
|
-
export function serializeRefactorDecision(decision: RefactorDecisionV1): string {
|
|
1667
|
-
const canonical: RefactorDecisionV1 = {
|
|
1668
|
-
schemaVersion: decision.schemaVersion,
|
|
1669
|
-
namespace: decision.namespace,
|
|
1670
|
-
recommendationId: decision.recommendationId,
|
|
1671
|
-
fingerprint: decision.fingerprint,
|
|
1672
|
-
fingerprintSchemaVersion: decision.fingerprintSchemaVersion,
|
|
1673
|
-
category: decision.category,
|
|
1674
|
-
kind: decision.kind,
|
|
1675
|
-
subject: {
|
|
1676
|
-
selectorKind: decision.subject.selectorKind,
|
|
1677
|
-
stableKey: decision.subject.stableKey,
|
|
1678
|
-
subjectSelectorId: decision.subject.subjectSelectorId
|
|
1679
|
-
},
|
|
1680
|
-
affectedNodeIds: decision.affectedNodeIds,
|
|
1681
|
-
affectedNodeCount: decision.affectedNodeCount,
|
|
1682
|
-
regressesFrom: decision.regressesFrom,
|
|
1683
|
-
status: decision.status,
|
|
1684
|
-
observationMetrics: decision.observationMetrics === null
|
|
1685
|
-
? null
|
|
1686
|
-
: Object.fromEntries(Object.entries(decision.observationMetrics).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))),
|
|
1687
|
-
...(decision.observationScopeDigest === undefined ? {} : { observationScopeDigest: decision.observationScopeDigest }),
|
|
1688
|
-
reason: decision.reason,
|
|
1689
|
-
actor: { kind: decision.actor.kind, id: decision.actor.id },
|
|
1690
|
-
decidedAt: decision.decidedAt,
|
|
1691
|
-
provenance: {
|
|
1692
|
-
headSha: decision.provenance.headSha,
|
|
1693
|
-
assessmentDigest: decision.provenance.assessmentDigest,
|
|
1694
|
-
baselineSnapshotDigest: decision.provenance.baselineSnapshotDigest
|
|
1695
|
-
}
|
|
1696
|
-
};
|
|
1697
|
-
return `${JSON.stringify(canonical, null, 2)}\n`;
|
|
1698
|
-
}
|
|
1699
|
-
|
|
1700
|
-
/**
|
|
1701
|
-
* Validates a decision value: closed key sets at every level, the frozen vocabularies, bounded
|
|
1702
|
-
* one-line strings and sorted bounded id lists. Identity that needs the core hashers (the
|
|
1703
|
-
* recommendation id from fingerprint and `regressesFrom`, the namespace-scoped selector) is checked
|
|
1704
|
-
* by the reader that has them.
|
|
1705
|
-
*/
|
|
1706
|
-
export function refactorDecisionInvariantIssues(value: unknown, prefix = "refactorDecision"): string[] {
|
|
1707
|
-
if (!isPlainObject(value)) return [`${prefix} must be an object`];
|
|
1708
|
-
const issues: string[] = [];
|
|
1709
|
-
const allowedKeys: readonly string[] = [...REFACTOR_DECISION_KEYS, ...REFACTOR_DECISION_OPTIONAL_KEYS];
|
|
1710
|
-
const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
|
|
1711
|
-
if (unknownKeys.length > 0) issues.push(`${prefix} has unsupported key(s): ${unknownKeys.join(", ")}`);
|
|
1712
|
-
const missing = REFACTOR_DECISION_KEYS.filter((key) => !(key in value));
|
|
1713
|
-
if (missing.length > 0) issues.push(`${prefix} is missing key(s): ${missing.join(", ")}`);
|
|
1714
|
-
if (issues.length > 0) return issues;
|
|
1715
|
-
const decision = value as unknown as RefactorDecisionV1;
|
|
1716
|
-
if (decision.schemaVersion !== REFACTOR_DECISION_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion must be ${REFACTOR_DECISION_SCHEMA_VERSION}`);
|
|
1717
|
-
issues.push(...refactorNamespaceIssues(decision.namespace, `${prefix}.namespace`));
|
|
1718
|
-
if (typeof decision.recommendationId !== "string" || !REFACTOR_RECOMMENDATION_ID_PATTERN.test(decision.recommendationId)) {
|
|
1719
|
-
issues.push(`${prefix}.recommendationId must match ${REFACTOR_RECOMMENDATION_ID_PATTERN.source}`);
|
|
1720
|
-
}
|
|
1721
|
-
if (typeof decision.fingerprint !== "string") issues.push(`${prefix}.fingerprint must be a sha256:<64-hex> digest`);
|
|
1722
|
-
else issues.push(...digestIssues(`${prefix}.fingerprint`, decision.fingerprint));
|
|
1723
|
-
if (decision.fingerprintSchemaVersion !== REFACTOR_RECOMMENDATION_FINGERPRINT_SCHEMA_VERSION) {
|
|
1724
|
-
issues.push(`${prefix}.fingerprintSchemaVersion must be ${REFACTOR_RECOMMENDATION_FINGERPRINT_SCHEMA_VERSION}`);
|
|
1725
|
-
}
|
|
1726
|
-
if (decision.category !== "structural_observation" && decision.category !== "refactor_proposal") {
|
|
1727
|
-
issues.push(`${prefix}.category must be structural_observation or refactor_proposal`);
|
|
1728
|
-
} else if (decision.category === "structural_observation"
|
|
1729
|
-
? !(REFACTOR_OBSERVATION_KINDS as readonly unknown[]).includes(decision.kind)
|
|
1730
|
-
: decision.kind !== null) {
|
|
1731
|
-
issues.push(`${prefix}.kind must be an observation kind for structural_observation and null for refactor_proposal`);
|
|
1732
|
-
}
|
|
1733
|
-
issues.push(...decisionSubjectIssues(decision.subject, `${prefix}.subject`));
|
|
1734
|
-
if (!Array.isArray(decision.affectedNodeIds) || decision.affectedNodeIds.some((id) => typeof id !== "string" || id.trim() === "")) {
|
|
1735
|
-
issues.push(`${prefix}.affectedNodeIds must be an array of node ids`);
|
|
1736
|
-
} else {
|
|
1737
|
-
issues.push(...sortedUniqueIssues(`${prefix}.affectedNodeIds`, decision.affectedNodeIds));
|
|
1738
|
-
if (!Number.isInteger(decision.affectedNodeCount) || decision.affectedNodeCount < 0) {
|
|
1739
|
-
issues.push(`${prefix}.affectedNodeCount must be a non-negative integer`);
|
|
1740
|
-
} else if (decision.affectedNodeIds.length !== Math.min(decision.affectedNodeCount, REFACTOR_EVIDENCE_ID_LIST_LIMIT)) {
|
|
1741
|
-
issues.push(`${prefix}.affectedNodeIds must hold min(affectedNodeCount, ${REFACTOR_EVIDENCE_ID_LIST_LIMIT}) entries`);
|
|
1742
|
-
}
|
|
1743
|
-
}
|
|
1744
|
-
if (decision.regressesFrom !== null
|
|
1745
|
-
&& (typeof decision.regressesFrom !== "string" || !REFACTOR_RECOMMENDATION_ID_PATTERN.test(decision.regressesFrom))) {
|
|
1746
|
-
issues.push(`${prefix}.regressesFrom must be null or a recommendation id`);
|
|
1747
|
-
}
|
|
1748
|
-
if (!isRefactorDecisionStatus(String(decision.status))) {
|
|
1749
|
-
issues.push(`${prefix}.status must be one of ${REFACTOR_DECISION_STATUSES.join(", ")}`);
|
|
1750
|
-
}
|
|
1751
|
-
if (decision.observationMetrics !== null) {
|
|
1752
|
-
if (!isPlainObject(decision.observationMetrics)
|
|
1753
|
-
|| Object.entries(decision.observationMetrics).some(([key, metric]) =>
|
|
1754
|
-
key.trim() === "" || !(metric === null || (typeof metric === "number" && Number.isFinite(metric))))) {
|
|
1755
|
-
issues.push(`${prefix}.observationMetrics must be null or a map of finite numbers and nulls`);
|
|
1756
|
-
}
|
|
1757
|
-
}
|
|
1758
|
-
if (decision.observationScopeDigest !== undefined) {
|
|
1759
|
-
if (typeof decision.observationScopeDigest === "string") issues.push(...digestIssues(`${prefix}.observationScopeDigest`, decision.observationScopeDigest));
|
|
1760
|
-
else issues.push(`${prefix}.observationScopeDigest must be a digest`);
|
|
1761
|
-
if (decision.category !== "structural_observation" || decision.observationMetrics === null) {
|
|
1762
|
-
issues.push(`${prefix}.observationScopeDigest requires measured observation metrics`);
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
issues.push(...boundedLineIssues(`${prefix}.reason`, decision.reason, REFACTOR_DECISION_REASON_MAX_LENGTH));
|
|
1766
|
-
if (!isPlainObject(decision.actor) || Object.keys(decision.actor).sort().join(",") !== "id,kind") {
|
|
1767
|
-
issues.push(`${prefix}.actor must carry exactly kind and id`);
|
|
1768
|
-
} else {
|
|
1769
|
-
if (!REFACTOR_DECISION_ACTOR_KINDS.includes(decision.actor.kind)) issues.push(`${prefix}.actor.kind is unsupported`);
|
|
1770
|
-
issues.push(...boundedLineIssues(`${prefix}.actor.id`, decision.actor.id, REFACTOR_DECISION_ACTOR_ID_MAX_LENGTH));
|
|
1771
|
-
}
|
|
1772
|
-
if (typeof decision.decidedAt !== "string" || !ISO_TIMESTAMP_PATTERN.test(decision.decidedAt)) {
|
|
1773
|
-
issues.push(`${prefix}.decidedAt must be an ISO-8601 timestamp`);
|
|
1774
|
-
}
|
|
1775
|
-
if (!isPlainObject(decision.provenance)
|
|
1776
|
-
|| Object.keys(decision.provenance).sort().join(",") !== "assessmentDigest,baselineSnapshotDigest,headSha") {
|
|
1777
|
-
issues.push(`${prefix}.provenance must carry exactly headSha, assessmentDigest and baselineSnapshotDigest`);
|
|
1778
|
-
} else {
|
|
1779
|
-
if (typeof decision.provenance.headSha !== "string" || !GIT_HEAD_SHA_PATTERN.test(decision.provenance.headSha)) {
|
|
1780
|
-
issues.push(`${prefix}.provenance.headSha must be a 40-hex Git commit sha`);
|
|
1781
|
-
}
|
|
1782
|
-
for (const field of ["assessmentDigest", "baselineSnapshotDigest"] as const) {
|
|
1783
|
-
const digest = decision.provenance[field];
|
|
1784
|
-
issues.push(...(typeof digest === "string" ? digestIssues(`${prefix}.provenance.${field}`, digest) : [`${prefix}.provenance.${field} must be a digest`]));
|
|
1785
|
-
}
|
|
1786
|
-
}
|
|
1787
|
-
return issues;
|
|
1788
|
-
}
|
|
1789
|
-
|
|
1790
|
-
/**
|
|
1791
|
-
* Parses one decision file exactly as it sits in the checkout. A file with an unresolved merge
|
|
1792
|
-
* conflict, a body that is not one JSON object, a value that breaks the contract, a basename that
|
|
1793
|
-
* is not its own recommendation id, or bytes that are not the canonical serialization is refused
|
|
1794
|
-
* with every reason; nothing is repaired.
|
|
1795
|
-
*
|
|
1796
|
-
* The one tolerated difference is CRLF line endings: a checkout with `core.autocrlf` (Windows)
|
|
1797
|
-
* turns every LF of a committed canonical file into CRLF, so the body is compared after rewriting
|
|
1798
|
-
* only `\r\n` pairs to `\n` — the projection digest's rule. A lone CR, or any other byte that
|
|
1799
|
-
* differs from the canonical serialization, still fails closed.
|
|
1800
|
-
*/
|
|
1801
|
-
export function parseRefactorDecisionFile(path: string, body: string): RefactorDecisionV1 {
|
|
1802
|
-
const match = REFACTOR_DECISION_FILE_PATTERN.exec(path);
|
|
1803
|
-
if (!match) throw new Error(`refactor-decision-path-invalid: ${path} must be ${REFACTOR_DECISION_DIRECTORY}/recommendation.<16-hex>.json`);
|
|
1804
|
-
const normalized = body.replaceAll("\r\n", "\n");
|
|
1805
|
-
if (GIT_CONFLICT_MARKER_PATTERN.test(normalized)) throw new Error(`refactor-decision-conflicted: ${path} carries Git conflict markers; resolve the merge first`);
|
|
1806
|
-
let value: unknown;
|
|
1807
|
-
try {
|
|
1808
|
-
value = JSON.parse(normalized);
|
|
1809
|
-
} catch (error) {
|
|
1810
|
-
throw new Error(`refactor-decision-malformed: ${path} is not JSON (${error instanceof Error ? error.message : String(error)})`);
|
|
1811
|
-
}
|
|
1812
|
-
const issues = refactorDecisionInvariantIssues(value, path);
|
|
1813
|
-
if (issues.length > 0) throw new Error(`refactor-decision-invalid: ${issues.join("; ")}`);
|
|
1814
|
-
const decision = value as RefactorDecisionV1;
|
|
1815
|
-
if (decision.recommendationId !== match[1]) {
|
|
1816
|
-
throw new Error(`refactor-decision-invalid: ${path} must be named after its recommendationId ${decision.recommendationId}`);
|
|
1817
|
-
}
|
|
1818
|
-
if (serializeRefactorDecision(decision) !== normalized) {
|
|
1819
|
-
throw new Error(`refactor-decision-noncanonical: ${path} is not the canonical serialization the daemon writes; decision files are written only by archctx recommendations <verb>`);
|
|
1820
|
-
}
|
|
1821
|
-
return decision;
|
|
1822
|
-
}
|
|
1823
|
-
|
|
1824
|
-
function decisionSubjectIssues(subject: unknown, label: string): string[] {
|
|
1825
|
-
if (!isPlainObject(subject) || Object.keys(subject).sort().join(",") !== "selectorKind,stableKey,subjectSelectorId") {
|
|
1826
|
-
return [`${label} must carry exactly selectorKind, stableKey and subjectSelectorId`];
|
|
1827
|
-
}
|
|
1828
|
-
const issues: string[] = [];
|
|
1829
|
-
if (!REFACTOR_DECISION_SELECTOR_KINDS.includes(subject.selectorKind as ArchitectureSubjectSelectorKind)) {
|
|
1830
|
-
issues.push(`${label}.selectorKind must be node or repository`);
|
|
1831
|
-
}
|
|
1832
|
-
issues.push(...boundedLineIssues(`${label}.stableKey`, subject.stableKey, REFACTOR_DECISION_STABLE_KEY_MAX_LENGTH));
|
|
1833
|
-
if (typeof subject.subjectSelectorId !== "string" || !/^subject\.(node|repository)\.[a-f0-9]{16}$/.test(subject.subjectSelectorId)) {
|
|
1834
|
-
issues.push(`${label}.subjectSelectorId must be a refactor subject selector id`);
|
|
1835
|
-
}
|
|
1836
|
-
return issues;
|
|
1837
|
-
}
|
|
1838
|
-
|
|
1839
|
-
function boundedLineIssues(label: string, value: unknown, maxLength: number): string[] {
|
|
1840
|
-
if (typeof value !== "string" || value.trim() === "" || value !== value.trim()) {
|
|
1841
|
-
return [`${label} must be a non-empty string without leading or trailing whitespace`];
|
|
1842
|
-
}
|
|
1843
|
-
if (value.length > maxLength) return [`${label} must be at most ${maxLength} characters`];
|
|
1844
|
-
return /[\u0000-\u001f\u007f]/.test(value) ? [`${label} must be one line without control characters`] : [];
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
1848
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1849
|
-
}
|
|
1
|
+
export * from "./refactor-constants";
|
|
2
|
+
export * from "./refactor-types";
|
|
3
|
+
export * from "./refactor-evidence-types";
|
|
4
|
+
export * from "./refactor-snapshot-validators";
|
|
5
|
+
export * from "./refactor-observation-validators";
|
|
6
|
+
export * from "./refactor-resolution-validators";
|
|
7
|
+
export * from "./refactor-decision-validators";
|