@planu/cli 8.10.0 → 8.12.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,16 @@
1
+ ## [8.12.0] - 2026-11-16
2
+
3
+ - Bind task completion strictly to the active first open task checkbox, preventing implicit task IDs from matching prose in later task titles.
4
+ - Reject malformed File Manifest bullets and duplicate explicit task IDs during lock validation with exact 1-based line diagnostics.
5
+ - Include bounded match line numbers, line-ending mismatch flags, and slice line-number prefix diagnostics on MODIFY patch failures.
6
+ - Refresh direct secretlint development dependencies to 14.0.0.
7
+
8
+ ## [8.11.0]
9
+
10
+ - Add versioned static advisory next actions to engine-formatted failures, exposed by the version 1 capability descriptor.
11
+ - Keep SDK and protocol errors before dispatch separate; existing details are not globally redacted. Uncertainty and mutation cancellation select recovery guidance; only read tools can advise retrying a read. A scoped verification process failure retains failure inspection guidance.
12
+ - Preserve the nine-tool surface; guidance grants no retry, verification time or write authority.
13
+
1
14
  ## [8.10.0] - 2026-11-15
2
15
 
3
16
  - Add an opt-in compact feature catalogue with literal ID query, status filtering and pages of 16 by default, up to 32 entries.
package/README.md CHANGED
@@ -144,6 +144,8 @@ The reviewed operator procedure is in the repository guide `docs/verification-bu
144
144
 
145
145
  ## Read-only diagnostics
146
146
 
147
+ For failure guidance, require `engineCapabilities.version=1` and `observations.errorNextAction=1` in setup diagnostics. Engine-produced formatted failures contain static `details.nextActionVersion=1` and `details.nextAction`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects `inspect_recovery`. Reasons `cancelled` or `verification_cancelled` select it for mutations; only the four read tools may advise `retry_read`. A scoped `verification_process_failed` keeps `inspect_failure` even when `cancelled=true`. Actions grant no retry, verification time or write authority.
148
+
147
149
  For an opt-in feature catalogue, first require `engineCapabilities.version=1`, `views.sdd_list_features` containing `catalogue`, and `observations.featureCatalogue=1` in setup diagnostics. Request `view="catalogue"` and follow each non-null `nextCursor` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
148
150
 
149
151
  For an opt-in bounded source read, first require `engineCapabilities.version=1`, `views.sdd_read_file_slice` containing `bounded`, and `observations.sourceSlice=1` in setup diagnostics. Treat absent or unknown versions or capability values as unsupported; never probe a mutation. Request `sdd_read_file_slice` with `view="bounded"`, a path and line range, then follow each non-null `nextCursor` read-only on the same server instance with the same normalized path and range. The cursor binds the server, root, request and physical snapshot; the snapshot digest is not a checksum of file contents. The default legacy read remains unchanged.
@@ -157,7 +159,7 @@ The existing nine tools expose additive diagnostics since 8.4.0; 8.5.0 adds comp
157
159
  ```json
