@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
@@ -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,18 @@ 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
+
23
+ To resume, request \`sdd_get_active_task\` with \`view="resume"\` and optional \`verification_receipts\`; require \`data.resume.version=1\` before using its task, progress, candidate, observed-input digests, gates, pending integration and \`nextAction\`. Then use the ordinary active-task read for its authorized body and File Manifest. Unsupplied evidence is pending; observed receipts are not certification. Neither compact view runs verification, writes artifacts or grants permission.
24
+
25
+ If \`history\` is null, follow \`nextAction\` without requesting history. If \`history.firstCursor\` is null, there are no records; do not request history. Otherwise use \`view="relock_history"\` with the checkpoint's \`history.firstCursor\` as \`history_cursor\`, then each \`nextCursor\`, to read at most eight descending records per page. \`history_cursor\` is accepted only with \`view="relock_history"\`. Stop when \`nextCursor\` is null. Require \`data.relockHistory.version=1\`; stale cursors require rereading the checkpoint. Each handler-produced compact result has exactly one text block of at most 8,192 UTF-8 bytes, without \`structuredContent\`; SDK validation before dispatch is a separate boundary. History digests reference the original unmodified lock; they do not attest historical actions. Preserve guards, locked authority and verification budgets.
26
+
15
27
  ## Delegation
16
28
 
17
29
  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.
@@ -89,52 +101,97 @@ function hostSkillTargets(slug) {
89
101
  ];
90
102
  }
91
103
  export async function inspectHostSkillPack(workspaceRoot) {
92
- 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.';
93
- let files;
94
- try {
95
- files = (await fs.readdir(path.join(TEMPLATES_ROOT, 'skills'))).filter((file) => file.endsWith('.md'));
96
- }
97
- catch {
98
- return advisory;
104
+ return (await inspectHostSkillPackDetailed(workspaceRoot, 'unknown')).hint;
105
+ }
106
+ async function batches(items, read) {
107
+ const results = [];
108
+ for (let offset = 0; offset < items.length; offset += 8) {
109
+ results.push(...(await Promise.allSettled(items.slice(offset, offset + 8).map(read))));
99
110
  }
100
- const expectedSlugs = Object.keys(HOST_SKILL_DESCRIPTIONS);
101
- if (files.length !== expectedSlugs.length ||
102
- files.some((file) => !expectedSlugs.includes(file.replace(/\.md$/u, '')))) {
103
- return advisory;
111
+ return results;
112
+ }
113
+ function collectHostSkillIssues(installed, targets) {
114
+ const issues = installed.flatMap((result, index) => {
115
+ if (result.status === 'fulfilled') {
116
+ return result.value ? [result.value] : [];
117
+ }
118
+ const target = targets[index];
119
+ return target
120
+ ? [
121
+ {
122
+ path: target.relative.split(path.sep).join('/'),
123
+ status: 'unreadable',
124
+ cause: 'read_failed',
125
+ },
126
+ ]
127
+ : [];
128
+ });
129
+ return issues;
130
+ }
131
+ function hostSkillAdvice(action) {
132
+ 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.';
133
+ switch (action) {
134
+ case 'inspect_installation':
135
+ return ('Inspect the pinned Planu installation and its bundled skill reference before project setup. ' +
136
+ setup);
137
+ case 'inspect_unsafe_paths':
138
+ return ('Review unsafe project skill paths and restore safe file boundaries before setup. ' + setup);
139
+ case 'review_project_setup':
140
+ return 'Planu host skills are missing, different, or unreadable. ' + setup;
141
+ case 'none':
142
+ return undefined;
104
143
  }
105
- let differs = false;
144
+ }
145
+ export async function inspectHostSkillPackDetailed(workspaceRoot, bundledVersion) {
146
+ const slugs = Object.keys(HOST_SKILL_DESCRIPTIONS).sort();
106
147
  const expected = new Map();
107
- // Each request rereads every body. Bound concurrent descriptors and drain each
108
- // batch before advancing, including when a file is missing or a read rejects.
109
- for (let offset = 0; offset < files.length; offset += 8) {
110
- const settled = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
111
- const slug = file.replace(/\.md$/u, '');
112
- const source = await readTextInsideWorkspace(TEMPLATES_ROOT, path.join(TEMPLATES_ROOT, 'skills', file), { maxBytes: 65_536 });
113
- return { slug, body: source.ok ? toHostSkillMarkdown(slug, source.text) : undefined };
114
- }));
115
- for (const result of settled) {
116
- if (result.status === 'fulfilled' && result.value.body !== undefined) {
117
- expected.set(result.value.slug, result.value.body);
118
- }
119
- else {
120
- differs = true;
121
- }
148
+ const sources = await batches(slugs, async (slug) => {
149
+ const source = await readTextInsideWorkspaceDetailed(TEMPLATES_ROOT, path.join(TEMPLATES_ROOT, 'skills', `${slug}.md`), { maxBytes: 65_536 });
150
+ if (source.ok) {
151
+ expected.set(slug, toHostSkillMarkdown(slug, source.text));
122
152
  }
123
- }
124
- const targets = files.flatMap((file) => {
125
- const slug = file.replace(/\.md$/u, '');
126
- return hostSkillTargets(slug).map((relative) => ({ slug, relative }));
127
153
  });
128
- for (let offset = 0; offset < targets.length; offset += 8) {
129
- const settled = await Promise.allSettled(targets.slice(offset, offset + 8).map(async ({ slug, relative }) => {
130
- const installed = await readTextInsideWorkspace(workspaceRoot, path.join(workspaceRoot, relative), { maxBytes: 65_536 });
131
- return installed.ok && installed.text === expected.get(slug);
132
- }));
133
- if (settled.some((result) => result.status === 'rejected' || !result.value)) {
134
- differs = true;
154
+ const available = sources.every((result) => result.status === 'fulfilled') && expected.size === slugs.length;
155
+ const targets = slugs.flatMap((slug) => hostSkillTargets(slug).map((relative) => ({ slug, relative })));
156
+ const installed = await batches(targets, async ({ slug, relative }) => {
157
+ const read = await readTextInsideWorkspaceDetailed(workspaceRoot, path.join(workspaceRoot, relative), { maxBytes: 65_536 });
158
+ const fixedPath = relative.split(path.sep).join('/');
159
+ if (!read.ok) {
160
+ return {
161
+ path: fixedPath,
162
+ status: read.cause === 'not_found' ? 'missing' : 'unreadable',
163
+ cause: read.cause,
164
+ };
135
165
  }
136
- }
137
- return differs ? advisory : undefined;
166
+ if (available && read.text !== expected.get(slug)) {
167
+ return {
168
+ path: fixedPath,
169
+ status: 'different',
170
+ cause: 'content_mismatch',
171
+ };
172
+ }
173
+ return undefined;
174
+ });
175
+ const issues = collectHostSkillIssues(installed, targets);
176
+ issues.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
177
+ const nextAction = !available
178
+ ? 'inspect_installation'
179
+ : issues.some((issue) => issue.cause === 'unsafe_path')
180
+ ? 'inspect_unsafe_paths'
181
+ : issues.length
182
+ ? 'review_project_setup'
183
+ : 'none';
184
+ return {
185
+ hostSkills: {
186
+ version: 1,
187
+ bundledVersion,
188
+ baseline: available ? 'available' : 'unavailable',
189
+ catalog: 'unverified',
190
+ issues,
191
+ nextAction,
192
+ },
193
+ ...(nextAction !== 'none' ? { hint: hostSkillAdvice(nextAction) } : {}),
194
+ };
138
195
  }
139
196
  async function readHostBody() {
140
197
  try {
@@ -187,7 +244,10 @@ export async function installCursorGuard(workspaceRoot) {
187
244
  await fs.copyFile(scriptSrc, scriptDest);
188
245
  await fs.chmod(scriptDest, 0o755);
189
246
  const incoming = readCursorHooks(await fs.readFile(hooksSrc, 'utf8'));
190
- let current = { version: 1, hooks: {} };
247
+ let current = {
248
+ version: 1,
249
+ hooks: {},
250
+ };
191
251
  try {
192
252
  current = readCursorHooks(await fs.readFile(hooksDest, 'utf8'));
193
253
  }
@@ -214,7 +274,10 @@ alwaysApply: true
214
274
 
215
275
  ${body}`;
