@planu/cli 8.2.19 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## [8.3.0] - 2026-11-06
2
+
3
+ - 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.
4
+ - A changed observed input requires restoring the baseline or a reviewed relock. The File Manifest remains the authority for patches.
5
+
6
+ ## [8.2.20] - 2026-10-26
7
+
8
+ - refresh the development and runtime resolution within existing ranges: @modelcontextprotocol/sdk 1.32.2, vite 8.3.5, knip 6.43.0 and tsc-alias 1.9.9
9
+ - keep declared dependency ranges, engines, the nine tools and input schemas, role bodies, execution controls and package membership unchanged
10
+
1
11
  ## [8.2.19] - 2026-10-24
2
12
 
3
13
  - guide selective delegation within the active task through compact native-agent handoffs; keep trivial, dependent or unavailable routes sequential
package/README.md CHANGED
@@ -132,10 +132,66 @@ This is role guidance, not a runtime dispatcher or a guarantee that a host loads
132
132
 
133
133
  Normal task verification still has a 180000 ms limit. An operator may authorize one pinned task in an isolated Darwin/Linux server with a strict startup-only budget of 180001–600000 ms. The grant binds the canonical workspace, feature, task, raw lock SHA-256 and exact command SHA-256. It is consumed before the first spawn, including failed attempts; uncertain cleanup or persistence quarantines that feature.
134
134
 
