@planu/cli 8.2.15 → 8.2.17

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,18 @@
1
+ ## [8.2.17] - 2026-10-23
2
+
3
+ - guide planning toward one observable increment, reused contracts and executable task gates that can advance from RED to GREEN
4
+ - preserve meaningful tests and distinguish scoped static assertion review from implementation and release acceptance
5
+ - regenerate the nine known mirrors when an existing real .sdd/skills directory is initialized; reject unsafe init paths and preserve feature history
6
+ - retain paired skill-evaluation inputs, raw transcripts, process outcomes and independent evidence-cited quality reviews, including failed attempts
7
+ - keep the nine MCP tools, public schemas, dependencies, protected roots, locks, task order and verification controls unchanged
8
+
9
+ ## [8.2.16] - 2026-10-22
10
+
11
+ - reject a MODIFY patch unless its search text occurs exactly once
12
+ - keep reads inside the real workspace and return a capped JSON slice
13
+ - return the active-task card, name missing lock sections, and cap verification failures
14
+ - stop copying the parent process environment into the verification shell
15
+
1
16
  ## [8.2.15] - 2026-10-22
2
17
 
3
18
  - state that Planu does not upload the project, that npx contacts the npm registry, and that the source is not published
package/README.md CHANGED
@@ -177,7 +177,7 @@ MCP:
177
177
  node dist/sdd-engine/cli.js
