@planu/cli 8.2.20 → 8.4.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +118 -3
  3. package/dist/sdd-engine/completion-snapshot.d.ts +5 -1
  4. package/dist/sdd-engine/completion-snapshot.js +79 -2
  5. package/dist/sdd-engine/contracts.d.ts +6 -3
  6. package/dist/sdd-engine/contracts.js +30 -3
  7. package/dist/sdd-engine/feature-authority.d.ts +3 -1
  8. package/dist/sdd-engine/feature-authority.js +33 -1
  9. package/dist/sdd-engine/feature-manifest.d.ts +4 -5
  10. package/dist/sdd-engine/feature-manifest.js +206 -93
  11. package/dist/sdd-engine/host-rule-pack.d.ts +5 -0
  12. package/dist/sdd-engine/host-rule-pack.js +103 -43
  13. package/dist/sdd-engine/host-skill-reader.d.ts +6 -0
  14. package/dist/sdd-engine/host-skill-reader.js +187 -0
  15. package/dist/sdd-engine/lock-integrity.d.ts +3 -2
  16. package/dist/sdd-engine/lock-integrity.js +30 -18
  17. package/dist/sdd-engine/receipt-assessment.d.ts +12 -0
  18. package/dist/sdd-engine/receipt-assessment.js +223 -0
  19. package/dist/sdd-engine/server.js +2 -4
  20. package/dist/sdd-engine/task-content.d.ts +19 -1
  21. package/dist/sdd-engine/task-content.js +128 -3
  22. package/dist/sdd-engine/task-failures.d.ts +2 -0
  23. package/dist/sdd-engine/task-failures.js +34 -0
  24. package/dist/sdd-engine/task-window.d.ts +3 -4
  25. package/dist/sdd-engine/task-window.js +49 -79
  26. package/dist/sdd-engine/tools/execution-tools.d.ts +1 -11
  27. package/dist/sdd-engine/tools/execution-tools.js +86 -57
  28. package/dist/sdd-engine/tools/workspace-tools.d.ts +1 -1
  29. package/dist/sdd-engine/tools/workspace-tools.js +17 -9
  30. package/dist/sdd-engine/tools.d.ts +2 -1
  31. package/dist/sdd-engine/tools.js +4 -2
  32. package/dist/sdd-engine/trinity-structure.d.ts +25 -0
  33. package/dist/sdd-engine/trinity-structure.js +317 -0
  34. package/dist/sdd-engine/verification-inputs.d.ts +12 -0
  35. package/dist/sdd-engine/verification-inputs.js +302 -0
  36. package/dist/sdd-engine/verification-preflight.d.ts +4 -0
  37. package/dist/sdd-engine/verification-preflight.js +271 -0
  38. package/dist/sdd-engine/verification-receipts.d.ts +16 -0
  39. package/dist/sdd-engine/verification-receipts.js +98 -0
  40. package/dist/sdd-engine/workspace-root.d.ts +1 -0
  41. package/dist/sdd-engine/workspace-root.js +1 -0
  42. package/dist/types/completion.d.ts +9 -2
  43. package/dist/types/sdd-engine.d.ts +203 -0
  44. package/package.json +1 -1
  45. package/templates/AGENTS.md +9 -1
  46. package/templates/host/planu-sdd.md +9 -0
  47. package/templates/skills/spec-architect.md +1 -0