158
160
  {
159
161
  "version": 1,
160
- "bundledVersion": "8.10.0",
162
+ "bundledVersion": "8.12.0",
161
163
  "baseline": "available",
162
164
  "catalog": "unverified",
163
165
  "issues": [{
@@ -390,7 +392,7 @@ See the [Planu Proprietary Free-Use License](LICENSE) and [planu.dev/license](ht
390
392
  "mcpServers": {
391
393
  "planu": {
392
394
  "command": "npx",
393
- "args": ["-y", "@planu/cli@8.10.0"],
395
+ "args": ["-y", "@planu/cli@8.12.0"],
394
396
  "cwd": ".",
395
397
  "env": {
396
398
  "PLANU_WORKSPACE": "."
@@ -1,3 +1,4 @@
1
+ import type * as engine from '../types/sdd-engine.js';
1
2
  import type { ListFeaturesInput, SddResult } from '../types/sdd-engine.js';
2
3
  import type { EngineCapabilitiesV1 } from '../types/resume-views.js';
3
4
  import { z } from 'zod';
@@ -68,4 +69,75 @@ export declare function boundedWorkspaceHint(parts: (string | undefined)[]): str
68
69
  export declare 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-*.";
69
70
  export declare function hasCatalogueOptions(input: ListFeaturesInput): boolean;
70
71
  export declare function signalIsAborted(signal: AbortSignal): boolean;
72
+ export declare const failureMetadata: {
73
+ unlocked: ["review_lock"];
74
+ checkpoint_requires_lock: ["review_lock", "ERR_SPEC_NOT_LOCKED"];
75
+ detail_cursor_invalid: ["reread_checkpoint"];
76
+ detail_cursor_stale: ["reread_checkpoint"];
77
+ journal_cursor_invalid: ["reread_checkpoint"];
78
+ journal_cursor_stale: ["reread_checkpoint"];
79
+ history_cursor_invalid: ["reread_checkpoint"];
80
+ history_cursor_stale: ["reread_checkpoint"];
81
+ contract_drift: ["reread_checkpoint"];
82
+ checkpoint_context_stale: ["reread_checkpoint", "ERR_SPEC_DRIFT", true];
83
+ checkpoint_requires_active_task: ["reread_checkpoint", "ERR_TASK_OUT_OF_SEQUENCE"];
84
+ receipt_input_drift: ["reread_checkpoint"];
85
+ already_completed: ["reread_checkpoint"];
86
+ workspace_unresolved: ["inspect_workspace"];
87
+ guard_present: ["wait_for_guard", "ERR_TASK_OUT_OF_SEQUENCE"];
88
+ tasks_missing: ["inspect_tasks"];
89
+ compact_identifier_invalid: ["inspect_tasks"];
90
+ artifact_unavailable: ["inspect_artifacts"];
91
+ history_invalid: ["inspect_artifacts"];
92
+ checkpoint_path_unsafe: ["inspect_artifacts", "ERR_PERMISSION_VIOLATION", true];
93
+ checkpoint_history_invalid: ["inspect_artifacts", "ERR_INVALID_ARTIFACT", true];
94
+ checkpoint_sequence_exhausted: ["inspect_artifacts", "ERR_INVALID_ARTIFACT", true];
95
+ compact_response_too_large: ["inspect_artifacts"];
96
+ slice_path_unsafe: ["inspect_artifacts"];
97
+ slice_unavailable: ["inspect_artifacts"];
98
+ slice_invalid_utf8: ["inspect_artifacts"];
99
+ slice_response_too_large: ["inspect_artifacts"];
100
+ catalogue_identifier_invalid: ["inspect_artifacts"];
101
+ catalogue_response_too_large: ["inspect_artifacts"];
102
+ catalogue_unavailable: ["inspect_artifacts"];
103
+ catalogue_path_unsafe: ["inspect_artifacts"];
104
+ compact_input_invalid: ["fix_inputs"];
105
+ checkpoint_input_invalid: ["fix_inputs", "ERR_INVALID_ARTIFACT", true];
106
+ slice_input_invalid: ["fix_inputs"];
107
+ catalogue_input_invalid: ["fix_inputs"];
108
+ slice_range_unavailable: ["fix_inputs"];
109
+ receipt_input_unavailable: ["fix_inputs"];
110
+ slice_cursor_invalid: ["reread_slice"];
111
+ slice_cursor_stale: ["reread_slice"];
112
+ catalogue_cursor_invalid: ["reread_catalogue"];
113
+ catalogue_cursor_stale: ["reread_catalogue"];
114
+ receipt_malformed: ["obtain_receipts"];
115
+ receipt_missing: ["obtain_receipts"];
116
+ receipt_duplicate: ["obtain_receipts"];
117
+ receipt_unexpected: ["obtain_receipts"];
118
+ receipt_invalid_signature: ["obtain_receipts"];
119
+ receipt_context_mismatch: ["obtain_receipts"];
120
+ receipt_candidate_mismatch: ["obtain_receipts"];
121
+ receipt_observed_mismatch: ["obtain_receipts"];
122
+ receipt_procedure_mismatch: ["obtain_receipts"];
123
+ receipt_environment_mismatch: ["obtain_receipts"];
124
+ receipt_non_pass: ["obtain_receipts"];
125
+ receipt_observed_baseline_drift: ["review_observed_drift"];
126
+ command_missing: ["restore_verification"];
127
+ receipt_not_configured: ["restore_verification"];
128
+ verification_policy_mismatch: ["review_verification_policy"];
129
+ verification_policy_workspace_mismatch: ["review_verification_policy"];
130
+ verification_state_unavailable: ["review_verification_policy"];
131
+ verification_in_progress: ["review_verification_policy"];
132
+ verification_grant_consumed: ["review_verification_policy"];
133
+ checkpoint_unavailable: ["inspect_failure", "ERR_VERIFICATION_FAILED"];
134
+ failed: ["inspect_failure"];
135
+ timeout: ["inspect_failure"];
136
+ verification_runner_error: ["inspect_failure"];
137
+ verification_process_failed: ["inspect_failure"];
138
+ persistence_uncertain: ["inspect_recovery", "ERR_VERIFICATION_FAILED", true];
139
+ cancelled: ["retry_read", "ERR_VERIFICATION_FAILED"];
140
+ };
141
+ export declare function nextAction(reasons: ReadonlySet<engine.PreflightBlockerReason>): engine.PreflightAction;
142
+ export declare function decorateFailure(failure: engine.SddFailure): engine.SddFailure;
71
143
  //# sourceMappingURL=canonical-tools.d.ts.map
@@ -35,6 +35,7 @@ export const ENGINE_CAPABILITIES = Object.freeze({
35
35
  sdd_lock_spec: Object.freeze(['lock', 'evidence_checkpoint']),
36
36
  }),
37
37
  observations: Object.freeze({
38
+ errorNextAction: 1,
38
39
  featureCatalogue: 1,
39
40
  sourceSlice: 1,
40
41
  setupDiagnostics: 1,
@@ -160,4 +161,167 @@ export function hasCatalogueOptions(input) {
160
161
  export function signalIsAborted(signal) {
161
162
  return signal.aborted;
162
163
  }
164
+ export const failureMetadata = {
165
+ unlocked: ['review_lock'],
166
+ checkpoint_requires_lock: ['review_lock', 'ERR_SPEC_NOT_LOCKED'],
167
+ detail_cursor_invalid: ['reread_checkpoint'],
168
+ detail_cursor_stale: ['reread_checkpoint'],
169
+ journal_cursor_invalid: ['reread_checkpoint'],
170
+ journal_cursor_stale: ['reread_checkpoint'],
171
+ history_cursor_invalid: ['reread_checkpoint'],
172
+ history_cursor_stale: ['reread_checkpoint'],
173
+ contract_drift: ['reread_checkpoint'],
174
+ checkpoint_context_stale: ['reread_checkpoint', 'ERR_SPEC_DRIFT', true],
175
+ checkpoint_requires_active_task: ['reread_checkpoint', 'ERR_TASK_OUT_OF_SEQUENCE'],
176
+ receipt_input_drift: ['reread_checkpoint'],
177
+ already_completed: ['reread_checkpoint'],
178
+ workspace_unresolved: ['inspect_workspace'],
179
+ guard_present: ['wait_for_guard', 'ERR_TASK_OUT_OF_SEQUENCE'],
180
+ tasks_missing: ['inspect_tasks'],
181
+ compact_identifier_invalid: ['inspect_tasks'],
182
+ artifact_unavailable: ['inspect_artifacts'],
183
+ history_invalid: ['inspect_artifacts'],
184
+ checkpoint_path_unsafe: ['inspect_artifacts', 'ERR_PERMISSION_VIOLATION', true],
185
+ checkpoint_history_invalid: ['inspect_artifacts', 'ERR_INVALID_ARTIFACT', true],
186
+ checkpoint_sequence_exhausted: ['inspect_artifacts', 'ERR_INVALID_ARTIFACT', true],
187
+ compact_response_too_large: ['inspect_artifacts'],
188
+ slice_path_unsafe: ['inspect_artifacts'],
189
+ slice_unavailable: ['inspect_artifacts'],
190
+ slice_invalid_utf8: ['inspect_artifacts'],
191
+ slice_response_too_large: ['inspect_artifacts'],
192
+ catalogue_identifier_invalid: ['inspect_artifacts'],
193
+ catalogue_response_too_large: ['inspect_artifacts'],
194
+ catalogue_unavailable: ['inspect_artifacts'],
195
+ catalogue_path_unsafe: ['inspect_artifacts'],
196
+ compact_input_invalid: ['fix_inputs'],
197
+ checkpoint_input_invalid: ['fix_inputs', 'ERR_INVALID_ARTIFACT', true],
198
+ slice_input_invalid: ['fix_inputs'],
199
+ catalogue_input_invalid: ['fix_inputs'],
200
+ slice_range_unavailable: ['fix_inputs'],
201
+ receipt_input_unavailable: ['fix_inputs'],
202
+ slice_cursor_invalid: ['reread_slice'],
203
+ slice_cursor_stale: ['reread_slice'],
204
+ catalogue_cursor_invalid: ['reread_catalogue'],
205
+ catalogue_cursor_stale: ['reread_catalogue'],
206
+ receipt_malformed: ['obtain_receipts'],
207
+ receipt_missing: ['obtain_receipts'],
208
+ receipt_duplicate: ['obtain_receipts'],
209
+ receipt_unexpected: ['obtain_receipts'],
210
+ receipt_invalid_signature: ['obtain_receipts'],
211
+ receipt_context_mismatch: ['obtain_receipts'],
212
+ receipt_candidate_mismatch: ['obtain_receipts'],
213
+ receipt_observed_mismatch: ['obtain_receipts'],
214
+ receipt_procedure_mismatch: ['obtain_receipts'],
215
+ receipt_environment_mismatch: ['obtain_receipts'],
216
+ receipt_non_pass: ['obtain_receipts'],
217
+ receipt_observed_baseline_drift: ['review_observed_drift'],
218
+ command_missing: ['restore_verification'],
219
+ receipt_not_configured: ['restore_verification'],
220
+ verification_policy_mismatch: ['review_verification_policy'],
221
+ verification_policy_workspace_mismatch: ['review_verification_policy'],
222
+ verification_state_unavailable: ['review_verification_policy'],
223
+ verification_in_progress: ['review_verification_policy'],
224
+ verification_grant_consumed: ['review_verification_policy'],
225
+ checkpoint_unavailable: ['inspect_failure', 'ERR_VERIFICATION_FAILED'],
226
+ failed: ['inspect_failure'],
227
+ timeout: ['inspect_failure'],
228
+ verification_runner_error: ['inspect_failure'],
229
+ verification_process_failed: ['inspect_failure'],
230
+ persistence_uncertain: ['inspect_recovery', 'ERR_VERIFICATION_FAILED', true],
231
+ cancelled: ['retry_read', 'ERR_VERIFICATION_FAILED'],
232
+ };
233
+ Object.values(failureMetadata).forEach(Object.freeze);
234
+ Object.freeze(failureMetadata);
235
+ export function nextAction(reasons) {
236
+ if (reasons.has('unlocked')) {
237
+ return 'review_lock';
238
+ }
239
+ if (reasons.has('platform_unsupported') || reasons.has('receipt_scoped_unsupported')) {
240
+ return 'use_supported_runtime';
241
+ }
242
+ if (reasons.has('command_missing')) {
243
+ return 'restore_verification';
244
+ }
245
+ if (reasons.has('receipt_input_unavailable')) {
246
+ return 'fix_inputs';
247
+ }
248
+ if (reasons.has('receipt_observed_baseline_drift')) {
249
+ return 'review_observed_drift';
250
+ }
251
+ if (reasons.has('receipt_not_configured')) {
252
+ return 'restore_verification';
253
+ }
254
+ if ([...reasons].some((reason) => reason.startsWith('verification_'))) {
255
+ return 'review_verification_policy';
256
+ }
257
+ return reasons.size ? 'obtain_receipts' : 'attempt_integration';
258
+ }
259
+ const codeActions = Object.freeze({
260
+ ERR_FEATURE_NOT_FOUND: 'inspect_artifacts',
261
+ ERR_FEATURE_ALREADY_EXISTS: 'fix_inputs',
262
+ ERR_SPEC_NOT_LOCKED: 'review_lock',
263
+ ERR_SPEC_ALREADY_LOCKED: 'review_lock',
264
+ ERR_SPEC_DRIFT: 'reread_checkpoint',
265
+ ERR_TASK_OUT_OF_SEQUENCE: 'reread_checkpoint',
266
+ ERR_TASK_NOT_FOUND: 'inspect_tasks',
267
+ ERR_FILE_OUT_OF_MANIFEST: 'inspect_artifacts',
268
+ ERR_PERMISSION_VIOLATION: 'inspect_artifacts',
269
+ ERR_PATCH_FAILED: 'inspect_recovery',
270
+ ERR_INVALID_ARTIFACT: 'inspect_artifacts',
271
+ ERR_INVALID_SLICE: 'fix_inputs',
272
+ ERR_WORKSPACE_UNRESOLVED: 'inspect_workspace',
273
+ ERR_TRINITY_INCOMPLETE: 'inspect_artifacts',
274
+ ERR_LOCK_REASON_REQUIRED: 'fix_inputs',
275
+ ERR_VERIFICATION_MISSING: 'restore_verification',
276
+ ERR_VERIFICATION_FAILED: 'inspect_failure',
277
+ });
278
+ function ownData(value, key) {
279
+ if (value === null || typeof value !== 'object') {
280
+ return undefined;
281
+ }
282
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
283
+ return descriptor && 'value' in descriptor ? descriptor.value : undefined;
284
+ }
285
+ export function decorateFailure(failure) {
286
+ const details = failure.error.details;
287
+ const reason = ownData(details, 'reason');
288
+ const process = ownData(details, 'verificationProcess');
289
+ let action;
290
+ if (['persistence_uncertain', 'verification_completion_io', 'verification_grant_quarantined'].some((item) => item === reason) ||
291
+ ownData(details, 'completionState') === 'uncertain' ||
292
+ ownData(details, 'cleanupComplete') === false ||
293
+ ownData(process, 'cleanupComplete') === false) {
294
+ action = 'inspect_recovery';
295
+ }
296
+ else if (reason === 'cancelled' || reason === 'verification_cancelled') {
297
+ action = ENGINE_CAPABILITIES.readOnlyTools.some((name) => name === failure.error.trigger)
298
+ ? 'retry_read'
299
+ : 'inspect_recovery';
300
+ }
301
+ else if (ownData(details, 'verificationSupported') === false ||
302
+ [
303
+ 'platform_unsupported',
304
+ 'receipt_scoped_unsupported',
305
+ 'checkpoint_capability_unavailable',
306
+ 'slice_capability_unavailable',
307
+ 'catalogue_capability_unavailable',
308
+ ].some((item) => item === reason)) {
309
+ action = 'use_supported_runtime';
310
+ }
311
+ else {
312
+ const known = typeof reason === 'string' && Object.hasOwn(failureMetadata, reason)
313
+ ? failureMetadata[reason][0]
314
+ : undefined;
315
+ action = known ?? codeActions[failure.error.code];
316
+ }
317
+ const descriptors = details && typeof details === 'object' ? Object.getOwnPropertyDescriptors(details) : {};
318
+ delete descriptors.nextAction;
319
+ delete descriptors.nextActionVersion;
320
+ const copy = Object.defineProperties({}, {
321
+ ...descriptors,
322
+ nextActionVersion: { value: 1, enumerable: true },
323
+ nextAction: { value: action, enumerable: true },
324
+ });
325
+ return { ...failure, error: { ...failure.error, details: copy } };
326
+ }
163
327
  //# sourceMappingURL=canonical-tools.js.map
@@ -5,7 +5,7 @@ export const FeatureIdSchema = z
5
5
  .string()
6
6
  .min(1)
7
7
  .regex(/^FEAT[-_][A-Z0-9_-]+$/, {
8
- message: 'El Feature ID debe cumplir con el formato FEAT-XXXX o FEAT_XXXX (letras mayúsculas, números, guiones).',
8
+ message: 'Feature ID must match FEAT-XXXX or FEAT_XXXX (uppercase ASCII letters, digits, hyphens, or underscores).',
9
9
  });
10
10
  export const ArtifactTypeSchema = z.enum(['spec', 'plan', 'tasks']);
11
11
  export const FilePermissionSchema = z.enum(['CREATE', 'MODIFY', 'READ_ONLY', 'DELETE']);
@@ -18,6 +18,8 @@ After the local client has registered the MCP server and the intended project is
18
18
 
19
19
  ## Read-only diagnostics
20
20
 
21
+ For failure guidance, require \`engineCapabilities.version=1\` and \`observations.errorNextAction=1\` in setup diagnostics. Engine-produced formatted failures contain static \`details.nextActionVersion=1\` and \`details.nextAction\`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects \`inspect_recovery\`. Reasons \`cancelled\` or \`verification_cancelled\` select it for mutations; only the four read tools may advise \`retry_read\`. A scoped \`verification_process_failed\` keeps \`inspect_failure\` even when \`cancelled=true\`. Actions grant no retry, verification time or write authority.
22
+
21
23
  For an opt-in feature catalogue, first require \`engineCapabilities.version=1\`, \`views.sdd_list_features\` containing \`catalogue\`, and \`observations.featureCatalogue=1\` in setup diagnostics. Request \`view="catalogue"\` and follow each non-null \`nextCursor\` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
22
24
 
23
25
  For an opt-in bounded source read, first require \`engineCapabilities.version=1\`, \`views.sdd_read_file_slice\` containing \`bounded\`, and \`observations.sourceSlice=1\` in setup diagnostics. Treat an absent or unknown descriptor version or capability value as unsupported; do not probe a mutation. Use \`sdd_read_file_slice\` with \`view="bounded"\` and the required path and line range. Follow a non-null \`nextCursor\` read-only on the same server instance, repeating the same normalized path and range; the cursor is bound to that server, root, request and physical snapshot. Stop when \`nextCursor\` is null. The physical snapshot digest is not a content checksum. A same-UID replacement after the last filesystem check is not transactionally excluded. This view and its cursor grant no permission, retry authority or verification time. The default legacy read remains unchanged.
@@ -2,6 +2,7 @@ import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import { parseManifestContent, toPosixPath } from './feature-manifest.js';
4
4
  import { CompletionGuardError, readArtifact, rewriteArtifact } from './feature-authority.js';
5
+ import { buildModifyPatchDiagnostics } from './task-content.js';
5
6
  export class PatchSandbox {
6
7
  workspaceRoot;
7
8
  constructor(workspaceRoot) {
@@ -88,16 +89,11 @@ export class PatchSandbox {
88
89
  return null;
89
90
  }
90
91
  rejectsProtectedRoot(workspacePath, fullPath, normalizedTarget, permission) {
91
- const sddRoot = path.resolve(workspacePath, '.sdd');
92
- const gitRoot = path.resolve(workspacePath, '.git');
93
- const legacySpecsRoot = path.resolve(workspacePath, 'planu', 'specs');
94
- if (isProtectedPrefix(normalizedTarget, '.sdd') ||
95
- isProtectedPrefix(normalizedTarget, '.git') ||
96
- isProtectedPrefix(normalizedTarget, 'planu/specs') ||
97
- this.isWithin(sddRoot, fullPath) ||
98
- this.isWithin(gitRoot, fullPath) ||
99
- this.isWithin(legacySpecsRoot, fullPath)) {
100
- return true;
92
+ for (const root of ['.sdd', '.git', 'planu/specs']) {
93
+ if (isProtectedPrefix(normalizedTarget, root) ||
94
+ this.isWithin(path.resolve(workspacePath, root), fullPath)) {
95
+ return true;
96
+ }
101
97
  }
102
98
  return permission === 'DELETE' && fullPath === workspacePath;
103
99
  }
@@ -209,7 +205,7 @@ export class PatchSandbox {
209
205
  code: 'ERR_PATCH_FAILED',
210
206
  message: `MODIFY search_content must occur exactly once in '${normalizedTarget}'.`,
211
207
  trigger: 'sdd_apply_file_patch',
212
- details: { matchCount, requestedPath: normalizedTarget },
208
+ details: buildModifyPatchDiagnostics(artifact.content, searchContent, matchCount, normalizedTarget),
213
209
  },
214
210
  };
215
211
  }
@@ -1,5 +1,5 @@
1
1
  import type { TaskBlock } from '../types/completion.js';
2
- import type { ActiveTaskResult, FeatureSummary, SddResult } from '../types/sdd-engine.js';
2
+ import type { ActiveTaskResult, FeatureSummary, SddResult, TrinityIssue } from '../types/sdd-engine.js';
3
3
  export declare function activeTaskFromContent(content: string, extractCommand: (markdown: string) => string | null): SddResult<ActiveTaskResult>;
4
4
  export declare function summarizeTaskContent(content: string, extractCommand: (markdown: string) => string | null): {
5
5
  current: SddResult<ActiveTaskResult>;
@@ -10,6 +10,8 @@ export declare function summarizeTaskContent(content: string, extractCommand: (m
10
10
  };
11
11
  export declare function taskBlocks(content: string): TaskBlock[];
12
12
  export declare function markTaskVerified(lines: string[], taskId: string, cleanOutput: string): string[] | null;
13
+ export declare function findDuplicateTaskIssues(tasksContent: string): TrinityIssue[];
14
+ export declare function buildModifyPatchDiagnostics(content: string, searchContent: string, matchCount: number, requestedPath: string): Record<string, unknown>;
13
15
  export declare function markReceiptTaskVerified(content: string, lineIndex: number, summary: string): string | undefined;
14
16
  export declare function remainingTaskCount(checkRes: SddResult<ActiveTaskResult>): number;
15
17
  export declare function summarizeEvidence(output: string): string;
@@ -113,17 +113,92 @@ function extractTaskId(rawTitle, index) {
113
113
  return { id: `TASK-${index}`, title: rawTitle };
114
114
  }
115
115
  export function markTaskVerified(lines, taskId, cleanOutput) {
116
- const regexExact = new RegExp(`^(\\s*[-*]\\s*\\[)[\\s/](\\]\\s*(?:${taskId}\\b|.*\\b${taskId}\\b.*))`, 'i');
117
- const next = [...lines];
118
- for (let i = 0; i < next.length; i++) {
119
- const line = next[i];
120
- if (line !== undefined && regexExact.test(line)) {
121
- next[i] = line.replace(regexExact, (_, open, rest) => `${open}x${rest} — [Verified: ${cleanOutput}]`);
122
- return next;
116
+ const targetId = taskId.toUpperCase();
117
+ let ordinal = 0;
118
+ for (let i = 0; i < lines.length; i++) {
119
+ const line = lines[i] ?? '';
120
+ const match = TASK_CHECKBOX.exec(line.trim());
121
+ if (!match?.[1] || !match[2]) {
122
+ continue;
123
+ }
124
+ ordinal += 1;
125
+ if (match[1].trim().toLowerCase() === 'x') {
126
+ continue;
127
+ }
128
+ if (extractTaskId(match[2].trim(), ordinal).id !== targetId) {
129
+ return null;
123
130
  }
131
+ const next = [...lines];
132
+ next[i] = formatVerifiedTaskLine(line, targetId, cleanOutput);
133
+ return next;
124
134
  }
125
135
  return null;
126
136
  }
137
+ function formatVerifiedTaskLine(line, targetId, cleanOutput) {
138
+ const lineEnding = line.endsWith('\r') ? '\r' : '';
139
+ const body = lineEnding ? line.slice(0, -1) : line;
140
+ const explicitPrefix = /^(\s*[-*]\s*\[)[\s/](\]\s*(?:TASK-[A-Z0-9_-]+|[A-Z0-9_-]+))(:\s*.*)$/iu.exec(body);
141
+ if (explicitPrefix?.[1] && explicitPrefix[2] && explicitPrefix[3]) {
142
+ return `${explicitPrefix[1]}x${explicitPrefix[2]} — [Verified: ${cleanOutput}]${explicitPrefix[3]}${lineEnding}`;
143
+ }
144
+ return (body.replace(/^(\s*[-*]\s*\[)[\s/](\]\s*)(.*)$/u, `$1x$2${targetId} — [Verified: ${cleanOutput}]: $3`) + lineEnding);
145
+ }
146
+ export function findDuplicateTaskIssues(tasksContent) {
147
+ const seen = new Set();
148
+ const issues = [];
149
+ for (const block of taskBlocks(tasksContent)) {
150
+ const explicit = (block.explicitId ?? block.legacyId)?.toUpperCase();
151
+ if (!explicit) {
152
+ continue;
153
+ }
154
+ if (seen.has(explicit)) {
155
+ issues.push({
156
+ artifact: 'tasks.md',
157
+ rule: 'duplicate_task_id',
158
+ line: block.lineIndex + 1,
159
+ });
160
+ }
161
+ else {
162
+ seen.add(explicit);
163
+ }
164
+ }
165
+ return issues;
166
+ }
167
+ const DIAGNOSTIC_BYTE_LIMIT = 262_144;
168
+ const SLICE_LINE_PREFIX = /^\d+: /u;
169
+ export function buildModifyPatchDiagnostics(content, searchContent, matchCount, requestedPath) {
170
+ if (!searchContent || content.length > DIAGNOSTIC_BYTE_LIMIT) {
171
+ return { matchCount, requestedPath };
172
+ }
173
+ if (matchCount > 1) {
174
+ return {
175
+ matchCount,
176
+ requestedPath,
177
+ matchLines: findMatchLines(content, searchContent),
178
+ };
179
+ }
180
+ const normContent = content.replaceAll('\r\n', '\n');
181
+ const normSearch = searchContent.replaceAll('\r\n', '\n');
182
+ const searchLines = normSearch.split('\n');
183
+ const stripped = searchLines.some((line) => SLICE_LINE_PREFIX.test(line))
184
+ ? searchLines.map((line) => line.replace(SLICE_LINE_PREFIX, '')).join('\n')
185
+ : '';
186
+ const totalLines = sourceLines(normContent).length;
187
+ return {
188
+ matchCount,
189
+ requestedPath,
190
+ totalLines,
191
+ hasCrlfMismatch: normContent.includes(normSearch),
192
+ hasLineNumberPrefixes: Boolean(stripped && normContent.includes(stripped)),
193
+ };
194
+ }
195
+ function findMatchLines(haystack, needle) {
196
+ const lines = [];
197
+ for (let at = haystack.indexOf(needle); at !== -1 && lines.length < 10; at = haystack.indexOf(needle, at + needle.length)) {
198
+ lines.push(haystack.slice(0, at).split('\n').length);
199
+ }
200
+ return lines;
201
+ }
127
202
  export function markReceiptTaskVerified(content, lineIndex, summary) {
128
203
  const lines = content.split('\n');
129
204
  const line = lines[lineIndex];
@@ -2,6 +2,7 @@ import type * as completion from '../types/completion.js';
2
2
  import type * as resumeTypes from '../types/resume-views.js';
3
3
  import type * as engine from '../types/sdd-engine.js';
4
4
  import type { ScopedVerificationRun, VerificationBudgetDiagnostic, VerificationProcessEvidence } from '../types/verification.js';
5
+ export { nextAction } from './canonical-tools.js';
5
6
  export declare function verificationProcessEvidence(run: ScopedVerificationRun): VerificationProcessEvidence;
6
7
  export declare function withVerificationProcess(result: engine.SddResult<engine.CompleteTaskResult>, run: ScopedVerificationRun): engine.SddResult<engine.CompleteTaskResult>;
7
8
  export declare function completionFailure(reason: string, code?: 'ERR_VERIFICATION_FAILED' | 'ERR_SPEC_DRIFT', trigger?: string): engine.SddResult<never>;
@@ -19,7 +20,6 @@ export declare function snapshotFailure(workspace?: boolean): engine.SddFailure;
19
20
  export declare function uncertainCompletion(): engine.SddFailure;
20
21
  export declare function scopedFailure(details: Record<string, unknown>): engine.SddFailure;
21
22
  export declare function cancelledVerification(signal: AbortSignal): engine.SddFailure | null;
22
- export declare function nextAction(reasons: ReadonlySet<engine.PreflightBlockerReason>): engine.PreflightAction;
23
23
  export declare function verificationCommand(taskMarkdown: string): string | null;
24
24
  export declare function withVerificationBudget(preflight: engine.VerificationPreflight, budget: VerificationBudgetDiagnostic): engine.VerificationPreflight;
25
25
  export declare function checkpointPresentation(snapshot: completion.PreflightReadSnapshot, summary: resumeTypes.CompactCore['summary'], assessment?: resumeTypes.PreflightAssessment): resumeTypes.ResumePresentation;
@@ -1,3 +1,5 @@
1
+ import { nextAction } from './canonical-tools.js';
2
+ export { nextAction } from './canonical-tools.js';
1
3
  import { CompletionGuardError } from './feature-authority.js';
2
4
  import { VerificationInputError } from './verification-inputs.js';
3
5
  function makeFailure(error) {
@@ -181,30 +183,6 @@ export function cancelledVerification(signal) {
181
183
  }
182
184
  return scopedFailure({ reason: 'verification_cancelled', cancelled: true, timedOut: false });
183
185
  }
184
- export function nextAction(reasons) {
185
- if (reasons.has('unlocked')) {
186
- return 'review_lock';
187
- }
188
- if (reasons.has('platform_unsupported') || reasons.has('receipt_scoped_unsupported')) {
189
- return 'use_supported_runtime';
190
- }
191
- if (reasons.has('command_missing')) {
192
- return 'restore_verification';
193
- }
194
- if (reasons.has('receipt_input_unavailable')) {
195
- return 'fix_inputs';
196
- }
197
- if (reasons.has('receipt_observed_baseline_drift')) {
198
- return 'review_observed_drift';
199
- }
200
- if (reasons.has('receipt_not_configured')) {
201
- return 'restore_verification';
202
- }
203
- if ([...reasons].some((reason) => reason.startsWith('verification_'))) {
204
- return 'review_verification_policy';
205
- }
206
- return reasons.size ? 'obtain_receipts' : 'attempt_integration';
207
- }
208
186
  export function verificationCommand(taskMarkdown) {
209
187
  const line = taskMarkdown
210
188
  .split('\n')
@@ -11,7 +11,7 @@ export declare function checkpointCapabilityFailure(trigger?: string): engineTyp
11
11
  export declare class CheckpointError extends Error {
12
12
  readonly reason: CheckpointFailureReason;
13
13
  readonly code: engineTypes.ErrorCode;
14
- readonly nextAction?: string;
14
+ readonly nextAction?: engineTypes.FailureNextActionV1;
15
15
  constructor(reason: CheckpointFailureReason);
16
16
  }
17
17
  export declare function checkpointError(reason: CheckpointFailureReason, trigger?: string): engineTypes.SddResult<never>;
@@ -1,25 +1,6 @@
1
1
  import { CompletionGuardError, hashArtifact } from '../feature-authority.js';
2
2
  import { VerificationInputError } from '../verification-inputs.js';
3
- const actions = {
4
- unlocked: 'review_lock',
5
- detail_cursor_invalid: 'reread_checkpoint',
6
- detail_cursor_stale: 'reread_checkpoint',
7
- journal_cursor_invalid: 'reread_checkpoint',
8
- journal_cursor_stale: 'reread_checkpoint',
9
- history_cursor_stale: 'reread_checkpoint',
10
- history_cursor_invalid: 'reread_checkpoint',
11
- workspace_unresolved: 'inspect_workspace',
12
- guard_present: 'wait_for_guard',
13
- persistence_uncertain: 'inspect_recovery',
14
- contract_drift: 'reread_checkpoint',
15
- tasks_missing: 'inspect_tasks',
16
- artifact_unavailable: 'inspect_artifacts',
17
- history_invalid: 'inspect_artifacts',
18
- compact_identifier_invalid: 'inspect_tasks',
19
- compact_input_invalid: 'fix_inputs',
20
- compact_response_too_large: 'inspect_artifacts',
21
- cancelled: 'retry_read',
22
- };
3
+ import { failureMetadata, decorateFailure, CANONICAL_SDD_TOOL_NAMES } from '../canonical-tools.js';
23
4
  export function compactFailure(reason, code = 'ERR_INVALID_ARTIFACT') {
24
5
  return {
25
6
  success: false,
@@ -27,7 +8,7 @@ export function compactFailure(reason, code = 'ERR_INVALID_ARTIFACT') {
27
8
  code,
28
9
  message: 'Compact task read is unavailable; follow the bounded next action.',
29
10
  trigger: 'sdd_get_active_task',
30
- details: { reason, nextAction: actions[reason] },
11
+ details: { reason, nextAction: failureMetadata[reason][0] },
31
12
  },
32
13
  };
33
14
  }
@@ -67,9 +48,20 @@ export function compactReadError(error) {
67
48
  return compactFailure('artifact_unavailable');
68
49
  }
69
50
  export function formatCompactResult(result) {
70
- const text = JSON.stringify(result);
51
+ const text = JSON.stringify(result.success ? result : decorateFailure(result));
71
52
  if (Buffer.byteLength(text, 'utf8') > 8192) {
72
- return formatCompactResult(compactFailure('compact_response_too_large'));
53
+ const trigger = !result.success && CANONICAL_SDD_TOOL_NAMES.some((name) => name === result.error.trigger)
54
+ ? result.error.trigger
55
+ : 'sdd_get_active_task';
56
+ const fallback = compactFailure('compact_response_too_large');
57
+ if (fallback.success) {
58
+ throw new Error('Invalid compact failure');
59
+ }
60
+ const fixed = JSON.stringify(decorateFailure({ ...fallback, error: { ...fallback.error, trigger } }));
61
+ if (Buffer.byteLength(fixed, 'utf8') > 8192) {
62
+ throw new Error('Compact fallback exceeds limit');
63
+ }
64
+ return { content: [{ type: 'text', text: fixed }], isError: true };
73
65
  }
74
66
  return {
75
67
  content: [{ type: 'text', text }],
@@ -77,24 +69,14 @@ export function formatCompactResult(result) {
77
69
  };
78
70
  }
79
71
  export function formatResult(result) {
80
- if (!result.success) {
81
- return {
82
- content: [
83
- {
84
- type: 'text',
85
- text: JSON.stringify(result, null, 2),
86
- },
87
- ],
88
- isError: true,
89
- };
90
- }
91
72
  return {
92
73
  content: [
93
74
  {
94
75
  type: 'text',
95
- text: JSON.stringify(result, null, 2),
76
+ text: JSON.stringify(result.success ? result : decorateFailure(result), null, 2),
96
77
  },
97
78
  ],
79
+ ...(!result.success ? { isError: true } : {}),
98
80
  };
99
81
  }
100
82
  export class CheckpointCapabilityError extends Error {
@@ -113,37 +95,6 @@ export function checkpointCapabilityFailure(trigger = 'sdd_lock_spec') {
113
95
  },
114
96
  };
115
97
  }
116
- const checkpointFailures = {
117
- checkpoint_input_invalid: {
118
- code: 'ERR_INVALID_ARTIFACT',
119
- nextAction: 'fix_inputs',
120
- },
121
- checkpoint_requires_lock: { code: 'ERR_SPEC_NOT_LOCKED' },
122
- checkpoint_requires_active_task: { code: 'ERR_TASK_OUT_OF_SEQUENCE' },
123
- checkpoint_context_stale: {
124
- code: 'ERR_SPEC_DRIFT',
125
- nextAction: 'reread_checkpoint',
126
- },
127
- checkpoint_path_unsafe: {
128
- code: 'ERR_PERMISSION_VIOLATION',
129
- nextAction: 'inspect_artifacts',
130
- },
131
- checkpoint_history_invalid: {
132
- code: 'ERR_INVALID_ARTIFACT',
133
- nextAction: 'inspect_artifacts',
134
- },
135
- checkpoint_sequence_exhausted: {
136
- code: 'ERR_INVALID_ARTIFACT',
137
- nextAction: 'inspect_artifacts',
138
- },
139
- guard_present: { code: 'ERR_TASK_OUT_OF_SEQUENCE' },
140
- persistence_uncertain: {
141
- code: 'ERR_VERIFICATION_FAILED',
142
- nextAction: 'inspect_recovery',
143
- },
144
- cancelled: { code: 'ERR_VERIFICATION_FAILED' },
145
- checkpoint_unavailable: { code: 'ERR_VERIFICATION_FAILED' },
146
- };
147
98
  export class CheckpointError extends Error {
148
99
  reason;
149
100
  code;
@@ -151,12 +102,14 @@ export class CheckpointError extends Error {
151
102
  constructor(reason) {
152
103
  super('Checkpoint operation failed.');
153
104
  this.reason = reason;
154
- this.code = checkpointFailures[reason].code;
155
- this.nextAction = checkpointFailures[reason].nextAction;
105
+ const [action, code, includeAction] = failureMetadata[reason];
106
+ this.code = code;
107
+ this.nextAction = includeAction ? action : undefined;
156
108
  }
157
109
  }
158
110
  export function checkpointError(reason, trigger = 'sdd_lock_spec') {
159
- const { code, nextAction } = checkpointFailures[reason];
111
+ const [action, code, includeAction] = failureMetadata[reason];
112
+ const nextAction = includeAction ? action : undefined;
160
113
  return {
161
114
  success: false,
162
115
  error: {
@@ -1,57 +1,53 @@
1
- import { hasReceiptDirective, insideMarkdownBlock } from './task-content.js';
1
+ import { findDuplicateTaskIssues, hasReceiptDirective, insideMarkdownBlock, } from './task-content.js';
2
2
  import { taskIdPattern } from './receipt-assessment.js';
3
3
  import { disjointPaths, isEvidencePath, CompletionGuardError } from './feature-authority.js';
4
4
  import * as path from 'node:path';
5
5
  const CHECKBOX_TASK = /^[-*]\s*\[[ xX]\]/u;
6
6
  const BDD_KEYWORDS = [/\bGIVEN\b/u, /\bWHEN\b/u, /\bTHEN\b/u];
7
+ const EMPTY_SCAFFOLD_MANIFEST = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*$/iu;
7
8
  export function assessTrinityCompleteness(specContent, planContent, tasksContent) {
8
- const missing = [];
9
- if (!hasHeading(specContent, 'Out-of-Scope')) {
10
- missing.push('out_of_scope');
11
- }
12
- if (!hasHeading(specContent, 'Error Matrix')) {
13
- missing.push('error_matrix');
14
- }
15
- if (!BDD_KEYWORDS.every((keyword) => keyword.test(specContent))) {
16
- missing.push('bdd');
17
- }
18
- if (!hasHeading(planContent, 'Frozen Dependencies')) {
19
- missing.push('frozen_dependencies');
20
- }
21
9
  const hasTask = tasksContent.split('\n').some((line) => CHECKBOX_TASK.test(line.trim()));
22
10
  const manifest = scanManifest(planContent);
23
- if (!manifest.hasPath) {
24
- missing.push('manifest_path');
25
- }
26
- if (!hasTask) {
27
- missing.push('checkbox_task');
28
- }
29
- const issues = boundedTrinityIssues([...missing.map(missingIssue), ...manifest.issues]);
30
- if (manifest.globDelete) {
11
+ const duplicateTaskIssues = findDuplicateTaskIssues(tasksContent);
12
+ const checks = [
13
+ [hasHeading(specContent, 'Out-of-Scope'), 'out_of_scope'],
14
+ [hasHeading(specContent, 'Error Matrix'), 'error_matrix'],
15
+ [BDD_KEYWORDS.every((keyword) => keyword.test(specContent)), 'bdd'],
16
+ [hasHeading(planContent, 'Frozen Dependencies'), 'frozen_dependencies'],
17
+ [manifest.hasPath, 'manifest_path'],
18
+ [hasTask, 'checkbox_task'],
19
+ ];
20
+ const missing = checks.filter(([present]) => !present).map(([, rule]) => rule);
21
+ const issues = boundedTrinityIssues([
22
+ ...missing.map(missingIssue),
23
+ ...manifest.issues,
24
+ ...duplicateTaskIssues,
25
+ ]);
26
+ const errorMessage = manifest.globDelete
27
+ ? 'DELETE File Manifest entries must be exact paths, not globs.'
28
+ : manifest.protectedWrite
29
+ ? 'File Manifest cannot grant writes on protected root paths.'
30
+ : manifest.invalidEntry
31
+ ? 'File Manifest entries must use canonical "PERMISSION: path" or "path: PERMISSION" syntax with CREATE, MODIFY, READ_ONLY, or DELETE.'
32
+ : duplicateTaskIssues.length > 0
33
+ ? 'Task checkbox identifiers in tasks.md must be unique.'
34
+ : null;
35
+ if (errorMessage !== null) {
31
36
  return {
32
37
  ok: false,
33
38
  code: 'ERR_TRINITY_INCOMPLETE',
34
- message: 'DELETE File Manifest entries must be exact paths, not globs.',
39
+ message: errorMessage,
35
40
  details: { issues },
36
41
  };
37
42
  }
38
- if (manifest.protectedWrite !== null) {
39
- return {
43
+ return missing.length === 0
44
+ ? { ok: true }
45
+ : {
40
46
  ok: false,
41
47
  code: 'ERR_TRINITY_INCOMPLETE',
42
- message: 'File Manifest cannot grant writes on protected root paths.',
43
- details: { issues },
48
+ message: 'Lock requires H1-H3 Out-of-Scope, Error Matrix, and Frozen Dependencies headings, GIVEN/WHEN/THEN acceptance criteria, a File Manifest path, and at least one checkbox task.',
49
+ details: { missing, issues },
44
50
  };
45
- }
46
- if (missing.length === 0) {
47
- return { ok: true };
48
- }
49
- return {
50
- ok: false,
51
- code: 'ERR_TRINITY_INCOMPLETE',
52
- 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.',
53
- details: { missing, issues },
54
- };
55
51
  }
56
52
  function hasHeading(content, needle) {
57
53
  const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -59,10 +55,11 @@ function hasHeading(content, needle) {
59
55
  }
60
56
  const PROTECTED_ROOTS = ['.sdd', '.git', 'planu/specs'];
61
57
  function scanManifest(planContent) {
62
- const effective = new Map(manifestEntries(planContent).map((entry) => [toPosixPath(entry.rawPath), entry]));
63
- const issues = [];
58
+ const { entries, invalidIssues } = scanManifestLines(planContent);
59
+ const effective = new Map(entries.map((entry) => [toPosixPath(entry.rawPath), entry]));
60
+ const issues = [...invalidIssues];
64
61
  let globDelete = false;
65
- let protectedWrite = null;
62
+ let protectedWrite = false;
66
63
  for (const [entryPath, { permission, line }] of effective) {
67
64
  if (permission === 'DELETE' && entryPath.includes('*')) {
68
65
  globDelete = true;
@@ -71,19 +68,57 @@ function scanManifest(planContent) {
71
68
  const normalized = path.posix.normalize(entryPath).toLowerCase();
72
69
  if (permission !== 'READ_ONLY' &&
73
70
  PROTECTED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))) {
74
- protectedWrite ??= entryPath;
71
+ protectedWrite = true;
75
72
  issues.push({ artifact: 'plan.md', rule: 'protected_write', line });
76
73
  }
77
74
  }
78
- return { hasPath: effective.size > 0, globDelete, protectedWrite, issues };
75
+ return {
76
+ hasPath: effective.size > 0,
77
+ globDelete,
78
+ protectedWrite,
79
+ invalidEntry: invalidIssues.length > 0,
80
+ issues,
81
+ };
82
+ }
83
+ function scanManifestLines(content) {
84
+ const lines = content.replaceAll('\r\n', '\n').split('\n');
85
+ const entries = [];
86
+ const invalidIssues = [];
87
+ let inManifest = false;
88
+ for (const [index, rawLine] of lines.entries()) {
89
+ const line = rawLine.trim();
90
+ if (/^#{1,3}\s+/.test(line)) {
91
+ inManifest = /^#{1,3}\s+.*file\s+manifest/i.test(line);
92
+ }
93
+ else if (inManifest && /^[-*]\s+/.test(line)) {
94
+ const entry = parseManifestLine(line);
95
+ if (entry && toPosixPath(entry.rawPath).toLowerCase() !== 'none') {
96
+ entries.push({ ...entry, line: index + 1 });
97
+ }
98
+ else if (!entry && !insideMarkdownBlock(lines.slice(0, index))) {
99
+ const item = line.replace(/^[-*]\s+/, '').trim();
100
+ if (item
101
+ .replace(/^`+|`+$/g, '')
102
+ .trim()
103
+ .toLowerCase() !== 'none' &&
104
+ !EMPTY_SCAFFOLD_MANIFEST.test(item)) {
105
+ invalidIssues.push({
106
+ artifact: 'plan.md',
107
+ rule: 'invalid_manifest_entry',
108
+ line: index + 1,
109
+ });
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return { entries, invalidIssues };
79
115
  }
80
116
  function missingIssue(rule) {
81
- const artifact = ['out_of_scope', 'error_matrix', 'bdd'].includes(rule)
82
- ? 'spec.md'
83
- : rule === 'checkbox_task'
84
- ? 'tasks.md'
85
- : 'plan.md';
86
- return { artifact, rule: rule };
117
+ const spec = ['out_of_scope', 'error_matrix', 'bdd'].includes(rule);
118
+ return {
119
+ artifact: spec ? 'spec.md' : rule === 'checkbox_task' ? 'tasks.md' : 'plan.md',
120
+ rule: rule,
121
+ };
87
122
  }
88
123
  function boundedTrinityIssues(issues) {
89
124
  const order = ['spec.md', 'plan.md', 'tasks.md'];
@@ -101,40 +136,21 @@ export function parseManifestContent(content) {
101
136
  return { allowedFiles };
102
137
  }
103
138
  export function manifestEntries(content) {
104
- const entries = [];
105
- let inManifestSection = false;
106
- for (const [index, rawLine] of content.split('\n').entries()) {
107
- const line = rawLine.trim();
108
- if (/^#{1,3}\s+/.test(line)) {
109
- inManifestSection = /^#{1,3}\s+.*file\s+manifest/i.test(line);
110
- continue;
111
- }
112
- if (inManifestSection && /^[-*]\s+/.test(line)) {
113
- const entry = parseManifestLine(line);
114
- if (entry && toPosixPath(entry.rawPath).toLowerCase() !== 'none') {
115
- entries.push({ ...entry, line: index + 1 });
116
- }
117
- }
118
- }
119
- return entries;
139
+ return scanManifestLines(content).entries;
120
140
  }
121
141
  function parseManifestLine(rawLine) {
122
142
  const item = rawLine.replace(/^[-*]\s+/, '').trim();
123
- const prefix = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item);
124
- if (prefix?.[1] && prefix[2]) {
125
- return {
126
- rawPath: prefix[2],
127
- permission: prefix[1].toUpperCase(),
128
- };
129
- }
130
- const postfix = /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
131
- if (postfix?.[1] && postfix[2]) {
132
- return {
133
- rawPath: postfix[1],
134
- permission: postfix[2].toUpperCase(),
135
- };
143
+ const match = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item) ??
144
+ /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
145
+ if (!match?.[1] || !match[2]) {
146
+ return undefined;
136
147
  }
137
- return undefined;
148
+ const firstUpper = match[1].toUpperCase();
149
+ const isPrefix = ['CREATE', 'MODIFY', 'READ_ONLY', 'DELETE'].includes(firstUpper);
150
+ return {
151
+ rawPath: isPrefix ? match[2] : match[1],
152
+ permission: (isPrefix ? firstUpper : match[2].toUpperCase()),
153
+ };
138
154
  }
139
155
  export function toPosixPath(value) {
140
156
  const posix = value.replaceAll('\\', '/');
@@ -248,6 +248,7 @@ export interface EngineCapabilitiesV1 {
248
248
  readonly sdd_lock_spec: readonly ['lock', 'evidence_checkpoint'];
249
249
  };
250
250
  readonly observations: {
251
+ readonly errorNextAction: 1;
251
252
  readonly featureCatalogue: 1;
252
253
  readonly sourceSlice?: 1;
253
254
  readonly setupDiagnostics: 1;
@@ -1,6 +1,6 @@
1
1
  import type { VerificationEvidence, VerificationPreflight, VerificationProcessEvidence } from './verification.js';
2
2
  export type { VerificationReceipt, ReceiptRejectionReason, ReceiptSetResult, GateAssessment, PreflightBlockerReason, PreflightAction, VerificationPreflight, ReceiptSetAssessment, VerificationGate, VerificationEvidence, } from './verification.js';
3
- export type TrinityRule = 'out_of_scope' | 'error_matrix' | 'bdd' | 'frozen_dependencies' | 'manifest_path' | 'checkbox_task' | 'glob_delete' | 'protected_write' | 'receipt_policy_invalid' | 'artifact_missing' | 'artifact_unreadable';
3
+ export type TrinityRule = 'out_of_scope' | 'error_matrix' | 'bdd' | 'frozen_dependencies' | 'manifest_path' | 'checkbox_task' | 'glob_delete' | 'protected_write' | 'invalid_manifest_entry' | 'duplicate_task_id' | 'receipt_policy_invalid' | 'artifact_missing' | 'artifact_unreadable';
4
4
  export interface TrinityIssue {
5
5
  artifact: 'spec.md' | 'plan.md' | 'tasks.md';
6
6
  rule: TrinityRule;
@@ -19,11 +19,26 @@ export interface ReceiptSealFailure {
19
19
  export type ArtifactType = 'spec' | 'plan' | 'tasks';
20
20
  export type FilePermission = 'CREATE' | 'MODIFY' | 'READ_ONLY' | 'DELETE';
21
21
  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' | 'ERR_VERIFICATION_MISSING' | 'ERR_VERIFICATION_FAILED';
22
+ export type FailureNextActionV1 = 'fix_inputs' | 'inspect_workspace' | 'review_lock' | 'reread_checkpoint' | 'wait_for_guard' | 'inspect_recovery' | 'inspect_tasks' | 'inspect_artifacts' | 'use_supported_runtime' | 'review_verification_policy' | 'restore_verification' | 'obtain_receipts' | 'review_observed_drift' | 'retry_read' | 'reread_slice' | 'reread_catalogue' | 'inspect_failure';
23
+ export type FailureReasonMetadata = readonly [
24
+ action: FailureNextActionV1,
25
+ checkpointCode?: ErrorCode,
26
+ includeCheckpointAction?: true
27
+ ];
28
+ export type CheckpointFailureReasonMetadata = readonly [
29
+ action: FailureNextActionV1,
30
+ checkpointCode: ErrorCode,
31
+ includeCheckpointAction?: true
32
+ ];
33
+ interface SddFailureDetails extends Record<string, unknown> {
34
+ nextActionVersion?: 1;
35
+ nextAction?: FailureNextActionV1;
36
+ }
22
37
  export interface SddErrorDetails {
23
38
  code: ErrorCode;
24
39
  message: string;
25
40
  trigger: string;
26
- details?: Record<string, unknown>;
41
+ details?: SddFailureDetails;
27
42
  }
28
43
  export interface SddSuccess<T> {
29
44
  success: true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planu/cli",
3
- "version": "8.10.0",
3
+ "version": "8.12.0",
4
4
  "description": "Planu — MCP server for Spec Driven Development. Planning and file operations on macOS/Linux/Windows; automated verification requires macOS/Linux (POSIX).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -74,7 +74,7 @@
74
74
  "@commitlint/cli": "^21.2.4",
75
75
  "@commitlint/config-conventional": "^21.2.4",
76
76
  "@eslint/js": "^10.0.1",
77
- "@secretlint/secretlint-rule-no-homedir": "^13.1.0",
77
+ "@secretlint/secretlint-rule-no-homedir": "^14.0.0",
78
78
  "@secretlint/secretlint-rule-preset-recommend": "^13.1.0",
79
79
  "@types/node": "^22.20.5",
80
80
  "@typescript/native": "npm:typescript@^7.0.2",
@@ -91,7 +91,7 @@
91
91
  "madge": "^8.0.0",
92
92
  "prettier": "^3.10.1",
93
93
  "qrcode": "1.5.4",
94
- "secretlint": "^13.1.0",
94
+ "secretlint": "^14.0.0",
95
95
  "tsc-alias": "^1.9.10",
96
96
  "type-coverage": "^2.31.2",
97
97
  "typescript": "npm:@typescript/typescript6@^6.0.2",
@@ -11,6 +11,8 @@ After the local client has registered the MCP server and the intended project is
11
11
 
12
12
  ## Read-only diagnostics
13
13
 
14
+ For failure guidance, require `engineCapabilities.version=1` and `observations.errorNextAction=1` in setup diagnostics. Engine-produced formatted failures contain static `details.nextActionVersion=1` and `details.nextAction`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects `inspect_recovery`. Reasons `cancelled` or `verification_cancelled` select it for mutations; only the four read tools may advise `retry_read`. A scoped `verification_process_failed` keeps `inspect_failure` even when `cancelled=true`. Actions grant no retry, verification time or write authority.
15
+
14
16
  For an opt-in feature catalogue, first require `engineCapabilities.version=1`, `views.sdd_list_features` containing `catalogue`, and `observations.featureCatalogue=1` in setup diagnostics. Request `view="catalogue"` and follow each non-null `nextCursor` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
15
17
 
16
18
  For an opt-in bounded source read, first require `engineCapabilities.version=1`, `views.sdd_read_file_slice` containing `bounded`, and `observations.sourceSlice=1` in setup diagnostics. Treat an absent or unknown descriptor version or capability value as unsupported; do not probe a mutation. Use `sdd_read_file_slice` with `view="bounded"` and the required path and line range. Follow a non-null `nextCursor` read-only on the same server instance, repeating the same normalized path and range; the cursor is bound to that server, root, request and physical snapshot. Stop when `nextCursor` is null. The physical snapshot digest is not a content checksum. A same-UID replacement after the last filesystem check is not transactionally excluded. This view and its cursor grant no permission, retry authority or verification time. The default legacy read remains unchanged.
@@ -10,6 +10,8 @@ After the local client has registered the MCP server and the intended project is
10
10
 
11
11
  ## Read-only diagnostics
12
12
 
13
+ For failure guidance, require `engineCapabilities.version=1` and `observations.errorNextAction=1` in setup diagnostics. Engine-produced formatted failures contain static `details.nextActionVersion=1` and `details.nextAction`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects `inspect_recovery`. Reasons `cancelled` or `verification_cancelled` select it for mutations; only the four read tools may advise `retry_read`. A scoped `verification_process_failed` keeps `inspect_failure` even when `cancelled=true`. Actions grant no retry, verification time or write authority.
14
+
13
15
  For an opt-in feature catalogue, first require `engineCapabilities.version=1`, `views.sdd_list_features` containing `catalogue`, and `observations.featureCatalogue=1` in setup diagnostics. Request `view="catalogue"` and follow each non-null `nextCursor` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
14
16
 
15
17
  For an opt-in bounded source read, first require `engineCapabilities.version=1`, `views.sdd_read_file_slice` containing `bounded`, and `observations.sourceSlice=1` in setup diagnostics. Treat an absent or unknown descriptor version or capability value as unsupported; do not probe a mutation. Use `sdd_read_file_slice` with `view="bounded"` and the required path and line range. Follow a non-null `nextCursor` read-only on the same server instance, repeating the same normalized path and range; the cursor is bound to that server, root, request and physical snapshot. Stop when `nextCursor` is null. The physical snapshot digest is not a content checksum. A same-UID replacement after the last filesystem check is not transactionally excluded. This view and its cursor grant no permission, retry authority or verification time. The default legacy read remains unchanged.
@@ -54,6 +54,8 @@ Preflight never edits product files and never marks tasks complete.
54
54
 
55
55
  ## Connection and read-only views
56
56
 
57
+ For failure guidance, require `engineCapabilities.version=1` and `observations.errorNextAction=1` in setup diagnostics. Engine-produced formatted failures contain static `details.nextActionVersion=1` and `details.nextAction`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects `inspect_recovery`. Reasons `cancelled` or `verification_cancelled` select it for mutations; only the four read tools may advise `retry_read`. A scoped `verification_process_failed` keeps `inspect_failure` even when `cancelled=true`. Actions grant no retry, verification time or write authority.
58
+
57
59
  For an opt-in feature catalogue, first require `engineCapabilities.version=1`, `views.sdd_list_features` containing `catalogue`, and `observations.featureCatalogue=1` in setup diagnostics. Request `view="catalogue"` and follow each non-null `nextCursor` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
58
60
 
59
61
  For an opt-in bounded source read, first require `engineCapabilities.version=1`, `views.sdd_read_file_slice` containing `bounded`, and `observations.sourceSlice=1` in setup diagnostics. Treat an absent or unknown descriptor version or capability value as unsupported; do not probe a mutation. Use `sdd_read_file_slice` with `view="bounded"` and the required path and line range. Follow a non-null `nextCursor` read-only on the same server instance, repeating the same normalized path and range; the cursor is bound to that server, root, request and physical snapshot. Stop when `nextCursor` is null. The physical snapshot digest is not a content checksum. A same-UID replacement after the last filesystem check is not transactionally excluded. This view and its cursor grant no permission, retry authority or verification time. The default legacy read remains unchanged.
@@ -37,6 +37,8 @@ You do not make architectural decisions, you do not add dependencies, and you do
37
37
 
38
38
  ## Evidence and current connection
39
39
 
40
+ For failure guidance, require `engineCapabilities.version=1` and `observations.errorNextAction=1` in setup diagnostics. Engine-produced formatted failures contain static `details.nextActionVersion=1` and `details.nextAction`; SDK/Zod, JSON-RPC and transport errors before dispatch are separate. Existing details are not globally redacted. Uncertainty selects `inspect_recovery`. Reasons `cancelled` or `verification_cancelled` select it for mutations; only the four read tools may advise `retry_read`. A scoped `verification_process_failed` keeps `inspect_failure` even when `cancelled=true`. Actions grant no retry, verification time or write authority.
41
+
40
42
  For an opt-in feature catalogue, first require `engineCapabilities.version=1`, `views.sdd_list_features` containing `catalogue`, and `observations.featureCatalogue=1` in setup diagnostics. Request `view="catalogue"` and follow each non-null `nextCursor` on the same server, repeating query, status and page size. Each compact response is at most 8192 UTF-8 bytes and each capture stage runs at most eight feature readers concurrently; a complete scan still reads all eligible inputs, so total I/O is not bounded. The cursor grants no permission or certification.
41
43
 
42
44
  For an opt-in bounded source read, first require `engineCapabilities.version=1`, `views.sdd_read_file_slice` containing `bounded`, and `observations.sourceSlice=1` in setup diagnostics. Treat an absent or unknown descriptor version or capability value as unsupported; do not probe a mutation. Use `sdd_read_file_slice` with `view="bounded"` and the required path and line range. Follow a non-null `nextCursor` read-only on the same server instance, repeating the same normalized path and range; the cursor is bound to that server, root, request and physical snapshot. Stop when `nextCursor` is null. The physical snapshot digest is not a content checksum. A same-UID replacement after the last filesystem check is not transactionally excluded. This view and its cursor grant no permission, retry authority or verification time. The default legacy read remains unchanged.