@planu/cli 8.1.1 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## [8.2.0] - 2026-09-21
2
+
3
+ - preserve existing `AGENTS.md` on `sdd_init_workspace` unless `force: true`
4
+ - `sdd_lock_spec` relock with `reason`, structural trinity gate, and `tasksHash`
5
+ - count every checkbox in `sdd_get_active_task`; File Manifest `*`/`**` for CREATE/MODIFY/READ_ONLY
6
+
7
+ ## [8.1.2] - 2026-09-21
8
+
9
+ - ignore unexpanded `${workspaceFolder}` and a `PLANU_WORKSPACE` equal to `$HOME` so Cursor/Windsurf interpolation stays per-project
10
+ - expand `~/...` in `PLANU_WORKSPACE` against `$HOME` (Cursor may interpolate `${workspaceFolder}` as a tilde path)
11
+ - document project MCP install for Cursor, Claude Code, Windsurf, and Codex
12
+
1
13
  ## [8.1.1] - 2026-09-21
2
14
 
3
15
  - fail closed with `ERR_WORKSPACE_UNRESOLVED` when the resolved workspace is the user home directory without MCP roots or `PLANU_WORKSPACE`
package/README.md CHANGED
@@ -25,20 +25,30 @@ Authentication is **not required**. Do not call `mcp_auth`.
25
25
 
26
26
  ## Installation
27
27
 
28
- Paste this into Claude Code, Cursor, Codex, or any MCP client:
28
+ Paste this into **Claude Code, Cursor, Windsurf, Codex, or any MCP client**. Prefer a **project** config (`.mcp.json` or `.cursor/mcp.json` in the repo you are editing) so the host can bind the open folder. A user-global server with no workspace interpolation will start in `$HOME` and fail closed.
29
29
 
30
30
  ```json
31
31
  {
32
32
  "mcpServers": {
33
33
  "planu": {
34
34
  "command": "npx",
35
- "args": ["-y", "@planu/cli@latest"]
35
+ "args": ["-y", "@planu/cli@latest"],
36
+ "env": {
37
+ "PLANU_WORKSPACE": "${workspaceFolder}"
38
+ }
36
39
  }
37
40
  }
38
41
  }
39
42
  ```
40
43
 
41
- That is the whole install. `npx @planu/cli` starts the MCP stdio server (`cli`, `planu`, and `sdd-engine` are the same binary). Each host restart resolves **latest** from npm.
44
+ | Host | Where to put it | How the project is bound |
45
+ |---|---|---|
46
+ | Cursor | `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` | `${workspaceFolder}` is interpolated into `PLANU_WORKSPACE` (absolute or `~/...`). Cursor user-global `cwd` is not reliable. |
47
+ | Claude Code | `.mcp.json` in the project, or Claude MCP settings | Process cwd is the launch directory; unexpanded `${workspaceFolder}` is ignored. |
48
+ | Windsurf | project MCP config (VS Code-compatible) | Use `${workspaceFolder}` the same way as Cursor. |
49
+ | Codex / other stdio | project MCP or the directory you launched from | Advertise MCP roots, or start the server with cwd = project. |
50
+
51
+ `npx @planu/cli` starts the MCP stdio server (`cli`, `planu`, and `sdd-engine` are the same binary). Each host restart resolves **latest** from npm.
42
52
 
43
53
  Local development in this repo:
44
54
 
@@ -47,14 +57,16 @@ Local development in this repo:
47
57
  "mcpServers": {
48
58
  "planu": {
49
59
  "command": "node",
50
- "args": ["dist/sdd-engine/cli.js"],
51
- "cwd": "/absolute/path/to/sdd-mcp-server"
60
+ "args": ["${workspaceFolder}/dist/sdd-engine/cli.js"],
61
+ "env": {
62
+ "PLANU_WORKSPACE": "${workspaceFolder}"
63
+ }
52
64
  }
53
65
  }
54
66
  }
55
67
  ```
56
68
 
57
- The published server asks the host for MCP roots and binds to the open project that owns `.sdd/`. If the process cwd is the user home directory and roots are missing, project-scoped tools return `ERR_WORKSPACE_UNRESOLVED` instead of creating `.sdd` under `$HOME`. Do not set a global `PLANU_WORKSPACE`: that pins every client to one repo. `PLANU_WORKSPACE` remains an optional per-process override. `pnpm start` runs the MCP server.
69
+ The published server asks the host for MCP roots and binds to the open project that owns `.sdd/`. Unexpanded `${workspaceFolder}` and a `PLANU_WORKSPACE` equal to `$HOME` are ignored. A `~/...` workspace path is expanded against `$HOME` so hosts that interpolate tildes still bind the open folder. If the process cwd is still the user home directory, project-scoped tools return `ERR_WORKSPACE_UNRESOLVED` instead of creating `.sdd` under `$HOME`. `sdd_init_workspace` does not overwrite an existing `AGENTS.md` unless `force: true`. `sdd_lock_spec` refuses empty skeletons and can reseal with `relock: true` and `reason`. Do not set a shell-global `PLANU_WORKSPACE`. `pnpm start` runs the MCP server.
58
70
 
59
71
  **Requirements:** Node.js >= 22.13.
60
72
 
@@ -66,11 +78,12 @@ The published server asks the host for MCP roots and binds to the open project t
66
78
  sdd_init_workspace → sdd_create_feature → architect trinity → sdd_lock_spec → execute tasks → verify → git-janitor
67
79
  ```
68
80
 
69
- 1. **Initialize:** `sdd_init_workspace` writes `.sdd/` and copies `AGENTS.md` plus skills.
81
+ 1. **Initialize:** `sdd_init_workspace` writes `.sdd/` and copies skills. Existing `AGENTS.md` is preserved unless `force: true`.
70
82
  2. **Architect:** Adopt `spec-architect.md`. Call `sdd_create_feature` with a title and omit `id` to reserve the next global `FEAT-NNNN-TITLE` identifier. Explicit `FEAT-*` IDs remain supported for imports; `SPEC-001` is rejected.
