@planu/cli 5.7.11 → 5.7.12

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/package-handoff.js +10 -3
  4. package/dist/config/runtime-policy.json +2 -1
  5. package/dist/engine/abortable-process-runner.js +1 -0
  6. package/dist/engine/bump-carrier-binding.d.ts +10 -0
  7. package/dist/engine/bump-carrier-binding.js +276 -0
  8. package/dist/engine/handoff-artifacts/schemas.d.ts +20 -0
  9. package/dist/engine/handoff-artifacts/schemas.js +12 -0
  10. package/dist/engine/runtime-policy.js +4 -0
  11. package/dist/engine/source-quality-binding.d.ts +26 -0
  12. package/dist/engine/source-quality-binding.js +162 -0
  13. package/dist/engine/source-quality-receipt-reader.d.ts +3 -0
  14. package/dist/engine/source-quality-receipt-reader.js +51 -0
  15. package/dist/engine/spec-format/bdd-parser.js +7 -4
  16. package/dist/engine/spec-format/technical-md-populator.js +114 -3
  17. package/dist/engine/spec-format/unified-spec-builder.js +33 -6
  18. package/dist/engine/validator/blast-radius-gate.d.ts +3 -0
  19. package/dist/engine/validator/blast-radius-gate.js +139 -0
  20. package/dist/engine/validator/spec-compliance-runner.d.ts +1 -0
  21. package/dist/engine/validator/spec-compliance-runner.js +3 -0
  22. package/dist/engine/validator/validation-report-writer.d.ts +2 -0
  23. package/dist/engine/validator/validation-report-writer.js +68 -30
  24. package/dist/storage/runtime-db.js +7 -3
  25. package/dist/storage/spec-store.js +6 -2
  26. package/dist/tools/challenge-spec/scenarios-data.js +2 -2
  27. package/dist/tools/challenge-spec/scenarios-utils.d.ts +2 -0
  28. package/dist/tools/challenge-spec/scenarios-utils.js +36 -3
  29. package/dist/tools/validate-lint.js +19 -0
  30. package/dist/tools/validate.js +46 -4
  31. package/dist/types/abortable-process.d.ts +1 -0
  32. package/dist/types/handoff-artifacts.d.ts +10 -0
  33. package/dist/types/runtime-policy.d.ts +1 -0
  34. package/dist/types/spec-format.d.ts +9 -0
  35. package/dist/types/validation-evidence.d.ts +21 -0
  36. package/package.json +2 -2
  37. package/planu-plugin.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,30 @@
1
+ ## [5.7.12] - 2026-09-03
2
+
3
+ ### Features
4
+ - feat(validate): reuse the source-quality receipt in the lint check
5
+ - feat(validate): run vitest related over the spec's affected files as a blast-radius gate
6
+ - feat(auto-merge): reuse the source-quality receipt in auto-merge.sh and validate:full
7
+
8
+ ### Bug Fixes
9
+ - fix(validator): resolve the blast-radius test runner binary through the technology registry
10
+ - fix(spec-format): fence-aware author section extraction and byte-identical fallback coverage
11
+ - fix(spec-format): use the first author section as the problem fallback instead of the whole source
12
+ - fix(hooks): call lint-staged through node_modules/.bin so pnpm cannot reinstall node_modules on commit
13
+ - fix(challenge-spec): scope the test-context guard per clause and accept DDL actions
14
+ - fix(challenge-spec): anchor database and cache capability signals to persistence and caching actions
15
+ - fix(cli): forward the project path to package_handoff and refresh drifted spec scalars
16
+ - fix(spec-format): accept flat Create/Modify/Test labels and merge sectioned with labelled Files
17
+ - fix(spec-format): keep labelled Files to create/modify entries in Files section
18
+ - fix(runtime-db): treat payload resubmission of a completed job as a fresh run
19
+ - fix(receipt): bound binding probes, skip absent receipt dirs and prove ledger reuse
20
+ - fix(validate): harden the blast-radius gate parsing, path handling and report persistence
21
+ - fix(pre-push): skip product tests on mirror sync of origin/main and surface build-step diagnostics
22
+ - fix(bdd-parser): accept markdown scenario headings and uppercase WHEN-opened blocks
23
+
24
+ ### Refactoring
25
+ - refactor(receipt): move source-quality binding computation into the engine
26
+
27
+
1
28
  ## [5.7.11] - 2026-09-02
2
29
 
3
30
  ### Features