178
178
  ```
179
179
 
180
- `pnpm eval:skills` is an operator-only eval of the spec-architect and spec-executor skills. Executor cases (`"skill": "executor"`) ship a locked trinity and fail on unchecked tasks, edits outside the File Manifest, or failing `checks`. It spends API budget by shelling out to the local `claude` CLI against a throwaway workspace, so it is not part of `pnpm check` and never runs in CI.
180
+ `pnpm eval:skills` evaluates planning, execution and test-integrity review in synthetic workspaces through the local `claude` CLI. Existing executor cases retain locked-task, File Manifest and check enforcement. The repository guide `docs/skill-quality-evaluation.md` defines the explicit paired operator protocol: eight subjects per reviewed attempt, frozen inputs, retained success/failure evidence and a separate independent quality assessment. These provider-spending evaluations require an operator launch; they are outside `pnpm check` and CI. Structural success and a scoped review do not certify production behavior.
181
181
 
182
182
  ---
183
183
 
@@ -194,7 +194,7 @@ See the [Planu Proprietary Free-Use License](LICENSE) and [planu.dev/license](ht
194
194
  "mcpServers": {
195
195
  "planu": {
196
196
  "command": "npx",
197
- "args": ["-y", "@planu/cli@8.2.15"],
197
+ "args": ["-y", "@planu/cli@8.2.17"],
198
198
  "cwd": ".",
199
199
  "env": {
200
200
  "PLANU_WORKSPACE": "."
@@ -78,6 +78,6 @@ export declare const ApplyFilePatchInputSchema: z.ZodObject<{
78
78
  export declare const CompleteTaskInputSchema: z.ZodObject<{
79
79
  feature_id: z.ZodString;
80
80
  task_id: z.ZodString;
81
- verification_output: z.ZodString;
81
+ verification_output: z.ZodOptional<z.ZodString>;
82
82
  }, z.core.$strip>;
83
83
  //# sourceMappingURL=contracts.d.ts.map
@@ -61,6 +61,6 @@ export const ApplyFilePatchInputSchema = z.object({
61
61
  export const CompleteTaskInputSchema = z.object({
62
62
  feature_id: FeatureIdSchema,
63
63
  task_id: z.string().min(1),
64
- verification_output: z.string().min(1),
64
+ verification_output: z.string().min(1).optional(),
65
65
  });
66
66
  //# sourceMappingURL=contracts.js.map
@@ -1,4 +1,4 @@
1
- import type { ErrorCode, LockIntegrityResult, ParsedManifest } from '../types/sdd-engine.js';
1
+ import type { ErrorCode, FilePermission, LockIntegrityResult, ParsedManifest } from '../types/sdd-engine.js';
2
2
  export declare function hashArtifact(content: string): string;
3
3
  export declare function verifyLockedTrinity(featDir: string): Promise<LockIntegrityResult>;
4
4
  export declare function parseManifestContent(content: string): ParsedManifest;
@@ -13,5 +13,17 @@ export declare function writeLockedTrinity(featDir: string, featureId: string, r
13
13
  ok: false;
14
14
  code: ErrorCode;
15
15
  message: string;
16
+ details?: {
17
+ missing: string[];
18
+ };
16
19
  }>;
20
+ export declare function executionCard(featDir: string): Promise<{
21
+ locked: boolean;
22
+ trinity: 'ready' | 'unlocked' | 'drift';
23
+ manifest: {
24
+ path: string;
25
+ permission: FilePermission;
26
+ }[];
27
+ }>;
28
+ export declare function scopedVerificationEnvironment(): NodeJS.ProcessEnv;
17
29
  //# sourceMappingURL=lock-integrity.d.ts.map
@@ -7,12 +7,27 @@ export function hashArtifact(content) {
7
7
  return createHash('sha256').update(content).digest('hex');
8
8
  }
9
9
  function assessTrinityCompleteness(specContent, planContent, tasksContent) {
10
- const specOk = hasHeading(specContent, 'Out-of-Scope') &&
11
- hasHeading(specContent, 'Error Matrix') &&
12
- BDD_KEYWORDS.every((keyword) => keyword.test(specContent));
13
- const planOk = hasHeading(planContent, 'Frozen Dependencies') && hasHeading(planContent, 'File Manifest');
10
+ const missing = [];
11
+ if (!hasHeading(specContent, 'Out-of-Scope')) {
12
+ missing.push('out_of_scope');
13
+ }
14
+ if (!hasHeading(specContent, 'Error Matrix')) {
15
+ missing.push('error_matrix');
16
+ }
17
+ if (!BDD_KEYWORDS.every((keyword) => keyword.test(specContent))) {
18
+ missing.push('bdd');
19
+ }
20
+ if (!hasHeading(planContent, 'Frozen Dependencies')) {
21
+ missing.push('frozen_dependencies');
22
+ }
14
23
  const hasTask = tasksContent.split('\n').some((line) => CHECKBOX_TASK.test(line.trim()));
15
24
  const manifest = scanManifest(planContent);
25
+ if (!manifest.hasPath) {
26
+ missing.push('manifest_path');
27
+ }
28
+ if (!hasTask) {
29
+ missing.push('checkbox_task');
30
+ }
16
31
  if (manifest.globDelete) {
17
32
  return {
18
33
  ok: false,
@@ -27,13 +42,14 @@ function assessTrinityCompleteness(specContent, planContent, tasksContent) {
27
42
  message: `File Manifest cannot grant writes on protected root path '${manifest.protectedWrite}' (.sdd, .git, planu/specs).`,
28
43
  };
29
44
  }
30
- if (specOk && planOk && hasTask && manifest.hasPath) {
45
+ if (missing.length === 0) {
31
46
  return { ok: true };
32
47
  }
33
48
  return {
34
49
  ok: false,
35
50
  code: 'ERR_TRINITY_INCOMPLETE',
36
51
  message: 'Lock requires Out-of-Scope, Error Matrix, GIVEN/WHEN/THEN acceptance criteria, Frozen Dependencies, a File Manifest path, and at least one checkbox task.',
52
+ details: { missing },
37
53
  };
38
54
  }
39
55
  export async function verifyLockedTrinity(featDir) {
@@ -80,25 +96,30 @@ export async function verifyLockedTrinity(featDir) {
80
96
  message: 'Locked spec.md or plan.md changed after sdd_lock_spec. Re-lock is required.',
81
97
  };
82
98
  }
83
- if (lock.tasksHash) {
84
- let tasksContent;
85
- try {
86
- tasksContent = await fs.readFile(path.join(featDir, 'tasks.md'), 'utf-8');
87
- }
88
- catch {
89
- return {
90
- ok: false,
91
- code: 'ERR_SPEC_DRIFT',
92
- message: 'Locked tasks.md is missing after sdd_lock_spec. Re-lock is required.',
93
- };
94
- }
95
- if (hashArtifact(tasksContent) !== lock.tasksHash) {
96
- return {
97
- ok: false,
98
- code: 'ERR_SPEC_DRIFT',
99
- message: 'Locked tasks.md changed after sdd_lock_spec. Re-lock is required.',
100
- };
101
- }
99
+ if (!lock.tasksHash) {
100
+ return {
101
+ ok: false,
102
+ code: 'ERR_SPEC_DRIFT',
103
+ message: 'Locked tasks.md hash is missing after sdd_lock_spec. Re-lock is required.',
104
+ };
105
+ }
106
+ let tasksContent;
107
+ try {
108
+ tasksContent = await fs.readFile(path.join(featDir, 'tasks.md'), 'utf-8');
109
+ }
110
+ catch {
111
+ return {
112
+ ok: false,
113
+ code: 'ERR_SPEC_DRIFT',
114
+ message: 'Locked tasks.md is missing after sdd_lock_spec. Re-lock is required.',
115
+ };
116
+ }
117
+ if (hashArtifact(tasksContent) !== lock.tasksHash) {
118
+ return {
119
+ ok: false,
120
+ code: 'ERR_SPEC_DRIFT',
121
+ message: 'Locked tasks.md changed after sdd_lock_spec. Re-lock is required.',
122
+ };
102
123
  }
103
124
  return { ok: true };
104
125
  }
@@ -209,7 +230,12 @@ async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, re
209
230
  }
210
231
  const completeness = assessTrinityCompleteness(specContent, planContent, tasksContent);
211
232
  if (!completeness.ok) {
212
- return { ok: false, code: completeness.code, message: completeness.message };
233
+ return {
234
+ ok: false,
235
+ code: completeness.code,
236
+ message: completeness.message,
237
+ ...(completeness.details ? { details: completeness.details } : {}),
238
+ };
213
239
  }
214
240
  let previous;
215
241
  if (lockExists) {
@@ -244,4 +270,28 @@ async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, re
244
270
  await fs.writeFile(lockPath, JSON.stringify(lockFile, null, 2), 'utf-8');
245
271
  return { ok: true, specHash, planHash, tasksHash, relocked: relock };
246
272
  }
273
+ export async function executionCard(featDir) {
274
+ const plan = await fs.readFile(path.join(featDir, 'plan.md'), 'utf8').catch(() => '');
275
+ const entries = [...parseManifestContent(plan).allowedFiles.entries()];
276
+ const manifest = entries.map(([filePath, permission]) => ({ path: filePath, permission }));
277
+ const integrity = await verifyLockedTrinity(featDir);
278
+ if (integrity.ok) {
279
+ return { locked: true, trinity: 'ready', manifest };
280
+ }
281
+ if (integrity.code === 'ERR_SPEC_NOT_LOCKED') {
282
+ return { locked: false, trinity: 'unlocked', manifest };
283
+ }
284
+ return { locked: true, trinity: 'drift', manifest };
285
+ }
286
+ export function scopedVerificationEnvironment() {
287
+ const env = {};
288
+ const names = 'PATH,HOME,TMPDIR,TMP,TEMP,LANG,LC_ALL,LC_CTYPE,SystemRoot,ComSpec,PATHEXT';
289
+ for (const key of names.split(',')) {
290
+ const value = process.env[key];
291
+ if (value !== undefined) {
292
+ env[key] = value;
293
+ }
294
+ }
295
+ return env;
296
+ }
247
297
  //# sourceMappingURL=lock-integrity.js.map
@@ -90,9 +90,9 @@ export class PatchSandbox {
90
90
  const sddRoot = path.resolve(workspacePath, '.sdd');
91
91
  const gitRoot = path.resolve(workspacePath, '.git');
92
92
  const legacySpecsRoot = path.resolve(workspacePath, 'planu', 'specs');
93
- if (isSddEnginePath(normalizedTarget) ||
94
- isGitPath(normalizedTarget) ||
95
- isLegacySpecsPath(normalizedTarget) ||
93
+ if (isProtectedPrefix(normalizedTarget, '.sdd') ||
94
+ isProtectedPrefix(normalizedTarget, '.git') ||
95
+ isProtectedPrefix(normalizedTarget, 'planu/specs') ||
96
96
  this.isWithin(sddRoot, fullPath) ||
97
97
  this.isWithin(gitRoot, fullPath) ||
98
98
  this.isWithin(legacySpecsRoot, fullPath)) {
@@ -238,19 +238,19 @@ export class PatchSandbox {
238
238
  },
239
239
  };
240
240
  }
241
- if (searchContent && !existingContent.includes(searchContent)) {
241
+ const matchCount = countOccurrences(existingContent, searchContent);
242
+ if (matchCount !== 1) {
242
243
  return {
243
244
  success: false,
244
245
  error: {
245
246
  code: 'ERR_PATCH_FAILED',
246
- message: `Exact 'search_content' block was not found in '${normalizedTarget}'.`,
247
+ message: `MODIFY search_content must occur exactly once in '${normalizedTarget}'.`,
247
248
  trigger: 'sdd_apply_file_patch',
249
+ details: { matchCount, requestedPath: normalizedTarget },
248
250
  },
249
251
  };
250
252
  }
251
- const updatedContent = searchContent
252
- ? existingContent.replace(searchContent, () => replaceContent)
253
- : replaceContent;
253
+ const updatedContent = existingContent.replace(searchContent, () => replaceContent);
254
254
  try {
255
255
  await fs.writeFile(fullPath, updatedContent, 'utf-8');
256
256
  return {
@@ -303,17 +303,25 @@ function globMatches(pattern, target) {
303
303
  }
304
304
  return new RegExp(`^${globPatternToRegExpSource(posixPattern)}$`).test(posixTarget);
305
305
  }
306
- function isSddEnginePath(relativePath) {
306
+ function isProtectedPrefix(relativePath, root) {
307
307
  const posix = toPosixPath(relativePath);
308
- return posix === '.sdd' || posix.startsWith('.sdd/');
308
+ return posix === root || posix.startsWith(`${root}/`);
309
309
  }
310
- function isGitPath(relativePath) {
311
- const posix = toPosixPath(relativePath);
312
- return posix === '.git' || posix.startsWith('.git/');
313
- }
314
- function isLegacySpecsPath(relativePath) {
315
- const posix = toPosixPath(relativePath);
316
- return posix === 'planu/specs' || posix.startsWith('planu/specs/');
310
+ function countOccurrences(haystack, needle) {
311
+ if (needle.length === 0) {
312
+ return 0;
313
+ }
314
+ let count = 0;
315
+ let from = 0;
316
+ while (from <= haystack.length) {
317
+ const at = haystack.indexOf(needle, from);
318
+ if (at < 0) {
319
+ return count;
320
+ }
321
+ count += 1;
322
+ from = at + needle.length;
323
+ }
324
+ return count;
317
325
  }
318
326
  function globPatternToRegExpSource(pattern) {
319
327
  let source = '';
@@ -3,7 +3,8 @@ import * as fs from 'node:fs/promises';
3
3
  import * as path from 'node:path';
4
4
  import { ScopedVerificationCoordinator } from './verification-runner.js';
5
5
  import { persistScopedCompletionFiles, scopedVerificationEnvironment, } from './verification-policy.js';
6
- import { hashArtifact } from './lock-integrity.js';
6
+ import { executionCard, hashArtifact } from './lock-integrity.js';
7
+ const UNLOCKED_CARD = { locked: false, trinity: 'unlocked', manifest: [] };
7
8
  export class TaskWindowManager {
8
9
  scopedPolicy;
9
10
  scoped;
@@ -64,19 +65,24 @@ export class TaskWindowManager {
64
65
  },
65
66
  };
66
67
  }
67
- return this.activeTaskFromContent(content);
68
+ const built = this.activeTaskFromContent(content);
69
+ if (!built.success) {
70
+ return built;
71
+ }
72
+ const card = await executionCard(path.dirname(tasksFilePath));
73
+ return { success: true, data: { ...built.data, ...card } };
68
74
  }
69
75
  buildActiveTaskResult(acc) {
70
76
  if (acc.totalTasks === 0) {
71
77
  return {
72
78
  success: true,
73
- data: { activeTask: null, allCompleted: false, status: 'NO_TASKS' },
79
+ data: { activeTask: null, allCompleted: false, status: 'NO_TASKS', ...UNLOCKED_CARD },
74
80
  };
75
81
  }
76
82
  if (acc.activeTaskIndex === -1 || acc.completedTasks === acc.totalTasks) {
77
83
  return {
78
84
  success: true,
79
- data: { activeTask: null, allCompleted: true, status: 'ALL_COMPLETED' },
85
+ data: { activeTask: null, allCompleted: true, status: 'ALL_COMPLETED', ...UNLOCKED_CARD },
80
86
  };
81
87
  }
82
88
  return {
@@ -86,12 +92,14 @@ export class TaskWindowManager {
86
92
  taskId: acc.activeTaskId,
87
93
  taskTitle: acc.activeTaskTitle,
88
94
  fullTaskMarkdown: acc.activeTaskLines.join('\n').trim(),
95
+ verificationCommand: verificationCommand(acc.activeTaskLines.join('\n')),
89
96
  taskIndex: acc.activeTaskIndex,
90
97
  totalTasks: acc.totalTasks,
91
98
  completedTasks: acc.completedTasks,
92
99
  },
93
100
  allCompleted: false,
94
101
  status: 'IN_PROGRESS',
102
+ ...UNLOCKED_CARD,
95
103
  },
96
104
  };
97
105
  }
@@ -176,7 +184,7 @@ export class TaskWindowManager {
176
184
  if (command === null) {
177
185
  return verificationMissing();
178
186
  }
179
- const run = await runVerification(workspaceRoot, command, this.scopedPolicy ? scopedVerificationEnvironment() : undefined);
187
+ const run = await runVerification(workspaceRoot, command, scopedVerificationEnvironment());
180
188
  if (!run.ok) {
181
189
  return verificationFailed(run);
182
190
  }
@@ -240,13 +248,14 @@ function verificationMissing() {
240
248
  };
241
249
  }
242
250
  function verificationFailed(run) {
251
+ const exitCode = run.exitCode ?? 1;
243
252
  return {
244
253
  success: false,
245
254
  error: {
246
255
  code: 'ERR_VERIFICATION_FAILED',
247
- message: run.output.trim() || `Verification command exited ${String(run.exitCode)}.`,
256
+ message: `Verification command exited ${String(exitCode)}.`,
248
257
  trigger: 'sdd_complete_task',
249
- details: { exitCode: run.exitCode },
258
+ details: { exitCode, outputTail: run.output.slice(-2000) },
250
259
  },
251
260
  };
252
261
  }
@@ -2,5 +2,16 @@ import type { VerificationPolicy } from '../../types/verification.js';
2
2
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import { TaskWindowManager } from '../task-window.js';
4
4
  import type { SddWorkspaceHandle } from '../../types/sdd-engine.js';
5
+ export declare function sliceNumberedSource(fileData: string, startLine: number, endLine: number): {
6
+ ok: true;
7
+ totalLines: number;
8
+ startLine: number;
9
+ endLine: number;
10
+ truncated: boolean;
11
+ text: string;
12
+ } | {
13
+ ok: false;
14
+ totalLines: number;
15
+ };
5
16
  export declare function registerExecutionTools(server: McpServer, workspace: SddWorkspaceHandle, policy?: VerificationPolicy): TaskWindowManager;
6
17
  //# sourceMappingURL=execution-tools.d.ts.map
@@ -1,11 +1,38 @@
1
- import * as fs from 'node:fs/promises';
2
1
  import * as path from 'node:path';
3
2
  import { ReadSpecArtifactInputSchema, ReadFileSliceInputSchema, GetActiveTaskInputSchema, ApplyFilePatchInputSchema, CompleteTaskInputSchema, } from '../contracts.js';
4
3
  import { PatchSandbox } from '../patch-sandbox.js';
5
4
  import { TaskWindowManager } from '../task-window.js';
6
5
  import { formatResult } from './format-result.js';
7
6
  import { verifyLockedTrinity } from '../lock-integrity.js';
8
- import { homeFallbackFailure } from '../workspace-root.js';
7
+ import { homeFallbackFailure, readTextInsideWorkspace } from '../workspace-root.js';
8
+ const SLICE_LINE_CAP = 200;
9
+ function sourceLines(fileData) {
10
+ if (fileData.length === 0) {
11
+ return [];
12
+ }
13
+ const parts = fileData.split('\n');
14
+ if (fileData.endsWith('\n')) {
15
+ parts.pop();
16
+ }
17
+ return parts;
18
+ }
19
+ export function sliceNumberedSource(fileData, startLine, endLine) {
20
+ const lines = sourceLines(fileData);
21
+ if (startLine > lines.length) {
22
+ return { ok: false, totalLines: lines.length };
23
+ }
24
+ const requestedEnd = Math.min(endLine, lines.length);
25
+ const cappedEnd = Math.min(requestedEnd, startLine + SLICE_LINE_CAP - 1);
26
+ const slice = lines.slice(startLine - 1, cappedEnd);
27
+ return {
28
+ ok: true,
29
+ totalLines: lines.length,
30
+ startLine,
31
+ endLine: cappedEnd,
32
+ truncated: cappedEnd < requestedEnd,
33
+ text: slice.map((content, index) => `${startLine + index}: ${content}`).join('\n'),
34
+ };
35
+ }
9
36
  export function registerExecutionTools(server, workspace, policy) {
10
37
  const taskWindow = new TaskWindowManager(policy);
11
38
  registerReadArtifactTool(server, workspace);
@@ -27,20 +54,20 @@ function registerReadArtifactTool(server, workspace) {
27
54
  return formatResult(homeError);
28
55
  }
29
56
  const targetPath = path.join(resolved.sddDir, 'features', args.feature_id, `${args.artifact}.md`);
30
- try {
31
- const text = await fs.readFile(targetPath, 'utf-8');
32
- return { content: [{ type: 'text', text }] };
33
- }
34
- catch {
57
+ const read = await readTextInsideWorkspace(resolved.workspaceRoot, targetPath);
58
+ if (!read.ok) {
35
59
  return formatResult({
36
60
  success: false,
37
61
  error: {
38
- code: 'ERR_INVALID_ARTIFACT',
39
- message: `Could not read '${args.artifact}.md' for feature '${args.feature_id}'.`,
62
+ code: read.reason === 'outside' ? 'ERR_PERMISSION_VIOLATION' : 'ERR_INVALID_ARTIFACT',
63
+ message: read.reason === 'outside'
64
+ ? 'Access denied outside workspace boundaries.'
65
+ : `Could not read '${args.artifact}.md' for feature '${args.feature_id}'.`,
40
66
  trigger: 'sdd_read_spec_artifact',
41
67
  },
42
68
  });
43
69
  }
70
+ return { content: [{ type: 'text', text: read.text }] };
44
71
  });
45
72
  }
46
73
  function registerReadFileSliceTool(server, workspace) {
@@ -105,51 +132,56 @@ function registerCompleteTaskTool(server, workspace, taskWindow) {
105
132
  return lockError;
106
133
  }
107
134
  const tasksPath = path.join(featDir, 'tasks.md');
108
- const result = await taskWindow.completeTask(tasksPath, args.task_id, resolved.workspaceRoot, args.verification_output, extra.signal);
135
+ const result = await taskWindow.completeTask(tasksPath, args.task_id, resolved.workspaceRoot, args.verification_output ?? '', extra.signal);
109
136
  return formatResult(result);
110
137
  });
111
138
  }
112
139
  async function executeReadFileSlice(workspaceRoot, relPath, startLine, endLine) {
113
- const targetFullPath = path.resolve(workspaceRoot, path.normalize(relPath));
114
- if (!targetFullPath.startsWith(path.resolve(workspaceRoot))) {
140
+ if (startLine > endLine || startLine < 1) {
115
141
  return formatResult({
116
142
  success: false,
117
143
  error: {
118
- code: 'ERR_PERMISSION_VIOLATION',
119
- message: 'Access denied outside workspace boundaries.',
144
+ code: 'ERR_INVALID_SLICE',
145
+ message: `Invalid line range: ${startLine} to ${endLine}.`,
120
146
  trigger: 'sdd_read_file_slice',
121
147
  },
122
148
  });
123
149
  }
124
- if (startLine > endLine || startLine < 1) {
150
+ const read = await readTextInsideWorkspace(workspaceRoot, path.resolve(workspaceRoot, path.normalize(relPath)));
151
+ if (!read.ok) {
125
152
  return formatResult({
126
153
  success: false,
127
154
  error: {
128
- code: 'ERR_INVALID_SLICE',
129
- message: `Invalid line range: ${startLine} to ${endLine}.`,
155
+ code: read.reason === 'outside' ? 'ERR_PERMISSION_VIOLATION' : 'ERR_INVALID_SLICE',
156
+ message: read.reason === 'outside'
157
+ ? 'Access denied outside workspace boundaries.'
158
+ : `Failed to read '${relPath}'.`,
130
159
  trigger: 'sdd_read_file_slice',
131
160
  },
132
161
  });
133
162
  }
134
- try {
135
- const fileData = await fs.readFile(targetFullPath, 'utf-8');
136
- const lines = fileData.split('\n');
137
- const effectiveStart = Math.min(startLine, lines.length);
138
- const effectiveEnd = Math.min(endLine, lines.length);
139
- const sliceLines = lines.slice(effectiveStart - 1, effectiveEnd);
140
- const text = sliceLines.map((content, idx) => `${effectiveStart + idx}: ${content}`).join('\n');
141
- return { content: [{ type: 'text', text }] };
142
- }
143
- catch (err) {
163
+ const sliced = sliceNumberedSource(read.text, startLine, endLine);
164
+ if (!sliced.ok) {
144
165
  return formatResult({
145
166
  success: false,
146
167
  error: {
147
168
  code: 'ERR_INVALID_SLICE',
148
- message: `Failed to read '${relPath}': ${err instanceof Error ? err.message : String(err)}`,
169
+ message: `Invalid line range: ${startLine} to ${endLine}.`,
149
170
  trigger: 'sdd_read_file_slice',
171
+ details: { totalLines: sliced.totalLines },
150
172
  },
151
173
  });
152
174
  }
175
+ return formatResult({
176
+ success: true,
177
+ data: {
178
+ totalLines: sliced.totalLines,
179
+ startLine: sliced.startLine,
180
+ endLine: sliced.endLine,
181
+ truncated: sliced.truncated,
182
+ text: sliced.text,
183
+ },
184
+ });
153
185
  }
154
186
  async function requireLockedTrinity(featDir, trigger) {
155
187
  const lockCheck = await verifyLockedTrinity(featDir);
@@ -5,6 +5,7 @@ import { InitWorkspaceInputSchema, ListFeaturesInputSchema, CreateFeatureInputSc
5
5
  import { TaskWindowManager } from '../task-window.js';
6
6
  import { formatResult } from './format-result.js';
7
7
  import { homeFallbackFailure } from '../workspace-root.js';
8
+ import { prepareProjectInitialization } from '../workspace-init.js';
8
9
  import { writeLockedTrinity } from '../lock-integrity.js';
9
10
  import { copyGlobalRules, installCursorGuard, installHostRulePack, installHostSkillPack, } from '../host-rule-pack.js';
10
11
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
@@ -45,7 +46,11 @@ function registerInitTool(server, workspace) {
45
46
  : resolved.sddDir;
46
47
  const featuresDir = path.join(targetBase, 'features');
47
48
  const skillsDir = path.join(targetBase, 'skills');
49
+ const refreshMirrors = args.scope === 'project'
50
+ ? await prepareProjectInitialization(resolved.workspaceRoot)
51
+ : undefined;
48
52
  await fs.mkdir(featuresDir, { recursive: true });
53
+ await refreshMirrors?.();
49
54
  if (args.scope === 'global') {
50
55
  await fs.mkdir(skillsDir, { recursive: true });
51
56
  await copySkillTemplates(skillsDir);
@@ -249,7 +254,7 @@ async function collectFeatures(featuresDir, taskWindow, statusFilter) {
249
254
  try {
250
255
  const entries = await fs.readdir(featuresDir, { withFileTypes: true });
251
256
  for (const entry of entries) {
252
- if (!entry.isDirectory()) {
257
+ if (!entry.isDirectory() || !/^FEAT[-_][A-Z0-9_-]+$/u.test(entry.name)) {
253
258
  continue;
254
259
  }
255
260
  const featId = entry.name;
@@ -259,13 +264,17 @@ async function collectFeatures(featuresDir, taskWindow, statusFilter) {
259
264
  .then(() => true)
260
265
  .catch(() => false);
261
266
  let status = 'planning';
267
+ let activeTaskId = null;
268
+ const tasksPath = path.join(featPath, 'tasks.md');
269
+ const taskRes = await taskWindow.getActiveTask(tasksPath);
262
270
  if (lockExists) {
263
- const tasksPath = path.join(featPath, 'tasks.md');
264
- const taskRes = await taskWindow.getActiveTask(tasksPath);
265
271
  status = taskRes.success && taskRes.data.allCompleted ? 'done' : 'executing';
266
272
  }
273
+ if (taskRes.success) {
274
+ activeTaskId = taskRes.data.activeTask?.taskId ?? null;
275
+ }
267
276
  if (!statusFilter || statusFilter === 'all' || statusFilter === status) {
268
- result.push({ id: featId, status, locked: lockExists });
277
+ result.push({ id: featId, status, locked: lockExists, activeTaskId });
269
278
  }
270
279
  }
271
280
  }
@@ -275,9 +284,9 @@ async function collectFeatures(featuresDir, taskWindow, statusFilter) {
275
284
  return result;
276
285
  }
277
286
  async function writeFeatureArtifacts(featDir, id, title) {
278
- const initialSpec = `# Spec: ${title}\nFeature ID: ${id}\n\n## 1. Out-of-Scope (Mandatory)\n- Explicitly list all modules, dependencies, and behaviors strictly forbidden from being modified.\n\n## 2. Contracts & Data Models\n- Define strict types, interfaces, structs, or schemas using the project's native programming language. Zero loose types.\n\n## 3. Error Matrix\n| Trigger | Condition | Error Code | Status / Payload |\n|---|---|---|---|\n| Invalid input | Missing required field | ERR_INVALID_INPUT | 400 Bad Request |\n`;
279
- const initialPlan = `# Plan: ${title}\nFeature ID: ${id}\n\n## Frozen Dependencies\n- (Frozen dependencies: zero new packages or dependencies allowed without architectural authorization)\n\n## File Manifest\n- CREATE: \n- MODIFY: \n- READ_ONLY: \n- DELETE: \n`;
280
- const initialTasks = `# Tasks: ${title}\nFeature ID: ${id}\n\n- [ ] TASK-1: Define core data structures and initial contracts\n Verification: <executable test command>\n`;
287
+ const initialSpec = `# Spec: ${title}\nFeature ID: ${id}\n\n## Observable Outcome\n- Select the smallest useful user outcome and explain its observable demonstration.\n\n## Acceptance Behavior\n- Replace these instructions with concrete executable acceptance scenarios for the selected outcome. This scaffold is not ready to lock.\n\n## Out-of-Scope (Mandatory)\n- Explicitly list excluded modules, dependencies, behaviors and deferred user outcomes.\n\n## Contracts & Data Models\n- Reuse existing contracts by exact source reference. Define strict types only for affected boundaries; explain when no contract changes are needed.\n\n## Error Matrix\n| Trigger | Condition | Error Code | Status / Payload |\n|---|---|---|---|\n| Describe applicable trigger | Describe condition | Reuse or define the affected error | State observable behavior |\n`;
288
+ const initialPlan = `# Plan: ${title}\nFeature ID: ${id}\n\n## Increment Design\n- Identify only the necessary layers and existing components for the selected outcome.\n- Justify any new abstraction or foundational step against a current requirement; describe the first usable result.\n\n## Frozen Dependencies\n- (Frozen dependencies: zero new packages or dependencies allowed without architectural authorization)\n\n## File Manifest\n- CREATE: \n- MODIFY: \n- READ_ONLY: \n- DELETE: \n`;
289
+ const initialTasks = `# Tasks: ${title}\nFeature ID: ${id}\n\n- [ ] TASK-1: Deliver the first useful increment with an observable demonstration\n Verification: <executable test command>\n`;
281
290
  await fs.writeFile(path.join(featDir, 'spec.md'), initialSpec, 'utf-8');