216
276
  const targets = [
217
- { relative: path.join('.cursor', 'rules', 'planu-sdd.mdc'), contents: cursorRule },
277
+ {
278
+ relative: path.join('.cursor', 'rules', 'planu-sdd.mdc'),
279
+ contents: cursorRule,
280
+ },
218
281
  { relative: path.join('.claude', 'rules', 'planu-sdd.md'), contents: body },
219
282
  { relative: path.join('.gemini', 'planu-sdd.md'), contents: body },
220
283
  ];
@@ -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
@@ -0,0 +1,187 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, realpath } from 'node:fs/promises';
3
+ import { join, relative, resolve, sep } from 'node:path';
4
+ function fail(cause) {
5
+ return { ok: false, cause };
6
+ }
7
+ function sameIdentity(a, b) {
8
+ return (a.dev === b.dev && a.ino === b.ino && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid);
9
+ }
10
+ function sameFile(a, b) {
11
+ return (sameIdentity(a, b) &&
12
+ a.nlink === b.nlink &&
13
+ a.size === b.size &&
14
+ a.mtimeNs === b.mtimeNs &&
15
+ a.ctimeNs === b.ctimeNs);
16
+ }
17
+ function safeFile(stat) {
18
+ return stat.isFile() && !stat.isSymbolicLink() && stat.nlink === 1n;
19
+ }
20
+ function errorCause(error, observed) {
21
+ const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined;
22
+ switch (code) {
23
+ case 'ENOENT':
24
+ return observed ? 'unstable' : 'not_found';
25
+ case 'EACCES':
26
+ case 'EPERM':
27
+ return 'access_denied';
28
+ case 'ELOOP':
29
+ case 'ENOTDIR':
30
+ return 'unsafe_path';
31
+ default:
32
+ return 'read_failed';
33
+ }
34
+ }
35
+ class HostSkillReader {
36
+ lexicalRoot;
37
+ local;
38
+ maxBytes;
39
+ directories = [];
40
+ canonicalRoot;
41
+ observedTarget = false;
42
+ handle;
43
+ constructor(lexicalRoot, local, maxBytes) {
44
+ this.lexicalRoot = lexicalRoot;
45
+ this.local = local;
46
+ this.maxBytes = maxBytes;
47
+ }
48
+ async run() {
49
+ let result;
50
+ try {
51
+ result = await this.captureAndRead();
52
+ }
53
+ catch (error) {
54
+ result = await this.failure(error);
55
+ }
56
+ if (this.handle) {
57
+ try {
58
+ await this.handle.close();
59
+ }
60
+ catch {
61
+ result = fail('read_failed');
62
+ }
63
+ }
64
+ return result;
65
+ }
66
+ async failure(error) {
67
+ const cause = errorCause(error, this.observedTarget);
68
+ try {
69
+ if (!(await this.recheckDirectories())) {
70
+ return fail('unstable');
71
+ }
72
+ return fail(cause === 'not_found' && this.directories.length === 0 ? 'unsafe_path' : cause);
73
+ }
74
+ catch {
75
+ return fail('unstable');
76
+ }
77
+ }
78
+ async recheckDirectories() {
79
+ if (this.canonicalRoot !== undefined &&
80
+ (await realpath(this.lexicalRoot)) !== this.canonicalRoot) {
81
+ return false;
82
+ }
83
+ for (const directory of this.directories) {
84
+ const current = await lstat(directory.path, { bigint: true });
85
+ if (!current.isDirectory() ||
86
+ current.isSymbolicLink() ||
87
+ !sameIdentity(directory.stat, current)) {
88
+ return false;
89
+ }
90
+ }
91
+ return true;
92
+ }
93
+ async capturePath() {
94
+ const root = await realpath(this.lexicalRoot);
95
+ this.canonicalRoot = root;
96
+ let current = root;
97
+ for (const component of this.local.split(sep)) {
98
+ const stat = await lstat(current, { bigint: true });
99
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
100
+ return undefined;
101
+ }
102
+ this.directories.push({ path: current, stat });
103
+ current = join(current, component);
104
+ }
105
+ return current;
106
+ }
107
+ async captureAndRead() {
108
+ const target = await this.capturePath();
109
+ if (target === undefined) {
110
+ return fail('unsafe_path');
111
+ }
112
+ const before = await lstat(target, { bigint: true });
113
+ this.observedTarget = true;
114
+ if (!safeFile(before)) {
115
+ return fail('unsafe_path');
116
+ }
117
+ if (before.size > BigInt(this.maxBytes)) {
118
+ return fail('over_limit');
119
+ }
120
+ this.handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
121
+ const opened = await this.handle.stat({ bigint: true });
122
+ if (!safeFile(opened)) {
123
+ return fail('unsafe_path');
124
+ }
125
+ if (!sameFile(before, opened)) {
126
+ return fail('unstable');
127
+ }
128
+ if (opened.size > BigInt(this.maxBytes)) {
129
+ return fail('over_limit');
130
+ }
131
+ if (!(await this.recheckDirectories()) || (await realpath(target)) !== target) {
132
+ return fail('unstable');
133
+ }
134
+ const revalidated = await lstat(target, { bigint: true });
135
+ if (!safeFile(revalidated) || !sameFile(opened, revalidated)) {
136
+ return fail('unstable');
137
+ }
138
+ return this.readDescriptor(this.handle, target, opened);
139
+ }
140
+ async readDescriptor(handle, target, opened) {
141
+ const bytes = Buffer.alloc(this.maxBytes);
142
+ let total = 0;
143
+ while (total < this.maxBytes) {
144
+ const { bytesRead } = await handle.read(bytes, total, this.maxBytes - total, total);
145
+ if (bytesRead === 0) {
146
+ break;
147
+ }
148
+ total += bytesRead;
149
+ }
150
+ const after = await handle.stat({ bigint: true });
151
+ const final = await lstat(target, { bigint: true });
152
+ if (after.size > BigInt(this.maxBytes) || final.size > BigInt(this.maxBytes)) {
153
+ return fail('over_limit');
154
+ }
155
+ if (!sameFile(opened, after) ||
156
+ !sameFile(after, final) ||
157
+ after.size !== BigInt(total) ||
158
+ !safeFile(final) ||
159
+ !(await this.recheckDirectories()) ||
160
+ (await realpath(target)) !== target) {
161
+ return fail('unstable');
162
+ }
163
+ try {
164
+ return {
165
+ ok: true,
166
+ text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, total)),
167
+ };
168
+ }
169
+ catch {
170
+ return fail('invalid_content');
171
+ }
172
+ }
173
+ }
174
+ /** Strict bounded reader for host diagnostics; legacy reader semantics remain unchanged. */
175
+ export function readTextInsideWorkspaceDetailed(workspaceRoot, absolutePath, options) {
176
+ const { maxBytes } = options;
177
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 65_536) {
178
+ return Promise.resolve(fail('read_failed'));
179
+ }
180
+ const root = resolve(workspaceRoot);
181
+ const local = relative(root, resolve(absolutePath));
182
+ if (!local || local === '..' || local.startsWith(`..${sep}`) || resolve(local) === local) {
183
+ return Promise.resolve(fail('unsafe_path'));
184
+ }
185
+ return new HostSkillReader(root, local, maxBytes).run();
186
+ }
187
+ //# sourceMappingURL=host-skill-reader.js.map
@@ -1,5 +1,6 @@
1
1
  import type { FilePermission, LockIntegrityResult, ReceiptSealFailure } from '../types/sdd-engine.js';