@@ -1 +1 @@
1
- {"schemaVersion":1,"commit":"751d4ec85be2cb3fcb93112587d70211814166b0"}
1
+ {"schemaVersion":1,"commit":"088e6b8cc7a4e82395e945609d0c575d31895578"}
@@ -41,9 +41,16 @@ export const packageHandoffCommand = {
41
41
  return;
42
42
  }
43
43
  const projectPath = values['project-path'];
44
- const projectId = values['project-id'] ??
45
- detectProjectId(projectPath ? resolve(projectPath) : undefined);
46
- const submission = await handlePackageHandoff({ projectId, specId });
44
+ const resolvedPath = projectPath ? resolve(projectPath) : undefined;
45
+ const detectedId = detectProjectId(resolvedPath);
46
+ const explicitProjectId = values['project-id'];
47
+ if (explicitProjectId && resolvedPath && explicitProjectId !== detectedId) {
48
+ process.stderr.write(`${red('Error:')} --project-id ${explicitProjectId} does not match the project detected at ${resolvedPath} (${detectedId})\n`);
49
+ process.exitCode = 1;
50
+ return;
51
+ }
52
+ const projectId = explicitProjectId ?? detectedId;
53
+ const submission = await handlePackageHandoff({ projectId, specId, projectPath: resolvedPath });
47
54
  if (submission.isError) {
48
55
  process.stderr.write(`${red(formatToolResult(submission, flags))}\n`);
49
56
  process.exitCode = 1;
@@ -44,7 +44,8 @@
44
44
  "freshnessInvalidationCoalesceMs": 25,
45
45
  "receiptPublicationDeadlineMs": 20000,
46
46
  "receiptCheckpointLogMaxBytes": 1048576,
47
- "receiptCheckpointResultMaxBytes": 4194304
47
+ "receiptCheckpointResultMaxBytes": 4194304,
48
+ "blastRadiusTimeoutMs": 300000
48
49
  },
49
50
  "postCommit": {
50
51
  "defaultTaskTimeoutMs": 10000,
@@ -145,6 +145,7 @@ export function runAbortableProcess(command, args, options) {
145
145
  cwd: options.cwd,
146
146
  detached: runtimePlatform() !== 'win32',
147
147
  stdio: ['ignore', 'pipe', 'pipe'],
148
+ ...(options.env !== undefined ? { env: options.env } : {}),
148
149
  });
149
150
  let stdout = '';
150
151
  let stderr = '';
