@planu/cli 8.3.0 → 8.5.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 (46) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +86 -2
  3. package/dist/sdd-engine/contracts.d.ts +13 -3
  4. package/dist/sdd-engine/contracts.js +48 -10
  5. package/dist/sdd-engine/feature-manifest.d.ts +2 -5
  6. package/dist/sdd-engine/feature-manifest.js +109 -184
  7. package/dist/sdd-engine/host-rule-pack.d.ts +5 -0
  8. package/dist/sdd-engine/host-rule-pack.js +106 -43
  9. package/dist/sdd-engine/host-skill-reader.d.ts +6 -0
  10. package/dist/sdd-engine/host-skill-reader.js +187 -0
  11. package/dist/sdd-engine/lock-integrity.d.ts +1 -0
  12. package/dist/sdd-engine/lock-integrity.js +25 -17
  13. package/dist/sdd-engine/receipt-assessment.d.ts +12 -0
  14. package/dist/sdd-engine/receipt-assessment.js +223 -0
  15. package/dist/sdd-engine/resume-history.d.ts +6 -0
  16. package/dist/sdd-engine/resume-history.js +117 -0
  17. package/dist/sdd-engine/resume-views.d.ts +9 -0
  18. package/dist/sdd-engine/resume-views.js +149 -0
  19. package/dist/sdd-engine/server.js +2 -4
  20. package/dist/sdd-engine/task-content.d.ts +18 -0
  21. package/dist/sdd-engine/task-content.js +36 -1
  22. package/dist/sdd-engine/task-window.d.ts +1 -0
  23. package/dist/sdd-engine/task-window.js +8 -1
  24. package/dist/sdd-engine/tools/compact-result.d.ts +6 -0
  25. package/dist/sdd-engine/tools/compact-result.js +66 -0
  26. package/dist/sdd-engine/tools/execution-tools.d.ts +1 -11
  27. package/dist/sdd-engine/tools/execution-tools.js +14 -32
  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-preflight.d.ts +11 -0
  35. package/dist/sdd-engine/verification-preflight.js +275 -0
  36. package/dist/sdd-engine/verification-receipts.d.ts +2 -10
  37. package/dist/sdd-engine/verification-receipts.js +2 -169
  38. package/dist/sdd-engine/workspace-root.d.ts +1 -0
  39. package/dist/sdd-engine/workspace-root.js +1 -0
  40. package/dist/types/completion.d.ts +9 -2
  41. package/dist/types/resume-views.d.ts +55 -0
  42. package/dist/types/resume-views.js +2 -0
  43. package/dist/types/sdd-engine.d.ts +78 -0
  44. package/package.json +1 -1
  45. package/templates/AGENTS.md +12 -0
  46. package/templates/host/planu-sdd.md +12 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## [8.5.0] - 2026-11-07
2
+
3
+ - Add the explicit `resume` checkpoint and `relock_history` views to `sdd_get_active_task`, preserving the ordinary task and preflight responses and all nine tools.
4
+ - Bound each handler-produced compact text to 8,192 UTF-8 bytes. Resume identifies the captured task, progress, current evidence and pending integration; history exposes at most eight descending references per page tied to the captured lock.
5
+ - Preserve original history and receipt inputs. Read-only evidence is not certification: neither view runs verification, writes artifacts, acquires a lease or changes locked authority or budgets.
6
+ - Synchronize package, host guidance and EN/ES/PT website facts for compact resumption.
7
+
8
+ ## [8.4.0] - 2026-11-07
9
+
10
+ - Diagnose installed host roles through `sdd_list_features`: fixed paths, concrete causes, bundled reference version and safe next action. The host catalogue remains unverified.
11
+ - Add artifact, stable rule and exact 1-based source locations to trinity rejection issues where a location exists, preserving rejection codes, legacy details and lock bytes on rejection.
12
+ - Add the explicit `verification_preflight` view to `sdd_get_active_task`, with optional signed receipts, per-gate evidence states, blockers and next action. It runs no command, writes no artifact and keeps integration `not_run`; readiness permits an attempt, not a runtime or integration claim.
13
+ - Preserve the nine tools, ordinary active-task response, dependencies and verification authority. Synchronize shipped guidance and EN/ES/PT website facts.
14
+
1
15
  ## [8.3.0] - 2026-11-06
2
16
 
3
17
  - Opted-in tasks can require reusable Ed25519 receipts for locally verified gates. Planu binds the evidence to the active task, workspace, lock, candidate files, and reviewed dependencies before running the integration command.
