@planu/cli 8.2.20 → 8.4.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +118 -3
  3. package/dist/sdd-engine/completion-snapshot.d.ts +5 -1
  4. package/dist/sdd-engine/completion-snapshot.js +79 -2
  5. package/dist/sdd-engine/contracts.d.ts +6 -3
  6. package/dist/sdd-engine/contracts.js +30 -3
  7. package/dist/sdd-engine/feature-authority.d.ts +3 -1
  8. package/dist/sdd-engine/feature-authority.js +33 -1
  9. package/dist/sdd-engine/feature-manifest.d.ts +4 -5
  10. package/dist/sdd-engine/feature-manifest.js +206 -93
  11. package/dist/sdd-engine/host-rule-pack.d.ts +5 -0
  12. package/dist/sdd-engine/host-rule-pack.js +103 -43
  13. package/dist/sdd-engine/host-skill-reader.d.ts +6 -0
  14. package/dist/sdd-engine/host-skill-reader.js +187 -0
  15. package/dist/sdd-engine/lock-integrity.d.ts +3 -2
  16. package/dist/sdd-engine/lock-integrity.js +30 -18
  17. package/dist/sdd-engine/receipt-assessment.d.ts +12 -0
  18. package/dist/sdd-engine/receipt-assessment.js +223 -0
  19. package/dist/sdd-engine/server.js +2 -4
  20. package/dist/sdd-engine/task-content.d.ts +19 -1
  21. package/dist/sdd-engine/task-content.js +128 -3
  22. package/dist/sdd-engine/task-failures.d.ts +2 -0
  23. package/dist/sdd-engine/task-failures.js +34 -0
  24. package/dist/sdd-engine/task-window.d.ts +3 -4
  25. package/dist/sdd-engine/task-window.js +49 -79
  26. package/dist/sdd-engine/tools/execution-tools.d.ts +1 -11
  27. package/dist/sdd-engine/tools/execution-tools.js +86 -57
  28. package/dist/sdd-engine/tools/workspace-tools.d.ts +1 -1
  29. package/dist/sdd-engine/tools/workspace-tools.js +17 -9
  30. package/dist/sdd-engine/tools.d.ts +2 -1
  31. package/dist/sdd-engine/tools.js +4 -2
  32. package/dist/sdd-engine/trinity-structure.d.ts +25 -0
  33. package/dist/sdd-engine/trinity-structure.js +317 -0
  34. package/dist/sdd-engine/verification-inputs.d.ts +12 -0
  35. package/dist/sdd-engine/verification-inputs.js +302 -0
  36. package/dist/sdd-engine/verification-preflight.d.ts +4 -0
  37. package/dist/sdd-engine/verification-preflight.js +271 -0
  38. package/dist/sdd-engine/verification-receipts.d.ts +16 -0
  39. package/dist/sdd-engine/verification-receipts.js +98 -0
  40. package/dist/sdd-engine/workspace-root.d.ts +1 -0
  41. package/dist/sdd-engine/workspace-root.js +1 -0
  42. package/dist/types/completion.d.ts +9 -2
  43. package/dist/types/sdd-engine.d.ts +203 -0
  44. package/package.json +1 -1
  45. package/templates/AGENTS.md +9 -1
  46. package/templates/host/planu-sdd.md +9 -0
  47. package/templates/skills/spec-architect.md +1 -0
