pi-jev-guard 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -0
- package/config/jev-config.example.json +10 -0
- package/config/jev-verification.example.json +22 -0
- package/extensions/index.ts +410 -2
- package/package.json +1 -1
- package/src/automatic/guardian.ts +26 -2
- package/src/commands.ts +111 -1
- package/src/config.ts +31 -0
- package/src/verification-runner.ts +177 -0
- package/src/verification-tool.ts +65 -0
- package/src/verification.ts +926 -0
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verifica deterministica delle modifiche osservate nella sessione.
|
|
3
|
+
*
|
|
4
|
+
* Diversa da Jev: qui non si prova a "capire" se il codice è corretto.
|
|
5
|
+
* Si conserva soltanto un fatto osservabile: edit/write riusciti e l'esito
|
|
6
|
+
* di comandi dichiarati dal progetto. Il footer finale è costruito da questi
|
|
7
|
+
* dati, non dal testo del modello, quindi non può inventare test superati.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
13
|
+
|
|
14
|
+
export type VerificationMode = "warn" | "repair" | "hold";
|
|
15
|
+
/** Profilo integrato usato quando non esiste un override locale/globale. */
|
|
16
|
+
export type VerificationDefaultProfile = "common" | "off";
|
|
17
|
+
export type VerificationManifestSource = "project" | "global-manifest" | "global-profile";
|
|
18
|
+
|
|
19
|
+
/** Impostazioni condivise; i comandi eseguibili arrivano solo dalla policy acquisita. */
|
|
20
|
+
export interface VerificationSettings {
|
|
21
|
+
/** Opt-in: nessun footer, repair o comando automatico finché è false. */
|
|
22
|
+
enabled: boolean;
|
|
23
|
+
/** warn = footer; repair = un tentativo privato; hold = blocco rigoroso. */
|
|
24
|
+
mode: VerificationMode;
|
|
25
|
+
/** File JSON relativo alla root del progetto, mai un comando generato dal modello. */
|
|
26
|
+
manifestPath: string;
|
|
27
|
+
/** Manifest opzionale dell'utente, assoluto o con `~/`; fallback dopo quello locale. */
|
|
28
|
+
globalManifestPath?: string;
|
|
29
|
+
/** Fallback integrato per nuovi progetti; resta inattivo finché enabled=false. */
|
|
30
|
+
defaultProfile: VerificationDefaultProfile;
|
|
31
|
+
/** Rigenerazioni massime per risposta quando mancano/falliscono check. */
|
|
32
|
+
maxRepairs: number;
|
|
33
|
+
/** Timeout massimo predefinito dei check avviati da jev_verify o /jev verify. */
|
|
34
|
+
commandTimeoutMs: number;
|
|
35
|
+
/** Output massimo restituito al modello per un check fallito. */
|
|
36
|
+
outputChars: number;
|
|
37
|
+
/** Limite di check eseguibili in una richiesta `recommended`/`all`. */
|
|
38
|
+
maxCommands: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface VerificationCheck {
|
|
42
|
+
/** Id stabile, usato da /jev verify e dal tool jev_verify. */
|
|
43
|
+
id: string;
|
|
44
|
+
/** Comando esplicitamente approvato dalla policy acquisita. */
|
|
45
|
+
command: string;
|
|
46
|
+
/** Glob dei file a cui il check si applica; assente = tutte le modifiche. */
|
|
47
|
+
files?: string[];
|
|
48
|
+
description?: string;
|
|
49
|
+
/** Override bounded dal timeout globale del guard. */
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface VerificationManifest {
|
|
54
|
+
version: 1;
|
|
55
|
+
checks: VerificationCheck[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type LoadedVerificationManifest =
|
|
59
|
+
| {
|
|
60
|
+
ok: true;
|
|
61
|
+
/** Percorso assoluto per manifest file, identificatore stabile per profilo integrato. */
|
|
62
|
+
path: string;
|
|
63
|
+
source: VerificationManifestSource;
|
|
64
|
+
sourceLabel: string;
|
|
65
|
+
/** File che influenzano i comandi autorizzati e che il modello non può alterare. */
|
|
66
|
+
protectedPaths: string[];
|
|
67
|
+
manifest: VerificationManifest;
|
|
68
|
+
fingerprint: string;
|
|
69
|
+
}
|
|
70
|
+
| { ok: false; path?: string; error: string };
|
|
71
|
+
|
|
72
|
+
/** Manifest/profilo acquisito a inizio sessione o su comando utente esplicito. */
|
|
73
|
+
export type VerificationManifestTrust =
|
|
74
|
+
| {
|
|
75
|
+
ok: true;
|
|
76
|
+
cwd: string;
|
|
77
|
+
path: string;
|
|
78
|
+
source: VerificationManifestSource;
|
|
79
|
+
sourceLabel: string;
|
|
80
|
+
protectedPaths: string[];
|
|
81
|
+
manifest: VerificationManifest;
|
|
82
|
+
fingerprint: string;
|
|
83
|
+
}
|
|
84
|
+
| { ok: false; cwd: string; error: string };
|
|
85
|
+
|
|
86
|
+
/** Un edit/write osservato con successo; non pretende di vedere modifiche via shell. */
|
|
87
|
+
export interface ObservedModification {
|
|
88
|
+
path: string;
|
|
89
|
+
seq: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface VerificationRun {
|
|
93
|
+
id: string;
|
|
94
|
+
command: string;
|
|
95
|
+
ok: boolean;
|
|
96
|
+
/** Assente quando il tool non espone l'exit code. */
|
|
97
|
+
exitCode?: number;
|
|
98
|
+
/**
|
|
99
|
+
* Ordine di INIZIO del check. Deve essere successivo al completamento
|
|
100
|
+
* dell'edit pertinente: un test partito in parallelo prima dell'edit non
|
|
101
|
+
* diventa fresco solo perché il suo tool_result arriva dopo.
|
|
102
|
+
*/
|
|
103
|
+
seq: number;
|
|
104
|
+
source: "jev_verify" | "bash" | "powershell" | "manual";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface VerificationState {
|
|
108
|
+
modifications: ObservedModification[];
|
|
109
|
+
runs: VerificationRun[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type VerificationCheckState = "passed" | "failed" | "pending";
|
|
113
|
+
|
|
114
|
+
export interface VerificationCheckStatus {
|
|
115
|
+
check: VerificationCheck;
|
|
116
|
+
state: VerificationCheckState;
|
|
117
|
+
/** Ultimo run dopo l'ultima modifica pertinente, se presente. */
|
|
118
|
+
run?: VerificationRun;
|
|
119
|
+
latestRelevantEditSeq: number;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface VerificationStatus {
|
|
123
|
+
changedFiles: string[];
|
|
124
|
+
/** Origine della policy che ha autorizzato i check correnti. */
|
|
125
|
+
manifestSource?: VerificationManifestSource;
|
|
126
|
+
manifestSourceLabel?: string;
|
|
127
|
+
/** Errore/mancanza manifest: non è una prova negativa sul codice. */
|
|
128
|
+
manifestError?: string;
|
|
129
|
+
checks: VerificationCheckStatus[];
|
|
130
|
+
/** Esistono check dichiarati che corrispondono alle modifiche osservate. */
|
|
131
|
+
actionable: boolean;
|
|
132
|
+
hasPending: boolean;
|
|
133
|
+
hasFailed: boolean;
|
|
134
|
+
allPassed: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function createVerificationState(): VerificationState {
|
|
138
|
+
return { modifications: [], runs: [] };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Trasforma un path tool in un path relativo al progetto. I path fuori root
|
|
143
|
+
* non entrano nella policy del progetto: possono essere riportati dal modello,
|
|
144
|
+
* ma non diventano falsamente coperti da un check del progetto corrente.
|
|
145
|
+
*/
|
|
146
|
+
export function normalizeObservedPath(path: unknown, cwd: string): string | undefined {
|
|
147
|
+
if (typeof path !== "string" || !path.trim()) return undefined;
|
|
148
|
+
const root = resolve(cwd);
|
|
149
|
+
const absolute = resolve(root, path.trim());
|
|
150
|
+
const rel = relative(root, absolute);
|
|
151
|
+
if (!rel || rel === "." || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
return rel.split(sep).join("/");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Registra l'ultima modifica riuscita per path; cap conservativo della memoria. */
|
|
158
|
+
export function recordObservedModification(
|
|
159
|
+
state: VerificationState,
|
|
160
|
+
path: string,
|
|
161
|
+
seq: number,
|
|
162
|
+
): void {
|
|
163
|
+
const existing = state.modifications.find((entry) => entry.path === path);
|
|
164
|
+
if (existing) {
|
|
165
|
+
existing.seq = seq;
|
|
166
|
+
} else {
|
|
167
|
+
state.modifications.push({ path, seq });
|
|
168
|
+
}
|
|
169
|
+
if (state.modifications.length > 100) {
|
|
170
|
+
state.modifications.sort((a, b) => a.seq - b.seq);
|
|
171
|
+
state.modifications.splice(0, state.modifications.length - 100);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Registra un esito reale; più run dello stesso id sono mantenuti per il freshness check. */
|
|
176
|
+
export function recordVerificationRun(
|
|
177
|
+
state: VerificationState,
|
|
178
|
+
run: VerificationRun,
|
|
179
|
+
): void {
|
|
180
|
+
state.runs.push({ ...run });
|
|
181
|
+
if (state.runs.length > 200) state.runs.splice(0, state.runs.length - 200);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
185
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const CHECK_ID = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
189
|
+
|
|
190
|
+
function parseFiles(value: unknown, index: number): string[] | undefined {
|
|
191
|
+
if (value === undefined) return undefined;
|
|
192
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > 100) {
|
|
193
|
+
throw new Error(`checks[${index}].files deve essere un array non vuoto (max 100)`);
|
|
194
|
+
}
|
|
195
|
+
const files = value.map((item, itemIndex) => {
|
|
196
|
+
if (typeof item !== "string" || !item.trim() || item.length > 240) {
|
|
197
|
+
throw new Error(`checks[${index}].files[${itemIndex}] non valido`);
|
|
198
|
+
}
|
|
199
|
+
const normalized = item.trim().replace(/\\/g, "/");
|
|
200
|
+
if (normalized.startsWith("/") || normalized.includes("\0")) {
|
|
201
|
+
throw new Error(`checks[${index}].files[${itemIndex}] deve essere un glob relativo`);
|
|
202
|
+
}
|
|
203
|
+
return normalized;
|
|
204
|
+
});
|
|
205
|
+
return [...new Set(files)];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Parser stretto: un manifest malformato non esegue mai comandi. */
|
|
209
|
+
export function parseVerificationManifest(value: unknown): VerificationManifest {
|
|
210
|
+
if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.checks)) {
|
|
211
|
+
throw new Error("manifest richiede { version: 1, checks: [...] }");
|
|
212
|
+
}
|
|
213
|
+
if (value.checks.length === 0 || value.checks.length > 50) {
|
|
214
|
+
throw new Error("manifest.checks deve contenere da 1 a 50 check");
|
|
215
|
+
}
|
|
216
|
+
const seen = new Set<string>();
|
|
217
|
+
const checks: VerificationCheck[] = value.checks.map((raw, index) => {
|
|
218
|
+
if (!isRecord(raw)) throw new Error(`checks[${index}] non è un oggetto`);
|
|
219
|
+
const id = raw.id;
|
|
220
|
+
const command = raw.command;
|
|
221
|
+
if (typeof id !== "string" || !CHECK_ID.test(id)) {
|
|
222
|
+
throw new Error(`checks[${index}].id non valido`);
|
|
223
|
+
}
|
|
224
|
+
if (seen.has(id)) throw new Error(`id check duplicato: ${id}`);
|
|
225
|
+
seen.add(id);
|
|
226
|
+
if (
|
|
227
|
+
typeof command !== "string" ||
|
|
228
|
+
!command.trim() ||
|
|
229
|
+
command.length > 2000 ||
|
|
230
|
+
command.includes("\0") ||
|
|
231
|
+
/[\r\n]/.test(command)
|
|
232
|
+
) {
|
|
233
|
+
throw new Error(`checks[${index}].command non valido`);
|
|
234
|
+
}
|
|
235
|
+
const description = raw.description;
|
|
236
|
+
if (description !== undefined && (typeof description !== "string" || description.length > 300)) {
|
|
237
|
+
throw new Error(`checks[${index}].description non valida`);
|
|
238
|
+
}
|
|
239
|
+
const timeoutMs = raw.timeoutMs;
|
|
240
|
+
if (timeoutMs !== undefined && (
|
|
241
|
+
typeof timeoutMs !== "number" ||
|
|
242
|
+
!Number.isInteger(timeoutMs) ||
|
|
243
|
+
timeoutMs < 1000 ||
|
|
244
|
+
timeoutMs > 3_600_000
|
|
245
|
+
)) {
|
|
246
|
+
throw new Error(`checks[${index}].timeoutMs non valido`);
|
|
247
|
+
}
|
|
248
|
+
const files = parseFiles(raw.files, index);
|
|
249
|
+
return {
|
|
250
|
+
id,
|
|
251
|
+
command: command.trim(),
|
|
252
|
+
...(files ? { files } : {}),
|
|
253
|
+
...(typeof description === "string" && description ? { description } : {}),
|
|
254
|
+
...(typeof timeoutMs === "number" ? { timeoutMs } : {}),
|
|
255
|
+
};
|
|
256
|
+
});
|
|
257
|
+
return { version: 1, checks };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Risolve un manifest esclusivamente dentro la root progetto. */
|
|
261
|
+
export function resolveManifestPath(cwd: string, manifestPath: string): string | undefined {
|
|
262
|
+
if (!manifestPath.trim()) return undefined;
|
|
263
|
+
const root = resolve(cwd);
|
|
264
|
+
const target = resolve(root, manifestPath.trim());
|
|
265
|
+
const rel = relative(root, target);
|
|
266
|
+
if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return undefined;
|
|
267
|
+
return target;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Un manifest globale è una scelta esplicita della config dell'utente: solo path assoluto o `~/`. */
|
|
271
|
+
export function resolveGlobalManifestPath(manifestPath: string | undefined): string | undefined {
|
|
272
|
+
const raw = manifestPath?.trim();
|
|
273
|
+
if (!raw) return undefined;
|
|
274
|
+
const expanded = raw === "~"
|
|
275
|
+
? homedir()
|
|
276
|
+
: raw.startsWith("~/") ? join(homedir(), raw.slice(2)) : raw;
|
|
277
|
+
return isAbsolute(expanded) ? resolve(expanded) : undefined;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Il modello non può alterare la policy che autorizza i suoi comandi. */
|
|
281
|
+
export function isVerificationManifestPath(
|
|
282
|
+
path: unknown,
|
|
283
|
+
cwd: string,
|
|
284
|
+
manifestPath: string,
|
|
285
|
+
): boolean {
|
|
286
|
+
if (typeof path !== "string" || !path.trim()) return false;
|
|
287
|
+
const manifest = resolveManifestPath(cwd, manifestPath);
|
|
288
|
+
if (!manifest) return false;
|
|
289
|
+
return canonicalPolicyPath(resolve(cwd, path.trim())) === canonicalPolicyPath(manifest);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function canonicalPolicyPath(path: string): string {
|
|
293
|
+
const resolved = resolve(path);
|
|
294
|
+
try {
|
|
295
|
+
// Il confronto passa dal target reale: una symlink non consente di
|
|
296
|
+
// aggirare l'immutabilità del manifest o di package.json acquisito.
|
|
297
|
+
return realpathSync(resolved);
|
|
298
|
+
} catch {
|
|
299
|
+
return resolved;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function normalizedToolPath(path: string, cwd: string): string {
|
|
304
|
+
const trimmed = path.trim();
|
|
305
|
+
const expanded = trimmed === "~"
|
|
306
|
+
? homedir()
|
|
307
|
+
: trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
|
|
308
|
+
return canonicalPolicyPath(resolve(cwd, expanded));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Protegge anche input (es. package.json) che decidono un profilo globale. */
|
|
312
|
+
export function isVerificationPolicyPath(
|
|
313
|
+
path: unknown,
|
|
314
|
+
cwd: string,
|
|
315
|
+
trust: VerificationManifestTrust | undefined,
|
|
316
|
+
): boolean {
|
|
317
|
+
if (typeof path !== "string" || !path.trim() || !trust?.ok || trust.cwd !== resolve(cwd)) return false;
|
|
318
|
+
const target = normalizedToolPath(path, cwd);
|
|
319
|
+
return trust.protectedPaths.includes(target);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function fingerprintText(text: string): string {
|
|
323
|
+
// Non è una firma/autorizzazione remota: serve a rilevare con robustezza
|
|
324
|
+
// una mutazione del file dopo la snapshot locale trusted.
|
|
325
|
+
return createHash("sha256").update(text).digest("hex");
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const COMMON_PROFILE_PATH = "<global-profile:common-v1>";
|
|
329
|
+
const MAX_MANIFEST_BYTES = 1_000_000;
|
|
330
|
+
const MAX_PROFILE_INPUT_BYTES = 1_000_000;
|
|
331
|
+
const MAX_PROFILE_INPUT_CHARS = 1_000_000;
|
|
332
|
+
const NODE_CODE_FILES = [
|
|
333
|
+
"**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mjs", "**/*.cjs",
|
|
334
|
+
"package.json", "tsconfig.json", "tsconfig.*.json",
|
|
335
|
+
];
|
|
336
|
+
const NODE_TEST_FILES = [...NODE_CODE_FILES, "test/**", "tests/**", "__tests__/**"];
|
|
337
|
+
|
|
338
|
+
interface ProfileInput {
|
|
339
|
+
path: string;
|
|
340
|
+
text: string;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function readProfileInput(path: string): ProfileInput | { error: string } {
|
|
344
|
+
try {
|
|
345
|
+
if (statSync(path).size > MAX_PROFILE_INPUT_BYTES) {
|
|
346
|
+
return { error: `${path} supera ${MAX_PROFILE_INPUT_BYTES} byte` };
|
|
347
|
+
}
|
|
348
|
+
const text = readFileSync(path, "utf8");
|
|
349
|
+
if (text.length > MAX_PROFILE_INPUT_CHARS) {
|
|
350
|
+
return { error: `${path} supera ${MAX_PROFILE_INPUT_CHARS} caratteri` };
|
|
351
|
+
}
|
|
352
|
+
return { path, text };
|
|
353
|
+
} catch (error) {
|
|
354
|
+
return { error: `${path}: ${error instanceof Error ? error.message : String(error)}` };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function isProfileInput(value: ProfileInput | { error: string }): value is ProfileInput {
|
|
359
|
+
return "text" in value;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function findGitRoot(cwd: string): string | undefined {
|
|
363
|
+
let current = resolve(cwd);
|
|
364
|
+
while (true) {
|
|
365
|
+
if (existsSync(join(current, ".git"))) return current;
|
|
366
|
+
const parent = dirname(current);
|
|
367
|
+
if (parent === current) return undefined;
|
|
368
|
+
current = parent;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function nodeProfile(root: string):
|
|
373
|
+
| { checks: VerificationCheck[]; inputs: ProfileInput[] }
|
|
374
|
+
| { error: string }
|
|
375
|
+
| undefined {
|
|
376
|
+
const path = join(root, "package.json");
|
|
377
|
+
if (!existsSync(path)) return undefined;
|
|
378
|
+
const input = readProfileInput(path);
|
|
379
|
+
if (!isProfileInput(input)) return input;
|
|
380
|
+
let parsed: unknown;
|
|
381
|
+
try {
|
|
382
|
+
parsed = JSON.parse(input.text);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return { error: `profilo globale: package.json non valido: ${error instanceof Error ? error.message : String(error)}` };
|
|
385
|
+
}
|
|
386
|
+
const scripts = isRecord(parsed) && isRecord(parsed.scripts) ? parsed.scripts : {};
|
|
387
|
+
const hasScript = (name: string) => typeof scripts[name] === "string" && scripts[name].trim().length > 0;
|
|
388
|
+
const checks: VerificationCheck[] = [];
|
|
389
|
+
if (hasScript("typecheck")) {
|
|
390
|
+
checks.push({ id: "node-typecheck", command: "npm run typecheck", description: "Node/TypeScript typecheck", files: NODE_CODE_FILES });
|
|
391
|
+
}
|
|
392
|
+
if (hasScript("lint")) {
|
|
393
|
+
checks.push({ id: "node-lint", command: "npm run lint", description: "Node lint", files: NODE_CODE_FILES });
|
|
394
|
+
}
|
|
395
|
+
const testScript = ["test:unit", "test:ci", "test"].find(hasScript);
|
|
396
|
+
if (testScript) {
|
|
397
|
+
checks.push({
|
|
398
|
+
id: "node-test",
|
|
399
|
+
command: testScript === "test" ? "npm test" : `npm run ${testScript}`,
|
|
400
|
+
description: `Node test (${testScript})`,
|
|
401
|
+
files: NODE_TEST_FILES,
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
return checks.length > 0 ? { checks, inputs: [input] } : undefined;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function markerProfile(args: {
|
|
408
|
+
root: string;
|
|
409
|
+
marker: string;
|
|
410
|
+
checks: VerificationCheck[];
|
|
411
|
+
}): { checks: VerificationCheck[]; inputs: ProfileInput[] } | { error: string } | undefined {
|
|
412
|
+
const path = join(args.root, args.marker);
|
|
413
|
+
if (!existsSync(path)) return undefined;
|
|
414
|
+
const input = readProfileInput(path);
|
|
415
|
+
if (!isProfileInput(input)) return input;
|
|
416
|
+
return { checks: args.checks, inputs: [input] };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function pythonProfile(root: string):
|
|
420
|
+
| { checks: VerificationCheck[]; inputs: ProfileInput[] }
|
|
421
|
+
| { error: string }
|
|
422
|
+
| undefined {
|
|
423
|
+
const candidates = ["pytest.ini", "pyproject.toml", "setup.cfg"];
|
|
424
|
+
const inputs: ProfileInput[] = [];
|
|
425
|
+
for (const name of candidates) {
|
|
426
|
+
const path = join(root, name);
|
|
427
|
+
if (!existsSync(path)) continue;
|
|
428
|
+
const input = readProfileInput(path);
|
|
429
|
+
if (!isProfileInput(input)) return input;
|
|
430
|
+
inputs.push(input);
|
|
431
|
+
}
|
|
432
|
+
const pytestConfigured = inputs.some((input) =>
|
|
433
|
+
input.path.endsWith("pytest.ini") ||
|
|
434
|
+
/\[(?:tool\.pytest(?:\.ini_options)?|tool:pytest)\]/.test(input.text) ||
|
|
435
|
+
/["']pytest(?:[<>=~!][^"']*)?["']/.test(input.text),
|
|
436
|
+
);
|
|
437
|
+
if (!pytestConfigured) return undefined;
|
|
438
|
+
return {
|
|
439
|
+
checks: [{
|
|
440
|
+
id: "python-pytest",
|
|
441
|
+
command: "python -m pytest",
|
|
442
|
+
description: "Python pytest",
|
|
443
|
+
files: ["**/*.py", "pyproject.toml", "pytest.ini", "setup.cfg"],
|
|
444
|
+
}],
|
|
445
|
+
inputs,
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Profilo built-in, deliberatamente conservativo. I comandi sono nel codice
|
|
451
|
+
* dell'estensione, non arrivano dal repository o dal modello; i file che ne
|
|
452
|
+
* abilitano la selezione entrano nel fingerprint/protectedPaths della snapshot.
|
|
453
|
+
*/
|
|
454
|
+
export function loadCommonVerificationProfile(cwd: string): LoadedVerificationManifest {
|
|
455
|
+
const root = resolve(cwd);
|
|
456
|
+
const node = nodeProfile(root);
|
|
457
|
+
if (node && "error" in node) return { ok: false, error: node.error };
|
|
458
|
+
const cargo = node ? undefined : markerProfile({
|
|
459
|
+
root,
|
|
460
|
+
marker: "Cargo.toml",
|
|
461
|
+
checks: [
|
|
462
|
+
{ id: "cargo-check", command: "cargo check", description: "Rust compile check", files: ["**/*.rs", "Cargo.toml", "Cargo.lock", "build.rs"] },
|
|
463
|
+
{ id: "cargo-test", command: "cargo test", description: "Rust tests", files: ["**/*.rs", "Cargo.toml", "Cargo.lock", "build.rs", "tests/**"] },
|
|
464
|
+
],
|
|
465
|
+
});
|
|
466
|
+
if (cargo && "error" in cargo) return { ok: false, error: cargo.error };
|
|
467
|
+
const go = node || cargo ? undefined : markerProfile({
|
|
468
|
+
root,
|
|
469
|
+
marker: "go.mod",
|
|
470
|
+
checks: [{ id: "go-test", command: "go test ./...", description: "Go tests", files: ["**/*.go", "go.mod", "go.sum"] }],
|
|
471
|
+
});
|
|
472
|
+
if (go && "error" in go) return { ok: false, error: go.error };
|
|
473
|
+
const python = node || cargo || go ? undefined : pythonProfile(root);
|
|
474
|
+
if (python && "error" in python) return { ok: false, error: python.error };
|
|
475
|
+
const selected = node ?? cargo ?? go ?? python;
|
|
476
|
+
const checks = selected ? [...selected.checks] : [];
|
|
477
|
+
const gitRoot = findGitRoot(root);
|
|
478
|
+
if (gitRoot) {
|
|
479
|
+
checks.push({ id: "git-diff-check", command: "git diff --check", description: "Whitespace and patch integrity" });
|
|
480
|
+
}
|
|
481
|
+
if (checks.length === 0) {
|
|
482
|
+
return {
|
|
483
|
+
ok: false,
|
|
484
|
+
error: "nessun manifest locale e profilo globale common non applicabile (nessun progetto Node/Rust/Go/Python o repository Git rilevato)",
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
const inputs = selected?.inputs ?? [];
|
|
488
|
+
const manifest: VerificationManifest = { version: 1, checks };
|
|
489
|
+
const fingerprint = fingerprintText(JSON.stringify({
|
|
490
|
+
profile: "common-v1",
|
|
491
|
+
root,
|
|
492
|
+
gitRoot: gitRoot ?? null,
|
|
493
|
+
inputs: inputs.map((input) => ({ path: input.path, text: input.text })),
|
|
494
|
+
manifest,
|
|
495
|
+
}));
|
|
496
|
+
return {
|
|
497
|
+
ok: true,
|
|
498
|
+
path: COMMON_PROFILE_PATH,
|
|
499
|
+
source: "global-profile",
|
|
500
|
+
sourceLabel: "profilo globale common",
|
|
501
|
+
protectedPaths: inputs.map((input) => canonicalPolicyPath(input.path)),
|
|
502
|
+
manifest,
|
|
503
|
+
fingerprint,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function loadManifestAtPath(args: {
|
|
508
|
+
path: string;
|
|
509
|
+
source: "project" | "global-manifest";
|
|
510
|
+
sourceLabel: string;
|
|
511
|
+
}): LoadedVerificationManifest {
|
|
512
|
+
if (!existsSync(args.path)) {
|
|
513
|
+
return { ok: false, path: args.path, error: `manifest non trovato: ${args.sourceLabel}` };
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
if (statSync(args.path).size > MAX_MANIFEST_BYTES) {
|
|
517
|
+
return { ok: false, path: args.path, error: `manifest non valido: supera ${MAX_MANIFEST_BYTES} byte` };
|
|
518
|
+
}
|
|
519
|
+
const text = readFileSync(args.path, "utf8");
|
|
520
|
+
const parsed = JSON.parse(text);
|
|
521
|
+
return {
|
|
522
|
+
ok: true,
|
|
523
|
+
path: args.path,
|
|
524
|
+
source: args.source,
|
|
525
|
+
sourceLabel: args.sourceLabel,
|
|
526
|
+
protectedPaths: [canonicalPolicyPath(args.path)],
|
|
527
|
+
manifest: parseVerificationManifest(parsed),
|
|
528
|
+
fingerprint: fingerprintText(text),
|
|
529
|
+
};
|
|
530
|
+
} catch (error) {
|
|
531
|
+
return {
|
|
532
|
+
ok: false,
|
|
533
|
+
path: args.path,
|
|
534
|
+
error: `manifest non valido: ${error instanceof Error ? error.message : String(error)}`,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Carica solo il manifest locale; API mantenuta per use case per-progetto espliciti. */
|
|
540
|
+
export function loadVerificationManifest(
|
|
541
|
+
cwd: string,
|
|
542
|
+
manifestPath: string,
|
|
543
|
+
): LoadedVerificationManifest {
|
|
544
|
+
const path = resolveManifestPath(cwd, manifestPath);
|
|
545
|
+
if (!path) {
|
|
546
|
+
return { ok: false, error: "percorso manifest non valido: deve restare dentro il progetto" };
|
|
547
|
+
}
|
|
548
|
+
return loadManifestAtPath({ path, source: "project", sourceLabel: `manifest locale: ${manifestPath}` });
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Precedenza: manifest locale → manifest globale dell'utente → profilo common.
|
|
553
|
+
* Un file esplicito ma malformato/non trovato non degrada silenziosamente a un
|
|
554
|
+
* altro fallback: l'utente deve accorgersi della policy che ha configurato.
|
|
555
|
+
*/
|
|
556
|
+
export function loadVerificationPolicy(
|
|
557
|
+
cwd: string,
|
|
558
|
+
settings: VerificationSettings,
|
|
559
|
+
): LoadedVerificationManifest {
|
|
560
|
+
const localPath = resolveManifestPath(cwd, settings.manifestPath);
|
|
561
|
+
if (!localPath) {
|
|
562
|
+
return { ok: false, error: "percorso manifest locale non valido: deve restare dentro il progetto" };
|
|
563
|
+
}
|
|
564
|
+
if (existsSync(localPath)) return loadVerificationManifest(cwd, settings.manifestPath);
|
|
565
|
+
|
|
566
|
+
const configuredGlobal = settings.globalManifestPath?.trim();
|
|
567
|
+
if (configuredGlobal) {
|
|
568
|
+
const globalPath = resolveGlobalManifestPath(configuredGlobal);
|
|
569
|
+
if (!globalPath) {
|
|
570
|
+
return { ok: false, error: "percorso manifest globale non valido: usa un path assoluto o ~/" };
|
|
571
|
+
}
|
|
572
|
+
return loadManifestAtPath({
|
|
573
|
+
path: globalPath,
|
|
574
|
+
source: "global-manifest",
|
|
575
|
+
sourceLabel: `manifest globale: ${globalPath}`,
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (settings.defaultProfile === "off") {
|
|
580
|
+
return { ok: false, path: localPath, error: `manifest locale non trovato: ${settings.manifestPath}; profilo globale disattivato` };
|
|
581
|
+
}
|
|
582
|
+
return loadCommonVerificationProfile(cwd);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function trustLoaded(cwd: string, loaded: LoadedVerificationManifest): VerificationManifestTrust {
|
|
586
|
+
return loaded.ok
|
|
587
|
+
? {
|
|
588
|
+
ok: true,
|
|
589
|
+
cwd: resolve(cwd),
|
|
590
|
+
path: loaded.path,
|
|
591
|
+
source: loaded.source,
|
|
592
|
+
sourceLabel: loaded.sourceLabel,
|
|
593
|
+
protectedPaths: [...loaded.protectedPaths],
|
|
594
|
+
manifest: loaded.manifest,
|
|
595
|
+
fingerprint: loaded.fingerprint,
|
|
596
|
+
}
|
|
597
|
+
: { ok: false, cwd: resolve(cwd), error: loaded.error };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Acquisisce un manifest locale esplicito; compatibilità con l'API v0.5. */
|
|
601
|
+
export function trustVerificationManifest(
|
|
602
|
+
cwd: string,
|
|
603
|
+
manifestPath: string,
|
|
604
|
+
): VerificationManifestTrust {
|
|
605
|
+
return trustLoaded(cwd, loadVerificationManifest(cwd, manifestPath));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Acquisisce la policy risolta (locale, globale o profilo integrato). */
|
|
609
|
+
export function trustVerificationPolicy(
|
|
610
|
+
cwd: string,
|
|
611
|
+
settings: VerificationSettings,
|
|
612
|
+
): VerificationManifestTrust {
|
|
613
|
+
return trustLoaded(cwd, loadVerificationPolicy(cwd, settings));
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function trustedLoaded(
|
|
617
|
+
trust: VerificationManifestTrust | undefined,
|
|
618
|
+
cwd: string,
|
|
619
|
+
current: LoadedVerificationManifest,
|
|
620
|
+
): LoadedVerificationManifest {
|
|
621
|
+
if (!trust) return { ok: false, error: "policy verifica non ancora acquisita; usa /jev verification reload" };
|
|
622
|
+
if (!trust.ok) return { ok: false, error: trust.error };
|
|
623
|
+
if (trust.cwd !== resolve(cwd)) {
|
|
624
|
+
return { ok: false, error: "policy verifica acquisita per un'altra directory; usa /jev verification reload" };
|
|
625
|
+
}
|
|
626
|
+
if (!current.ok) return current;
|
|
627
|
+
if (
|
|
628
|
+
current.path !== trust.path ||
|
|
629
|
+
current.source !== trust.source ||
|
|
630
|
+
current.fingerprint !== trust.fingerprint
|
|
631
|
+
) {
|
|
632
|
+
return {
|
|
633
|
+
ok: false,
|
|
634
|
+
path: current.path,
|
|
635
|
+
error: `${trust.source === "global-profile" ? "profilo globale" : "manifest"} modificato dopo l'acquisizione; controllalo e usa /jev verification reload`,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
ok: true,
|
|
640
|
+
path: trust.path,
|
|
641
|
+
source: trust.source,
|
|
642
|
+
sourceLabel: trust.sourceLabel,
|
|
643
|
+
protectedPaths: [...trust.protectedPaths],
|
|
644
|
+
manifest: trust.manifest,
|
|
645
|
+
fingerprint: trust.fingerprint,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** Ritorna il manifest locale acquisito, rifiutando mutazioni dopo il trust. */
|
|
650
|
+
export function trustedVerificationManifest(
|
|
651
|
+
trust: VerificationManifestTrust | undefined,
|
|
652
|
+
cwd: string,
|
|
653
|
+
manifestPath: string,
|
|
654
|
+
): LoadedVerificationManifest {
|
|
655
|
+
return trustedLoaded(trust, cwd, loadVerificationManifest(cwd, manifestPath));
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** Ritorna la policy acquisita, rifiutando mutazioni di manifest o input profilo. */
|
|
659
|
+
export function trustedVerificationPolicy(
|
|
660
|
+
trust: VerificationManifestTrust | undefined,
|
|
661
|
+
cwd: string,
|
|
662
|
+
settings: VerificationSettings,
|
|
663
|
+
): LoadedVerificationManifest {
|
|
664
|
+
return trustedLoaded(trust, cwd, loadVerificationPolicy(cwd, settings));
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function globToRegExp(pattern: string): RegExp {
|
|
668
|
+
let source = "^";
|
|
669
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
670
|
+
const char = pattern[i];
|
|
671
|
+
if (char === "*") {
|
|
672
|
+
if (pattern[i + 1] === "*") {
|
|
673
|
+
if (pattern[i + 2] === "/") {
|
|
674
|
+
source += "(?:.*/)?";
|
|
675
|
+
i += 2;
|
|
676
|
+
} else {
|
|
677
|
+
source += ".*";
|
|
678
|
+
i++;
|
|
679
|
+
}
|
|
680
|
+
} else {
|
|
681
|
+
source += "[^/]*";
|
|
682
|
+
}
|
|
683
|
+
} else if (char === "?") {
|
|
684
|
+
source += "[^/]";
|
|
685
|
+
} else {
|
|
686
|
+
source += char.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return new RegExp(`${source}$`);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** True se il check è pertinente a un file; `files` assente significa globale. */
|
|
693
|
+
export function checkMatchesPath(check: VerificationCheck, path: string): boolean {
|
|
694
|
+
if (!check.files || check.files.length === 0) return true;
|
|
695
|
+
return check.files.some((pattern) => globToRegExp(pattern).test(path));
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function latestRunAfter(
|
|
699
|
+
state: VerificationState,
|
|
700
|
+
id: string,
|
|
701
|
+
afterSeq: number,
|
|
702
|
+
): VerificationRun | undefined {
|
|
703
|
+
return state.runs
|
|
704
|
+
.filter((run) => run.id === id && run.seq > afterSeq)
|
|
705
|
+
.sort((a, b) => b.seq - a.seq)[0];
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** Stato derivato esclusivamente da modifiche e run osservati. */
|
|
709
|
+
export function buildVerificationStatus(
|
|
710
|
+
state: VerificationState,
|
|
711
|
+
loaded: LoadedVerificationManifest,
|
|
712
|
+
): VerificationStatus {
|
|
713
|
+
const modifications = [...state.modifications].sort((a, b) => a.path.localeCompare(b.path));
|
|
714
|
+
const changedFiles = modifications.map((entry) => entry.path);
|
|
715
|
+
if (changedFiles.length === 0) {
|
|
716
|
+
return {
|
|
717
|
+
changedFiles,
|
|
718
|
+
...(loaded.ok
|
|
719
|
+
? { manifestSource: loaded.source, manifestSourceLabel: loaded.sourceLabel }
|
|
720
|
+
: { manifestError: loaded.error }),
|
|
721
|
+
checks: [],
|
|
722
|
+
actionable: false,
|
|
723
|
+
hasPending: false,
|
|
724
|
+
hasFailed: false,
|
|
725
|
+
allPassed: false,
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
if (!loaded.ok) {
|
|
729
|
+
return {
|
|
730
|
+
changedFiles,
|
|
731
|
+
manifestError: loaded.error,
|
|
732
|
+
checks: [],
|
|
733
|
+
actionable: false,
|
|
734
|
+
hasPending: false,
|
|
735
|
+
hasFailed: false,
|
|
736
|
+
allPassed: false,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
const checks: VerificationCheckStatus[] = [];
|
|
740
|
+
for (const check of loaded.manifest.checks) {
|
|
741
|
+
const relevant = modifications.filter((edit) => checkMatchesPath(check, edit.path));
|
|
742
|
+
if (relevant.length === 0) continue;
|
|
743
|
+
const latestRelevantEditSeq = Math.max(...relevant.map((edit) => edit.seq));
|
|
744
|
+
const run = latestRunAfter(state, check.id, latestRelevantEditSeq);
|
|
745
|
+
checks.push({
|
|
746
|
+
check,
|
|
747
|
+
latestRelevantEditSeq,
|
|
748
|
+
...(run ? { run } : {}),
|
|
749
|
+
state: run ? (run.ok ? "passed" : "failed") : "pending",
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
const hasPending = checks.some((check) => check.state === "pending");
|
|
753
|
+
const hasFailed = checks.some((check) => check.state === "failed");
|
|
754
|
+
return {
|
|
755
|
+
changedFiles,
|
|
756
|
+
manifestSource: loaded.source,
|
|
757
|
+
manifestSourceLabel: loaded.sourceLabel,
|
|
758
|
+
checks,
|
|
759
|
+
actionable: checks.length > 0,
|
|
760
|
+
hasPending,
|
|
761
|
+
hasFailed,
|
|
762
|
+
allPassed: checks.length > 0 && !hasPending && !hasFailed,
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function code(value: string): string {
|
|
767
|
+
return `\`${value.replace(/`/g, "'")}\``;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function shortList(values: string[], max = 8): string {
|
|
771
|
+
const shown = values.slice(0, max).map(code).join(", ");
|
|
772
|
+
return values.length > max ? `${shown}, +${values.length - max}` : shown;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Footer trasparente, costruito dal guard e non dal modello. */
|
|
776
|
+
export function verificationNotice(status: VerificationStatus): string | undefined {
|
|
777
|
+
if (status.changedFiles.length === 0) return undefined;
|
|
778
|
+
const lines = [
|
|
779
|
+
"",
|
|
780
|
+
"> [jev] verifica osservata (generata dal guard, non dal modello)",
|
|
781
|
+
`> - Modifiche osservate via edit/write: ${shortList(status.changedFiles)}`,
|
|
782
|
+
];
|
|
783
|
+
if (status.manifestError) {
|
|
784
|
+
lines.push(`> - Stato: ${status.manifestError}; nessuna verifica configurata è stata attribuita.`);
|
|
785
|
+
return lines.join("\n");
|
|
786
|
+
}
|
|
787
|
+
if (status.manifestSourceLabel) {
|
|
788
|
+
lines.push(`> - Policy: ${status.manifestSourceLabel}.`);
|
|
789
|
+
}
|
|
790
|
+
if (!status.actionable) {
|
|
791
|
+
lines.push(
|
|
792
|
+
"> - Stato: nessun check della policy corrisponde ai file modificati; correttezza non verificata.",
|
|
793
|
+
);
|
|
794
|
+
return lines.join("\n");
|
|
795
|
+
}
|
|
796
|
+
for (const item of status.checks) {
|
|
797
|
+
const label = code(item.check.id);
|
|
798
|
+
if (item.state === "passed") lines.push(`> - ${label}: superato dopo l'ultima modifica pertinente.`);
|
|
799
|
+
else if (item.state === "failed") {
|
|
800
|
+
const detail = item.run?.exitCode !== undefined ? ` (exit ${item.run.exitCode})` : "";
|
|
801
|
+
lines.push(`> - ${label}: fallito${detail}.`);
|
|
802
|
+
} else {
|
|
803
|
+
lines.push(`> - ${label}: non eseguito dopo l'ultima modifica pertinente.`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return lines.join("\n");
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
export interface VerificationDecision {
|
|
810
|
+
action: "publish" | "regenerate" | "hold";
|
|
811
|
+
notice?: string;
|
|
812
|
+
feedback?: string;
|
|
813
|
+
holdText?: string;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
export function buildVerificationRepairFeedback(status: VerificationStatus): string {
|
|
817
|
+
const pending = status.checks.filter((item) => item.state === "pending").map((item) => item.check.id);
|
|
818
|
+
const failed = status.checks.filter((item) => item.state === "failed").map((item) => item.check.id);
|
|
819
|
+
return [
|
|
820
|
+
"Deterministic verification is incomplete or failing after observed edits.",
|
|
821
|
+
pending.length > 0 ? `Checks not run after relevant edits: ${pending.join(", ")}.` : "",
|
|
822
|
+
failed.length > 0 ? `Checks failed: ${failed.join(", ")}.` : "",
|
|
823
|
+
"Use jev_verify with check='recommended' to run only the project-approved pending checks.",
|
|
824
|
+
"If a check failed, inspect its real tool output, fix the code, then run it again.",
|
|
825
|
+
"Do not state that code compiles or tests pass unless the observed verification status says so.",
|
|
826
|
+
].filter(Boolean).join("\n");
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
export function buildVerificationHoldText(status: VerificationStatus): string {
|
|
830
|
+
const failed = status.checks.filter((item) => item.state === "failed").map((item) => item.check.id);
|
|
831
|
+
const pending = status.checks.filter((item) => item.state === "pending").map((item) => item.check.id);
|
|
832
|
+
return [
|
|
833
|
+
"[JEV — OUTPUT NON PUBBLICATO]",
|
|
834
|
+
"",
|
|
835
|
+
"Risultato: verification-hold",
|
|
836
|
+
`Modifiche osservate: ${status.changedFiles.join(", ")}`,
|
|
837
|
+
failed.length > 0 ? `Check falliti: ${failed.join(", ")}` : "",
|
|
838
|
+
pending.length > 0 ? `Check mancanti: ${pending.join(", ")}` : "",
|
|
839
|
+
"",
|
|
840
|
+
"La risposta non viene pubblicata finché i check configurati non sono aggiornati.",
|
|
841
|
+
].filter((line) => line !== "").join("\n");
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* `hold` è deliberatamente stretto: senza manifest/non pertinente non blocca.
|
|
846
|
+
* Su check mancanti permette prima una riparazione; su failure concreta trattiene.
|
|
847
|
+
*/
|
|
848
|
+
export function decideVerificationAction(args: {
|
|
849
|
+
status: VerificationStatus;
|
|
850
|
+
mode: VerificationMode;
|
|
851
|
+
repairsUsed: number;
|
|
852
|
+
maxRepairs: number;
|
|
853
|
+
}): VerificationDecision {
|
|
854
|
+
const { status, mode, repairsUsed, maxRepairs } = args;
|
|
855
|
+
const notice = verificationNotice(status);
|
|
856
|
+
if (status.changedFiles.length === 0 || !status.actionable) {
|
|
857
|
+
return { action: "publish", ...(notice ? { notice } : {}) };
|
|
858
|
+
}
|
|
859
|
+
const needsAction = status.hasPending || status.hasFailed;
|
|
860
|
+
if (!needsAction) return { action: "publish", ...(notice ? { notice } : {}) };
|
|
861
|
+
if (mode === "warn") return { action: "publish", ...(notice ? { notice } : {}) };
|
|
862
|
+
if (mode === "hold" && status.hasFailed) {
|
|
863
|
+
return { action: "hold", holdText: buildVerificationHoldText(status) };
|
|
864
|
+
}
|
|
865
|
+
if (repairsUsed < Math.max(0, maxRepairs)) {
|
|
866
|
+
return { action: "regenerate", feedback: buildVerificationRepairFeedback(status) };
|
|
867
|
+
}
|
|
868
|
+
if (mode === "hold") {
|
|
869
|
+
return { action: "hold", holdText: buildVerificationHoldText(status) };
|
|
870
|
+
}
|
|
871
|
+
return { action: "publish", ...(notice ? { notice } : {}) };
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
export type VerificationSelection = "recommended" | "all" | string;
|
|
875
|
+
|
|
876
|
+
export type SelectedChecks =
|
|
877
|
+
| { ok: true; checks: VerificationCheck[] }
|
|
878
|
+
| { ok: false; error: string };
|
|
879
|
+
|
|
880
|
+
/** Seleziona soltanto id dichiarati; il modello non può passare un comando. */
|
|
881
|
+
export function selectVerificationChecks(
|
|
882
|
+
loaded: LoadedVerificationManifest,
|
|
883
|
+
status: VerificationStatus,
|
|
884
|
+
selection: VerificationSelection | undefined,
|
|
885
|
+
maxCommands: number,
|
|
886
|
+
): SelectedChecks {
|
|
887
|
+
if (!loaded.ok) return { ok: false, error: loaded.error };
|
|
888
|
+
const requested = (selection ?? "recommended").trim();
|
|
889
|
+
let checks: VerificationCheck[];
|
|
890
|
+
if (requested === "recommended") {
|
|
891
|
+
if (status.changedFiles.length === 0) {
|
|
892
|
+
return { ok: false, error: "nessuna modifica edit/write osservata; usa all o un id esplicito" };
|
|
893
|
+
}
|
|
894
|
+
checks = status.checks
|
|
895
|
+
.filter((item) => item.state !== "passed")
|
|
896
|
+
.map((item) => item.check);
|
|
897
|
+
if (checks.length === 0) return { ok: false, error: "tutti i check pertinenti risultano già superati" };
|
|
898
|
+
} else if (requested === "all") {
|
|
899
|
+
checks = [...loaded.manifest.checks];
|
|
900
|
+
} else {
|
|
901
|
+
const found = loaded.manifest.checks.find((check) => check.id === requested);
|
|
902
|
+
if (!found) return { ok: false, error: `check sconosciuto: ${requested}` };
|
|
903
|
+
checks = [found];
|
|
904
|
+
}
|
|
905
|
+
const numericMax = typeof maxCommands === "number" && Number.isFinite(maxCommands)
|
|
906
|
+
? maxCommands
|
|
907
|
+
: 3;
|
|
908
|
+
const max = Math.max(1, Math.min(20, Math.floor(numericMax)));
|
|
909
|
+
if (checks.length > max) {
|
|
910
|
+
return { ok: false, error: `selezione contiene ${checks.length} check, oltre maxCommands=${max}` };
|
|
911
|
+
}
|
|
912
|
+
return { ok: true, checks };
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** Match conservativo per i bash nativi: solo comando identico, whitespace normalizzato. */
|
|
916
|
+
export function manifestCheckForCommand(
|
|
917
|
+
manifest: VerificationManifest,
|
|
918
|
+
command: unknown,
|
|
919
|
+
): VerificationCheck | undefined {
|
|
920
|
+
if (typeof command !== "string") return undefined;
|
|
921
|
+
const normalized = command.trim().replace(/\s+/g, " ");
|
|
922
|
+
if (!normalized) return undefined;
|
|
923
|
+
return manifest.checks.find(
|
|
924
|
+
(check) => check.command.replace(/\s+/g, " ") === normalized,
|
|
925
|
+
);
|
|
926
|
+
}
|