282
291
  await fs.writeFile(path.join(featDir, 'plan.md'), initialPlan, 'utf-8');
283
292
  await fs.writeFile(path.join(featDir, 'tasks.md'), initialTasks, 'utf-8');
@@ -287,7 +296,12 @@ async function executeLockSpec(featDir, featureId, relock, reason) {
287
296
  if (!outcome.ok) {
288
297
  return formatResult({
289
298
  success: false,
290
- error: { code: outcome.code, message: outcome.message, trigger: 'sdd_lock_spec' },
299
+ error: {
300
+ code: outcome.code,
301
+ message: outcome.message,
302
+ trigger: 'sdd_lock_spec',
303
+ ...(outcome.details ? { details: outcome.details } : {}),
304
+ },
291
305
  });
292
306
  }
293
307
  return formatResult({
@@ -10,7 +10,7 @@ export declare function revalidateScopedVerificationSnapshot(policy: ScopedPolic
10
10
  export declare function uncertainCompletion(): SddFailure;
11
11
  export declare function persistScopedCompletionFiles(policy: ScopedPolicy, snapshot: ScopedVerificationSnapshot, writtenTasks: string, signal: AbortSignal): Promise<SddResult<null>>;
12
12
  export declare function scopedFeaturePathFailure(policy: ScopedPolicy): Promise<SddFailure | null>;
13
- export declare function scopedVerificationEnvironment(): NodeJS.ProcessEnv;
13
+ export { scopedVerificationEnvironment } from './lock-integrity.js';
14
14
  export declare function scopedFailure(details: Record<string, unknown>): SddFailure;
15
15
  export declare function cancelledVerification(signal: AbortSignal): SddFailure | null;
16
16
  //# sourceMappingURL=verification-policy.d.ts.map
@@ -312,11 +312,7 @@ export async function scopedFeaturePathFailure(policy) {
312
312
  return snapshotFailure(true);
313
313
  }
314
314
  }
315
- export function scopedVerificationEnvironment() {
316
- const env = { ...process.env };
317
- delete env.PLANU_VERIFICATION_TIMEOUT_POLICY;
318
- return env;
319
- }
315
+ export { scopedVerificationEnvironment } from './lock-integrity.js';
320
316
  export function scopedFailure(details) {
321
317
  return {
322
318
  success: false,
@@ -0,0 +1,3 @@
1
+ /** Validate the complete project init write set before the caller writes anything. */
2
+ export declare function prepareProjectInitialization(workspaceRoot: string): Promise<() => Promise<void>>;
3
+ //# sourceMappingURL=workspace-init.d.ts.map
@@ -0,0 +1,197 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import * as path from 'node:path';
5
+ const SKILL_NAMES = [
6
+ 'git-janitor',
7
+ 'legacy-sunset',
8
+ 'lib-sync',
9
+ 'preflight-guardian',
10
+ 'reconciler',
11
+ 'spec-architect',
12
+ 'spec-executor',
13
+ 'verification-auditor',
14
+ 'visual-release-auditor',
15
+ ];
16
+ function missing(error) {
17
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT';
18
+ }
19
+ function unsafe(relative, code = 'EINVAL') {
20
+ return Object.assign(new Error(`Unsafe initialization path: ${relative}`), { code });
21
+ }
22
+ function containedPath(root, relative) {
23
+ const contained = path.relative(root, path.resolve(root, relative));
24
+ if (!contained ||
25
+ contained === '..' ||
26
+ contained.startsWith(`..${path.sep}`) ||
27
+ path.isAbsolute(contained)) {
28
+ throw unsafe(relative);
29
+ }
30
+ return contained;
31
+ }
32
+ // Walk from a resolved trust root. Missing paths are allowed; symlinks (including
33
+ // dangling links), incompatible types and hardlinked write targets are not.
34
+ async function inspectPath(root, relative, kind, writable = true) {
35
+ const parts = containedPath(root, relative).split(path.sep);
36
+ let current = root;
37
+ for (const [index, part] of parts.entries()) {
38
+ current = path.join(current, part);
39
+ let stat;
40
+ try {
41
+ stat = await fs.lstat(current);
42
+ }
43
+ catch (error) {
44
+ if (missing(error)) {
45
+ return false;
46
+ }
47
+ throw error;
48
+ }
49
+ if (stat.isSymbolicLink()) {
50
+ throw unsafe(relative, 'ELOOP');
51
+ }
52
+ const directory = index < parts.length - 1 || kind === 'directory';
53
+ if (directory ? !stat.isDirectory() : !stat.isFile()) {
54
+ throw unsafe(relative, directory ? 'ENOTDIR' : 'EINVAL');
55
+ }
56
+ if (!directory && writable && stat.nlink !== 1) {
57
+ throw unsafe(relative);
58
+ }
59
+ }
60
+ return true;
61
+ }
62
+ async function readRegular(file) {
63
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
64
+ try {
65
+ if (!(await handle.stat()).isFile()) {
66
+ throw unsafe(file);
67
+ }
68
+ return await handle.readFile();
69
+ }
70
+ finally {
71
+ await handle.close();
72
+ }
73
+ }
74
+ async function readTemplates() {
75
+ const packageRoot = await fs.realpath(path.resolve(import.meta.dirname, '../..'));
76
+ const source = 'templates/skills';
77
+ await inspectPath(packageRoot, source, 'directory', false);
78
+ const names = SKILL_NAMES.map((name) => `${name}.md`);
79
+ const found = (await fs.readdir(path.join(packageRoot, source)))
80
+ .filter((name) => name.endsWith('.md'))
81
+ .sort();
82
+ if (JSON.stringify(found) !== JSON.stringify(names)) {
83
+ throw new Error('Unexpected cognitive skill template set');
84
+ }
85
+ // Validate every source before reading any; a missing or unsafe late role
86
+ // cannot leave a partially regenerated mirror.
87
+ for (const name of names) {
88
+ if (!(await inspectPath(packageRoot, path.join(source, name), 'file', false))) {
89
+ throw new Error(`Missing cognitive skill template: ${name}`);
90
+ }
91
+ }
92
+ const templates = [];
93
+ for (const name of names) {
94
+ templates.push({ name, content: await readRegular(path.join(packageRoot, source, name)) });
95
+ }
96
+ for (const relative of [
97
+ 'templates/AGENTS.md',
98
+ 'templates/host/planu-sdd.md',
99
+ 'templates/cursor/planu-guard.mjs',
100
+ 'templates/cursor/hooks.json',
101
+ ]) {
102
+ const exists = await inspectPath(packageRoot, relative, 'file', false);
103
+ if (!exists && relative !== 'templates/host/planu-sdd.md') {
104
+ throw new Error(`Missing initialization template: ${relative}`);
105
+ }
106
+ if (exists) {
107
+ await readRegular(path.join(packageRoot, relative));
108
+ }
109
+ }
110
+ return templates;
111
+ }
112
+ function projectTargets() {
113
+ const targets = [
114
+ { relative: '.sdd/features', kind: 'directory' },
115
+ { relative: '.sdd/skills', kind: 'directory' },
116
+ ];
117
+ const files = [
118
+ 'AGENTS.md',
119
+ '.cursor/rules/planu-sdd.mdc',
120
+ '.claude/rules/planu-sdd.md',
121
+ '.gemini/planu-sdd.md',
122
+ '.cursor/hooks/planu-guard.mjs',
123
+ '.cursor/hooks.json',
124
+ ];
125
+ for (const name of SKILL_NAMES) {
126
+ for (const host of ['.claude', '.cursor', '.agents']) {
127
+ files.push(path.join(host, 'skills', `planu-${name}`, 'SKILL.md'));
128
+ }
129
+ files.push(path.join('.gemini', 'skills', `planu-${name}.md`));
130
+ }
131
+ return [...targets, ...files.map((relative) => ({ relative, kind: 'file' }))];
132
+ }
133
+ async function removeOwnedTemporary(root, temporary) {
134
+ if (!(await inspectPath(root, '.sdd/skills', 'directory'))) {
135
+ throw unsafe('.sdd/skills');
136
+ }
137
+ await fs.unlink(temporary);
138
+ }
139
+ async function replaceMirror(root, relative, content) {
140
+ if (!(await inspectPath(root, '.sdd/skills', 'directory'))) {
141
+ throw unsafe('.sdd/skills');
142
+ }
143
+ const exists = await inspectPath(root, relative, 'file');
144
+ const destination = path.join(root, relative);
145
+ if (exists && (await readRegular(destination)).equals(content)) {
146
+ return;
147
+ }
148
+ const temporary = path.join(path.dirname(destination), `.planu-${randomUUID()}.tmp`);
149
+ let owned = false;
150
+ try {
151
+ const handle = await fs.open(temporary, 'wx', 0o644);
152
+ owned = true;
153
+ try {
154
+ await handle.writeFile(content);
155
+ await handle.sync();
156
+ }
157
+ finally {
158
+ await handle.close();
159
+ }
160
+ // Recheck immediately before replacement. These checks do not promise an
161
+ // OS sandbox against hostile same-user concurrent directory replacement.
162
+ if (!(await inspectPath(root, '.sdd/skills', 'directory'))) {
163
+ throw unsafe('.sdd/skills');
164
+ }
165
+ await inspectPath(root, relative, 'file');
166
+ await fs.rename(temporary, destination);
167
+ owned = false;
168
+ }
169
+ finally {
170
+ if (owned) {
171
+ // Only remove this invocation's exclusive temporary inside a safe parent.
172
+ await removeOwnedTemporary(root, temporary);
173
+ }
174
+ }
175
+ }
176
+ /** Validate the complete project init write set before the caller writes anything. */
177
+ export async function prepareProjectInitialization(workspaceRoot) {
178
+ const root = await fs.realpath(workspaceRoot);
179
+ const templates = await readTemplates();
180
+ for (const target of projectTargets()) {
181
+ await inspectPath(root, target.relative, target.kind);
182
+ }
183
+ const mirrorExists = await inspectPath(root, '.sdd/skills', 'directory');
184
+ if (mirrorExists) {
185
+ for (const template of templates) {
186
+ await inspectPath(root, path.join('.sdd/skills', template.name), 'file');
187
+ }
188
+ }
189
+ return async () => {
190
+ if (mirrorExists) {
191
+ for (const template of templates) {
192
+ await replaceMirror(root, path.join('.sdd/skills', template.name), template.content);
193
+ }
194
+ }
195
+ };
196
+ }
197
+ //# sourceMappingURL=workspace-init.js.map
@@ -4,4 +4,11 @@ export declare function resolveSddWorkspaceRoot(startDir?: string, env?: NodeJS.
4
4
  export declare function resolveSddWorkspace(input?: ResolveSddWorkspaceInput): ResolvedSddWorkspace;
5
5
  export declare function isHomeFallbackWorkspace(resolved: ResolvedSddWorkspace, env?: NodeJS.ProcessEnv): boolean;
6
6
  export declare function homeFallbackFailure(resolved: ResolvedSddWorkspace, trigger: string, env?: NodeJS.ProcessEnv): SddFailure | null;
7
+ export declare function readTextInsideWorkspace(workspaceRoot: string, absolutePath: string): Promise<{
8
+ ok: true;
9
+ text: string;
10
+ } | {
11
+ ok: false;
12
+ reason: 'outside' | 'missing';
13
+ }>;
7
14
  //# sourceMappingURL=workspace-root.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
+ import { readFile, realpath } from 'node:fs/promises';
2
3
  import { dirname, join, resolve, sep } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
5
  const ERR_WORKSPACE_UNRESOLVED_MESSAGE = 'Resolved workspace is the user home directory without MCP roots or PLANU_WORKSPACE. Set the MCP server cwd to the project, advertise MCP roots, or set a per-process PLANU_WORKSPACE. Do not pin PLANU_WORKSPACE globally.';
@@ -127,6 +128,33 @@ function expandHomePrefix(raw, env) {
127
128
  }
128
129
  return raw;
129
130
  }
131
+ export async function readTextInsideWorkspace(workspaceRoot, absolutePath) {
132
+ let root;
133
+ try {
134
+ root = await realpath(workspaceRoot);
135
+ }
136
+ catch {
137
+ return { ok: false, reason: 'outside' };
138
+ }
139
+ const target = resolve(absolutePath);
140
+ const boundary = root.endsWith(sep) ? root : `${root}${sep}`;
141
+ let realTarget;
142
+ try {
143
+ realTarget = await realpath(target);
144
+ }
145
+ catch {
146
+ return { ok: false, reason: 'missing' };
147
+ }
148
+ if (realTarget !== root && !realTarget.startsWith(boundary)) {
149
+ return { ok: false, reason: 'outside' };
150
+ }
151
+ try {
152
+ return { ok: true, text: await readFile(realTarget, 'utf8') };
153
+ }
154
+ catch {
155
+ return { ok: false, reason: 'missing' };
156
+ }
157
+ }
130
158
  function unique(values) {
131
159
  const seen = new Set();
132
160
  const out = [];
@@ -53,7 +53,7 @@ export interface ApplyFilePatchInput {
53
53
  export interface CompleteTaskInput {
54
54
  feature_id: string;
55
55
  task_id: string;
56
- verification_output: string;
56
+ verification_output?: string;
57
57
  }
58
58
  export interface ParsedManifest {
59
59
  allowedFiles: Map<string, FilePermission>;
@@ -67,6 +67,7 @@ export interface ActiveTaskDetails {
67
67
  taskId: string;
68
68
  taskTitle: string;
69
69
  fullTaskMarkdown: string;
70
+ verificationCommand: string | null;
70
71
  taskIndex: number;
71
72
  totalTasks: number;
72
73
  completedTasks: number;
@@ -75,6 +76,12 @@ export interface ActiveTaskResult {
75
76
  activeTask: ActiveTaskDetails | null;
76
77
  allCompleted: boolean;
77
78
  status: 'IN_PROGRESS' | 'ALL_COMPLETED' | 'NO_TASKS';
79
+ locked: boolean;
80
+ trinity: 'ready' | 'unlocked' | 'drift';
81
+ manifest: {
82
+ path: string;
83
+ permission: FilePermission;
84
+ }[];
78
85
  }
79
86
  export interface CompleteTaskResult {
80
87
  completedTaskId: string;
@@ -94,6 +101,7 @@ export interface FeatureSummary {
94
101
  id: string;
95
102
  status: 'planning' | 'executing' | 'done';
96
103
  locked: boolean;
104
+ activeTaskId: string | null;
97
105
  }
98
106
  export interface RelockRecord {
99
107
  lockedAt: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planu/cli",
3
- "version": "8.2.15",
3
+ "version": "8.2.17",
4
4
  "description": "Planu — MCP Server for Spec Driven Development. Cross-platform (Linux/macOS/Windows, x64/arm64).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -25,6 +25,14 @@ Your objective is to safely adapt `plan.md` and `tasks.md` when business require
25
25
  4. **Language:**
26
26
  - ALL updates to artifacts MUST be written entirely in Technical English.
27
27
 
28
+ ## Current increment or deferred idea
29
+
30
+ - Classify each discovery as a correction necessary for the selected user outcome or a separate future outcome. Defer independent ideas in the existing backlog/source; do not silently expand the current feature.
31
+ - Preserve the smallest useful increment and its observable demonstration. Reuse unchanged contracts by exact source reference; describe only affected boundaries at the depth their risk requires.
32
+ - A necessary foundational step must explain the first usable result it enables. A preference for another abstraction or possible future requirement is not sufficient scope.
33
+ - Keep every pending task concrete and verifiable before lock/relock. Do not execute partially specified future tasks or omit acceptance, Error Matrix, Frozen Dependencies or File Manifest authority.
34
+ - Obtain approval before a changed locked contract is resealed. Preserve completed tasks and their evidence; new information never authorizes rewriting that history.
35
+
28
36
  ## Traceability and obsolescence gate
29
37
 
30
38
  Before changing an unlocked plan, produce a matrix with one row per changed requirement:
@@ -7,7 +7,7 @@ target_tools: [sdd_create_feature, sdd_read_spec_artifact, sdd_lock_spec]
7
7
  # SDD SPEC ARCHITECT DIRECTIVE (HIGH REASONING)
8
8
 
9
9
  You act as the Staff Systems Architect and Lead Spec Designer.
10
- Your objective is to produce airtight, deterministic, and unambiguous specifications before any implementation code is written.
10
+ Your objective is to specify the smallest useful increment with deterministic, unambiguous acceptance behavior before implementation.
11
11
 
12
12
  ## CORE PRINCIPLES & LAWS
13
13
 
@@ -17,7 +17,8 @@ Your objective is to produce airtight, deterministic, and unambiguous specificat
17
17
 
18
18
  2. **Strict Typed Contracts (Zero Loose Types):**
19
19
  - No `any`, dynamic untyped objects, or vague comments.
20
- - Define exact data models, DTOs, structs, or schemas using the target language's native typing system (e.g., Rust structs, Go structs, TypeScript interfaces, Python dataclasses/Pydantic).
20
+ - Reuse existing contracts by exact source reference. Define exact native types only at affected boundaries; do not duplicate an unchanged model to fill a section.
21
+ - Explain when no contract change is applicable. Keep the section and the Error Matrix substantive without inventing data fields, failures, HTTP statuses, or requirements.
21
22
 
22
23
  3. **Deterministic Error Matrix:**
23
24
  - Never write "handle errors appropriately".
@@ -33,16 +34,32 @@ Your objective is to produce airtight, deterministic, and unambiguous specificat
33
34
  - `DELETE: path/to/file-or-directory` (exact path only; no globs)
34
35
  - CREATE, MODIFY, and READ_ONLY may use `*` (one path segment) or `**` (many segments).
35
36
  - `sdd_lock_spec` rejects incomplete trinities. Reseal after review with `relock: true` and `reason`.
36
- - *Crucial Rule:* The MCP server rejects any file edit not declared in this manifest (`ERR_FILE_OUT_OF_MANIFEST`).
37
+ - _Crucial Rule:_ The MCP server rejects any file edit not declared in this manifest (`ERR_FILE_OUT_OF_MANIFEST`).
37
38
 
38
39
  5. **Atomic Linear Tasks in `tasks.md`:**
39
- - Break the implementation into small, atomic, verifiable steps.
40
+ - Break the selected increment into small, atomic, verifiable steps that contribute to its observable outcome. Internal tasks may be technical; small tasks alone do not establish a usable increment.
41
+ - The server runs each task's Verification and advances only on exit 0. Plan a command that succeeds when that task's own work is complete, using the files/state available at that point in the sequence.
42
+ - Verification contains literal executable syntax only. Put expected results, RED explanations and other prose in the task description, never as annotations appended to the command.
43
+ - Normally capture RED and implement the fix within one task that ends with a GREEN completion command. Do not put a necessarily failing test command before a later implementation task: the server cannot certify it or reach the fix.
44
+ - If a separate RED-only task is necessary, specify a checker that proves the intended acceptance failure, rejects syntax/setup/infrastructure errors and itself exits 0. Never ignore the result, use unconditional success or weaken assertions to advance.
45
+ - Before lock, inspect each literal command for syntax, working directory, available paths and successful progression after prior tasks. This is planning inspection; do not execute product code during architecture.
40
46
  - Required format:
41
47
  ```markdown
42
48
  - [ ] TASK-1: Describe atomic work
43
- Verification: <executable test command>
49
+ Verification: <executable test command>
44
50
  ```
45
51
 
52
+ ## SELECT THE INCREMENT BEFORE STRUCTURE
53
+
54
+ - Name one smallest useful user outcome and its observable demonstration. Defer independent requested outcomes explicitly; use the existing backlog or source rather than creating a second planning system.
55
+ - Plan only the necessary layers for that outcome. A CLI command, backend capability or worker behavior can be useful without inventing a UI.
56
+ - Reuse the current architecture and components. Every new abstraction, dependency or preparatory layer needs a current acceptance requirement; anticipated future flexibility is insufficient.
57
+ - Foundational work is allowed when necessary, but explain why it is needed for this increment and identify the first demonstrable result it enables.
58
+ - Scale technical detail to changed boundaries and risk. Do not enforce arbitrary document lengths, line caps, task counts, architecture patterns or separate layers for their own sake.
59
+ - Preserve explicit authorization, isolation, concurrency, failure and rollback requirements where relevant; proportional planning never weakens a control.
60
+ - Every task in the locked feature must be concrete and verifiable. Do not freeze an entire speculative backlog or execute placeholders for later work.
61
+ - Resolve questions from current source and the user's requirements first. Ask only when a material unknown prevents a sound contract; never invent acceptance behavior.
62
+
46
63
  ## WORKFLOW
47
64
 
48
65
  1. Initialize the feature using `sdd_create_feature(id, title)` with a `FEAT-*` id.
@@ -33,6 +33,17 @@ You do not make architectural decisions, you do not add dependencies, and you do
33
33
  - Repeat from step 1 until `allCompleted` is true.
34
34
  - Then adopt `git-janitor.md`.
35
35
 
36
+ ## Small steps and early feedback
37
+
38
+ - Tie the active task to the selected user outcome. Make the smallest change needed for its current acceptance behavior, reusing existing contracts and components; do not add layers for hypothetical future work.
39
+ - For a behavior change, establish a meaningful regression before the fix when feasible. Record red and green commands, exit codes and relevant output, then inspect the actual scoped diff.
40
+ - If red evidence is unavailable, state the concrete reason and its evidence class, and provide an alternative substantive proof. A test that would pass without the fix is not regression evidence.
41
+ - Pure documentation, metadata and behavior-preserving refactors do not need fabricated red failures. Preserve their applicable static or before/after regression proof instead.
42
+ - Inspect changed tests as well as implementation. Do not delete assertions, add skips/focus, relax expected values or thresholds, or mock away the tested boundary just to obtain green output.
43
+ - Legitimate test corrections and refactors are allowed when their reason is tied to acceptance behavior and equivalent or stronger coverage is demonstrated. Tests are not immutable, but a changed test needs reviewable justification.
44
+ - Review each incremental diff before continuing. Stop for a scope, dependency or contract change that needs reconciliation; do not add a human approval prompt for every already-authorized microchange.
45
+ - Keep canonical task order, File Manifest authority and server-run Verification unchanged. A local green check does not replace task certification or independent acceptance review.
46
+
36
47
  ## ENTRY AND EXIT GATES
37
48
 
38
49
  - Begin only after `preflight-guardian.md` returns `READY` for the named feature and active task.
@@ -16,9 +16,17 @@ You do not implement fixes while wearing this role. Your objective is to prove o
16
16
  - Never infer approval from a green happy-path test, a task checkbox, or another agent's summary.
17
17
  - Preserve unrelated user changes and report any path outside the File Manifest.
18
18
 
19
+ ## Match the verdict to the requested scope
20
+
21
+ - Establish the property the requester asked you to review before choosing its proof. An explicitly static-only review of assertion preservation or a supplied patch can be decided from complete before/after bytes.
22
+ - If that requested static property is demonstrated, emit APPROVED for that property only. State the static evidence and explicitly leave runtime behavior, implementation acceptance and release unverified.
23
+ - Do not demand execution, a full feature trinity or release evidence to decide a narrower static property when those are outside the requested scope. Missing runtime alone is not a blocker for a demonstrated static property.
24
+ - Never use this scoped verdict to certify an implementation task, feature, runtime behavior or release. Those decisions retain every required executed verification and independent release gate. Missing evidence required by the actual requested scope still blocks approval.
25
+
19
26
  ## Evidence classes
20
27
 
21
28
  Classify every claim as one of:
29
+
22
30
  - `executed`: observed command, exit code, and relevant output from this verification.
23
31
  - `static`: established by source, diff, configuration, or artifact inspection only.
24
32
  - `reported`: supplied by another agent or requester and not reproduced.
@@ -29,6 +37,7 @@ Never present reported or environment-blocked evidence as executed.
29
37
  ## Acceptance mapping
30
38
 
31
39
  For every acceptance criterion, record:
40
+
32
41
  1. the implementation path and observable behavior;
33
42
  2. the substantive test or inspection that proves it;
34
43
  3. the command and exit code when executed;
@@ -37,6 +46,16 @@ For every acceptance criterion, record:
37
46
 
38
47
  Count-only assertions, existence checks, snapshots without semantics, and tests that pass before the change do not prove behavior.
39
48
 
49
+ ## Test-integrity review
50
+
51
+ - Compare before and after test code against the actual acceptance behavior, not only the final runner status.
52
+ - Look for removed assertions, skipped or focused tests, relaxed expected values or thresholds, and mocks replacing the boundary under test. Require a concrete acceptance-linked reason and substantive proof for each relevant change.
53
+ - Tests are not immutable. A justified correction, relocation or refactor can preserve or strengthen coverage; verify that assertions and the exercised boundary remain meaningful rather than rejecting every edited test.
54
+ - Inspect execution evidence: command, exit code, which tests actually ran, and whether a filter or skip excluded the acceptance case. An intentionally scoped check is not a full-suite result.
55
+ - For changed behavior, inspect the red and green witnesses when feasible and whether reverting the fix would make the regression fail. Missing red evidence needs an explicit reason and an alternative substantive proof.
56
+ - Pure documentation, metadata and behavior-preserving refactors need their applicable proof, not invented failing tests. Keep executed, static, reported and environment-blocked evidence distinct.
57
+ - Static assertion preservation is a scoped conclusion only; it does not certify runtime behavior or a release. A green command, a valid receipt or a task checkbox is insufficient when acceptance evidence is missing.
58
+
40
59
  ## Mandatory final checks
41
60
 
42
61
  - Run the exact task verification commands when safe and available.
@@ -56,6 +75,7 @@ Count-only assertions, existence checks, snapshots without semantics, and tests
56
75
  ## Verdict
57
76
 
58
77
  Emit exactly one verdict:
78
+
59
79
  - `APPROVED`: every criterion has substantive evidence and no required gate remains.
60
80
  - `CHANGES_REQUESTED`: a product, contract, scope, or proof defect is actionable in the repository.
61
81
  - `BLOCKED`: required proof depends on unavailable authority or external state.