@@ -0,0 +1,302 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import * as fs from 'node:fs/promises';
4
+ import * as nodePath from 'node:path';
5
+ import { disjointPaths, isEvidencePath } from './feature-authority.js';
6
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
7
+ const MAX_TOTAL_BYTES = 16 * 1024 * 1024;
8
+ export class VerificationInputError extends Error {
9
+ reason;
10
+ category;
11
+ path;
12
+ constructor(reason, category, path) {
13
+ super(reason === 'cancelled'
14
+ ? 'Verification was cancelled.'
15
+ : reason === 'receipt_input_drift'
16
+ ? 'A verification input changed during the attempt.'
17
+ : 'A declared verification input is unavailable or unsafe.');
18
+ this.reason = reason;
19
+ this.category = category;
20
+ this.path = path;
21
+ this.name = 'VerificationInputError';
22
+ }
23
+ }
24
+ function checkCancellation(signal) {
25
+ if (signal?.aborted) {
26
+ throw new VerificationInputError('cancelled');
27
+ }
28
+ }
29
+ function unavailable(request) {
30
+ throw new VerificationInputError('receipt_input_unavailable', request?.category, request?.path);
31
+ }
32
+ function sameDirectory(left, right) {
33
+ return (right.isDirectory() &&
34
+ left.dev === right.dev &&
35
+ left.ino === right.ino &&
36
+ left.mode === right.mode &&
37
+ left.uid === right.uid &&
38
+ left.gid === right.gid);
39
+ }
40
+ function ownedRegular(stat) {
41
+ return (stat.isFile() &&
42
+ stat.nlink === 1n &&
43
+ typeof process.getuid === 'function' &&
44
+ stat.uid === BigInt(process.getuid()));
45
+ }
46
+ function sameFile(left, right) {
47
+ return (ownedRegular(right) &&
48
+ left.dev === right.dev &&
49
+ left.ino === right.ino &&
50
+ left.mode === right.mode &&
51
+ left.uid === right.uid &&
52
+ left.gid === right.gid &&
53
+ left.size === right.size &&
54
+ left.mtimeNs === right.mtimeNs &&
55
+ left.ctimeNs === right.ctimeNs);
56
+ }
57
+ export async function captureVerificationRoot(workspaceRoot) {
58
+ try {
59
+ const canonical = await fs.realpath(workspaceRoot);
60
+ const stat = await fs.lstat(canonical, { bigint: true });
61
+ if (!stat.isDirectory()) {
62
+ unavailable();
63
+ }
64
+ return { canonical, stat };
65
+ }
66
+ catch {
67
+ return unavailable();
68
+ }
69
+ }
70
+ function sameRoot(left, right) {
71
+ return left.canonical === right.canonical && sameDirectory(left.stat, right.stat);
72
+ }
73
+ // Check spelling through directory entries even on filesystems where lstat accepts aliases.
74
+ // Stream names so an unrelated large directory never causes an unbounded allocation.
75
+ async function hasExactName(parent, component, request, signal) {
76
+ const folded = component.toLowerCase();
77
+ let exact = false;
78
+ for await (const entry of await fs.opendir(parent)) {
79
+ checkCancellation(signal);
80
+ if (entry.name === component) {
81
+ exact = true;
82
+ }
83
+ else if (entry.name.toLowerCase() === folded) {
84
+ unavailable(request);
85
+ }
86
+ }
87
+ return exact;
88
+ }
89
+ async function inspectPath(root, request, signal) {
90
+ const parts = request.path.split('/');
91
+ const directories = [];
92
+ let parent = root.canonical;
93
+ for (const [index, component] of parts.entries()) {
94
+ const absolute = nodePath.join(parent, component);
95
+ const exact = await hasExactName(parent, component, request, signal);
96
+ let stat;
97
+ try {
98
+ stat = await fs.lstat(absolute, { bigint: true });
99
+ }
100
+ catch (error) {
101
+ if (!exact &&
102
+ request.allowAbsent &&
103
+ error.code === 'ENOENT' &&
104
+ (await fs.realpath(parent)) === parent) {
105
+ return { state: 'absent', directories, absolute };
106
+ }
107
+ return unavailable(request);
108
+ }
109
+ if (!exact || stat.isSymbolicLink()) {
110
+ return unavailable(request);
111
+ }
112
+ if (index === parts.length - 1) {
113
+ if (!ownedRegular(stat) || (await fs.realpath(absolute)) !== absolute) {
114
+ return unavailable(request);
115
+ }
116
+ return { state: 'present', directories, absolute, stat };
117
+ }
118
+ if (!stat.isDirectory()) {
119
+ return unavailable(request);
120
+ }
121
+ directories.push(stat);
122
+ parent = absolute;
123
+ }
124
+ return unavailable(request);
125
+ }
126
+ async function readFileHash(walk, request, limit, signal) {
127
+ if (walk.stat.size > BigInt(limit) ||
128
+ !Number.isInteger(constants.O_NOFOLLOW) ||
129
+ !Number.isInteger(constants.O_NONBLOCK)) {
130
+ return unavailable(request);
131
+ }
132
+ const handle = await fs.open(walk.absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
133
+ try {
134
+ const opened = await handle.stat({ bigint: true });
135
+ if (!sameFile(walk.stat, opened) || opened.size > BigInt(limit)) {
136
+ return unavailable(request);
137
+ }
138
+ const bytes = Buffer.alloc(Number(opened.size));
139
+ let offset = 0;
140
+ while (offset < bytes.length) {
141
+ checkCancellation(signal);
142
+ const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
143
+ if (bytesRead === 0) {
144
+ return unavailable(request);
145
+ }
146
+ offset += bytesRead;
147
+ }
148
+ const trailing = await handle.read(Buffer.alloc(1), 0, 1, offset);
149
+ if (trailing.bytesRead !== 0 || !sameFile(opened, await handle.stat({ bigint: true }))) {
150
+ return unavailable(request);
151
+ }
152
+ return createHash('sha256').update(bytes).digest('hex');
153
+ }
154
+ finally {
155
+ await handle.close();
156
+ }
157
+ }
158
+ function sameWalk(left, right) {
159
+ return (left.absolute === right.absolute &&
160
+ left.directories.length === right.directories.length &&
161
+ left.directories.every((stat, index) => {
162
+ const current = right.directories[index];
163
+ return current !== undefined && sameDirectory(stat, current);
164
+ }) &&
165
+ (left.state === 'absent'
166
+ ? right.state === 'absent'
167
+ : right.state === 'present' && sameFile(left.stat, right.stat)));
168
+ }
169
+ async function withSafeDiagnostic(request, operation, signal) {
170
+ checkCancellation(signal);
171
+ try {
172
+ return await operation();
173
+ }
174
+ catch {
175
+ checkCancellation(signal);
176
+ return unavailable(request);
177
+ }
178
+ }
179
+ function jsonSha256(value) {
180
+ return createHash('sha256').update(JSON.stringify(value), 'utf8').digest('hex');
181
+ }
182
+ function digestCategory(inputs, category) {
183
+ const entries = inputs
184
+ .filter(({ request }) => request.category === category)
185
+ .map((input) => 'rawSha256' in input
186
+ ? [input.request.path, 'present', input.mode, input.rawSha256]
187
+ : [input.request.path, 'absent']);
188
+ return jsonSha256(['planu.verification-inputs.v1', category, entries]);
189
+ }
190
+ async function capture(workspaceRoot, requests, signal, expectedRoot) {
191
+ checkCancellation(signal);
192
+ const root = await captureVerificationRoot(workspaceRoot);
193
+ checkCancellation(signal);
194
+ if (expectedRoot && !sameRoot(root, expectedRoot)) {
195
+ throw new VerificationInputError('receipt_input_drift');
196
+ }
197
+ const inputs = [];
198
+ let remaining = MAX_TOTAL_BYTES;
199
+ for (const request of requests) {
200
+ const input = await withSafeDiagnostic(request, async () => {
201
+ const walk = await inspectPath(root, request, signal);
202
+ if (walk.state === 'absent') {
203
+ return { request, walk };
204
+ }
205
+ const rawSha256 = await readFileHash(walk, request, Math.min(remaining, MAX_FILE_BYTES), signal);
206
+ remaining -= Number(walk.stat.size);
207
+ return { request, walk, rawSha256, mode: Number(walk.stat.mode & 4095n) };
208
+ }, signal);
209
+ inputs.push(input);
210
+ }
211
+ // Revisit names after all descriptor reads, including each proof of future absence.
212
+ for (const { request, walk } of inputs) {
213
+ await withSafeDiagnostic(request, async () => {
214
+ if (!sameWalk(walk, await inspectPath(root, request, signal))) {
215
+ unavailable(request);
216
+ }
217
+ }, signal);
218
+ }
219
+ if (!sameRoot(root, await captureVerificationRoot(workspaceRoot))) {
220
+ unavailable();
221
+ }
222
+ checkCancellation(signal);
223
+ return {
224
+ workspaceRoot,
225
+ root,
226
+ inputs,
227
+ workspaceSha256: jsonSha256([
228
+ 'planu.workspace.v1',
229
+ root.canonical,
230
+ root.stat.dev.toString(10),
231
+ root.stat.ino.toString(10),
232
+ ]),
233
+ candidateSha256: digestCategory(inputs, 'candidate'),
234
+ observedSha256: digestCategory(inputs, 'observed'),
235
+ };
236
+ }
237
+ export async function captureVerificationInputs(workspaceRoot, candidates, task, signal, expectedRoot) {
238
+ checkCancellation(signal);
239
+ if (candidates.length < 1 || candidates.length > 64 || task.observed.length > 64) {
240
+ return unavailable();
241
+ }
242
+ const paths = [...candidates.map((candidate) => candidate.path), ...task.observed];
243
+ if (!paths.every(isEvidencePath) || !disjointPaths(paths)) {
244
+ return unavailable();
245
+ }
246
+ const requests = [
247
+ ...candidates.map((candidate) => ({
248
+ category: 'candidate',
249
+ path: candidate.path,
250
+ allowAbsent: task.ordinal < candidate.requiredFrom,
251
+ })),
252
+ ...task.observed.map((observed) => ({
253
+ category: 'observed',
254
+ path: observed,
255
+ allowAbsent: false,
256
+ })),
257
+ ];
258
+ requests.sort((left, right) => (left.path < right.path ? -1 : Number(left.path > right.path)));
259
+ return capture(workspaceRoot, requests, signal, expectedRoot);
260
+ }
261
+ export async function checkReceiptPatchTarget(root, workspaceRoot, path, permission, searchContent) {
262
+ if (permission !== 'CREATE' && permission !== 'MODIFY') {
263
+ return;
264
+ }
265
+ const request = {
266
+ category: 'candidate',
267
+ path,
268
+ allowAbsent: permission === 'CREATE' && searchContent === '',
269
+ };
270
+ await withSafeDiagnostic(request, async () => {
271
+ await inspectPath(root, request);
272
+ if (!sameRoot(root, await captureVerificationRoot(workspaceRoot))) {
273
+ unavailable(request);
274
+ }
275
+ });
276
+ }
277
+ export async function revalidateVerificationInputs(snapshot, signal) {
278
+ let current;
279
+ try {
280
+ current = await capture(snapshot.workspaceRoot, snapshot.inputs.map(({ request }) => request), signal, snapshot.root);
281
+ }
282
+ catch (error) {
283
+ checkCancellation(signal);
284
+ if (error instanceof VerificationInputError && error.reason === 'receipt_input_unavailable') {
285
+ throw new VerificationInputError('receipt_input_drift', error.category, error.path);
286
+ }
287
+ throw error;
288
+ }
289
+ if (!sameRoot(snapshot.root, current.root)) {
290
+ throw new VerificationInputError('receipt_input_drift');
291
+ }
292
+ for (const [index, previous] of snapshot.inputs.entries()) {
293
+ const next = current.inputs[index];
294
+ if (!next ||
295
+ !sameWalk(previous.walk, next.walk) ||
296
+ ('rawSha256' in previous && (!('rawSha256' in next) || previous.rawSha256 !== next.rawSha256))) {
297
+ throw new VerificationInputError('receipt_input_drift', previous.request.category, previous.request.path);
298
+ }
299
+ }
300
+ checkCancellation(signal);
301
+ }
302
+ //# sourceMappingURL=verification-inputs.js.map
@@ -0,0 +1,4 @@
1
+ import type { ActiveTaskResult, SddResult } from '../types/sdd-engine.js';
2
+ import type { ScopedPolicy } from '../types/verification.js';
3
+ export declare function getVerificationPreflight(tasksPath: string, workspaceRoot: string, extractCommand: (markdown: string) => string | null, receipts?: unknown, scopedPolicy?: ScopedPolicy, signal?: AbortSignal): Promise<SddResult<ActiveTaskResult>>;
4
+ //# sourceMappingURL=verification-preflight.d.ts.map
@@ -0,0 +1,271 @@
1
+ import * as path from 'node:path';
2
+ import { CompletionGuardError, captureDirectories, lastAuthorityDirectory, readArtifact, revalidateDirectories, sameIdentity, } from './feature-authority.js';
3
+ import { inspectCompletionGuard } from './completion-guard.js';
4
+ import { captureCompletionSnapshot, revalidateCompletionSnapshot } from './completion-snapshot.js';
5
+ import { parseManifestContent, parseVerificationReceiptPolicy } from './feature-manifest.js';
6
+ import { activeTaskFromContent } from './task-content.js';
7
+ import { completionError } from './task-failures.js';
8
+ import { captureReceiptEvidence, assessVerificationReceiptSet } from './verification-receipts.js';
9
+ import { captureVerificationRoot, revalidateVerificationInputs, VerificationInputError, } from './verification-inputs.js';
10
+ import { isScopedVerificationFeature } from './verification-policy.js';
11
+ function report(taskId, reasons, gates = [], applicable = true) {
12
+ const blockers = [...new Set(reasons)]
13
+ .sort()
14
+ .slice(0, 16)
15
+ .map((reason) => ({ reason }));
16
+ const rejectedGate = gates.some((gate) => gate.state !== 'receipt_valid');
17
+ const actionReasons = new Set(reasons);
18
+ for (const gate of gates) {
19
+ if (gate.reason) {
20
+ actionReasons.add(gate.reason);
21
+ }
22
+ }
23
+ return {
24
+ version: 1,
25
+ taskId,
26
+ status: !applicable
27
+ ? 'not_applicable'
28
+ : blockers.length || rejectedGate
29
+ ? 'blocked'
30
+ : 'ready_to_attempt',
31
+ gates,
32
+ blockers,
33
+ integration: 'not_run',
34
+ nextAction: applicable ? nextAction(actionReasons) : 'none',
35
+ };
36
+ }
37
+ function nextAction(reasons) {
38
+ if (reasons.has('unlocked')) {
39
+ return 'review_lock';
40
+ }
41
+ if (reasons.has('platform_unsupported') || reasons.has('receipt_scoped_unsupported')) {
42
+ return 'use_supported_runtime';
43
+ }
44
+ if (reasons.has('command_missing')) {
45
+ return 'restore_verification';
46
+ }
47
+ if (reasons.has('receipt_input_unavailable')) {
48
+ return 'fix_inputs';
49
+ }
50
+ if (reasons.has('receipt_observed_baseline_drift')) {
51
+ return 'review_observed_drift';
52
+ }
53
+ if (reasons.has('receipt_not_configured')) {
54
+ return 'restore_verification';
55
+ }
56
+ return reasons.size ? 'obtain_receipts' : 'attempt_integration';
57
+ }
58
+ function taskBlockers(active, task) {
59
+ const reasons = [];
60
+ if (!(task ? task.command : active.verificationCommand)) {
61
+ reasons.push('command_missing');
62
+ }
63
+ if (!['darwin', 'linux'].includes(process.platform)) {
64
+ reasons.push('platform_unsupported');
65
+ }
66
+ return reasons;
67
+ }
68
+ /** The same captured authority can be assessed by other read views without selecting again. */
69
+ async function assessVerificationPreflight(snapshot, root, workspaceRoot, active, receipts, scopedPolicy, signal) {
70
+ if (!active) {
71
+ return report(null, [], [], false);
72
+ }
73
+ const policy = parseVerificationReceiptPolicy(path.basename(snapshot.featDir), snapshot.planContent, snapshot.tasksContent);
74
+ if (policy.status === 'invalid') {
75
+ throw new CompletionGuardError('contract_drift', 'Preflight authority changed.');
76
+ }
77
+ const task = policy.status === 'ready' ? policy.tasks.get(active.taskId) : undefined;
78
+ const reasons = taskBlockers(active, task);
79
+ if (policy.status !== 'ready' || !task) {
80
+ if (receipts !== undefined) {
81
+ reasons.push('receipt_not_configured');
82
+ }
83
+ return report(active.taskId, reasons);
84
+ }
85
+ if (scopedPolicy && (await isScopedVerificationFeature(scopedPolicy, snapshot.featDir))) {
86
+ reasons.push('receipt_scoped_unsupported');
87
+ }
88
+ try {
89
+ const captured = await captureReceiptEvidence(snapshot, workspaceRoot, policy, task, root, signal);
90
+ if (!captured.success) {
91
+ if (captured.error.details?.reason !== 'receipt_observed_baseline_drift') {
92
+ throw new CompletionGuardError('contract_drift', 'Preflight authority changed.');
93
+ }
94
+ return report(active.taskId, [...reasons, 'receipt_observed_baseline_drift']);
95
+ }
96
+ const assessed = assessVerificationReceiptSet(receipts, captured.data.evidence, policy.publicKey);
97
+ await revalidateVerificationInputs(captured.data.inputs, signal);
98
+ return report(active.taskId, [...reasons, ...assessed.blockers.map(({ reason }) => reason)], assessed.gates);
99
+ }
100
+ catch (error) {
101
+ if (error instanceof VerificationInputError && error.reason === 'receipt_input_unavailable') {
102
+ return report(active.taskId, [...reasons, 'receipt_input_unavailable']);
103
+ }
104
+ throw error;
105
+ }
106
+ }
107
+ async function optionalArtifact(feature, name) {
108
+ try {
109
+ return await readArtifact(feature, name);
110
+ }
111
+ catch (error) {
112
+ if (error.code === 'ENOENT') {
113
+ return undefined;
114
+ }
115
+ throw error;
116
+ }
117
+ }
118
+ async function requiredTaskArtifact(feature) {
119
+ const task = await optionalArtifact(feature, 'tasks.md');
120
+ if (!task) {
121
+ throw new CompletionGuardError('contract_drift', 'Task authority is unavailable.', 'ERR_TASK_NOT_FOUND');
122
+ }
123
+ return task;
124
+ }
125
+ async function captureReadSnapshot(feature, root) {
126
+ try {
127
+ const locked = await captureCompletionSnapshot(feature, {
128
+ workspaceRoot: root.canonical,
129
+ });
130
+ return {
131
+ feature: locked.featDir,
132
+ directories: locked.directories,
133
+ artifacts: locked.artifacts,
134
+ locked,
135
+ };
136
+ }
137
+ catch (error) {
138
+ if (error.code === 'ENOENT') {
139
+ await requiredTaskArtifact(feature);
140
+ throw new CompletionGuardError('contract_drift', 'Preflight authority is unavailable.');
141
+ }
142
+ if (!(error instanceof CompletionGuardError) || error.code !== 'ERR_SPEC_NOT_LOCKED') {
143
+ throw error;
144
+ }
145
+ }
146
+ const directories = await captureDirectories(feature, root.canonical);
147
+ const canonical = lastAuthorityDirectory(directories).directory;
148
+ const artifacts = {};
149
+ for (const name of ['.lock', 'spec.md', 'plan.md', 'tasks.md']) {
150
+ artifacts[name] =
151
+ name === 'tasks.md'
152
+ ? await requiredTaskArtifact(canonical)
153
+ : await optionalArtifact(canonical, name);
154
+ }
155
+ if (artifacts['.lock']) {
156
+ throw new CompletionGuardError('contract_drift', 'Preflight authority changed.');
157
+ }
158
+ return { feature: canonical, directories, artifacts };
159
+ }
160
+ async function revalidateReadSnapshot(snapshot, root, workspaceRoot) {
161
+ if (snapshot.locked) {
162
+ await revalidateCompletionSnapshot(snapshot.locked);
163
+ }
164
+ else {
165
+ await revalidateDirectories(snapshot.directories);
166
+ for (const name of ['.lock', 'spec.md', 'plan.md', 'tasks.md']) {
167
+ const current = await optionalArtifact(snapshot.feature, name);
168
+ const expected = snapshot.artifacts[name];
169
+ if (current?.content !== expected?.content ||
170
+ (current && expected && !sameIdentity(current.identity, expected.identity))) {
171
+ throw new CompletionGuardError('contract_drift', 'Preflight authority changed.');
172
+ }
173
+ }
174
+ await revalidateDirectories(snapshot.directories);
175
+ }
176
+ const currentRoot = await captureVerificationRoot(workspaceRoot);
177
+ if (root.canonical !== currentRoot.canonical ||
178
+ root.stat.dev !== currentRoot.stat.dev ||
179
+ root.stat.ino !== currentRoot.stat.ino ||
180
+ root.stat.mode !== currentRoot.stat.mode ||
181
+ root.stat.uid !== currentRoot.stat.uid ||
182
+ root.stat.gid !== currentRoot.stat.gid) {
183
+ throw new CompletionGuardError('contract_drift', 'Preflight authority changed.');
184
+ }
185
+ await assertGuardAbsent(snapshot.feature);
186
+ }
187
+ async function assertGuardAbsent(feature) {
188
+ const guard = await inspectCompletionGuard(feature);
189
+ if (guard) {
190
+ throw new CompletionGuardError(guard.reason, 'Preflight authority is guarded.', 'ERR_VERIFICATION_FAILED');
191
+ }
192
+ }
193
+ function receiptActiveTask(snapshot, active) {
194
+ if (!snapshot || !active) {
195
+ return active;
196
+ }
197
+ const policy = parseVerificationReceiptPolicy(path.basename(snapshot.featDir), snapshot.planContent, snapshot.tasksContent);
198
+ const task = policy.status === 'ready' ? policy.tasks.get(active.taskId) : undefined;
199
+ return task ? { ...active, verificationCommand: task.command } : active;
200
+ }
201
+ function preflightError(error) {
202
+ const failure = completionError(error, 'sdd_get_active_task');
203
+ if (failure.success) {
204
+ return {
205
+ success: false,
206
+ error: {
207
+ code: 'ERR_VERIFICATION_FAILED',
208
+ message: 'Verification preflight is unavailable.',
209
+ trigger: 'sdd_get_active_task',
210
+ },
211
+ };
212
+ }
213
+ const rawReason = failure.error.details?.reason;
214
+ const reasons = new Set([
215
+ 'guard_present',
216
+ 'contract_drift',
217
+ 'cancelled',
218
+ 'persistence_uncertain',
219
+ 'receipt_input_drift',
220
+ 'receipt_input_unavailable',
221
+ ]);
222
+ const reason = typeof rawReason === 'string' && reasons.has(rawReason) ? rawReason : 'failed';
223
+ return {
224
+ success: false,
225
+ error: {
226
+ code: failure.error.code,
227
+ message: 'Verification preflight is unavailable; inspect the bounded reason before retrying.',
228
+ trigger: 'sdd_get_active_task',
229
+ details: { reason },
230
+ },
231
+ };
232
+ }
233
+ export async function getVerificationPreflight(tasksPath, workspaceRoot, extractCommand, receipts, scopedPolicy, signal) {
234
+ try {
235
+ const root = await captureVerificationRoot(workspaceRoot);
236
+ const snapshot = await captureReadSnapshot(path.dirname(tasksPath), root);
237
+ await assertGuardAbsent(snapshot.feature);
238
+ const current = activeTaskFromContent(snapshot.artifacts['tasks.md']?.content ?? '', extractCommand);
239
+ if (!current.success) {
240
+ return current;
241
+ }
242
+ const data = {
243
+ ...current.data,
244
+ activeTask: receiptActiveTask(snapshot.locked, current.data.activeTask),
245
+ };
246
+ const verificationPreflight = snapshot.locked
247
+ ? await assessVerificationPreflight(snapshot.locked, root, workspaceRoot, data.activeTask, receipts, scopedPolicy, signal)
248
+ : report(data.activeTask?.taskId ?? null, ['unlocked']);
249
+ if (signal?.aborted) {
250
+ throw new CompletionGuardError('cancelled', 'Preflight was cancelled.');
251
+ }
252
+ await revalidateReadSnapshot(snapshot, root, workspaceRoot);
253
+ const manifest = [
254
+ ...parseManifestContent(snapshot.artifacts['plan.md']?.content ?? '').allowedFiles.entries(),
255
+ ].map(([filePath, permission]) => ({ path: filePath, permission }));
256
+ return {
257
+ success: true,
258
+ data: {
259
+ ...data,
260
+ locked: !!snapshot.locked,
261
+ trinity: snapshot.locked ? 'ready' : 'unlocked',
262
+ manifest,
263
+ verificationPreflight,
264
+ },
265
+ };
266
+ }
267
+ catch (error) {
268
+ return preflightError(error);
269
+ }
270
+ }
271
+ //# sourceMappingURL=verification-preflight.js.map
@@ -0,0 +1,16 @@
1
+ export { maxVerificationReceipts, gateIdPattern, taskIdPattern, featureIdPattern, sha256Schema, importReceiptPublicKey, validateVerificationReceiptSet, assessVerificationReceiptSet, } from './receipt-assessment.js';
2
+ import type { CompleteTaskResult, ReceiptPolicyResult, ReceiptTaskPolicy, SddResult, VerificationEvidence, WorkspaceRoot } from '../types/sdd-engine.js';
3
+ import type { CompletionSnapshot } from '../types/completion.js';
4
+ import type { CompletionLease } from './completion-guard.js';
5
+ import { captureVerificationInputs } from './verification-inputs.js';
6
+ import type { ScopedVerificationRun, ScopedVerificationRunnerOptions } from '../types/verification.js';
7
+ export declare function captureReceiptEvidence(snapshot: CompletionSnapshot, workspaceRoot: string, policy: Extract<ReceiptPolicyResult, {
8
+ status: 'ready';
9
+ }>, task: ReceiptTaskPolicy, root: WorkspaceRoot, signal?: AbortSignal): Promise<SddResult<{
10
+ evidence: VerificationEvidence;
11
+ inputs: Awaited<ReturnType<typeof captureVerificationInputs>>;
12
+ }>>;
13
+ export declare function completeReceiptTask(snapshot: CompletionSnapshot, workspaceRoot: string, policy: Extract<ReceiptPolicyResult, {
14
+ status: 'ready';
15
+ }>, task: ReceiptTaskPolicy, receipts: unknown, lease: CompletionLease, signal: AbortSignal, timeoutMs: number, runVerification: (options: ScopedVerificationRunnerOptions) => Promise<ScopedVerificationRun>): Promise<SddResult<CompleteTaskResult>>;
16
+ //# sourceMappingURL=verification-receipts.d.ts.map