package/README.md CHANGED
@@ -112,7 +112,7 @@ After the one-time client registration above, ask your agent:
112
112
 
113
113
  > Set up Planu in this project and tell me the next step.
114
114
 
115
- The guided route starts with `sdd_list_features`. If setup is missing or unverified, use `sdd_init_workspace(scope=project)` without `force` for the identified project. The setup request already supplies that project's setup intent. Keep the MCP server bound to the project through roots or cwd, rather than `$HOME`.
115
+ The guided route starts with `sdd_list_features`. Inspect `hostSkills` for installed role issues. When project setup is authorized and the installed pack needs repair, use `sdd_init_workspace(scope=project)` without `force` for the identified project. The setup request already supplies that project's setup intent; `catalog: "unverified"` alone does not establish a file problem or authorize setup. Keep the MCP server bound to the project through roots or cwd, rather than `$HOME`.
116
116
 
117
117
  Immediately after init, use the canonical `sdd_read_file_slice` tool to read `.agents/skills/planu-preflight-guardian/SKILL.md` and the installed role for the next action, such as `.agents/skills/planu-spec-architect/SKILL.md` for planning. Init installs role files; native discovery in the client's skill catalog may require a client reload or a new session. That catalog reload is separate from restarting MCP. The instructions guide an agent; the server cannot guarantee that a host has loaded a role or that a model follows it.
118
118
 
@@ -136,6 +136,90 @@ There is no timeout tool argument. The nine tool names are unchanged. The option
136
136
 
137
137
  The reviewed operator procedure is in the repository guide `docs/verification-budget.md`: finite local-build fingerprint, exact policy schema, per-process Node 24.22.1 PATH, SDK request budget of 660000 ms, one-use launch and safe disable/reconciliation. The grant is not a global registration or a cache replacement. Barbuno acceptance remains a separate handoff.
138
138
 