135
- There is no timeout tool argument. The nine tools and the three complete-task fields are unchanged. The programmatic factory ignores the CLI environment unless its optional typed policy is explicitly supplied. Agents must not create or widen grants themselves.
135
+ There is no timeout tool argument. The nine tool names are unchanged. The optional verification_receipts field carries signed evidence and grants no extra time. The programmatic factory ignores the CLI environment unless its optional typed policy is explicitly supplied. Agents must not create or widen grants themselves.
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
+ ## Reusable verification receipts
140
+
141
+ 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:
142
+
143
+ - `publicKey`, the operator's Ed25519 SPKI public key in canonical unpadded base64url.
144
+ - `tasks`, the opted-in entries with `taskId`, `gates`, `observed`, and `observedBaselineSha256`. Each gate has an `id`, `procedureSha256`, and `environmentSha256`.
145
+ - `candidateCreates`, with one `{ path, requiredFromTaskId }` for each exact `CREATE` path. The due task is identified by its explicit ID and its position in the task list.
146
+
147
+ Use exactly one literal `Verification (receipts v1):` command on each opted-in task. Use exact `CREATE` and `MODIFY` paths for candidate inputs. Observed files are separate and carry no write authority. A future create is hashed as absent until it exists, and must exist at its due task. Keep an ordinary `Verification:` task for a later integration step if the feature requires one.
148
+
149
+ For observed baseline and candidate digests, sort exact relative paths in ASCII order. Use the SHA-256 of the UTF-8 compact JSON `["planu.verification-inputs.v1", category, entries]`. A present entry is `[path, "present", mode & 0o7777, sha256(rawBytes)]`. A future create that is absent before its due task is `[path, "absent"]`. An empty observed list has the digest of `["planu.verification-inputs.v1","observed",[]]`.
150
+
151
+ Read `verificationEvidence` from `sdd_get_active_task` after sealing. A trusted issuer measures the inputs, runs the reviewed checks against that challenge, and compares the inputs again before signing. It attests the exact procedure, measured immutable environment, outcome, and digest of complete evidence. Keep the signing key outside the workspace, Planu process, integration command, and agents. Only use receipts for checks whose inputs and environment are stable across attempts. Live checks belong in the fresh integration command.
152
+
153
+ This offline Node.js example signs one gate in a disposable fixture with one exact candidate named `candidate.txt`, no observed files, and no future creates. Run the issuer separately with its own key file and the challenge saved to an operator-controlled file. Pin the digests of the example procedure and environment shown below when preparing the fixture policy.
154
+
155
+ ```js
156
+ import { createHash, createPrivateKey, sign } from 'node:crypto';
157
+ import { readFileSync, statSync } from 'node:fs';
158
+
159
+ const [keyPath, challengePath] = process.argv.slice(2);
160
+ const key = createPrivateKey(readFileSync(keyPath));
161
+ const { gates, ...challenge } = JSON.parse(readFileSync(challengePath, 'utf8'));
162
+ const gate = gates.find(({ id }) => id === 'contents');
163
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
164
+ const hashJson = (value) => sha(JSON.stringify(value));
165
+ const procedure = 'Read candidate.txt and require exactly hello followed by LF';
166
+ const environment = JSON.stringify([process.platform, process.arch, process.version, 'fixture-v1']);
167
+ const snapshot = () => {
168
+ const bytes = readFileSync('candidate.txt');
169
+ const mode = statSync('candidate.txt').mode & 0o7777;
170
+ return { bytes, digest: hashJson(['planu.verification-inputs.v1', 'candidate',
171
+ [['candidate.txt', 'present', mode, sha(bytes)]]]) };
172
+ };
173
+ const before = snapshot();
174
+ if (before.digest !== challenge.candidateSha256 ||
175
+ hashJson(['planu.verification-inputs.v1', 'observed', []]) !== challenge.observedSha256 ||
176
+ sha(procedure) !== gate?.procedureSha256 || sha(environment) !== gate.environmentSha256 ||
177
+ !before.bytes.equals(Buffer.from('hello\n')) || snapshot().digest !== before.digest) {
178
+ throw new Error('The fixture check or reviewed challenge did not match');
179
+ }
180
+ const outcome = 'pass';
181
+ const evidenceSha256 = hashJson({ procedure, environment, outcome, candidate: before.digest });
182
+ const message = ['planu.verification-receipt.v1', challenge.featureId, challenge.taskId,
183
+ challenge.workspaceSha256, challenge.lockSha256, challenge.candidateSha256,
184
+ challenge.observedSha256, gate.id, gate.procedureSha256, gate.environmentSha256,
185
+ outcome, evidenceSha256];
186
+ const signature = sign(null, Buffer.from(JSON.stringify(message)), key).toString('base64url');
187
+ console.log(JSON.stringify({ ...challenge, gateId: gate.id, procedureSha256: gate.procedureSha256,
188
+ environmentSha256: gate.environmentSha256, outcome, evidenceSha256, signature }));
189
+ ```
190
+
191
+ Supply exactly one matching receipt per gate through `verification_receipts` on `sdd_complete_task`. Planu verifies the set and reruns the integration command. A failed command leaves the task open. Retry with the same receipts only while the challenge matches. Advancing or resealing the task changes the lock and requires a fresh challenge. If an observed dependency changes, restore the locked baseline or review and record a new baseline using a relock with reason, then obtain fresh receipts. The completion record stores the accepted set digest rather than the receipts or issuer logs.
192
+
193
+ A matching scoped time grant cannot run an opted-in receipt task in this version. Older Planu versions cannot complete these tasks because the receipt directive has no legacy Verification line. To return a pending task to ordinary verification, use a reviewed relock and run all required checks in the ordinary command.
194
+
139
195
  ## The SDD Lifecycle (v8)
140
196
 
