@planu/cli 8.2.17 → 8.2.19

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 (36) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +22 -2
  3. package/dist/sdd-engine/completion-guard.d.ts +28 -0
  4. package/dist/sdd-engine/completion-guard.js +320 -0
  5. package/dist/sdd-engine/completion-snapshot.d.ts +11 -0
  6. package/dist/sdd-engine/completion-snapshot.js +155 -0
  7. package/dist/sdd-engine/feature-authority.d.ts +20 -0
  8. package/dist/sdd-engine/feature-authority.js +199 -0
  9. package/dist/sdd-engine/feature-manifest.d.ts +6 -0
  10. package/dist/sdd-engine/feature-manifest.js +116 -0
  11. package/dist/sdd-engine/host-rule-pack.d.ts +1 -0
  12. package/dist/sdd-engine/host-rule-pack.js +67 -7
  13. package/dist/sdd-engine/lock-integrity.d.ts +3 -18
  14. package/dist/sdd-engine/lock-integrity.js +192 -217
  15. package/dist/sdd-engine/patch-sandbox.js +1 -1
  16. package/dist/sdd-engine/server.js +4 -6
  17. package/dist/sdd-engine/task-content.d.ts +8 -0
  18. package/dist/sdd-engine/task-content.js +132 -0
  19. package/dist/sdd-engine/task-failures.d.ts +12 -0
  20. package/dist/sdd-engine/task-failures.js +125 -0
  21. package/dist/sdd-engine/task-window.d.ts +10 -4
  22. package/dist/sdd-engine/task-window.js +177 -246
  23. package/dist/sdd-engine/tools/execution-tools.js +29 -26
  24. package/dist/sdd-engine/tools/feature-store.d.ts +11 -0
  25. package/dist/sdd-engine/tools/feature-store.js +224 -0
  26. package/dist/sdd-engine/tools/workspace-tools.js +65 -127
  27. package/dist/sdd-engine/workspace-root.d.ts +3 -1
  28. package/dist/sdd-engine/workspace-root.js +69 -3
  29. package/dist/types/completion.d.ts +77 -0
  30. package/dist/types/completion.js +2 -0
  31. package/package.json +2 -2
  32. package/templates/AGENTS.md +8 -0
  33. package/templates/host/planu-sdd.md +8 -0
  34. package/templates/skills/spec-architect.md +4 -0
  35. package/templates/skills/spec-executor.md +18 -0
  36. package/templates/skills/verification-auditor.md +6 -0
