@planu/cli 5.7.13 → 5.7.15
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/CHANGELOG.md +26 -0
- package/README.md +3 -6
- package/dist/.planu-build.json +1 -1
- package/dist/config/negative-predicate-phrases.json +33 -0
- package/dist/config/runtime-policy.json +1 -1
- package/dist/engine/mcp-config/mcp-config-writer.d.ts +1 -0
- package/dist/engine/mcp-config/mcp-config-writer.js +11 -0
- package/dist/engine/spec-format/bdd-parser.d.ts +2 -0
- package/dist/engine/spec-format/bdd-parser.js +70 -4
- package/dist/engine/validator/analyzer.d.ts +0 -9
- package/dist/engine/validator/analyzer.js +33 -9
- package/dist/engine/validator/blast-radius-gate.js +86 -1
- package/dist/engine/validator/deep-code-checker.js +2 -5
- package/dist/engine/validator/negative-predicate.d.ts +18 -0
- package/dist/engine/validator/negative-predicate.js +240 -0
- package/dist/engine/validator/spec-compliance-runner.js +17 -2
- package/dist/storage/runtime-db.d.ts +1 -1
- package/dist/storage/runtime-db.js +15 -2
- package/dist/tools/create-spec.js +10 -0
- package/dist/tools/init-project/handler.js +3 -1
- package/dist/tools/jobs/handlers.d.ts +2 -1
- package/dist/tools/jobs/handlers.js +17 -3
- package/dist/tools/tool-registry/core-tools.js +28 -2
- package/dist/tools/update-status/evidence-gate.js +13 -1
- package/dist/tools/update-status/transition-guard.js +33 -9
- package/dist/tools/validate.js +14 -2
- package/dist/types/analysis.d.ts +20 -0
- package/dist/types/errors/structured-error.d.ts +1 -1
- package/dist/types/plugin-configs.d.ts +4 -0
- package/dist/types/spec/inputs.d.ts +14 -0
- package/dist/types/validation-evidence.d.ts +3 -1
- package/package.json +2 -1
- package/planu-plugin.json +1 -1
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { readFile, lstat, realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join, relative, sep } from 'node:path';
|
|
3
|
+
import { glob } from 'glob';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { ConfigLoader } from '../config-loader.js';
|
|
6
|
+
const NegativePredicatePhraseGroupSchema = z.object({
|
|
7
|
+
id: z.string().describe('Phrase group identifier (e.g. "deletion", "import-absence")'),
|
|
8
|
+
phrases: z
|
|
9
|
+
.array(z.string())
|
|
10
|
+
.describe('Lowercase phrases that mark a criterion as asserting absence'),
|
|
11
|
+
});
|
|
12
|
+
const NegativePredicatePhraseGroupArraySchema = z.array(NegativePredicatePhraseGroupSchema);
|
|
13
|
+
const loader = new ConfigLoader('negative-predicate-phrases', NegativePredicatePhraseGroupArraySchema);
|
|
14
|
+
export function loadNegativePredicatePhrases() {
|
|
15
|
+
return loader.load().flatMap((group) => group.phrases.map((phrase) => phrase.toLowerCase()));
|
|
16
|
+
}
|
|
17
|
+
export function matchesNegativePhrase(text) {
|
|
18
|
+
const lower = text.toLowerCase();
|
|
19
|
+
return loadNegativePredicatePhrases().some((phrase) => lower.includes(phrase));
|
|
20
|
+
}
|
|
21
|
+
const LEGACY_ABSENT_GROUP_ID = 'literal-absence';
|
|
22
|
+
export function matchesLegacyAbsentPhrase(text) {
|
|
23
|
+
const lower = text.toLowerCase();
|
|
24
|
+
return loader
|
|
25
|
+
.load()
|
|
26
|
+
.filter((group) => group.id === LEGACY_ABSENT_GROUP_ID)
|
|
27
|
+
.flatMap((group) => group.phrases.map((phrase) => phrase.toLowerCase()))
|
|
28
|
+
.some((phrase) => lower.includes(phrase));
|
|
29
|
+
}
|
|
30
|
+
const SLASH_JOINED_IDENTIFIER_PAIR = /^[A-Za-z_$][\w$]*(?:\/[A-Za-z_$][\w$]*)+$/;
|
|
31
|
+
const BARE_TOKEN_PATTERN = /(?:^|[\s(,])((?:@[\w.-]+\/)?[\w.@-]+(?:\/[\w.@*-]+)+)/g;
|
|
32
|
+
function normalizeToken(rawToken) {
|
|
33
|
+
return rawToken
|
|
34
|
+
.trim()
|
|
35
|
+
.replace(/[.,;:)]+$/, '')
|
|
36
|
+
.replace(/\*$/u, '');
|
|
37
|
+
}
|
|
38
|
+
function splitSlashJoinedIdentifiers(token) {
|
|
39
|
+
return SLASH_JOINED_IDENTIFIER_PAIR.test(token) ? token.split('/') : [token];
|
|
40
|
+
}
|
|
41
|
+
export function extractNegativeTokens(text) {
|
|
42
|
+
const rawTokens = [];
|
|
43
|
+
for (const match of text.matchAll(/`([^`]+)`/g)) {
|
|
44
|
+
rawTokens.push(match[1] ?? '');
|
|
45
|
+
}
|
|
46
|
+
for (const match of text.matchAll(/"([^"]+)"/g)) {
|
|
47
|
+
rawTokens.push(match[1] ?? '');
|
|
48
|
+
}
|
|
49
|
+
for (const match of text.matchAll(/'([^']+)'/g)) {
|
|
50
|
+
rawTokens.push(match[1] ?? '');
|
|
51
|
+
}
|
|
52
|
+
for (const match of text.matchAll(BARE_TOKEN_PATTERN)) {
|
|
53
|
+
rawTokens.push(match[1] ?? '');
|
|
54
|
+
}
|
|
55
|
+
const tokens = [];
|
|
56
|
+
const seen = new Set();
|
|
57
|
+
for (const raw of rawTokens) {
|
|
58
|
+
const normalized = normalizeToken(raw);
|
|
59
|
+
for (const token of splitSlashJoinedIdentifiers(normalized)) {
|
|
60
|
+
if (token.length < 3 || seen.has(token)) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
seen.add(token);
|
|
64
|
+
tokens.push(token);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return tokens;
|
|
68
|
+
}
|
|
69
|
+
export function isPathShaped(token) {
|
|
70
|
+
return (token.includes('/') &&
|
|
71
|
+
!token.includes('*') &&
|
|
72
|
+
!/\s/.test(token) &&
|
|
73
|
+
!token.includes('\\') &&
|
|
74
|
+
!token.startsWith('/') &&
|
|
75
|
+
!token.startsWith('@') &&
|
|
76
|
+
!token.split('/').includes('..'));
|
|
77
|
+
}
|
|
78
|
+
export function classifyNegativePredicate(text) {
|
|
79
|
+
const tokens = extractNegativeTokens(text);
|
|
80
|
+
return { isNegative: matchesNegativePhrase(text) && tokens.length > 0, tokens };
|
|
81
|
+
}
|
|
82
|
+
export const NEGATIVE_TOKEN_SCOPE = [
|
|
83
|
+
'src/**/*.{ts,tsx,mts,cts,js,mjs,cjs,jsx,json}',
|
|
84
|
+
'scripts/**/*.{ts,mts,cts,js,mjs,cjs,sh,json}',
|
|
85
|
+
'**/package.json',
|
|
86
|
+
'pnpm-workspace.yaml',
|
|
87
|
+
'tsconfig*.json',
|
|
88
|
+
];
|
|
89
|
+
export const NEGATIVE_SCAN_IGNORE = [
|
|
90
|
+
'**/node_modules/**',
|
|
91
|
+
'**/dist/**',
|
|
92
|
+
'**/build/**',
|
|
93
|
+
'**/coverage/**',
|
|
94
|
+
'**/.vitepress/cache/**',
|
|
95
|
+
'.git/**',
|
|
96
|
+
'planu/**',
|
|
97
|
+
'.planu/**',
|
|
98
|
+
'.worktrees/**',
|
|
99
|
+
];
|
|
100
|
+
export const NEGATIVE_SCAN_FILE_LIMIT = 5000;
|
|
101
|
+
function isOutside(root, candidate) {
|
|
102
|
+
const pathFromRoot = relative(root, candidate);
|
|
103
|
+
return pathFromRoot === '..' || pathFromRoot.startsWith(`..${sep}`) || isAbsolute(pathFromRoot);
|
|
104
|
+
}
|
|
105
|
+
async function projectEntryExists(projectPath, token) {
|
|
106
|
+
const candidate = join(projectPath, token);
|
|
107
|
+
try {
|
|
108
|
+
await lstat(candidate);
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
const code = err.code;
|
|
112
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') {
|
|
113
|
+
return { status: 'absent' };
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
status: 'unverifiable',
|
|
117
|
+
evidence: `scan-unreadable: ${token} could not be stat'd — absence cannot be verified`,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const [rootReal, parentReal] = await Promise.all([
|
|
122
|
+
realpath(projectPath),
|
|
123
|
+
realpath(dirname(candidate)),
|
|
124
|
+
]);
|
|
125
|
+
if (isOutside(rootReal, parentReal)) {
|
|
126
|
+
return {
|
|
127
|
+
status: 'unverifiable',
|
|
128
|
+
evidence: `scan-escaped: ${token} resolves outside the project — absence cannot be verified`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
return { status: 'present' };
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return {
|
|
135
|
+
status: 'unverifiable',
|
|
136
|
+
evidence: `scan-unreadable: ${token} could not be resolved — absence cannot be verified`,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function scanContentHits(files, tokens, projectPath, signal) {
|
|
141
|
+
const contentHits = [];
|
|
142
|
+
for (const relPath of files) {
|
|
143
|
+
signal?.throwIfAborted();
|
|
144
|
+
let content;
|
|
145
|
+
try {
|
|
146
|
+
content = await readFile(join(projectPath, relPath), 'utf-8');
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return {
|
|
150
|
+
ok: false,
|
|
151
|
+
result: {
|
|
152
|
+
met: false,
|
|
153
|
+
unverifiable: true,
|
|
154
|
+
evidence: [`scan-unreadable: ${relPath} could not be read — absence cannot be verified`],
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
for (const token of tokens) {
|
|
159
|
+
const index = content.indexOf(token);
|
|
160
|
+
if (index !== -1) {
|
|
161
|
+
const line = content.slice(0, index).split('\n').length;
|
|
162
|
+
contentHits.push(`\`${token}\`: still present at ${relPath}:${line}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { ok: true, hits: contentHits };
|
|
167
|
+
}
|
|
168
|
+
async function scanPathHits(tokens, projectPath) {
|
|
169
|
+
const pathHits = [];
|
|
170
|
+
for (const token of tokens) {
|
|
171
|
+
if (!isPathShaped(token)) {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const entry = await projectEntryExists(projectPath, token);
|
|
175
|
+
if (entry.status === 'unverifiable') {
|
|
176
|
+
return {
|
|
177
|
+
ok: false,
|
|
178
|
+
result: { met: false, unverifiable: true, evidence: [entry.evidence] },
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (entry.status === 'present') {
|
|
182
|
+
pathHits.push(`\`${token}\`: still present as project entry ${token}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { ok: true, hits: pathHits };
|
|
186
|
+
}
|
|
187
|
+
export async function checkTokensAbsent(tokens, projectPath, options) {
|
|
188
|
+
if (tokens.length === 0) {
|
|
189
|
+
return {
|
|
190
|
+
met: false,
|
|
191
|
+
unverifiable: true,
|
|
192
|
+
evidence: ['no tokens extracted — absence cannot be verified'],
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
const fileLimit = options?.fileLimit ?? NEGATIVE_SCAN_FILE_LIMIT;
|
|
196
|
+
let files;
|
|
197
|
+
try {
|
|
198
|
+
files = await glob([...NEGATIVE_TOKEN_SCOPE], {
|
|
199
|
+
cwd: projectPath,
|
|
200
|
+
nodir: true,
|
|
201
|
+
ignore: [...NEGATIVE_SCAN_IGNORE],
|
|
202
|
+
signal: options?.signal,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return {
|
|
207
|
+
met: false,
|
|
208
|
+
unverifiable: true,
|
|
209
|
+
evidence: [
|
|
210
|
+
'scan-error: glob failed over the negative-token scope — absence cannot be verified',
|
|
211
|
+
],
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
if (files.length > fileLimit) {
|
|
215
|
+
return {
|
|
216
|
+
met: false,
|
|
217
|
+
unverifiable: true,
|
|
218
|
+
evidence: [
|
|
219
|
+
`scan-truncated: ${files.length} files exceed the ${fileLimit}-file scan limit — absence cannot be verified`,
|
|
220
|
+
],
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const contentScan = await scanContentHits(files, tokens, projectPath, options?.signal);
|
|
224
|
+
if (!contentScan.ok) {
|
|
225
|
+
return contentScan.result;
|
|
226
|
+
}
|
|
227
|
+
const pathScan = await scanPathHits(tokens, projectPath);
|
|
228
|
+
if (!pathScan.ok) {
|
|
229
|
+
return pathScan.result;
|
|
230
|
+
}
|
|
231
|
+
const hits = [...contentScan.hits, ...pathScan.hits];
|
|
232
|
+
const met = hits.length === 0;
|
|
233
|
+
const evidence = met
|
|
234
|
+
? tokens.map((token) => isPathShaped(token)
|
|
235
|
+
? `\`${token}\`: absent — 0 matches in ${files.length} scanned files, and no project entry`
|
|
236
|
+
: `\`${token}\`: absent — 0 matches in ${files.length} scanned files`)
|
|
237
|
+
: hits;
|
|
238
|
+
return { met, unverifiable: false, evidence };
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=negative-predicate.js.map
|
|
@@ -10,6 +10,7 @@ import { readEvidenceArtifacts, traceabilityRowHasCurrentCommandEvidence, } from
|
|
|
10
10
|
import { normalizeCriterionText } from '../criterion-identity.js';
|
|
11
11
|
import { isExecutableTestPath } from '../spec-format/executable-test-path.js';
|
|
12
12
|
import { normalizeExecutableEvidence } from './executable-evidence.js';
|
|
13
|
+
import { classifyNegativePredicate, checkTokensAbsent } from './negative-predicate.js';
|
|
13
14
|
/** A sanitized terminal adapter failure that cannot be mistaken for a failed test verdict. */
|
|
14
15
|
export class ComplianceCommandTerminalError extends Error {
|
|
15
16
|
code;
|
|
@@ -612,8 +613,22 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
|
|
|
612
613
|
}
|
|
613
614
|
return `${technologyValue('technology-vitest-a9127f')} --reporter=json --run ${links.map((link) => link.path).join(' ')}`;
|
|
614
615
|
});
|
|
615
|
-
const scenarioResults = scenarios.map((scenario) => {
|
|
616
|
+
const scenarioResults = await Promise.all(scenarios.map(async (scenario) => {
|
|
616
617
|
if (!scenario.tests?.length) {
|
|
618
|
+
const criterion = canonicalScenarioCriterion(scenario);
|
|
619
|
+
const negative = criterion
|
|
620
|
+
? classifyNegativePredicate(criterion)
|
|
621
|
+
: { isNegative: false, tokens: [] };
|
|
622
|
+
if (negative.isNegative) {
|
|
623
|
+
const absence = await checkTokensAbsent(negative.tokens, projectPath, { signal });
|
|
624
|
+
return {
|
|
625
|
+
title: scenario.title,
|
|
626
|
+
verdict: absence.met ? 'pass' : 'missing',
|
|
627
|
+
evidence: absence.evidence,
|
|
628
|
+
linkVerdicts: [],
|
|
629
|
+
...(absence.unverifiable ? { unverifiable: true } : {}),
|
|
630
|
+
};
|
|
631
|
+
}
|
|
617
632
|
return {
|
|
618
633
|
title: scenario.title,
|
|
619
634
|
verdict: 'missing',
|
|
@@ -668,7 +683,7 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
|
|
|
668
683
|
linkVerdicts: verdicts,
|
|
669
684
|
...(unverifiable ? { unverifiable: true } : {}),
|
|
670
685
|
};
|
|
671
|
-
});
|
|
686
|
+
}));
|
|
672
687
|
const perScenario = scenarioResults.map(({ linkVerdicts: _linkVerdicts, ...scenario }) => scenario);
|
|
673
688
|
const passCount = perScenario.filter((scenario) => scenario.verdict === 'pass').length;
|
|
674
689
|
const indeterminateCount = perScenario.filter((scenario) => scenario.verdict === 'indeterminate').length;
|
|
@@ -84,7 +84,6 @@ export declare class RuntimeSchemaAheadError extends Error {
|
|
|
84
84
|
readonly code: 'RUNTIME_SCHEMA_AHEAD';
|
|
85
85
|
constructor(storeSchema: number, supportedSchema: number);
|
|
86
86
|
}
|
|
87
|
-
/** A bounded (one connection), transactional SQLite runtime store. */
|
|
88
87
|
export declare class RuntimeDatabase implements Disposable {
|
|
89
88
|
readonly path: string;
|
|
90
89
|
readonly schemaVersion = 5;
|
|
@@ -139,6 +138,7 @@ export declare class RuntimeDatabase implements Disposable {
|
|
|
139
138
|
restartReceiptPublication(projectId: string, workspaceId: string, id: string, limits: ValidationReceiptCheckpointLimits): DurableJobRecord;
|
|
140
139
|
restartJobWithPayload(projectId: string, workspaceId: string, id: string, payload: unknown): DurableJobRecord;
|
|
141
140
|
cancelJob(projectId: string, workspaceId: string, id: string): DurableJobRecord;
|
|
141
|
+
private notRestartableError;
|
|
142
142
|
private assertRestartCeiling;
|
|
143
143
|
private freshRestartDeadline;
|
|
144
144
|
private archiveCheckpointBeforeRestart;
|
|
@@ -109,6 +109,16 @@ function withFreshValidateDeadline(payload, deadlineAt) {
|
|
|
109
109
|
return { ...payload, deadlineAt };
|
|
110
110
|
}
|
|
111
111
|
/** A bounded (one connection), transactional SQLite runtime store. */
|
|
112
|
+
const RESTART_NEXT_ACTION = {
|
|
113
|
+
absent: 'no job exists under this operation id; submit the work again with validate or package_handoff',
|
|
114
|
+
running: 'wait for the current attempt to finish, poll get_job with the same operationId, then restart_job once it leaves running',
|
|
115
|
+
accepted: 'the job is already queued; poll get_job with the same operationId instead of restarting',
|
|
116
|
+
checkpointed: 'the job is already queued from its checkpoint; poll get_job with the same operationId',
|
|
117
|
+
cancelled: 'the run was cancelled; resubmit it with validate or package_handoff',
|
|
118
|
+
failed: 'restart_job is the correct verb here; re-read the row with get_job and retry',
|
|
119
|
+
'dead-letter': 'restart_job is the correct verb here; re-read the row with get_job and retry',
|
|
120
|
+
completed: 'the job already produced a result; read it with get_job, and only re-run validate if its inputs changed',
|
|
121
|
+
};
|
|
112
122
|
export class RuntimeDatabase {
|
|
113
123
|
path;
|
|
114
124
|
schemaVersion = CURRENT_SCHEMA_VERSION;
|
|
@@ -609,7 +619,7 @@ export class RuntimeDatabase {
|
|
|
609
619
|
const current = this.getJob(projectId, workspaceId, id);
|
|
610
620
|
if (!current ||
|
|
611
621
|
!['accepted', 'checkpointed', 'failed', 'dead-letter', 'cancelled', 'completed'].includes(current.state)) {
|
|
612
|
-
throw
|
|
622
|
+
throw this.notRestartableError('Job', id, current?.state ?? 'absent');
|
|
613
623
|
}
|
|
614
624
|
this.assertRestartCeiling(current, id);
|
|
615
625
|
const { now, deadlineAt } = this.freshRestartDeadline();
|
|
@@ -639,7 +649,7 @@ export class RuntimeDatabase {
|
|
|
639
649
|
!['failed', 'dead-letter'].includes(current.state) ||
|
|
640
650
|
current.cancelRequested ||
|
|
641
651
|
!parseValidationReceiptPendingCheckpoint(current.checkpoint, limits)) {
|
|
642
|
-
throw
|
|
652
|
+
throw this.notRestartableError('Job receipt publication', id, current?.state ?? 'absent');
|
|
643
653
|
}
|
|
644
654
|
this.assertRestartCeiling(current, id);
|
|
645
655
|
const { now, deadlineAt } = this.freshRestartDeadline();
|
|
@@ -710,6 +720,9 @@ export class RuntimeDatabase {
|
|
|
710
720
|
.run(now, projectId, workspaceId, id);
|
|
711
721
|
return requireJobRecord(this.getJob(projectId, workspaceId, id), id);
|
|
712
722
|
}
|
|
723
|
+
notRestartableError(subject, id, state) {
|
|
724
|
+
return new Error(`[Planu] ${subject} ${id}: ${subject === 'Job' ? 'not restartable' : 'receipt publication is not restartable'} in state ${state}: ${RESTART_NEXT_ACTION[state]}`);
|
|
725
|
+
}
|
|
713
726
|
assertRestartCeiling(current, id) {
|
|
714
727
|
if (current.restarts >= current.maxAttempts) {
|
|
715
728
|
throw new Error(`[Planu] Job ${id} was restarted ${String(current.restarts)} times (ceiling ${String(current.maxAttempts)}); the operation id is deterministic, so fix the failing run before submitting it again`);
|
|
@@ -21,6 +21,7 @@ import { extractFilesFromSpecBody, extractMarkerDeclaredPaths, } from '../engine
|
|
|
21
21
|
import { buildCanonicalUnifiedSpecContent, containsUnresolvedContractPlaceholder, validateUnifiedSpecCandidate, } from '../engine/spec-format/unified-spec-builder.js';
|
|
22
22
|
import { buildImplementationContractSection } from '../engine/implementation-contract/index.js';
|
|
23
23
|
import { updateFrontmatterField } from '../engine/frontmatter-parser.js';
|
|
24
|
+
import { parseBddScenarios, PLACEHOLDER_WHEN_STEP_TEXT } from '../engine/spec-format/bdd-parser.js';
|
|
24
25
|
import { resolveEnglishOnlySpecGate } from '../engine/spec-language/english-only.js';
|
|
25
26
|
import { FallbackGenerator } from '../engine/spec-generator/index.js';
|
|
26
27
|
import { analyzeProjectForSpec, getEmptyAutopilotResult, } from './create-spec/autopilot-analyzer.js';
|
|
@@ -1309,6 +1310,15 @@ async function prepareCreateSpecCandidate(initialParams, server) {
|
|
|
1309
1310
|
// candidate.
|
|
1310
1311
|
unifiedSpec = updateFrontmatterField(unifiedSpec, 'qualityWarnings', JSON.stringify(spec.qualityWarnings));
|
|
1311
1312
|
}
|
|
1313
|
+
if (params.acFormat === 'bdd' && leanSpec.includes(PLACEHOLDER_WHEN_STEP_TEXT)) {
|
|
1314
|
+
const unparsedCriterion = criteria.find((criterion) => parseBddScenarios(criterion.text).length === 0)?.text ?? '';
|
|
1315
|
+
const placeholderFallbackWarning = `BDD parse fell back to placeholder steps — restate as a single GIVEN … WHEN … THEN … line: ` +
|
|
1316
|
+
`"${unparsedCriterion.slice(0, 120)}"`;
|
|
1317
|
+
spec.qualityWarnings = [
|
|
1318
|
+
...new Set([...(spec.qualityWarnings ?? []), placeholderFallbackWarning]),
|
|
1319
|
+
];
|
|
1320
|
+
unifiedSpec = updateFrontmatterField(unifiedSpec, 'qualityWarnings', JSON.stringify(spec.qualityWarnings));
|
|
1321
|
+
}
|
|
1312
1322
|
const genericOutputGate = checkGenericSpecOutput(unifiedSpec);
|
|
1313
1323
|
if (!genericOutputGate.passed) {
|
|
1314
1324
|
return earlyPreparation({
|
|
@@ -13,7 +13,8 @@ import { detectMissingAreas, buildRequestPrompt } from '../../engine/context-mer
|
|
|
13
13
|
import { detectProjectPrivacyConfig, maybeGenerateEnvExample, buildBeginnerEnvGuide, } from './helpers.js';
|
|
14
14
|
import { buildDefaultPrivacyConfig } from '../../engine/pii-detector.js';
|
|
15
15
|
import { checkBundledVersionGap } from '../../engine/version-detector/bundled-version-checker.js';
|
|
16
|
-
import { checkAndFixBundledVersion } from '../../engine/mcp-config/mcp-config-writer.js';
|
|
16
|
+
import { checkAndFixBundledVersion, healLegacyLatestEntry, } from '../../engine/mcp-config/mcp-config-writer.js';
|
|
17
|
+
import { planuVersion } from '../../config/version.js';
|
|
17
18
|
import { buildInitProjectResult } from './result-builder.js';
|
|
18
19
|
import { fetchRecommendedSkills } from '../suggest-tooling/skills-fetcher.js';
|
|
19
20
|
import { autoCompleteSpecs } from '../git/auto-complete-ops.js';
|
|
@@ -223,6 +224,7 @@ export async function handleInitProject(params, server) {
|
|
|
223
224
|
// SPEC-1699: Sweep runtime residue on every init_project run, including the
|
|
224
225
|
// already-initialized early-return path below — not just the fresh-init path.
|
|
225
226
|
scheduleHousekeepingSweeps(projectPath);
|
|
227
|
+
void healLegacyLatestEntry(projectPath, planuVersion()).catch(() => undefined);
|
|
226
228
|
const authorizedMigrations = params.authorizedMigrations ?? [];
|
|
227
229
|
if (isUpdate && authorizedMigrations.length === 0) {
|
|
228
230
|
const reconciliation = await reconcilePortableSpecIndex(projectPath, projectId);
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { ToolResult } from '../../types/index.js';
|
|
2
2
|
export interface JobToolIdentityInput {
|
|
3
3
|
operationId: string;
|
|
4
|
-
projectId
|
|
4
|
+
projectId?: string;
|
|
5
|
+
projectPath?: string;
|
|
5
6
|
workspaceId?: string;
|
|
6
7
|
}
|
|
7
8
|
export declare function handleGetJob(input: JobToolIdentityInput): Promise<ToolResult>;
|
|
@@ -56,6 +56,19 @@ import { schedulePackageHandoffJobExecution } from '../../engine/execution/packa
|
|
|
56
56
|
import { isValidationReceiptPendingIntent, parseValidationReceiptPendingCheckpoint, } from '../../types/durable-validation.js';
|
|
57
57
|
import { redactText } from '../../security/redactor.js';
|
|
58
58
|
import { getRuntimePolicy } from '../../engine/runtime-policy.js';
|
|
59
|
+
import { resolveProjectId } from '../resolve-project-id.js';
|
|
60
|
+
function jobIdentity(input) {
|
|
61
|
+
const derived = resolveProjectId({ projectPath: input.projectPath });
|
|
62
|
+
const passed = input.projectId?.trim();
|
|
63
|
+
if (derived && passed && derived !== passed) {
|
|
64
|
+
throw new Error(`[Planu] projectPath resolves to projectId ${derived} but projectId ${passed} was passed; pass only one.`);
|
|
65
|
+
}
|
|
66
|
+
const projectId = derived ?? passed;
|
|
67
|
+
if (!projectId) {
|
|
68
|
+
throw new Error('[Planu] Provide projectPath or projectId to identify the project.');
|
|
69
|
+
}
|
|
70
|
+
return { operationId: input.operationId, projectId, workspaceId: input.workspaceId };
|
|
71
|
+
}
|
|
59
72
|
function result(payload) {
|
|
60
73
|
return {
|
|
61
74
|
content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
|
|
@@ -101,7 +114,7 @@ export function handleGetJob(input) {
|
|
|
101
114
|
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
102
115
|
try {
|
|
103
116
|
const runtime = __addDisposableResource(env_1, new DurableJobRuntime(), false);
|
|
104
|
-
const job = runtime.get(input);
|
|
117
|
+
const job = runtime.get(jobIdentity(input));
|
|
105
118
|
const observation = publicJob(runtime, job);
|
|
106
119
|
return Promise.resolve(result({ schemaVersion: 1, job: observation, cursor: publicJobCursor(observation) }));
|
|
107
120
|
}
|
|
@@ -117,12 +130,13 @@ export function handleRestartJob(input) {
|
|
|
117
130
|
const env_2 = { stack: [], error: void 0, hasError: false };
|
|
118
131
|
try {
|
|
119
132
|
const runtime = __addDisposableResource(env_2, new DurableJobRuntime(), false);
|
|
120
|
-
const
|
|
133
|
+
const identity = jobIdentity(input);
|
|
134
|
+
const current = runtime.get(identity);
|
|
121
135
|
const pending = parseValidationReceiptPendingCheckpoint(current.checkpoint, checkpointLimits());
|
|
122
136
|
if (!pending && isValidationReceiptPendingIntent(current.checkpoint)) {
|
|
123
137
|
throw new Error('[Planu] Invalid validation receipt checkpoint');
|
|
124
138
|
}
|
|
125
|
-
const job = pending ? runtime.restartReceiptPublication(
|
|
139
|
+
const job = pending ? runtime.restartReceiptPublication(identity) : runtime.restart(identity);
|
|
126
140
|
rescheduleStalledJob(job);
|
|
127
141
|
const observation = publicJob(runtime, job);
|
|
128
142
|
return Promise.resolve(result({ schemaVersion: 1, job: observation, cursor: publicJobCursor(observation) }));
|
|
@@ -77,7 +77,20 @@ const coreToolsRegistry = [
|
|
|
77
77
|
.min(1)
|
|
78
78
|
.max(128)
|
|
79
79
|
.describe('Job operation ID. Max 128 characters.'),
|
|
80
|
-
projectId: z
|
|
80
|
+
projectId: z
|
|
81
|
+
.string()
|
|
82
|
+
.trim()
|
|
83
|
+
.min(1)
|
|
84
|
+
.max(128)
|
|
85
|
+
.optional()
|
|
86
|
+
.describe('Project ID hash. Optional when projectPath is given. Max 128 characters.'),
|
|
87
|
+
projectPath: z
|
|
88
|
+
.string()
|
|
89
|
+
.trim()
|
|
90
|
+
.min(1)
|
|
91
|
+
.max(4096)
|
|
92
|
+
.optional()
|
|
93
|
+
.describe('Absolute path to the project root; projectId is derived from it. Max 4096 characters.'),
|
|
81
94
|
workspaceId: z
|
|
82
95
|
.string()
|
|
83
96
|
.trim()
|
|
@@ -106,7 +119,20 @@ const coreToolsRegistry = [
|
|
|
106
119
|
.min(1)
|
|
107
120
|
.max(128)
|
|
108
121
|
.describe('Job operation ID. Max 128 characters.'),
|
|
109
|
-
projectId: z
|
|
122
|
+
projectId: z
|
|
123
|
+
.string()
|
|
124
|
+
.trim()
|
|
125
|
+
.min(1)
|
|
126
|
+
.max(128)
|
|
127
|
+
.optional()
|
|
128
|
+
.describe('Project ID hash. Optional when projectPath is given. Max 128 characters.'),
|
|
129
|
+
projectPath: z
|
|
130
|
+
.string()
|
|
131
|
+
.trim()
|
|
132
|
+
.min(1)
|
|
133
|
+
.max(4096)
|
|
134
|
+
.optional()
|
|
135
|
+
.describe('Absolute path to the project root; projectId is derived from it. Max 4096 characters.'),
|
|
110
136
|
workspaceId: z
|
|
111
137
|
.string()
|
|
112
138
|
.trim()
|
|
@@ -128,13 +128,20 @@ export async function checkLifecycleEvidenceTransitionGate(args) {
|
|
|
128
128
|
: null;
|
|
129
129
|
if (receiptResult && !receiptResult.ok) {
|
|
130
130
|
const message = receiptResult.reason === 'stale-bindings'
|
|
131
|
-
?
|
|
131
|
+
? staleBindingsIssueMessage(args.specId)
|
|
132
132
|
: receiptResult.reason;
|
|
133
133
|
return evidenceGateError({
|
|
134
134
|
specId: args.specId,
|
|
135
135
|
transition: args.transition,
|
|
136
136
|
issues: [{ code: 'evidence_provenance_invalid', message }],
|
|
137
137
|
requiredContractKinds: [],
|
|
138
|
+
nextAction: receiptResult.reason === 'stale-bindings'
|
|
139
|
+
? {
|
|
140
|
+
tool: 'validate',
|
|
141
|
+
args: { specId: args.specId },
|
|
142
|
+
rationale: 'Re-run validate for a fresh sourceDigest, then package_handoff for a fresh contextHash, then retry done.',
|
|
143
|
+
}
|
|
144
|
+
: undefined,
|
|
138
145
|
});
|
|
139
146
|
}
|
|
140
147
|
const result = await checkLifecycleEvidenceGate({
|
|
@@ -314,6 +321,9 @@ async function extractLifecycleGateCriteriaAndBody(spec, projectPath) {
|
|
|
314
321
|
}
|
|
315
322
|
return { criteria: await extractCriteria(spec), body: null };
|
|
316
323
|
}
|
|
324
|
+
function staleBindingsIssueMessage(specId) {
|
|
325
|
+
return `stale-bindings: validation inputs changed after the receipt was issued, so the receipt's bound sourceDigest no longer matches the working tree. Re-run validate(specId=${specId}) for a fresh sourceDigest, then package_handoff(specId=${specId}) for a fresh contextHash, then retry done.`;
|
|
326
|
+
}
|
|
317
327
|
function evidenceGateError(args) {
|
|
318
328
|
return {
|
|
319
329
|
content: [
|
|
@@ -327,6 +337,7 @@ function evidenceGateError(args) {
|
|
|
327
337
|
issues: args.issues.length,
|
|
328
338
|
firstIssue: args.issues[0]?.message,
|
|
329
339
|
requiredContractKinds: args.requiredContractKinds.length,
|
|
340
|
+
nextActionTool: args.nextAction?.tool,
|
|
330
341
|
fixHint: 'Add the missing evidence artifact to the external Planu project data handoff store, then retry the transition. Do not create JSON files under planu/specs/<spec>/.',
|
|
331
342
|
}),
|
|
332
343
|
},
|
|
@@ -341,6 +352,7 @@ function evidenceGateError(args) {
|
|
|
341
352
|
transition: args.transition,
|
|
342
353
|
issues: args.issues,
|
|
343
354
|
requiredContractKinds: args.requiredContractKinds,
|
|
355
|
+
nextAction: args.nextAction,
|
|
344
356
|
},
|
|
345
357
|
fixHint: 'Add discovery.json, task-plan.json, traceability-matrix.json, and contract-validation-*.json to the external Planu handoff store as required for this transition. Spec folders remain spec.md-only.',
|
|
346
358
|
},
|
|
@@ -209,7 +209,7 @@ export async function checkAmbiguityGate(spec, newStatus) {
|
|
|
209
209
|
}
|
|
210
210
|
const report = await scoreAmbiguityFromPath(spec.specPath);
|
|
211
211
|
if (!report) {
|
|
212
|
-
return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.');
|
|
212
|
+
return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.', readinessGateIdentity(spec));
|
|
213
213
|
}
|
|
214
214
|
if (report.score >= 70) {
|
|
215
215
|
return null;
|
|
@@ -342,11 +342,11 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
|
|
|
342
342
|
? `spec.md is missing at ${spec.specPath}. Recreate the spec via create_spec or restore spec.md from git/backup before retrying this transition.`
|
|
343
343
|
: error instanceof Error
|
|
344
344
|
? error.message
|
|
345
|
-
: 'spec.md could not be read');
|
|
345
|
+
: 'spec.md could not be read', readinessGateIdentity(spec, projectPath));
|
|
346
346
|
}
|
|
347
347
|
// Guard: mock environments return undefined; unreadable files return non-string
|
|
348
348
|
if (typeof body !== 'string') {
|
|
349
|
-
return readinessUnavailable('READINESS_SPEC_INVALID', 'spec.md did not return text content');
|
|
349
|
+
return readinessUnavailable('READINESS_SPEC_INVALID', 'spec.md did not return text content', readinessGateIdentity(spec, projectPath));
|
|
350
350
|
}
|
|
351
351
|
const languageValidation = validateEnglishOnlySpecText(body);
|
|
352
352
|
if (!languageValidation.ok) {
|
|
@@ -440,7 +440,7 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
|
|
|
440
440
|
catch (error) {
|
|
441
441
|
/* reliability-optional: READINESS_EVALUATION_FAILED — transition fails closed below */
|
|
442
442
|
reportClassifiedDegradation('READINESS_EVALUATION_FAILED', error);
|
|
443
|
-
return readinessUnavailable('READINESS_EVALUATION_FAILED', error instanceof Error ? error.message : 'readiness evaluation failed', structuralInterpolationWarnings);
|
|
443
|
+
return readinessUnavailable('READINESS_EVALUATION_FAILED', error instanceof Error ? error.message : 'readiness evaluation failed', readinessGateIdentity(spec, projectPath), structuralInterpolationWarnings);
|
|
444
444
|
}
|
|
445
445
|
const { score } = readiness;
|
|
446
446
|
const blockers = [...readiness.issues.blockers];
|
|
@@ -579,15 +579,39 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
|
|
|
579
579
|
qualityWarnings: structuralInterpolationWarnings,
|
|
580
580
|
};
|
|
581
581
|
}
|
|
582
|
-
function
|
|
582
|
+
function gateBlockedText(message) {
|
|
583
|
+
return `${message} Transition blocked until the gate succeeds. Do not retry the spec-level transition until the originating condition is cleared.`;
|
|
584
|
+
}
|
|
585
|
+
function readinessGateIdentity(spec, projectPath) {
|
|
586
|
+
const identity = { specId: spec.id, projectId: spec.projectId };
|
|
587
|
+
return projectPath === undefined ? identity : { ...identity, projectPath };
|
|
588
|
+
}
|
|
589
|
+
function gateUnavailableResult(code, message, identity) {
|
|
590
|
+
const structuredContent = {
|
|
591
|
+
error: code,
|
|
592
|
+
message,
|
|
593
|
+
retryable: false,
|
|
594
|
+
externalGateBlocked: true,
|
|
595
|
+
originatingCondition: code,
|
|
596
|
+
nextAction: {
|
|
597
|
+
tool: 'check_readiness',
|
|
598
|
+
args: {
|
|
599
|
+
specId: identity.specId,
|
|
600
|
+
...(identity.projectPath === undefined
|
|
601
|
+
? { projectId: identity.projectId }
|
|
602
|
+
: { projectPath: identity.projectPath }),
|
|
603
|
+
},
|
|
604
|
+
rationale: `${message} Fix the originating condition outside the spec contract, then re-run check_readiness to confirm it cleared. Retrying update_status on the same spec will not clear it.`,
|
|
605
|
+
},
|
|
606
|
+
};
|
|
583
607
|
return {
|
|
584
|
-
content: [{ type: 'text', text:
|
|
608
|
+
content: [{ type: 'text', text: gateBlockedText(message) }],
|
|
585
609
|
isError: true,
|
|
586
|
-
structuredContent:
|
|
610
|
+
structuredContent: structuredContent,
|
|
587
611
|
};
|
|
588
612
|
}
|
|
589
|
-
function readinessUnavailable(code, message, qualityWarnings = []) {
|
|
590
|
-
return { blockResult: gateUnavailableResult(code, message), qualityWarnings };
|
|
613
|
+
function readinessUnavailable(code, message, identity, qualityWarnings = []) {
|
|
614
|
+
return { blockResult: gateUnavailableResult(code, message, identity), qualityWarnings };
|
|
591
615
|
}
|
|
592
616
|
const CHALLENGE_RESOLUTION_INSTRUCTIONS = 'Add a "### Challenge Resolution" subsection to the spec\'s spec.md with one "- " bullet per unresolved finding, each bullet containing that finding\'s exact scenario text plus your mitigation, then re-run challenge_spec to re-derive the report.';
|
|
593
617
|
/**
|
package/dist/tools/validate.js
CHANGED
|
@@ -120,7 +120,19 @@ function computeIntegrationTimeoutMs() {
|
|
|
120
120
|
function isBlastRadiusPassed(blastRadiusGate) {
|
|
121
121
|
return blastRadiusGate.passed && blastRadiusGate.warningReason === null;
|
|
122
122
|
}
|
|
123
|
-
function
|
|
123
|
+
function blastRadiusWarnings(blastRadiusGate) {
|
|
124
|
+
if (blastRadiusGate.warningReason === 'stale-dist') {
|
|
125
|
+
return [
|
|
126
|
+
{
|
|
127
|
+
file: 'blast-radius',
|
|
128
|
+
line: 0,
|
|
129
|
+
severity: 'warning',
|
|
130
|
+
rule: 'stale-dist',
|
|
131
|
+
message: 'Blast radius gate could not run: dist/ build provenance is stale',
|
|
132
|
+
suggestion: 'Run pnpm build:ts and re-run validate.',
|
|
133
|
+
},
|
|
134
|
+
];
|
|
135
|
+
}
|
|
124
136
|
return blastRadiusGate.warningReason === null
|
|
125
137
|
? []
|
|
126
138
|
: [
|
|
@@ -622,7 +634,7 @@ export async function executeValidate(args, server, onProgress) {
|
|
|
622
634
|
suggestion: 'No importer regression coverage ran for this validate call.',
|
|
623
635
|
});
|
|
624
636
|
}
|
|
625
|
-
output.qualityIssues.push(...
|
|
637
|
+
output.qualityIssues.push(...blastRadiusWarnings(blastRadiusGate));
|
|
626
638
|
output.qualityIssues.push(...strictAuditsQualityIssues(strictAuditsGate));
|
|
627
639
|
// Auto-suggest corrective actions based on validation results
|
|
628
640
|
// score is null when no criteria can be extracted — treat as 0 for comparisons.
|