@@ -1,116 +1,229 @@
1
- import * as path from 'node:path';
2
- const CHECKBOX_TASK = /^[-*]\s*\[[ xX]\]/u;
3
- const BDD_KEYWORDS = [/\bGIVEN\b/u, /\bWHEN\b/u, /\bTHEN\b/u];
4
- export function assessTrinityCompleteness(specContent, planContent, tasksContent) {
5
- const missing = [];
6
- if (!hasHeading(specContent, 'Out-of-Scope')) {
7
- missing.push('out_of_scope');
8
- }
9
- if (!hasHeading(specContent, 'Error Matrix')) {
10
- missing.push('error_matrix');
1
+ import { z } from 'zod';
2
+ import { countTaskIds, dueTaskOrdinals, hasReceiptDirective, receiptCommand, taskBlocks, } from './task-content.js';
3
+ import { featureIdPattern, gateIdPattern, importReceiptPublicKey, maxVerificationReceipts, sha256Schema, taskIdPattern, } from './verification-receipts.js';
4
+ import { disjointPaths, isEvidencePath } from './feature-authority.js';
5
+ import { candidateCreationIssue, invalidTask, invalidCandidate, candidateIssue, manifestEntries, policyIssueLine, policyText, toPosixPath, } from './trinity-structure.js';
6
+ export { assessTrinityCompleteness, parseManifestContent, toPosixPath, } from './trinity-structure.js';
7
+ const policySchema = z.strictObject({
8
+ publicKey: z.string().max(128),
9
+ tasks: z
10
+ .array(z.strictObject({
11
+ taskId: z.string().regex(taskIdPattern),
12
+ gates: z
13
+ .array(z.strictObject({
14
+ id: z.string().regex(gateIdPattern),
15
+ procedureSha256: sha256Schema,
16
+ environmentSha256: sha256Schema,
17
+ }))
18
+ .min(1)
19
+ .max(maxVerificationReceipts),
20
+ observed: z.array(z.string().max(240)).max(64),
21
+ observedBaselineSha256: sha256Schema,
22
+ }))
23
+ .min(1)
24
+ .max(32),
25
+ candidateCreates: z
26
+ .array(z.strictObject({
27
+ path: z.string().max(240),
28
+ requiredFromTaskId: z.string().regex(/^[A-Z0-9_-]+$/u),
29
+ }))
30
+ .max(64),
31
+ });
32
+ const INVALID_POLICY = { status: 'invalid' };
33
+ function readPolicy(text, locations) {
34
+ try {
35
+ const value = JSON.parse(text);
36
+ if (JSON.stringify(value, null, 2) !== text) {
37
+ return {};
38
+ }
39
+ const parsed = policySchema.safeParse(value);
40
+ if (parsed.success) {
41
+ return { value: parsed.data };
42
+ }
43
+ const first = parsed.error.issues[0];
44
+ return { line: first ? policyIssueLine(first, locations) : undefined };
11
45
  }
12
- if (!BDD_KEYWORDS.every((keyword) => keyword.test(specContent))) {
13
- missing.push('bdd');
46
+ catch {
47
+ return {};
14
48
  }
15
- if (!hasHeading(planContent, 'Frozen Dependencies')) {
16
- missing.push('frozen_dependencies');
49
+ }
50
+ function parseCandidates(plan, creates, dueTasks, locations) {
51
+ const entries = manifestEntries(plan);
52
+ const writable = entries.filter(({ permission }) => permission !== 'READ_ONLY');
53
+ if (writable.length > 64) {
54
+ return candidateIssue(writable[64]);
17
55
  }
18
- const hasTask = tasksContent.split('\n').some((line) => CHECKBOX_TASK.test(line.trim()));
19
- const manifest = scanManifest(planContent);
20
- if (!manifest.hasPath) {
21
- missing.push('manifest_path');
56
+ const paths = writable.map(({ rawPath }) => rawPath);
57
+ if (writable.length < 1 ||
58
+ !paths.every(isEvidencePath) ||
59
+ !disjointPaths(paths) ||
60
+ writable.some(({ permission }) => permission === 'DELETE')) {
61
+ const bad = invalidCandidate(writable, paths);
62
+ return candidateIssue(bad);
22
63
  }
23
- if (!hasTask) {
24
- missing.push('checkbox_task');
64
+ const writes = new Set(paths.map((item) => item.toLowerCase()));
65
+ const shadow = entries.find(({ rawPath, permission }) => permission === 'READ_ONLY' && writes.has(toPosixPath(rawPath).toLowerCase()));
66
+ if (shadow) {
67
+ return candidateIssue(undefined);
25
68
  }
26
- if (manifest.globDelete) {
27
- return {
28
- ok: false,
29
- code: 'ERR_TRINITY_INCOMPLETE',
30
- message: 'DELETE File Manifest entries must be exact paths, not globs.',
31
- };
69
+ const mappings = new Map(creates.map(({ path: candidatePath, requiredFromTaskId }) => [
70
+ candidatePath,
71
+ requiredFromTaskId,
72
+ ]));
73
+ if (mappings.size !== creates.length ||
74
+ mappings.size !== writable.filter(({ permission }) => permission === 'CREATE').length) {
75
+ return undefined;
32
76
  }
33
- if (manifest.protectedWrite !== null) {
34
- return {
35
- ok: false,
36
- code: 'ERR_TRINITY_INCOMPLETE',
37
- message: `File Manifest cannot grant writes on protected root path '${manifest.protectedWrite}' (.sdd, .git, planu/specs).`,
38
- };
39
- }
40
- if (missing.length === 0) {
41
- return { ok: true };
77
+ const candidates = [];
78
+ for (const entry of writable) {
79
+ const { rawPath, permission } = entry;
80
+ const due = mappings.get(rawPath);
81
+ const requiredFrom = permission === 'CREATE' && due !== undefined ? dueTasks.get(due) : 1;
82
+ if (requiredFrom === undefined ||
83
+ (permission === 'CREATE' ? due === undefined : due !== undefined)) {
84
+ return candidateCreationIssue(rawPath, creates, requiredFrom, locations);
85
+ }
86
+ candidates.push({ path: rawPath, requiredFrom });
42
87
  }
88
+ return candidates;
89
+ }
90
+ function planPolicyIssue(line) {
43
91
  return {
44
- ok: false,
45
- code: 'ERR_TRINITY_INCOMPLETE',
46
- 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.',
47
- details: { missing },
92
+ artifact: 'plan.md',
93
+ rule: 'receipt_policy_invalid',
94
+ ...(line === undefined ? {} : { line }),
48
95
  };
49
96
  }
50
- function hasHeading(content, needle) {
51
- const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
52
- return new RegExp(`^#{1,3}\\s+.*${escaped}`, 'imu').test(content);
97
+ function receiptTaskIssue(task, candidatePaths, index, locations) {
98
+ const prefix = 'tasks/' + String(index);
99
+ const duplicate = task.gates.findIndex(({ id }, gate) => task.gates.slice(0, gate).some((prior) => prior.id === id));
100
+ if (duplicate >= 0) {
101
+ return planPolicyIssue(locations.get(prefix + '/gates/' + String(duplicate) + '/id'));
102
+ }
103
+ const unsafe = task.observed.findIndex((item) => !isEvidencePath(item));
104
+ if (unsafe >= 0) {
105
+ return planPolicyIssue(locations.get(prefix + '/observed/' + String(unsafe)));
106
+ }
107
+ return disjointPaths([...candidatePaths, ...task.observed]) ? undefined : planPolicyIssue();
53
108
  }
54
- const PROTECTED_ROOTS = ['.sdd', '.git', 'planu/specs'];
55
- function scanManifest(planContent) {
56
- const { allowedFiles } = parseManifestContent(planContent);
57
- let globDelete = false;
58
- let protectedWrite = null;
59
- for (const [entryPath, permission] of allowedFiles) {
60
- if (permission === 'DELETE' && entryPath.includes('*')) {
61
- globDelete = true;
62
- }
63
- const normalized = path.posix.normalize(entryPath).toLowerCase();
64
- if (permission !== 'READ_ONLY' &&
65
- protectedWrite === null &&
66
- PROTECTED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))) {
67
- protectedWrite = entryPath;
68
- }
109
+ function bindReceiptTask(block, task, count) {
110
+ const command = receiptCommand(block);
111
+ if (!task || block.explicitId !== task.taskId || count !== 1 || !command) {
112
+ return undefined;
69
113
  }
70
- return { hasPath: allowedFiles.size > 0, globDelete, protectedWrite };
114
+ return {
115
+ ...task,
116
+ command,
117
+ ordinal: block.ordinal,
118
+ lineIndex: block.lineIndex,
119
+ };
71
120
  }
72
- export function parseManifestContent(content) {
73
- const allowedFiles = new Map();
74
- let inManifestSection = false;
75
- for (const rawLine of content.split('\n')) {
76
- const line = rawLine.trim();
77
- if (/^#{1,3}\s+/.test(line)) {
78
- inManifestSection = /^#{1,3}\s+.*file\s+manifest/i.test(line);
121
+ function readBindings(taskText, policy, plan, publicKey, locations) {
122
+ const blocks = taskBlocks(taskText);
123
+ const byId = new Map(policy.tasks.map((task) => [task.taskId, task]));
124
+ const counts = countTaskIds(blocks);
125
+ const candidates = parseCandidates(plan, policy.candidateCreates, dueTaskOrdinals(blocks, counts), locations);
126
+ if (candidates && !Array.isArray(candidates)) {
127
+ return { ...INVALID_POLICY, issue: candidates };
128
+ }
129
+ const preamble = taskText.split('\n').slice(0, blocks[0]?.lineIndex);
130
+ const directive = preamble.findIndex(hasReceiptDirective);
131
+ if (directive >= 0) {
132
+ return {
133
+ ...INVALID_POLICY,
134
+ issue: {
135
+ artifact: 'tasks.md',
136
+ rule: 'receipt_policy_invalid',
137
+ line: directive + 1,
138
+ },
139
+ };
140
+ }
141
+ if (!candidates || byId.size !== policy.tasks.length) {
142
+ return INVALID_POLICY;
143
+ }
144
+ const paths = candidates.map(({ path: candidatePath }) => candidatePath);
145
+ const tasks = new Map();
146
+ for (const block of blocks) {
147
+ const task = byId.get(block.id);
148
+ if (!task && !block.lines.some((line) => hasReceiptDirective(line))) {
79
149
  continue;
80
150
  }
81
- if (inManifestSection && /^[-*]\s+/.test(line)) {
82
- parseManifestLine(line, allowedFiles);
151
+ const binding = bindReceiptTask(block, task, counts.get(block.id));
152
+ if (!binding) {
153
+ const duplicate = task
154
+ ? blocks.find((item) => item.id === block.id && item.lineIndex > block.lineIndex)
155
+ : undefined;
156
+ return invalidTask(block, duplicate?.lineIndex);
83
157
  }
158
+ const issue = receiptTaskIssue(binding, paths, policy.tasks.findIndex((item) => item.taskId === block.id), locations);
159
+ if (issue) {
160
+ return { ...invalidTask(block), issue };
161
+ }
162
+ tasks.set(binding.taskId, binding);
84
163
  }
85
- return { allowedFiles };
164
+ return tasks.size === byId.size
165
+ ? { status: 'ready', tasks, candidates, publicKey }
166
+ : INVALID_POLICY;
86
167
  }
87
- function parseManifestLine(rawLine, allowedFiles) {
88
- const item = rawLine.replace(/^[-*]\s+/, '').trim();
89
- const prefixMatch = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item);
90
- if (prefixMatch?.[1] && prefixMatch[2]) {
91
- const prefixPath = toPosixPath(prefixMatch[2].trim());
92
- if (prefixPath.toLowerCase() === 'none') {
93
- return;
94
- }
95
- allowedFiles.set(prefixPath, prefixMatch[1].toUpperCase());
96
- return;
97
- }
98
- const postfixMatch = /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
99
- if (postfixMatch?.[1] && postfixMatch[2]) {
100
- const postfixPath = toPosixPath(postfixMatch[1].trim());
101
- if (postfixPath.toLowerCase() === 'none') {
102
- return;
168
+ export function parseVerificationReceiptPolicy(featureId, plan, taskText) {
169
+ const source = policyText(plan);
170
+ const { text } = source;
171
+ const invalid = {
172
+ ...INVALID_POLICY,
173
+ issue: {
174
+ artifact: 'plan.md',
175
+ rule: 'receipt_policy_invalid',
176
+ ...(source.line === undefined ? {} : { line: source.line }),
177
+ },
178
+ };
179
+ if (text === undefined) {
180
+ if (!taskText.split('\n').some((line) => hasReceiptDirective(line))) {
181
+ return { status: 'none' };
103
182
  }
104
- allowedFiles.set(postfixPath, postfixMatch[2].toUpperCase());
183
+ const block = taskBlocks(taskText).find(({ lines }) => lines.some((line) => hasReceiptDirective(line)));
184
+ return block
185
+ ? invalidTask(block)
186
+ : {
187
+ ...INVALID_POLICY,
188
+ issue: {
189
+ artifact: 'tasks.md',
190
+ rule: 'receipt_policy_invalid',
191
+ line: taskText.split('\n').findIndex(hasReceiptDirective) + 1,
192
+ },
193
+ };
194
+ }
195
+ if (text === null || !featureIdPattern.test(featureId)) {
196
+ return invalid;
197
+ }
198
+ const locations = source.locations ?? new Map();
199
+ const parsed = readPolicy(text, locations);
200
+ const policy = parsed.value;
201
+ if (!policy) {
202
+ return { ...invalid, issue: planPolicyIssue(parsed.line) };
105
203
  }
204
+ const publicKey = importReceiptPublicKey(policy.publicKey);
205
+ if (!publicKey) {
206
+ return { ...invalid, issue: planPolicyIssue(locations.get('publicKey')) };
207
+ }
208
+ const result = readBindings(taskText, policy, plan, publicKey, locations);
209
+ return result.status === 'invalid' && !result.issue
210
+ ? { ...result, issue: invalid.issue }
211
+ : result;
106
212
  }
107
- export function toPosixPath(value) {
108
- const posix = value.replaceAll('\\', '/');
109
- const absolute = posix.startsWith('/');
110
- const joined = posix
111
- .split('/')
112
- .filter((part) => part !== '' && part !== '.')
113
- .join('/');
114
- return absolute ? `/${joined}` : joined;
213
+ export function receiptSealFailure(featureId, plan, tasks) {
214
+ const policy = parseVerificationReceiptPolicy(featureId, plan, tasks);
215
+ if (policy.status === 'invalid') {
216
+ return {
217
+ ok: false,
218
+ code: 'ERR_TRINITY_INCOMPLETE',
219
+ message: 'The receipt verification policy or task directive is invalid.',
220
+ details: {
221
+ reason: 'receipt_policy_invalid',
222
+ issues: policy.issue ? [policy.issue] : [],
223
+ ...(policy.taskId ? { taskId: policy.taskId } : {}),
224
+ },
225
+ };
226
+ }
227
+ return undefined;
115
228
  }
116
229
  //# sourceMappingURL=feature-manifest.js.map
@@ -1,6 +1,11 @@
1
+ import type { HostSkillDiagnostics } from '../types/sdd-engine.js';
1
2
  export declare function isStaleV6HostDoc(content: string): boolean;
2
3
  export declare function copyGlobalRules(workspaceRoot: string, force?: boolean): Promise<'preserved' | 'replaced' | 'created'>;
3
4
  export declare function inspectHostSkillPack(workspaceRoot: string): Promise<string | undefined>;
5
+ export declare function inspectHostSkillPackDetailed(workspaceRoot: string, bundledVersion: string): Promise<{
6
+ hostSkills: HostSkillDiagnostics;
7
+ hint?: string;
8
+ }>;
4
9
  export declare function installHostSkillPack(workspaceRoot: string): Promise<string[]>;
5
10
  export declare function installCursorGuard(workspaceRoot: string): Promise<string[]>;
6
11
  export declare function installHostRulePack(workspaceRoot: string): Promise<string[]>;
@@ -1,7 +1,7 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { readTextInsideWorkspace } from './workspace-root.js';
4
+ import { readTextInsideWorkspaceDetailed } from './workspace-root.js';
5
5
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
6
6
  const TEMPLATES_ROOT = path.resolve(moduleDir, '..', '..', 'templates');
7
7
  const FALLBACK_HOST_BODY = `# Planu v8 host contract
@@ -12,6 +12,14 @@ The only SDD contract is \`.sdd/features/{FEAT-*}/spec.md\`, \`plan.md\`, and \`
12
12
 
13
13
  After the local client has registered the MCP server and the intended project is open, use \`sdd_list_features\` to inspect setup. A setup request authorizes \`sdd_init_workspace(scope="project")\` in that identified project; connecting or inspecting alone does not. Use the default \`force=false\` to preserve an existing current AGENTS.md. Read \`.agents/skills/planu-preflight-guardian/SKILL.md\` and the matching role immediately with \`sdd_read_file_slice\` before feature work. Initialization installs nine roles in four host formats. Matching files do not prove that the host has loaded them: a host/session catalog reload may be required, separately from restarting the MCP server. Do not promise automatic compliance by every client or model.
14
14
 
15
+ ## Read-only diagnostics
16
+
17
+ Use \`sdd_list_features.hostSkills\` to identify fixed installed role paths, causes and the bundled reference version. \`catalog\` stays \`unverified\` even when files match. An unavailable baseline requires inspecting the installation; unsafe paths require inspection before authorized setup. Project setup and client catalogue reload are explicit, separate actions.
18
+
19
+ For a rejected \`sdd_lock_spec\`, inspect \`error.details.issues\` for artifact, stable rule and optional 1-based original source line. Missing or ambiguous locations omit the line. Existing rejection codes and legacy details remain authoritative; rejection writes no lock. Do not automatically relock.
20
+
21
+ Before verification, request \`sdd_get_active_task\` with \`view="verification_preflight"\` and optional \`verification_receipts\`. Require \`verificationPreflight.version=1\`; older servers may ignore the view. Inspect per-gate states, aggregate blockers and \`nextAction\`. \`ready_to_attempt\` only permits attempting integration; runtime prerequisites and integration remain unverified. Preflight runs no command, consumes no grant, writes no artifact and issues no certificate. Keep the default task read and all nine tools unchanged.
22
+
15
23
  ## Delegation
16
24
 
17
25
  Delegate useful independent work within the active TASK through available native agents; keep trivial/dependent work sequential. Load the bounded protocol from \`spec-executor.md\` on demand; use \`spec-architect.md\` for workstream routing and \`verification-auditor.md\` for provenance checks. The parent alone applies canonical patches and certifies. Preserve all nine tools, lock, File Manifest, limits and protected-root controls; host capabilities grant no extra authority.
@@ -22,6 +30,7 @@ Delegate useful independent work within the active TASK through available native
22
30
  - If a pre-push, commitlint, or husky guard still requires \`planu/specs/SPEC-*/spec.md\`, that guard is the defect. Delete or rewrite it. Do not stub a SPEC file.
23
31
  - Quality lives in \`.claude/skills/\`, \`.cursor/skills/\`, \`.agents/skills/\`, and \`.gemini/skills/\`. Specs stay in \`.sdd/features\`. There is no validate MCP tool.
24
32
  - Agents must never grant themselves extra verification time or edit trusted launcher policy. Report budget failures for operator review; an approved startup grant does not change task or File Manifest authority.
33
+ - For tasks using the locked receipt policy, take the current challenge from sdd_get_active_task. Obtain gate evidence from the operator-controlled issuer and pass the signed receipts to sdd_complete_task. The server still runs the task integration command. A changed observed baseline requires reviewed resolution.
25
34
  `;
26
35
  const PROHIBITION = /\b(never|do not|don't|no longer|not|forbidden|prohibited|deleted|removed|retired|invalid|reject(?:s|ed)?)\b/iu;
27
36
  const LEGACY_TREE = /planu\/specs\/SPEC-|write (?:specs )?to planu\/specs/iu;
@@ -88,52 +97,97 @@ function hostSkillTargets(slug) {
88
97
  ];
89
98
  }
90
99
  export async function inspectHostSkillPack(workspaceRoot) {
91
- const advisory = 'Planu host skills are missing, different, or unreadable. Run sdd_init_workspace to refresh the bundled skill pack, then read the matching role before continuing.';
92
- let files;
93
- try {
94
- files = (await fs.readdir(path.join(TEMPLATES_ROOT, 'skills'))).filter((file) => file.endsWith('.md'));
95
- }
96
- catch {
97
- return advisory;
100
+ return (await inspectHostSkillPackDetailed(workspaceRoot, 'unknown')).hint;
101
+ }
102
+ async function batches(items, read) {
103
+ const results = [];
104
+ for (let offset = 0; offset < items.length; offset += 8) {
105
+ results.push(...(await Promise.allSettled(items.slice(offset, offset + 8).map(read))));
98
106
  }
99
- const expectedSlugs = Object.keys(HOST_SKILL_DESCRIPTIONS);
100
- if (files.length !== expectedSlugs.length ||
101
- files.some((file) => !expectedSlugs.includes(file.replace(/\.md$/u, '')))) {
102
- return advisory;
107
+ return results;
108
+ }
109
+ function collectHostSkillIssues(installed, targets) {
110
+ const issues = installed.flatMap((result, index) => {
111
+ if (result.status === 'fulfilled') {
112
+ return result.value ? [result.value] : [];
113
+ }
114
+ const target = targets[index];
115
+ return target
116
+ ? [
117
+ {
118
+ path: target.relative.split(path.sep).join('/'),
119
+ status: 'unreadable',
120
+ cause: 'read_failed',
121
+ },
122
+ ]
123
+ : [];
124
+ });
125
+ return issues;
126
+ }
127
+ function hostSkillAdvice(action) {
128
+ const setup = 'For requested project setup, use sdd_init_workspace(scope="project", force=false), then read the matching role. Catalog reload may require a host session refresh, separately from restarting MCP.';
129
+ switch (action) {
130
+ case 'inspect_installation':
131
+ return ('Inspect the pinned Planu installation and its bundled skill reference before project setup. ' +
132
+ setup);
133
+ case 'inspect_unsafe_paths':
134
+ return ('Review unsafe project skill paths and restore safe file boundaries before setup. ' + setup);
135
+ case 'review_project_setup':
136
+ return 'Planu host skills are missing, different, or unreadable. ' + setup;
137
+ case 'none':
138
+ return undefined;
103
139
  }
104
- let differs = false;
140
+ }
141
+ export async function inspectHostSkillPackDetailed(workspaceRoot, bundledVersion) {
142
+ const slugs = Object.keys(HOST_SKILL_DESCRIPTIONS).sort();
105
143
  const expected = new Map();
106
- // Each request rereads every body. Bound concurrent descriptors and drain each
107
- // batch before advancing, including when a file is missing or a read rejects.
108
- for (let offset = 0; offset < files.length; offset += 8) {
109
- const settled = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
110
- const slug = file.replace(/\.md$/u, '');
111
- const source = await readTextInsideWorkspace(TEMPLATES_ROOT, path.join(TEMPLATES_ROOT, 'skills', file), { maxBytes: 65_536 });
112
- return { slug, body: source.ok ? toHostSkillMarkdown(slug, source.text) : undefined };
113
- }));
114
- for (const result of settled) {
115
- if (result.status === 'fulfilled' && result.value.body !== undefined) {
116
- expected.set(result.value.slug, result.value.body);
117
- }
118
- else {
119
- differs = true;
120
- }
144
+ const sources = await batches(slugs, async (slug) => {
145
+ const source = await readTextInsideWorkspaceDetailed(TEMPLATES_ROOT, path.join(TEMPLATES_ROOT, 'skills', `${slug}.md`), { maxBytes: 65_536 });
146
+ if (source.ok) {
147
+ expected.set(slug, toHostSkillMarkdown(slug, source.text));
121
148
  }
122
- }
123
- const targets = files.flatMap((file) => {
124
- const slug = file.replace(/\.md$/u, '');
125
- return hostSkillTargets(slug).map((relative) => ({ slug, relative }));
126
149
  });
127
- for (let offset = 0; offset < targets.length; offset += 8) {
128
- const settled = await Promise.allSettled(targets.slice(offset, offset + 8).map(async ({ slug, relative }) => {
129
- const installed = await readTextInsideWorkspace(workspaceRoot, path.join(workspaceRoot, relative), { maxBytes: 65_536 });
130
- return installed.ok && installed.text === expected.get(slug);
131
- }));
132
- if (settled.some((result) => result.status === 'rejected' || !result.value)) {
133
- differs = true;
150
+ const available = sources.every((result) => result.status === 'fulfilled') && expected.size === slugs.length;
151
+ const targets = slugs.flatMap((slug) => hostSkillTargets(slug).map((relative) => ({ slug, relative })));
152
+ const installed = await batches(targets, async ({ slug, relative }) => {
153
+ const read = await readTextInsideWorkspaceDetailed(workspaceRoot, path.join(workspaceRoot, relative), { maxBytes: 65_536 });
154
+ const fixedPath = relative.split(path.sep).join('/');
155
+ if (!read.ok) {
156
+ return {
157
+ path: fixedPath,
158
+ status: read.cause === 'not_found' ? 'missing' : 'unreadable',
159
+ cause: read.cause,
160
+ };
134
161
  }
135
- }
136
- return differs ? advisory : undefined;
162
+ if (available && read.text !== expected.get(slug)) {
163
+ return {
164
+ path: fixedPath,
165
+ status: 'different',
166
+ cause: 'content_mismatch',
167
+ };
168
+ }
169
+ return undefined;
170
+ });
171
+ const issues = collectHostSkillIssues(installed, targets);
172
+ issues.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
173
+ const nextAction = !available
174
+ ? 'inspect_installation'
175
+ : issues.some((issue) => issue.cause === 'unsafe_path')
176
+ ? 'inspect_unsafe_paths'
177
+ : issues.length
178
+ ? 'review_project_setup'
179
+ : 'none';
180
+ return {
181
+ hostSkills: {
182
+ version: 1,
183
+ bundledVersion,
184
+ baseline: available ? 'available' : 'unavailable',
185
+ catalog: 'unverified',
186
+ issues,
187
+ nextAction,
188
+ },
189
+ ...(nextAction !== 'none' ? { hint: hostSkillAdvice(nextAction) } : {}),
190
+ };
137
191
  }
138
192
  async function readHostBody() {
139
193
  try {
@@ -186,7 +240,10 @@ export async function installCursorGuard(workspaceRoot) {
186
240
  await fs.copyFile(scriptSrc, scriptDest);
187
241
  await fs.chmod(scriptDest, 0o755);
188
242
  const incoming = readCursorHooks(await fs.readFile(hooksSrc, 'utf8'));
189
- let current = { version: 1, hooks: {} };
243
+ let current = {
244
+ version: 1,
245
+ hooks: {},
246
+ };
190
247
  try {
191
248
  current = readCursorHooks(await fs.readFile(hooksDest, 'utf8'));
192
249
  }
@@ -213,7 +270,10 @@ alwaysApply: true
213
270
 
214
271
  ${body}`;
215
272
  const targets = [
216
- { relative: path.join('.cursor', 'rules', 'planu-sdd.mdc'), contents: cursorRule },
273
+ {
274
+ relative: path.join('.cursor', 'rules', 'planu-sdd.mdc'),
275
+ contents: cursorRule,
276
+ },
217
277
  { relative: path.join('.claude', 'rules', 'planu-sdd.md'), contents: body },
218
278
  { relative: path.join('.gemini', 'planu-sdd.md'), contents: body },
219
279
  ];
@@ -0,0 +1,6 @@
1
+ import type { HostSkillReadResult } from '../types/sdd-engine.js';
2
+ /** Strict bounded reader for host diagnostics; legacy reader semantics remain unchanged. */
3
+ export declare function readTextInsideWorkspaceDetailed(workspaceRoot: string, absolutePath: string, options: {
4
+ maxBytes: number;
5
+ }): Promise<HostSkillReadResult>;
6
+ //# sourceMappingURL=host-skill-reader.d.ts.map