iterate-plugin 3.11.0 → 3.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ /**
2
+ * src/tools/preflight.ts — `iterate_preflight` tool.
3
+ *
4
+ * Answers one question BEFORE a run starts: "is this project ready to iterate
5
+ * safely, and what must be fixed first?" It reads only local state (config,
6
+ * git, persisted artifacts, checkpoint) and returns a structured checklist the
7
+ * observatory renders as a preflight panel (F11).
8
+ *
9
+ * Why it exists: the most expensive failure mode is starting a run that cannot
10
+ * prove anything — an empty `validation.commands` means the loop has no way to
11
+ * tell a fix from a regression, and a stale FAIL certificate or a leftover
12
+ * interrupted checkpoint makes the first round lie about its starting state.
13
+ * Preflight surfaces those conditions before the model spends a round
14
+ * discovering them mid-flight.
15
+ *
16
+ * Read-only: never mutates config, files, or artifacts.
17
+ */
18
+ import { defineTool } from '@deepseek-ai/dsh-tools';
19
+ import { resolveProjectRootForExec, loadEffectiveConfig, flattenCommands } from "../config-loader.js";
20
+ import { runGit } from "../git-scope.js";
21
+ import { readQualityGate } from "./quality-store.js";
22
+ import { readCheckpoint, computeStatus } from "./checkpoint.js";
23
+ import { readDecisionEntries } from "./decision-log.js";
24
+ import { readRegistry } from "./fix.js";
25
+ import { resultHeadline } from "./present.js";
26
+ import { detectValidationCommands } from "../validation-detect.js";
27
+ /**
28
+ * Build the readiness checklist from already-gathered facts (pure).
29
+ *
30
+ * The five checks and why each exists:
31
+ * 1. `validation` — empty command set ⇒ the loop cannot prove a
32
+ * fix; the product is fail-closed here, so this
33
+ * is a BLOCKING `fail`, not a warning.
34
+ * 2. `git` — changed-only scope + `iterate_diff` need a
35
+ * repository; full-scope review still works, so
36
+ * absent is a `warn`.
37
+ * 3. `dirty-tree` — a run over uncommitted work mixes the user's
38
+ * WIP with the plugin's fixes; advisory `warn`.
39
+ * Unknown (null) is treated as pass so a git
40
+ * hiccup never fabricates a warning.
41
+ * 4. `stale-gate` — a persisted FAIL certificate makes the first
42
+ * round read stale; `warn` + clear before a
43
+ * fresh run.
44
+ * 5. `interrupted-checkpoint`— a leftover checkpoint from a run that never
45
+ * progressed; `warn` + resume or clear.
46
+ */
47
+ export function buildPreflightReport(input) {
48
+ const suggestions = Array.isArray(input.suggestedCommands) ? input.suggestedCommands.filter((c) => typeof c === 'string' && c.length > 0) : [];
49
+ const checks = [
50
+ {
51
+ id: 'validation',
52
+ status: input.validationCommandCount > 0 ? 'pass' : 'fail',
53
+ detail: {
54
+ commandCount: input.validationCommandCount,
55
+ // Only meaningful when the blocking case is hit; the client turns these
56
+ // into a one-click "apply detected commands" action.
57
+ ...(input.validationCommandCount === 0 && suggestions.length > 0
58
+ ? {
59
+ suggestedCommands: suggestions,
60
+ ecosystem: input.ecosystem ?? null,
61
+ detectedFrom: Array.isArray(input.detectedFrom) ? input.detectedFrom : [],
62
+ }
63
+ : {}),
64
+ },
65
+ },
66
+ {
67
+ id: 'git',
68
+ status: input.isGitRepo ? 'pass' : 'warn',
69
+ detail: { isRepo: input.isGitRepo },
70
+ },
71
+ {
72
+ id: 'dirty-tree',
73
+ status: input.changedFiles !== null && input.changedFiles > 0 ? 'warn' : 'pass',
74
+ detail: { changedFiles: input.changedFiles },
75
+ },
76
+ {
77
+ id: 'stale-gate',
78
+ status: input.gateOverallStatus === 'fail' ? 'warn' : 'pass',
79
+ detail: { overallStatus: input.gateOverallStatus },
80
+ },
81
+ {
82
+ id: 'interrupted-checkpoint',
83
+ status: input.interrupted ? 'warn' : 'pass',
84
+ detail: { interrupted: input.interrupted, resumeCount: input.resumeCount },
85
+ },
86
+ ];
87
+ const blocking = checks.filter((c) => c.status === 'fail').length;
88
+ const warnings = checks.filter((c) => c.status === 'warn').length;
89
+ return { ok: true, ready: blocking === 0, blocking, warnings, checks };
90
+ }
91
+ /** Human-readable (English, for the model-facing render) description per check. */
92
+ function describeCheck(id, detail) {
93
+ switch (id) {
94
+ case 'validation': {
95
+ const n = Number(detail.commandCount ?? 0);
96
+ if (n > 0)
97
+ return `${n} validation command(s) configured`;
98
+ const suggested = Array.isArray(detail.suggestedCommands)
99
+ ? detail.suggestedCommands.map((c) => String(c))
100
+ : [];
101
+ if (suggested.length > 0) {
102
+ return ('no validation.commands configured — the run cannot prove fixes (blocking); ' +
103
+ `detected ${String(detail.ecosystem ?? 'project')} commands: ${suggested.join(', ')}`);
104
+ }
105
+ return 'no validation.commands configured — the run cannot prove fixes (blocking)';
106
+ }
107
+ case 'git':
108
+ return detail.isRepo === true
109
+ ? 'git repository detected'
110
+ : 'not a git repository — changed-only scope and iterate_diff need one';
111
+ case 'dirty-tree': {
112
+ const n = detail.changedFiles;
113
+ if (n === null || n === undefined)
114
+ return 'uncommitted changes: unknown';
115
+ const num = Number(n);
116
+ return num > 0
117
+ ? `${num} uncommitted/untracked file(s) — commit or stash before a run`
118
+ : 'working tree clean';
119
+ }
120
+ case 'stale-gate': {
121
+ const s = detail.overallStatus;
122
+ if (s === 'fail')
123
+ return 'a stale FAIL quality gate is persisted — clear it before a fresh run';
124
+ return s ? `quality gate: ${String(s)}` : 'no persisted quality gate';
125
+ }
126
+ case 'interrupted-checkpoint': {
127
+ if (detail.interrupted === true) {
128
+ const rc = Number(detail.resumeCount ?? 0);
129
+ return `an interrupted checkpoint is waiting (resumed ${rc}x) — resume or clear it`;
130
+ }
131
+ return 'no interrupted checkpoint';
132
+ }
133
+ default:
134
+ return '';
135
+ }
136
+ }
137
+ /**
138
+ * Register the `iterate_preflight` tool.
139
+ */
140
+ export function registerPreflightTool(ctx) {
141
+ ctx.tools.register(defineTool({
142
+ name: 'iterate_preflight',
143
+ // Pure read of on-disk state + git → safe to join a parallel group.
144
+ isConcurrencySafe: () => true,
145
+ presentResult: (_args, result) => {
146
+ const title = resultHeadline(result);
147
+ return title ? { card: 'generic', title } : undefined;
148
+ },
149
+ description: 'Read-only readiness check to run BEFORE starting an iterate run. Returns a checklist: whether ' +
150
+ 'validation.commands is configured (an empty set means the loop cannot prove fixes — blocking), ' +
151
+ 'whether the project is a git repository, how many files are uncommitted, whether a stale FAIL ' +
152
+ 'quality gate is persisted, and whether an interrupted checkpoint is waiting. Use it before a fresh ' +
153
+ 'run so you fix the environment first instead of discovering it mid-round.',
154
+ parameters: {
155
+ path: { type: 'string', description: 'Project root directory (default: current working directory).' },
156
+ },
157
+ output: {
158
+ schema: {
159
+ type: 'object',
160
+ additionalProperties: false,
161
+ properties: {
162
+ ok: { type: 'boolean', required: true },
163
+ ready: { type: 'boolean' },
164
+ blocking: { type: 'integer' },
165
+ warnings: { type: 'integer' },
166
+ checks: { type: 'json', description: 'Per-check outcomes: { id, status: pass|warn|fail, detail }.' },
167
+ error: { type: 'string' },
168
+ },
169
+ },
170
+ render: (_args, value) => {
171
+ if (!value.ok)
172
+ return [{ type: 'text', text: `preflight failed: ${value.error}` }];
173
+ const checks = Array.isArray(value.checks) ? value.checks : [];
174
+ const warnings = Number(value.warnings ?? 0);
175
+ const noun = warnings === 1 ? 'warning' : 'warnings';
176
+ const head = value.ready
177
+ ? `Preflight: READY (${Number(value.blocking ?? 0)} blocking, ${warnings} ${noun})`
178
+ : `Preflight: NOT READY (${Number(value.blocking ?? 0)} blocking, ${warnings} ${noun})`;
179
+ const lines = checks.map((c) => {
180
+ const check = c;
181
+ const id = String(check.id ?? '?');
182
+ const status = String(check.status ?? '?').toUpperCase();
183
+ return ` ${status} ${id} — ${describeCheck(id, check.detail ?? {})}`;
184
+ });
185
+ return [{ type: 'text', text: [head, ...lines].join('\n') }];
186
+ },
187
+ },
188
+ async execute(args, exec) {
189
+ const resolved = resolveProjectRootForExec(exec, args.path);
190
+ if (!resolved.ok) {
191
+ return { ok: false, ready: false, blocking: 0, warnings: 0, checks: [], error: resolved.reason };
192
+ }
193
+ const projectRoot = resolved.root;
194
+ // 1. validation.commands — the load-bearing check.
195
+ let validationCommandCount = 0;
196
+ try {
197
+ const effective = loadEffectiveConfig(projectRoot);
198
+ validationCommandCount = flattenCommands(effective.config.validation?.commands).length;
199
+ }
200
+ catch {
201
+ validationCommandCount = 0;
202
+ }
203
+ // 1b. When nothing is configured, inspect the project manifest so the
204
+ // blocking check ships with an actionable, ready-to-apply set.
205
+ let suggestedCommands = [];
206
+ let detectedEcosystem = null;
207
+ let detectedFrom = [];
208
+ if (validationCommandCount === 0) {
209
+ try {
210
+ const detection = detectValidationCommands(projectRoot);
211
+ suggestedCommands = detection.commands;
212
+ detectedEcosystem = detection.ecosystem;
213
+ detectedFrom = detection.sources.map((s) => s.file);
214
+ }
215
+ catch {
216
+ suggestedCommands = [];
217
+ detectedEcosystem = null;
218
+ detectedFrom = [];
219
+ }
220
+ }
221
+ // 2/3. git repo + dirty tree (best-effort; any failure degrades to unknown).
222
+ let isGitRepo = false;
223
+ let changedFiles = null;
224
+ try {
225
+ const inside = await runGit(['rev-parse', '--is-inside-work-tree'], projectRoot, { signal: exec.signal });
226
+ isGitRepo = inside.ok && inside.stdout.trim() === 'true';
227
+ if (isGitRepo) {
228
+ const status = await runGit(['status', '--porcelain', '-z'], projectRoot, { signal: exec.signal });
229
+ if (status.ok) {
230
+ // `-z` NUL-terminates each entry; a rename emits two NUL-separated
231
+ // paths for one entry, but counting non-empty tokens is still a
232
+ // faithful "there is uncommitted work" signal (>=1 when dirty).
233
+ changedFiles = status.stdout.split('\u0000').filter((s) => s.length > 0).length;
234
+ }
235
+ }
236
+ }
237
+ catch {
238
+ isGitRepo = false;
239
+ changedFiles = null;
240
+ }
241
+ // 4. stale quality gate.
242
+ let gateOverallStatus = null;
243
+ try {
244
+ gateOverallStatus = readQualityGate(projectRoot).overallStatus ?? null;
245
+ }
246
+ catch {
247
+ gateOverallStatus = null;
248
+ }
249
+ // 5. interrupted checkpoint (reuse the exact status logic so preflight
250
+ // and iterate_status can never disagree about "interrupted").
251
+ let interrupted = false;
252
+ let resumeCount = 0;
253
+ try {
254
+ const status = computeStatus({
255
+ checkpoint: readCheckpoint(projectRoot),
256
+ decisionEntries: readDecisionEntries(projectRoot),
257
+ fixRegistry: readRegistry(projectRoot),
258
+ });
259
+ interrupted = status.interrupted;
260
+ resumeCount = status.resumeCount;
261
+ }
262
+ catch {
263
+ interrupted = false;
264
+ resumeCount = 0;
265
+ }
266
+ const report = buildPreflightReport({
267
+ validationCommandCount,
268
+ isGitRepo,
269
+ changedFiles,
270
+ gateOverallStatus,
271
+ interrupted,
272
+ resumeCount,
273
+ suggestedCommands,
274
+ ecosystem: detectedEcosystem,
275
+ detectedFrom,
276
+ });
277
+ return { ...report, checks: report.checks };
278
+ },
279
+ }));
280
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * src/validation-detect.ts — detect a project's validation commands.
3
+ *
4
+ * Why it exists: the iterate loop is fail-closed on `validation.commands` — an
5
+ * empty set means it cannot tell a fix from a regression, so `iterate_preflight`
6
+ * blocks the run. Until now the only remedy was to hand-write the YAML, which is
7
+ * error-prone (wrong nesting, wrong module key, commands the project does not
8
+ * actually expose). This module inspects the project's own manifest files and
9
+ * proposes a small, curated command set that the config tool can apply in one
10
+ * call.
11
+ *
12
+ * Detection is advisory and read-only: it only proposes commands the project's
13
+ * manifest actually advertises (package.json scripts, pytest/ruff/mypy config,
14
+ * Cargo, Go, Make targets). It never invents a command and never executes one.
15
+ */
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ /** Hard cap so a project with many scripts cannot flood the config. */
19
+ const MAX_COMMANDS = 6;
20
+ function readText(path) {
21
+ try {
22
+ return readFileSync(path, 'utf-8');
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ function readJsonObject(path) {
29
+ const text = readText(path);
30
+ if (text === null)
31
+ return null;
32
+ try {
33
+ const parsed = JSON.parse(text);
34
+ // A JSON array / scalar is not a manifest object — treat it as absent.
35
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
36
+ ? parsed
37
+ : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ function existsFile(root, name) {
44
+ try {
45
+ return existsSync(join(root, name));
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ function asRecord(value) {
52
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
53
+ ? value
54
+ : {};
55
+ }
56
+ /** Node: only scripts the manifest explicitly defines, in a curated order. */
57
+ function detectNode(root, add) {
58
+ const pkg = readJsonObject(join(root, 'package.json'));
59
+ if (!pkg)
60
+ return false;
61
+ const scripts = asRecord(pkg.scripts);
62
+ const has = (name) => typeof scripts[name] === 'string' && scripts[name].trim().length > 0;
63
+ // test/typecheck/lint/build are the four signals that actually prove a change
64
+ // is sound. Arbitrary user scripts are intentionally NOT auto-run.
65
+ if (has('test'))
66
+ add('npm test', 'package.json', 'scripts.test');
67
+ if (has('typecheck'))
68
+ add('npm run typecheck', 'package.json', 'scripts.typecheck');
69
+ if (has('lint'))
70
+ add('npm run lint', 'package.json', 'scripts.lint');
71
+ if (has('build'))
72
+ add('npm run build', 'package.json', 'scripts.build');
73
+ return true;
74
+ }
75
+ /** Python: pytest plus configured ruff / mypy. A bare pyproject is not pytest. */
76
+ function detectPython(root, add) {
77
+ const pyproject = readText(join(root, 'pyproject.toml'));
78
+ const setupCfg = readText(join(root, 'setup.cfg'));
79
+ const pytestIni = existsFile(root, 'pytest.ini');
80
+ const toxIni = existsFile(root, 'tox.ini');
81
+ const testsDir = existsFile(root, 'tests');
82
+ const pyprojectPytest = pyproject !== null && /\[tool\.pytest/.test(pyproject);
83
+ const setupCfgPytest = setupCfg !== null && /\[tool:pytest\]/.test(setupCfg);
84
+ const matched = pyproject !== null || setupCfg !== null || pytestIni || toxIni || testsDir;
85
+ if (!matched)
86
+ return false;
87
+ if (pytestIni)
88
+ add('pytest -q', 'pytest.ini', 'pytest');
89
+ else if (toxIni)
90
+ add('pytest -q', 'tox.ini', 'pytest');
91
+ else if (pyprojectPytest)
92
+ add('pytest -q', 'pyproject.toml', 'tool.pytest');
93
+ else if (setupCfgPytest)
94
+ add('pytest -q', 'setup.cfg', 'tool:pytest');
95
+ else if (testsDir)
96
+ add('pytest -q', 'tests', 'tests-dir');
97
+ if (pyproject !== null && /\[tool\.ruff/.test(pyproject))
98
+ add('ruff check .', 'pyproject.toml', 'tool.ruff');
99
+ if (pyproject !== null && /\[tool\.mypy\]/.test(pyproject))
100
+ add('mypy .', 'pyproject.toml', 'tool.mypy');
101
+ return true;
102
+ }
103
+ /** Rust: cargo test, plus clippy/rustfmt when the project configures them. */
104
+ function detectRust(root, add) {
105
+ if (!existsFile(root, 'Cargo.toml'))
106
+ return false;
107
+ add('cargo test', 'Cargo.toml', 'cargo.test');
108
+ if (existsFile(root, 'clippy.toml') || existsFile(root, '.clippy.toml')) {
109
+ add('cargo clippy --all-targets -- -D warnings', 'clippy.toml', 'cargo.clippy');
110
+ }
111
+ if (existsFile(root, 'rustfmt.toml') || existsFile(root, '.rustfmt.toml')) {
112
+ add('cargo fmt --check', 'rustfmt.toml', 'cargo.fmt');
113
+ }
114
+ return true;
115
+ }
116
+ /** Go: test + vet are the two checks a go module always supports. */
117
+ function detectGo(root, add) {
118
+ if (!existsFile(root, 'go.mod'))
119
+ return false;
120
+ add('go test ./...', 'go.mod', 'go.test');
121
+ add('go vet ./...', 'go.mod', 'go.vet');
122
+ return true;
123
+ }
124
+ /** Make: the generic fallback, only when no ecosystem-specific command exists. */
125
+ function detectMake(root, add) {
126
+ const makefile = ['Makefile', 'makefile', 'GNUmakefile'].find((name) => existsFile(root, name));
127
+ if (!makefile)
128
+ return false;
129
+ const text = readText(join(root, makefile)) ?? '';
130
+ const targets = new Set();
131
+ for (const line of text.split(/\r?\n/)) {
132
+ // `target:`, but NOT a `VAR := value` / `VAR = value` assignment. The
133
+ // lookahead has to skip the optional space before `=` (`test := nope`).
134
+ const match = /^([A-Za-z0-9_.-]+)\s*:(?!=|\s*=)/.exec(line);
135
+ if (match)
136
+ targets.add(match[1]);
137
+ }
138
+ if (targets.has('test'))
139
+ add('make test', makefile, 'target.test');
140
+ if (targets.has('check'))
141
+ add('make check', makefile, 'target.check');
142
+ return true;
143
+ }
144
+ /**
145
+ * Inspect `projectRoot` and return a curated, ordered validation-command set.
146
+ *
147
+ * Never throws: unreadable or malformed manifests simply contribute nothing.
148
+ * The returned `commands` and `sources` always have the same length.
149
+ */
150
+ export function detectValidationCommands(projectRoot) {
151
+ const commands = [];
152
+ const sources = [];
153
+ const seen = new Set();
154
+ const add = (command, file, reason) => {
155
+ if (commands.length >= MAX_COMMANDS)
156
+ return;
157
+ if (seen.has(command))
158
+ return;
159
+ seen.add(command);
160
+ commands.push(command);
161
+ sources.push({ file, reason });
162
+ };
163
+ let ecosystem = null;
164
+ const run = (name, detect) => {
165
+ const before = commands.length;
166
+ let matched = false;
167
+ try {
168
+ matched = detect(add);
169
+ }
170
+ catch {
171
+ matched = false;
172
+ }
173
+ if (matched && commands.length > before && ecosystem === null)
174
+ ecosystem = name;
175
+ };
176
+ run('node', (a) => detectNode(projectRoot, a));
177
+ run('python', (a) => detectPython(projectRoot, a));
178
+ run('rust', (a) => detectRust(projectRoot, a));
179
+ run('go', (a) => detectGo(projectRoot, a));
180
+ // Make is the generic wrapper: only consult it when nothing else produced a
181
+ // command, so a Makefile that just calls `npm test` does not double-report.
182
+ if (commands.length === 0)
183
+ run('make', (a) => detectMake(projectRoot, a));
184
+ return { ecosystem, commands, sources };
185
+ }
186
+ /**
187
+ * Build the partial config update that installs a detected command set under
188
+ * the `default` module. The config tool deep-merges this into an existing
189
+ * `validation.commands` map, so other modules are preserved.
190
+ */
191
+ export function buildValidationUpdates(commands) {
192
+ return { validation: { commands: { default: [...commands] } } };
193
+ }