@@ -0,0 +1,12 @@
1
+ import type { CompleteTaskResult, SddResult } from '../types/sdd-engine.js';
2
+ import type { ScopedVerificationRun } from '../types/verification.js';
3
+ export declare function completionFailure(reason: string, code?: 'ERR_VERIFICATION_FAILED' | 'ERR_SPEC_DRIFT', trigger?: string): SddResult<never>;
4
+ export declare function completionError(error: unknown, trigger?: string): SddResult<never>;
5
+ export declare function taskOutOfSequence(taskId: string, activeTaskId: string | null, alreadyCompleted?: boolean): SddResult<CompleteTaskResult>;
6
+ export declare function verificationMissing(): SddResult<CompleteTaskResult>;
7
+ export declare function verificationFailed(run: ScopedVerificationRun): SddResult<CompleteTaskResult>;
8
+ export declare function unsupportedVerificationPlatform(): SddResult<CompleteTaskResult>;
9
+ export declare function scopedPathMismatch(): SddResult<never>;
10
+ export declare function taskFileMissing(tasksFilePath: string): SddResult<never>;
11
+ export declare function catalogueReadFailure(error: unknown, id: string): SddResult<never>;
12
+ //# sourceMappingURL=task-failures.d.ts.map
@@ -0,0 +1,125 @@
1
+ import { CompletionGuardError } from './feature-authority.js';
2
+ export function completionFailure(reason, code = reason === 'contract_drift'
3
+ ? 'ERR_SPEC_DRIFT'
4
+ : 'ERR_VERIFICATION_FAILED', trigger = 'sdd_complete_task') {
5
+ return {
6
+ success: false,
7
+ error: {
8
+ code,
9
+ message: reason === 'persistence_uncertain'
10
+ ? 'Completion state requires explicit reviewed recovery with sdd_lock_spec.'
11
+ : 'Completion was denied; inspect the bounded reason before retrying.',
12
+ trigger,
13
+ details: { reason },
14
+ },
15
+ };
16
+ }
17
+ export function completionError(error, trigger = 'sdd_complete_task') {
18
+ if (error instanceof CompletionGuardError) {
19
+ return {
20
+ success: false,
21
+ error: {
22
+ code: error.code,
23
+ message: error.message,
24
+ trigger,
25
+ details: { reason: error.reason },
26
+ },
27
+ };
28
+ }
29
+ return completionFailure('failed', undefined, trigger);
30
+ }
31
+ export function taskOutOfSequence(taskId, activeTaskId, alreadyCompleted = false) {
32
+ return {
33
+ success: false,
34
+ error: {
35
+ code: 'ERR_TASK_OUT_OF_SEQUENCE',
36
+ message: `Task '${taskId}' is not active or was already completed.`,
37
+ trigger: 'sdd_complete_task',
38
+ details: {
39
+ requestedTaskId: taskId,
40
+ activeTaskId,
41
+ ...(alreadyCompleted ? { reason: 'already_completed' } : {}),
42
+ },
43
+ },
44
+ };
45
+ }
46
+ export function verificationMissing() {
47
+ return {
48
+ success: false,
49
+ error: {
50
+ code: 'ERR_VERIFICATION_MISSING',
51
+ message: 'The active task needs one Verification line whose command does not contain < or >.',
52
+ trigger: 'sdd_complete_task',
53
+ },
54
+ };
55
+ }
56
+ export function verificationFailed(run) {
57
+ const exitCode = run.exitCode ?? 1;
58
+ return {
59
+ success: false,
60
+ error: {
61
+ code: 'ERR_VERIFICATION_FAILED',
62
+ message: `Verification command exited ${String(exitCode)}.`,
63
+ trigger: 'sdd_complete_task',
64
+ details: {
65
+ reason: run.cancelled ? 'cancelled' : run.timedOut ? 'timeout' : 'failed',
66
+ exitCode,
67
+ outputTail: run.output.slice(-2000),
68
+ cleanupComplete: run.cleanupComplete,
69
+ },
70
+ },
71
+ };
72
+ }
73
+ export function unsupportedVerificationPlatform() {
74
+ return {
75
+ success: false,
76
+ error: {
77
+ code: 'ERR_VERIFICATION_FAILED',
78
+ message: 'Automatic task verification currently requires local macOS or Linux for owned process-tree cleanup. Planning and read-only tools remain available.',
79
+ trigger: 'sdd_complete_task',
80
+ details: {
81
+ reason: 'failed',
82
+ platform: process.platform,
83
+ verificationSupported: false,
84
+ },
85
+ },
86
+ };
87
+ }
88
+ export function scopedPathMismatch() {
89
+ return {
90
+ success: false,
91
+ error: {
92
+ code: 'ERR_WORKSPACE_UNRESOLVED',
93
+ message: 'Scoped verification path does not match its trusted policy.',
94
+ trigger: 'sdd_complete_task',
95
+ details: { reason: 'verification_policy_workspace_mismatch' },
96
+ },
97
+ };
98
+ }
99
+ export function taskFileMissing(tasksFilePath) {
100
+ return {
101
+ success: false,
102
+ error: {
103
+ code: 'ERR_TASK_NOT_FOUND',
104
+ message: `File tasks.md not found at: '${tasksFilePath}'.`,
105
+ trigger: 'sdd_get_active_task',
106
+ },
107
+ };
108
+ }
109
+ export function catalogueReadFailure(error, id) {
110
+ return {
111
+ success: false,
112
+ error: {
113
+ code: error instanceof CompletionGuardError ? error.code : 'ERR_INVALID_ARTIFACT',
114
+ message: error instanceof CompletionGuardError
115
+ ? error.message
116
+ : 'Could not read the complete feature catalogue.',
117
+ trigger: 'sdd_list_features',
118
+ details: {
119
+ entry: id,
120
+ ...(error instanceof CompletionGuardError ? { reason: error.reason } : {}),
121
+ },
122
+ },
123
+ };
124
+ }
125
+ //# sourceMappingURL=task-failures.js.map
@@ -1,18 +1,24 @@
1
- import type { ActiveTaskResult, CompleteTaskResult, SddResult } from '../types/sdd-engine.js';
1
+ import type { ActiveTaskResult, CompleteTaskResult, FeatureSummary, SddResult } from '../types/sdd-engine.js';
2
2
  import type { VerificationPolicy } from '../types/verification.js';
3
3
  export declare class TaskWindowManager {
4
4
  private readonly scopedPolicy;
5
5
  private readonly scoped;
6
+ private readonly shutdownController;
7
+ private readonly pending;
6
8
  constructor(policy?: VerificationPolicy);
7
9
  shutdown(): Promise<void>;
8
10
  private activeTaskFromContent;
9
11
  private selectScopedTask;
10
12
  private commitScopedTask;
11
13
  getActiveTask(tasksFilePath: string): Promise<SddResult<ActiveTaskResult>>;
12
- private buildActiveTaskResult;
13
- private parseTasks;
14
- private extractTaskId;
14
+ getCatalogueEntry(featDir: string): Promise<SddResult<FeatureSummary>>;
15
15
  completeTask(tasksFilePath: string, taskId: string, workspaceRoot: string, _verificationOutput: string, signal?: AbortSignal): Promise<SddResult<CompleteTaskResult>>;
16
+ private completeOwned;
17
+ private checkScopedPaths;
18
+ private attemptScopedCompletion;
19
+ private commitOwnedScopedTask;
20
+ private completeOrdinary;
21
+ private commitOrdinary;
16
22
  }
17
23
  export declare function verificationCommand(taskMarkdown: string): string | null;
18
24
  //# sourceMappingURL=task-window.d.ts.map
@@ -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