@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
@@ -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,7 +1,8 @@
1
- import type { FilePermission, LockIntegrityResult } from '../types/sdd-engine.js';
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
- export declare function writeLockedTrinity(requestedFeatDir: string, featureId: string, relock: boolean, reason: string | undefined): Promise<SealResult>;
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<{
6
7
  locked: boolean;
7
8
  trinity: 'ready' | 'unlocked' | 'drift';
@@ -3,8 +3,10 @@ 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
- import { assessTrinityCompleteness, parseManifestContent } from './feature-manifest.js';
9
+ import { assessTrinityCompleteness, parseManifestContent, receiptSealFailure, } from './feature-manifest.js';
8
10
  export async function verifyLockedTrinity(featDir) {
9
11
  try {
10
12
  await captureCompletionSnapshot(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,18 +199,17 @@ 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
  }
206
+ const receiptFailure = receiptSealFailure(featureId, captured['plan.md'].content, captured['tasks.md'].content);
207
+ if (receiptFailure) {
208
+ return receiptFailure;
209
+ }
196
210
  const completeness = assessTrinityCompleteness(captured['spec.md'].content, captured['plan.md'].content, captured['tasks.md'].content);
197
211
  if (!completeness.ok) {
198
- return {
199
- ok: false,
200
- code: completeness.code,
201
- message: completeness.message,
202
- ...(completeness.details ? { details: completeness.details } : {}),
203
- };
212
+ return completeness;
204
213
  }
205
214
  const { previous, artifact } = await readPreviousLock(featDir, lockPath, lockExists);
206
215
  const lockFile = prepareLock(captured, previous, relock, trimmedReason);
@@ -222,7 +231,7 @@ export async function executionCard(featDir) {
222
231
  plan = await readFeatureArtifact(featDir, 'plan.md');
223
232
  }
224
233
  catch (error) {
225
- if (error.code !== 'ENOENT') {
234
+ if (error?.code !== 'ENOENT') {
226
235
  if (error instanceof CompletionGuardError) {
227
236
  throw error;
228
237
  }
@@ -231,7 +240,10 @@ export async function executionCard(featDir) {
231
240
  plan = '';
232
241
  }
233
242
  const entries = [...parseManifestContent(plan).allowedFiles.entries()];
234
- const manifest = entries.map(([filePath, permission]) => ({ path: filePath, permission }));
243
+ const manifest = entries.map(([filePath, permission]) => ({
244
+ path: filePath,
245
+ permission,
246
+ }));
235
247
  const guard = await inspectCompletionGuard(featDir);
236
248
  if (guard) {
237
249
  throw new CompletionGuardError(guard.reason, 'Feature ownership requires completion or explicit reviewed recovery.', 'ERR_VERIFICATION_FAILED');
@@ -262,7 +274,7 @@ async function lockAlreadyExists(lockPath) {
262
274
  await fs.access(lockPath);
263
275
  }
264
276
  catch (error) {
265
- if (error.code !== 'ENOENT') {
277
+ if (error?.code !== 'ENOENT') {
266
278
  throw error;
267
279
  }
268
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
@@ -0,0 +1,223 @@
1
+ import { createHash, createPublicKey, verify } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ export const maxVerificationReceipts = 32;
4
+ export const gateIdPattern = /^[a-z][a-z0-9-]{0,31}$/u;
5
+ export const taskIdPattern = /^TASK-[1-9][0-9]{0,18}$/u;
6
+ export const featureIdPattern = /^FEAT[-_][A-Z0-9_-]{1,123}$/u;
7
+ export const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/u);
8
+ function decodeCanonicalBase64Url(value) {
9
+ if (!/^[A-Za-z0-9_-]+$/u.test(value)) {
10
+ return undefined;
11
+ }
12
+ const decoded = Buffer.from(value, 'base64url');
13
+ return decoded.toString('base64url') === value ? decoded : undefined;
14
+ }
15
+ export function importReceiptPublicKey(value) {
16
+ const der = value.length <= 128 ? decodeCanonicalBase64Url(value) : undefined;
17
+ if (!der) {
18
+ return undefined;
19
+ }
20
+ try {
21
+ const key = createPublicKey({ key: der, format: 'der', type: 'spki' });
22
+ if (key.asymmetricKeyType !== 'ed25519') {
23
+ return undefined;
24
+ }
25
+ return key.export({ format: 'der', type: 'spki' }).equals(der) ? key : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ const receiptSchema = z.strictObject({
32
+ version: z.literal(1),
33
+ featureId: z.string().regex(featureIdPattern),
34
+ taskId: z.string().regex(taskIdPattern),
35
+ workspaceSha256: sha256Schema,
36
+ lockSha256: sha256Schema,
37
+ candidateSha256: sha256Schema,
38
+ observedSha256: sha256Schema,
39
+ gateId: z.string().regex(gateIdPattern),
40
+ procedureSha256: sha256Schema,
41
+ environmentSha256: sha256Schema,
42
+ outcome: z.enum(['pass', 'fail', 'skipped', 'partial']),
43
+ evidenceSha256: sha256Schema,
44
+ signature: z.string().regex(/^[A-Za-z0-9_-]{86}$/u),
45
+ });
46
+ const RECEIPT_KEY_COUNT = Object.keys(receiptSchema.shape).length;
47
+ function receiptMessage(receipt) {
48
+ return [
49
+ 'planu.verification-receipt.v1',
50
+ receipt.featureId,
51
+ receipt.taskId,
52
+ receipt.workspaceSha256,
53
+ receipt.lockSha256,
54
+ receipt.candidateSha256,
55
+ receipt.observedSha256,
56
+ receipt.gateId,
57
+ receipt.procedureSha256,
58
+ receipt.environmentSha256,
59
+ receipt.outcome,
60
+ receipt.evidenceSha256,
61
+ ];
62
+ }
63
+ function decodeReceipt(input) {
64
+ if (typeof input !== 'object' ||
65
+ input === null ||
66
+ Object.keys(input).length !== RECEIPT_KEY_COUNT) {
67
+ return undefined;
68
+ }
69
+ const parsed = receiptSchema.safeParse(input);
70
+ if (!parsed.success) {
71
+ return undefined;
72
+ }
73
+ const signature = decodeCanonicalBase64Url(parsed.data.signature);
74
+ if (signature?.length !== 64) {
75
+ return undefined;
76
+ }
77
+ return {
78
+ receipt: parsed.data,
79
+ message: receiptMessage(parsed.data),
80
+ signature,
81
+ };
82
+ }
83
+ function matchCoverage(signed, gates) {
84
+ const required = new Set(gates.map((gate) => gate.id));
85
+ const byGate = new Map();
86
+ for (const entry of signed) {
87
+ const gateId = entry.receipt.gateId;
88
+ if (!required.has(gateId)) {
89
+ return { ok: false, reason: 'receipt_unexpected' };
90
+ }
91
+ if (byGate.has(gateId)) {
92
+ return { ok: false, reason: 'receipt_duplicate', gateId };
93
+ }
94
+ byGate.set(gateId, entry);
95
+ }
96
+ const matched = [];
97
+ for (const gate of gates) {
98
+ const entry = byGate.get(gate.id);
99
+ if (!entry) {
100
+ return { ok: false, reason: 'receipt_missing', gateId: gate.id };
101
+ }
102
+ matched.push({ ...entry, gate });
103
+ }
104
+ return { ok: true, matched };
105
+ }
106
+ function validateClaims(matched, challenge) {
107
+ const checks = [
108
+ [
109
+ (receipt) => receipt.workspaceSha256 === challenge.workspaceSha256 &&
110
+ receipt.featureId === challenge.featureId &&
111
+ receipt.taskId === challenge.taskId &&
112
+ receipt.lockSha256 === challenge.lockSha256,
113
+ 'receipt_context_mismatch',
114
+ ],
115
+ [
116
+ (receipt) => receipt.candidateSha256 === challenge.candidateSha256,
117
+ 'receipt_candidate_mismatch',
118
+ ],
119
+ [(receipt) => receipt.observedSha256 === challenge.observedSha256, 'receipt_observed_mismatch'],
120
+ [
121
+ (receipt, gate) => receipt.procedureSha256 === gate.procedureSha256,
122
+ 'receipt_procedure_mismatch',
123
+ ],
124
+ [
125
+ (receipt, gate) => receipt.environmentSha256 === gate.environmentSha256,
126
+ 'receipt_environment_mismatch',
127
+ ],
128
+ [(receipt) => receipt.outcome === 'pass', 'receipt_non_pass'],
129
+ ];
130
+ for (const [accepts, reason] of checks) {
131
+ const failed = matched.find(({ receipt, gate }) => !accepts(receipt, gate));
132
+ if (failed) {
133
+ return { ok: false, reason, gateId: failed.gate.id };
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+ function validateReceiptSet(input, challenge, publicKey) {
139
+ const gates = [...challenge.gates].sort((left, right) => left.id < right.id ? -1 : left.id === right.id ? 0 : 1);
140
+ if (input === undefined) {
141
+ const gateId = gates[0]?.id;
142
+ return {
143
+ ok: false,
144
+ reason: 'receipt_missing',
145
+ ...(gateId ? { gateId } : {}),
146
+ };
147
+ }
148
+ if (!Array.isArray(input) || input.length < 1 || input.length > maxVerificationReceipts) {
149
+ return { ok: false, reason: 'receipt_malformed' };
150
+ }
151
+ const signed = [];
152
+ for (const raw of input) {
153
+ const receipt = decodeReceipt(raw);
154
+ if (!receipt) {
155
+ return { ok: false, reason: 'receipt_malformed' };
156
+ }
157
+ signed.push(receipt);
158
+ }
159
+ const coverage = matchCoverage(signed, gates);
160
+ if (!coverage.ok) {
161
+ return coverage;
162
+ }
163
+ for (const { receipt, message, signature } of coverage.matched) {
164
+ if (!verify(null, Buffer.from(JSON.stringify(message), 'utf8'), publicKey, signature)) {
165
+ return {
166
+ ok: false,
167
+ reason: 'receipt_invalid_signature',
168
+ gateId: receipt.gateId,
169
+ };
170
+ }
171
+ }
172
+ const rejected = validateClaims(coverage.matched, challenge);
173
+ if (rejected) {
174
+ return rejected;
175
+ }
176
+ const entries = coverage.matched.map(({ message, receipt }) => [message, receipt.signature]);
177
+ const receiptSetSha256 = createHash('sha256')
178
+ .update(JSON.stringify(['planu.verification-receipt-set.v1', entries]), 'utf8')
179
+ .digest('hex');
180
+ return { ok: true, gateCount: entries.length, receiptSetSha256 };
181
+ }
182
+ export function assessVerificationReceiptSet(input, challenge, publicKey) {
183
+ const result = validateReceiptSet(input, challenge, publicKey);
184
+ const gates = [...challenge.gates]
185
+ .sort((left, right) => (left.id < right.id ? -1 : left.id === right.id ? 0 : 1))
186
+ .slice(0, maxVerificationReceipts)
187
+ .map((gate) => {
188
+ const subset = Array.isArray(input) && input.length >= 1 && input.length <= maxVerificationReceipts
189
+ ? input.filter((entry) => typeof entry === 'object' &&
190
+ entry !== null &&
191
+ 'gateId' in entry &&
192
+ entry.gateId === gate.id)
193
+ : input;
194
+ const selected = Array.isArray(input) && input.length >= 1 && Array.isArray(subset) && subset.length === 0
195
+ ? undefined
196
+ : subset;
197
+ const checked = validateReceiptSet(selected, { ...challenge, gates: [gate] }, publicKey);
198
+ if (checked.ok) {
199
+ return { gateId: gate.id, state: 'receipt_valid' };
200
+ }
201
+ return {
202
+ gateId: gate.id,
203
+ state: checked.reason === 'receipt_missing' ? 'receipt_missing' : 'receipt_rejected',
204
+ reason: checked.reason,
205
+ };
206
+ });
207
+ const reasons = new Set();
208
+ if (!result.ok && !gates.some((gate) => gate.reason === result.reason)) {
209
+ reasons.add(result.reason);
210
+ }
211
+ return {
212
+ result,
213
+ gates,
214
+ blockers: [...reasons]
215
+ .sort()
216
+ .slice(0, 16)
217
+ .map((reason) => ({ reason })),
218
+ };
219
+ }
220
+ export function validateVerificationReceiptSet(input, challenge, publicKey) {
221
+ return validateReceiptSet(input, challenge, publicKey);
222
+ }
223
+ //# sourceMappingURL=receipt-assessment.js.map
@@ -1,9 +1,7 @@
1
- import { readFileSync } from 'node:fs';
2
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
3
  import { captureVerificationPolicy, resolveVerificationPolicy } from './verification-policy.js';
5
- import { registerUltralightSddTools } from './tools.js';
6
- const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
4
+ import { bundledPackageVersion as version, registerUltralightSddTools } from './tools.js';
7
5
  export function createUltralightSddServer(workspaceRoot, options) {
8
6
  const policy = resolveVerificationPolicy(options?.verificationPolicy, workspaceRoot);
9
7
  const server = new McpServer({ name: 'sdd-engine', version }, {
@@ -11,7 +9,7 @@ export function createUltralightSddServer(workspaceRoot, options) {
11
9
  instructions: 'First use: call sdd_list_features. If setup is missing or unverified, call sdd_init_workspace(scope=project) only for the identified project and requested setup. Then use sdd_read_file_slice to read .agents/skills/planu-preflight-guardian/SKILL.md and the matching role. Keep one active task, the locked File Manifest and all nine tools. Installed files do not prove a host catalog reload; explain client-dependent discovery and never initialize on connect.',
12
10
  });
13
11
  const pinnedRoot = policy.mode === 'scoped' ? policy.workspaceRoot : workspaceRoot;
14
- const tasks = registerUltralightSddTools(server, pinnedRoot, policy);
12
+ const tasks = registerUltralightSddTools(server, pinnedRoot, policy, version);
15
13
  {
16
14
  const close = server.close.bind(server);
17
15
  server.close = async () => {
@@ -1,8 +1,26 @@
1
- import type { ActiveTaskResult, FeatureSummary, SddResult } from '../types/sdd-engine.js';
1
+ import type { ActiveTaskResult, FeatureSummary, SddResult, TaskBlock } from '../types/sdd-engine.js';
2
2
  export declare function activeTaskFromContent(content: string, extractCommand: (markdown: string) => string | null): SddResult<ActiveTaskResult>;
3
+ export declare function taskBlocks(content: string): TaskBlock[];
3
4
  export declare function markTaskVerified(lines: string[], taskId: string, cleanOutput: string): string[] | null;
5
+ export declare function markReceiptTaskVerified(content: string, lineIndex: number, summary: string): string | undefined;
4
6
  export declare function remainingTaskCount(checkRes: SddResult<ActiveTaskResult>): number;
5
7
  export declare function summarizeEvidence(output: string): string;
6
8
  export declare function wasTaskCompleted(tasksContent: string, taskId: string): boolean;
7
9
  export declare function catalogueFromContent(id: string, locked: boolean, tasksContent: string, extractCommand: (markdown: string) => string | null): SddResult<FeatureSummary>;
10
+ export declare function insideMarkdownBlock(lines: readonly string[]): boolean;
11
+ export declare function hasReceiptDirective(line: string): boolean;
12
+ export declare function receiptCommand(block: TaskBlock): string | undefined;
13
+ export declare function countTaskIds(blocks: readonly TaskBlock[]): Map<string, number>;
14
+ export declare function dueTaskOrdinals(blocks: readonly TaskBlock[], counts: ReadonlyMap<string, number>): Map<string, number>;
15
+ export declare function sliceNumberedSource(fileData: string, startLine: number, endLine: number): {
16
+ ok: true;
17
+ totalLines: number;
18
+ startLine: number;
19
+ endLine: number;
20
+ truncated: boolean;
21
+ text: string;
22
+ } | {
23
+ ok: false;
24
+ totalLines: number;
25
+ };
8
26
  //# sourceMappingURL=task-content.d.ts.map