@under18dev/veritas-improvement 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +12 -2
- package/dist/apply.d.ts +29 -0
- package/dist/apply.d.ts.map +1 -0
- package/dist/apply.js +403 -0
- package/dist/apply.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/oracle.d.ts +33 -0
- package/dist/oracle.d.ts.map +1 -0
- package/dist/oracle.js +130 -0
- package/dist/oracle.js.map +1 -0
- package/dist/plan.d.ts +26 -0
- package/dist/plan.d.ts.map +1 -0
- package/dist/plan.js +550 -0
- package/dist/plan.js.map +1 -0
- package/dist/render.d.ts +10 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +52 -0
- package/dist/render.js.map +1 -0
- package/dist/schema.d.ts +331 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +115 -0
- package/dist/schema.js.map +1 -0
- package/dist/store.d.ts +27 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +79 -0
- package/dist/store.js.map +1 -0
- package/dist/validate.d.ts +11 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/validate.js +83 -0
- package/dist/validate.js.map +1 -0
- package/dist/vitest.d.ts +19 -0
- package/dist/vitest.d.ts.map +1 -0
- package/dist/vitest.js +77 -0
- package/dist/vitest.js.map +1 -0
- package/dist/workspace.d.ts +27 -0
- package/dist/workspace.d.ts.map +1 -0
- package/dist/workspace.js +166 -0
- package/dist/workspace.js.map +1 -0
- package/package.json +29 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @under18dev/veritas-improvement
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Plans test-only improvements and applies them after measuring them in an isolated workspace
|
|
4
|
+
|
|
5
|
+
Part of [Veritas](https://github.com/under18dev/veritas), specification-aware test verification for TypeScript/JavaScript projects. Most users install the main package, which provides the `veritas` and `veritas-mcp` commands and the Node API:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -D @under18dev/veritas
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
This package is an internal building block of that package; its API may change between minor versions. Source: [`packages/improvement`](https://github.com/under18dev/veritas/tree/main/packages/improvement).
|
|
12
|
+
|
|
13
|
+
Licensed under Apache-2.0.
|
package/dist/apply.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { PatchAttempt } from '@under18dev/veritas-core';
|
|
2
|
+
export interface ApplyOptions {
|
|
3
|
+
root: string;
|
|
4
|
+
planId: string;
|
|
5
|
+
approvalToken: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
allowCodeConfig?: boolean;
|
|
8
|
+
/** Environment used for the CI check (defaults to `process.env`). */
|
|
9
|
+
env?: NodeJS.ProcessEnv;
|
|
10
|
+
/**
|
|
11
|
+
* Test hook, not exposed by the CLI: runs after the patch is written into the isolated workspace and before
|
|
12
|
+
* the patched tests run. It can only affect the workspace; the real repository only ever receives the
|
|
13
|
+
* approved plan content.
|
|
14
|
+
*/
|
|
15
|
+
afterPatchInWorkspace?: (workspace: string) => void | Promise<void>;
|
|
16
|
+
/** Who approves (recorded); defaults to VERITAS_ACTOR, then the git user name. */
|
|
17
|
+
actor?: string;
|
|
18
|
+
/** Entry point recorded with the approval (default `api`). */
|
|
19
|
+
via?: 'cli' | 'mcp' | 'api';
|
|
20
|
+
}
|
|
21
|
+
/** `CI` set to anything but an explicit false value means a CI environment. */
|
|
22
|
+
export declare function isCi(env: NodeJS.ProcessEnv): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Apply an approved plan: measure it in an isolated copy (baseline tests + mutation, patched tests + mutation)
|
|
25
|
+
* and copy the new test files into the repository only when the killed-mutant count increases and no
|
|
26
|
+
* previously passing test fails. Any failure leaves the repository unchanged.
|
|
27
|
+
*/
|
|
28
|
+
export declare function applyImprovement(options: ApplyOptions): Promise<PatchAttempt>;
|
|
29
|
+
//# sourceMappingURL=apply.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../src/apply.ts"],"names":[],"mappings":"AAGA,OAAO,EAML,YAAY,EAQb,MAAM,0BAA0B,CAAC;AAsBlC,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qEAAqE;IACrE,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,kFAAkF;IAClF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8DAA8D;IAC9D,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;CAC7B;AAKD,+EAA+E;AAC/E,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAIpD;AAqJD;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAqWnF"}
|
package/dist/apply.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { gitCommit, gitOutput, loadConfig, PatchAttempt, redact, sha256, stableId, VeritasError, } from '@under18dev/veritas-core';
|
|
5
|
+
import { readArtifact, recordedRunOptions, runVeritas } from '@under18dev/veritas-engine';
|
|
6
|
+
import { runMutation } from '@under18dev/veritas-mutation-adapter';
|
|
7
|
+
import { applyApprovals, loadApprovals } from '@under18dev/veritas-property-engine';
|
|
8
|
+
import { expectedFromSpec } from './oracle.js';
|
|
9
|
+
import { renderTestFile } from './render.js';
|
|
10
|
+
import { ImprovementApproval } from './schema.js';
|
|
11
|
+
import { approvalTokenFor, assertPlanId, attemptCount, readPlan, writePlanArtifact } from './store.js';
|
|
12
|
+
import { validatePatch } from './validate.js';
|
|
13
|
+
import { runVitest } from './vitest.js';
|
|
14
|
+
import { createWorkspace, diffSnapshots, projectHash, removeWorkspace, snapshotTree, treeHash, undoWrites, writeNewFiles, } from './workspace.js';
|
|
15
|
+
/** Hard cap on apply attempts per plan, matching the configuration limit. */
|
|
16
|
+
const MAX_ITERATIONS = 20;
|
|
17
|
+
/** `CI` set to anything but an explicit false value means a CI environment. */
|
|
18
|
+
export function isCi(env) {
|
|
19
|
+
const v = env.CI;
|
|
20
|
+
return v !== undefined && v !== '' && !/^(false|0)$/i.test(v);
|
|
21
|
+
}
|
|
22
|
+
function sameToken(a, b) {
|
|
23
|
+
const x = Buffer.from(a);
|
|
24
|
+
const y = Buffer.from(b);
|
|
25
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
26
|
+
}
|
|
27
|
+
/** Problems that make an approved plan unsafe even with a valid token. */
|
|
28
|
+
function planProblems(root, doc, config) {
|
|
29
|
+
const problems = validatePatch(root, doc.files, {
|
|
30
|
+
testInclude: config.analysis.testInclude,
|
|
31
|
+
maxPatchFiles: Math.min(doc.budget.maxPatchFiles, config.improvement.maxPatchFiles),
|
|
32
|
+
});
|
|
33
|
+
if (doc.plan?.touchesProductionCode !== false)
|
|
34
|
+
problems.push('the plan is marked as touching production code');
|
|
35
|
+
// Every expected value must still be the one the specification model documents.
|
|
36
|
+
let properties;
|
|
37
|
+
try {
|
|
38
|
+
// Apply the approval ledger as it is now: a property rejected after planning invalidates the plan.
|
|
39
|
+
const recorded = readArtifact(root, doc.runId, 'properties').data.properties;
|
|
40
|
+
properties = new Map(applyApprovals(recorded, loadApprovals(root)).properties.map((p) => [p.id, p]));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
return [...problems, `cannot re-read the specification of run ${doc.runId}: ${error.message}`];
|
|
44
|
+
}
|
|
45
|
+
for (const t of doc.tests) {
|
|
46
|
+
const p = properties.get(t.propertyId);
|
|
47
|
+
if (!p?.ir) {
|
|
48
|
+
problems.push(`test ${t.id}: property ${t.propertyId} has no formal model in run ${doc.runId}`);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (p.status === 'conflicted' || p.status === 'rejected' || p.status === 'superseded') {
|
|
52
|
+
problems.push(`test ${t.id}: property ${t.propertyId} is ${p.status}`);
|
|
53
|
+
}
|
|
54
|
+
else if (p.status !== 'accepted' && !doc.includeProposed) {
|
|
55
|
+
problems.push(`test ${t.id}: property ${t.propertyId} is ${p.status}, not accepted`);
|
|
56
|
+
}
|
|
57
|
+
const assumedNegative = p.assumptions.some((a) => /^assumed:/i.test(a));
|
|
58
|
+
const e = expectedFromSpec(p.ir, t.input, {
|
|
59
|
+
exclude: (c) => assumedNegative && c.guard?.kind === 'unary' && c.guard.op === 'not',
|
|
60
|
+
});
|
|
61
|
+
if (e.status !== 'expected' || e.value !== t.expected) {
|
|
62
|
+
problems.push(`test ${t.id}: expected value ${String(t.expected)} is not what the specification documents (${e.status === 'expected' ? String(e.value) : e.reason})`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// File contents must be exactly the rendering of the planned tests: no hand-edited assertions.
|
|
66
|
+
for (const f of doc.files) {
|
|
67
|
+
const propertyId = /veritas-(.+)\.test\.[jt]s$/.exec(f.path)?.[1];
|
|
68
|
+
const tests = doc.tests.filter((t) => t.propertyId === propertyId);
|
|
69
|
+
if (!propertyId || tests.length === 0 || renderTestFile(f.path, propertyId, tests) !== f.content) {
|
|
70
|
+
problems.push(`${f.path}: content differs from the rendering of the planned tests`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return problems;
|
|
74
|
+
}
|
|
75
|
+
function snapshot(tests, mutation, claimStatuses) {
|
|
76
|
+
return {
|
|
77
|
+
testsPassed: tests.passed,
|
|
78
|
+
testsFailed: tests.failed,
|
|
79
|
+
mutantsKilled: mutation.counts.killed ?? 0,
|
|
80
|
+
mutantsSurvived: mutation.counts.survived ?? 0,
|
|
81
|
+
claimStatuses,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** Formal and property-based results of the run the plan was made from: the state before the patch. */
|
|
85
|
+
/**
|
|
86
|
+
* Re-evaluate the formal and property-based results on the patched workspace: prove, plus the mutate and pbt
|
|
87
|
+
* stages if the plan's run had them, with that run's options (see below), offline. Claims that depend on test
|
|
88
|
+
* inputs (distinguishability) see the new tests. The run is written inside the workspace, never the repository.
|
|
89
|
+
*/
|
|
90
|
+
async function reassess(workspace, root, runId, options) {
|
|
91
|
+
mkdirSync(path.join(workspace, '.veritas'), { recursive: true });
|
|
92
|
+
for (const file of ['config.json', 'approvals.json']) {
|
|
93
|
+
const from = path.join(root, '.veritas', file);
|
|
94
|
+
if (existsSync(from))
|
|
95
|
+
copyFileSync(from, path.join(workspace, '.veritas', file));
|
|
96
|
+
}
|
|
97
|
+
const original = readArtifact(root, runId, 'run').data;
|
|
98
|
+
// Mutant relations (equivalence, distinguishability, detection) need the mutate stage as well.
|
|
99
|
+
const had = new Set(original.stages.map((s) => s.stage));
|
|
100
|
+
const optional = ['mutate', 'pbt'];
|
|
101
|
+
const stages = [
|
|
102
|
+
'index',
|
|
103
|
+
'discover',
|
|
104
|
+
'spec',
|
|
105
|
+
'map',
|
|
106
|
+
...optional.filter((stage) => had.has(stage)),
|
|
107
|
+
'prove',
|
|
108
|
+
];
|
|
109
|
+
// Everything the run was made with, except the mutation input: like the before/after measurement, the copy
|
|
110
|
+
// always runs mutator on all mutants, because an imported report or a `--since` selection describes the code
|
|
111
|
+
// before the patch.
|
|
112
|
+
const { mutationReport: _report, since: _since, ...recorded } = recordedRunOptions(original);
|
|
113
|
+
const summary = await runVeritas({
|
|
114
|
+
...recorded,
|
|
115
|
+
root: workspace,
|
|
116
|
+
command: 'improve',
|
|
117
|
+
stages,
|
|
118
|
+
offline: true,
|
|
119
|
+
allowCodeConfig: options.allowCodeConfig ?? false,
|
|
120
|
+
// The workspace has no .git: read the revision from the repository so ids and approvals match.
|
|
121
|
+
gitRoot: root,
|
|
122
|
+
signal: options.signal,
|
|
123
|
+
});
|
|
124
|
+
const failed = summary.run.stages
|
|
125
|
+
.filter((s) => s.status === 'error' || s.status === 'failed' || s.status === 'cancelled')
|
|
126
|
+
.map((s) => `${s.stage}=${s.status}`);
|
|
127
|
+
return { runId: summary.runId, statuses: recordedClaimStatuses(workspace, summary.runId), failed };
|
|
128
|
+
}
|
|
129
|
+
function recordedClaimStatuses(root, runId) {
|
|
130
|
+
const out = {};
|
|
131
|
+
try {
|
|
132
|
+
for (const c of readArtifact(root, runId, 'claims').data)
|
|
133
|
+
out[c.id] = c.status;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* the run had no prove stage */
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
for (const r of readArtifact(root, runId, 'pbt').data)
|
|
140
|
+
out[r.id] = r.status;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* the run had no property-based tests */
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Apply an approved plan: measure it in an isolated copy (baseline tests + mutation, patched tests + mutation)
|
|
149
|
+
* and copy the new test files into the repository only when the killed-mutant count increases and no
|
|
150
|
+
* previously passing test fails. Any failure leaves the repository unchanged.
|
|
151
|
+
*/
|
|
152
|
+
export async function applyImprovement(options) {
|
|
153
|
+
const { root, planId } = options;
|
|
154
|
+
assertPlanId(planId);
|
|
155
|
+
if (isCi(options.env ?? process.env)) {
|
|
156
|
+
throw new VeritasError('user', 'IMPROVE_APPLY_IN_CI', 'applying an improvement is refused in CI (improvement.autoApply is always false)', 'run `veritas improve --apply` locally after reviewing the plan');
|
|
157
|
+
}
|
|
158
|
+
if (!options.approvalToken) {
|
|
159
|
+
throw new VeritasError('user', 'APPROVAL_REQUIRED', 'an approval token is required to apply a plan', 'pass --approve <token> as printed by `veritas improve --dry-run`');
|
|
160
|
+
}
|
|
161
|
+
const doc = readPlan(root, planId);
|
|
162
|
+
if (!sameToken(options.approvalToken, approvalTokenFor(doc))) {
|
|
163
|
+
throw new VeritasError('user', 'APPROVAL_MISMATCH', `the approval token does not match plan ${planId} (the plan changed or the token is wrong)`, 'review the plan again with `veritas improve --dry-run` and use the token it prints');
|
|
164
|
+
}
|
|
165
|
+
if (doc.outcome !== 'planned' || !doc.plan) {
|
|
166
|
+
throw new VeritasError('user', 'PLAN_NOT_APPLICABLE', `plan ${planId} has outcome ${doc.outcome}; there is nothing to apply`);
|
|
167
|
+
}
|
|
168
|
+
const loaded = await loadConfig(root, { allowCodeConfig: options.allowCodeConfig ?? false });
|
|
169
|
+
if (loaded.hash !== doc.configHash || projectHash(root) !== doc.projectHash) {
|
|
170
|
+
throw new VeritasError('user', 'PLAN_STALE', `plan ${planId} was made for a different version of the project or configuration`, 'run `veritas run` and `veritas improve --dry-run` again');
|
|
171
|
+
}
|
|
172
|
+
const config = loaded.config;
|
|
173
|
+
const token = approvalTokenFor(doc);
|
|
174
|
+
const approvalId = stableId('AP', { planId, token });
|
|
175
|
+
const context = {
|
|
176
|
+
runId: doc.runId,
|
|
177
|
+
configHash: loaded.hash,
|
|
178
|
+
sourceHash: doc.runSourceHash,
|
|
179
|
+
gitCommit: gitCommit(root),
|
|
180
|
+
};
|
|
181
|
+
// The approval is recorded before anything runs: who approved this exact content, when and how. Writing
|
|
182
|
+
// approval-<n>.json exclusively claims attempt number n, so concurrent applies never share or overwrite one.
|
|
183
|
+
const env = options.env ?? process.env;
|
|
184
|
+
const { actor, actorSource } = options.actor?.trim()
|
|
185
|
+
? {
|
|
186
|
+
actor: options.actor.trim(),
|
|
187
|
+
actorSource: options.via === 'mcp' ? 'claimed_by_client' : 'option',
|
|
188
|
+
}
|
|
189
|
+
: env.VERITAS_ACTOR?.trim()
|
|
190
|
+
? { actor: env.VERITAS_ACTOR.trim(), actorSource: 'env' }
|
|
191
|
+
: { actor: gitOutput(root, ['config', 'user.name'])?.trim() || 'unknown', actorSource: 'git' };
|
|
192
|
+
let n = attemptCount(root, planId) + 1;
|
|
193
|
+
for (;;) {
|
|
194
|
+
try {
|
|
195
|
+
writePlanArtifact(root, planId, `approval-${n}.json`, ImprovementApproval, {
|
|
196
|
+
approvalId,
|
|
197
|
+
planId,
|
|
198
|
+
tokenSha256: sha256(options.approvalToken),
|
|
199
|
+
actor,
|
|
200
|
+
actorSource,
|
|
201
|
+
approvedAt: new Date().toISOString(),
|
|
202
|
+
via: options.via ?? 'api',
|
|
203
|
+
}, context, { exclusive: true });
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
if (error.code !== 'EEXIST')
|
|
208
|
+
throw error;
|
|
209
|
+
n++;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const base = {
|
|
213
|
+
id: stableId('PA', { planId, n }),
|
|
214
|
+
planId,
|
|
215
|
+
approvalId,
|
|
216
|
+
patch: doc.plan.patchPreview,
|
|
217
|
+
...(doc.implementationFixProposals[0]
|
|
218
|
+
? { implementationFixProposalId: doc.implementationFixProposals[0].id }
|
|
219
|
+
: {}),
|
|
220
|
+
};
|
|
221
|
+
const persist = (attempt) => {
|
|
222
|
+
writePlanArtifact(root, planId, `attempt-${n}.json`, PatchAttempt, attempt, {
|
|
223
|
+
runId: doc.runId,
|
|
224
|
+
configHash: loaded.hash,
|
|
225
|
+
sourceHash: doc.runSourceHash,
|
|
226
|
+
gitCommit: gitCommit(root),
|
|
227
|
+
});
|
|
228
|
+
return attempt;
|
|
229
|
+
};
|
|
230
|
+
const end = (outcome, reasons, fields) => persist({
|
|
231
|
+
...base,
|
|
232
|
+
workspace: fields.workspace ?? '',
|
|
233
|
+
before: fields.before ?? null,
|
|
234
|
+
after: fields.after ?? null,
|
|
235
|
+
rolledBack: fields.rolledBack,
|
|
236
|
+
outcome,
|
|
237
|
+
reasons: reasons.map((r) => redact(r)),
|
|
238
|
+
});
|
|
239
|
+
const maxIterations = Math.min(doc.budget.maxIterations, MAX_ITERATIONS);
|
|
240
|
+
if (n > maxIterations) {
|
|
241
|
+
return end('blocked', [`iteration budget exhausted: ${n - 1} of ${maxIterations} attempt(s) used`], {
|
|
242
|
+
rolledBack: false,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const problems = planProblems(root, doc, config);
|
|
246
|
+
if (problems.length > 0) {
|
|
247
|
+
return end('blocked', ['the plan fails the safety checks; nothing was written', ...problems], {
|
|
248
|
+
rolledBack: false,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
const deadline = Date.now() + doc.budget.timeBudgetMs;
|
|
252
|
+
const remaining = () => Math.max(1, deadline - Date.now());
|
|
253
|
+
const workspace = createWorkspace(root);
|
|
254
|
+
let written = null;
|
|
255
|
+
try {
|
|
256
|
+
const measureTests = async (label) => {
|
|
257
|
+
let run = { status: 'error', detail: 'not run' };
|
|
258
|
+
for (let i = 0; i <= doc.budget.maxTestRetries; i++) {
|
|
259
|
+
run = await runVitest(workspace, {
|
|
260
|
+
timeoutMs: remaining(),
|
|
261
|
+
label: `${label}-${i}`,
|
|
262
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
263
|
+
});
|
|
264
|
+
if (run.status === 'ok' || options.signal?.aborted || Date.now() >= deadline)
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
return run;
|
|
268
|
+
};
|
|
269
|
+
const measureMutation = (label) => runMutation({
|
|
270
|
+
root: workspace,
|
|
271
|
+
config: {
|
|
272
|
+
...config,
|
|
273
|
+
mutation: { ...config.mutation, timeoutMs: Math.min(config.mutation.timeoutMs, remaining()) },
|
|
274
|
+
},
|
|
275
|
+
reportDir: path.join(workspace, '.veritas', 'improve', `mutation-${label}`),
|
|
276
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
277
|
+
});
|
|
278
|
+
// Baseline.
|
|
279
|
+
const testsBefore = await measureTests('before');
|
|
280
|
+
if (testsBefore.status !== 'ok') {
|
|
281
|
+
return end('error', [`baseline test run failed: ${testsBefore.detail}`], {
|
|
282
|
+
workspace,
|
|
283
|
+
rolledBack: false,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
const mutationBefore = await measureMutation('before');
|
|
287
|
+
if (mutationBefore.status !== 'succeeded') {
|
|
288
|
+
return end(mutationBefore.status === 'failed' ? 'no_safe_improvement' : 'error', [`baseline mutation run is ${mutationBefore.status}: ${mutationBefore.detail ?? ''}`], { workspace, rolledBack: false });
|
|
289
|
+
}
|
|
290
|
+
const before = snapshot(testsBefore, mutationBefore, recordedClaimStatuses(root, doc.runId));
|
|
291
|
+
// Patched.
|
|
292
|
+
writeNewFiles(workspace, doc.files);
|
|
293
|
+
await options.afterPatchInWorkspace?.(workspace);
|
|
294
|
+
const testsAfter = await measureTests('after');
|
|
295
|
+
if (testsAfter.status !== 'ok') {
|
|
296
|
+
return end('error', [`patched test run failed: ${testsAfter.detail}`, 'the patch was discarded'], {
|
|
297
|
+
workspace,
|
|
298
|
+
before,
|
|
299
|
+
rolledBack: true,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const newFiles = new Set(doc.files.map((f) => f.path));
|
|
303
|
+
const broken = [...testsBefore.tests].filter(([key, status]) => status === 'passed' && testsAfter.tests.get(key) !== 'passed');
|
|
304
|
+
const newTests = [...testsAfter.tests].filter(([key]) => newFiles.has(key.split('::')[0]));
|
|
305
|
+
const failingNew = newTests.filter(([, status]) => status !== 'passed');
|
|
306
|
+
if (broken.length > 0 || failingNew.length > 0 || newTests.length === 0) {
|
|
307
|
+
return end('no_safe_improvement', [
|
|
308
|
+
'the patched tests do not all pass in the isolated copy; the patch was discarded and the repository is unchanged',
|
|
309
|
+
...(newTests.length === 0 ? ['no added test was executed'] : []),
|
|
310
|
+
...broken.map(([key]) => `previously passing test no longer passes: ${key}`),
|
|
311
|
+
...testsAfter.failures.slice(0, 10),
|
|
312
|
+
], {
|
|
313
|
+
workspace,
|
|
314
|
+
before,
|
|
315
|
+
after: { ...before, testsPassed: testsAfter.passed, testsFailed: testsAfter.failed },
|
|
316
|
+
rolledBack: true,
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
const mutationAfter = await measureMutation('after');
|
|
320
|
+
if (mutationAfter.status !== 'succeeded') {
|
|
321
|
+
return end('error', [
|
|
322
|
+
`patched mutation run is ${mutationAfter.status}: ${mutationAfter.detail ?? ''}`,
|
|
323
|
+
'the patch was discarded',
|
|
324
|
+
], { workspace, before, rolledBack: true });
|
|
325
|
+
}
|
|
326
|
+
const reassessed = await reassess(workspace, root, doc.runId, options);
|
|
327
|
+
if (reassessed.failed.length > 0) {
|
|
328
|
+
return end('error', [
|
|
329
|
+
`formal and property-based re-evaluation failed (${reassessed.failed.join(', ')}, run ${reassessed.runId})`,
|
|
330
|
+
'the patch was discarded',
|
|
331
|
+
], { workspace, before, rolledBack: true });
|
|
332
|
+
}
|
|
333
|
+
const after = snapshot(testsAfter, mutationAfter, reassessed.statuses);
|
|
334
|
+
const killedBefore = new Set(mutationBefore.mutants.filter((m) => m.status === 'killed').map((m) => m.id));
|
|
335
|
+
const newlyKilled = mutationAfter.mutants.filter((m) => m.status === 'killed' && !killedBefore.has(m.id));
|
|
336
|
+
if (after.mutantsKilled <= before.mutantsKilled) {
|
|
337
|
+
return end('no_safe_improvement', [
|
|
338
|
+
`killed mutants did not increase (${before.mutantsKilled} -> ${after.mutantsKilled}); the patch was discarded`,
|
|
339
|
+
], { workspace, before, after, rolledBack: true });
|
|
340
|
+
}
|
|
341
|
+
// Copy exactly the approved files into the repository, then prove nothing else changed.
|
|
342
|
+
if (options.signal?.aborted) {
|
|
343
|
+
return end('error', ['cancelled before writing to the repository'], {
|
|
344
|
+
workspace,
|
|
345
|
+
before,
|
|
346
|
+
after,
|
|
347
|
+
rolledBack: true,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
const repoBefore = snapshotTree(root);
|
|
351
|
+
if (treeHash(repoBefore) !== doc.projectHash) {
|
|
352
|
+
return end('error', ['the repository changed while the plan was being measured; nothing was written'], {
|
|
353
|
+
workspace,
|
|
354
|
+
before,
|
|
355
|
+
after,
|
|
356
|
+
rolledBack: true,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
let record;
|
|
360
|
+
try {
|
|
361
|
+
record = writeNewFiles(root, doc.files);
|
|
362
|
+
written = record;
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
return end('error', [`could not write the new test files: ${error.message}`, 'partial writes were removed'], {
|
|
366
|
+
workspace,
|
|
367
|
+
before,
|
|
368
|
+
after,
|
|
369
|
+
rolledBack: true,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
const repoAfter = snapshotTree(root);
|
|
373
|
+
const changed = diffSnapshots(repoBefore, repoAfter);
|
|
374
|
+
const expected = new Map(doc.files.map((f) => [f.path, sha256(f.content)]));
|
|
375
|
+
const unexpected = changed.filter((p) => !expected.has(p) || repoAfter.get(p) !== expected.get(p));
|
|
376
|
+
if (unexpected.length > 0 || changed.length !== expected.size) {
|
|
377
|
+
const leftovers = undoWrites(record);
|
|
378
|
+
written = null;
|
|
379
|
+
return end('error', [
|
|
380
|
+
`unexpected repository changes after writing: ${unexpected.join(', ') || 'missing files'}; the written files were removed`,
|
|
381
|
+
...(leftovers.length ? [`could not remove: ${leftovers.join(', ')}`] : []),
|
|
382
|
+
], { workspace, before, after, rolledBack: true });
|
|
383
|
+
}
|
|
384
|
+
return end('improved', [
|
|
385
|
+
`killed mutants ${before.mutantsKilled} -> ${after.mutantsKilled}, survived ${before.mutantsSurvived} -> ${after.mutantsSurvived}`,
|
|
386
|
+
...(newlyKilled.length ? [`newly killed: ${newlyKilled.map((m) => m.id).join(', ')}`] : []),
|
|
387
|
+
`added: ${doc.files.map((f) => f.path).join(', ')}`,
|
|
388
|
+
`formal and property-based results re-evaluated in ${reassessed.runId} on the patched copy`,
|
|
389
|
+
], { workspace, before, after, rolledBack: false });
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
const leftovers = written ? undoWrites(written) : [];
|
|
393
|
+
return end('error', [
|
|
394
|
+
`apply failed: ${error.message}`,
|
|
395
|
+
written ? 'files written to the repository were removed' : 'the repository was not changed',
|
|
396
|
+
...(leftovers.length ? [`could not remove: ${leftovers.join(', ')}`] : []),
|
|
397
|
+
], { workspace, rolledBack: true });
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
removeWorkspace(workspace);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
//# sourceMappingURL=apply.js.map
|