139
+ ## Read-only diagnostics
140
+
141
+ The existing nine tools expose additive diagnostics since 8.4.0; 8.5.0 adds compact resume and history views. An ordinary `sdd_get_active_task` request keeps its previous response shape.
142
+
143
+ `sdd_list_features` includes `hostSkills`. For example, a missing installed role can produce this field (other installed files match the available bundled reference):
144
+
145
+ ```json
146
+ {
147
+ "version": 1,
148
+ "bundledVersion": "8.5.0",
149
+ "baseline": "available",
150
+ "catalog": "unverified",
151
+ "issues": [{
152
+ "path": ".agents/skills/planu-spec-executor/SKILL.md",
153
+ "status": "missing",
154
+ "cause": "not_found"
155
+ }],
156
+ "nextAction": "review_project_setup"
157
+ }
158
+ ```
159
+
160
+ Issues use the fixed workspace-relative paths of the nine roles across four hosts and concrete causes such as `content_mismatch`, `access_denied` or `unsafe_path`. `bundledVersion` identifies the shipped reference, not the installed role or client. An unavailable reference reports `baseline: "unavailable"` and `inspect_installation` rather than inferring project mismatches. Inspect unsafe paths before setup; use the explicit project setup route for repair only when authorized. A matching pack still leaves `catalog: "unverified"`; client catalogue reload and MCP restart remain separate actions.
161
+
162
+ `sdd_lock_spec` keeps existing rejection codes and legacy details, adding bounded `error.details.issues`. For a protected manifest declaration on the fifth source line, the diagnostic includes:
163
+
164
+ ```json
165
+ {
166
+ "artifact": "plan.md",
167
+ "rule": "protected_write",
168
+ "line": 5
169
+ }
170
+ ```
171
+
172
+ That structural rejection keeps `ERR_TRINITY_INCOMPLETE`. Lines are 1-based original source locations. Missing sections and ambiguous cross-declaration failures omit `line`; errors do not echo the manifest path or source text. A rejected initial lock or relock writes no lock. Diagnostics do not authorize automatic relocking.
173
+
174
+ Request preflight explicitly through `sdd_get_active_task`:
175
+
176
+ ```json
177
+ {"feature_id":"FEAT-EXAMPLE","view":"verification_preflight"}
178
+ ```
179
+
180
+ Optionally supply `verification_receipts` with the signed receipt array described below. Receipts require an explicit `verification_preflight` or `resume` view. For an opted-in task with one required gate named `contents`, no supplied receipts and otherwise available inputs, `data.verificationPreflight` is:
181
+
182
+ ```json
183
+ {
184
+ "version": 1,
185
+ "taskId": "TASK-1",
186
+ "status": "blocked",
187
+ "gates": [{"gateId":"contents","state":"receipt_missing","reason":"receipt_missing"}],
188
+ "blockers": [],
189
+ "integration": "not_run",
190
+ "nextAction": "obtain_receipts"
191
+ }
192
+ ```
193
+
194
+ Check `version: 1` on the requested response: an older server may ignore optional arguments. Inspect both per-gate states and aggregate blockers. Preflight can identify rejected evidence, unavailable inputs, changed observed baselines, missing commands, unsupported platforms or matching scoped receipt grants, and lock/guard problems. Follow `nextAction`; a changed observed baseline requires restoring the input or the existing reviewed relock route. An ordinary task rejects supplied receipts with `receipt_not_configured`.
195
+
196
+ `ready_to_attempt` with `attempt_integration` means these read-only checks passed for the current candidate. Runtime prerequisites, write access and integration remain unverified. `not_applicable` means a locked feature has no active task. Preflight runs no command, consumes no grant, writes no artifact and issues no certificate; setup, relock and completion remain explicit actions.
197
+
198
+ ### Resume a task from one compact checkpoint
199
+
200
+ ```json
201
+ {"feature_id":"FEAT-EXAMPLE","view":"resume"}
202
+ ```
203
+
204
+ Require `data.resume.version=1`: older servers may ignore the requested view. The checkpoint identifies task and progress, captured contract hashes, candidate and observed-input digests when available, per-gate evidence, blockers, pending integration and a safe next action. Read the ordinary active task next to obtain its authorized body and File Manifest. Optional `verification_receipts` are checked against that captured candidate; observed receipts are not certification. Missing evidence is pending and does not prove a verifier never ran. `candidate:null` does not establish successful checks. Integration remains `pending` for an active task; the compact read never certifies it.
205
+
206
+ `history_cursor` is accepted only with `view="relock_history"`. If `history` is null, follow `nextAction` without requesting history. If `history.firstCursor` is null, there are no records; do not request history. Otherwise use the checkpoint's `history.firstCursor` as `history_cursor` with `view="relock_history"`, then follow `data.relockHistory.nextCursor` until null. Require `data.relockHistory.version=1`. Pages contain at most eight records in descending zero-based storage-index order. A stale cursor requires rereading the checkpoint; never silently continue with a different lock. Empty history has no cursor. Resume references the history without loading reasons or the full task; malformed selected history fails without a partial page.
207
+
208
+ Every handler-produced compact result, including controlled failures, contains exactly one `content[0].text` of at most 8,192 UTF-8 bytes and no `structuredContent` or auxiliary content. SDK/JSON-RPC validation before handler dispatch is a separate boundary. Neither compact view executes verification, consumes a grant, writes an artifact, acquires a lease or issues a certificate. Guard presence never proves an owner stopped. Locks, File Manifest authority, receipt inputs, stored history and verification budgets remain unchanged.
209
+
210
+ For an authorized reader holding the original `.lock` bytes, the exact digest calculations are:
211
+
212
+ ```js
213
+ import { createHash } from 'node:crypto';
214
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
215
+ const lockSha256 = sha256(rawLockBytes);
216
+ const record = JSON.parse(rawLockBytes.toString('utf8')).relockHistory[index];
217
+ const recordSha256 = sha256(Buffer.from(JSON.stringify(record), 'utf8'));
218
+ const reasonSha256 = sha256(Buffer.from(record.reason, 'utf8'));
219
+ ```
220
+
221
+ `recordSha256` hashes the complete parsed record, including extra fields. ECMAScript JSON parse/stringify normalization applies: numeric-key ordering, normalized numbers and escapes, and last duplicate key wins. Raw byte identity belongs to `lockSha256`. Node UTF-8 encoding replaces lone UTF-16 surrogates with U+FFFD, so `reasonSha256` is not a unique UTF-16-string identity; record and raw-lock hashes retain their separate correspondence. Hashes reference stored bytes, not the author or provenance of historical actions. Original reasons and records remain in the lock.
222
+
139
223
  ## Reusable verification receipts
140
224
 
141
225
  Opt in by adding a level-two `Verification Receipts v1` heading to the locked plan, followed by a single JSON fence with the policy formatted using `JSON.stringify(policy, null, 2)`. It contains:
@@ -270,7 +354,7 @@ See the [Planu Proprietary Free-Use License](LICENSE) and [planu.dev/license](ht
270
354
  "mcpServers": {
271
355
  "planu": {
272
356
  "command": "npx",
273
- "args": ["-y", "@planu/cli@8.3.0"],
357
+ "args": ["-y", "@planu/cli@8.5.0"],
274
358
  "cwd": ".",
275
359
  "env": {
276
360
  "PLANU_WORKSPACE": "."
@@ -66,15 +66,25 @@ export declare const ReadFileSliceInputSchema: z.ZodObject<{
66
66
  start_line: z.ZodNumber;
67
67
  end_line: z.ZodNumber;
68
68
  }, z.core.$strip>;
69
- export declare const GetActiveTaskInputSchema: z.ZodObject<{
70
- feature_id: z.ZodString;
71
- }, z.core.$strip>;
72
69
  export declare const ApplyFilePatchInputSchema: z.ZodObject<{
73
70
  feature_id: z.ZodString;
74
71
  path: z.ZodString;
75
72
  search_content: z.ZodString;
76
73
  replace_content: z.ZodString;
77
74
  }, z.core.$strip>;
75
+ export declare const GetActiveTaskInputSchema: z.ZodObject<{
76
+ feature_id: z.ZodString;
77
+ view: z.ZodOptional<z.ZodEnum<{
78
+ relock_history: "relock_history";
79
+ resume: "resume";
80
+ verification_preflight: "verification_preflight";
81
+ }>>;
82
+ verification_receipts: z.ZodOptional<z.ZodArray<z.ZodPreprocess<z.ZodObject<{}, z.core.$loose>, unknown>>>;
83
+ history_cursor: z.ZodOptional<z.ZodPreprocess<z.ZodObject<{
84
+ snapshotSha256: z.ZodString;
85
+ startIndex: z.ZodNumber;
86
+ }, z.core.$strip>, unknown>>;
87
+ }, z.core.$strip>;
78
88
  export declare const CompleteTaskInputSchema: z.ZodObject<{
79
89
  feature_id: z.ZodString;
80
90
  task_id: z.ZodString;
@@ -49,9 +49,6 @@ export const ReadFileSliceInputSchema = z.object({
49
49
  start_line: z.number().int().min(1),
50
50
  end_line: z.number().int().min(1),
51
51
  });
52
- export const GetActiveTaskInputSchema = z.object({
53
- feature_id: FeatureIdSchema,
54
- });
55
52
  export const ApplyFilePatchInputSchema = z.object({
56
53
  feature_id: FeatureIdSchema,
57
54
  path: z.string().min(1),
@@ -65,16 +62,57 @@ const VerificationReceiptInputSchema = z.preprocess((input, context) => {
65
62
  }
66
63
  return input;
67
64
  }, z.looseObject({}, { error: 'Invalid verification receipt element.' }));
65
+ const VerificationReceiptsInputSchema = z
66
+ .array(VerificationReceiptInputSchema, {
67
+ error: 'Invalid verification receipt array.',
68
+ })
69
+ .min(1, { error: 'Invalid verification receipt array length.' })
70
+ .max(32, { error: 'Invalid verification receipt array length.' })
71
+ .optional();
72
+ const HistoryCursorShape = z.strictObject({
73
+ snapshotSha256: z.string().regex(/^[a-f0-9]{64}$/u),
74
+ startIndex: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
75
+ });
76
+ // Sanitize before SDK validation can echo arbitrary unknown cursor keys.
77
+ const HistoryCursorInputSchema = z.preprocess((input) => {
78
+ const parsed = HistoryCursorShape.safeParse(input);
79
+ return parsed.success ? parsed.data : { snapshotSha256: '0'.repeat(64), startIndex: -1 };
80
+ }, z.object({
81
+ snapshotSha256: z.string().regex(/^[a-f0-9]{64}$/u),
82
+ startIndex: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
83
+ }));
84
+ export const GetActiveTaskInputSchema = z
85
+ .object({
86
+ feature_id: FeatureIdSchema,
87
+ view: z
88
+ .enum(['verification_preflight', 'resume', 'relock_history'], {
89
+ error: 'Invalid active task view.',
90
+ })
91
+ .optional(),
92
+ verification_receipts: VerificationReceiptsInputSchema,
93
+ history_cursor: HistoryCursorInputSchema.optional(),
94
+ })
95
+ .superRefine((input, context) => {
96
+ if (input.history_cursor !== undefined && input.view !== 'relock_history') {
97
+ context.addIssue({
98
+ code: 'custom',
99
+ message: 'History cursor requires the history view.',
100
+ path: ['history_cursor'],
101
+ });
102
+ }
103
+ if (input.verification_receipts !== undefined &&
104
+ !['verification_preflight', 'resume'].includes(input.view ?? '')) {
105
+ context.addIssue({
106
+ code: 'custom',
107
+ message: 'Verification receipts require the verification_preflight view.',
108
+ path: ['verification_receipts'],
109
+ });
110
+ }
111
+ });
68
112
  export const CompleteTaskInputSchema = z.object({
69
113
  feature_id: FeatureIdSchema,
70
114
  task_id: z.string().min(1),
71
115
  verification_output: z.string().min(1).optional(),
72
- verification_receipts: z
73
- .array(VerificationReceiptInputSchema, {
74
- error: 'Invalid verification receipt array.',
75
- })
76
- .min(1, { error: 'Invalid verification receipt array length.' })
77
- .max(32, { error: 'Invalid verification receipt array length.' })
78
- .optional(),
116
+ verification_receipts: VerificationReceiptsInputSchema,
79
117
  });
80
118
  //# sourceMappingURL=contracts.js.map
@@ -1,8 +1,5 @@
1
- import type { ParsedManifest, ReceiptPolicyResult, ReceiptSealFailure } from '../types/sdd-engine.js';
2
- import type { TrinityCompleteness } from '../types/completion.js';
3
- export declare function assessTrinityCompleteness(specContent: string, planContent: string, tasksContent: string): TrinityCompleteness;
4
- export declare function parseManifestContent(content: string): ParsedManifest;
5
- export declare function toPosixPath(value: string): string;
1
+ import type { ReceiptPolicyResult, ReceiptSealFailure } from '../types/sdd-engine.js';
2
+ export { assessTrinityCompleteness, parseManifestContent, toPosixPath, } from './trinity-structure.js';
6
3
  export declare function parseVerificationReceiptPolicy(featureId: string, plan: string, taskText: string): ReceiptPolicyResult;
7
4
  export declare function receiptSealFailure(featureId: string, plan: string, tasks: string): ReceiptSealFailure | undefined;
8
5
  //# sourceMappingURL=feature-manifest.d.ts.map
@@ -1,127 +1,9 @@
1
- import * as path from 'node:path';
2
1
  import { z } from 'zod';
3
- import { countTaskIds, dueTaskOrdinals, hasReceiptDirective, insideMarkdownBlock, receiptCommand, taskBlocks, } from './task-content.js';
2
+ import { countTaskIds, dueTaskOrdinals, hasReceiptDirective, receiptCommand, taskBlocks, } from './task-content.js';
4
3
  import { featureIdPattern, gateIdPattern, importReceiptPublicKey, maxVerificationReceipts, sha256Schema, taskIdPattern, } from './verification-receipts.js';
5
4
  import { disjointPaths, isEvidencePath } from './feature-authority.js';
6
- const CHECKBOX_TASK = /^[-*]\s*\[[ xX]\]/u;
7
- const BDD_KEYWORDS = [/\bGIVEN\b/u, /\bWHEN\b/u, /\bTHEN\b/u];
8
- export function assessTrinityCompleteness(specContent, planContent, tasksContent) {
9
- const missing = [];
10
- if (!hasHeading(specContent, 'Out-of-Scope')) {
11
- missing.push('out_of_scope');
12
- }
13
- if (!hasHeading(specContent, 'Error Matrix')) {
14
- missing.push('error_matrix');
15
- }
16
- if (!BDD_KEYWORDS.every((keyword) => keyword.test(specContent))) {
17
- missing.push('bdd');
18
- }
19
- if (!hasHeading(planContent, 'Frozen Dependencies')) {
20
- missing.push('frozen_dependencies');
21
- }
22
- const hasTask = tasksContent.split('\n').some((line) => CHECKBOX_TASK.test(line.trim()));
23
- const manifest = scanManifest(planContent);
24
- if (!manifest.hasPath) {
25
- missing.push('manifest_path');
26
- }
27
- if (!hasTask) {
28
- missing.push('checkbox_task');
29
- }
30
- if (manifest.globDelete) {
31
- return {
32
- ok: false,
33
- code: 'ERR_TRINITY_INCOMPLETE',
34
- message: 'DELETE File Manifest entries must be exact paths, not globs.',
35
- };
36
- }
37
- if (manifest.protectedWrite !== null) {
38
- return {
39
- ok: false,
40
- code: 'ERR_TRINITY_INCOMPLETE',
41
- message: `File Manifest cannot grant writes on protected root path '${manifest.protectedWrite}' (.sdd, .git, planu/specs).`,
42
- };
43
- }
44
- if (missing.length === 0) {
45
- return { ok: true };
46
- }
47
- return {
48
- ok: false,
49
- code: 'ERR_TRINITY_INCOMPLETE',
50
- 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.',
51
- details: { missing },
52
- };
53
- }
54
- function hasHeading(content, needle) {
55
- const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
- return new RegExp(`^#{1,3}\\s+.*${escaped}`, 'imu').test(content);
57
- }
58
- const PROTECTED_ROOTS = ['.sdd', '.git', 'planu/specs'];
59
- function scanManifest(planContent) {
60
- const { allowedFiles } = parseManifestContent(planContent);
61
- let globDelete = false;
62
- let protectedWrite = null;
63
- for (const [entryPath, permission] of allowedFiles) {
64
- if (permission === 'DELETE' && entryPath.includes('*')) {
65
- globDelete = true;
66
- }
67
- const normalized = path.posix.normalize(entryPath).toLowerCase();
68
- if (permission !== 'READ_ONLY' &&
69
- protectedWrite === null &&
70
- PROTECTED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))) {
71
- protectedWrite = entryPath;
72
- }
73
- }
74
- return { hasPath: allowedFiles.size > 0, globDelete, protectedWrite };
75
- }
76
- export function parseManifestContent(content) {
77
- const allowedFiles = new Map();
78
- for (const { rawPath, permission } of manifestEntries(content)) {
79
- allowedFiles.set(toPosixPath(rawPath), permission);
80
- }
81
- return { allowedFiles };
82
- }
83
- function manifestEntries(content) {
84
- const entries = [];
85
- let inManifestSection = false;
86
- for (const rawLine of content.split('\n')) {
87
- const line = rawLine.trim();
88
- if (/^#{1,3}\s+/.test(line)) {
89
- inManifestSection = /^#{1,3}\s+.*file\s+manifest/i.test(line);
90
- continue;
91
- }
92
- if (inManifestSection && /^[-*]\s+/.test(line)) {
93
- const entry = parseManifestLine(line);
94
- if (entry && toPosixPath(entry.rawPath).toLowerCase() !== 'none') {
95
- entries.push(entry);
96
- }
97
- }
98
- }
99
- return entries;
100
- }
101
- function parseManifestLine(rawLine) {
102
- const item = rawLine.replace(/^[-*]\s+/, '').trim();
103
- const prefix = /^(CREATE|MODIFY|READ_ONLY|DELETE):\s*`?([^`\s#]+)`?\s*$/i.exec(item);
104
- if (prefix?.[1] && prefix[2]) {
105
- return { rawPath: prefix[2], permission: prefix[1].toUpperCase() };
106
- }
107
- const postfix = /^`?([^`\s:#]+)`?:\s*(CREATE|MODIFY|READ_ONLY|DELETE)\s*$/i.exec(item);
108
- if (postfix?.[1] && postfix[2]) {
109
- return { rawPath: postfix[1], permission: postfix[2].toUpperCase() };
110
- }
111
- return undefined;
112
- }
113
- export function toPosixPath(value) {
114
- const posix = value.replaceAll('\\', '/');
115
- const absolute = posix.startsWith('/');
116
- const joined = posix
117
- .split('/')
118
- .filter((part) => part !== '' && part !== '.')
119
- .join('/');
120
- return absolute ? `/${joined}` : joined;
121
- }
122
- const POLICY_LIMIT = 65_536;
123
- const RECEIPT_HEADING = /^#{1,6}\s+Verification\s+Receipts(?:\s*$|\s*v[0-9])/iu;
124
- const FENCE = String.fromCharCode(96).repeat(3);
5
+ import { candidateCreationIssue, invalidTask, invalidCandidate, candidateIssue, manifestEntries, policyIssueLine, policyText, toPosixPath, } from './trinity-structure.js';
6
+ export { assessTrinityCompleteness, parseManifestContent, toPosixPath, } from './trinity-structure.js';
125
7
  const policySchema = z.strictObject({
126
8
  publicKey: z.string().max(128),
127
9
  tasks: z
@@ -148,63 +30,41 @@ const policySchema = z.strictObject({
148
30
  .max(64),
149
31
  });
150
32
  const INVALID_POLICY = { status: 'invalid' };
151
- function policyText(plan) {
152
- const lines = plan.replaceAll('\r\n', '\n').split('\n');
153
- const headings = lines.flatMap((line, index) => RECEIPT_HEADING.test(line.trim()) ? [index] : []);
154
- if (headings.length === 0) {
155
- return undefined;
156
- }
157
- const start = headings[0];
158
- if (start === undefined ||
159
- headings.length !== 1 ||
160
- insideMarkdownBlock(lines.slice(0, start)) ||
161
- lines[start]?.trim() !== '## Verification Receipts v1') {
162
- return null;
163
- }
164
- const after = lines.findIndex((line, index) => index > start && /^#{1,2}\s/u.test(line.trim()));
165
- const section = lines
166
- .slice(start + 1, after < 0 ? undefined : after)
167
- .join('\n')
168
- .trim();
169
- const prefix = FENCE + 'json\n';
170
- const suffix = '\n' + FENCE;
171
- if (!section.startsWith(prefix) || !section.endsWith(suffix)) {
172
- return null;
173
- }
174
- const payload = section.slice(prefix.length, -suffix.length);
175
- return Buffer.byteLength(payload) <= POLICY_LIMIT ? payload.trim() : null;
176
- }
177
- function readPolicy(text) {
33
+ function readPolicy(text, locations) {
178
34
  try {
179
35
  const value = JSON.parse(text);
180
36
  if (JSON.stringify(value, null, 2) !== text) {
181
- return undefined;
37
+ return {};
182
38
  }
183
39
  const parsed = policySchema.safeParse(value);
184
- return parsed.success ? parsed.data : undefined;
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 };
185
45
  }
186
46
  catch {
187
- return undefined;
47
+ return {};
188
48
  }
189
49
  }
190
- function invalidTask(block) {
191
- const id = block.explicitId ?? block.id;
192
- return taskIdPattern.test(id) ? { status: 'invalid', taskId: id } : INVALID_POLICY;
193
- }
194
- function parseCandidates(plan, creates, dueTasks) {
50
+ function parseCandidates(plan, creates, dueTasks, locations) {
195
51
  const entries = manifestEntries(plan);
196
52
  const writable = entries.filter(({ permission }) => permission !== 'READ_ONLY');
53
+ if (writable.length > 64) {
54
+ return candidateIssue(writable[64]);
55
+ }
197
56
  const paths = writable.map(({ rawPath }) => rawPath);
198
57
  if (writable.length < 1 ||
199
- writable.length > 64 ||
200
58
  !paths.every(isEvidencePath) ||
201
59
  !disjointPaths(paths) ||
202
60
  writable.some(({ permission }) => permission === 'DELETE')) {
203
- return undefined;
61
+ const bad = invalidCandidate(writable, paths);
62
+ return candidateIssue(bad);
204
63
  }
205
64
  const writes = new Set(paths.map((item) => item.toLowerCase()));
206
- if (entries.some(({ rawPath, permission }) => permission === 'READ_ONLY' && writes.has(toPosixPath(rawPath).toLowerCase()))) {
207
- return undefined;
65
+ const shadow = entries.find(({ rawPath, permission }) => permission === 'READ_ONLY' && writes.has(toPosixPath(rawPath).toLowerCase()));
66
+ if (shadow) {
67
+ return candidateIssue(undefined);
208
68
  }
209
69
  const mappings = new Map(creates.map(({ path: candidatePath, requiredFromTaskId }) => [
210
70
  candidatePath,
@@ -215,39 +75,70 @@ function parseCandidates(plan, creates, dueTasks) {
215
75
  return undefined;
216
76
  }
217
77
  const candidates = [];
218
- for (const { rawPath, permission } of writable) {
78
+ for (const entry of writable) {
79
+ const { rawPath, permission } = entry;
219
80
  const due = mappings.get(rawPath);
220
81
  const requiredFrom = permission === 'CREATE' && due !== undefined ? dueTasks.get(due) : 1;
221
82
  if (requiredFrom === undefined ||
222
83
  (permission === 'CREATE' ? due === undefined : due !== undefined)) {
223
- return undefined;
84
+ return candidateCreationIssue(rawPath, creates, requiredFrom, locations);
224
85
  }
225
86
  candidates.push({ path: rawPath, requiredFrom });
226
87
  }
227
88
  return candidates;
228
89
  }
229
- function bindReceiptTask(block, task, count, candidatePaths) {
90
+ function planPolicyIssue(line) {
91
+ return {
92
+ artifact: 'plan.md',
93
+ rule: 'receipt_policy_invalid',
94
+ ...(line === undefined ? {} : { line }),
95
+ };
96
+ }
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();
108
+ }
109
+ function bindReceiptTask(block, task, count) {
230
110
  const command = receiptCommand(block);
231
- if (!task ||
232
- block.explicitId !== task.taskId ||
233
- count !== 1 ||
234
- !command ||
235
- new Set(task.gates.map(({ id }) => id)).size !== task.gates.length ||
236
- !task.observed.every(isEvidencePath) ||
237
- !disjointPaths([...candidatePaths, ...task.observed])) {
111
+ if (!task || block.explicitId !== task.taskId || count !== 1 || !command) {
238
112
  return undefined;
239
113
  }
240
- return { ...task, command, ordinal: block.ordinal, lineIndex: block.lineIndex };
114
+ return {
115
+ ...task,
116
+ command,
117
+ ordinal: block.ordinal,
118
+ lineIndex: block.lineIndex,
119
+ };
241
120
  }
242
- function readBindings(taskText, policy, plan, publicKey) {
121
+ function readBindings(taskText, policy, plan, publicKey, locations) {
243
122
  const blocks = taskBlocks(taskText);
244
123
  const byId = new Map(policy.tasks.map((task) => [task.taskId, task]));
245
124
  const counts = countTaskIds(blocks);
246
- const candidates = parseCandidates(plan, policy.candidateCreates, dueTaskOrdinals(blocks, counts));
125
+ const candidates = parseCandidates(plan, policy.candidateCreates, dueTaskOrdinals(blocks, counts), locations);
126
+ if (candidates && !Array.isArray(candidates)) {
127
+ return { ...INVALID_POLICY, issue: candidates };
128
+ }
247
129
  const preamble = taskText.split('\n').slice(0, blocks[0]?.lineIndex);
248
- if (!candidates ||
249
- byId.size !== policy.tasks.length ||
250
- preamble.some((line) => hasReceiptDirective(line))) {
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) {
251
142
  return INVALID_POLICY;
252
143
  }
253
144
  const paths = candidates.map(({ path: candidatePath }) => candidatePath);
@@ -257,9 +148,16 @@ function readBindings(taskText, policy, plan, publicKey) {
257
148
  if (!task && !block.lines.some((line) => hasReceiptDirective(line))) {
258
149
  continue;
259
150
  }
260
- const binding = bindReceiptTask(block, task, counts.get(block.id), paths);
151
+ const binding = bindReceiptTask(block, task, counts.get(block.id));
261
152
  if (!binding) {
262
- return invalidTask(block);
153
+ const duplicate = task
154
+ ? blocks.find((item) => item.id === block.id && item.lineIndex > block.lineIndex)
155
+ : undefined;
156
+ return invalidTask(block, duplicate?.lineIndex);
157
+ }
158
+ const issue = receiptTaskIssue(binding, paths, policy.tasks.findIndex((item) => item.taskId === block.id), locations);
159
+ if (issue) {
160
+ return { ...invalidTask(block), issue };
263
161
  }
264
162
  tasks.set(binding.taskId, binding);
265
163
  }
@@ -268,23 +166,49 @@ function readBindings(taskText, policy, plan, publicKey) {
268
166
  : INVALID_POLICY;
269
167
  }
270
168
  export function parseVerificationReceiptPolicy(featureId, plan, taskText) {
271
- const text = policyText(plan);
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
+ };
272
179
  if (text === undefined) {
273
180
  if (!taskText.split('\n').some((line) => hasReceiptDirective(line))) {
274
181
  return { status: 'none' };
275
182
  }
276
183
  const block = taskBlocks(taskText).find(({ lines }) => lines.some((line) => hasReceiptDirective(line)));
277
- return block ? invalidTask(block) : INVALID_POLICY;
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
+ };
278
194
  }
279
195
  if (text === null || !featureIdPattern.test(featureId)) {
280
- return INVALID_POLICY;
196
+ return invalid;
281
197
  }
282
- const policy = readPolicy(text);
198
+ const locations = source.locations ?? new Map();
199
+ const parsed = readPolicy(text, locations);
200
+ const policy = parsed.value;
283
201
  if (!policy) {
284
- return INVALID_POLICY;
202
+ return { ...invalid, issue: planPolicyIssue(parsed.line) };
285
203
  }
286
204
  const publicKey = importReceiptPublicKey(policy.publicKey);
287
- return publicKey ? readBindings(taskText, policy, plan, publicKey) : INVALID_POLICY;
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;
288
212
  }
289
213
  export function receiptSealFailure(featureId, plan, tasks) {
290
214
  const policy = parseVerificationReceiptPolicy(featureId, plan, tasks);
@@ -295,6 +219,7 @@ export function receiptSealFailure(featureId, plan, tasks) {
295
219
  message: 'The receipt verification policy or task directive is invalid.',
296
220
  details: {
297
221
  reason: 'receipt_policy_invalid',
222
+ issues: policy.issue ? [policy.issue] : [],
298
223
  ...(policy.taskId ? { taskId: policy.taskId } : {}),
299
224
  },
300
225
  };
@@ -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[]>;