71
- 3. **Lock:** `sdd_lock_spec` hashes spec/plan. Do not lock an empty skeleton (cognitive rule).
72
- 4. **Execute:** `sdd_get_active_task` → `sdd_apply_file_patch` → `sdd_complete_task`. CREATE, MODIFY, READ_ONLY, and DELETE permissions are exact manifest entries.
73
- 5. **Verify:** independently prove acceptance criteria with `verification-auditor.md`.\n6. **Janitor:** prune local branches and orphaned worktrees only with authorization.
83
+ 3. **Lock:** `sdd_lock_spec` hashes spec, plan, and tasks. It rejects empty skeletons. Reseal after review with `relock: true` and `reason`.
84
+ 4. **Execute:** `sdd_get_active_task` → `sdd_apply_file_patch` → `sdd_complete_task`. CREATE, MODIFY, and READ_ONLY may use `*` / `**` (dot-prefixed segments require an exact entry). DELETE is an exact path. `.sdd/` and `.git/` are never writable.
85
+ 5. **Verify:** independently prove acceptance criteria with `verification-auditor.md`.
86
+ 6. **Janitor:** prune local branches and orphaned worktrees only with authorization.
74
87
 
75
88
  `sdd_list_features` enumerates executable `.sdd/features/FEAT-*` records only. Historical v6 records are not executed, enumerated, generated, or shipped by the v8 runtime.
76
89
 
