@planu/cli 8.2.16 → 8.2.18

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 (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +15 -3
  3. package/dist/sdd-engine/cli.js +0 -0
  4. package/dist/sdd-engine/completion-guard.d.ts +28 -0
  5. package/dist/sdd-engine/completion-guard.js +320 -0
  6. package/dist/sdd-engine/completion-snapshot.d.ts +11 -0
  7. package/dist/sdd-engine/completion-snapshot.js +155 -0
  8. package/dist/sdd-engine/feature-authority.d.ts +20 -0
  9. package/dist/sdd-engine/feature-authority.js +199 -0
  10. package/dist/sdd-engine/feature-manifest.d.ts +6 -0
  11. package/dist/sdd-engine/feature-manifest.js +116 -0
  12. package/dist/sdd-engine/host-rule-pack.d.ts +1 -0
  13. package/dist/sdd-engine/host-rule-pack.js +63 -7
  14. package/dist/sdd-engine/lock-integrity.d.ts +3 -18
  15. package/dist/sdd-engine/lock-integrity.js +192 -217
  16. package/dist/sdd-engine/patch-sandbox.js +6 -14
  17. package/dist/sdd-engine/server.js +4 -6
  18. package/dist/sdd-engine/task-content.d.ts +8 -0
  19. package/dist/sdd-engine/task-content.js +132 -0
  20. package/dist/sdd-engine/task-failures.d.ts +12 -0
  21. package/dist/sdd-engine/task-failures.js +125 -0
  22. package/dist/sdd-engine/task-window.d.ts +10 -4
  23. package/dist/sdd-engine/task-window.js +177 -246
  24. package/dist/sdd-engine/tools/execution-tools.js +29 -26
  25. package/dist/sdd-engine/tools/feature-store.d.ts +11 -0
  26. package/dist/sdd-engine/tools/feature-store.js +224 -0
  27. package/dist/sdd-engine/tools/workspace-tools.js +70 -127
  28. package/dist/sdd-engine/workspace-init.d.ts +3 -0
  29. package/dist/sdd-engine/workspace-init.js +197 -0
  30. package/dist/sdd-engine/workspace-root.d.ts +3 -1
  31. package/dist/sdd-engine/workspace-root.js +69 -3
  32. package/dist/types/completion.d.ts +77 -0
  33. package/dist/types/completion.js +2 -0
  34. package/package.json +32 -35
  35. package/templates/AGENTS.md +4 -0
  36. package/templates/host/planu-sdd.md +4 -0
  37. package/templates/skills/reconciler.md +8 -0
  38. package/templates/skills/spec-architect.md +22 -5
  39. package/templates/skills/spec-executor.md +11 -0
  40. package/templates/skills/verification-auditor.md +20 -0
@@ -1,13 +1,17 @@
1
- import { spawn } from 'node:child_process';
2
- import * as fs from 'node:fs/promises';
3
1
  import * as path from 'node:path';
4
- import { ScopedVerificationCoordinator } from './verification-runner.js';
5
- import { persistScopedCompletionFiles, scopedVerificationEnvironment, } from './verification-policy.js';
6
- import { executionCard, hashArtifact } from './lock-integrity.js';
7
- const UNLOCKED_CARD = { locked: false, trinity: 'unlocked', manifest: [] };
2
+ import { ScopedVerificationCoordinator, runScopedVerification } from './verification-runner.js';
3
+ import { persistScopedCompletionFiles, isScopedVerificationFeature, scopedFeaturePathFailure, } from './verification-policy.js';
4
+ import { executionCard } from './lock-integrity.js';
5
+ import { CompletionGuardError, readFeatureArtifact } from './feature-authority.js';
6
+ 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';
8
10
  export class TaskWindowManager {
9
11
  scopedPolicy;
10
12
  scoped;
13
+ shutdownController = new AbortController();
14
+ pending = new Set();
11
15
  constructor(policy) {
12
16
  this.scopedPolicy = policy?.mode === 'scoped' ? policy : undefined;
13
17
  this.scoped = this.scopedPolicy
@@ -15,10 +19,12 @@ export class TaskWindowManager {
15
19
  : undefined;
16
20
  }
17
21
  async shutdown() {
22
+ this.shutdownController.abort();
18
23
  await this.scoped?.shutdown();
24
+ await Promise.allSettled([...this.pending]);
19
25
  }
20
26
  activeTaskFromContent(content) {
21
- return this.buildActiveTaskResult(this.parseTasks(content.split('\n')));
27
+ return activeTaskFromContent(content, verificationCommand);
22
28
  }
23
29
  selectScopedTask(content) {
24
30
  const result = this.activeTaskFromContent(content);
@@ -53,230 +59,214 @@ export class TaskWindowManager {
53
59
  async getActiveTask(tasksFilePath) {
54
60
  let content;
55
61
  try {
56
- content = await fs.readFile(tasksFilePath, 'utf-8');
62
+ const feature = path.dirname(tasksFilePath);
63
+ const guard = await inspectCompletionGuard(feature);
64
+ if (guard) {
65
+ return completionFailure(guard.reason, undefined, 'sdd_get_active_task');
66
+ }
67
+ content = await readFeatureArtifact(feature, 'tasks.md');
57
68
  }
58
- catch {
59
- return {
60
- success: false,
61
- error: {
62
- code: 'ERR_TASK_NOT_FOUND',
63
- message: `File tasks.md not found at: '${tasksFilePath}'.`,
64
- trigger: 'sdd_get_active_task',
65
- },
66
- };
69
+ catch (error) {
70
+ if (error instanceof CompletionGuardError) {
71
+ return completionError(error, 'sdd_get_active_task');
72
+ }
73
+ return taskFileMissing(tasksFilePath);
67
74
  }
68
75
  const built = this.activeTaskFromContent(content);
69
76
  if (!built.success) {
70
77
  return built;
71
78
  }
72
- const card = await executionCard(path.dirname(tasksFilePath));
73
- return { success: true, data: { ...built.data, ...card } };
79
+ try {
80
+ const card = await executionCard(path.dirname(tasksFilePath));
81
+ const guard = await inspectCompletionGuard(path.dirname(tasksFilePath));
82
+ if (guard) {
83
+ return completionFailure(guard.reason, undefined, 'sdd_get_active_task');
84
+ }
85
+ return { success: true, data: { ...built.data, ...card } };
86
+ }
87
+ catch (error) {
88
+ return completionError(error, 'sdd_get_active_task');
89
+ }
74
90
  }
75
- buildActiveTaskResult(acc) {
76
- if (acc.totalTasks === 0) {
77
- return {
78
- success: true,
79
- data: { activeTask: null, allCompleted: false, status: 'NO_TASKS', ...UNLOCKED_CARD },
80
- };
91
+ async getCatalogueEntry(featDir) {
92
+ const id = path.basename(featDir);
93
+ try {
94
+ const artifacts = await readCatalogueArtifacts(featDir);
95
+ return catalogueFromContent(id, artifacts.locked, artifacts.tasksContent, verificationCommand);
81
96
  }
82
- if (acc.activeTaskIndex === -1 || acc.completedTasks === acc.totalTasks) {
83
- return {
84
- success: true,
85
- data: { activeTask: null, allCompleted: true, status: 'ALL_COMPLETED', ...UNLOCKED_CARD },
86
- };
97
+ catch (error) {
98
+ return catalogueReadFailure(error, id);
87
99
  }
88
- return {
89
- success: true,
90
- data: {
91
- activeTask: {
92
- taskId: acc.activeTaskId,
93
- taskTitle: acc.activeTaskTitle,
94
- fullTaskMarkdown: acc.activeTaskLines.join('\n').trim(),
95
- verificationCommand: verificationCommand(acc.activeTaskLines.join('\n')),
96
- taskIndex: acc.activeTaskIndex,
97
- totalTasks: acc.totalTasks,
98
- completedTasks: acc.completedTasks,
99
- },
100
- allCompleted: false,
101
- status: 'IN_PROGRESS',
102
- ...UNLOCKED_CARD,
103
- },
104
- };
105
100
  }
106
- parseTasks(lines) {
107
- const acc = {
108
- totalTasks: 0,
109
- completedTasks: 0,
110
- activeTaskIndex: -1,
111
- activeTaskId: '',
112
- activeTaskTitle: '',
113
- activeTaskLines: [],
114
- isCapturingActive: false,
115
- };
116
- const taskRegex = /^[-*]\s*\[([\s/xX])\]\s*(.*)$/;
117
- for (const line of lines) {
118
- const match = taskRegex.exec(line.trim());
119
- if (match?.[1] && match[2]) {
120
- acc.totalTasks++;
121
- const statusChar = match[1].trim().toLowerCase();
122
- if (statusChar === 'x') {
123
- acc.completedTasks++;
124
- if (acc.isCapturingActive) {
125
- acc.isCapturingActive = false;
126
- }
127
- }
128
- else if (!acc.isCapturingActive && acc.activeTaskIndex === -1) {
129
- acc.isCapturingActive = true;
130
- acc.activeTaskIndex = acc.totalTasks;
131
- const parsed = this.extractTaskId(match[2].trim(), acc.activeTaskIndex);
132
- acc.activeTaskId = parsed.id;
133
- acc.activeTaskTitle = parsed.title;
134
- acc.activeTaskLines.push(line);
135
- }
136
- else if (acc.isCapturingActive) {
137
- acc.isCapturingActive = false;
101
+ async completeTask(tasksFilePath, taskId, workspaceRoot, _verificationOutput, signal) {
102
+ const operation = this.completeOwned(tasksFilePath, taskId, workspaceRoot, signal);
103
+ this.pending.add(operation);
104
+ try {
105
+ return await operation;
106
+ }
107
+ finally {
108
+ this.pending.delete(operation);
109
+ }
110
+ }
111
+ async completeOwned(tasksFilePath, taskId, workspaceRoot, signal) {
112
+ try {
113
+ const feature = path.dirname(tasksFilePath);
114
+ const abortSignal = AbortSignal.any([
115
+ this.shutdownController.signal,
116
+ ...(signal ? [signal] : []),
117
+ ]);
118
+ const pathFailure = await this.checkScopedPaths(tasksFilePath, workspaceRoot, feature);
119
+ if (pathFailure) {
120
+ return pathFailure;
121
+ }
122
+ const lease = await acquireCompletionLease(feature, { operation: 'complete', workspaceRoot });
123
+ try {
124
+ const snapshot = await captureCompletionSnapshot(feature, {
125
+ writable: true,
126
+ workspaceRoot,
127
+ validateLock: this.scopedPolicy === undefined,
128
+ });
129
+ const selected = this.selectScopedTask(snapshot.tasksContent);
130
+ await lease.bind(taskId, selected?.command ?? '', snapshot.digest);
131
+ const scoped = await this.attemptScopedCompletion(tasksFilePath, taskId, workspaceRoot, abortSignal, snapshot, lease);
132
+ if (scoped !== null) {
133
+ return scoped;
138
134
  }
135
+ return await this.completeOrdinary(snapshot, lease, taskId, workspaceRoot, abortSignal);
139
136
  }
140
- else if (acc.isCapturingActive) {
141
- acc.activeTaskLines.push(line);
137
+ finally {
138
+ // A retained lease deliberately blocks recovery after uncertain persistence or cleanup.
139
+ await lease.release(abortSignal);
142
140
  }
143
141
  }
144
- return acc;
142
+ catch (error) {
143
+ return completionError(error);
144
+ }
145
145
  }
146
- extractTaskId(rawTitle, index) {
147
- const idMatch = /^(TASK-[A-Z0-9_-]+|[A-Z0-9_-]+):\s*(.*)$/i.exec(rawTitle);
148
- if (idMatch?.[1] && idMatch[2]) {
149
- return { id: idMatch[1].toUpperCase(), title: idMatch[2].trim() };
146
+ async checkScopedPaths(tasksFilePath, workspaceRoot, feature) {
147
+ const policy = this.scopedPolicy;
148
+ if (policy && (await isScopedVerificationFeature(policy, feature))) {
149
+ if (workspaceRoot !== policy.workspaceRoot ||
150
+ tasksFilePath !==
151
+ path.join(policy.workspaceRoot, '.sdd', 'features', policy.featureId, 'tasks.md')) {
152
+ return scopedPathMismatch();
153
+ }
154
+ const failure = await scopedFeaturePathFailure(policy);
155
+ if (failure) {
156
+ return failure;
157
+ }
150
158
  }
151
- return { id: `TASK-${index}`, title: rawTitle };
159
+ return null;
152
160
  }
153
- async completeTask(tasksFilePath, taskId, workspaceRoot, _verificationOutput, signal) {
161
+ async attemptScopedCompletion(tasksFilePath, taskId, workspaceRoot, signal, snapshot, lease) {
154
162
  const policy = this.scopedPolicy;
155
- if (this.scoped && policy) {
156
- const scoped = await this.scoped.complete({
157
- tasksPath: tasksFilePath,
158
- taskId,
159
- workspaceRoot,
160
- signal,
161
- selectTask: (content) => this.selectScopedTask(content),
162
- commit: (snapshot, output, abortSignal) => this.commitScopedTask(policy, taskId, snapshot, output, abortSignal),
163
- });
164
- if (scoped) {
165
- return scoped;
163
+ if (!this.scoped || !policy) {
164
+ return null;
165
+ }
166
+ const scoped = await this.scoped.complete({
167
+ tasksPath: tasksFilePath,
168
+ taskId,
169
+ workspaceRoot,
170
+ signal,
171
+ selectTask: (content) => this.selectScopedTask(content),
172
+ commit: (scopedSnapshot, output, commitSignal) => this.commitOwnedScopedTask(policy, taskId, scopedSnapshot, output, commitSignal, snapshot, lease),
173
+ });
174
+ if (scoped !== null) {
175
+ if (!scoped.success && scoped.error.details?.cleanupComplete === false) {
176
+ lease.retain();
166
177
  }
178
+ return scoped;
167
179
  }
168
- let content;
180
+ // A grant for another feature never authorizes this ordinary invocation.
181
+ await revalidateCompletionSnapshot(snapshot);
182
+ return null;
183
+ }
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();
169
190
  try {
170
- content = await fs.readFile(tasksFilePath, 'utf-8');
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;
171
200
  }
172
- catch {
173
- return missingTasksFile(tasksFilePath);
201
+ catch (error) {
202
+ lease.retain();
203
+ throw error;
174
204
  }
175
- const active = await this.getActiveTask(tasksFilePath);
205
+ }
206
+ async completeOrdinary(snapshot, lease, taskId, workspaceRoot, signal) {
207
+ const active = this.activeTaskFromContent(snapshot.tasksContent);
176
208
  if (!active.success) {
177
209
  return active;
178
210
  }
179
211
  const activeTask = active.data.activeTask;
180
212
  if (activeTask?.taskId.toUpperCase() !== taskId.toUpperCase()) {
181
- return taskOutOfSequence(taskId, activeTask?.taskId ?? null);
213
+ return taskOutOfSequence(taskId, activeTask?.taskId ?? null, wasTaskCompleted(snapshot.tasksContent, taskId));
182
214
  }
183
215
  const command = verificationCommand(activeTask.fullTaskMarkdown);
184
216
  if (command === null) {
185
217
  return verificationMissing();
186
218
  }
187
- const run = await runVerification(workspaceRoot, command, scopedVerificationEnvironment());
219
+ // Validate ordinary integrity even if the server holds an unrelated scoped grant.
220
+ const validated = await captureCompletionSnapshot(snapshot.featDir, {
221
+ writable: true,
222
+ workspaceRoot,
223
+ });
224
+ if (validated.digest !== snapshot.digest) {
225
+ return completionFailure('contract_drift');
226
+ }
227
+ if (signal.aborted) {
228
+ return completionFailure('cancelled');
229
+ }
230
+ if (!['darwin', 'linux'].includes(process.platform)) {
231
+ return unsupportedVerificationPlatform();
232
+ }
233
+ const run = await runScopedVerification({
234
+ cwd: workspaceRoot,
235
+ command,
236
+ timeoutMs: VERIFICATION_TIMEOUT_MS,
237
+ signal,
238
+ });
239
+ if (!run.cleanupComplete) {
240
+ lease.retain();
241
+ }
188
242
  if (!run.ok) {
189
243
  return verificationFailed(run);
190
244
  }
191
- const lines = content.split('\n');
192
- const cleanOutput = summarizeEvidence(run.output);
193
- const marked = markTaskVerified(lines, taskId, cleanOutput);
194
- if (!marked) {
195
- return {
196
- success: false,
197
- error: {
198
- code: 'ERR_TASK_OUT_OF_SEQUENCE',
199
- message: `Task '${taskId}' is not active or was already completed.`,
200
- trigger: 'sdd_complete_task',
201
- details: { requestedTaskId: taskId },
202
- },
203
- };
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);
204
256
  }
205
257
  const written = marked.join('\n');
206
- await fs.writeFile(tasksFilePath, written, 'utf-8');
207
- await refreshTasksHashIfLocked(tasksFilePath, written);
208
- const checkRes = await this.getActiveTask(tasksFilePath);
258
+ await persistCompletionSnapshot(lease, snapshot, written, signal);
259
+ const next = this.activeTaskFromContent(written);
209
260
  return {
210
261
  success: true,
211
262
  data: {
212
263
  completedTaskId: taskId,
213
- verificationSummary: cleanOutput,
214
- remainingTasks: remainingTaskCount(checkRes),
264
+ verificationSummary: summary,
265
+ remainingTasks: remainingTaskCount(next),
215
266
  },
216
267
  };
217
268
  }
218
269
  }
219
- function missingTasksFile(tasksFilePath) {
220
- return {
221
- success: false,
222
- error: {
223
- code: 'ERR_TASK_NOT_FOUND',
224
- message: `File tasks.md not found at: '${tasksFilePath}'.`,
225
- trigger: 'sdd_complete_task',
226
- },
227
- };
228
- }
229
- function taskOutOfSequence(taskId, activeTaskId) {
230
- return {
231
- success: false,
232
- error: {
233
- code: 'ERR_TASK_OUT_OF_SEQUENCE',
234
- message: `Task '${taskId}' is not active or was already completed.`,
235
- trigger: 'sdd_complete_task',
236
- details: { requestedTaskId: taskId, activeTaskId },
237
- },
238
- };
239
- }
240
- function verificationMissing() {
241
- return {
242
- success: false,
243
- error: {
244
- code: 'ERR_VERIFICATION_MISSING',
245
- message: 'The active task needs one Verification line whose command does not contain < or >.',
246
- trigger: 'sdd_complete_task',
247
- },
248
- };
249
- }
250
- function verificationFailed(run) {
251
- const exitCode = run.exitCode ?? 1;
252
- return {
253
- success: false,
254
- error: {
255
- code: 'ERR_VERIFICATION_FAILED',
256
- message: `Verification command exited ${String(exitCode)}.`,
257
- trigger: 'sdd_complete_task',
258
- details: { exitCode, outputTail: run.output.slice(-2000) },
259
- },
260
- };
261
- }
262
- function markTaskVerified(lines, taskId, cleanOutput) {
263
- const regexExact = new RegExp(`^(\\s*[-*]\\s*\\[)[\\s/](\\]\\s*(?:${taskId}\\b|.*\\b${taskId}\\b.*))`, 'i');
264
- const next = [...lines];
265
- for (let i = 0; i < next.length; i++) {
266
- const line = next[i];
267
- if (line !== undefined && regexExact.test(line)) {
268
- next[i] = line.replace(regexExact, (_, open, rest) => `${open}x${rest} — [Verified: ${cleanOutput}]`);
269
- return next;
270
- }
271
- }
272
- return null;
273
- }
274
- function remainingTaskCount(checkRes) {
275
- if (!checkRes.success || !checkRes.data.activeTask) {
276
- return 0;
277
- }
278
- return checkRes.data.activeTask.totalTasks - checkRes.data.activeTask.completedTasks;
279
- }
280
270
  const VERIFICATION_TIMEOUT_MS = 180_000;
281
271
  export function verificationCommand(taskMarkdown) {
282
272
  const line = taskMarkdown
@@ -292,66 +282,7 @@ export function verificationCommand(taskMarkdown) {
292
282
  }
293
283
  return command;
294
284
  }
295
- function runVerification(cwd, command, env) {
296
- return new Promise((resolve) => {
297
- const child = spawn(command, {
298
- cwd,
299
- shell: true,
300
- timeout: VERIFICATION_TIMEOUT_MS,
301
- ...(env ? { env } : {}),
302
- windowsHide: true,
303
- });
304
- let output = '';
305
- const append = (chunk) => {
306
- output += chunk.toString('utf8');
307
- if (output.length > 100_000) {
308
- output = output.slice(-100_000);
309
- }
310
- };
311
- child.stdout.on('data', append);
312
- child.stderr.on('data', append);
313
- child.on('error', (error) => {
314
- resolve({ ok: false, exitCode: 1, output: error.message });
315
- });
316
- child.on('close', (code, signal) => {
317
- const timedOut = signal === 'SIGTERM';
318
- resolve({
319
- ok: code === 0 && !timedOut,
320
- exitCode: code,
321
- output: timedOut ? `${output}\nverification timed out after 180 seconds` : output,
322
- });
323
- });
324
- });
325
- }
326
- const EVIDENCE_LIMIT = 500;
327
- function summarizeEvidence(output) {
328
- const collapsed = output.trim().replace(/\s+/g, ' ');
329
- if (collapsed.length <= EVIDENCE_LIMIT) {
330
- return collapsed;
331
- }
332
- const head = Array.from(collapsed).slice(0, EVIDENCE_LIMIT).join('');
333
- const lastSpace = head.lastIndexOf(' ');
334
- return `${(lastSpace > 0 ? head.slice(0, lastSpace) : head).trimEnd()}…`;
335
- }
336
- async function refreshTasksHashIfLocked(tasksFilePath, tasksContent) {
337
- const lockPath = path.join(path.dirname(tasksFilePath), '.lock');
338
- let raw;
339
- try {
340
- raw = await fs.readFile(lockPath, 'utf-8');
341
- }
342
- catch {
343
- return;
344
- }
345
- try {
346
- const lock = JSON.parse(raw);
347
- if (!lock.tasksHash) {
348
- return;
349
- }
350
- lock.tasksHash = hashArtifact(tasksContent);
351
- await fs.writeFile(lockPath, JSON.stringify(lock, null, 2), 'utf-8');
352
- }
353
- catch {
354
- return;
355
- }
285
+ function isAborted(signal) {
286
+ return signal.aborted;
356
287
  }
357
288
  //# sourceMappingURL=task-window.js.map
@@ -3,7 +3,9 @@ import { ReadSpecArtifactInputSchema, ReadFileSliceInputSchema, GetActiveTaskInp
3
3
  import { PatchSandbox } from '../patch-sandbox.js';
4
4
  import { TaskWindowManager } from '../task-window.js';
5
5
  import { formatResult } from './format-result.js';
6
- import { verifyLockedTrinity } from '../lock-integrity.js';
6
+ import { acquireCompletionLease } from '../completion-guard.js';
7
+ import { captureCompletionSnapshot } from '../completion-snapshot.js';
8
+ import { CompletionGuardError } from '../feature-authority.js';
7
9
  import { homeFallbackFailure, readTextInsideWorkspace } from '../workspace-root.js';
8
10
  const SLICE_LINE_CAP = 200;
9
11
  function sourceLines(fileData) {
@@ -127,10 +129,6 @@ function registerCompleteTaskTool(server, workspace, taskWindow) {
127
129
  return formatResult(homeError);
128
130
  }
129
131
  const featDir = path.join(resolved.sddDir, 'features', args.feature_id);
130
- const lockError = await requireLockedTrinity(featDir, 'sdd_complete_task');
131
- if (lockError) {
132
- return lockError;
133
- }
134
132
  const tasksPath = path.join(featDir, 'tasks.md');
135
133
  const result = await taskWindow.completeTask(tasksPath, args.task_id, resolved.workspaceRoot, args.verification_output ?? '', extra.signal);
136
134
  return formatResult(result);
@@ -183,29 +181,34 @@ async function executeReadFileSlice(workspaceRoot, relPath, startLine, endLine)
183
181
  },
184
182
  });
185
183
  }
186
- async function requireLockedTrinity(featDir, trigger) {
187
- const lockCheck = await verifyLockedTrinity(featDir);
188
- if (lockCheck.ok) {
189
- return null;
190
- }
191
- return formatResult({
192
- success: false,
193
- error: {
194
- code: lockCheck.code ?? 'ERR_SPEC_NOT_LOCKED',
195
- message: lockCheck.message ?? `Feature spec at '${featDir}' must be locked before execution.`,
196
- trigger,
197
- },
198
- });
199
- }
200
184
  async function executeApplyPatch(sddDir, patchSandbox, args) {
201
185
  const featDir = path.join(sddDir, 'features', args.feature_id);
202
- const lockError = await requireLockedTrinity(featDir, 'sdd_apply_file_patch');
203
- if (lockError) {
204
- return lockError;
186
+ try {
187
+ const lease = await acquireCompletionLease(featDir, {
188
+ operation: 'patch',
189
+ workspaceRoot: path.dirname(sddDir),
190
+ });
191
+ 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);
196
+ return formatResult(patchResult);
197
+ }
198
+ finally {
199
+ await lease.release();
200
+ }
201
+ }
202
+ 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
+ });
205
212
  }
206
- const planPath = path.join(featDir, 'plan.md');
207
- const manifest = await patchSandbox.parsePlanManifest(planPath);
208
- const patchResult = await patchSandbox.applyPatch(manifest, args.path, args.search_content, args.replace_content);
209
- return formatResult(patchResult);
210
213
  }
211
214
  //# sourceMappingURL=execution-tools.js.map
@@ -0,0 +1,11 @@
1
+ import type { FeatureSummary, SddFailure, SddResult } from '../../types/sdd-engine.js';
2
+ import type { TaskWindowManager } from '../task-window.js';
3
+ export declare function createExplicitFeatureDirectory(featDir: string, featureId: string): Promise<SddFailure | null>;
4
+ export declare function reserveAutomaticFeatureDirectory(featuresDir: string, title: string): Promise<{
5
+ featureId: string;
6
+ featDir: string;
7
+ }>;
8
+ export declare function collectFeatures(featuresDir: string, taskWindow: TaskWindowManager, statusFilter?: 'all' | 'planning' | 'executing' | 'done'): Promise<SddResult<FeatureSummary[]>>;
9
+ export declare function featurePathFailure(workspaceRoot: string, directory: string, trigger: string): Promise<SddFailure | null>;
10
+ export declare function writeFeatureArtifacts(featDir: string, id: string, title: string): Promise<void>;
11
+ //# sourceMappingURL=feature-store.d.ts.map