@@ -0,0 +1,10 @@
1
+ export declare const VERSION_PLACEHOLDER = "0.0.0";
2
+ export declare const BUMP_CARRIER_STRUCTURAL_PATHS: readonly ['package.json', 'planu-plugin.json', 'pnpm-lock.yaml', 'website/public/proof/product-proof.json'];
3
+ export declare const BUMP_CARRIER_EXCLUDED_PATHS: readonly ['CHANGELOG.md', 'planu/session-context.md', 'planu/project.json'];
4
+ export declare function isStructuralCarrierPath(path: string): boolean;
5
+ export declare function isExcludedCarrierPath(path: string): boolean;
6
+ export declare function isBumpCarrierPath(path: string): boolean;
7
+ export declare function canonical(value: unknown): string;
8
+ export declare function normalizeCarrierBytes(path: string, raw: Buffer): Buffer;
9
+ export declare function filterMaskedTreeEntries(entries: string[]): string[];
10
+ //# sourceMappingURL=bump-carrier-binding.d.ts.map
@@ -0,0 +1,276 @@
1
+ export const VERSION_PLACEHOLDER = '0.0.0';
2
+ export const BUMP_CARRIER_STRUCTURAL_PATHS = [
3
+ 'package.json',
4
+ 'planu-plugin.json',
5
+ 'pnpm-lock.yaml',
6
+ 'website/public/proof/product-proof.json',
7
+ ];
8
+ export const BUMP_CARRIER_EXCLUDED_PATHS = [
9
+ 'CHANGELOG.md',
10
+ 'planu/session-context.md',
11
+ 'planu/project.json',
12
+ ];
13
+ const STRUCTURAL_SET = new Set(BUMP_CARRIER_STRUCTURAL_PATHS);
14
+ const EXCLUDED_SET = new Set(BUMP_CARRIER_EXCLUDED_PATHS);
15
+ const CARRIER_SET = new Set([...STRUCTURAL_SET, ...EXCLUDED_SET]);
16
+ export function isStructuralCarrierPath(path) {
17
+ return STRUCTURAL_SET.has(path);
18
+ }
19
+ export function isExcludedCarrierPath(path) {
20
+ return EXCLUDED_SET.has(path);
21
+ }
22
+ export function isBumpCarrierPath(path) {
23
+ return CARRIER_SET.has(path);
24
+ }
25
+ export function canonical(value) {
26
+ if (Array.isArray(value)) {
27
+ return `[${value.map(canonical).join(',')}]`;
28
+ }
29
+ if (value !== null && typeof value === 'object') {
30
+ return `{${Object.entries(value)
31
+ .sort(([left], [right]) => left.localeCompare(right))
32
+ .map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`)
33
+ .join(',')}}`;
34
+ }
35
+ return JSON.stringify(value);
36
+ }
37
+ function findUniqueLineMatch(text, pattern) {
38
+ const matches = [...text.matchAll(new RegExp(pattern, 'gmu'))];
39
+ if (matches.length !== 1) {
40
+ return null;
41
+ }
42
+ const match = matches[0];
43
+ if (match === undefined) {
44
+ return null;
45
+ }
46
+ const [full, prefix = '', value = '', suffix = ''] = match;
47
+ return { full, prefix, value, suffix, index: match.index };
48
+ }
49
+ function substituteLine(text, pattern, replacement) {
50
+ const match = findUniqueLineMatch(text, pattern);
51
+ if (match === null) {
52
+ return null;
53
+ }
54
+ const replaced = `${match.prefix}${replacement(match.value)}${match.suffix}`;
55
+ return text.slice(0, match.index) + replaced + text.slice(match.index + match.full.length);
56
+ }
57
+ function substituteAllLines(text, pattern, expectedCount, replacement) {
58
+ const matches = [...text.matchAll(new RegExp(pattern, 'gmu'))];
59
+ if (matches.length !== expectedCount) {
60
+ return null;
61
+ }
62
+ let result = '';
63
+ let cursor = 0;
64
+ for (const match of matches) {
65
+ const [full, prefix = '', value = '', suffix = ''] = match;
66
+ result += text.slice(cursor, match.index) + prefix + replacement(value) + suffix;
67
+ cursor = match.index + full.length;
68
+ }
69
+ return result + text.slice(cursor);
70
+ }
71
+ function isIsoTimestamp(value) {
72
+ if (typeof value !== 'string') {
73
+ return false;
74
+ }
75
+ const date = new Date(value);
76
+ return !Number.isNaN(date.getTime()) && date.toISOString() === value;
77
+ }
78
+ function isLosslessUtf8(raw, text) {
79
+ return Buffer.from(text, 'utf8').equals(raw);
80
+ }
81
+ const TOP_LEVEL_VERSION_LINE = /^( {2}"version": ")([^"]*)(",?)$/mu;
82
+ function normalizeVersionField(raw) {
83
+ const text = raw.toString('utf8');
84
+ if (!isLosslessUtf8(raw, text)) {
85
+ return raw;
86
+ }
87
+ const next = substituteLine(text, TOP_LEVEL_VERSION_LINE, () => VERSION_PLACEHOLDER);
88
+ return next === null ? raw : Buffer.from(next, 'utf8');
89
+ }
90
+ const RELEASE_VERSION_LINE = /^( {4}"version": ")([^"]*)(",?)$/mu;
91
+ const RELEASE_TAG_LINE = /^( {4}"tag": ")([^"]*)(",?)$/mu;
92
+ const RELEASE_SOURCE_URL_LINE = /^( {6}"url": ")([^"]*)(")$/mu;
93
+ const RELEASE_COMMIT_LINE = /^( {4}"commit": ")([^"]*)(",?)$/mu;
94
+ const TOP_LEVEL_GENERATED_AT_LINE = /^( {2}"generatedAt": ")([^"]*)(",?)$/mu;
95
+ const RELEASE_VERIFIED_AT_LINE = /^( {4}"verifiedAt": ")([^"]*)(",?)$/mu;
96
+ const METRIC_VERIFIED_AT_LINE = /^( {6}"verifiedAt": ")([^"]*)(",?)$/mu;
97
+ const METRICS_ARRAY_HEADER = '\n "metrics": [';
98
+ const COMMIT_SHA_PATTERN = /^[0-9a-f]{40}$/u;
99
+ const COMMIT_SHA_PLACEHOLDER = '0'.repeat(40);
100
+ const TIMESTAMP_PLACEHOLDER = '1970-01-01T00:00:00.000Z';
101
+ function findMetricsArrayRegion(text) {
102
+ const headerIndex = text.indexOf(METRICS_ARRAY_HEADER);
103
+ if (headerIndex === -1 || text.includes(METRICS_ARRAY_HEADER, headerIndex + 1)) {
104
+ return null;
105
+ }
106
+ const start = headerIndex + METRICS_ARRAY_HEADER.length;
107
+ const closeIndex = text.indexOf('\n ]', start);
108
+ if (closeIndex === -1) {
109
+ return null;
110
+ }
111
+ return { start, end: closeIndex };
112
+ }
113
+ function substituteAllLinesInRegion(text, region, pattern, expectedCount, replacement) {
114
+ const slice = text.slice(region.start, region.end);
115
+ const replacedSlice = substituteAllLines(slice, pattern, expectedCount, replacement);
116
+ if (replacedSlice === null) {
117
+ return null;
118
+ }
119
+ return text.slice(0, region.start) + replacedSlice + text.slice(region.end);
120
+ }
121
+ function parseValidatedProductProof(text) {
122
+ let parsed;
123
+ try {
124
+ parsed = JSON.parse(text);
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ const release = parsed.release;
130
+ if (!release || typeof release !== 'object') {
131
+ return null;
132
+ }
133
+ const { version, tag, source, commit, verifiedAt: releaseVerifiedAt } = release;
134
+ if (typeof version !== 'string' || typeof tag !== 'string' || tag !== `v${version}`) {
135
+ return null;
136
+ }
137
+ const url = source && typeof source === 'object' ? source.url : undefined;
138
+ if (typeof url !== 'string' || !url.includes(version)) {
139
+ return null;
140
+ }
141
+ if (typeof commit !== 'string' || !COMMIT_SHA_PATTERN.test(commit)) {
142
+ return null;
143
+ }
144
+ if (!isIsoTimestamp(parsed.generatedAt) || !isIsoTimestamp(releaseVerifiedAt)) {
145
+ return null;
146
+ }
147
+ const metrics = parsed.metrics;
148
+ if (!Array.isArray(metrics)) {
149
+ return null;
150
+ }
151
+ for (const metric of metrics) {
152
+ if (!metric ||
153
+ typeof metric !== 'object' ||
154
+ !isIsoTimestamp(metric.verifiedAt)) {
155
+ return null;
156
+ }
157
+ }
158
+ return { version, metricsCount: metrics.length };
159
+ }
160
+ function normalizeProductProof(raw) {
161
+ const text = raw.toString('utf8');
162
+ if (!isLosslessUtf8(raw, text)) {
163
+ return raw;
164
+ }
165
+ const validated = parseValidatedProductProof(text);
166
+ if (validated === null) {
167
+ return raw;
168
+ }
169
+ const { version, metricsCount } = validated;
170
+ let next = substituteLine(text, RELEASE_VERSION_LINE, () => VERSION_PLACEHOLDER);
171
+ if (next === null) {
172
+ return raw;
173
+ }
174
+ next = substituteLine(next, RELEASE_TAG_LINE, () => `v${VERSION_PLACEHOLDER}`);
175
+ if (next === null) {
176
+ return raw;
177
+ }
178
+ next = substituteLine(next, RELEASE_SOURCE_URL_LINE, (value) => value.split(version).join(VERSION_PLACEHOLDER));
179
+ if (next === null) {
180
+ return raw;
181
+ }
182
+ next = substituteLine(next, RELEASE_COMMIT_LINE, () => COMMIT_SHA_PLACEHOLDER);
183
+ if (next === null) {
184
+ return raw;
185
+ }
186
+ next = substituteLine(next, TOP_LEVEL_GENERATED_AT_LINE, () => TIMESTAMP_PLACEHOLDER);
187
+ if (next === null) {
188
+ return raw;
189
+ }
190
+ next = substituteLine(next, RELEASE_VERIFIED_AT_LINE, () => TIMESTAMP_PLACEHOLDER);
191
+ if (next === null) {
192
+ return raw;
193
+ }
194
+ const metricsRegion = findMetricsArrayRegion(next);
195
+ if (metricsRegion === null) {
196
+ return raw;
197
+ }
198
+ next = substituteAllLinesInRegion(next, metricsRegion, METRIC_VERIFIED_AT_LINE, metricsCount, () => TIMESTAMP_PLACEHOLDER);
199
+ if (next === null) {
200
+ return raw;
201
+ }
202
+ return Buffer.from(next, 'utf8');
203
+ }
204
+ const IMPORTERS_HEADER = /^importers:\s*$/u;
205
+ const ROOT_IMPORTER_HEADER = /^ {2}\.:\s*$/u;
206
+ const IMPORTER_KEY = /^ {2}\S/u;
207
+ const ROOT_VERSION_LINE = /^( {4}version:\s*)\S.*$/u;
208
+ function normalizePnpmLock(raw) {
209
+ const lines = raw.toString('utf8').split('\n');
210
+ let inImporters = false;
211
+ let inRootImporter = false;
212
+ const normalized = lines.map((line) => {
213
+ if (IMPORTERS_HEADER.test(line)) {
214
+ inImporters = true;
215
+ inRootImporter = false;
216
+ return line;
217
+ }
218
+ if (!inImporters) {
219
+ return line;
220
+ }
221
+ if (/^\S/u.test(line)) {
222
+ inImporters = false;
223
+ inRootImporter = false;
224
+ return line;
225
+ }
226
+ if (ROOT_IMPORTER_HEADER.test(line)) {
227
+ inRootImporter = true;
228
+ return line;
229
+ }
230
+ if (IMPORTER_KEY.test(line)) {
231
+ inRootImporter = false;
232
+ return line;
233
+ }
234
+ if (inRootImporter) {
235
+ const match = ROOT_VERSION_LINE.exec(line);
236
+ if (match) {
237
+ return `${match[1]}${VERSION_PLACEHOLDER}`;
238
+ }
239
+ }
240
+ return line;
241
+ });
242
+ return Buffer.from(normalized.join('\n'), 'utf8');
243
+ }
244
+ export function normalizeCarrierBytes(path, raw) {
245
+ try {
246
+ if (path === 'package.json' || path === 'planu-plugin.json') {
247
+ return normalizeVersionField(raw);
248
+ }
249
+ if (path === 'website/public/proof/product-proof.json') {
250
+ return normalizeProductProof(raw);
251
+ }
252
+ if (path === 'pnpm-lock.yaml') {
253
+ return normalizePnpmLock(raw);
254
+ }
255
+ }
256
+ catch {
257
+ return raw;
258
+ }
259
+ return raw;
260
+ }
261
+ const MASKED_OBJECT_ID = '0'.repeat(40);
262
+ export function filterMaskedTreeEntries(entries) {
263
+ return entries.map((entry) => {
264
+ const tabIndex = entry.indexOf('\t');
265
+ if (tabIndex === -1) {
266
+ return entry;
267
+ }
268
+ const path = entry.slice(tabIndex + 1);
269
+ if (!isBumpCarrierPath(path)) {
270
+ return entry;
271
+ }
272
+ const [mode, type] = entry.slice(0, tabIndex).split(' ');
273
+ return `${mode} ${type} ${MASKED_OBJECT_ID}\t${path}`;
274
+ });
275
+ }
276
+ //# sourceMappingURL=bump-carrier-binding.js.map
@@ -181,6 +181,16 @@ export declare const ValidationReportV1Schema: z.ZodObject<{
181
181
  }, z.core.$strip>>;
182
182
  score: z.ZodOptional<z.ZodNumber>;
183
183
  completedAt: z.ZodISODateTime;
184
+ blastRadius: z.ZodOptional<z.ZodObject<{
185
+ selectedFiles: z.ZodNumber;
186
+ passed: z.ZodBoolean;
187
+ timedOut: z.ZodBoolean;
188
+ skipped: z.ZodOptional<z.ZodString>;
189
+ failures: z.ZodArray<z.ZodObject<{
190
+ file: z.ZodString;
191
+ message: z.ZodString;
192
+ }, z.core.$strip>>;
193
+ }, z.core.$strip>>;
184
194
  }, z.core.$strip>;
185
195
  export declare const ReconciliationReceiptV1Schema: z.ZodType<ReconciliationReceiptV1>;
186
196
  export declare const ARTIFACT_SCHEMAS: {
@@ -339,6 +349,16 @@ export declare const ARTIFACT_SCHEMAS: {
339
349
  }, z.core.$strip>>;
340
350
  score: z.ZodOptional<z.ZodNumber>;
341
351
  completedAt: z.ZodISODateTime;
352
+ blastRadius: z.ZodOptional<z.ZodObject<{
353
+ selectedFiles: z.ZodNumber;
354
+ passed: z.ZodBoolean;
355
+ timedOut: z.ZodBoolean;
356
+ skipped: z.ZodOptional<z.ZodString>;
357
+ failures: z.ZodArray<z.ZodObject<{
358
+ file: z.ZodString;
359
+ message: z.ZodString;
360
+ }, z.core.$strip>>;
361
+ }, z.core.$strip>>;
342
362
  }, z.core.$strip>;
343
363
  readonly implementation_review: z.ZodObject<{
344
364
  schema_version: z.ZodString;
@@ -136,6 +136,18 @@ export const ValidationReportV1Schema = z.object({
136
136
  .optional(),
137
137
  score: z.number().optional(),
138
138
  completedAt: z.iso.datetime(),
139
+ blastRadius: z
140
+ .object({
141
+ selectedFiles: z.number(),
142
+ passed: z.boolean(),
143
+ timedOut: z.boolean(),
144
+ skipped: z.string().optional(),
145
+ failures: z.array(z.object({
146
+ file: z.string(),
147
+ message: z.string(),
148
+ })),
149
+ })
150
+ .optional(),
139
151
  });
140
152
  export const ReconciliationReceiptV1Schema = z.object({
141
153
  schema_version: z.literal('1.0.0'),
@@ -63,8 +63,12 @@ const runtimePolicySchema = z
63
63
  receiptPublicationDeadlineMs: z.number().int().positive(),
64
64
  receiptCheckpointLogMaxBytes: z.number().int().positive(),
65
65
  receiptCheckpointResultMaxBytes: z.number().int().positive(),
66
+ blastRadiusTimeoutMs: z.number().int().positive(),
66
67
  })
67
68
  .strict()
69
+ .refine((value) => value.blastRadiusTimeoutMs < value.complianceCommandTimeoutMs, {
70
+ message: 'blastRadiusTimeoutMs must be below complianceCommandTimeoutMs',
71
+ })
68
72
  .refine((value) => value.submissionLockPollMs < value.submissionLockWaitMs, {
69
73
  message: 'submissionLockPollMs must be below submissionLockWaitMs',
70
74
  })
@@ -0,0 +1,26 @@
1
+ export declare class SourceQualityBindingError extends Error {
2
+ }
3
+ export declare function runIdentity(command: string, args: string[], cwd: string): string;
4
+ export declare function sha256(value: string | Buffer): string;
5
+ export declare function assertCleanSource(projectPath: string): void;
6
+ export declare function readPolicy(projectPath: string): {
7
+ sourceQualityPlan: {
8
+ id: string;
9
+ executable: string;
10
+ args: string[];
11
+ timeoutSeconds: number;
12
+ }[];
13
+ sourceReceiptInputPatterns: string[];
14
+ };
15
+ export declare function computeBinding(projectPath: string): {
16
+ source: {
17
+ maskedTreeDigest: string;
18
+ };
19
+ inputs: {
20
+ path: string;
21
+ sha256: string;
22
+ }[];
23
+ commandPlan: ReturnType<typeof readPolicy>['sourceQualityPlan'];
24
+ toolchain: Record<string, unknown>;
25
+ };
26
+ //# sourceMappingURL=source-quality-binding.d.ts.map
@@ -0,0 +1,162 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { basename, join } from 'node:path';
5
+ import { BUMP_CARRIER_STRUCTURAL_PATHS, canonical, filterMaskedTreeEntries, isExcludedCarrierPath, isStructuralCarrierPath, normalizeCarrierBytes, } from './bump-carrier-binding.js';
6
+ export class SourceQualityBindingError extends Error {
7
+ }
8
+ const IDENTITY_PROBE_TIMEOUT_MS = 30_000;
9
+ function fail(message) {
10
+ throw new SourceQualityBindingError(message);
11
+ }
12
+ function cleanChildEnv() {
13
+ const env = { ...process.env };
14
+ delete env.NODE_OPTIONS;
15
+ delete env.NODE_PATH;
16
+ delete env.BASH_ENV;
17
+ delete env.ENV;
18
+ return env;
19
+ }
20
+ export function runIdentity(command, args, cwd) {
21
+ const result = spawnSync(command, args, {
22
+ cwd,
23
+ encoding: 'utf8',
24
+ env: cleanChildEnv(),
25
+ stdio: ['ignore', 'pipe', 'pipe'],
26
+ timeout: IDENTITY_PROBE_TIMEOUT_MS,
27
+ });
28
+ if (result.error) {
29
+ fail(`cannot identify ${basename(command)}: ${result.error.message}`);
30
+ }
31
+ if (result.signal) {
32
+ fail(`cannot identify ${basename(command)}: timed out after ${String(IDENTITY_PROBE_TIMEOUT_MS)}ms`);
33
+ }
34
+ if (result.status !== 0) {
35
+ const detail = (result.stderr || result.stdout).trim().split(/\r?\n/u)[0];
36
+ fail(`cannot identify ${basename(command)}${detail ? `: ${detail}` : ''}`);
37
+ }
38
+ return result.stdout.trim();
39
+ }
40
+ export function sha256(value) {
41
+ return createHash('sha256').update(value).digest('hex');
42
+ }
43
+ export function assertCleanSource(projectPath) {
44
+ const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=normal'], {
45
+ cwd: projectPath,
46
+ encoding: 'utf8',
47
+ timeout: IDENTITY_PROBE_TIMEOUT_MS,
48
+ });
49
+ if (result.error) {
50
+ fail(`cannot check source cleanliness: ${result.error.message}`);
51
+ }
52
+ if (result.signal) {
53
+ fail(`cannot check source cleanliness: timed out after ${String(IDENTITY_PROBE_TIMEOUT_MS)}ms`);
54
+ }
55
+ if (result.status !== 0 || result.stdout.trim()) {
56
+ fail('requires a clean exact release commit');
57
+ }
58
+ }
59
+ function computeMaskedTreeDigest(projectPath) {
60
+ const entries = runIdentity('git', ['ls-tree', '-r', '-z', 'HEAD'], projectPath)
61
+ .split('\0')
62
+ .filter(Boolean);
63
+ return sha256(filterMaskedTreeEntries(entries).join('\0'));
64
+ }
65
+ function isPlanStep(value) {
66
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
67
+ return false;
68
+ }
69
+ const step = value;
70
+ return (Object.keys(step).sort().join(',') === 'args,executable,id,timeoutSeconds' &&
71
+ typeof step.id === 'string' &&
72
+ /^[a-z][a-z0-9-]*$/u.test(step.id) &&
73
+ typeof step.executable === 'string' &&
74
+ /^[A-Za-z0-9._+-]+$/u.test(step.executable) &&
75
+ Array.isArray(step.args) &&
76
+ step.args.every((argument) => typeof argument === 'string' && !argument.includes('\0')) &&
77
+ Number.isSafeInteger(step.timeoutSeconds) &&
78
+ Number(step.timeoutSeconds) > 0);
79
+ }
80
+ function isNonEmptyStringArray(value) {
81
+ return (Array.isArray(value) &&
82
+ value.length > 0 &&
83
+ value.every((entry) => typeof entry === 'string' && !!entry));
84
+ }
85
+ export function readPolicy(projectPath) {
86
+ const policyPath = join(projectPath, 'src/config/release-policy.json');
87
+ let optimization;
88
+ try {
89
+ const policy = JSON.parse(readFileSync(policyPath, 'utf8'));
90
+ optimization = policy.releaseOptimization ?? {};
91
+ }
92
+ catch {
93
+ fail('policy is missing or malformed');
94
+ }
95
+ const plan = optimization.sourceQualityPlan;
96
+ const patterns = optimization.sourceReceiptInputPatterns;
97
+ const validPlan = Array.isArray(plan) &&
98
+ plan.length > 0 &&
99
+ plan.every(isPlanStep) &&
100
+ new Set(plan.map(({ id }) => id)).size === plan.length;
101
+ if (!validPlan || !isNonEmptyStringArray(patterns)) {
102
+ fail('policy does not define one canonical structured source-gate plan');
103
+ }
104
+ const validate = plan.filter(({ executable, args }) => executable === 'pnpm' && canonical(args) === canonical(['validate']));
105
+ const strict = plan.filter(({ executable, args }) => executable === 'pnpm' && canonical(args) === canonical(['check:strict']));
106
+ if (validate.length !== 1 || strict.length !== 1) {
107
+ fail('policy must execute pnpm validate and pnpm check:strict exactly once');
108
+ }
109
+ return {
110
+ sourceQualityPlan: plan,
111
+ sourceReceiptInputPatterns: patterns,
112
+ };
113
+ }
114
+ function conciseIdentity(command, args, cwd) {
115
+ const output = runIdentity(command, args, cwd);
116
+ const lines = output.split(/\r?\n/u).filter(Boolean);
117
+ const version = lines[0] ?? '';
118
+ if (!version) {
119
+ fail(`returned an empty identity for ${basename(command)}`);
120
+ }
121
+ return { version, outputSha256: sha256(output) };
122
+ }
123
+ function collectToolchain(cwd) {
124
+ return {
125
+ node: { version: process.version, versionsSha256: sha256(canonical(process.versions)) },
126
+ npm: conciseIdentity('npm', ['--version'], cwd),
127
+ pnpm: conciseIdentity('pnpm', ['--version'], cwd),
128
+ };
129
+ }
130
+ function collectInputs(projectPath, patterns) {
131
+ let matchers;
132
+ try {
133
+ matchers = patterns.map((pattern) => new RegExp(pattern, 'u'));
134
+ }
135
+ catch {
136
+ fail('policy contains an invalid source input pattern');
137
+ }
138
+ const tracked = runIdentity('git', ['ls-files', '-z'], projectPath).split('\0').filter(Boolean);
139
+ const trackedSet = new Set(tracked);
140
+ const patternSelected = tracked.filter((path) => matchers.some((matcher) => matcher.test(path)) && !isExcludedCarrierPath(path));
141
+ const structuralSelected = BUMP_CARRIER_STRUCTURAL_PATHS.filter((path) => trackedSet.has(path));
142
+ const selected = [...new Set([...patternSelected, ...structuralSelected])].sort();
143
+ if (selected.length === 0 || !selected.includes('src/config/release-policy.json')) {
144
+ fail('input plan does not bind the release policy');
145
+ }
146
+ return selected.map((path) => {
147
+ const raw = readFileSync(join(projectPath, path));
148
+ const bytes = isStructuralCarrierPath(path) ? normalizeCarrierBytes(path, raw) : raw;
149
+ return { path, sha256: sha256(bytes) };
150
+ });
151
+ }
152
+ export function computeBinding(projectPath) {
153
+ assertCleanSource(projectPath);
154
+ const policy = readPolicy(projectPath);
155
+ return {
156
+ source: { maskedTreeDigest: computeMaskedTreeDigest(projectPath) },
157
+ inputs: collectInputs(projectPath, policy.sourceReceiptInputPatterns),
158
+ commandPlan: policy.sourceQualityPlan,
159
+ toolchain: collectToolchain(projectPath),
160
+ };
161
+ }
162
+ //# sourceMappingURL=source-quality-binding.js.map
@@ -0,0 +1,3 @@
1
+ import type { SourceQualityReceiptMatch } from '../types/index.js';
2
+ export declare function readMatchingSourceQualityReceipt(projectPath: string, command: string): SourceQualityReceiptMatch | null;
3
+ //# sourceMappingURL=source-quality-receipt-reader.d.ts.map
@@ -0,0 +1,51 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { canonical } from './bump-carrier-binding.js';
4
+ import { computeBinding, runIdentity, sha256 } from './source-quality-binding.js';
5
+ import { VALIDATION_COMMANDS } from './validation-impact-planner.js';
6
+ function successfulResults(commandPlan) {
7
+ return commandPlan.map(({ id, executable, args }) => ({ id, executable, args, exitCode: 0 }));
8
+ }
9
+ function gitDirectory(projectPath) {
10
+ const value = runIdentity('git', ['rev-parse', '--git-dir'], projectPath);
11
+ return realpathSync(isAbsolute(value) ? value : join(projectPath, value));
12
+ }
13
+ function isCanonicalReceiptFile(path) {
14
+ return (existsSync(path) &&
15
+ !lstatSync(path).isSymbolicLink() &&
16
+ lstatSync(path).isFile() &&
17
+ realpathSync(path) === path &&
18
+ (statSync(path).mode & 0o777) === 0o600);
19
+ }
20
+ function receiptDirectoryHasReceipts(receiptDirectory) {
21
+ return (existsSync(receiptDirectory) &&
22
+ readdirSync(receiptDirectory).some((entry) => entry.endsWith('.json')));
23
+ }
24
+ export function readMatchingSourceQualityReceipt(projectPath, command) {
25
+ if (command !== VALIDATION_COMMANDS.lint) {
26
+ return null;
27
+ }
28
+ try {
29
+ const receiptDirectory = join(gitDirectory(projectPath), 'planu-release-artifacts', 'source-quality');
30
+ if (!receiptDirectoryHasReceipts(receiptDirectory)) {
31
+ return null;
32
+ }
33
+ const binding = computeBinding(projectPath);
34
+ const results = successfulResults(binding.commandPlan);
35
+ const key = sha256(canonical({ binding, results }));
36
+ const path = join(receiptDirectory, `${key}.json`);
37
+ if (!isCanonicalReceiptFile(path)) {
38
+ return null;
39
+ }
40
+ const actual = JSON.parse(readFileSync(path, 'utf8'));
41
+ const expected = { schemaVersion: 1, key, binding, results };
42
+ if (canonical(actual) !== canonical(expected)) {
43
+ return null;
44
+ }
45
+ return { key, path };
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ //# sourceMappingURL=source-quality-receipt-reader.js.map