141
197
  ```text
@@ -214,7 +270,7 @@ See the [Planu Proprietary Free-Use License](LICENSE) and [planu.dev/license](ht
214
270
  "mcpServers": {
215
271
  "planu": {
216
272
  "command": "npx",
217
- "args": ["-y", "@planu/cli@8.2.19"],
273
+ "args": ["-y", "@planu/cli@8.3.0"],
218
274
  "cwd": ".",
219
275
  "env": {
220
276
  "PLANU_WORKSPACE": "."
@@ -1,3 +1,5 @@
1
+ import type { ScopedVerificationSnapshot } from '../types/verification.js';
2
+ import type { CompleteTaskResult, SddResult } from '../types/sdd-engine.js';
1
3
  import type { CompletionSnapshot, CompletionSnapshotOptions } from '../types/completion.js';
2
4
  import { type CompletionLease } from './completion-guard.js';
3
5
  /** Catalogue reads need task status and lock presence, not an execution readiness card. */
@@ -7,5 +9,7 @@ export declare function readCatalogueArtifacts(featDir: string): Promise<{
7
9
  }>;
8
10
  export declare function captureCompletionSnapshot(requestedFeatDir: string, options?: CompletionSnapshotOptions): Promise<CompletionSnapshot>;
9
11
  export declare function revalidateCompletionSnapshot(snapshot: CompletionSnapshot): Promise<void>;
10
- export declare function persistCompletionSnapshot(lease: CompletionLease, snapshot: CompletionSnapshot, writtenTasks: string, signal?: AbortSignal): Promise<void>;
12
+ export declare function commitOwnedScopedTask(taskId: string, scopedSnapshot: ScopedVerificationSnapshot, output: string, signal: AbortSignal, snapshot: CompletionSnapshot, lease: CompletionLease, persist: (written: string) => Promise<SddResult<null>>): Promise<SddResult<CompleteTaskResult>>;
13
+ export declare function commitOrdinaryTask(snapshot: CompletionSnapshot, lease: CompletionLease, taskId: string, output: string, signal: AbortSignal): Promise<SddResult<CompleteTaskResult>>;
14
+ export declare function persistCompletionSnapshot(lease: CompletionLease, snapshot: CompletionSnapshot, writtenTasks: string, signal?: AbortSignal, checkEvidence?: () => Promise<void>): Promise<void>;
11
15
  //# sourceMappingURL=completion-snapshot.d.ts.map
@@ -1,5 +1,7 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
+ import { activeTaskFromContent, markTaskVerified, remainingTaskCount, summarizeEvidence, } from './task-content.js';
4
+ import { completionFailure, taskOutOfSequence } from './task-failures.js';
3
5
  import { CompletionGuardError, captureDirectories, lastAuthorityDirectory, checkWritable, guardFailure, hashArtifact, readArtifact, revalidateDirectories, rewriteArtifact, sameIdentity, } from './feature-authority.js';
4
6
  import { assertCatalogueAvailable } from './completion-guard.js';
5
7
  /** Catalogue reads need task status and lock presence, not an execution readiness card. */
@@ -75,7 +77,82 @@ export async function revalidateCompletionSnapshot(snapshot) {
75
77
  guardFailure('contract_drift', 'Authoritative completion snapshot changed after selection.');
76
78
  }
77
79
  }
78
- export async function persistCompletionSnapshot(lease, snapshot, writtenTasks, signal) {
80
+ async function commitScopedTask(taskId, snapshot, output, persist) {
81
+ const summary = summarizeEvidence(output);
82
+ const marked = markTaskVerified(snapshot.tasksContent.split('\n'), taskId, summary);
83
+ if (marked === null) {
84
+ return taskOutOfSequence(taskId, null);
85
+ }
86
+ const written = marked.join('\n');
87
+ const persisted = await persist(written);
88
+ if (!persisted.success) {
89
+ return persisted;
90
+ }
91
+ return {
92
+ success: true,
93
+ data: {
94
+ completedTaskId: taskId,
95
+ verificationSummary: summary,
96
+ remainingTasks: remainingTaskCount(activeTaskFromContent(written, () => null)),
97
+ },
98
+ };
99
+ }
100
+ export async function commitOwnedScopedTask(taskId, scopedSnapshot, output, signal, snapshot, lease, persist) {
101
+ await revalidateCompletionSnapshot(snapshot);
102
+ if (signal.aborted) {
103
+ return completionFailure('cancelled');
104
+ }
105
+ await lease.beginPersistence();
106
+ try {
107
+ const outcome = await commitScopedTask(taskId, scopedSnapshot, output, persist);
108
+ if (outcome.success) {
109
+ lease.notePersistenceWrite();
110
+ }
111
+ if (isAborted(signal) ||
112
+ (!outcome.success && outcome.error.details?.completionState === 'uncertain')) {
113
+ lease.retain();
114
+ }
115
+ return outcome;
116
+ }
117
+ catch (error) {
118
+ lease.retain();
119
+ throw error;
120
+ }
121
+ }
122
+ export async function commitOrdinaryTask(snapshot, lease, taskId, output, signal) {
123
+ await revalidateCompletionSnapshot(snapshot);
124
+ if (signal.aborted) {
125
+ return completionFailure('cancelled');
126
+ }
127
+ const summary = summarizeEvidence(output);
128
+ const marked = markTaskVerified(snapshot.tasksContent.split('\n'), taskId, summary);
129
+ if (marked === null) {
130
+ return taskOutOfSequence(taskId, null, true);
131
+ }
132
+ const written = marked.join('\n');
133
+ await persistCompletionSnapshot(lease, snapshot, written, signal);
134
+ const next = activeTaskFromContent(written, () => null);
135
+ return {
136
+ success: true,
137
+ data: {
138
+ completedTaskId: taskId,
139
+ verificationSummary: summary,
140
+ remainingTasks: remainingTaskCount(next),
141
+ },
142
+ };
143
+ }
144
+ function isAborted(signal) {
145
+ return signal.aborted;
146
+ }
147
+ function prepareEvidenceWrite(snapshot, checkEvidence) {
148
+ return checkEvidence
149
+ ? async () => {
150
+ await checkEvidence();
151
+ await revalidateCompletionSnapshot(snapshot);
152
+ }
153
+ : undefined;
154
+ }
155
+ export async function persistCompletionSnapshot(lease, snapshot, writtenTasks, signal, checkEvidence) {
79
156
  if (signal?.aborted) {
80
157
  guardFailure('cancelled', 'Completion was cancelled before persistence.');
81
158
  }
@@ -93,7 +170,7 @@ export async function persistCompletionSnapshot(lease, snapshot, writtenTasks, s
93
170
  // The following syscall can write a prefix even when it rejects.
94
171
  persistence.writeStarted = true;
95
172
  lease.notePersistenceWrite();
96
- });
173
+ }, prepareEvidenceWrite(snapshot, checkEvidence));
97
174
  const writtenLock = JSON.stringify({ ...snapshot.lock, tasksHash: hashArtifact(writtenTasks) }, null, 2);
98
175
  await revalidatePersistedContract(snapshot);
99
176
  await rewriteArtifact(snapshot.featDir, '.lock', snapshot.artifacts['.lock'], writtenLock);
@@ -79,5 +79,6 @@ export declare const CompleteTaskInputSchema: z.ZodObject<{
79
79
  feature_id: z.ZodString;
80
80
  task_id: z.ZodString;
81
81
  verification_output: z.ZodOptional<z.ZodString>;
82
+ verification_receipts: z.ZodOptional<z.ZodArray<z.ZodPreprocess<z.ZodObject<{}, z.core.$loose>, unknown>>>;
82
83
  }, z.core.$strip>;
83
84
  //# sourceMappingURL=contracts.d.ts.map
@@ -58,9 +58,23 @@ export const ApplyFilePatchInputSchema = z.object({
58
58
  search_content: z.string(),
59
59
  replace_content: z.string(),
60
60
  });
61
+ const VerificationReceiptInputSchema = z.preprocess((input, context) => {
62
+ if (typeof input === 'object' && input !== null && Object.hasOwn(input, '__proto__')) {
63
+ context.addIssue({ code: 'custom', message: 'Invalid verification receipt element.' });
64
+ return z.NEVER;
65
+ }
66
+ return input;
67
+ }, z.looseObject({}, { error: 'Invalid verification receipt element.' }));
61
68
  export const CompleteTaskInputSchema = z.object({
62
69
  feature_id: FeatureIdSchema,
63
70
  task_id: z.string().min(1),
64
71
  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(),
65
79
  });
66
80
  //# sourceMappingURL=contracts.js.map
@@ -14,7 +14,9 @@ export declare function captureDirectories(featDir: string, workspaceRoot?: stri
14
14
  export declare function revalidateDirectories(directories: AuthorityDirectory[]): Promise<void>;
15
15
  export declare function readArtifact(featDir: string, name: string, limit?: number, nonRegularCode?: ErrorCode, initialStat?: Stats): Promise<ArtifactCapture>;
16
16
  export declare function readFeatureArtifact(featDir: string, name: 'spec.md' | 'plan.md' | 'tasks.md' | '.lock', workspaceRoot?: string): Promise<string>;
17
- export declare function rewriteArtifact(featDir: string, name: string, expected: ArtifactCapture, content: string, beforeWrite?: () => void): Promise<void>;
17
+ export declare function rewriteArtifact(featDir: string, name: string, expected: ArtifactCapture, content: string, beforeWrite?: () => void, prepareWrite?: () => Promise<void>): Promise<void>;
18
+ export declare function isEvidencePath(value: string): boolean;
19
+ export declare function disjointPaths(paths: readonly string[]): boolean;
18
20
  export declare function hashArtifact(content: string): string;
19
21
  export declare function lastAuthorityDirectory(directories: AuthorityDirectory[]): AuthorityDirectory;
20
22
  //# sourceMappingURL=feature-authority.d.ts.map
@@ -159,9 +159,12 @@ export async function readFeatureArtifact(featDir, name, workspaceRoot) {
159
159
  await revalidateDirectories(directories);
160
160
  return artifact.content;
161
161
  }
162
- export async function rewriteArtifact(featDir, name, expected, content, beforeWrite) {
162
+ export async function rewriteArtifact(featDir, name, expected, content, beforeWrite, prepareWrite) {
163
163
  const handle = await fs.open(path.join(featDir, name), fsConstants.O_RDWR | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
164
164
  try {
165
+ if (prepareWrite) {
166
+ await prepareWrite();
167
+ }
165
168
  const stat = await handle.stat();
166
169
  checkWritable(stat);
167
170
  if (!ownedRegular(stat) ||
@@ -169,6 +172,9 @@ export async function rewriteArtifact(featDir, name, expected, content, beforeWr
169
172
  decodeArtifact(await handle.readFile()) !== expected.content) {
170
173
  guardFailure('contract_drift', 'Authoritative write checkpoint changed.');
171
174
  }
175
+ if (prepareWrite) {
176
+ await validateArtifactRead(path.join(featDir, name), handle, stat);
177
+ }
172
178
  const bytes = Buffer.from(content);
173
179
  beforeWrite?.();
174
180
  const written = await handle.write(bytes, 0, bytes.length, 0);
@@ -186,6 +192,32 @@ export async function rewriteArtifact(featDir, name, expected, content, beforeWr
186
192
  await handle.close();
187
193
  }
188
194
  }
195
+ export function isEvidencePath(value) {
196
+ const lower = value.toLowerCase();
197
+ if (value.length > 240 ||
198
+ !/^[A-Za-z0-9._/-]+$/u.test(value) ||
199
+ lower === 'planu/specs' ||
200
+ lower.startsWith('planu/specs/') ||
201
+ /\.(?:pem|key|p12|pfx)$/u.test(lower)) {
202
+ return false;
203
+ }
204
+ return lower
205
+ .split('/')
206
+ .every((part) => /^[a-z0-9._-]+$/u.test(part) &&
207
+ !['.', '..', '.git', '.sdd', 'node_modules', '.env'].includes(part) &&
208
+ !part.startsWith('.env.'));
209
+ }
210
+ export function disjointPaths(paths) {
211
+ const canonical = new Set(paths.map((item) => item.toLowerCase()));
212
+ if (canonical.size !== paths.length) {
213
+ return false;
214
+ }
215
+ return paths.every((item) => {
216
+ const parts = item.toLowerCase().split('/');
217
+ parts.pop();
218
+ return parts.every((_, index) => !canonical.has(parts.slice(0, index + 1).join('/')));
219
+ });
220
+ }
189
221
  export function hashArtifact(content) {
190
222
  return createHash('sha256').update(content).digest('hex');
191
223
  }
@@ -1,6 +1,8 @@
1
- import type { ParsedManifest } from '../types/sdd-engine.js';
1
+ import type { ParsedManifest, ReceiptPolicyResult, ReceiptSealFailure } from '../types/sdd-engine.js';
2
2
  import type { TrinityCompleteness } from '../types/completion.js';
3
3
  export declare function assessTrinityCompleteness(specContent: string, planContent: string, tasksContent: string): TrinityCompleteness;
4
4
  export declare function parseManifestContent(content: string): ParsedManifest;
5
5
  export declare function toPosixPath(value: string): string;
6
+ export declare function parseVerificationReceiptPolicy(featureId: string, plan: string, taskText: string): ReceiptPolicyResult;
7
+ export declare function receiptSealFailure(featureId: string, plan: string, tasks: string): ReceiptSealFailure | undefined;
6
8
  //# sourceMappingURL=feature-manifest.d.ts.map
@@ -1,4 +1,8 @@
1
1
  import * as path from 'node:path';
2
+ import { z } from 'zod';
3
+ import { countTaskIds, dueTaskOrdinals, hasReceiptDirective, insideMarkdownBlock, receiptCommand, taskBlocks, } from './task-content.js';
4
+ import { featureIdPattern, gateIdPattern, importReceiptPublicKey, maxVerificationReceipts, sha256Schema, taskIdPattern, } from './verification-receipts.js';
5
+ import { disjointPaths, isEvidencePath } from './feature-authority.js';
2
6
  const CHECKBOX_TASK = /^[-*]\s*\[[ xX]\]/u;
3
7
  const BDD_KEYWORDS = [/\bGIVEN\b/u, /\bWHEN\b/u, /\bTHEN\b/u];
4
8
  export function assessTrinityCompleteness(specContent, planContent, tasksContent) {
@@ -71,6 +75,13 @@ function scanManifest(planContent) {
71
75
  }
72
76
  export function parseManifestContent(content) {
73
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 = [];
74
85
  let inManifestSection = false;
75
86
  for (const rawLine of content.split('\n')) {
76
87
  const line = rawLine.trim();
@@ -79,30 +90,25 @@ export function parseManifestContent(content) {
79
90
  continue;
80
91
  }
81
92
  if (inManifestSection && /^[-*]\s+/.test(line)) {
82
- parseManifestLine(line, allowedFiles);
93
+ const entry = parseManifestLine(line);
94
+ if (entry && toPosixPath(entry.rawPath).toLowerCase() !== 'none') {
95
+ entries.push(entry);
96
+ }
83
97
  }
84
98
  }
85
- return { allowedFiles };
99
+ return entries;
86
100
  }
87
- function parseManifestLine(rawLine, allowedFiles) {
101
+ function parseManifestLine(rawLine) {
88
102
  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;
103
- }
104
- allowedFiles.set(postfixPath, postfixMatch[2].toUpperCase());
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() };
105
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;
106
112
  }
107
113
  export function toPosixPath(value) {
108
114
  const posix = value.replaceAll('\\', '/');
@@ -113,4 +119,186 @@ export function toPosixPath(value) {
113
119
  .join('/');
114
120
  return absolute ? `/${joined}` : joined;
115
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);
125
+ const policySchema = z.strictObject({
126
+ publicKey: z.string().max(128),
127
+ tasks: z
128
+ .array(z.strictObject({
129
+ taskId: z.string().regex(taskIdPattern),
130
+ gates: z
131
+ .array(z.strictObject({
132
+ id: z.string().regex(gateIdPattern),
133
+ procedureSha256: sha256Schema,
134
+ environmentSha256: sha256Schema,
135
+ }))
136
+ .min(1)
137
+ .max(maxVerificationReceipts),
138
+ observed: z.array(z.string().max(240)).max(64),
139
+ observedBaselineSha256: sha256Schema,
140
+ }))
141
+ .min(1)
142
+ .max(32),
143
+ candidateCreates: z
144
+ .array(z.strictObject({
145
+ path: z.string().max(240),
146
+ requiredFromTaskId: z.string().regex(/^[A-Z0-9_-]+$/u),
147
+ }))
148
+ .max(64),
149
+ });
150
+ 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) {
178
+ try {
179
+ const value = JSON.parse(text);
180
+ if (JSON.stringify(value, null, 2) !== text) {
181
+ return undefined;
182
+ }
183
+ const parsed = policySchema.safeParse(value);
184
+ return parsed.success ? parsed.data : undefined;
185
+ }
186
+ catch {
187
+ return undefined;
188
+ }
189
+ }
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) {
195
+ const entries = manifestEntries(plan);
196
+ const writable = entries.filter(({ permission }) => permission !== 'READ_ONLY');
197
+ const paths = writable.map(({ rawPath }) => rawPath);
198
+ if (writable.length < 1 ||
199
+ writable.length > 64 ||
200
+ !paths.every(isEvidencePath) ||
201
+ !disjointPaths(paths) ||
202
+ writable.some(({ permission }) => permission === 'DELETE')) {
203
+ return undefined;
204
+ }
205
+ 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;
208
+ }
209
+ const mappings = new Map(creates.map(({ path: candidatePath, requiredFromTaskId }) => [
210
+ candidatePath,
211
+ requiredFromTaskId,
212
+ ]));
213
+ if (mappings.size !== creates.length ||
214
+ mappings.size !== writable.filter(({ permission }) => permission === 'CREATE').length) {
215
+ return undefined;
216
+ }
217
+ const candidates = [];
218
+ for (const { rawPath, permission } of writable) {
219
+ const due = mappings.get(rawPath);
220
+ const requiredFrom = permission === 'CREATE' && due !== undefined ? dueTasks.get(due) : 1;
221
+ if (requiredFrom === undefined ||
222
+ (permission === 'CREATE' ? due === undefined : due !== undefined)) {
223
+ return undefined;
224
+ }
225
+ candidates.push({ path: rawPath, requiredFrom });
226
+ }
227
+ return candidates;
228
+ }
229
+ function bindReceiptTask(block, task, count, candidatePaths) {
230
+ 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])) {
238
+ return undefined;
239
+ }
240
+ return { ...task, command, ordinal: block.ordinal, lineIndex: block.lineIndex };
241
+ }
242
+ function readBindings(taskText, policy, plan, publicKey) {
243
+ const blocks = taskBlocks(taskText);
244
+ const byId = new Map(policy.tasks.map((task) => [task.taskId, task]));
245
+ const counts = countTaskIds(blocks);
246
+ const candidates = parseCandidates(plan, policy.candidateCreates, dueTaskOrdinals(blocks, counts));
247
+ 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))) {
251
+ return INVALID_POLICY;
252
+ }
253
+ const paths = candidates.map(({ path: candidatePath }) => candidatePath);
254
+ const tasks = new Map();
255
+ for (const block of blocks) {
256
+ const task = byId.get(block.id);
257
+ if (!task && !block.lines.some((line) => hasReceiptDirective(line))) {
258
+ continue;
259
+ }
260
+ const binding = bindReceiptTask(block, task, counts.get(block.id), paths);
261
+ if (!binding) {
262
+ return invalidTask(block);
263
+ }
264
+ tasks.set(binding.taskId, binding);
265
+ }
266
+ return tasks.size === byId.size
267
+ ? { status: 'ready', tasks, candidates, publicKey }
268
+ : INVALID_POLICY;
269
+ }
270
+ export function parseVerificationReceiptPolicy(featureId, plan, taskText) {
271
+ const text = policyText(plan);
272
+ if (text === undefined) {
273
+ if (!taskText.split('\n').some((line) => hasReceiptDirective(line))) {
274
+ return { status: 'none' };
275
+ }
276
+ const block = taskBlocks(taskText).find(({ lines }) => lines.some((line) => hasReceiptDirective(line)));
277
+ return block ? invalidTask(block) : INVALID_POLICY;
278
+ }
279
+ if (text === null || !featureIdPattern.test(featureId)) {
280
+ return INVALID_POLICY;
281
+ }
282
+ const policy = readPolicy(text);
283
+ if (!policy) {
284
+ return INVALID_POLICY;
285
+ }
286
+ const publicKey = importReceiptPublicKey(policy.publicKey);
287
+ return publicKey ? readBindings(taskText, policy, plan, publicKey) : INVALID_POLICY;
288
+ }
289
+ export function receiptSealFailure(featureId, plan, tasks) {
290
+ const policy = parseVerificationReceiptPolicy(featureId, plan, tasks);
291
+ if (policy.status === 'invalid') {
292
+ return {
293
+ ok: false,
294
+ code: 'ERR_TRINITY_INCOMPLETE',
295
+ message: 'The receipt verification policy or task directive is invalid.',
296
+ details: {
297
+ reason: 'receipt_policy_invalid',
298
+ ...(policy.taskId ? { taskId: policy.taskId } : {}),
299
+ },
300
+ };
301
+ }
302
+ return undefined;
303
+ }
116
304
  //# sourceMappingURL=feature-manifest.js.map
@@ -22,6 +22,7 @@ Delegate useful independent work within the active TASK through available native
22
22
  - 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
23
  - Quality lives in \`.claude/skills/\`, \`.cursor/skills/\`, \`.agents/skills/\`, and \`.gemini/skills/\`. Specs stay in \`.sdd/features\`. There is no validate MCP tool.
24
24
  - 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.
25
+ - 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
26
  `;
