@planu/cli 8.2.17 → 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 (33) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +14 -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 +63 -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 +4 -0
  33. package/templates/host/planu-sdd.md +4 -0
@@ -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
@@ -0,0 +1,224 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { CompletionGuardError } from '../feature-authority.js';
4
+ export async function createExplicitFeatureDirectory(featDir, featureId) {
5
+ try {
6
+ await fs.mkdir(featDir);
7
+ return null;
8
+ }
9
+ catch (err) {
10
+ if (isNodeErrorCode(err, 'EEXIST')) {
11
+ return {
12
+ success: false,
13
+ error: {
14
+ code: 'ERR_FEATURE_ALREADY_EXISTS',
15
+ message: `Feature '${featureId}' already exists in the workspace.`,
16
+ trigger: 'sdd_create_feature',
17
+ },
18
+ };
19
+ }
20
+ throw err;
21
+ }
22
+ }
23
+ export async function reserveAutomaticFeatureDirectory(featuresDir, title) {
24
+ const entries = await fs.readdir(featuresDir, { withFileTypes: true });
25
+ const featureNames = entries
26
+ .filter((entry) => entry.isDirectory() && /^FEAT[-_]/u.test(entry.name))
27
+ .map((entry) => entry.name);
28
+ const allocatedSequences = entries.flatMap((entry) => {
29
+ if (!entry.isDirectory()) {
30
+ return [];
31
+ }
32
+ const sequence = /^FEAT[-_](\d+)(?:[-_]|$)/u.exec(entry.name)?.[1] ??
33
+ /^\.FEAT-(\d+)\.reserve$/u.exec(entry.name)?.[1];
34
+ return sequence ? [Number(sequence)] : [];
35
+ });
36
+ const highestSequence = Math.max(0, ...allocatedSequences);
37
+ let nextSequence = Math.max(highestSequence + 1, featureNames.length + 1);
38
+ const slug = createFeatureSlug(title);
39
+ for (;;) {
40
+ const sequenceLabel = String(nextSequence).padStart(4, '0');
41
+ const reservationDir = path.join(featuresDir, `.FEAT-${sequenceLabel}.reserve`);
42
+ try {
43
+ await fs.mkdir(reservationDir);
44
+ }
45
+ catch (err) {
46
+ if (!isNodeErrorCode(err, 'EEXIST')) {
47
+ throw err;
48
+ }
49
+ nextSequence += 1;
50
+ continue;
51
+ }
52
+ const featureId = `FEAT-${sequenceLabel}-${slug}`;
53
+ const featDir = path.join(featuresDir, featureId);
54
+ try {
55
+ await fs.mkdir(featDir);
56
+ }
57
+ catch (err) {
58
+ await fs.rm(reservationDir, { recursive: true, force: true });
59
+ if (isNodeErrorCode(err, 'EEXIST')) {
60
+ nextSequence += 1;
61
+ continue;
62
+ }
63
+ throw err;
64
+ }
65
+ try {
66
+ await fs.rm(reservationDir, { recursive: true, force: false });
67
+ }
68
+ catch (err) {
69
+ await fs.rm(featDir, { recursive: true, force: true });
70
+ throw err;
71
+ }
72
+ return { featureId, featDir };
73
+ }
74
+ }
75
+ function createFeatureSlug(title) {
76
+ const slug = title
77
+ .normalize('NFKD')
78
+ .replace(/[\u0300-\u036f]/gu, '')
79
+ .toUpperCase()
80
+ .replace(/[^A-Z0-9]+/gu, '-')
81
+ .replace(/^-+|-+$/gu, '')
82
+ .slice(0, 48)
83
+ .replace(/-+$/gu, '');
84
+ return slug || 'FEATURE';
85
+ }
86
+ function isNodeErrorCode(err, code) {
87
+ return typeof err === 'object' && err !== null && 'code' in err && err.code === code;
88
+ }
89
+ export async function collectFeatures(featuresDir, taskWindow, statusFilter) {
90
+ const result = [];
91
+ let entries;
92
+ try {
93
+ entries = await fs.readdir(featuresDir, { withFileTypes: true });
94
+ }
95
+ catch (error) {
96
+ if (isNodeErrorCode(error, 'ENOENT')) {
97
+ return { success: true, data: [] };
98
+ }
99
+ return catalogueFailure();
100
+ }
101
+ try {
102
+ const candidates = entries.filter((entry) => /^FEAT[-_][A-Z0-9_-]+$/u.test(entry.name));
103
+ // Bound concurrent feature reads to eight. allSettled drains every started read
104
+ // before returning a failure, and ordered reduction preserves filesystem order.
105
+ for (let offset = 0; offset < candidates.length; offset += 8) {
106
+ const settled = await Promise.allSettled(candidates
107
+ .slice(offset, offset + 8)
108
+ .map(async (entry) => {
109
+ if (entry.isSymbolicLink()) {
110
+ return pathFailure('sdd_list_features', true);
111
+ }
112
+ if (!entry.isDirectory()) {
113
+ return catalogueFailure();
114
+ }
115
+ const featId = entry.name;
116
+ const featPath = path.join(featuresDir, featId);
117
+ const entryResult = await taskWindow.getCatalogueEntry(featPath);
118
+ if (!entryResult.success) {
119
+ return entryResult;
120
+ }
121
+ if (!statusFilter ||
122
+ statusFilter === 'all' ||
123
+ statusFilter === entryResult.data.status) {
124
+ return { success: true, data: entryResult.data };
125
+ }
126
+ return { success: true, data: null };
127
+ }));
128
+ for (const outcome of settled) {
129
+ if (outcome.status === 'rejected') {
130
+ throw outcome.reason;
131
+ }
132
+ const current = outcome.value;
133
+ if (!current.success) {
134
+ return current;
135
+ }
136
+ if (current.data !== null) {
137
+ result.push(current.data);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ catch (error) {
143
+ if (error instanceof CompletionGuardError) {
144
+ return {
145
+ success: false,
146
+ error: {
147
+ code: error.code,
148
+ message: error.message,
149
+ trigger: 'sdd_list_features',
150
+ details: { reason: error.reason },
151
+ },
152
+ };
153
+ }
154
+ return catalogueFailure();
155
+ }
156
+ return { success: true, data: result };
157
+ }
158
+ function pathFailure(trigger, outside) {
159
+ return {
160
+ success: false,
161
+ error: {
162
+ code: outside ? 'ERR_PERMISSION_VIOLATION' : 'ERR_INVALID_ARTIFACT',
163
+ message: outside
164
+ ? 'Unsafe feature path outside the physical workspace boundary.'
165
+ : 'Feature storage is not a readable directory.',
166
+ trigger,
167
+ },
168
+ };
169
+ }
170
+ function catalogueFailure(entry) {
171
+ return {
172
+ success: false,
173
+ error: {
174
+ code: 'ERR_INVALID_ARTIFACT',
175
+ message: 'Could not read the complete feature catalogue.',
176
+ trigger: 'sdd_list_features',
177
+ ...(entry ? { details: { entry } } : {}),
178
+ },
179
+ };
180
+ }
181
+ export async function featurePathFailure(workspaceRoot, directory, trigger) {
182
+ const relative = path.relative(path.resolve(workspaceRoot), path.resolve(directory));
183
+ if (relative.startsWith('..' + path.sep) || relative === '..' || path.isAbsolute(relative)) {
184
+ return pathFailure(trigger, true);
185
+ }
186
+ try {
187
+ let current = await fs.realpath(workspaceRoot);
188
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
189
+ current = path.join(current, segment);
190
+ let stat;
191
+ try {
192
+ stat = await fs.lstat(current);
193
+ }
194
+ catch (error) {
195
+ if (isNodeErrorCode(error, 'ENOENT')) {
196
+ return null;
197
+ }
198
+ throw error;
199
+ }
200
+ if (stat.isSymbolicLink()) {
201
+ return pathFailure(trigger, true);
202
+ }
203
+ if (!stat.isDirectory()) {
204
+ return pathFailure(trigger, false);
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+ catch {
210
+ return pathFailure(trigger, false);
211
+ }
212
+ }
213
+ export async function writeFeatureArtifacts(featDir, id, title) {
214
+ 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`;
215
+ 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`;
216
+ 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`;
217
+ await fs.writeFile(path.join(featDir, 'spec.md'), initialSpec, { encoding: 'utf8', flag: 'wx' });
218
+ await fs.writeFile(path.join(featDir, 'plan.md'), initialPlan, { encoding: 'utf8', flag: 'wx' });
219
+ await fs.writeFile(path.join(featDir, 'tasks.md'), initialTasks, {
220
+ encoding: 'utf8',
221
+ flag: 'wx',
222
+ });
223
+ }
224
+ //# sourceMappingURL=feature-store.js.map
@@ -7,7 +7,9 @@ import { formatResult } from './format-result.js';
7
7
  import { homeFallbackFailure } from '../workspace-root.js';
8
8
  import { prepareProjectInitialization } from '../workspace-init.js';
9
9
  import { writeLockedTrinity } from '../lock-integrity.js';
10
- import { copyGlobalRules, installCursorGuard, installHostRulePack, installHostSkillPack, } from '../host-rule-pack.js';
10
+ import { CompletionGuardError } from '../feature-authority.js';
11
+ import { reserveAutomaticFeatureDirectory, createExplicitFeatureDirectory, collectFeatures, featurePathFailure, writeFeatureArtifacts, } from './feature-store.js';
12
+ import { copyGlobalRules, installCursorGuard, installHostRulePack, installHostSkillPack, inspectHostSkillPack, } from '../host-rule-pack.js';
11
13
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
12
14
  const MISSING_SDD_HINT = 'No .sdd directory in the client project. Call sdd_init_workspace with scope=project. MCP hosts should advertise roots; do not pin PLANU_WORKSPACE globally.';
13
15
  const LEGACY_SPECS_HINT = 'Planu ignores planu/specs. Do not create SPEC-* stubs or copy a FEAT into that tree. Retire host hooks that require planu/specs/SPEC-*/spec.md; the only contract is .sdd/features/FEAT-*.';
@@ -16,10 +18,24 @@ async function composeWorkspaceHint(workspaceRoot, extra) {
16
18
  .access(path.join(workspaceRoot, 'planu', 'specs'))
17
19
  .then(() => true)
18
20
  .catch(() => false);
19
- if (!legacySpecsPresent) {
20
- return extra;
21
+ const pack = await inspectHostSkillPack(workspaceRoot).catch(() => 'Planu host skill verification was unavailable. Run sdd_init_workspace for requested project setup and read the matching role.');
22
+ const combined = [extra, pack, legacySpecsPresent ? LEGACY_SPECS_HINT : undefined]
23
+ .filter((item) => item !== undefined)
24
+ .join(' ');
25
+ if (!combined) {
26
+ return undefined;
21
27
  }
22
- return extra ? `${extra} ${LEGACY_SPECS_HINT}` : LEGACY_SPECS_HINT;
28
+ let bounded = '';
29
+ let bytes = 0;
30
+ for (const character of combined) {
31
+ const size = Buffer.byteLength(character);
32
+ if (bytes + size > 1024) {
33
+ break;
34
+ }
35
+ bounded += character;
36
+ bytes += size;
37
+ }
38
+ return bounded;
23
39
  }
24
40
  export function registerWorkspaceTools(server, workspace) {
25
41
  const taskWindow = new TaskWindowManager();
@@ -59,7 +75,7 @@ function registerInitTool(server, workspace) {
59
75
  const hostRules = args.scope === 'project' ? await installHostRulePack(resolved.workspaceRoot) : [];
60
76
  const cursorGuard = args.scope === 'project' ? await installCursorGuard(resolved.workspaceRoot) : [];
61
77
  const hostSkills = args.scope === 'project' ? await installHostSkillPack(resolved.workspaceRoot) : [];
62
- const hint = await composeWorkspaceHint(resolved.workspaceRoot, 'Commit .sdd/features with the project. Host quality gates must map .sdd/ as versioned documentation. Cursor, Claude, Gemini, and Codex load Planu skills from sdd_init_workspace host folders, not .sdd/skills.');
78
+ const hint = await composeWorkspaceHint(resolved.workspaceRoot, 'Commit .sdd/features with the project. Host quality gates must map .sdd/ as versioned documentation. Cursor, Claude, Gemini, and Codex load Planu skills from sdd_init_workspace host folders, not .sdd/skills. Read .agents/skills/planu-preflight-guardian/SKILL.md and the matching role with sdd_read_file_slice now. Host catalog discovery may require a client/session reload; restarting MCP and reloading host skills are separate actions.');
63
79
  return formatResult({
64
80
  success: true,
65
81
  data: {
@@ -92,7 +108,15 @@ function registerListTool(server, workspace, taskWindow) {
92
108
  return formatResult(homeError);
93
109
  }
94
110
  const featuresDir = path.join(resolved.sddDir, 'features');
95
- const featuresList = await collectFeatures(featuresDir, taskWindow, args.status_filter);
111
+ const safety = await featurePathFailure(resolved.workspaceRoot, featuresDir, 'sdd_list_features');
112
+ if (safety) {
113
+ return formatResult(safety);
114
+ }
115
+ const collected = await collectFeatures(featuresDir, taskWindow, args.status_filter);
116
+ if (!collected.success) {
117
+ return formatResult(collected);
118
+ }
119
+ const featuresList = collected.data;
96
120
  const hint = await composeWorkspaceHint(resolved.workspaceRoot, resolved.sddPresent ? undefined : MISSING_SDD_HINT);
97
121
  return formatResult({
98
122
  success: true,
@@ -119,26 +143,26 @@ function registerCreateTool(server, workspace) {
119
143
  return formatResult(homeError);
120
144
  }
121
145
  const featuresDir = path.join(resolved.sddDir, 'features');
146
+ const safety = await featurePathFailure(resolved.workspaceRoot, featuresDir, 'sdd_create_feature');
147
+ if (safety) {
148
+ return formatResult(safety);
149
+ }
122
150
  await fs.mkdir(featuresDir, { recursive: true });
151
+ const afterCreation = await featurePathFailure(resolved.workspaceRoot, featuresDir, 'sdd_create_feature');
152
+ if (afterCreation) {
153
+ return formatResult(afterCreation);
154
+ }
123
155
  let featureId = args.id;
124
156
  let featDir;
125
157
  if (featureId) {
126
158
  featDir = path.join(featuresDir, featureId);
127
- try {
128
- await fs.mkdir(featDir);
159
+ const existingSafety = await featurePathFailure(resolved.workspaceRoot, featDir, 'sdd_create_feature');
160
+ if (existingSafety) {
161
+ return formatResult(existingSafety);
129
162
  }
130
- catch (err) {
131
- if (isNodeErrorCode(err, 'EEXIST')) {
132
- return formatResult({
133
- success: false,
134
- error: {
135
- code: 'ERR_FEATURE_ALREADY_EXISTS',
136
- message: `Feature '${featureId}' already exists in the workspace.`,
137
- trigger: 'sdd_create_feature',
138
- },
139
- });
140
- }
141
- throw err;
163
+ const creationFailure = await createExplicitFeatureDirectory(featDir, featureId);
164
+ if (creationFailure) {
165
+ return formatResult(creationFailure);
142
166
  }
143
167
  }
144
168
  else {
@@ -146,7 +170,12 @@ function registerCreateTool(server, workspace) {
146
170
  featureId = reservation.featureId;
147
171
  featDir = reservation.featDir;
148
172
  }
173
+ const featureSafety = await featurePathFailure(resolved.workspaceRoot, featDir, 'sdd_create_feature');
174
+ if (featureSafety) {
175
+ return formatResult(featureSafety);
176
+ }
149
177
  await writeFeatureArtifacts(featDir, featureId, args.title);
178
+ const hint = await composeWorkspaceHint(resolved.workspaceRoot);
150
179
  return formatResult({
151
180
  success: true,
152
181
  data: {
@@ -154,73 +183,11 @@ function registerCreateTool(server, workspace) {
154
183
  artifactsCreated: ['spec.md', 'plan.md', 'tasks.md'],
155
184
  directory: featDir,
156
185
  workspaceRoot: resolved.workspaceRoot,
186
+ ...(hint ? { hint } : {}),
157
187
  },
158
188
  });
159
189
  });
160
190
  }
161
- async function reserveAutomaticFeatureDirectory(featuresDir, title) {
162
- const entries = await fs.readdir(featuresDir, { withFileTypes: true });
163
- const featureNames = entries
164
- .filter((entry) => entry.isDirectory() && /^FEAT[-_]/u.test(entry.name))
165
- .map((entry) => entry.name);
166
- const allocatedSequences = entries.flatMap((entry) => {
167
- if (!entry.isDirectory()) {
168
- return [];
169
- }
170
- const sequence = /^FEAT[-_](\d+)(?:[-_]|$)/u.exec(entry.name)?.[1] ??
171
- /^\.FEAT-(\d+)\.reserve$/u.exec(entry.name)?.[1];
172
- return sequence ? [Number(sequence)] : [];
173
- });
174
- const highestSequence = Math.max(0, ...allocatedSequences);
175
- let nextSequence = Math.max(highestSequence + 1, featureNames.length + 1);
176
- const slug = createFeatureSlug(title);
177
- for (;;) {
178
- const sequenceLabel = String(nextSequence).padStart(4, '0');
179
- const reservationDir = path.join(featuresDir, `.FEAT-${sequenceLabel}.reserve`);
180
- try {
181
- await fs.mkdir(reservationDir);
182
- }
183
- catch (err) {
184
- if (!isNodeErrorCode(err, 'EEXIST')) {
185
- throw err;
186
- }
187
- nextSequence += 1;
188
- continue;
189
- }
190
- const featureId = `FEAT-${sequenceLabel}-${slug}`;
191
- const featDir = path.join(featuresDir, featureId);
192
- try {
193
- await fs.mkdir(featDir);
194
- }
195
- catch (err) {
196
- await fs.rm(reservationDir, { recursive: true, force: true });
197
- if (isNodeErrorCode(err, 'EEXIST')) {
198
- nextSequence += 1;
199
- continue;
200
- }
201
- throw err;
202
- }
203
- try {
204
- await fs.rm(reservationDir, { recursive: true, force: false });
205
- }
206
- catch (err) {
207
- await fs.rm(featDir, { recursive: true, force: true });
208
- throw err;
209
- }
210
- return { featureId, featDir };
211
- }
212
- }
213
- function createFeatureSlug(title) {
214
- const slug = title
215
- .normalize('NFKD')
216
- .replace(/[\u0300-\u036f]/gu, '')
217
- .toUpperCase()
218
- .replace(/[^A-Z0-9]+/gu, '-')
219
- .replace(/^-+|-+$/gu, '')
220
- .slice(0, 48)
221
- .replace(/-+$/gu, '');
222
- return slug || 'FEATURE';
223
- }
224
191
  function registerLockTool(server, workspace) {
225
192
  server.registerTool('sdd_lock_spec', {
226
193
  description: 'Locks spec.md, plan.md, and tasks.md. Pass relock=true and reason to reseal after review.',
@@ -236,9 +203,6 @@ function registerLockTool(server, workspace) {
236
203
  return executeLockSpec(featDir, args.feature_id, args.relock === true, args.reason);
237
204
  });
238
205
  }
239
- function isNodeErrorCode(err, code) {
240
- return typeof err === 'object' && err !== null && 'code' in err && err.code === code;
241
- }
242
206
  async function copySkillTemplates(skillsDir) {
243
207
  const sourceSkillsDir = path.resolve(moduleDir, '..', '..', '..', 'templates', 'skills');
244
208
  const files = await fs.readdir(sourceSkillsDir);
@@ -249,50 +213,24 @@ async function copySkillTemplates(skillsDir) {
249
213
  }
250
214
  }
251
215
  }
252
- async function collectFeatures(featuresDir, taskWindow, statusFilter) {
253
- const result = [];
216
+ async function executeLockSpec(featDir, featureId, relock, reason) {
217
+ let outcome;
254
218
  try {
255
- const entries = await fs.readdir(featuresDir, { withFileTypes: true });
256
- for (const entry of entries) {
257
- if (!entry.isDirectory() || !/^FEAT[-_][A-Z0-9_-]+$/u.test(entry.name)) {
258
- continue;
259
- }
260
- const featId = entry.name;
261
- const featPath = path.join(featuresDir, featId);
262
- const lockExists = await fs
263
- .access(path.join(featPath, '.lock'))
264
- .then(() => true)
265
- .catch(() => false);
266
- let status = 'planning';
267
- let activeTaskId = null;
268
- const tasksPath = path.join(featPath, 'tasks.md');
269
- const taskRes = await taskWindow.getActiveTask(tasksPath);
270
- if (lockExists) {
271
- status = taskRes.success && taskRes.data.allCompleted ? 'done' : 'executing';
272
- }
273
- if (taskRes.success) {
274
- activeTaskId = taskRes.data.activeTask?.taskId ?? null;
275
- }
276
- if (!statusFilter || statusFilter === 'all' || statusFilter === status) {
277
- result.push({ id: featId, status, locked: lockExists, activeTaskId });
278
- }
279
- }
219
+ outcome = await writeLockedTrinity(featDir, featureId, relock, reason);
280
220
  }
281
- catch {
282
- // Directory does not exist yet
221
+ catch (error) {
222
+ return formatResult({
223
+ success: false,
224
+ error: {
225
+ code: error instanceof CompletionGuardError ? error.code : 'ERR_INVALID_ARTIFACT',
226
+ message: error instanceof CompletionGuardError
227
+ ? error.message
228
+ : 'The feature could not be safely locked.',
229
+ trigger: 'sdd_lock_spec',
230
+ details: { reason: error instanceof CompletionGuardError ? error.reason : 'failed' },
231
+ },
232
+ });
283
233
  }
284
- return result;
285
- }
286
- async function writeFeatureArtifacts(featDir, id, title) {
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`;
290
- await fs.writeFile(path.join(featDir, 'spec.md'), initialSpec, 'utf-8');
291
- await fs.writeFile(path.join(featDir, 'plan.md'), initialPlan, 'utf-8');
292
- await fs.writeFile(path.join(featDir, 'tasks.md'), initialTasks, 'utf-8');
293
- }
294
- async function executeLockSpec(featDir, featureId, relock, reason) {
295
- const outcome = await writeLockedTrinity(featDir, featureId, relock, reason);
296
234
  if (!outcome.ok) {
297
235
  return formatResult({
298
236
  success: false,
@@ -4,7 +4,9 @@ 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<{
7
+ export declare function readTextInsideWorkspace(workspaceRoot: string, absolutePath: string, options?: {
8
+ maxBytes: number;
9
+ }): Promise<{
8
10
  ok: true;
9
11
  text: string;
10
12
  } | {