@@ -18,6 +18,7 @@ export declare const ErrorCodeSchema: z.ZodEnum<{
18
18
  ERR_FILE_OUT_OF_MANIFEST: "ERR_FILE_OUT_OF_MANIFEST";
19
19
  ERR_INVALID_ARTIFACT: "ERR_INVALID_ARTIFACT";
20
20
  ERR_INVALID_SLICE: "ERR_INVALID_SLICE";
21
+ ERR_LOCK_REASON_REQUIRED: "ERR_LOCK_REASON_REQUIRED";
21
22
  ERR_PATCH_FAILED: "ERR_PATCH_FAILED";
22
23
  ERR_PERMISSION_VIOLATION: "ERR_PERMISSION_VIOLATION";
23
24
  ERR_SPEC_ALREADY_LOCKED: "ERR_SPEC_ALREADY_LOCKED";
@@ -25,6 +26,7 @@ export declare const ErrorCodeSchema: z.ZodEnum<{
25
26
  ERR_SPEC_NOT_LOCKED: "ERR_SPEC_NOT_LOCKED";
26
27
  ERR_TASK_NOT_FOUND: "ERR_TASK_NOT_FOUND";
27
28
  ERR_TASK_OUT_OF_SEQUENCE: "ERR_TASK_OUT_OF_SEQUENCE";
29
+ ERR_TRINITY_INCOMPLETE: "ERR_TRINITY_INCOMPLETE";
28
30
  ERR_WORKSPACE_UNRESOLVED: "ERR_WORKSPACE_UNRESOLVED";
29
31
  }>;
30
32
  export declare const InitWorkspaceInputSchema: z.ZodObject<{
@@ -48,6 +50,8 @@ export declare const CreateFeatureInputSchema: z.ZodObject<{
48
50
  }, z.core.$strip>;
49
51
  export declare const LockSpecInputSchema: z.ZodObject<{
50
52
  feature_id: z.ZodString;
53
+ relock: z.ZodOptional<z.ZodBoolean>;
54
+ reason: z.ZodOptional<z.ZodString>;
51
55
  }, z.core.$strip>;
52
56
  export declare const ReadSpecArtifactInputSchema: z.ZodObject<{
53
57
  feature_id: z.ZodString;
@@ -21,6 +21,8 @@ export const ErrorCodeSchema = z.enum([
21
21
  'ERR_INVALID_ARTIFACT',
22
22
  'ERR_INVALID_SLICE',
23
23
  'ERR_WORKSPACE_UNRESOLVED',
24
+ 'ERR_TRINITY_INCOMPLETE',
25
+ 'ERR_LOCK_REASON_REQUIRED',
24
26
  ]);
25
27
  export const InitWorkspaceInputSchema = z.object({
26
28
  scope: z.enum(['global', 'project']),
@@ -35,6 +37,8 @@ export const CreateFeatureInputSchema = z.object({
35
37
  });
36
38
  export const LockSpecInputSchema = z.object({
37
39
  feature_id: FeatureIdSchema,
40
+ relock: z.boolean().optional(),
41
+ reason: z.string().optional(),
38
42
  });
39
43
  export const ReadSpecArtifactInputSchema = z.object({
40
44
  feature_id: FeatureIdSchema,
@@ -1,3 +1,17 @@
1
- import type { LockIntegrityResult } from '../types/sdd-engine.js';
1
+ import type { ErrorCode, LockIntegrityResult, ParsedManifest } from '../types/sdd-engine.js';
2
+ export declare function hashArtifact(content: string): string;
2
3
  export declare function verifyLockedTrinity(featDir: string): Promise<LockIntegrityResult>;
4
+ export declare function parseManifestContent(content: string): ParsedManifest;
5
+ export declare function toPosixPath(value: string): string;
6
+ export declare function writeLockedTrinity(featDir: string, featureId: string, relock: boolean, reason: string | undefined): Promise<{
7
+ ok: true;
8
+ specHash: string;
9
+ planHash: string;
10
+ tasksHash: string;
11
+ relocked: boolean;
12
+ } | {
13
+ ok: false;
14
+ code: ErrorCode;
15
+ message: string;
16
+ }>;
3
17
  //# sourceMappingURL=lock-integrity.d.ts.map
@@ -1,6 +1,33 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import * as fs from 'node:fs/promises';
3
3
  import * as path from 'node:path';
4
+ const CHECKBOX_TASK = /^[-*]\s*\[[ xX]\]/u;
5
+ export function hashArtifact(content) {
6
+ return createHash('sha256').update(content).digest('hex');
7
+ }
8
+ function assessTrinityCompleteness(specContent, planContent, tasksContent) {
9
+ const specOk = hasHeading(specContent, 'Out-of-Scope') &&
10
+ hasHeading(specContent, 'Error Matrix') &&
11
+ (hasHeading(specContent, 'Acceptance Criteria') || /\bGIVEN\b/u.test(specContent));
12
+ const planOk = hasHeading(planContent, 'Frozen Dependencies') && hasHeading(planContent, 'File Manifest');
13
+ const hasTask = tasksContent.split('\n').some((line) => CHECKBOX_TASK.test(line.trim()));
14
+ const manifest = scanManifest(planContent);
15
+ if (manifest.globDelete) {
16
+ return {
17
+ ok: false,
18
+ code: 'ERR_TRINITY_INCOMPLETE',
19
+ message: 'DELETE File Manifest entries must be exact paths, not globs.',
20
+ };
21
+ }
22
+ if (specOk && planOk && hasTask && manifest.hasPath) {
23
+ return { ok: true };
24
+ }
25
+ return {
26
+ ok: false,
27
+ code: 'ERR_TRINITY_INCOMPLETE',
28
+ message: 'Lock requires Out-of-Scope, Error Matrix, Acceptance Criteria or GIVEN, Frozen Dependencies, a File Manifest path, and at least one checkbox task.',
29
+ };
30
+ }
4
31
  export async function verifyLockedTrinity(featDir) {
5
32
  const lockPath = path.join(featDir, '.lock');
6
33
  let raw;
@@ -38,15 +65,162 @@ export async function verifyLockedTrinity(featDir) {
38
65
  message: `Failed to read locked artifacts at '${featDir}'.`,
39
66
  };
40
67
  }
41
- const specHash = createHash('sha256').update(specContent).digest('hex');
42
- const planHash = createHash('sha256').update(planContent).digest('hex');
43
- if (specHash !== lock.specHash || planHash !== lock.planHash) {
68
+ if (hashArtifact(specContent) !== lock.specHash || hashArtifact(planContent) !== lock.planHash) {
44
69
  return {
45
70
  ok: false,
46
71
  code: 'ERR_SPEC_DRIFT',
47
72
  message: 'Locked spec.md or plan.md changed after sdd_lock_spec. Re-lock is required.',
48
73
  };
49
74
  }
75
+ if (lock.tasksHash) {
76
+ let tasksContent;
77
+ try {
78
+ tasksContent = await fs.readFile(path.join(featDir, 'tasks.md'), 'utf-8');
79
+ }
80
+ catch {
81
+ return {
82
+ ok: false,
83
+ code: 'ERR_SPEC_DRIFT',
84
+ message: 'Locked tasks.md is missing after sdd_lock_spec. Re-lock is required.',
85
+ };
86
+ }
87
+ if (hashArtifact(tasksContent) !== lock.tasksHash) {
88
+ return {
89
+ ok: false,
90
+ code: 'ERR_SPEC_DRIFT',
91
+ message: 'Locked tasks.md changed after sdd_lock_spec. Re-lock is required.',
92
+ };
93
+ }
94
+ }
50
95
  return { ok: true };
51
96
  }
97
+ function hasHeading(content, needle) {
98
+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
99
+ return new RegExp(`^#{1,3}\\s+.*${escaped}`, 'imu').test(content);
100
+ }
101
+ function scanManifest(planContent) {
102
+ const { allowedFiles } = parseManifestContent(planContent);
103
+ let globDelete = false;
104
+ for (const [entryPath, permission] of allowedFiles) {
105
+ if (permission === 'DELETE' && entryPath.includes('*')) {
106
+ globDelete = true;
107
+ }
108
+ }
109
+ return { hasPath: allowedFiles.size > 0, globDelete };
110
+ }
111
+ export function parseManifestContent(content) {
112
+ const allowedFiles = new Map();
113
+ let inManifestSection = false;
114
+ for (const rawLine of content.split('\n')) {
115
+ const line = rawLine.trim();
116
+ if (/^#{1,3}\s+.*file\s+manifest/i.test(line)) {
117
+ inManifestSection = true;
118
+ continue;
119
+ }
120
+ if (inManifestSection && /^#{1,3}\s+/.test(line)) {
121
+ break;
122
+ }
123
+ if (inManifestSection && /^[-*]\s+/.test(line)) {
124
+ parseManifestLine(line, allowedFiles);
125
+ }
126
+ }
127
+ return { allowedFiles };
128
+ }
129
+ function parseManifestLine(rawLine, allowedFiles) {
130
+ const item = rawLine.replace(/^[-*]\s+/, '').trim();
131
+ const prefixMatch = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item);
132
+ if (prefixMatch?.[1] && prefixMatch[2]) {
133
+ allowedFiles.set(toPosixPath(prefixMatch[2].trim()), prefixMatch[1].toUpperCase());
134
+ return;
135
+ }
136
+ const postfixMatch = /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
137
+ if (postfixMatch?.[1] && postfixMatch[2]) {
138
+ allowedFiles.set(toPosixPath(postfixMatch[1].trim()), postfixMatch[2].toUpperCase());
139
+ }
140
+ }
141
+ export function toPosixPath(value) {
142
+ const posix = value.replaceAll('\\', '/');
143
+ const absolute = posix.startsWith('/');
144
+ const joined = posix
145
+ .split('/')
146
+ .filter((part) => part !== '' && part !== '.')
147
+ .join('/');
148
+ return absolute ? `/${joined}` : joined;
149
+ }
150
+ export async function writeLockedTrinity(featDir, featureId, relock, reason) {
151
+ const lockPath = path.join(featDir, '.lock');
152
+ const lockExists = await fs
153
+ .access(lockPath)
154
+ .then(() => true)
155
+ .catch(() => false);
156
+ if (lockExists && !relock) {
157
+ return {
158
+ ok: false,
159
+ code: 'ERR_SPEC_ALREADY_LOCKED',
160
+ message: `Feature '${featureId}' is already locked for execution.`,
161
+ };
162
+ }
163
+ const trimmedReason = reason?.trim() ?? '';
164
+ if (relock && trimmedReason.length < 8) {
165
+ return {
166
+ ok: false,
167
+ code: 'ERR_LOCK_REASON_REQUIRED',
168
+ message: 'relock requires reason with at least 8 non-whitespace characters.',
169
+ };
170
+ }
171
+ return sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, relock, trimmedReason);
172
+ }
173
+ async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, relock, trimmedReason) {
174
+ let specContent;
175
+ let planContent;
176
+ let tasksContent;
177
+ try {
178
+ specContent = await fs.readFile(path.join(featDir, 'spec.md'), 'utf-8');
179
+ planContent = await fs.readFile(path.join(featDir, 'plan.md'), 'utf-8');
180
+ tasksContent = await fs.readFile(path.join(featDir, 'tasks.md'), 'utf-8');
181
+ }
182
+ catch {
183
+ return {
184
+ ok: false,
185
+ code: 'ERR_FEATURE_NOT_FOUND',
186
+ message: `Failed to read base artifacts for '${featureId}'.`,
187
+ };
188
+ }
189
+ const completeness = assessTrinityCompleteness(specContent, planContent, tasksContent);
190
+ if (!completeness.ok) {
191
+ return { ok: false, code: completeness.code, message: completeness.message };
192
+ }
193
+ let previous;
194
+ if (lockExists) {
195
+ try {
196
+ previous = JSON.parse(await fs.readFile(lockPath, 'utf-8'));
197
+ }
198
+ catch {
199
+ previous = undefined;
200
+ }
201
+ }
202
+ const specHash = hashArtifact(specContent);
203
+ const planHash = hashArtifact(planContent);
204
+ const tasksHash = hashArtifact(tasksContent);
205
+ const lockedAt = new Date().toISOString();
206
+ const history = [...(previous?.relockHistory ?? [])];
207
+ if (relock && previous?.specHash && previous.planHash) {
208
+ history.push({
209
+ lockedAt: previous.lockedAt ?? lockedAt,
210
+ specHash: previous.specHash,
211
+ planHash: previous.planHash,
212
+ tasksHash: previous.tasksHash,
213
+ reason: trimmedReason,
214
+ });
215
+ }
216
+ const lockFile = {
217
+ lockedAt,
218
+ specHash,
219
+ planHash,
220
+ tasksHash,
221
+ ...(history.length > 0 ? { relockHistory: history } : {}),
222
+ };
223
+ await fs.writeFile(lockPath, JSON.stringify(lockFile, null, 2), 'utf-8');
224
+ return { ok: true, specHash, planHash, tasksHash, relocked: relock };
225
+ }
52
226
  //# sourceMappingURL=lock-integrity.js.map
@@ -3,12 +3,12 @@ export declare class PatchSandbox {
3
3
  private readonly workspaceRoot;
4
4
  constructor(workspaceRoot: string);
5
5
  parsePlanManifest(planPath: string): Promise<ParsedManifest>;
6
- private parseManifestLine;
7
6
  applyPatch(manifest: ParsedManifest, targetRelativePath: string, searchContent: string, replaceContent: string): Promise<SddResult<PatchResultData>>;
8
7
  private validateTargetContainment;
8
+ private rejectsProtectedRoot;
9
+ private rejectsResolvedProtectedRoot;
9
10
  private isRawProtectedDelete;
10
11
  private validateCreateTargetAbsent;
11
- private isGitMetadataTarget;
12
12
  private nearestExistingParent;
13
13
  private isWithin;
14
14
  private permissionViolation;
@@ -1,53 +1,22 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
+ import { parseManifestContent, toPosixPath } from './lock-integrity.js';
3
4
  export class PatchSandbox {
4
5
  workspaceRoot;
5
6
  constructor(workspaceRoot) {
6
7
  this.workspaceRoot = workspaceRoot;
7
8
  }
8
9
  async parsePlanManifest(planPath) {
9
- const allowedFiles = new Map();
10
- let content;
11
10
  try {
12
- content = await fs.readFile(planPath, 'utf-8');
11
+ return parseManifestContent(await fs.readFile(planPath, 'utf-8'));
13
12
  }
14
13
  catch {
15
- return { allowedFiles };
16
- }
17
- const lines = content.split('\n');
18
- let inManifestSection = false;
19
- for (const rawLine of lines) {
20
- const line = rawLine.trim();
21
- if (/^#{1,3}\s+.*file\s+manifest/i.test(line)) {
22
- inManifestSection = true;
23
- continue;
24
- }
25
- if (inManifestSection && /^#{1,3}\s+/.test(line)) {
26
- break;
27
- }
28
- if (inManifestSection && /^[-*]\s+/.test(line)) {
29
- this.parseManifestLine(line, allowedFiles);
30
- }
31
- }
32
- return { allowedFiles };
33
- }
34
- parseManifestLine(rawLine, allowedFiles) {
35
- const item = rawLine.replace(/^[-*]\s+/, '').trim();
36
- const prefixMatch = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item);
37
- if (prefixMatch?.[1] && prefixMatch[2]) {
38
- const perm = prefixMatch[1].toUpperCase();
39
- allowedFiles.set(path.normalize(prefixMatch[2].trim()), perm);
40
- return;
41
- }
42
- const postfixMatch = /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
43
- if (postfixMatch?.[1] && postfixMatch[2]) {
44
- const perm = postfixMatch[2].toUpperCase();
45
- allowedFiles.set(path.normalize(postfixMatch[1].trim()), perm);
14
+ return { allowedFiles: new Map() };
46
15
  }
47
16
  }
48
17
  async applyPatch(manifest, targetRelativePath, searchContent, replaceContent) {
49
- const normalizedTarget = path.normalize(targetRelativePath);
50
- const permission = manifest.allowedFiles.get(normalizedTarget);
18
+ const normalizedTarget = toPosixPath(targetRelativePath);
19
+ const permission = resolveManifestPermission(manifest.allowedFiles, normalizedTarget);
51
20
  if (!permission) {
52
21
  return {
53
22
  success: false,
@@ -88,8 +57,7 @@ export class PatchSandbox {
88
57
  if (!this.isWithin(workspacePath, fullPath)) {
89
58
  return this.permissionViolation(normalizedTarget);
90
59
  }
91
- if (permission === 'DELETE' &&
92
- this.isRawProtectedDelete(workspacePath, fullPath, normalizedTarget)) {
60
+ if (this.rejectsProtectedRoot(workspacePath, fullPath, normalizedTarget, permission)) {
93
61
  return this.permissionViolation(normalizedTarget);
94
62
  }
95
63
  const createError = permission === 'CREATE'
@@ -106,8 +74,7 @@ export class PatchSandbox {
106
74
  if (!this.isWithin(workspaceRealPath, containmentTarget)) {
107
75
  return this.permissionViolation(normalizedTarget);
108
76
  }
109
- if (permission === 'DELETE' &&
110
- (await this.isGitMetadataTarget(workspaceRealPath, containmentTarget))) {
77
+ if (await this.rejectsResolvedProtectedRoot(workspaceRealPath, containmentTarget)) {
111
78
  return this.permissionViolation(normalizedTarget);
112
79
  }
113
80
  }
@@ -118,10 +85,28 @@ export class PatchSandbox {
118
85
  }
119
86
  return null;
120
87
  }
121
- isRawProtectedDelete(workspacePath, fullPath, normalizedTarget) {
122
- return (fullPath === workspacePath ||
123
- normalizedTarget === '.git' ||
124
- normalizedTarget.startsWith(`.git${path.sep}`));
88
+ rejectsProtectedRoot(workspacePath, fullPath, normalizedTarget, permission) {
89
+ const sddRoot = path.resolve(workspacePath, '.sdd');
90
+ const gitRoot = path.resolve(workspacePath, '.git');
91
+ if (isSddEnginePath(normalizedTarget) ||
92
+ isGitPath(normalizedTarget) ||
93
+ this.isWithin(sddRoot, fullPath) ||
94
+ this.isWithin(gitRoot, fullPath)) {
95
+ return true;
96
+ }
97
+ return permission === 'DELETE' && this.isRawProtectedDelete(workspacePath, fullPath);
98
+ }
99
+ async rejectsResolvedProtectedRoot(workspaceRealPath, containmentTarget) {
100
+ for (const dirName of ['.sdd', '.git']) {
101
+ const realRoot = await fs.realpath(path.join(workspaceRealPath, dirName)).catch(() => null);
102
+ if (realRoot && this.isWithin(realRoot, containmentTarget)) {
103
+ return true;
104
+ }
105
+ }
106
+ return false;
107
+ }
108
+ isRawProtectedDelete(workspacePath, fullPath) {
109
+ return fullPath === workspacePath;
125
110
  }
126
111
  async validateCreateTargetAbsent(fullPath, normalizedTarget) {
127
112
  try {
@@ -134,18 +119,6 @@ export class PatchSandbox {
134
119
  : this.permissionViolation(normalizedTarget);
135
120
  }
136
121
  }
137
- async isGitMetadataTarget(workspaceRealPath, containmentTarget) {
138
- try {
139
- const gitRealPath = await fs.realpath(path.join(workspaceRealPath, '.git'));
140
- return this.isWithin(gitRealPath, containmentTarget);
141
- }
142
- catch (err) {
143
- if (this.isNodeErrorCode(err, 'ENOENT')) {
144
- return false;
145
- }
146
- throw err;
147
- }
148
- }
149
122
  async nearestExistingParent(candidate, workspacePath) {
150
123
  let current = candidate;
151
124
  while (this.isWithin(workspacePath, current)) {
@@ -296,4 +269,68 @@ export class PatchSandbox {
296
269
  }
297
270
  }
298
271
  }
272
+ function resolveManifestPermission(allowedFiles, normalizedTarget) {
273
+ const exact = allowedFiles.get(normalizedTarget);
274
+ if (exact) {
275
+ return exact;
276
+ }
277
+ let writeMatch;
278
+ for (const [pattern, permission] of allowedFiles) {
279
+ if (permission === 'DELETE' ||
280
+ !pattern.includes('*') ||
281
+ !globMatches(pattern, normalizedTarget)) {
282
+ continue;
283
+ }
284
+ if (permission === 'READ_ONLY') {
285
+ return 'READ_ONLY';
286
+ }
287
+ writeMatch ??= permission;
288
+ }
289
+ return writeMatch;
290
+ }
291
+ function globMatches(pattern, target) {
292
+ const posixPattern = toPosixPath(pattern);
293
+ const posixTarget = toPosixPath(target);
294
+ if (posixPattern.split('/').includes('..') ||
295
+ posixTarget.split('/').includes('..') ||
296
+ path.isAbsolute(posixPattern) ||
297
+ path.isAbsolute(posixTarget)) {
298
+ return false;
299
+ }
300
+ return new RegExp(`^${globPatternToRegExpSource(posixPattern)}$`).test(posixTarget);
301
+ }
302
+ function isSddEnginePath(relativePath) {
303
+ const posix = toPosixPath(relativePath);
304
+ return posix === '.sdd' || posix.startsWith('.sdd/');
305
+ }
306
+ function isGitPath(relativePath) {
307
+ const posix = toPosixPath(relativePath);
308
+ return posix === '.git' || posix.startsWith('.git/');
309
+ }
310
+ function globPatternToRegExpSource(pattern) {
311
+ let source = '';
312
+ for (let i = 0; i < pattern.length; i++) {
313
+ const char = pattern[i] ?? '';
314
+ if (char === '*' && pattern[i + 1] === '*') {
315
+ i += 1;
316
+ if (pattern[i + 1] === '/') {
317
+ i += 1;
318
+ source += '(?:(?![.])[^/]+/)*';
319
+ }
320
+ else {
321
+ source += '(?:(?![.])[^/]+/)*(?:(?![.])[^/]+)?';
322
+ }
323
+ }
324
+ else if (char === '*') {
325
+ source += '(?![.])[^/]+';
326
+ }
327
+ else if ('\\^$+?.()|[]{}'.includes(char)) {
328
+ source += `\\${char}`;
329
+ }
330
+ else {
331
+ source += char;
332
+ }
333
+ }
334
+ return source;
335
+ }
299
336
  //# sourceMappingURL=patch-sandbox.js.map
@@ -4,7 +4,7 @@ import { registerUltralightSddTools } from './tools.js';
4
4
  export function createUltralightSddServer(workspaceRoot) {
5
5
  const server = new McpServer({
6
6
  name: 'sdd-engine',
7
- version: '8.1.1',
7
+ version: '8.2.0',
8
8
  }, {
9
9
  capabilities: {
10
10
  tools: {},
@@ -1,4 +1,6 @@
1
1
  import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { hashArtifact } from './lock-integrity.js';
2
4
  export class TaskWindowManager {
3
5
  async getActiveTask(tasksFilePath) {
4
6
  let content;
@@ -66,22 +68,19 @@ export class TaskWindowManager {
66
68
  if (statusChar === 'x') {
67
69
  acc.completedTasks++;
68
70
  if (acc.isCapturingActive) {
69
- break;
71
+ acc.isCapturingActive = false;
70
72
  }
71
73
  }
72
- else {
73
- if (!acc.isCapturingActive && acc.activeTaskIndex === -1) {
74
- acc.isCapturingActive = true;
75
- acc.activeTaskIndex = acc.totalTasks;
76
- const parsed = this.extractTaskId(match[2].trim(), acc.activeTaskIndex);
77
- acc.activeTaskId = parsed.id;
78
- acc.activeTaskTitle = parsed.title;
79
- acc.activeTaskLines.push(line);
80
- continue;
81
- }
82
- if (acc.isCapturingActive) {
83
- break;
84
- }
74
+ else if (!acc.isCapturingActive && acc.activeTaskIndex === -1) {
75
+ acc.isCapturingActive = true;
76
+ acc.activeTaskIndex = acc.totalTasks;
77
+ const parsed = this.extractTaskId(match[2].trim(), acc.activeTaskIndex);
78
+ acc.activeTaskId = parsed.id;
79
+ acc.activeTaskTitle = parsed.title;
80
+ acc.activeTaskLines.push(line);
81
+ }
82
+ else if (acc.isCapturingActive) {
83
+ acc.isCapturingActive = false;
85
84
  }
86
85
  }
87
86
  else if (acc.isCapturingActive) {
@@ -152,6 +151,7 @@ export class TaskWindowManager {
152
151
  };
153
152
  }
154
153
  await fs.writeFile(tasksFilePath, lines.join('\n'), 'utf-8');
154
+ await refreshTasksHashIfLocked(tasksFilePath, lines.join('\n'));
155
155
  const checkRes = await this.getActiveTask(tasksFilePath);
156
156
  const remainingTasks = checkRes.success && checkRes.data.activeTask
157
157
  ? checkRes.data.activeTask.totalTasks - checkRes.data.activeTask.completedTasks
@@ -166,4 +166,25 @@ export class TaskWindowManager {
166
166
  };
167
167
  }
168
168
  }
169
+ async function refreshTasksHashIfLocked(tasksFilePath, tasksContent) {
170
+ const lockPath = path.join(path.dirname(tasksFilePath), '.lock');
171
+ let raw;
172
+ try {
173
+ raw = await fs.readFile(lockPath, 'utf-8');
174
+ }
175
+ catch {
176
+ return;
177
+ }
178
+ try {
179
+ const lock = JSON.parse(raw);
180
+ if (!lock.tasksHash) {
181
+ return;
182
+ }
183
+ lock.tasksHash = hashArtifact(tasksContent);
184
+ await fs.writeFile(lockPath, JSON.stringify(lock, null, 2), 'utf-8');
185
+ }
186
+ catch {
187
+ return;
188
+ }
189
+ }
169
190
  //# sourceMappingURL=task-window.js.map
@@ -1,12 +1,12 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
3
  import { fileURLToPath } from 'node:url';
5
4
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
6
5
  import { InitWorkspaceInputSchema, ListFeaturesInputSchema, CreateFeatureInputSchema, LockSpecInputSchema, } from '../contracts.js';
7
6
  import { TaskWindowManager } from '../task-window.js';
8
7
  import { formatResult } from './format-result.js';
9
8
  import { homeFallbackFailure } from '../workspace-root.js';
9
+ import { writeLockedTrinity } from '../lock-integrity.js';
10
10
  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.';
11
11
  export function registerWorkspaceTools(server, workspace) {
12
12
  const taskWindow = new TaskWindowManager();
@@ -36,7 +36,7 @@ function registerInitTool(server, workspace) {
36
36
  await fs.mkdir(featuresDir, { recursive: true });
37
37
  await fs.mkdir(skillsDir, { recursive: true });
38
38
  await copySkillTemplates(skillsDir);
39
- await copyGlobalRules(resolved.workspaceRoot);
39
+ const agentsMd = await copyGlobalRules(resolved.workspaceRoot, args.force);
40
40
  return formatResult({
41
41
  success: true,
42
42
  data: {
@@ -46,6 +46,8 @@ function registerInitTool(server, workspace) {
46
46
  skillsDir,
47
47
  workspaceRoot: resolved.workspaceRoot,
48
48
  source: resolved.source,
49
+ agentsMd,
50
+ versionedHint: 'Commit .sdd/ with the project. Host quality gates must map .sdd/ as versioned documentation.',
49
51
  },
50
52
  });
51
53
  });
@@ -191,7 +193,7 @@ function createFeatureSlug(title) {
191
193
  }
192
194
  function registerLockTool(server, workspace) {
193
195
  server.registerTool('sdd_lock_spec', {
194
- description: 'Locks spec.md and plan.md with cryptographic digests to enable execution phase.',
196
+ description: 'Locks spec.md, plan.md, and tasks.md. Pass relock=true and reason to reseal after review.',
195
197
  inputSchema: LockSpecInputSchema.shape,
196
198
  }, async (rawArgs) => {
197
199
  const args = LockSpecInputSchema.parse(rawArgs);
@@ -201,7 +203,7 @@ function registerLockTool(server, workspace) {
201
203
  return formatResult(homeError);
202
204
  }
203
205
  const featDir = path.join(resolved.sddDir, 'features', args.feature_id);
204
- return executeLockSpec(featDir, args.feature_id);
206
+ return executeLockSpec(featDir, args.feature_id, args.relock === true, args.reason);
205
207
  });
206
208
  }
207
209
  function isNodeErrorCode(err, code) {
@@ -223,15 +225,23 @@ async function copySkillTemplates(skillsDir) {
223
225
  await fs.writeFile(path.join(skillsDir, 'spec-executor.md'), '# Spec Executor Skill\n\nOperate in Zero-Freedom mode.\n', 'utf-8');
224
226
  }
225
227
  }
226
- async function copyGlobalRules(workspaceRoot) {
228
+ async function copyGlobalRules(workspaceRoot, force) {
227
229
  const sourcePath = path.resolve(moduleDir, '..', '..', '..', 'templates', 'AGENTS.md');
228
230
  const targetPath = path.resolve(workspaceRoot, 'AGENTS.md');
231
+ const existed = await fs
232
+ .access(targetPath)
233
+ .then(() => true)
234
+ .catch(() => false);
235
+ if (existed && force !== true) {
236
+ return 'preserved';
237
+ }
229
238
  try {
230
239
  const content = await fs.readFile(sourcePath, 'utf-8');
231
240
  await fs.writeFile(targetPath, content, 'utf-8');
241
+ return existed ? 'replaced' : 'created';
232
242
  }
233
243
  catch {
234
- // Ignore if not found
244
+ return existed ? 'preserved' : 'created';
235
245
  }
236
246
  }
237
247
  async function collectFeatures(featuresDir, taskWindow, statusFilter) {
@@ -272,44 +282,24 @@ async function writeFeatureArtifacts(featDir, id, title) {
272
282
  await fs.writeFile(path.join(featDir, 'plan.md'), initialPlan, 'utf-8');
273
283
  await fs.writeFile(path.join(featDir, 'tasks.md'), initialTasks, 'utf-8');
274
284
  }
275
- async function executeLockSpec(featDir, featureId) {
276
- const lockPath = path.join(featDir, '.lock');
277
- const lockExists = await fs
278
- .access(lockPath)
279
- .then(() => true)
280
- .catch(() => false);
281
- if (lockExists) {
282
- return formatResult({
283
- success: false,
284
- error: {
285
- code: 'ERR_SPEC_ALREADY_LOCKED',
286
- message: `Feature '${featureId}' is already locked for execution.`,
287
- trigger: 'sdd_lock_spec',
288
- },
289
- });
290
- }
291
- let specContent;
292
- let planContent;
293
- try {
294
- specContent = await fs.readFile(path.join(featDir, 'spec.md'), 'utf-8');
295
- planContent = await fs.readFile(path.join(featDir, 'plan.md'), 'utf-8');
296
- }
297
- catch {
285
+ async function executeLockSpec(featDir, featureId, relock, reason) {
286
+ const outcome = await writeLockedTrinity(featDir, featureId, relock, reason);
287
+ if (!outcome.ok) {
298
288
  return formatResult({
299
289
  success: false,
300
- error: {
301
- code: 'ERR_FEATURE_NOT_FOUND',
302
- message: `Failed to read base artifacts for '${featureId}'.`,
303
- trigger: 'sdd_lock_spec',
304
- },
290
+ error: { code: outcome.code, message: outcome.message, trigger: 'sdd_lock_spec' },
305
291
  });
306
292
  }
307
- const specHash = createHash('sha256').update(specContent).digest('hex');
308
- const planHash = createHash('sha256').update(planContent).digest('hex');
309
- await fs.writeFile(lockPath, JSON.stringify({ lockedAt: new Date().toISOString(), specHash, planHash }, null, 2), 'utf-8');
310
293
  return formatResult({
311
294
  success: true,
312
- data: { featureId, locked: true, specHash, planHash },
295
+ data: {
296
+ featureId,
297
+ locked: true,
298
+ specHash: outcome.specHash,
299
+ planHash: outcome.planHash,
300
+ tasksHash: outcome.tasksHash,
301
+ relocked: outcome.relocked,
302
+ },
313
303
  });
314
304
  }
315
305
  //# sourceMappingURL=workspace-tools.js.map
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
2
+ import { dirname, join, resolve, sep } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  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.';
5
5
  export function parseMcpRootUri(uri) {
@@ -29,9 +29,9 @@ export function resolveSddWorkspace(input = {}) {
29
29
  if (input.pinnedRoot?.trim()) {
30
30
  return finish(resolve(input.pinnedRoot.trim()), 'pin');
31
31
  }
32
- const fromEnv = env.PLANU_WORKSPACE?.trim();
32
+ const fromEnv = usablePlanuWorkspaceEnv(env);
33
33
  if (fromEnv) {
34
- return finish(resolve(fromEnv), 'env');
34
+ return finish(fromEnv, 'env');
35
35
  }
36
36
  const mcpDirs = unique((input.mcpRootUris ?? [])
37
37
  .map((uri) => parseMcpRootUri(uri))
@@ -96,6 +96,37 @@ function isHomeDirectory(dir, env) {
96
96
  }
97
97
  return resolve(dir) === resolve(home);
98
98
  }
99
+ function usablePlanuWorkspaceEnv(env) {
100
+ const fromEnv = env.PLANU_WORKSPACE?.trim();
101
+ if (!fromEnv || fromEnv.includes('${')) {
102
+ return null;
103
+ }
104
+ const expanded = expandHomePrefix(fromEnv, env);
105
+ if (!expanded) {
106
+ return null;
107
+ }
108
+ const resolved = resolve(expanded);
109
+ if (resolved.includes(`${sep}~${sep}`) || resolved.endsWith(`${sep}~`)) {
110
+ return null;
111
+ }
112
+ if (isHomeDirectory(resolved, env)) {
113
+ return null;
114
+ }
115
+ return resolved;
116
+ }
117
+ function expandHomePrefix(raw, env) {
118
+ if (raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')) {
119
+ const home = env.HOME?.trim() ?? env.USERPROFILE?.trim();
120
+ if (!home) {
121
+ return null;
122
+ }
123
+ if (raw === '~') {
124
+ return home;
125
+ }
126
+ return join(home, raw.slice(2));
127
+ }
128
+ return raw;
129
+ }
99
130
  function unique(values) {
100
131
  const seen = new Set();
101
132
  const out = [];
@@ -1,6 +1,6 @@
1
1
  export type ArtifactType = 'spec' | 'plan' | 'tasks';
2
2
  export type FilePermission = 'CREATE' | 'MODIFY' | 'READ_ONLY' | 'DELETE';
3
- export type ErrorCode = 'ERR_FEATURE_NOT_FOUND' | 'ERR_FEATURE_ALREADY_EXISTS' | 'ERR_SPEC_NOT_LOCKED' | 'ERR_SPEC_ALREADY_LOCKED' | 'ERR_SPEC_DRIFT' | 'ERR_TASK_OUT_OF_SEQUENCE' | 'ERR_TASK_NOT_FOUND' | 'ERR_FILE_OUT_OF_MANIFEST' | 'ERR_PERMISSION_VIOLATION' | 'ERR_PATCH_FAILED' | 'ERR_INVALID_ARTIFACT' | 'ERR_INVALID_SLICE' | 'ERR_WORKSPACE_UNRESOLVED';
3
+ export type ErrorCode = 'ERR_FEATURE_NOT_FOUND' | 'ERR_FEATURE_ALREADY_EXISTS' | 'ERR_SPEC_NOT_LOCKED' | 'ERR_SPEC_ALREADY_LOCKED' | 'ERR_SPEC_DRIFT' | 'ERR_TASK_OUT_OF_SEQUENCE' | 'ERR_TASK_NOT_FOUND' | 'ERR_FILE_OUT_OF_MANIFEST' | 'ERR_PERMISSION_VIOLATION' | 'ERR_PATCH_FAILED' | 'ERR_INVALID_ARTIFACT' | 'ERR_INVALID_SLICE' | 'ERR_WORKSPACE_UNRESOLVED' | 'ERR_TRINITY_INCOMPLETE' | 'ERR_LOCK_REASON_REQUIRED';
4
4
  export interface SddErrorDetails {
5
5
  code: ErrorCode;
6
6
  message: string;
@@ -29,6 +29,8 @@ export interface CreateFeatureInput {
29
29
  }
30
30
  export interface LockSpecInput {
31
31
  feature_id: string;
32
+ relock?: boolean;
33
+ reason?: string;
32
34
  }
33
35
  export interface ReadSpecArtifactInput {
34
36
  feature_id: string;
@@ -93,9 +95,19 @@ export interface FeatureSummary {
93
95
  status: 'planning' | 'executing' | 'done';
94
96
  locked: boolean;
95
97
  }
98
+ export interface RelockRecord {
99
+ lockedAt: string;
100
+ specHash: string;
101
+ planHash: string;
102
+ tasksHash?: string;
103
+ reason: string;
104
+ }
96
105
  export interface SddLockFile {
106
+ lockedAt?: string;
97
107
  specHash?: string;
98
108
  planHash?: string;
109
+ tasksHash?: string;
110
+ relockHistory?: RelockRecord[];
99
111
  }
100
112
  export interface LockIntegrityResult {
101
113
  ok: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planu/cli",
3
- "version": "8.1.1",
3
+ "version": "8.2.0",
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",
@@ -19,8 +19,8 @@ Your objective is to safely adapt `plan.md` and `tasks.md` when business require
19
19
  - Do NOT rewrite the history of completed tasks; only adjust pending tasks or add new ones.
20
20
 
21
21
  3. **Locked features:**
22
- - The engine has no unlock tool. Do not silently edit a locked `spec.md` / `plan.md`.
23
- - File a new `FEAT-*` with `sdd_create_feature` for the delta, or stop and report that lock must be lifted by a future engine capability.
22
+ - Do not silently edit a locked `spec.md` / `plan.md` / `tasks.md`.
23
+ - After an approved review correction, reseal with `sdd_lock_spec` (`relock: true`, `reason`) so hashes and history stay traced.
24
24
 
25
25
  4. **Language:**
26
26
  - ALL updates to artifacts MUST be written entirely in Technical English.
@@ -30,7 +30,9 @@ Your objective is to produce airtight, deterministic, and unambiguous specificat
30
30
  - `CREATE: path/to/file`
31
31
  - `MODIFY: path/to/file`
32
32
  - `READ_ONLY: path/to/file`
33
- - `DELETE: path/to/file-or-directory`
33
+ - `DELETE: path/to/file-or-directory` (exact path only; no globs)
34
+ - CREATE, MODIFY, and READ_ONLY may use `*` (one path segment) or `**` (many segments).
35
+ - `sdd_lock_spec` rejects incomplete trinities. Reseal after review with `relock: true` and `reason`.
34
36
  - *Crucial Rule:* The MCP server rejects any file edit not declared in this manifest (`ERR_FILE_OUT_OF_MANIFEST`).
35
37
 
36
38
  5. **Atomic Linear Tasks in `tasks.md`:**