26
27
  const PROHIBITION = /\b(never|do not|don't|no longer|not|forbidden|prohibited|deleted|removed|retired|invalid|reject(?:s|ed)?)\b/iu;
27
28
  const LEGACY_TREE = /planu\/specs\/SPEC-|write (?:specs )?to planu\/specs/iu;
@@ -1,7 +1,7 @@
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
3
  export declare function verifyLockedTrinity(featDir: string): Promise<LockIntegrityResult>;
4
- export declare function writeLockedTrinity(requestedFeatDir: string, featureId: string, relock: boolean, reason: string | undefined): Promise<SealResult>;
4
+ export declare function writeLockedTrinity(requestedFeatDir: string, featureId: string, relock: boolean, reason: string | undefined): Promise<SealResult | ReceiptSealFailure>;
5
5
  export declare function executionCard(featDir: string): Promise<{
6
6
  locked: boolean;
7
7
  trinity: 'ready' | 'unlocked' | 'drift';
@@ -4,7 +4,7 @@ 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
6
  import { captureCompletionSnapshot } from './completion-snapshot.js';
7
- import { assessTrinityCompleteness, parseManifestContent } from './feature-manifest.js';
7
+ import { assessTrinityCompleteness, parseManifestContent, receiptSealFailure, } from './feature-manifest.js';
8
8
  export async function verifyLockedTrinity(featDir) {
9
9
  try {
10
10
  await captureCompletionSnapshot(featDir);
@@ -193,6 +193,10 @@ async function sealTrinityArtifacts(featDir, featureId, lockPath, lockExists, re
193
193
  if ('ok' in captured) {
194
194
  return captured;
195
195
  }
196
+ const receiptFailure = receiptSealFailure(featureId, captured['plan.md'].content, captured['tasks.md'].content);
197
+ if (receiptFailure) {
198
+ return receiptFailure;
199
+ }
196
200
  const completeness = assessTrinityCompleteness(captured['spec.md'].content, captured['plan.md'].content, captured['tasks.md'].content);
197
201
  if (!completeness.ok) {
198
202
  return {
@@ -1,8 +1,15 @@
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>;
8
15
  //# sourceMappingURL=task-content.d.ts.map