2
2
  import type { SealResult } from '../types/completion.js';
3
+ export { readTrinityFailureIssues } from './trinity-structure.js';
3
4
  export declare function verifyLockedTrinity(featDir: string): Promise<LockIntegrityResult>;
4
5
  export declare function writeLockedTrinity(requestedFeatDir: string, featureId: string, relock: boolean, reason: string | undefined): Promise<SealResult | ReceiptSealFailure>;
5
6
  export declare function executionCard(featDir: string): Promise<{
@@ -3,6 +3,8 @@ import * as fs from 'node:fs/promises';
3
3
  import * as path from 'node:path';
4
4
  import { CompletionGuardError, captureDirectories, lastAuthorityDirectory, checkWritable, guardFailure, hashArtifact, readArtifact, readFeatureArtifact, revalidateDirectories, rewriteArtifact, sameIdentity, } from './feature-authority.js';
5
5
  import { acquireCompletionLease, claimStoppedCompletion, inspectCompletionGuard, } from './completion-guard.js';
6
+ import { TrinityReadError } from './trinity-structure.js';
7
+ export { readTrinityFailureIssues } from './trinity-structure.js';
6
8
  import { captureCompletionSnapshot } from './completion-snapshot.js';
7
9
  import { assessTrinityCompleteness, parseManifestContent, receiptSealFailure, } from './feature-manifest.js';
8
10
  export async function verifyLockedTrinity(featDir) {
@@ -12,7 +14,7 @@ export async function verifyLockedTrinity(featDir) {
12
14
  }
13
15
  catch (error) {
14
16
  const missingLock = (error instanceof CompletionGuardError && error.code === 'ERR_SPEC_NOT_LOCKED') ||
15
- (error.code === 'ENOENT' &&
17
+ (error?.code === 'ENOENT' &&
16
18
  path.basename(error.path ?? '') === '.lock');
17
19
  return {
18
20
  ok: false,
@@ -66,21 +68,29 @@ export async function writeLockedTrinity(requestedFeatDir, featureId, relock, re
66
68
  await lease?.release();
67
69
  }
68
70
  }
69
- async function readTrinity(featDir, featureId) {
71
+ async function readTrinity(featDir) {
72
+ let artifact = 'spec.md';
70
73
  try {
71
- const spec = await readArtifact(featDir, 'spec.md');
72
- const plan = await readArtifact(featDir, 'plan.md');
73
- const tasks = await readArtifact(featDir, 'tasks.md');
74
+ const spec = await readArtifact(featDir, artifact);
75
+ artifact = 'plan.md';
76
+ const plan = await readArtifact(featDir, artifact);
77
+ artifact = 'tasks.md';
78
+ const tasks = await readArtifact(featDir, artifact);
74
79
  return { 'spec.md': spec, 'plan.md': plan, 'tasks.md': tasks };
75
80
  }
76
81
  catch (error) {
77
82
  if (error instanceof CompletionGuardError) {
78
- throw error;
83
+ throw new TrinityReadError(error, artifact);
79
84
  }
85
+ const missing = error?.code === 'ENOENT';
86
+ const rule = missing ? 'artifact_missing' : 'artifact_unreadable';
80
87
  return {
81
88
  ok: false,
82
89
  code: 'ERR_FEATURE_NOT_FOUND',
83
- message: `Failed to read base artifacts for '${featureId}'.`,
90
+ message: 'Failed to read required contract artifacts.',
91
+ details: {
92
+ issues: [{ artifact, rule }],
93
+ },
84
94
  };
85
95
  }
86
96
  }
@@ -189,7 +199,7 @@ async function persistReseal(featDir, lockPath, directories, captured, previousA
189
199
  }
190
200
  async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, relock, trimmedReason, lease) {
191
201
  const directories = await captureDirectories(featDir);
192
- const captured = await readTrinity(featDir, featureId);
202
+ const captured = await readTrinity(featDir);
193
203
  if ('ok' in captured) {
194
204
  return captured;
195
205
  }
@@ -199,12 +209,7 @@ async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, re
199
209
  }
200
210
  const completeness = assessTrinityCompleteness(captured['spec.md'].content, captured['plan.md'].content, captured['tasks.md'].content);
201
211
  if (!completeness.ok) {
202
- return {
203
- ok: false,
204
- code: completeness.code,
205
- message: completeness.message,
206
- ...(completeness.details ? { details: completeness.details } : {}),
207
- };
212
+ return completeness;
208
213
  }
209
214
  const { previous, artifact } = await readPreviousLock(featDir, lockPath, lockExists);
210
215
  const lockFile = prepareLock(captured, previous, relock, trimmedReason);
@@ -226,7 +231,7 @@ export async function executionCard(featDir) {
226
231
  plan = await readFeatureArtifact(featDir, 'plan.md');
227
232
  }
228
233
  catch (error) {
229
- if (error.code !== 'ENOENT') {
234
+ if (error?.code !== 'ENOENT') {
230
235
  if (error instanceof CompletionGuardError) {
231
236
  throw error;
232
237
  }
@@ -235,7 +240,10 @@ export async function executionCard(featDir) {
235
240
  plan = '';
236
241
  }
237
242
  const entries = [...parseManifestContent(plan).allowedFiles.entries()];
238
- const manifest = entries.map(([filePath, permission]) => ({ path: filePath, permission }));
243
+ const manifest = entries.map(([filePath, permission]) => ({
244
+ path: filePath,
245
+ permission,
246
+ }));
239
247
  const guard = await inspectCompletionGuard(featDir);
240
248
  if (guard) {
241
249
  throw new CompletionGuardError(guard.reason, 'Feature ownership requires completion or explicit reviewed recovery.', 'ERR_VERIFICATION_FAILED');
@@ -266,7 +274,7 @@ async function lockAlreadyExists(lockPath) {
266
274
  await fs.access(lockPath);
267
275
  }
268
276
  catch (error) {
269
- if (error.code !== 'ENOENT') {
277
+ if (error?.code !== 'ENOENT') {
270
278
  throw error;
271
279
  }
272
280
  lockExists = false;
@@ -0,0 +1,12 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import type { ReceiptSetResult, VerificationEvidence, ReceiptSetAssessment } from '../types/sdd-engine.js';
4
+ export declare const maxVerificationReceipts = 32;
5
+ export declare const gateIdPattern: RegExp;
6
+ export declare const taskIdPattern: RegExp;
7
+ export declare const featureIdPattern: RegExp;
8
+ export declare const sha256Schema: z.ZodString;
9
+ export declare function importReceiptPublicKey(value: string): KeyObject | undefined;
10
+ export declare function assessVerificationReceiptSet(input: unknown, challenge: VerificationEvidence, publicKey: KeyObject): ReceiptSetAssessment;
11
+ export declare function validateVerificationReceiptSet(input: unknown, challenge: VerificationEvidence, publicKey: KeyObject): ReceiptSetResult;
12
+ //# sourceMappingURL=receipt-assessment.d.ts.map