@planu/cli 8.2.20 → 8.3.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.
@@ -43,9 +43,8 @@ function parseTasks(lines) {
43
43
  activeTaskLines: [],
44
44
  isCapturingActive: false,
45
45
  };
46
- const taskRegex = /^[-*]\s*\[([\s/xX])\]\s*(.*)$/;
47
46
  for (const line of lines) {
48
- const match = taskRegex.exec(line.trim());
47
+ const match = TASK_CHECKBOX.exec(line.trim());
49
48
  if (match?.[1] && match[2]) {
50
49
  acc.totalTasks++;
51
50
  const statusChar = match[1].trim().toLowerCase();
@@ -73,8 +72,34 @@ function parseTasks(lines) {
73
72
  }
74
73
  return acc;
75
74
  }
75
+ const TASK_CHECKBOX = /^[-*]\s*\[([\s/xX])\]\s*(.*)$/u;
76
+ const EXPLICIT_TASK_ID = /^(TASK-[A-Z0-9_-]+|[A-Z0-9_-]+):\s*(.*)$/i;
77
+ const LEGACY_COMPLETED_ID = /^([A-Z0-9_-]+) — \[Verified: .*?\]:\s*/i;
78
+ export function taskBlocks(content) {
79
+ const blocks = [];
80
+ for (const [lineIndex, line] of content.split('\n').entries()) {
81
+ const match = TASK_CHECKBOX.exec(line.trim());
82
+ if (!match?.[1] || !match[2]) {
83
+ blocks.at(-1)?.lines.push(line);
84
+ continue;
85
+ }
86
+ const title = match[2].trim();
87
+ const ordinal = blocks.length + 1;
88
+ const explicit = EXPLICIT_TASK_ID.exec(title);
89
+ const historical = match[1].toLowerCase() === 'x' ? LEGACY_COMPLETED_ID.exec(title) : null;
90
+ blocks.push({
91
+ id: historical?.[1]?.toUpperCase() ?? extractTaskId(title, ordinal).id,
92
+ explicitId: explicit?.[2] ? explicit[1] : undefined,
93
+ legacyId: historical?.[1],
94
+ ordinal,
95
+ lineIndex,
96
+ lines: [],
97
+ });
98
+ }
99
+ return blocks;
100
+ }
76
101
  function extractTaskId(rawTitle, index) {
77
- const idMatch = /^(TASK-[A-Z0-9_-]+|[A-Z0-9_-]+):\s*(.*)$/i.exec(rawTitle);
102
+ const idMatch = EXPLICIT_TASK_ID.exec(rawTitle);
78
103
  if (idMatch?.[1] && idMatch[2]) {
79
104
  return { id: idMatch[1].toUpperCase(), title: idMatch[2].trim() };
80
105
  }
@@ -92,6 +117,20 @@ export function markTaskVerified(lines, taskId, cleanOutput) {
92
117
  }
93
118
  return null;
94
119
  }
120
+ export function markReceiptTaskVerified(content, lineIndex, summary) {
121
+ const lines = content.split('\n');
122
+ const line = lines[lineIndex];
123
+ if (!line) {
124
+ return undefined;
125
+ }
126
+ const checked = line.replace(/^(\s*[-*]\s*\[)[\s/](\])/u, '$1x$2');
127
+ if (checked === line) {
128
+ return undefined;
129
+ }
130
+ const lineEnding = checked.endsWith('\r') ? '\r' : '';
131
+ lines[lineIndex] = checked.trimEnd() + ' — [Verified: ' + summary + ']' + lineEnding;
132
+ return lines.join('\n');
133
+ }
95
134
  export function remainingTaskCount(checkRes) {
96
135
  if (!checkRes.success || !checkRes.data.activeTask) {
97
136
  return 0;
@@ -129,4 +168,62 @@ export function catalogueFromContent(id, locked, tasksContent, extractCommand) {
129
168
  },
130
169
  };
131
170
  }
171
+ const RECEIPT_DIRECTIVE = /^verification\s*\(\s*receipts(?:\b|v[0-9])/iu;
172
+ const COMMAND_DIRECTIVE = 'Verification (receipts v1):';
173
+ export function insideMarkdownBlock(lines) {
174
+ let fence;
175
+ let comment = false;
176
+ for (const raw of lines) {
177
+ const line = raw.trimStart();
178
+ const delimiter = /^(\u0060{3,}|~{3,})/u.exec(line)?.[0];
179
+ if (fence) {
180
+ if (delimiter?.startsWith(fence) && !line.slice(delimiter.length).trim()) {
181
+ fence = undefined;
182
+ }
183
+ continue;
184
+ }
185
+ if (!comment && delimiter) {
186
+ fence = delimiter;
187
+ continue;
188
+ }
189
+ for (const marker of line.matchAll(/<!--|-->/gu)) {
190
+ comment = marker[0] === '<!--';
191
+ }
192
+ }
193
+ return comment || fence !== undefined;
194
+ }
195
+ export function hasReceiptDirective(line) {
196
+ return RECEIPT_DIRECTIVE.test(line.trim());
197
+ }
198
+ export function receiptCommand(block) {
199
+ const lines = block.lines.map((line) => line.trim());
200
+ const directives = lines.filter((line) => RECEIPT_DIRECTIVE.test(line));
201
+ const directive = directives[0];
202
+ const precedingLines = lines.slice(0, directive ? lines.indexOf(directive) : 0);
203
+ if (directives.length !== 1 ||
204
+ !directive?.startsWith(COMMAND_DIRECTIVE) ||
205
+ insideMarkdownBlock(precedingLines) ||
206
+ lines.some((line) => /^verification:/iu.test(line))) {
207
+ return undefined;
208
+ }
209
+ const command = directive.slice(COMMAND_DIRECTIVE.length).trim();
210
+ return command && !/[<>]/u.test(command) ? command : undefined;
211
+ }
212
+ export function countTaskIds(blocks) {
213
+ const counts = new Map();
214
+ for (const { id } of blocks) {
215
+ counts.set(id, (counts.get(id) ?? 0) + 1);
216
+ }
217
+ return counts;
218
+ }
219
+ export function dueTaskOrdinals(blocks, counts) {
220
+ const due = new Map();
221
+ for (const block of blocks) {
222
+ const id = (block.explicitId ?? block.legacyId)?.toUpperCase();
223
+ if (id !== undefined && counts.get(id) === 1) {
224
+ due.set(id, block.ordinal);
225
+ }
226
+ }
227
+ return due;
228
+ }
132
229
  //# sourceMappingURL=task-content.js.map
@@ -1,6 +1,8 @@
1
1
  import type { CompleteTaskResult, SddResult } from '../types/sdd-engine.js';
2
2
  import type { ScopedVerificationRun } from '../types/verification.js';
3
3
  export declare function completionFailure(reason: string, code?: 'ERR_VERIFICATION_FAILED' | 'ERR_SPEC_DRIFT', trigger?: string): SddResult<never>;
4
+ export declare function patchMutationError(error: unknown): SddResult<never>;
5
+ export declare function receiptFailure(reason: string, details?: Record<string, unknown>, trigger?: string): SddResult<never>;
4
6
  export declare function completionError(error: unknown, trigger?: string): SddResult<never>;
5
7
  export declare function taskOutOfSequence(taskId: string, activeTaskId: string | null, alreadyCompleted?: boolean): SddResult<CompleteTaskResult>;
6
8
  export declare function verificationMissing(): SddResult<CompleteTaskResult>;
@@ -1,4 +1,5 @@
1
1
  import { CompletionGuardError } from './feature-authority.js';
2
+ import { VerificationInputError } from './verification-inputs.js';
2
3
  export function completionFailure(reason, code = reason === 'contract_drift'
3
4
  ? 'ERR_SPEC_DRIFT'
4
5
  : 'ERR_VERIFICATION_FAILED', trigger = 'sdd_complete_task') {
@@ -14,7 +15,40 @@ export function completionFailure(reason, code = reason === 'contract_drift'
14
15
  },
15
16
  };
16
17
  }
18
+ export function patchMutationError(error) {
19
+ const guarded = error instanceof CompletionGuardError || error instanceof VerificationInputError;
20
+ return {
21
+ success: false,
22
+ error: {
23
+ code: error instanceof VerificationInputError
24
+ ? 'ERR_PERMISSION_VIOLATION'
25
+ : error instanceof CompletionGuardError
26
+ ? error.code
27
+ : 'ERR_VERIFICATION_FAILED',
28
+ message: guarded ? error.message : 'Feature mutation was denied.',
29
+ trigger: 'sdd_apply_file_patch',
30
+ details: { reason: guarded ? error.reason : 'failed' },
31
+ },
32
+ };
33
+ }
34
+ export function receiptFailure(reason, details = {}, trigger = 'sdd_complete_task') {
35
+ return {
36
+ success: false,
37
+ error: {
38
+ code: 'ERR_VERIFICATION_FAILED',
39
+ message: 'Receipt verification was denied.',
40
+ trigger,
41
+ details: { reason, ...details },
42
+ },
43
+ };
44
+ }
17
45
  export function completionError(error, trigger = 'sdd_complete_task') {
46
+ if (error instanceof VerificationInputError) {
47
+ return receiptFailure(error.reason, {
48
+ ...(error.category ? { category: error.category } : {}),
49
+ ...(error.path ? { path: error.path } : {}),
50
+ }, trigger);
51
+ }
18
52
  if (error instanceof CompletionGuardError) {
19
53
  return {
20
54
  success: false,
@@ -9,16 +9,14 @@ export declare class TaskWindowManager {
9
9
  shutdown(): Promise<void>;
10
10
  private activeTaskFromContent;
11
11
  private selectScopedTask;
12
- private commitScopedTask;
13
12
  getActiveTask(tasksFilePath: string): Promise<SddResult<ActiveTaskResult>>;
14
13
  getCatalogueEntry(featDir: string): Promise<SddResult<FeatureSummary>>;
15
- completeTask(tasksFilePath: string, taskId: string, workspaceRoot: string, _verificationOutput: string, signal?: AbortSignal): Promise<SddResult<CompleteTaskResult>>;
14
+ completeTask(tasksFilePath: string, taskId: string, workspaceRoot: string, _verificationOutput: string, signal?: AbortSignal, receipts?: unknown): Promise<SddResult<CompleteTaskResult>>;
16
15
  private completeOwned;
16
+ private completeIfReceiptTask;
17
17
  private checkScopedPaths;
18
18
  private attemptScopedCompletion;
19
- private commitOwnedScopedTask;
20
19
  private completeOrdinary;
21
- private commitOrdinary;
22
20
  }
23
21
  export declare function verificationCommand(taskMarkdown: string): string | null;
24
22
  //# sourceMappingURL=task-window.d.ts.map
@@ -1,12 +1,14 @@
1
1
  import * as path from 'node:path';
2
2
  import { ScopedVerificationCoordinator, runScopedVerification } from './verification-runner.js';
3
- import { persistScopedCompletionFiles, isScopedVerificationFeature, scopedFeaturePathFailure, } from './verification-policy.js';
3
+ import { isScopedVerificationFeature, persistScopedCompletionFiles, scopedFeaturePathFailure, } from './verification-policy.js';
4
4
  import { executionCard } from './lock-integrity.js';
5
+ import { parseVerificationReceiptPolicy } from './feature-manifest.js';
6
+ import { completeReceiptTask } from './verification-receipts.js';
5
7
  import { CompletionGuardError, readFeatureArtifact } from './feature-authority.js';
6
8
  import { acquireCompletionLease, inspectCompletionGuard, } from './completion-guard.js';
7
- import { captureCompletionSnapshot, revalidateCompletionSnapshot, persistCompletionSnapshot, readCatalogueArtifacts, } from './completion-snapshot.js';
8
- import { activeTaskFromContent, catalogueFromContent, markTaskVerified, remainingTaskCount, summarizeEvidence, wasTaskCompleted, } from './task-content.js';
9
- import { completionFailure, completionError, taskOutOfSequence, verificationMissing, verificationFailed, unsupportedVerificationPlatform, scopedPathMismatch, taskFileMissing, catalogueReadFailure, } from './task-failures.js';
9
+ import { captureCompletionSnapshot, revalidateCompletionSnapshot, commitOrdinaryTask, commitOwnedScopedTask, readCatalogueArtifacts, } from './completion-snapshot.js';
10
+ import { activeTaskFromContent, catalogueFromContent, wasTaskCompleted } from './task-content.js';
11
+ import { completionFailure, completionError, taskOutOfSequence, receiptFailure, verificationMissing, verificationFailed, unsupportedVerificationPlatform, scopedPathMismatch, taskFileMissing, catalogueReadFailure, } from './task-failures.js';
10
12
  export class TaskWindowManager {
11
13
  scopedPolicy;
12
14
  scoped;
@@ -36,26 +38,6 @@ export class TaskWindowManager {
36
38
  }
37
39
  : null;
38
40
  }
39
- async commitScopedTask(policy, taskId, snapshot, output, signal) {
40
- const summary = summarizeEvidence(output);
41
- const marked = markTaskVerified(snapshot.tasksContent.split('\n'), taskId, summary);
42
- if (marked === null) {
43
- return taskOutOfSequence(taskId, null);
44
- }
45
- const written = marked.join('\n');
46
- const persisted = await persistScopedCompletionFiles(policy, snapshot, written, signal);
47
- if (!persisted.success) {
48
- return persisted;
49
- }
50
- return {
51
- success: true,
52
- data: {
53
- completedTaskId: taskId,
54
- verificationSummary: summary,
55
- remainingTasks: remainingTaskCount(this.activeTaskFromContent(written)),
56
- },
57
- };
58
- }
59
41
  async getActiveTask(tasksFilePath) {
60
42
  let content;
61
43
  try {
@@ -77,8 +59,13 @@ export class TaskWindowManager {
77
59
  return built;
78
60
  }
79
61
  try {
80
- const card = await executionCard(path.dirname(tasksFilePath));
81
- const guard = await inspectCompletionGuard(path.dirname(tasksFilePath));
62
+ const feature = path.dirname(tasksFilePath);
63
+ const card = await executionCard(feature);
64
+ if (card.trinity === 'ready' &&
65
+ (await readFeatureArtifact(feature, 'tasks.md')) !== content) {
66
+ return completionFailure('contract_drift', undefined, 'sdd_get_active_task');
67
+ }
68
+ const guard = await inspectCompletionGuard(feature);
82
69
  if (guard) {
83
70
  return completionFailure(guard.reason, undefined, 'sdd_get_active_task');
84
71
  }
@@ -98,8 +85,8 @@ export class TaskWindowManager {
98
85
  return catalogueReadFailure(error, id);
99
86
  }
100
87
  }
101
- async completeTask(tasksFilePath, taskId, workspaceRoot, _verificationOutput, signal) {
102
- const operation = this.completeOwned(tasksFilePath, taskId, workspaceRoot, signal);
88
+ async completeTask(tasksFilePath, taskId, workspaceRoot, _verificationOutput, signal, receipts) {
89
+ const operation = this.completeOwned(tasksFilePath, taskId, workspaceRoot, signal, receipts);
103
90
  this.pending.add(operation);
104
91
  try {
105
92
  return await operation;
@@ -108,7 +95,7 @@ export class TaskWindowManager {
108
95
  this.pending.delete(operation);
109
96
  }
110
97
  }
111
- async completeOwned(tasksFilePath, taskId, workspaceRoot, signal) {
98
+ async completeOwned(tasksFilePath, taskId, workspaceRoot, signal, receipts) {
112
99
  try {
113
100
  const feature = path.dirname(tasksFilePath);
114
101
  const abortSignal = AbortSignal.any([
@@ -127,6 +114,10 @@ export class TaskWindowManager {
127
114
  validateLock: this.scopedPolicy === undefined,
128
115
  });
129
116
  const selected = this.selectScopedTask(snapshot.tasksContent);
117
+ const receiptResult = await this.completeIfReceiptTask(snapshot, lease, selected, taskId, workspaceRoot, abortSignal, receipts);
118
+ if (receiptResult) {
119
+ return receiptResult;
120
+ }
130
121
  await lease.bind(taskId, selected?.command ?? '', snapshot.digest);
131
122
  const scoped = await this.attemptScopedCompletion(tasksFilePath, taskId, workspaceRoot, abortSignal, snapshot, lease);
132
123
  if (scoped !== null) {
@@ -143,6 +134,25 @@ export class TaskWindowManager {
143
134
  return completionError(error);
144
135
  }
145
136
  }
137
+ async completeIfReceiptTask(snapshot, lease, selected, taskId, workspaceRoot, signal, receipts) {
138
+ const policy = parseVerificationReceiptPolicy(path.basename(snapshot.featDir), snapshot.planContent, snapshot.tasksContent);
139
+ if (policy.status === 'invalid') {
140
+ return completionFailure('contract_drift');
141
+ }
142
+ const task = policy.status === 'ready' && selected ? policy.tasks.get(selected.taskId) : undefined;
143
+ if (policy.status !== 'ready' || !task) {
144
+ return receipts === undefined ? undefined : receiptFailure('receipt_not_configured');
145
+ }
146
+ if (task.taskId !== taskId.toUpperCase()) {
147
+ return taskOutOfSequence(taskId, task.taskId, wasTaskCompleted(snapshot.tasksContent, taskId));
148
+ }
149
+ if (this.scopedPolicy &&
150
+ (await isScopedVerificationFeature(this.scopedPolicy, snapshot.featDir))) {
151
+ return receiptFailure('receipt_scoped_unsupported');
152
+ }
153
+ await lease.bind(taskId, task.command, snapshot.digest);
154
+ return completeReceiptTask(snapshot, workspaceRoot, policy, task, receipts, lease, signal, VERIFICATION_TIMEOUT_MS, runScopedVerification);
155
+ }
146
156
  async checkScopedPaths(tasksFilePath, workspaceRoot, feature) {
147
157
  const policy = this.scopedPolicy;
148
158
  if (policy && (await isScopedVerificationFeature(policy, feature))) {
@@ -169,7 +179,7 @@ export class TaskWindowManager {
169
179
  workspaceRoot,
170
180
  signal,
171
181
  selectTask: (content) => this.selectScopedTask(content),
172
- commit: (scopedSnapshot, output, commitSignal) => this.commitOwnedScopedTask(policy, taskId, scopedSnapshot, output, commitSignal, snapshot, lease),
182
+ commit: (scopedSnapshot, output, commitSignal) => commitOwnedScopedTask(taskId, scopedSnapshot, output, commitSignal, snapshot, lease, (written) => persistScopedCompletionFiles(policy, scopedSnapshot, written, commitSignal)),
173
183
  });
174
184
  if (scoped !== null) {
175
185
  if (!scoped.success && scoped.error.details?.cleanupComplete === false) {
@@ -181,28 +191,6 @@ export class TaskWindowManager {
181
191
  await revalidateCompletionSnapshot(snapshot);
182
192
  return null;
183
193
  }
184
- async commitOwnedScopedTask(policy, taskId, scopedSnapshot, output, signal, snapshot, lease) {
185
- await revalidateCompletionSnapshot(snapshot);
186
- if (signal.aborted) {
187
- return completionFailure('cancelled');
188
- }
189
- await lease.beginPersistence();
190
- try {
191
- const outcome = await this.commitScopedTask(policy, taskId, scopedSnapshot, output, signal);
192
- if (outcome.success) {
193
- lease.notePersistenceWrite();
194
- }
195
- if (isAborted(signal) ||
196
- (!outcome.success && outcome.error.details?.completionState === 'uncertain')) {
197
- lease.retain();
198
- }
199
- return outcome;
200
- }
201
- catch (error) {
202
- lease.retain();
203
- throw error;
204
- }
205
- }
206
194
  async completeOrdinary(snapshot, lease, taskId, workspaceRoot, signal) {
207
195
  const active = this.activeTaskFromContent(snapshot.tasksContent);
208
196
  if (!active.success) {
@@ -242,29 +230,7 @@ export class TaskWindowManager {
242
230
  if (!run.ok) {
243
231
  return verificationFailed(run);
244
232
  }
245
- return this.commitOrdinary(snapshot, lease, taskId, run.output, signal);
246
- }
247
- async commitOrdinary(snapshot, lease, taskId, output, signal) {
248
- await revalidateCompletionSnapshot(snapshot);
249
- if (signal.aborted) {
250
- return completionFailure('cancelled');
251
- }
252
- const summary = summarizeEvidence(output);
253
- const marked = markTaskVerified(snapshot.tasksContent.split('\n'), taskId, summary);
254
- if (marked === null) {
255
- return taskOutOfSequence(taskId, null, true);
256
- }
257
- const written = marked.join('\n');
258
- await persistCompletionSnapshot(lease, snapshot, written, signal);
259
- const next = this.activeTaskFromContent(written);
260
- return {
261
- success: true,
262
- data: {
263
- completedTaskId: taskId,
264
- verificationSummary: summary,
265
- remainingTasks: remainingTaskCount(next),
266
- },
267
- };
233
+ return commitOrdinaryTask(snapshot, lease, taskId, run.output, signal);
268
234
  }
269
235
  }
270
236
  const VERIFICATION_TIMEOUT_MS = 180_000;
@@ -282,7 +248,4 @@ export function verificationCommand(taskMarkdown) {
282
248
  }
283
249
  return command;
284
250
  }
285
- function isAborted(signal) {
286
- return signal.aborted;
287
- }
288
251
  //# sourceMappingURL=task-window.js.map
@@ -1,12 +1,17 @@
1
1
  import * as path from 'node:path';
2
2
  import { ReadSpecArtifactInputSchema, ReadFileSliceInputSchema, GetActiveTaskInputSchema, ApplyFilePatchInputSchema, CompleteTaskInputSchema, } from '../contracts.js';
3
3
  import { PatchSandbox } from '../patch-sandbox.js';
4
- import { TaskWindowManager } from '../task-window.js';
4
+ import { TaskWindowManager, verificationCommand } from '../task-window.js';
5
+ import { activeTaskFromContent, hasReceiptDirective } from '../task-content.js';
6
+ import { parseManifestContent, parseVerificationReceiptPolicy, toPosixPath, } from '../feature-manifest.js';
7
+ import { captureReceiptEvidence } from '../verification-receipts.js';
8
+ import { captureVerificationRoot, checkReceiptPatchTarget, revalidateVerificationInputs, } from '../verification-inputs.js';
9
+ import { completionError, completionFailure, patchMutationError } from '../task-failures.js';
5
10
  import { formatResult } from './format-result.js';
6
- import { acquireCompletionLease } from '../completion-guard.js';
7
- import { captureCompletionSnapshot } from '../completion-snapshot.js';
8
- import { CompletionGuardError } from '../feature-authority.js';
11
+ import { acquireCompletionLease, inspectCompletionGuard } from '../completion-guard.js';
12
+ import { captureCompletionSnapshot, revalidateCompletionSnapshot } from '../completion-snapshot.js';
9
13
  import { homeFallbackFailure, readTextInsideWorkspace } from '../workspace-root.js';
14
+ import { guardFailure } from '../feature-authority.js';
10
15
  const SLICE_LINE_CAP = 200;
11
16
  function sourceLines(fileData) {
12
17
  if (fileData.length === 0) {
@@ -90,7 +95,7 @@ function registerGetActiveTaskTool(server, workspace, taskWindow) {
90
95
  server.registerTool('sdd_get_active_task', {
91
96
  description: 'Delivers exclusively the active task (Single Task Window). Zero future backlog.',
92
97
  inputSchema: GetActiveTaskInputSchema.shape,
93
- }, async (rawArgs) => {
98
+ }, async (rawArgs, extra) => {
94
99
  const args = GetActiveTaskInputSchema.parse(rawArgs);
95
100
  const resolved = await workspace.resolve();
96
101
  const homeError = homeFallbackFailure(resolved, 'sdd_get_active_task');
@@ -99,9 +104,60 @@ function registerGetActiveTaskTool(server, workspace, taskWindow) {
99
104
  }
100
105
  const tasksPath = path.join(resolved.sddDir, 'features', args.feature_id, 'tasks.md');
101
106
  const result = await taskWindow.getActiveTask(tasksPath);
107
+ const active = result.success ? result.data.activeTask : null;
108
+ if (result.success &&
109
+ result.data.trinity === 'ready' &&
110
+ active?.fullTaskMarkdown.split('\n').some(hasReceiptDirective)) {
111
+ return formatResult(await getReceiptActiveTask(path.dirname(tasksPath), active.fullTaskMarkdown, resolved.workspaceRoot, extra.signal));
112
+ }
102
113
  return formatResult(result);
103
114
  });
104
115
  }
116
+ async function getReceiptActiveTask(feature, previousTaskMarkdown, workspaceRoot, signal) {
117
+ const trigger = 'sdd_get_active_task';
118
+ try {
119
+ const root = await captureVerificationRoot(workspaceRoot);
120
+ const snapshot = await captureCompletionSnapshot(feature, { workspaceRoot: root.canonical });
121
+ const current = activeTaskFromContent(snapshot.tasksContent, verificationCommand);
122
+ const active = current.success ? current.data.activeTask : null;
123
+ if (!current.success || active?.fullTaskMarkdown !== previousTaskMarkdown) {
124
+ return completionFailure('contract_drift', undefined, trigger);
125
+ }
126
+ const data = current.data;
127
+ const policy = parseVerificationReceiptPolicy(path.basename(snapshot.featDir), snapshot.planContent, snapshot.tasksContent);
128
+ const task = policy.status === 'ready' ? policy.tasks.get(active.taskId) : undefined;
129
+ if (policy.status !== 'ready' || !task) {
130
+ return completionFailure('contract_drift', undefined, trigger);
131
+ }
132
+ const captured = await captureReceiptEvidence(snapshot, workspaceRoot, policy, task, root, signal);
133
+ if (captured.success) {
134
+ await revalidateVerificationInputs(captured.data.inputs, signal);
135
+ }
136
+ await revalidateCompletionSnapshot(snapshot);
137
+ const guard = await inspectCompletionGuard(feature);
138
+ if (guard) {
139
+ return completionFailure(guard.reason, undefined, trigger);
140
+ }
141
+ if (!captured.success) {
142
+ return { ...captured, error: { ...captured.error, trigger } };
143
+ }
144
+ const manifest = [...parseManifestContent(snapshot.planContent).allowedFiles.entries()].map(([filePath, permission]) => ({ path: filePath, permission }));
145
+ return {
146
+ success: true,
147
+ data: {
148
+ ...data,
149
+ activeTask: { ...active, verificationCommand: task.command },
150
+ locked: true,
151
+ trinity: 'ready',
152
+ manifest,
153
+ verificationEvidence: captured.data.evidence,
154
+ },
155
+ };
156
+ }
157
+ catch (error) {
158
+ return completionError(error, trigger);
159
+ }
160
+ }
105
161
  function registerApplyPatchTool(server, workspace) {
106
162
  server.registerTool('sdd_apply_file_patch', {
107
163
  description: 'Applies CREATE and MODIFY patches, or exact DELETE operations, strictly authorized in plan.md File Manifest. DELETE requires empty search_content and replace_content.',
@@ -113,8 +169,7 @@ function registerApplyPatchTool(server, workspace) {
113
169
  if (homeError) {
114
170
  return formatResult(homeError);
115
171
  }
116
- const patchSandbox = new PatchSandbox(resolved.workspaceRoot);
117
- return executeApplyPatch(resolved.sddDir, patchSandbox, args);
172
+ return executeApplyPatch(resolved.workspaceRoot, args);
118
173
  });
119
174
  }
120
175
  function registerCompleteTaskTool(server, workspace, taskWindow) {
@@ -128,9 +183,8 @@ function registerCompleteTaskTool(server, workspace, taskWindow) {
128
183
  if (homeError) {
129
184
  return formatResult(homeError);
130
185
  }
131
- const featDir = path.join(resolved.sddDir, 'features', args.feature_id);
132
- const tasksPath = path.join(featDir, 'tasks.md');
133
- const result = await taskWindow.completeTask(tasksPath, args.task_id, resolved.workspaceRoot, args.verification_output ?? '', extra.signal);
186
+ const tasksPath = path.join(resolved.sddDir, 'features', args.feature_id, 'tasks.md');
187
+ const result = await taskWindow.completeTask(tasksPath, args.task_id, resolved.workspaceRoot, args.verification_output ?? '', extra.signal, args.verification_receipts);
134
188
  return formatResult(result);
135
189
  });
136
190
  }
@@ -181,18 +235,25 @@ async function executeReadFileSlice(workspaceRoot, relPath, startLine, endLine)
181
235
  },
182
236
  });
183
237
  }
184
- async function executeApplyPatch(sddDir, patchSandbox, args) {
185
- const featDir = path.join(sddDir, 'features', args.feature_id);
238
+ async function executeApplyPatch(workspaceRoot, args) {
186
239
  try {
187
- const lease = await acquireCompletionLease(featDir, {
188
- operation: 'patch',
189
- workspaceRoot: path.dirname(sddDir),
190
- });
240
+ const root = await captureVerificationRoot(workspaceRoot);
241
+ const featDir = path.join(root.canonical, '.sdd', 'features', args.feature_id);
242
+ const authority = { workspaceRoot: root.canonical };
243
+ const lease = await acquireCompletionLease(featDir, { ...authority, operation: 'patch' });
191
244
  try {
192
- await captureCompletionSnapshot(featDir, { workspaceRoot: path.dirname(sddDir) });
193
- const planPath = path.join(featDir, 'plan.md');
194
- const manifest = await patchSandbox.parsePlanManifest(planPath);
195
- const patchResult = await patchSandbox.applyPatch(manifest, args.path, args.search_content, args.replace_content);
245
+ const snapshot = await captureCompletionSnapshot(featDir, authority);
246
+ const manifest = parseManifestContent(snapshot.planContent);
247
+ const receiptPolicy = parseVerificationReceiptPolicy(args.feature_id, snapshot.planContent, snapshot.tasksContent);
248
+ if (receiptPolicy.status === 'invalid') {
249
+ guardFailure('contract_drift', 'The locked receipt policy is invalid.');
250
+ }
251
+ if (receiptPolicy.status === 'ready') {
252
+ const target = toPosixPath(args.path);
253
+ await checkReceiptPatchTarget(root, workspaceRoot, target, manifest.allowedFiles.get(target), args.search_content);
254
+ await revalidateCompletionSnapshot(snapshot);
255
+ }
256
+ const patchResult = await new PatchSandbox(root.canonical).applyPatch(manifest, args.path, args.search_content, args.replace_content);
196
257
  return formatResult(patchResult);
197
258
  }
198
259
  finally {
@@ -200,15 +261,7 @@ async function executeApplyPatch(sddDir, patchSandbox, args) {
200
261
  }
201
262
  }
202
263
  catch (error) {
203
- return formatResult({
204
- success: false,
205
- error: {
206
- code: error instanceof CompletionGuardError ? error.code : 'ERR_VERIFICATION_FAILED',
207
- message: error instanceof CompletionGuardError ? error.message : 'Feature mutation was denied.',
208
- trigger: 'sdd_apply_file_patch',
209
- details: { reason: error instanceof CompletionGuardError ? error.reason : 'failed' },
210
- },
211
- });
264
+ return formatResult(patchMutationError(error));
212
265
  }
213
266
  }
214
267
  //# sourceMappingURL=execution-tools.js.map
@@ -0,0 +1,12 @@
1
+ import type { FilePermission, ReceiptCandidate, ReceiptTaskPolicy, VerificationInputCategory, VerificationInputReason, WorkspaceRoot, VerificationInputSnapshot } from '../types/sdd-engine.js';
2
+ export declare class VerificationInputError extends Error {
3
+ readonly reason: VerificationInputReason;
4
+ readonly category?: VerificationInputCategory | undefined;
5
+ readonly path?: string | undefined;
6
+ constructor(reason: VerificationInputReason, category?: VerificationInputCategory | undefined, path?: string | undefined);
7
+ }
8
+ export declare function captureVerificationRoot(workspaceRoot: string): Promise<WorkspaceRoot>;
9
+ export declare function captureVerificationInputs(workspaceRoot: string, candidates: readonly ReceiptCandidate[], task: ReceiptTaskPolicy, signal?: AbortSignal, expectedRoot?: WorkspaceRoot): Promise<VerificationInputSnapshot>;
10
+ export declare function checkReceiptPatchTarget(root: WorkspaceRoot, workspaceRoot: string, path: string, permission: FilePermission | undefined, searchContent: string): Promise<void>;
11
+ export declare function revalidateVerificationInputs(snapshot: VerificationInputSnapshot, signal?: AbortSignal): Promise<void>;
12
+ //# sourceMappingURL=verification-inputs.d.ts.map