@turri-dev/cli 0.4.3-next.620bae9 → 0.4.3-next.a60ada5
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/README.md +1 -0
- package/dist/background-skills.d.ts +4 -1
- package/dist/background-skills.js +9 -1
- package/dist/capture/agents.d.ts +361 -0
- package/dist/capture/agents.js +332 -0
- package/dist/capture/area.d.ts +58 -0
- package/dist/capture/area.js +197 -0
- package/dist/capture/assemble.d.ts +122 -0
- package/dist/capture/assemble.js +452 -0
- package/dist/capture/capture.d.ts +116 -0
- package/dist/capture/capture.js +1228 -0
- package/dist/capture/chat.d.ts +29 -0
- package/dist/capture/chat.js +94 -0
- package/dist/capture/checks.d.ts +142 -0
- package/dist/capture/checks.js +643 -0
- package/dist/capture/config.d.ts +13 -0
- package/dist/capture/config.js +60 -0
- package/dist/capture/interface.d.ts +71 -0
- package/dist/capture/interface.js +199 -0
- package/dist/capture/map.d.ts +56 -0
- package/dist/capture/map.js +530 -0
- package/dist/capture/progress.d.ts +108 -0
- package/dist/capture/progress.js +234 -0
- package/dist/capture/report.d.ts +75 -0
- package/dist/capture/report.js +267 -0
- package/dist/capture/scripts.d.ts +26 -0
- package/dist/capture/scripts.js +33 -0
- package/dist/capture/state.d.ts +296 -0
- package/dist/capture/state.js +43 -0
- package/dist/capture/trial.d.ts +34 -0
- package/dist/capture/trial.js +89 -0
- package/dist/capture-cli.d.ts +1 -0
- package/dist/capture-cli.js +77 -0
- package/dist/chat-tabs.d.ts +7 -1
- package/dist/chat-tabs.js +10 -6
- package/dist/chat-terminal.js +5 -2
- package/dist/chats.d.ts +11 -8
- package/dist/chats.js +34 -20
- package/dist/cli.js +32 -14
- package/dist/config-edit.js +1 -0
- package/dist/config.d.ts +15 -2
- package/dist/config.js +57 -3
- package/dist/extension.d.ts +1 -0
- package/dist/extension.js +188 -55
- package/dist/identity.js +2 -1
- package/dist/init-config.js +1 -0
- package/dist/loop-cli.js +5 -1
- package/dist/loop-tools.js +5 -1
- package/dist/new-project.d.ts +5 -0
- package/dist/new-project.js +11 -0
- package/dist/pi-launch.js +2 -0
- package/dist/pi-themes.d.ts +3 -0
- package/dist/pi-themes.js +21 -0
- package/dist/pi.js +2 -2
- package/dist/plain-code-blocks.d.ts +14 -0
- package/dist/plain-code-blocks.js +56 -0
- package/dist/pointer-hover.d.ts +1 -1
- package/dist/pointer-hover.js +4 -0
- package/dist/question-dialog.d.ts +5 -0
- package/dist/question-dialog.js +20 -1
- package/dist/regenerate/command-check.js +80 -11
- package/dist/regenerate/job-panel.d.ts +5 -107
- package/dist/regenerate/job-panel.js +4 -289
- package/dist/regenerate/loop.js +9 -1
- package/dist/regenerate/side-panel.d.ts +2 -0
- package/dist/regenerate/side-panel.js +32 -5
- package/dist/regenerate/spec-map-view.d.ts +2 -2
- package/dist/regenerate/test-scripts.d.ts +5 -0
- package/dist/regenerate/test-scripts.js +4 -0
- package/dist/reopen.d.ts +29 -0
- package/dist/reopen.js +47 -0
- package/dist/sentinel-chat.js +7 -2
- package/dist/sentinel.d.ts +1 -1
- package/dist/sentinel.js +3 -1
- package/dist/setup.js +9 -1
- package/dist/terminal-notifications.d.ts +31 -0
- package/dist/terminal-notifications.js +134 -0
- package/docs/README.md +2 -0
- package/docs/capture.md +191 -0
- package/docs/chats.md +3 -2
- package/docs/config.md +15 -3
- package/docs/development.md +4 -1
- package/docs/hosting.md +2 -2
- package/docs/launch.md +2 -2
- package/docs/regenerating.md +1 -1
- package/docs/sandbox.md +2 -2
- package/docs/sentinel.md +11 -11
- package/docs/theming.md +3 -3
- package/docs/using.md +7 -3
- package/genome/capture/capture.md +26 -0
- package/genome/capture/check-conventions.md +5 -0
- package/genome/capture/check-reference.md +11 -0
- package/genome/capture/concepts.md +3 -0
- package/genome/capture/divide.md +9 -0
- package/genome/capture/feature.md +45 -0
- package/genome/capture/interface.md +9 -0
- package/genome/capture/modules.md +23 -0
- package/genome/capture/outline.md +11 -0
- package/genome/capture/readability.md +12 -0
- package/genome/capture/reference.md +10 -0
- package/genome/capture/split.md +9 -0
- package/genome/capture/survey.md +37 -0
- package/genome/capture/trial.md +18 -0
- package/genome/capture/verify.md +7 -0
- package/genome/rules/turri-regeneration.md +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1228 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, relative, resolve } from "node:path";
|
|
3
|
+
import { CONFIG_FILE, modelSpec, projectModels, readProjectConfig, withConfigModule } from "../config.js";
|
|
4
|
+
import { slashed } from "../regenerate/paths.js";
|
|
5
|
+
import { findTestScripts, testingScriptSkill } from "../regenerate/test-scripts.js";
|
|
6
|
+
import { checkPlainFile } from "../plain/check.js";
|
|
7
|
+
import { conformanceOf, stdlibCatalogue, stdlibTemplates } from "../stdlib.js";
|
|
8
|
+
import { AREAS_TOOL, askAgent, watched, CONCEPTS_TOOL, CONVENTIONS_TOOL, CORRECTIONS_TOOL, definitionsOf, EDITS_TOOL, FEATURE_TOOL, FEATURES_TOOL, INTERFACE_TOOL, leftOutOf, MODULES_TOOL, OWNERS_TOOL, records, REFERENCE_CHECKED_TOOL, REFERENCE_TOOL, strings, SURVEY_TOOL, text, TRIAL_TOOL } from "./agents.js";
|
|
9
|
+
import { buildOrder, covers, entriesOf, filesOf, kebab, linesOf, renderArea, testEvidence } from "./area.js";
|
|
10
|
+
import { entriesIn, entryFile, entrySurface, interfaceConcept, renderReference, interfaceDefinition, interfaceGaps, interfaceIn, leftOutPaths, namedExactly, namedIn, optionsNotInReference, referenceOf, shownSurface } from "./interface.js";
|
|
11
|
+
import { assemble, featureKey, featurePaths, featuresOf, leavesOf, mergedInto, MODULE_SPECS, outlinedFeature, sharedName, writeCapture } from "./assemble.js";
|
|
12
|
+
import { conventionProblems, correctionProblems, divisionProblems, moduleProblems, referenceProblems, editProblems, featureProblems, gapProblems, outlineProblems, reconciledProblems, scenarioBudget, splitProblems, surveyProblems, trialProblems, unplaced } from "./checks.js";
|
|
13
|
+
import { buildMap, INTERFACE_KINDS } from "./map.js";
|
|
14
|
+
import { CaptureTracker } from "./progress.js";
|
|
15
|
+
import { configInUse, configInUseProblem, startingConfig } from "./config.js";
|
|
16
|
+
import { renderReport, summaryOf } from "./report.js";
|
|
17
|
+
import { writeTestingScript } from "./scripts.js";
|
|
18
|
+
import { captureDir, newState, readState, reportFile, saveState } from "./state.js";
|
|
19
|
+
import { copyOriginal, trialBatches, trialTestReqs } from "./trial.js";
|
|
20
|
+
/** A capture that cannot start, or cannot go on: said as it is, nothing written but what was before. */
|
|
21
|
+
export class CaptureError extends Error {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "CaptureError";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Lines above which an area is split rather than outlined: about what one agent can outline from a map and a look. */
|
|
28
|
+
export const LEAF_LINES = Number(process.env.TURRI_CAPTURE_LEAF_LINES ?? 6000);
|
|
29
|
+
/** Characters of the map an agent is shown: about six thousand tokens. */
|
|
30
|
+
export const MAP_BUDGET = 24_000;
|
|
31
|
+
/** How many agents work at once, unless told. */
|
|
32
|
+
export const DEFAULT_PARALLEL = 4;
|
|
33
|
+
/** How many concepts one reconciling agent is given, and how many functional specs one readability pass reads. */
|
|
34
|
+
const CONFLICTS_PER_AGENT = 20;
|
|
35
|
+
const SPECS_PER_PASS = 30;
|
|
36
|
+
/** The most surfaces of the interface one writer is given to capture: past this, another writer takes the rest. */
|
|
37
|
+
const SURFACES_PER_WRITER = 30;
|
|
38
|
+
/** The most surfaces of the interface a writer is shown, file by file. */
|
|
39
|
+
const INTERFACE_LISTED = 200;
|
|
40
|
+
/** The most lines of the files defining the interface one agent takes it from, and the most files. */
|
|
41
|
+
const REFERENCE_LINES = 4000;
|
|
42
|
+
const REFERENCE_FILES = 12;
|
|
43
|
+
/** Characters of a part's features the agent that gathers them into modules is shown: about thirty thousand tokens. */
|
|
44
|
+
const GATHERING_BUDGET = 120_000;
|
|
45
|
+
/** Tool calls an agent trying scenarios on the original makes before it is told to hand over: installing it, then a few a scenario. */
|
|
46
|
+
const TRIAL_CALLS = 100;
|
|
47
|
+
/** The least a turn of an agent trying scenarios may take: installing the original and running them takes a while. */
|
|
48
|
+
const TRIAL_TURN_MS = 30 * 60 * 1000;
|
|
49
|
+
/** The output folder's state as it stands: nothing there, a capture to go on with, or something capture must not touch. */
|
|
50
|
+
export function plainDirState(plainDir) {
|
|
51
|
+
if (!existsSync(plainDir))
|
|
52
|
+
return { kind: "empty" };
|
|
53
|
+
if (!statSync(plainDir).isDirectory())
|
|
54
|
+
return { kind: "taken", why: `${plainDir} is a file` };
|
|
55
|
+
const state = readState(plainDir);
|
|
56
|
+
if (state?.finished !== undefined)
|
|
57
|
+
return { kind: "finished" };
|
|
58
|
+
if (state !== undefined)
|
|
59
|
+
return { kind: "resume", state };
|
|
60
|
+
const entries = readdirSync(plainDir).filter((entry) => entry !== ".turri" && entry !== ".DS_Store");
|
|
61
|
+
return entries.length === 0 ? { kind: "empty" } : { kind: "taken", why: `${plainDir} holds ${entries.slice(0, 3).join(", ")}${entries.length > 3 ? ", ..." : ""} and no capture of turri's` };
|
|
62
|
+
}
|
|
63
|
+
/** Run a whole capture - or go on with one stopped part-way. */
|
|
64
|
+
export async function runCapture(options) {
|
|
65
|
+
const root = resolve(options.root);
|
|
66
|
+
if (!existsSync(root) || !statSync(root).isDirectory())
|
|
67
|
+
throw new CaptureError(`${root} is not a folder to capture.`);
|
|
68
|
+
const plainDir = resolve(options.plainDir ?? join(root, "plain"));
|
|
69
|
+
const found = plainDirState(plainDir);
|
|
70
|
+
if (found.kind === "finished") {
|
|
71
|
+
throw new CaptureError(`${plainDir} holds a finished capture already - its report is ${reportFile(plainDir)}. To capture again, move that folder out of the way.`);
|
|
72
|
+
}
|
|
73
|
+
if (found.kind === "taken")
|
|
74
|
+
throw new CaptureError(`Nothing captured: ${found.why}. Capture writes into a folder of its own - name another.`);
|
|
75
|
+
const source = options.configFrom !== undefined ? configInUse(options.configFrom) : undefined;
|
|
76
|
+
const unusable = found.kind === "empty" ? configInUseProblem(source) : undefined;
|
|
77
|
+
if (unusable !== undefined)
|
|
78
|
+
throw new CaptureError(unusable);
|
|
79
|
+
const tracker = new CaptureTracker(root, options.progress, options.watch);
|
|
80
|
+
const map = buildMap(root, { exclude: [plainDir] });
|
|
81
|
+
if (!map.files.some((file) => file.kind === "source"))
|
|
82
|
+
throw new CaptureError(`${root} holds no source code to capture.`);
|
|
83
|
+
const state = found.kind === "resume" ? found.state : newState(root);
|
|
84
|
+
if (found.kind === "resume")
|
|
85
|
+
tracker.said(`going on with the capture started ${state.started}`);
|
|
86
|
+
const save = () => {
|
|
87
|
+
saveState(plainDir, state);
|
|
88
|
+
tracker.counted(state);
|
|
89
|
+
};
|
|
90
|
+
save();
|
|
91
|
+
// The config in use, from the start - after the state, so a capture stopped here goes on: its agents run on its models,
|
|
92
|
+
// and the project it writes keeps them.
|
|
93
|
+
const given = { ...(options.harnessModel !== undefined ? { harnessModel: options.harnessModel } : {}), ...(options.codingModel !== undefined ? { codingModel: options.codingModel } : {}) };
|
|
94
|
+
if (found.kind === "empty")
|
|
95
|
+
writeFileSync(join(plainDir, CONFIG_FILE), startingConfig(source, given));
|
|
96
|
+
const inUse = projectModels(readProjectConfig(plainDir));
|
|
97
|
+
const model = options.model ?? modelSpec(inUse.harness);
|
|
98
|
+
const codingModel = options.codingModel ?? modelSpec(inUse.coding);
|
|
99
|
+
const run = new CaptureRun({ ...options, root, plainDir, ...(model !== undefined ? { model } : {}), ...(codingModel !== undefined ? { codingModel } : {}), given }, map, state, save, tracker);
|
|
100
|
+
tracker.stage("surveying");
|
|
101
|
+
await run.survey();
|
|
102
|
+
await run.checkConventions();
|
|
103
|
+
await run.extractInterface();
|
|
104
|
+
tracker.stage("outlining");
|
|
105
|
+
await Promise.all(state.survey.parts.map((part) => run.outlineArea(part.name)));
|
|
106
|
+
await run.divide();
|
|
107
|
+
tracker.stage("capturing");
|
|
108
|
+
await Promise.all(state.survey.parts.map((part) => run.captureFeatures(part.name)));
|
|
109
|
+
await run.fillInterface();
|
|
110
|
+
await run.gatherModules();
|
|
111
|
+
await run.reconcile();
|
|
112
|
+
await run.readability();
|
|
113
|
+
await run.verifyInterface();
|
|
114
|
+
await run.trialScenarios();
|
|
115
|
+
tracker.stage("writing");
|
|
116
|
+
run.write();
|
|
117
|
+
await run.scripts();
|
|
118
|
+
return run.finish();
|
|
119
|
+
}
|
|
120
|
+
/** The testing scripts a captured project gets: conformance tests are on in it, so both. */
|
|
121
|
+
const SCRIPT_KINDS = ["unit", "conformance"];
|
|
122
|
+
/** Runs no more than `limit` at once, the rest waiting their turn. */
|
|
123
|
+
function limiter(limit) {
|
|
124
|
+
let running = 0;
|
|
125
|
+
const waiting = [];
|
|
126
|
+
return async (work) => {
|
|
127
|
+
if (running >= limit)
|
|
128
|
+
await new Promise((go) => waiting.push(go));
|
|
129
|
+
running += 1;
|
|
130
|
+
try {
|
|
131
|
+
return await work();
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
running -= 1;
|
|
135
|
+
waiting.shift()?.();
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
class CaptureRun {
|
|
140
|
+
options;
|
|
141
|
+
map;
|
|
142
|
+
state;
|
|
143
|
+
save;
|
|
144
|
+
tracker;
|
|
145
|
+
progress;
|
|
146
|
+
limited;
|
|
147
|
+
leafLines;
|
|
148
|
+
budget;
|
|
149
|
+
constructor(options, map, state, save, tracker) {
|
|
150
|
+
this.options = options;
|
|
151
|
+
this.map = map;
|
|
152
|
+
this.state = state;
|
|
153
|
+
this.save = save;
|
|
154
|
+
this.tracker = tracker;
|
|
155
|
+
this.progress = (line) => tracker.said(line);
|
|
156
|
+
this.limited = limiter(Math.max(1, options.parallel ?? DEFAULT_PARALLEL));
|
|
157
|
+
this.leafLines = options.leafLines ?? LEAF_LINES;
|
|
158
|
+
this.budget = options.mapBudget ?? MAP_BUDGET;
|
|
159
|
+
}
|
|
160
|
+
stopIfAsked() {
|
|
161
|
+
if (this.options.signal?.aborted === true)
|
|
162
|
+
throw new CaptureError("The capture was stopped. Run it again to go on from where it was.");
|
|
163
|
+
}
|
|
164
|
+
agent(label, prompt, context, extra) {
|
|
165
|
+
return {
|
|
166
|
+
plainDir: this.options.plainDir,
|
|
167
|
+
root: this.options.root,
|
|
168
|
+
...(this.options.model !== undefined ? { model: this.options.model } : {}),
|
|
169
|
+
...(this.options.signal !== undefined ? { signal: this.options.signal } : {}),
|
|
170
|
+
label: `capture ${label}`,
|
|
171
|
+
watch: this.tracker.agent(label),
|
|
172
|
+
prompt,
|
|
173
|
+
context,
|
|
174
|
+
...extra,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
codebaseBlock() {
|
|
178
|
+
return `<codebase>\n${this.options.root}\n</codebase>`;
|
|
179
|
+
}
|
|
180
|
+
async survey() {
|
|
181
|
+
if (this.state.survey !== undefined)
|
|
182
|
+
return;
|
|
183
|
+
this.stopIfAsked();
|
|
184
|
+
this.progress("surveying the codebase");
|
|
185
|
+
const context = [
|
|
186
|
+
this.codebaseBlock(),
|
|
187
|
+
`<map>\n${renderArea(this.map, ["."], this.budget)}\n</map>`,
|
|
188
|
+
`<manifests>\n${this.manifests()}\n</manifests>`,
|
|
189
|
+
`<docs>\n${this.docs()}\n</docs>`,
|
|
190
|
+
`<standard library>\n${stdlibCatalogue()}\n</standard library>`,
|
|
191
|
+
].join("\n\n");
|
|
192
|
+
const { answer, problems } = await this.limited(() => askAgent(this.agent("survey", "survey", context, { reads: true, rules: true, calls: 45 }), { ...SURVEY_TOOL, convert: (params) => ({ parts: records(params.parts).map(partOf), leftOut: leftOutOf(params.left_out), assumptions: strings(params.assumptions) }) }, (survey) => surveyProblems(this.map, survey)));
|
|
193
|
+
if (answer === undefined)
|
|
194
|
+
throw new CaptureError(`The survey of the codebase did not hold, so nothing could be captured:\n- ${problems.join("\n- ")}`);
|
|
195
|
+
this.state.survey = answer;
|
|
196
|
+
for (const part of answer.parts)
|
|
197
|
+
this.state.areas[part.name] ??= { id: part.name, name: part.name, about: part.about, paths: part.paths, part: part.name };
|
|
198
|
+
this.save();
|
|
199
|
+
this.progress(`surveyed: ${answer.parts.map((part) => `${part.name}${part.stdlibStack !== undefined ? ` (${part.stdlibStack})` : ""}`).join(", ")}`);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Each part's conventions checked against the code before any writer is given them: every feature follows them, so
|
|
203
|
+
* one that is wrong is wrong everywhere. An agent reads the code each names and corrects what does not hold; a check
|
|
204
|
+
* that never holds leaves them as surveyed, and the report says so.
|
|
205
|
+
*/
|
|
206
|
+
async checkConventions() {
|
|
207
|
+
const pending = this.state.survey.parts.filter((part) => (part.conventions ?? []).length > 0 && this.state.conventionsChecked?.[part.name] === undefined);
|
|
208
|
+
if (pending.length === 0)
|
|
209
|
+
return;
|
|
210
|
+
this.tracker.stage("checking", pending.length);
|
|
211
|
+
await Promise.all(pending.map((part) => this.limited(async () => {
|
|
212
|
+
this.stopIfAsked();
|
|
213
|
+
this.progress(`checking the ${part.conventions.length} conventions of ${part.name} against the code`);
|
|
214
|
+
const known = new Set(part.definitions.map((definition) => definition.concept));
|
|
215
|
+
const context = [
|
|
216
|
+
this.codebaseBlock(),
|
|
217
|
+
`<part>\n${part.name} - ${part.about}\n</part>`,
|
|
218
|
+
`<concepts>\n${part.definitions.map((definition) => `- ${definition.text}`).join("\n") || "None."}\n</concepts>`,
|
|
219
|
+
`<conventions>\n${part.conventions.map((convention, at) => `${at + 1}. ${convention.text}\n decided in: ${convention.where.join(", ")}`).join("\n")}\n</conventions>`,
|
|
220
|
+
].join("\n\n");
|
|
221
|
+
const { answer, problems } = await askAgent(this.agent(`check ${part.name}`, "check-conventions", context, { reads: true, rules: false, calls: 30 }), { ...CONVENTIONS_TOOL, convert: (params) => ({ conventions: conventionsOf(params.conventions), changes: strings(params.changes) }) }, (answer) => [...(answer.conventions.length === 0 ? ["Give every convention as the code has it - those that hold too."] : []), ...conventionProblems(this.map, answer.conventions, known)]);
|
|
222
|
+
if (answer !== undefined)
|
|
223
|
+
part.conventions = answer.conventions;
|
|
224
|
+
(this.state.conventionsChecked ??= {})[part.name] = answer !== undefined ? { changes: answer.changes } : { changes: [], failed: `the check did not hold: ${problems.join(" ")}` };
|
|
225
|
+
this.save();
|
|
226
|
+
this.tracker.worked();
|
|
227
|
+
this.progress(answer === undefined
|
|
228
|
+
? `could not check the conventions of ${part.name} - kept as surveyed`
|
|
229
|
+
: answer.changes.length === 0
|
|
230
|
+
? `every convention of ${part.name} holds`
|
|
231
|
+
: `corrected the conventions of ${part.name}: ${answer.changes.length} change${answer.changes.length === 1 ? "" : "s"}`);
|
|
232
|
+
})));
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Each part's interface taken from the code as data, before any feature is outlined: the files where the map found
|
|
236
|
+
* it, so many lines an agent, each agent listing every command, argument, option, route and environment variable they
|
|
237
|
+
* define - every name, what it takes, its choices, its default and its help, word for word - with where; every literal
|
|
238
|
+
* checked against the code it cites, and every surface the map found listed or excluded with why (`referenceProblems`).
|
|
239
|
+
* A part whose interface was taken gets its interface concept, which links the reference every writer then works from.
|
|
240
|
+
*/
|
|
241
|
+
async extractInterface() {
|
|
242
|
+
const leftOut = this.state.survey.leftOut.map((item) => item.path);
|
|
243
|
+
const parts = this.state.survey.parts.filter((part) => !(this.state.interfaceTaken ?? []).includes(part.name));
|
|
244
|
+
const work = [];
|
|
245
|
+
for (const part of parts) {
|
|
246
|
+
const files = filesOf(this.map, part.paths).filter((file) => file.kind !== "test" && !leftOut.some((path) => covers(path, file.path)) && file.surfaces.some((surface) => INTERFACE_KINDS.has(surface.kind)));
|
|
247
|
+
const batches = [];
|
|
248
|
+
let batch = [];
|
|
249
|
+
let lines = 0;
|
|
250
|
+
for (const file of files) {
|
|
251
|
+
if (batch.length > 0 && (lines + file.lines > REFERENCE_LINES || batch.length >= REFERENCE_FILES)) {
|
|
252
|
+
batches.push(batch);
|
|
253
|
+
batch = [];
|
|
254
|
+
lines = 0;
|
|
255
|
+
}
|
|
256
|
+
batch.push(file.path);
|
|
257
|
+
lines += file.lines;
|
|
258
|
+
}
|
|
259
|
+
if (batch.length > 0)
|
|
260
|
+
batches.push(batch);
|
|
261
|
+
// The map found none: one agent looks for it, from the entry points.
|
|
262
|
+
if (batches.length === 0)
|
|
263
|
+
batches.push([]);
|
|
264
|
+
batches.forEach((files, at) => {
|
|
265
|
+
const key = files.join(", ") || "(the map found none)";
|
|
266
|
+
if (this.state.interfaces?.[part.name]?.[key] === undefined)
|
|
267
|
+
work.push({ part, key, files, label: `reference ${part.name}${batches.length > 1 ? ` ${at + 1}` : ""}` });
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
if (work.length > 0) {
|
|
271
|
+
this.tracker.stage("extracting", work.length);
|
|
272
|
+
this.progress(`taking the interface from the code: ${work.length === 1 ? "an agent" : `${work.length} agents`}`);
|
|
273
|
+
await Promise.all(work.map((item) => this.limited(async () => {
|
|
274
|
+
this.stopIfAsked();
|
|
275
|
+
const listed = item.files.map((path) => {
|
|
276
|
+
const file = this.map.files.find((candidate) => candidate.path === path);
|
|
277
|
+
const names = [...new Set(file.surfaces.filter((surface) => INTERFACE_KINDS.has(surface.kind)).map((surface) => `\`${surface.name}\``))];
|
|
278
|
+
return `- ${path} - ${file.lines} lines; the map found ${names.slice(0, 60).join(", ")}${names.length > 60 ? `, and ${names.length - 60} more` : ""}`;
|
|
279
|
+
});
|
|
280
|
+
const context = [
|
|
281
|
+
this.codebaseBlock(),
|
|
282
|
+
`<part>\n${item.part.name} - ${item.part.about}\n</part>`,
|
|
283
|
+
`<files>\n${listed.length > 0 ? listed.join("\n") : "The map found no interface in the part's files: find it - from its entry points, where its arguments, routes and variables are read."}\n</files>`,
|
|
284
|
+
`<map>\n${renderArea(this.map, item.part.paths, Math.floor(this.budget / 2))}\n</map>`,
|
|
285
|
+
].join("\n\n");
|
|
286
|
+
const { answer, problems } = await askAgent(this.agent(item.label, "reference", context, { reads: true, rules: false, calls: 60 }), { ...REFERENCE_TOOL, convert: referenceAnswerOf }, (answer) => referenceProblems(this.map, this.options.root, item.files, answer));
|
|
287
|
+
((this.state.interfaces ??= {})[item.part.name] ??= {})[item.key] = answer ?? { failed: `what its agent handed over did not hold: ${problems.join(" ")}` };
|
|
288
|
+
this.save();
|
|
289
|
+
this.tracker.worked();
|
|
290
|
+
this.progress(answer !== undefined ? `took ${answer.entries.length} piece${answer.entries.length === 1 ? "" : "s"} of ${item.part.name}'s interface from ${item.files.length === 1 ? item.files[0] : `${item.files.length} files`}` : `could not take ${item.part.name}'s interface from ${item.key}`);
|
|
291
|
+
})));
|
|
292
|
+
}
|
|
293
|
+
await this.checkReference(parts);
|
|
294
|
+
for (const part of parts) {
|
|
295
|
+
const concept = interfaceConcept(part.name);
|
|
296
|
+
if (referenceOf(this.state, part.name).entries.length > 0 && !part.definitions.some((definition) => definition.concept === concept))
|
|
297
|
+
part.definitions.push({ concept, text: interfaceDefinition(part.name) });
|
|
298
|
+
(this.state.interfaceTaken ??= []).push(part.name);
|
|
299
|
+
}
|
|
300
|
+
this.save();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Each part of the interface reference checked against the code by a fresh agent, as the conventions are: what the
|
|
304
|
+
* checks of the code cannot see - a help text cut to its first line, choices left out or worked out when it runs, an
|
|
305
|
+
* environment variable read through a constant - corrected or added, every entry again checked against the code it
|
|
306
|
+
* cites. A check that never holds leaves the reference as it was taken, and the report says so.
|
|
307
|
+
*/
|
|
308
|
+
async checkReference(parts) {
|
|
309
|
+
const work = parts.flatMap((part) => Object.entries(this.state.interfaces?.[part.name] ?? {}).flatMap(([key, batch], at, all) => "entries" in batch && batch.checked === undefined ? [{ part, key, batch, label: `check reference ${part.name}${all.length > 1 ? ` ${at + 1}` : ""}` }] : []));
|
|
310
|
+
if (work.length === 0)
|
|
311
|
+
return;
|
|
312
|
+
this.tracker.stage("extracting", work.length);
|
|
313
|
+
this.progress(`checking the interface reference against the code: ${work.length === 1 ? "an agent" : `${work.length} agents`}`);
|
|
314
|
+
await Promise.all(work.map((item) => this.limited(async () => {
|
|
315
|
+
this.stopIfAsked();
|
|
316
|
+
const files = item.key === "(the map found none)" ? [] : item.key.split(", ");
|
|
317
|
+
const context = [
|
|
318
|
+
this.codebaseBlock(),
|
|
319
|
+
`<part>\n${item.part.name} - ${item.part.about}\n</part>`,
|
|
320
|
+
`<the reference>\nAs it was taken from ${files.length > 0 ? files.join(", ") : "the part's code"}:\n\n${renderReference(item.part.name, item.batch.entries)}\n${item.batch.entries.map((entry) => `- \`${entry.name}\`${entry.command !== undefined ? ` of \`${entry.command}\`` : ""}: ${entry.where}${entry.also.length > 0 ? `, also ${entry.also.join(", ")}` : ""}`).join("\n")}\n${item.batch.excluded.length > 0 ? `\nLeft out: ${item.batch.excluded.map((excluded) => `\`${excluded.name}\` (${excluded.path}) - ${excluded.why}`).join("; ")}\n` : ""}</the reference>`,
|
|
321
|
+
`<map>\n${renderArea(this.map, item.part.paths, Math.floor(this.budget / 2))}\n</map>`,
|
|
322
|
+
].join("\n\n");
|
|
323
|
+
const { answer, problems } = await askAgent(this.agent(item.label, "check-reference", context, { reads: true, rules: false, calls: 60 }), { ...REFERENCE_CHECKED_TOOL, convert: (params) => ({ ...referenceAnswerOf(params), changes: strings(params.changes) }) }, (answer) => [...(answer.entries.length === 0 ? ["Give every entry as the code has it - those that hold too."] : []), ...referenceProblems(this.map, this.options.root, files, answer)]);
|
|
324
|
+
const batch = this.state.interfaces[item.part.name][item.key];
|
|
325
|
+
if ("entries" in batch) {
|
|
326
|
+
if (answer !== undefined) {
|
|
327
|
+
batch.entries = answer.entries;
|
|
328
|
+
batch.excluded = answer.excluded;
|
|
329
|
+
batch.checked = { changes: answer.changes };
|
|
330
|
+
}
|
|
331
|
+
else
|
|
332
|
+
batch.checked = { failed: `the check did not hold: ${problems.join(" ")}` };
|
|
333
|
+
}
|
|
334
|
+
this.save();
|
|
335
|
+
this.tracker.worked();
|
|
336
|
+
this.progress(answer === undefined ? `could not check ${item.part.name}'s interface reference - kept as taken` : answer.changes.length === 0 ? `${item.part.name}'s interface reference holds` : `corrected ${item.part.name}'s interface reference: ${answer.changes.length} change${answer.changes.length === 1 ? "" : "s"}`);
|
|
337
|
+
})));
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The interface among some paths, for an agent: the reference's entries there - exact, taken from the code - and what
|
|
341
|
+
* the map found there that the reference neither lists nor excludes; the map's alone where no reference was taken.
|
|
342
|
+
*/
|
|
343
|
+
interfaceFor(part, paths) {
|
|
344
|
+
const reference = referenceOf(this.state, part);
|
|
345
|
+
const found = interfaceIn(this.map, paths, leftOutPaths(this.state));
|
|
346
|
+
if (reference.entries.length === 0)
|
|
347
|
+
return { entries: [], unlisted: found };
|
|
348
|
+
const listed = reference.entries.map(entrySurface);
|
|
349
|
+
return {
|
|
350
|
+
entries: entriesIn(reference.entries, paths),
|
|
351
|
+
unlisted: found.filter((surface) => !listed.some((entry) => namedIn(surface, entry.name)) && !reference.excluded.some((item) => namedExactly(surface, item.name))),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** What a feature's writer is told of the interface in its files: the reference's entries, exact, and what to do with them. */
|
|
355
|
+
writerInterfaceBlock(part, paths) {
|
|
356
|
+
const { entries, unlisted } = this.interfaceFor(part, paths);
|
|
357
|
+
if (referenceOf(this.state, part).entries.length === 0) {
|
|
358
|
+
return interfaceBlock("the interface in your files", "Every option, command, route, screen and environment variable the code defines in your feature's files - capture exactly each your feature owns:", unlisted);
|
|
359
|
+
}
|
|
360
|
+
const concept = interfaceConcept(part);
|
|
361
|
+
return referenceBlock("the interface in your files", `Taken from the code, every literal checked against it: ${concept}'s reference, which every functional spec using ${concept} carries. Of these, capture what each your feature owns does - by its exact name, using ${concept}. What one takes, its choices, its default and its help are the reference's: say them only where a behaviour turns on them, and never otherwise than here.`, entries, unlisted);
|
|
362
|
+
}
|
|
363
|
+
/** What a writer of the interface no feature captured is given: those pieces, with the reference's entry of each. */
|
|
364
|
+
gapBlock(part, gaps) {
|
|
365
|
+
const { entries } = referenceOf(this.state, part);
|
|
366
|
+
const exact = entries.filter((entry) => gaps.some((gap) => gap.name === entrySurface(entry).name && gap.path === entryFile(entry)));
|
|
367
|
+
const rest = gaps.filter((gap) => !exact.some((entry) => gap.name === entrySurface(entry).name && gap.path === entryFile(entry)));
|
|
368
|
+
return referenceBlock("the interface to capture", "Named in no functional spec of the part - capture each exactly, or drop it, by name, with why:", exact, rest);
|
|
369
|
+
}
|
|
370
|
+
/** The manifests near the root, each cut short: what the codebase is built on. */
|
|
371
|
+
manifests() {
|
|
372
|
+
const files = this.map.files.filter((file) => file.kind === "manifest" && file.path.split("/").length <= 3).sort((a, b) => a.path.split("/").length - b.path.split("/").length);
|
|
373
|
+
return this.excerpts(files.map((file) => file.path), 3000, 16_000) || "None found.";
|
|
374
|
+
}
|
|
375
|
+
/** The READMEs near the root, cut short. */
|
|
376
|
+
docs() {
|
|
377
|
+
const files = this.map.files.filter((file) => /^readme/i.test(file.path.split("/").at(-1)) && file.path.split("/").length <= 2);
|
|
378
|
+
return this.excerpts(files.map((file) => file.path), 6000, 8000) || "None found.";
|
|
379
|
+
}
|
|
380
|
+
excerpts(paths, each, total) {
|
|
381
|
+
const parts = [];
|
|
382
|
+
let used = 0;
|
|
383
|
+
for (const path of paths) {
|
|
384
|
+
if (used >= total)
|
|
385
|
+
break;
|
|
386
|
+
let body;
|
|
387
|
+
try {
|
|
388
|
+
body = readFileSync(join(this.map.root, ...path.split("/")), "utf8");
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
const cut = body.length > each ? `${body.slice(0, each)}\n[... ${body.length - each} more characters]` : body;
|
|
394
|
+
parts.push(`### ${path}\n${cut.trimEnd()}`);
|
|
395
|
+
used += cut.length;
|
|
396
|
+
}
|
|
397
|
+
return parts.join("\n\n");
|
|
398
|
+
}
|
|
399
|
+
part(name) {
|
|
400
|
+
return this.state.survey.parts.find((part) => part.name === name);
|
|
401
|
+
}
|
|
402
|
+
/** Outline an area: split it and outline its areas, or outline it into features - whichever is left to do. */
|
|
403
|
+
async outlineArea(id) {
|
|
404
|
+
const area = this.state.areas[id];
|
|
405
|
+
if (area.failed !== undefined)
|
|
406
|
+
return;
|
|
407
|
+
if (area.children === undefined && area.features === undefined) {
|
|
408
|
+
const files = filesOf(this.map, area.paths);
|
|
409
|
+
const splittable = linesOf(files) > this.leafLines && entriesOf(this.map, area.paths).length >= 2;
|
|
410
|
+
if (!splittable || !(await this.split(area)))
|
|
411
|
+
await this.outline(area);
|
|
412
|
+
}
|
|
413
|
+
if (area.children !== undefined)
|
|
414
|
+
await Promise.all(area.children.map((child) => this.outlineArea(child)));
|
|
415
|
+
}
|
|
416
|
+
/** Capture a part's features, side by side - all but those the division merged into others. */
|
|
417
|
+
async captureFeatures(part) {
|
|
418
|
+
await Promise.all(featuresOf(this.state, part).map(({ leaf, feature }) => this.feature(leaf, feature)));
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Each part's features divided, once all its areas are outlined: each behaviour given to one feature, a feature that
|
|
422
|
+
* is a slice of another's behaviour merged into it. A part outlined as one area was outlined by one agent that saw all
|
|
423
|
+
* of it, and a part whose features are being written already keeps them as they are. A division that never holds
|
|
424
|
+
* leaves each feature owning what it was outlined for.
|
|
425
|
+
*/
|
|
426
|
+
async divide() {
|
|
427
|
+
const pending = this.state.survey.parts.filter((part) => this.state.divided?.[part.name] === undefined && leavesOf(this.state, part.name).length > 1 && !featuresOf(this.state, part.name, { merged: true }).some(({ key }) => this.state.features[key] !== undefined));
|
|
428
|
+
if (pending.length === 0)
|
|
429
|
+
return;
|
|
430
|
+
this.tracker.stage("dividing", pending.length);
|
|
431
|
+
await Promise.all(pending.map((part) => this.limited(async () => {
|
|
432
|
+
this.stopIfAsked();
|
|
433
|
+
const features = featuresOf(this.state, part.name, { merged: true });
|
|
434
|
+
const keys = features.map(({ key }) => key);
|
|
435
|
+
this.progress(`dividing the ${features.length} features of ${part.name}`);
|
|
436
|
+
const context = [`<part>\n${part.name} - ${part.about}\n</part>`, `<features of ${part.name}, in build order>\n${this.featureList(part.name, { paths: true })}\n</features of ${part.name}>`].join("\n\n");
|
|
437
|
+
const convert = (params) => ({
|
|
438
|
+
owns: records(params.features).map((item) => ({ feature: text(item.feature), owns: text(item.owns) })),
|
|
439
|
+
merged: records(params.merged).map((item) => ({ feature: text(item.feature), into: strings(item.into), why: text(item.why) })),
|
|
440
|
+
});
|
|
441
|
+
const { answer, problems } = await askAgent(this.agent(`divide ${part.name}`, "divide", context, { reads: false, rules: false, calls: 3 }), { ...OWNERS_TOOL, convert }, (answer) => divisionProblems(keys, answer));
|
|
442
|
+
(this.state.divided ??= {})[part.name] =
|
|
443
|
+
answer !== undefined
|
|
444
|
+
? { owns: Object.fromEntries(answer.owns.map((item) => [item.feature, item.owns])), merged: Object.fromEntries(answer.merged.map((item) => [item.feature, { into: item.into, why: item.why }])) }
|
|
445
|
+
: { owns: {}, merged: {}, failed: `the division did not hold: ${problems.join(" ")}` };
|
|
446
|
+
this.save();
|
|
447
|
+
this.tracker.worked();
|
|
448
|
+
this.progress(answer !== undefined ? `divided the features of ${part.name}${answer.merged.length > 0 ? `: ${answer.merged.map((item) => `${item.feature} merged into ${item.into.join(", ")}`).join("; ")}` : ""}` : `could not divide the features of ${part.name} - each owns what it was outlined for`);
|
|
449
|
+
})));
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* A part's features in build order, area by area - each with what it owns once divided, else what it was outlined
|
|
453
|
+
* for - for the division and for each writer: `mine` marks a writer's own, and leaves out those merged; `paths` adds
|
|
454
|
+
* where each is built. Folded to a budget: where each is built goes first, then what the features of other areas own,
|
|
455
|
+
* then their titles - a writer's own area is always listed whole.
|
|
456
|
+
*/
|
|
457
|
+
featureList(part, options) {
|
|
458
|
+
const division = this.state.divided?.[part];
|
|
459
|
+
const mineLeaf = options.mine?.split("#")[0];
|
|
460
|
+
const levels = ["paths", "owns", "titles", "keys"];
|
|
461
|
+
const render = (fold) => leavesOf(this.state, part)
|
|
462
|
+
.flatMap((leaf) => {
|
|
463
|
+
const features = (leaf.features ?? []).map((feature) => ({ key: featureKey(leaf.id, feature.name), feature })).filter(({ key }) => options.mine === undefined || division?.merged[key] === undefined);
|
|
464
|
+
if (features.length === 0)
|
|
465
|
+
return [];
|
|
466
|
+
const level = leaf.id === mineLeaf ? "owns" : fold;
|
|
467
|
+
return [
|
|
468
|
+
`## ${leaf.id} - ${leaf.about}`,
|
|
469
|
+
...features.flatMap(({ key, feature }) => {
|
|
470
|
+
const mark = options.mine === undefined ? "- " : key === options.mine ? "-> " : " ";
|
|
471
|
+
if (level === "keys")
|
|
472
|
+
return [`${mark}${key}`];
|
|
473
|
+
if (level === "titles")
|
|
474
|
+
return [`${mark}${key} - ${feature.title}`];
|
|
475
|
+
const line = `${mark}${key} - ${feature.title}: ${division?.owns[key] ?? feature.about}`;
|
|
476
|
+
return options.paths === true && level === "paths" ? [line, ` built in: ${feature.paths.join(", ")}`] : [line];
|
|
477
|
+
}),
|
|
478
|
+
];
|
|
479
|
+
})
|
|
480
|
+
.join("\n");
|
|
481
|
+
const budget = options.mine === undefined ? this.budget * 2 : this.budget;
|
|
482
|
+
let listed = "";
|
|
483
|
+
for (const fold of levels) {
|
|
484
|
+
listed = render(fold);
|
|
485
|
+
if (listed.length <= budget)
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
488
|
+
return listed;
|
|
489
|
+
}
|
|
490
|
+
areaContext(area, budget) {
|
|
491
|
+
const part = this.part(area.part);
|
|
492
|
+
return [
|
|
493
|
+
this.codebaseBlock(),
|
|
494
|
+
`<part>\n${part.name} - ${part.about}\n</part>`,
|
|
495
|
+
`<area>\n${area.id} - ${area.about}\n</area>`,
|
|
496
|
+
`<map>\n${renderArea(this.map, area.paths, budget)}\n</map>`,
|
|
497
|
+
].join("\n\n");
|
|
498
|
+
}
|
|
499
|
+
/** Split an area into areas in build order. False when the split never held - it is outlined instead. */
|
|
500
|
+
async split(area) {
|
|
501
|
+
this.stopIfAsked();
|
|
502
|
+
const convert = (params) => ({
|
|
503
|
+
areas: records(params.areas).map((item) => ({ name: kebab(text(item.name)) || text(item.name), about: text(item.about), paths: strings(item.paths).map(trimSlash) })),
|
|
504
|
+
leftOut: leftOutOf(params.left_out),
|
|
505
|
+
});
|
|
506
|
+
const { answer, problems } = await this.limited(() => askAgent(this.agent(`split ${area.id}`, "split", this.areaContext(area, this.budget), { reads: true, rules: false, calls: 15 }), { ...AREAS_TOOL, convert }, (answer) => splitProblems(this.map, area.paths, answer)));
|
|
507
|
+
if (answer === undefined) {
|
|
508
|
+
this.progress(`could not split ${area.id} - outlining it whole: ${problems[0] ?? ""}`);
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
const ordered = buildOrder(this.map, answer.areas);
|
|
512
|
+
area.children = ordered.map((child) => {
|
|
513
|
+
const id = `${area.id}/${child.name}`;
|
|
514
|
+
this.state.areas[id] = { id, name: child.name, about: child.about, paths: child.paths, part: area.part };
|
|
515
|
+
return id;
|
|
516
|
+
});
|
|
517
|
+
area.leftOut = [...answer.leftOut, ...unplaced(this.map, area.paths, answer.areas, answer.leftOut).map((path) => ({ path, why: "placed in no area by the split" }))];
|
|
518
|
+
this.save();
|
|
519
|
+
this.progress(`split ${area.id} into ${ordered.map((child) => child.name).join(", ")}`);
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
async outline(area) {
|
|
523
|
+
this.stopIfAsked();
|
|
524
|
+
const convert = (params) => ({
|
|
525
|
+
features: records(params.features).map((item) => ({ name: kebab(text(item.name)) || text(item.name), title: text(item.title), about: text(item.about), paths: strings(item.paths).map(trimSlash) })),
|
|
526
|
+
leftOut: leftOutOf(params.left_out),
|
|
527
|
+
});
|
|
528
|
+
const { answer, problems } = await this.limited(() => askAgent(this.agent(`outline ${area.id}`, "outline", `${stackBlock(this.part(area.part))}\n\n${this.areaContext(area, this.budget)}`, { reads: true, rules: false, calls: 25 }), { ...FEATURES_TOOL, convert }, (answer) => outlineProblems(this.map, area.paths, answer)));
|
|
529
|
+
if (answer === undefined) {
|
|
530
|
+
area.failed = `its outline did not hold: ${problems.join(" ")}`;
|
|
531
|
+
this.save();
|
|
532
|
+
this.progress(`could not outline ${area.id}`);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
area.features = answer.features;
|
|
536
|
+
area.leftOut = answer.leftOut;
|
|
537
|
+
this.save();
|
|
538
|
+
this.progress(`outlined ${area.id}: ${answer.features.length} feature${answer.features.length === 1 ? "" : "s"}`);
|
|
539
|
+
}
|
|
540
|
+
async feature(area, feature) {
|
|
541
|
+
const key = featureKey(area.id, feature.name);
|
|
542
|
+
const known = this.state.features[key];
|
|
543
|
+
if (known?.captured !== undefined || known?.failed !== undefined)
|
|
544
|
+
return;
|
|
545
|
+
this.stopIfAsked();
|
|
546
|
+
const part = this.part(area.part);
|
|
547
|
+
const division = this.state.divided?.[part.name];
|
|
548
|
+
// What the division merged into it is its own to capture: the merged features' files are where it is built too.
|
|
549
|
+
const taken = mergedInto(this.state, key);
|
|
550
|
+
const paths = featurePaths(this.state, key);
|
|
551
|
+
const evidence = testEvidence(this.map, paths);
|
|
552
|
+
const budget = scenarioBudget(evidence.reduce((sum, file) => sum + file.lines, 0));
|
|
553
|
+
// A feature the harness added for the interface no feature captured: its writer captures each surface, or says why not.
|
|
554
|
+
const gaps = feature.interface;
|
|
555
|
+
const context = [
|
|
556
|
+
this.codebaseBlock(),
|
|
557
|
+
`<part>\n${part.name} - ${part.about}\n</part>`,
|
|
558
|
+
stackBlock(part),
|
|
559
|
+
`<concepts>\n${part.definitions.map((definition) => `- ${definition.text}`).join("\n") || "None given."}\n</concepts>`,
|
|
560
|
+
`<features of ${part.name}>\nEvery feature of the part, in build order, with what it owns - yours marked:\n${this.featureList(part.name, { mine: key })}\n</features of ${part.name}>`,
|
|
561
|
+
[
|
|
562
|
+
"<feature>",
|
|
563
|
+
`${key} - ${feature.title}: ${feature.about}`,
|
|
564
|
+
...(division?.owns[key] !== undefined ? [`What it owns: ${division.owns[key]}`] : []),
|
|
565
|
+
...taken.map((from) => `Merged into it: ${from.key} - ${outlinedFeature(this.state, from.key)?.about ?? ""} (${from.why})`),
|
|
566
|
+
`Where it is built: ${paths.join(", ")}`,
|
|
567
|
+
"</feature>",
|
|
568
|
+
].join("\n"),
|
|
569
|
+
gaps !== undefined ? this.gapBlock(part.name, gaps) : this.writerInterfaceBlock(part.name, paths),
|
|
570
|
+
testsBlock(evidence, budget),
|
|
571
|
+
`<map>\n${renderArea(this.map, paths, Math.floor(this.budget / 2))}\n</map>`,
|
|
572
|
+
].join("\n\n");
|
|
573
|
+
const { answer, problems } = await this.limited(() => {
|
|
574
|
+
this.stopIfAsked();
|
|
575
|
+
if (gaps === undefined)
|
|
576
|
+
return askAgent(this.agent(`feature ${key}`, "feature", context, { reads: true, rules: true, calls: 40 }), { ...FEATURE_TOOL, convert: capturedOf }, (captured) => featureProblems(captured, part.definitions, budget));
|
|
577
|
+
return askAgent(this.agent(`interface ${key}`, ["feature", "interface"], context, { reads: true, rules: true, calls: 40 }), { ...INTERFACE_TOOL, convert: (params) => ({ ...capturedOf(params), title: text(params.title) }) },
|
|
578
|
+
// A writer may find none of them is the software's interface: then it drops them all, and writes nothing.
|
|
579
|
+
(captured) => [...(captured.title === "" ? ["Give the feature a title."] : []), ...featureProblems(captured, part.definitions, budget, { mayBeEmpty: true }), ...gapProblems(captured, gaps)]);
|
|
580
|
+
});
|
|
581
|
+
if (answer?.title !== undefined)
|
|
582
|
+
feature.title = answer.title;
|
|
583
|
+
this.state.features[key] = answer !== undefined ? { key, captured: withoutTitle(answer) } : { key, failed: `what its writer handed over did not hold: ${problems.join(" ")}` };
|
|
584
|
+
this.save();
|
|
585
|
+
this.progress(answer !== undefined ? `captured ${key}: ${answer.specs.length} functional spec${answer.specs.length === 1 ? "" : "s"}` : `could not capture ${key}`);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* The interface no feature captured, once every feature is written: each option, command, route, screen and
|
|
589
|
+
* environment variable of the code the part's ***plain names nowhere goes to a writer of its own - a feature added to
|
|
590
|
+
* the area whose files define it, so many surfaces a writer - which captures each exactly, or drops it, by name, with
|
|
591
|
+
* why. Once a part: a capture stopped part-way asks again only the writers that never answered.
|
|
592
|
+
*/
|
|
593
|
+
async fillInterface() {
|
|
594
|
+
const pending = this.state.survey.parts.filter((part) => !(this.state.interfaceFilled ?? []).includes(part.name));
|
|
595
|
+
if (pending.length === 0)
|
|
596
|
+
return;
|
|
597
|
+
const gaps = interfaceGaps(this.map, this.state, assemble(this.state, this.options.moduleSpecs));
|
|
598
|
+
const asked = [];
|
|
599
|
+
for (const part of pending) {
|
|
600
|
+
const leaves = leavesOf(this.state, part.name);
|
|
601
|
+
const before = leaves.flatMap((leaf) => (leaf.features ?? []).filter((feature) => feature.interface !== undefined).map((feature) => ({ leaf, feature })));
|
|
602
|
+
if (before.length > 0) {
|
|
603
|
+
asked.push(...before.filter(({ leaf, feature }) => this.state.features[featureKey(leaf.id, feature.name)] === undefined));
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
const byLeaf = new Map();
|
|
607
|
+
for (const gap of gaps.filter((candidate) => candidate.part === part.name)) {
|
|
608
|
+
const leaf = leaves.find((candidate) => candidate.paths.some((path) => covers(path, gap.path))) ?? leaves.at(-1);
|
|
609
|
+
if (leaf !== undefined)
|
|
610
|
+
byLeaf.set(leaf, [...(byLeaf.get(leaf) ?? []), { path: gap.path, kind: gap.kind, name: gap.name }]);
|
|
611
|
+
}
|
|
612
|
+
for (const [leaf, surfaces] of byLeaf) {
|
|
613
|
+
for (let at = 0; at < surfaces.length; at += SURFACES_PER_WRITER) {
|
|
614
|
+
const batch = surfaces.slice(at, at + SURFACES_PER_WRITER);
|
|
615
|
+
const taken = new Set((leaf.features ?? []).map((feature) => feature.name));
|
|
616
|
+
let name = "interface";
|
|
617
|
+
for (let n = 2; taken.has(name); n += 1)
|
|
618
|
+
name = `interface-${n}`;
|
|
619
|
+
const feature = { name, title: "The rest of its interface", about: "the interface of its code no other feature captured", paths: [...new Set(batch.map((surface) => surface.path))], interface: batch };
|
|
620
|
+
(leaf.features ??= []).push(feature);
|
|
621
|
+
asked.push({ leaf, feature });
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
this.save();
|
|
626
|
+
if (asked.length > 0) {
|
|
627
|
+
const surfaces = asked.reduce((sum, { feature }) => sum + (feature.interface?.length ?? 0), 0);
|
|
628
|
+
this.tracker.stage("filling", asked.length);
|
|
629
|
+
this.progress(`capturing the interface no feature named: ${surfaces} option${surfaces === 1 ? "" : "s"}, command${surfaces === 1 ? "" : "s"}, route${surfaces === 1 ? "" : "s"} or variable${surfaces === 1 ? "" : "s"}`);
|
|
630
|
+
await Promise.all(asked.map(({ leaf, feature }) => this.feature(leaf, feature).then(() => this.tracker.worked())));
|
|
631
|
+
}
|
|
632
|
+
this.state.interfaceFilled = [...(this.state.interfaceFilled ?? []), ...pending.map((part) => part.name)];
|
|
633
|
+
this.save();
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Each module's interface checked against the code, once its ***plain reads well: every option, command, route,
|
|
637
|
+
* field, message and exit code its functional specs and scenarios state, by an agent that reads the code deciding it
|
|
638
|
+
* and corrects what is wrong or left out - over the readability pass, which never sees the code. A correction that
|
|
639
|
+
* never holds is not made: what the ***plain said stays.
|
|
640
|
+
*/
|
|
641
|
+
async verifyInterface() {
|
|
642
|
+
const { modules, shared } = assemble(this.state, this.options.moduleSpecs);
|
|
643
|
+
const pending = modules.filter((module) => !(this.state.verified ?? []).includes(module.name));
|
|
644
|
+
if (pending.length === 0)
|
|
645
|
+
return;
|
|
646
|
+
this.tracker.stage("verifying", pending.length);
|
|
647
|
+
this.progress(`checking the interface of ${pending.length} module${pending.length === 1 ? "" : "s"} against the code`);
|
|
648
|
+
await Promise.all(pending.map((module) => this.limited(async () => {
|
|
649
|
+
this.stopIfAsked();
|
|
650
|
+
const sharedModule = shared.find((candidate) => candidate.name === module.shared);
|
|
651
|
+
const known = new Set([...sharedModule.definitions, ...module.definitions].map((definition) => definition.concept));
|
|
652
|
+
const paths = [...new Set(module.features.flatMap((feature) => featurePaths(this.state, feature.key)))];
|
|
653
|
+
const own = this.interfaceFor(module.part, paths);
|
|
654
|
+
const reference = referenceOf(this.state, module.part);
|
|
655
|
+
const specs = module.features.flatMap((feature) => feature.specs);
|
|
656
|
+
// An option the ***plain names that the code does not define: found mechanically, for the check to settle.
|
|
657
|
+
const invented = reference.entries.length > 0 ? optionsNotInReference(specs.flatMap((spec) => [spec.text, ...spec.conformance.map((scenario) => scenario.text), ...spec.acceptance.map((scenario) => scenario.text)]).join("\n"), reference.entries) : [];
|
|
658
|
+
const corrections = [];
|
|
659
|
+
for (let at = 0; at < specs.length; at += SPECS_PER_PASS) {
|
|
660
|
+
const chunk = specs.slice(at, at + SPECS_PER_PASS);
|
|
661
|
+
const byId = new Map(chunk.map((spec) => [spec.funcId, spec]));
|
|
662
|
+
const context = [
|
|
663
|
+
this.codebaseBlock(),
|
|
664
|
+
readabilityContext(module, sharedModule.definitions, chunk, stackBlock(this.part(module.part))),
|
|
665
|
+
referenceBlock("the interface in its code", reference.entries.length > 0
|
|
666
|
+
? `Taken from the code, every literal checked against it - ${interfaceConcept(module.part)}'s reference, which the ***plain carries. The ***plain must agree with it, and with the code:`
|
|
667
|
+
: "Every option, command, route, screen and environment variable the code of this module's features defines:", own.entries, own.unlisted),
|
|
668
|
+
...(invented.length > 0 ? [`<options the ***plain names that the reference does not have>\n${invented.map((option) => `\`${option}\``).join(", ")} - an option the code does not define is wrong, unless the code shows otherwise.\n</options the ***plain names that the reference does not have>`] : []),
|
|
669
|
+
`<map>\n${renderArea(this.map, paths, Math.floor(this.budget / 2))}\n</map>`,
|
|
670
|
+
].join("\n\n");
|
|
671
|
+
const { answer } = await askAgent(this.agent(`verify ${module.name}`, "verify", context, { reads: true, rules: true, calls: 40 }), {
|
|
672
|
+
...CORRECTIONS_TOOL,
|
|
673
|
+
convert: (params) => records(params.corrections).map((item) => ({ funcId: text(item.func_id), ...(text(item.scenario_id) !== "" ? { scenarioId: text(item.scenario_id) } : {}), text: text(item.text), why: text(item.why) })),
|
|
674
|
+
}, (answer) => correctionProblems(answer, byId, known));
|
|
675
|
+
for (const correction of answer ?? []) {
|
|
676
|
+
const spec = byId.get(correction.funcId);
|
|
677
|
+
const was = correction.scenarioId === undefined ? spec.text : [...spec.conformance, ...spec.acceptance].find((scenario) => scenario.id === correction.scenarioId)?.text;
|
|
678
|
+
if (correction.text !== was)
|
|
679
|
+
corrections.push(correction);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
(this.state.corrections ??= {})[module.name] = corrections;
|
|
683
|
+
(this.state.verified ??= []).push(module.name);
|
|
684
|
+
this.save();
|
|
685
|
+
this.tracker.worked();
|
|
686
|
+
this.progress(corrections.length === 0 ? `the interface of ${module.name} holds` : `corrected the interface of ${module.name}: ${corrections.length} correction${corrections.length === 1 ? "" : "s"}`);
|
|
687
|
+
})));
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Each part's features gathered into modules by concern and put in the order they are built, once every feature is
|
|
691
|
+
* written. A module is a concern of its own - what a person looks for in one file - never one that holds everything:
|
|
692
|
+
* the code's areas, gathered by size alone, can put a small codebase's every concern in one. And a module is built on
|
|
693
|
+
* the code of the modules before it, its scenarios run as soon as it is: a module whose scenarios send a request comes
|
|
694
|
+
* after the one that sends it. The areas are in the order of their code's imports, which is not that order - the code
|
|
695
|
+
* that runs everything imports everything, yet everything needs it built first. An agent reads every feature's
|
|
696
|
+
* functional specs and scenarios, and the modules as the areas make them, and gathers and orders them, naming what each
|
|
697
|
+
* needs of those before it; a scenario that needs a module after its own whatever the order is rewritten. Once only,
|
|
698
|
+
* before anything is done module by module: what never holds leaves the modules as the code's areas make them.
|
|
699
|
+
*/
|
|
700
|
+
async gatherModules() {
|
|
701
|
+
if (this.state.edited.length > 0 || (this.state.verified ?? []).length > 0 || this.state.written === true)
|
|
702
|
+
return;
|
|
703
|
+
const { modules } = assemble(this.state, this.options.moduleSpecs);
|
|
704
|
+
const pending = this.state.survey.parts.filter((part) => this.state.gathered?.[part.name] === undefined && this.gatheredFeatures(part.name).length > 1);
|
|
705
|
+
if (pending.length === 0)
|
|
706
|
+
return;
|
|
707
|
+
this.tracker.stage("gathering", pending.length);
|
|
708
|
+
await Promise.all(pending.map((part) => this.limited(async () => {
|
|
709
|
+
this.stopIfAsked();
|
|
710
|
+
const features = this.gatheredFeatures(part.name);
|
|
711
|
+
const byArea = modules.filter((module) => module.part === part.name);
|
|
712
|
+
this.progress(`gathering the ${features.length} features of ${part.name} into modules`);
|
|
713
|
+
const given = {
|
|
714
|
+
features: new Map(features.map(({ key, specs }) => [key, specs])),
|
|
715
|
+
known: this.knownConcepts(part.name),
|
|
716
|
+
reserved: new Set(this.state.survey.parts.map((candidate) => sharedName(candidate.name))),
|
|
717
|
+
moduleSpecs: this.options.moduleSpecs ?? MODULE_SPECS,
|
|
718
|
+
};
|
|
719
|
+
const context = [
|
|
720
|
+
`<part>\n${part.name} - ${part.about}\n</part>`,
|
|
721
|
+
`<features of ${part.name}, area by area, in the order of their code>\n${gatheringList(features, GATHERING_BUDGET)}\n</features of ${part.name}>`,
|
|
722
|
+
`<modules as the code's areas make them>\n${byArea.map((module) => `- ${module.name} - ${module.about}: ${module.features.map((feature) => feature.key).join(", ")}`).join("\n")}\n</modules as the code's areas make them>`,
|
|
723
|
+
].join("\n\n");
|
|
724
|
+
const convert = (params) => ({
|
|
725
|
+
modules: records(params.modules).map((item) => ({ name: kebab(text(item.name)) || text(item.name), about: text(item.about), features: strings(item.features), needs: strings(item.needs) })),
|
|
726
|
+
rewrites: records(params.rewrites).map((item) => ({ feature: text(item.feature), funcId: text(item.func_id), scenarioId: text(item.scenario_id), text: text(item.text), why: text(item.why) })),
|
|
727
|
+
});
|
|
728
|
+
const { answer, problems } = await askAgent(this.agent(`modules ${part.name}`, "modules", context, { reads: false, rules: true, calls: 3 }), { ...MODULES_TOOL, convert }, (answer) => moduleProblems(answer, given));
|
|
729
|
+
(this.state.gathered ??= {})[part.name] = answer !== undefined ? answer : { modules: [], rewrites: [], failed: `the gathering did not hold: ${problems.join(" ")}` };
|
|
730
|
+
this.save();
|
|
731
|
+
this.tracker.worked();
|
|
732
|
+
this.progress(answer === undefined
|
|
733
|
+
? `could not gather the features of ${part.name} into modules - they are as the code's areas make them`
|
|
734
|
+
: `gathered the features of ${part.name} into ${answer.modules.length} module${answer.modules.length === 1 ? "" : "s"}: ${answer.modules.map((module) => module.name).join(", ")}${answer.rewrites.length > 0 ? `; ${answer.rewrites.length} scenario${answer.rewrites.length === 1 ? "" : "s"} rewritten` : ""}`);
|
|
735
|
+
})));
|
|
736
|
+
}
|
|
737
|
+
/** A part's features a module can hold, in the order of their code: written, with functional specs. */
|
|
738
|
+
gatheredFeatures(part) {
|
|
739
|
+
const division = this.state.divided?.[part];
|
|
740
|
+
return featuresOf(this.state, part).flatMap(({ key, leaf, feature }) => {
|
|
741
|
+
const specs = this.state.features[key]?.captured?.specs ?? [];
|
|
742
|
+
return specs.length === 0 ? [] : [{ key, area: leaf, title: feature.title, owns: division?.owns[key] ?? feature.about, specs }];
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Each module's scenarios tried on the original, once its ***plain is checked against the code and before it is
|
|
747
|
+
* written. They are what the regenerated code's conformance tests check, written by agents that read the original but
|
|
748
|
+
* never ran it - so one can expect a terminal its test will not give, a site on the internet, wrapping at a width
|
|
749
|
+
* nobody set. An agent with a shell on a copy of the original - its files, installed there by the agent - runs each as
|
|
750
|
+
* its conformance test will, under the test reqs: one the original does otherwise is corrected to what it does, one
|
|
751
|
+
* nothing outside can check is removed, and what a test must set up for the original to act as they say joins the test
|
|
752
|
+
* reqs. So many scenarios an agent; a module's agents one after another in a copy of its own, removed once they are
|
|
753
|
+
* done. What never holds is left as it was, and the report says so.
|
|
754
|
+
*/
|
|
755
|
+
async trialScenarios() {
|
|
756
|
+
const assembly = assemble(this.state, this.options.moduleSpecs, { trials: false });
|
|
757
|
+
const pending = assembly.modules
|
|
758
|
+
.filter((module) => !(this.state.tried ?? []).includes(module.name))
|
|
759
|
+
.map((module) => ({ module, batches: trialBatches(module) }))
|
|
760
|
+
.map((item) => ({ ...item, left: item.batches.filter((_, at) => this.state.trials?.[item.module.name]?.[String(at + 1)] === undefined).length }));
|
|
761
|
+
if (pending.length === 0)
|
|
762
|
+
return;
|
|
763
|
+
const total = pending.reduce((sum, item) => sum + item.left, 0);
|
|
764
|
+
if (total > 0) {
|
|
765
|
+
const scenarios = pending.reduce((sum, item) => sum + item.batches.reduce((inner, batch) => inner + batch.length, 0), 0);
|
|
766
|
+
this.tracker.stage("trying", total);
|
|
767
|
+
this.progress(`trying ${scenarios} scenario${scenarios === 1 ? "" : "s"} on the original: ${total === 1 ? "an agent" : `${total} agents`}`);
|
|
768
|
+
}
|
|
769
|
+
await Promise.all(pending.map((item) => (item.left === 0 ? this.triedAll(item.module.name) : this.limited(() => this.trialModule(item.module, item.batches, assembly)))));
|
|
770
|
+
}
|
|
771
|
+
async triedAll(module) {
|
|
772
|
+
if (!(this.state.tried ?? []).includes(module))
|
|
773
|
+
(this.state.tried ??= []).push(module);
|
|
774
|
+
this.save();
|
|
775
|
+
}
|
|
776
|
+
/** A module's scenarios tried on a copy of the original of its own, so many an agent, one after another. */
|
|
777
|
+
async trialModule(module, batches, assembly) {
|
|
778
|
+
const dir = join(captureDir(this.options.plainDir), "trial", module.name);
|
|
779
|
+
const original = join(dir, "original");
|
|
780
|
+
const part = this.part(module.part);
|
|
781
|
+
const checked = checkedModule(module, assembly.shared);
|
|
782
|
+
try {
|
|
783
|
+
for (const [at, batch] of batches.entries()) {
|
|
784
|
+
const key = String(at + 1);
|
|
785
|
+
if (this.state.trials?.[module.name]?.[key] !== undefined)
|
|
786
|
+
continue;
|
|
787
|
+
this.stopIfAsked();
|
|
788
|
+
const installed = existsSync(original);
|
|
789
|
+
if (!installed)
|
|
790
|
+
copyOriginal(this.map, original);
|
|
791
|
+
const label = `trial ${module.name}${batches.length > 1 ? ` ${at + 1}` : ""}`;
|
|
792
|
+
const context = this.trialContext(part, module, batch, assembly, { folder: original, installed });
|
|
793
|
+
const convert = (params) => ({
|
|
794
|
+
results: records(params.scenarios).map((item) => {
|
|
795
|
+
const corrected = text(item.text);
|
|
796
|
+
const why = text(item.why);
|
|
797
|
+
return { funcId: text(item.func_id), scenarioId: text(item.scenario_id), outcome: text(item.outcome), ran: text(item.ran), ...(corrected !== "" ? { text: corrected } : {}), ...(why !== "" ? { why } : {}) };
|
|
798
|
+
}),
|
|
799
|
+
specs: records(params.functional_specs).map((item) => ({ funcId: text(item.func_id), text: text(item.text), why: text(item.why) })),
|
|
800
|
+
testReqs: strings(params.test_reqs).map((req) => req.replace(/^-\s+/, "")),
|
|
801
|
+
});
|
|
802
|
+
const { answer, problems } = await askAgent({ ...this.agent(label, "trial", context, { reads: true, rules: false, calls: TRIAL_CALLS }), shell: { workdir: original, home: dir }, turnAtLeastMs: TRIAL_TURN_MS }, { ...TRIAL_TOOL, convert }, (answer) => trialProblems(answer, batch, checked));
|
|
803
|
+
((this.state.trials ??= {})[module.name] ??= {})[key] = answer ?? { failed: `what its agent handed over did not hold: ${problems.join(" ")}` };
|
|
804
|
+
this.save();
|
|
805
|
+
this.tracker.worked();
|
|
806
|
+
this.progress(answer === undefined ? `could not try ${label.slice("trial ".length)}'s scenarios on the original - kept as they were` : `tried ${batch.length} scenario${batch.length === 1 ? "" : "s"} of ${module.name} on the original: ${trialSummary(answer.results)}`);
|
|
807
|
+
}
|
|
808
|
+
await this.triedAll(module.name);
|
|
809
|
+
}
|
|
810
|
+
finally {
|
|
811
|
+
// The copy, its installs, its home and its caches: what an agent ran the original in, never kept.
|
|
812
|
+
rmSync(dir, { recursive: true, force: true });
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
/** What an agent trying scenarios is given: how the tests run, the conventions, the functional specs, the scenarios, its folder. */
|
|
816
|
+
trialContext(part, module, batch, assembly, copy) {
|
|
817
|
+
const sharedModule = assembly.shared.find((candidate) => candidate.name === module.shared);
|
|
818
|
+
const conformance = part.stdlibStack !== undefined && part.stdlibConformance === true ? stdlibTemplates().find((template) => template.name === conformanceOf(part.stdlibStack)) : undefined;
|
|
819
|
+
// What the trials before this one found a test must set up: of this part's modules, so far.
|
|
820
|
+
const found = trialTestReqs(assembly.modules.filter((candidate) => candidate.part === part.name).flatMap((candidate) => Object.values(this.state.trials?.[candidate.name] ?? {})));
|
|
821
|
+
const reqs = [...sharedModule.testReqs, ...found.filter((req) => !sharedModule.testReqs.includes(req))];
|
|
822
|
+
const specs = new Map(module.features.flatMap((feature) => feature.specs).map((spec) => [spec.funcId, spec]));
|
|
823
|
+
const funcIds = [...new Set(batch.map((scenario) => scenario.funcId))];
|
|
824
|
+
return [
|
|
825
|
+
`<part>\n${part.name} - ${part.about}\n</part>`,
|
|
826
|
+
[
|
|
827
|
+
"<how its conformance tests run>",
|
|
828
|
+
...(conformance !== undefined ? [`### ${conformance.name}`, conformance.text.trim(), ""] : []),
|
|
829
|
+
...(reqs.length > 0 ? ["### The part's test reqs", ...reqs.map((req) => `- ${req}`)] : conformance === undefined ? ["None written: run each scenario as a black-box test would - from outside, its output captured, its input not a terminal."] : []),
|
|
830
|
+
"</how its conformance tests run>",
|
|
831
|
+
].join("\n"),
|
|
832
|
+
...((part.conventions ?? []).length > 0 ? [`<conventions>\n${part.conventions.map((convention) => `- ${convention.text}`).join("\n")}\n</conventions>`] : []),
|
|
833
|
+
`<definitions>\n${[...sharedModule.definitions, ...module.definitions].map((definition) => `- ${definition.text}`).join("\n") || "None."}\n</definitions>`,
|
|
834
|
+
`<functional specs of ${module.name}>\n${funcIds.map((funcId) => `# ${funcId}\n${specs.get(funcId)?.text ?? ""}`).join("\n\n")}\n</functional specs of ${module.name}>`,
|
|
835
|
+
`<scenarios to try>\n${batch.map((scenario) => `### ${scenario.funcId}, scenario ${scenario.scenarioId} (${scenario.kind})\n${scenario.text}`).join("\n\n")}\n</scenarios to try>`,
|
|
836
|
+
`<your folder>\n${slashed(copy.folder)} - a copy of the original codebase: its files as git has them, ${copy.installed ? "where an agent before you tried other scenarios of the module - what it installed may be there: look before installing again" : "nothing installed"}.\n</your folder>`,
|
|
837
|
+
].join("\n\n");
|
|
838
|
+
}
|
|
839
|
+
/** Concepts defined in different words by different features, given one definition each. */
|
|
840
|
+
async reconcile() {
|
|
841
|
+
const conflicts = assemble(this.state, this.options.moduleSpecs).conflicts;
|
|
842
|
+
if (conflicts.length === 0)
|
|
843
|
+
return;
|
|
844
|
+
const batches = [];
|
|
845
|
+
for (let at = 0; at < conflicts.length; at += CONFLICTS_PER_AGENT)
|
|
846
|
+
batches.push(conflicts.slice(at, at + CONFLICTS_PER_AGENT));
|
|
847
|
+
this.tracker.stage("reconciling", batches.length);
|
|
848
|
+
this.progress(`reconciling ${conflicts.length} concept${conflicts.length === 1 ? "" : "s"} defined twice`);
|
|
849
|
+
await Promise.all(batches.map((batch, index) => this.limited(async () => {
|
|
850
|
+
this.stopIfAsked();
|
|
851
|
+
const part = batch[0].part;
|
|
852
|
+
const known = this.knownConcepts(part);
|
|
853
|
+
const others = this.definitionsOf(part);
|
|
854
|
+
const context = batch
|
|
855
|
+
.map((conflict) => [
|
|
856
|
+
`<concept name="${conflict.concept}" part="${conflict.part}">`,
|
|
857
|
+
"Its definitions:",
|
|
858
|
+
...conflict.texts.map((given) => `- ${given}`),
|
|
859
|
+
"Used in:",
|
|
860
|
+
...conflict.uses.slice(0, 4).map((use) => `- ${use.where}: ${use.text.slice(0, 400).replace(/\n/g, " ")}`),
|
|
861
|
+
"</concept>",
|
|
862
|
+
].join("\n"))
|
|
863
|
+
.concat(`<concepts you may use>\n${[...known].join(", ")}\n</concepts you may use>`)
|
|
864
|
+
.join("\n\n");
|
|
865
|
+
const asked = batch.map((conflict) => conflict.concept);
|
|
866
|
+
const { answer } = await askAgent(this.agent(`concepts ${index + 1}`, "concepts", context, { reads: false, rules: true, calls: 3 }), { ...CONCEPTS_TOOL, convert: (params) => definitionsOf(params.definitions) }, (answer) => reconciledProblems(answer, asked, known, others));
|
|
867
|
+
// What never held keeps the first definition given: one of the writers' own.
|
|
868
|
+
for (const conflict of batch) {
|
|
869
|
+
const given = answer?.find((definition) => definition.concept === conflict.concept)?.text ?? conflict.texts[0];
|
|
870
|
+
(this.state.reconciled[conflict.part] ??= {})[conflict.concept] = given;
|
|
871
|
+
}
|
|
872
|
+
this.save();
|
|
873
|
+
this.tracker.worked();
|
|
874
|
+
})));
|
|
875
|
+
}
|
|
876
|
+
/** Every concept a part's modules may use: the part's own, and every one its features defined. */
|
|
877
|
+
knownConcepts(part) {
|
|
878
|
+
return new Set(this.definitionsOf(part).map((definition) => definition.concept));
|
|
879
|
+
}
|
|
880
|
+
/** A part's definitions: its own, and the first of each its features defined - or the one reconciled. */
|
|
881
|
+
definitionsOf(part) {
|
|
882
|
+
const found = new Map(this.part(part).definitions.map((definition) => [definition.concept, definition]));
|
|
883
|
+
const reconciled = this.state.reconciled[part] ?? {};
|
|
884
|
+
for (const leaf of leavesOf(this.state, part)) {
|
|
885
|
+
for (const feature of leaf.features ?? []) {
|
|
886
|
+
for (const definition of this.state.features[featureKey(leaf.id, feature.name)]?.captured?.definitions ?? []) {
|
|
887
|
+
if (!found.has(definition.concept))
|
|
888
|
+
found.set(definition.concept, reconciled[definition.concept] !== undefined ? { concept: definition.concept, text: reconciled[definition.concept] } : definition);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return [...found.values()];
|
|
893
|
+
}
|
|
894
|
+
/** Each module's ***plain read for readability alone, its functional specs rewritten where they read as code. */
|
|
895
|
+
async readability() {
|
|
896
|
+
const { modules, shared } = assemble(this.state, this.options.moduleSpecs);
|
|
897
|
+
const pending = modules.filter((module) => !this.state.edited.includes(module.name));
|
|
898
|
+
if (pending.length === 0)
|
|
899
|
+
return;
|
|
900
|
+
this.tracker.stage("reading", pending.length);
|
|
901
|
+
this.progress(`reading ${pending.length} module${pending.length === 1 ? "" : "s"} for readability`);
|
|
902
|
+
await Promise.all(pending.map((module) => this.limited(async () => {
|
|
903
|
+
this.stopIfAsked();
|
|
904
|
+
const sharedModule = shared.find((candidate) => candidate.name === module.shared);
|
|
905
|
+
const known = new Set([...sharedModule.definitions, ...module.definitions].map((definition) => definition.concept));
|
|
906
|
+
const specs = module.features.flatMap((feature) => feature.specs);
|
|
907
|
+
const edits = {};
|
|
908
|
+
for (let at = 0; at < specs.length; at += SPECS_PER_PASS) {
|
|
909
|
+
const chunk = specs.slice(at, at + SPECS_PER_PASS);
|
|
910
|
+
const originals = new Map(chunk.map((spec) => [spec.funcId, spec.text]));
|
|
911
|
+
const context = readabilityContext(module, sharedModule.definitions, chunk, stackBlock(this.part(module.part)));
|
|
912
|
+
const { answer } = await askAgent(this.agent(`readability ${module.name}`, "readability", context, { reads: false, rules: true, calls: 3 }), { ...EDITS_TOOL, convert: (params) => records(params.edits).map((item) => ({ funcId: text(item.func_id), text: text(item.text) })) }, (answer) => answer.flatMap((edit) => editProblems(edit.funcId, edit.text, originals.get(edit.funcId), known)));
|
|
913
|
+
// What did not hold is left as the writer had it: the pass is an optimiser, never a gate.
|
|
914
|
+
for (const edit of answer ?? [])
|
|
915
|
+
if (edit.text !== originals.get(edit.funcId) && editProblems(edit.funcId, edit.text, originals.get(edit.funcId), known).length === 0)
|
|
916
|
+
edits[edit.funcId] = edit.text;
|
|
917
|
+
}
|
|
918
|
+
this.state.edits[module.name] = edits;
|
|
919
|
+
this.state.edited.push(module.name);
|
|
920
|
+
this.save();
|
|
921
|
+
this.tracker.worked();
|
|
922
|
+
})));
|
|
923
|
+
}
|
|
924
|
+
/** Write the ***plain - once: the testing scripts are written for it, and may name themselves in its config. */
|
|
925
|
+
write() {
|
|
926
|
+
const assembly = assemble(this.state, this.options.moduleSpecs);
|
|
927
|
+
if (assembly.modules.length === 0)
|
|
928
|
+
throw new CaptureError("Nothing could be captured: no feature of the codebase held. Run it again to try the areas and features that failed once more.");
|
|
929
|
+
if (this.state.written === true)
|
|
930
|
+
return;
|
|
931
|
+
writeCapture(this.options.plainDir, this.map, this.state, assembly, this.options.given);
|
|
932
|
+
this.state.written = true;
|
|
933
|
+
this.save();
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Each part's testing scripts, written by turri's skills on the ***plain just written - on the coding model when one
|
|
937
|
+
* was given - side by side. One that is not written does not stop the capture: the report says why, and what to ask.
|
|
938
|
+
*/
|
|
939
|
+
async scripts() {
|
|
940
|
+
const assembly = assemble(this.state, this.options.moduleSpecs);
|
|
941
|
+
const parts = this.state.survey.parts;
|
|
942
|
+
const asked = parts.flatMap((part) => {
|
|
943
|
+
const first = assembly.modules.find((module) => module.part === part.name);
|
|
944
|
+
if (first === undefined)
|
|
945
|
+
return [];
|
|
946
|
+
return SCRIPT_KINDS.map((kind) => ({ key: `${part.name}:${kind}`, part, module: first.name, ...(parts.length > 1 ? { configModule: first.name } : {}), kind }));
|
|
947
|
+
});
|
|
948
|
+
const pending = asked.filter((item) => this.state.scripts?.[item.key] === undefined);
|
|
949
|
+
if (pending.length === 0)
|
|
950
|
+
return;
|
|
951
|
+
this.tracker.stage("scripts", pending.length);
|
|
952
|
+
this.progress(`writing ${pending.length === 1 ? "a testing script" : `${pending.length} testing scripts`}`);
|
|
953
|
+
await Promise.all(pending.map((item) => this.limited(async () => {
|
|
954
|
+
this.stopIfAsked();
|
|
955
|
+
const outcome = await this.script(item);
|
|
956
|
+
(this.state.scripts ??= {})[item.key] = outcome;
|
|
957
|
+
this.save();
|
|
958
|
+
this.tracker.worked();
|
|
959
|
+
const { what } = testingScriptSkill(item.kind);
|
|
960
|
+
this.progress("written" in outcome ? `wrote the ${what} of ${item.part.name}: ${outcome.written}` : `no ${what} for ${item.part.name}: ${outcome.failed}`);
|
|
961
|
+
})));
|
|
962
|
+
}
|
|
963
|
+
async script(item) {
|
|
964
|
+
const { plainDir, root, signal } = this.options;
|
|
965
|
+
const model = this.options.codingModel ?? this.options.model;
|
|
966
|
+
try {
|
|
967
|
+
await watched(this.tracker.agent(testingScriptSkill(item.kind).what), signal, () => (this.options.writeScript ?? writeTestingScript)({
|
|
968
|
+
plainDir,
|
|
969
|
+
root,
|
|
970
|
+
module: item.module,
|
|
971
|
+
...(item.configModule !== undefined ? { configModule: item.configModule } : {}),
|
|
972
|
+
part: item.part,
|
|
973
|
+
kind: item.kind,
|
|
974
|
+
...(model !== undefined ? { model } : {}),
|
|
975
|
+
...(signal !== undefined ? { signal } : {}),
|
|
976
|
+
}));
|
|
977
|
+
}
|
|
978
|
+
catch (error) {
|
|
979
|
+
this.stopIfAsked();
|
|
980
|
+
return { failed: error instanceof Error ? error.message : String(error) };
|
|
981
|
+
}
|
|
982
|
+
const found = withConfigModule(item.configModule, () => findTestScripts(plainDir, join(plainDir, `${item.module}.plain`)))[item.kind];
|
|
983
|
+
return found !== undefined ? { written: slashed(relative(plainDir, found)) } : { failed: "its skill ended with no script written" };
|
|
984
|
+
}
|
|
985
|
+
/** Check the ***plain, write the report, and mark the capture finished. */
|
|
986
|
+
finish() {
|
|
987
|
+
const { plainDir } = this.options;
|
|
988
|
+
const assembly = assemble(this.state, this.options.moduleSpecs);
|
|
989
|
+
const checks = assembly.modules.map((module) => checkPlainFile(join(plainDir, `${module.name}.plain`)));
|
|
990
|
+
this.state.finished = new Date().toISOString();
|
|
991
|
+
const report = renderReport({ root: this.options.root, plainDir, map: this.map, state: this.state, assembly, checks });
|
|
992
|
+
writeFileSync(reportFile(plainDir), report);
|
|
993
|
+
this.save();
|
|
994
|
+
const specs = assembly.modules.reduce((sum, module) => sum + module.features.reduce((inner, feature) => inner + feature.specs.length, 0), 0);
|
|
995
|
+
const failedAreas = Object.values(this.state.areas).filter((area) => area.failed !== undefined).length;
|
|
996
|
+
const failedFeatures = Object.values(this.state.features).filter((feature) => feature.failed !== undefined).length;
|
|
997
|
+
return {
|
|
998
|
+
plainDir,
|
|
999
|
+
reportFile: reportFile(plainDir),
|
|
1000
|
+
summary: summaryOf({ plainDir, map: this.map, assembly, state: this.state, checks }),
|
|
1001
|
+
modules: assembly.modules.map((module) => module.name),
|
|
1002
|
+
specs,
|
|
1003
|
+
uncaptured: failedAreas + failedFeatures,
|
|
1004
|
+
failing: checks.filter((check) => !check.ok).length,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function trimSlash(path) {
|
|
1009
|
+
return path.replace(/^\.\/(?=.)/, "").replace(/\/+$/, "") || ".";
|
|
1010
|
+
}
|
|
1011
|
+
function partOf(item) {
|
|
1012
|
+
const stack = text(item.stdlib_stack);
|
|
1013
|
+
return {
|
|
1014
|
+
name: kebab(text(item.name)) || text(item.name),
|
|
1015
|
+
about: text(item.about),
|
|
1016
|
+
paths: strings(item.paths).map(trimSlash),
|
|
1017
|
+
...(stack !== "" ? { stdlibStack: stack.replace(/\.plain$/, "") } : {}),
|
|
1018
|
+
...(item.stdlib_conformance === true ? { stdlibConformance: true } : {}),
|
|
1019
|
+
implementationReqs: strings(item.implementation_reqs).map((req) => req.replace(/^-\s+/, "")),
|
|
1020
|
+
conventions: conventionsOf(item.conventions),
|
|
1021
|
+
testReqs: strings(item.test_reqs).map((req) => req.replace(/^-\s+/, "")),
|
|
1022
|
+
definitions: definitionsOf(item.definitions),
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function capturedOf(params) {
|
|
1026
|
+
const scenarios = (value) => records(value).map((item) => ({ id: text(item.scenario_id), text: text(item.text) }));
|
|
1027
|
+
return {
|
|
1028
|
+
specs: records(params.functional_specs).map((item) => ({ funcId: text(item.func_id), text: text(item.text), conformance: scenarios(item.conformance), acceptance: scenarios(item.acceptance) })),
|
|
1029
|
+
definitions: definitionsOf(params.definitions),
|
|
1030
|
+
assumptions: strings(params.assumptions),
|
|
1031
|
+
uncertain: strings(params.uncertain),
|
|
1032
|
+
dropped: strings(params.dropped),
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
/** The interface among some files, file by file, for an agent: each name the code gives it, so many at most. */
|
|
1036
|
+
export function interfaceBlock(tag, lead, surfaces) {
|
|
1037
|
+
if (surfaces.length === 0)
|
|
1038
|
+
return `<${tag}>\nThe map found none in these files: find it in the code.\n</${tag}>`;
|
|
1039
|
+
const byFile = new Map();
|
|
1040
|
+
for (const surface of surfaces.slice(0, INTERFACE_LISTED))
|
|
1041
|
+
byFile.set(surface.path, [...(byFile.get(surface.path) ?? []), surface.kind === "env" ? `\`${surface.name}\` (environment variable)` : `\`${surface.name}\``]);
|
|
1042
|
+
const more = surfaces.length > INTERFACE_LISTED ? [`and ${surfaces.length - INTERFACE_LISTED} more, in these files and others of yours`] : [];
|
|
1043
|
+
return [`<${tag}>`, lead, ...[...byFile].map(([path, names]) => `- ${path}: ${names.join(", ")}`), ...more, `</${tag}>`].join("\n");
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* The interface among some files, for an agent: the reference's entries - each with every name, what it takes, its
|
|
1047
|
+
* choices and its default, and where - and, after them, what the map found there that the reference does not list.
|
|
1048
|
+
*/
|
|
1049
|
+
export function referenceBlock(tag, lead, entries, unlisted) {
|
|
1050
|
+
if (entries.length === 0 && unlisted.length === 0)
|
|
1051
|
+
return `<${tag}>\nNone in these files: find it in the code.\n</${tag}>`;
|
|
1052
|
+
const line = (entry) => {
|
|
1053
|
+
const facts = [
|
|
1054
|
+
...(entry.aliases.length > 0 ? [`also ${entry.aliases.map((alias) => `\`${alias}\``).join(", ")}`] : []),
|
|
1055
|
+
...(entry.takes !== undefined ? [`takes \`${entry.takes}\``] : []),
|
|
1056
|
+
...(entry.choices.length > 0 ? [`one of ${entry.choices.map((choice) => `\`${choice}\``).join(", ")}`] : []),
|
|
1057
|
+
...(entry.default !== undefined ? [`default \`${entry.default}\``] : []),
|
|
1058
|
+
...(entry.hidden === true ? ["hidden"] : []),
|
|
1059
|
+
];
|
|
1060
|
+
return `- ${entry.kind}${entry.command !== undefined ? ` of \`${entry.command}\`` : ""} \`${entry.name}\`${facts.length > 0 ? ` - ${facts.join("; ")}` : ""} (${entry.where})`;
|
|
1061
|
+
};
|
|
1062
|
+
const shown = entries.slice(0, INTERFACE_LISTED).map(line);
|
|
1063
|
+
const more = entries.length > INTERFACE_LISTED ? [`and ${entries.length - INTERFACE_LISTED} more - the reference lists them all`] : [];
|
|
1064
|
+
const others = unlisted.length > 0
|
|
1065
|
+
? [entries.length > 0 ? "Found by the map, and in no entry of the reference - read each where it is:" : "", ...unlisted.slice(0, INTERFACE_LISTED).map((surface) => `- ${shownSurface(surface)}`)].filter((text) => text !== "")
|
|
1066
|
+
: [];
|
|
1067
|
+
return [`<${tag}>`, lead, ...shown, ...more, ...others, `</${tag}>`].join("\n");
|
|
1068
|
+
}
|
|
1069
|
+
/** An agent's part of the interface reference, as it handed it over. */
|
|
1070
|
+
function referenceAnswerOf(params) {
|
|
1071
|
+
const given = (value) => (typeof value === "string" && value.trim() !== "" ? value.trim() : undefined);
|
|
1072
|
+
return {
|
|
1073
|
+
entries: records(params.entries).map((item) => {
|
|
1074
|
+
const command = given(item.command);
|
|
1075
|
+
const takes = given(item.takes);
|
|
1076
|
+
const value = typeof item.default === "string" && item.default.trim() !== "" ? item.default.trim() : undefined;
|
|
1077
|
+
const help = typeof item.help === "string" && item.help.trim() !== "" ? item.help.trim() : undefined;
|
|
1078
|
+
return {
|
|
1079
|
+
kind: text(item.kind),
|
|
1080
|
+
name: text(item.name),
|
|
1081
|
+
aliases: strings(item.aliases),
|
|
1082
|
+
...(command !== undefined ? { command } : {}),
|
|
1083
|
+
...(takes !== undefined ? { takes } : {}),
|
|
1084
|
+
choices: strings(item.choices),
|
|
1085
|
+
...(value !== undefined ? { default: value } : {}),
|
|
1086
|
+
...(item.repeatable === true ? { repeatable: true } : {}),
|
|
1087
|
+
...(item.required === true ? { required: true } : {}),
|
|
1088
|
+
...(item.hidden === true ? { hidden: true } : {}),
|
|
1089
|
+
...(help !== undefined ? { help } : {}),
|
|
1090
|
+
details: strings(item.details),
|
|
1091
|
+
where: text(item.where),
|
|
1092
|
+
also: strings(item.also).map(trimSlash),
|
|
1093
|
+
};
|
|
1094
|
+
}),
|
|
1095
|
+
excluded: records(params.excluded).map((item) => ({ name: text(item.name), path: trimSlash(text(item.path)), why: text(item.why) })),
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
/** A feature's answer as the state keeps it: the title an interface writer gave goes to its outline. */
|
|
1099
|
+
function withoutTitle(answer) {
|
|
1100
|
+
return { specs: answer.specs, definitions: answer.definitions, assumptions: answer.assumptions, uncertain: answer.uncertain, dropped: answer.dropped };
|
|
1101
|
+
}
|
|
1102
|
+
/** Conventions as an agent handed them over: each a line, and the files that decide it. */
|
|
1103
|
+
function conventionsOf(value) {
|
|
1104
|
+
return records(value).map((convention) => ({ text: text(convention.text).replace(/^-\s+/, ""), where: strings(convention.where).map(trimSlash) }));
|
|
1105
|
+
}
|
|
1106
|
+
/** A module as its order's and its trials' checks see it: its functional specs by func-id, and the concepts it may use. */
|
|
1107
|
+
function checkedModule(module, shared) {
|
|
1108
|
+
const sharedModule = shared.find((candidate) => candidate.name === module.shared);
|
|
1109
|
+
return {
|
|
1110
|
+
specs: new Map(module.features.flatMap((feature) => feature.specs).map((spec) => [spec.funcId, spec])),
|
|
1111
|
+
known: new Set([...(sharedModule?.definitions ?? []), ...module.definitions].map((definition) => definition.concept)),
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
/** A text's first line, cut to so many characters. */
|
|
1115
|
+
function cut(text, chars) {
|
|
1116
|
+
const line = text.trim().split("\n")[0].trim();
|
|
1117
|
+
return line.length > chars ? `${line.slice(0, chars)}...` : line;
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* A part's features for the agent that gathers them into modules, area by area in the order of their code: each with
|
|
1121
|
+
* what it owns, the first line of each functional spec, and its scenarios - cut shorter, then left out, until they fit
|
|
1122
|
+
* the budget.
|
|
1123
|
+
*/
|
|
1124
|
+
export function gatheringList(features, budget) {
|
|
1125
|
+
const render = (scenarioChars) => {
|
|
1126
|
+
const lines = [];
|
|
1127
|
+
let area;
|
|
1128
|
+
for (const feature of features) {
|
|
1129
|
+
if (feature.area.id !== area) {
|
|
1130
|
+
if (area !== undefined)
|
|
1131
|
+
lines.push("");
|
|
1132
|
+
area = feature.area.id;
|
|
1133
|
+
lines.push(`## ${feature.area.id} - ${feature.area.about}`);
|
|
1134
|
+
}
|
|
1135
|
+
lines.push(`### ${feature.key} - ${feature.title}: ${cut(feature.owns, 300)}`);
|
|
1136
|
+
for (const spec of feature.specs) {
|
|
1137
|
+
lines.push(`- ${spec.funcId}: ${cut(spec.text, 200)}`);
|
|
1138
|
+
if (scenarioChars !== undefined)
|
|
1139
|
+
for (const scenario of [...spec.conformance, ...spec.acceptance])
|
|
1140
|
+
lines.push(` - scenario ${scenario.id}: ${cut(scenario.text, scenarioChars)}`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return lines.join("\n");
|
|
1144
|
+
};
|
|
1145
|
+
for (const chars of [400, 160, 60]) {
|
|
1146
|
+
const listed = render(chars);
|
|
1147
|
+
if (listed.length <= budget)
|
|
1148
|
+
return listed;
|
|
1149
|
+
}
|
|
1150
|
+
return render(undefined);
|
|
1151
|
+
}
|
|
1152
|
+
/** What trying some scenarios on the original found, in a line: `22 held, 2 corrected, 1 removed`. */
|
|
1153
|
+
function trialSummary(results) {
|
|
1154
|
+
const outcomes = [
|
|
1155
|
+
["held", "held"],
|
|
1156
|
+
["corrected", "corrected"],
|
|
1157
|
+
["removed", "removed"],
|
|
1158
|
+
["untried", "not tried"],
|
|
1159
|
+
];
|
|
1160
|
+
return outcomes
|
|
1161
|
+
.map(([outcome, said]) => [results.filter((result) => result.outcome === outcome).length, said])
|
|
1162
|
+
.filter(([count]) => count > 0)
|
|
1163
|
+
.map(([count, said]) => `${count} ${said}`)
|
|
1164
|
+
.join(", ");
|
|
1165
|
+
}
|
|
1166
|
+
/** How many test names of one file a writer is shown. */
|
|
1167
|
+
const TESTS_LISTED = 15;
|
|
1168
|
+
/**
|
|
1169
|
+
* The original's tests in a feature's files, for its writer: how many lines each holds and what they are called - where
|
|
1170
|
+
* its scenarios go - and how many scenarios it may write, more the more the original tests it.
|
|
1171
|
+
*/
|
|
1172
|
+
export function testsBlock(evidence, budget) {
|
|
1173
|
+
const lines = evidence.reduce((sum, file) => sum + file.lines, 0);
|
|
1174
|
+
const files = evidence.map((file) => {
|
|
1175
|
+
const names = file.tests.slice(0, TESTS_LISTED).join(", ");
|
|
1176
|
+
const more = file.tests.length > TESTS_LISTED ? `, and ${file.tests.length - TESTS_LISTED} more` : "";
|
|
1177
|
+
return `- ${file.path} - ${file.lines} lines: ${names}${more}`;
|
|
1178
|
+
});
|
|
1179
|
+
return [
|
|
1180
|
+
"<the original's tests>",
|
|
1181
|
+
evidence.length === 0
|
|
1182
|
+
? `No file of your feature is a test of the original - its tests may be elsewhere: grep for what it does. You may write up to ${budget} scenarios.`
|
|
1183
|
+
: `The original tests your feature's files in ${lines} lines - you may write up to ${budget} scenarios, the most where these are densest:`,
|
|
1184
|
+
...files,
|
|
1185
|
+
"</the original's tests>",
|
|
1186
|
+
].join("\n");
|
|
1187
|
+
}
|
|
1188
|
+
function readabilityContext(module, shared, specs, stack) {
|
|
1189
|
+
return [
|
|
1190
|
+
stack,
|
|
1191
|
+
`<definitions>\n${[...shared, ...module.definitions].map((definition) => `- ${definition.text}`).join("\n") || "None."}\n</definitions>`,
|
|
1192
|
+
`<functional specs of ${module.name}>\n${specs.map((spec) => `# ${spec.funcId}\n${spec.text}${scenariosOf(spec)}`).join("\n\n")}\n</functional specs of ${module.name}>`,
|
|
1193
|
+
].join("\n\n");
|
|
1194
|
+
}
|
|
1195
|
+
/** A functional spec's scenarios, under it, for the readability pass: what they pin, its text need not say. */
|
|
1196
|
+
function scenariosOf(spec) {
|
|
1197
|
+
const lines = [...spec.conformance.map((scenario) => `- conformance ${scenario.id}: ${scenario.text}`), ...spec.acceptance.map((scenario) => `- acceptance ${scenario.id}: ${scenario.text}`)];
|
|
1198
|
+
return lines.length === 0 ? "" : `\n<scenarios of ${spec.funcId}>\n${lines.join("\n")}\n</scenarios of ${spec.funcId}>`;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* What a part is built on, as a writer is told it: the standard library's templates it imports - the stack, its kind's
|
|
1202
|
+
* common one, its language's - in full, and its own implementation reqs. All of it is the default: what the code does
|
|
1203
|
+
* because of it is never restated.
|
|
1204
|
+
*/
|
|
1205
|
+
export function stackBlock(part) {
|
|
1206
|
+
const templates = new Map(stdlibTemplates().map((template) => [template.name, template]));
|
|
1207
|
+
const imported = [];
|
|
1208
|
+
const visit = (name) => {
|
|
1209
|
+
const template = templates.get(name);
|
|
1210
|
+
if (template === undefined || imported.includes(name) || name.includes("/conformance/"))
|
|
1211
|
+
return;
|
|
1212
|
+
for (const below of template.imports)
|
|
1213
|
+
visit(below);
|
|
1214
|
+
imported.push(name);
|
|
1215
|
+
};
|
|
1216
|
+
if (part.stdlibStack !== undefined)
|
|
1217
|
+
visit(part.stdlibStack);
|
|
1218
|
+
return [
|
|
1219
|
+
"<stack>",
|
|
1220
|
+
...(imported.length > 0 ? ["Built on turri's standard library - what these say the code does is settled already: never write it again.", ""] : []),
|
|
1221
|
+
...imported.flatMap((name) => [`### ${name}`, templates.get(name).text, ""]),
|
|
1222
|
+
...(part.implementationReqs.length > 0 ? ["### The part's own implementation reqs", ...part.implementationReqs.map((req) => `- ${req}`), ""] : []),
|
|
1223
|
+
...((part.conventions ?? []).length > 0
|
|
1224
|
+
? ["### The part's conventions - settled from its code: every functional spec and scenario follows them, and none decides them again", ...part.conventions.map((convention) => `- ${convention.text}`)]
|
|
1225
|
+
: []),
|
|
1226
|
+
"</stack>",
|
|
1227
|
+
].join("\n");
|
|
1228
|
+
}
|