@planu/cli 8.2.16 → 8.2.18

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 (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +15 -3
  3. package/dist/sdd-engine/cli.js +0 -0
  4. package/dist/sdd-engine/completion-guard.d.ts +28 -0
  5. package/dist/sdd-engine/completion-guard.js +320 -0
  6. package/dist/sdd-engine/completion-snapshot.d.ts +11 -0
  7. package/dist/sdd-engine/completion-snapshot.js +155 -0
  8. package/dist/sdd-engine/feature-authority.d.ts +20 -0
  9. package/dist/sdd-engine/feature-authority.js +199 -0
  10. package/dist/sdd-engine/feature-manifest.d.ts +6 -0
  11. package/dist/sdd-engine/feature-manifest.js +116 -0
  12. package/dist/sdd-engine/host-rule-pack.d.ts +1 -0
  13. package/dist/sdd-engine/host-rule-pack.js +63 -7
  14. package/dist/sdd-engine/lock-integrity.d.ts +3 -18
  15. package/dist/sdd-engine/lock-integrity.js +192 -217
  16. package/dist/sdd-engine/patch-sandbox.js +6 -14
  17. package/dist/sdd-engine/server.js +4 -6
  18. package/dist/sdd-engine/task-content.d.ts +8 -0
  19. package/dist/sdd-engine/task-content.js +132 -0
  20. package/dist/sdd-engine/task-failures.d.ts +12 -0
  21. package/dist/sdd-engine/task-failures.js +125 -0
  22. package/dist/sdd-engine/task-window.d.ts +10 -4
  23. package/dist/sdd-engine/task-window.js +177 -246
  24. package/dist/sdd-engine/tools/execution-tools.js +29 -26
  25. package/dist/sdd-engine/tools/feature-store.d.ts +11 -0
  26. package/dist/sdd-engine/tools/feature-store.js +224 -0
  27. package/dist/sdd-engine/tools/workspace-tools.js +70 -127
  28. package/dist/sdd-engine/workspace-init.d.ts +3 -0
  29. package/dist/sdd-engine/workspace-init.js +197 -0
  30. package/dist/sdd-engine/workspace-root.d.ts +3 -1
  31. package/dist/sdd-engine/workspace-root.js +69 -3
  32. package/dist/types/completion.d.ts +77 -0
  33. package/dist/types/completion.js +2 -0
  34. package/package.json +32 -35
  35. package/templates/AGENTS.md +4 -0
  36. package/templates/host/planu-sdd.md +4 -0
  37. package/templates/skills/reconciler.md +8 -0
  38. package/templates/skills/spec-architect.md +22 -5
  39. package/templates/skills/spec-executor.md +11 -0
  40. package/templates/skills/verification-auditor.md +20 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ ## [8.2.18] - 2026-10-23
2
+
3
+ - guide first use with one ordinary-language setup request after Node/npm prerequisites and one-time MCP registration; read the installed role immediately and distinguish client skill-catalog reload from MCP restart
4
+ - freshly inspect all nine role bodies across 36 installed host files with bounded input/output and at most eight concurrent reads per phase; retain every physical containment check, drain started reads and avoid readiness caches
5
+ - reject unsafe feature creation and unreadable or invalid catalogues explicitly instead of returning false success, an empty list or a partial list
6
+ - give ordinary completion one physical-feature owner across clients and processes; reject contract/identity drift and read-only task/lock modes, ignore fabricated client evidence, and settle owned verification on cancellation, stdin EOF and shutdown
7
+ - require coherent task/lock/evidence readback; retain blocking ownership after uncertain persistence or post-write cancellation, and expose recovery-required state through read-only views
8
+ - recover stopped-owner state only through explicit reviewed relock with a reason, preserving reconciled bytes and history without automatic command replay, external-edit rollback or live-owner eviction
9
+ - retain matched cached-baseline benchmark samples, errors and failed attempts; local measured latency budgets are not universal performance guarantees
10
+ - clarify that planning and file operations remain available on Windows, while automated server verification requires macOS/Linux (POSIX) and fails closed on Windows; native Windows execution remains unvalidated
11
+ - keep the nine tool names and input schemas, role bodies, dependencies, engines and trusted verification limits unchanged
12
+
13
+ ## [8.2.17] - 2026-10-23
14
+
15
+ - guide planning toward one observable increment, reused contracts and executable task gates that can advance from RED to GREEN
16
+ - preserve meaningful tests and distinguish scoped static assertion review from implementation and release acceptance
17
+ - regenerate the nine known mirrors when an existing real .sdd/skills directory is initialized; reject unsafe init paths and preserve feature history
18
+ - retain paired skill-evaluation inputs, raw transcripts, process outcomes and independent evidence-cited quality reviews, including failed attempts
19
+ - keep the nine MCP tools, public schemas, dependencies, protected roots, locks, task order and verification controls unchanged
20
+
1
21
  ## [8.2.16] - 2026-10-22
2
22
 
3
23
  - reject a MODIFY patch unless its search text occurs exactly once
package/README.md CHANGED
@@ -25,6 +25,8 @@ Authentication is **not required**. Do not call `mcp_auth`.
25
25
 
26
26
  ## Installation
27
27
 
28
+ Install Node.js >=22.13.0 with npm/npx available to your MCP client. Register Planu once using a host option below, then restart its MCP connection so the nine tools are available. Open the project you intend to set up.
29
+
28
30
  ### Claude Code plugin
29
31
 
30
32
  Claude Code users can install Planu as a plugin instead of hand-editing `.mcp.json`:
@@ -104,7 +106,17 @@ Local development in this repo:
104
106
 
105
107
  The published server asks the host for MCP roots and binds to the open project that owns `.sdd/`. Unexpanded `${workspaceFolder}` and a `PLANU_WORKSPACE` equal to `$HOME` are ignored. A `~/...` workspace path is expanded against `$HOME` so hosts that interpolate tildes still bind the open folder. If the process cwd is still the user home directory, project-scoped tools return `ERR_WORKSPACE_UNRESOLVED` instead of creating `.sdd` under `$HOME`. `sdd_init_workspace` always writes Planu-owned Cursor, Claude, and Gemini host rules. Existing `AGENTS.md` is preserved unless `force: true` or the file still requires `planu/specs/SPEC-*` or instructs calling `create_spec`. `sdd_lock_spec` refuses empty skeletons and can reseal with `relock: true` and `reason`. Do not set a shell-global `PLANU_WORKSPACE`. `pnpm start` runs the MCP server.
106
108
 
107
- **Requirements:** Node.js >= 22.13.
109
+ ### Set up the open project
110
+
111
+ After the one-time client registration above, ask your agent:
112
+
113
+ > Set up Planu in this project and tell me the next step.
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`.
116
+
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
+
119
+ Windows retains planning, catalogue and file operations. Automated server verification through `sdd_complete_task` requires macOS/Linux (POSIX) and fails closed before command execution on Windows. Native Windows execution has not been validated.
108
120
 
109
121
  ---
110
122
 
@@ -177,7 +189,7 @@ MCP:
177
189
  node dist/sdd-engine/cli.js
178
190
  ```
179
191
 
180
- `pnpm eval:skills` is an operator-only eval of the spec-architect and spec-executor skills. Executor cases (`"skill": "executor"`) ship a locked trinity and fail on unchecked tasks, edits outside the File Manifest, or failing `checks`. It spends API budget by shelling out to the local `claude` CLI against a throwaway workspace, so it is not part of `pnpm check` and never runs in CI.
192
+ `pnpm eval:skills` evaluates planning, execution and test-integrity review in synthetic workspaces through the local `claude` CLI. Existing executor cases retain locked-task, File Manifest and check enforcement. The repository guide `docs/skill-quality-evaluation.md` defines the explicit paired operator protocol: eight subjects per reviewed attempt, frozen inputs, retained success/failure evidence and a separate independent quality assessment. These provider-spending evaluations require an operator launch; they are outside `pnpm check` and CI. Structural success and a scoped review do not certify production behavior.
181
193
 
182
194
  ---
183
195
 
@@ -194,7 +206,7 @@ See the [Planu Proprietary Free-Use License](LICENSE) and [planu.dev/license](ht
194
206
  "mcpServers": {
195
207
  "planu": {
196
208
  "command": "npx",
197
- "args": ["-y", "@planu/cli@8.2.16"],
209
+ "args": ["-y", "@planu/cli@8.2.18"],
198
210
  "cwd": ".",
199
211
  "env": {
200
212
  "PLANU_WORKSPACE": "."
File without changes
@@ -0,0 +1,28 @@
1
+ import type * as completion from '../types/completion.js';
2
+ export declare function inspectCompletionGuard(featDir: string): Promise<null | {
3
+ reason: 'guard_present' | 'persistence_uncertain';
4
+ phase: 'running' | 'persisting';
5
+ }>;
6
+ export declare class CompletionLease {
7
+ readonly featDir: string;
8
+ private readonly guardPath;
9
+ private readonly identity;
10
+ private record;
11
+ private readonly directories;
12
+ private readonly recovery;
13
+ private retained;
14
+ private released;
15
+ private persistenceWritten;
16
+ constructor(featDir: string, guardPath: string, identity: completion.PhysicalIdentity, record: completion.GuardRecord, directories: completion.AuthorityDirectory[], recovery?: boolean);
17
+ private check;
18
+ private update;
19
+ bind(taskId: string, command: string, snapshotDigest: string): Promise<void>;
20
+ beginPersistence(): Promise<void>;
21
+ notePersistenceWrite(): void;
22
+ retain(): void;
23
+ release(signal?: AbortSignal): Promise<void>;
24
+ }
25
+ export declare function acquireCompletionLease(requestedFeatDir: string, options?: completion.CompletionLeaseOptions): Promise<CompletionLease>;
26
+ export declare function claimStoppedCompletion(requestedFeatDir: string): Promise<CompletionLease>;
27
+ export declare function assertCatalogueAvailable(feature: completion.AuthorityDirectory): Promise<void>;
28
+ //# sourceMappingURL=completion-guard.d.ts.map
@@ -0,0 +1,320 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import * as os from 'node:os';
4
+ import * as fs from 'node:fs/promises';
5
+ import * as path from 'node:path';
6
+ import * as authority from './feature-authority.js';
7
+ const GUARD_NAME = '.completion-guard';
8
+ const GUARD_LIMIT = 4096;
9
+ function isDigest(value) {
10
+ return typeof value === 'string' && /^[a-f0-9]{64}$/u.test(value);
11
+ }
12
+ function isNonce(value) {
13
+ return typeof value === 'string' && /^[a-f0-9]{48}$/u.test(value);
14
+ }
15
+ function hasGuardOwner(value) {
16
+ return (value.version === 1 &&
17
+ typeof value.pid === 'number' &&
18
+ Number.isSafeInteger(value.pid) &&
19
+ value.pid > 0 &&
20
+ value.host === os.hostname() &&
21
+ isNonce(value.nonce) &&
22
+ typeof value.startedAt === 'string' &&
23
+ Number.isFinite(Date.parse(value.startedAt)));
24
+ }
25
+ function hasGuardBindings(value) {
26
+ return ((value.taskId === undefined ||
27
+ (typeof value.taskId === 'string' && value.taskId.length <= 128)) &&
28
+ (value.commandDigest === undefined || isDigest(value.commandDigest)) &&
29
+ (value.snapshotDigest === undefined || isDigest(value.snapshotDigest)) &&
30
+ (value.predecessor === undefined || isNonce(value.predecessor)));
31
+ }
32
+ function isGuardRecord(value, feature) {
33
+ if (!value || typeof value !== 'object') {
34
+ return false;
35
+ }
36
+ const record = value;
37
+ return (hasGuardOwner(record) &&
38
+ (record.operation === 'complete' ||
39
+ record.operation === 'patch' ||
40
+ record.operation === 'lock') &&
41
+ (record.phase === 'running' || record.phase === 'persisting') &&
42
+ record.featureDev === feature.dev &&
43
+ record.featureIno === feature.ino &&
44
+ hasGuardBindings(record));
45
+ }
46
+ function advanceGuardHistory(effective, value, knownNonces) {
47
+ if (!effective) {
48
+ if (value.predecessor !== undefined) {
49
+ authority.guardFailure('guard_present', 'Completion owner history has no base record.');
50
+ }
51
+ return value;
52
+ }
53
+ if (!value.predecessor ||
54
+ !knownNonces.has(value.predecessor) ||
55
+ value.operation !== 'lock' ||
56
+ value.phase !== 'persisting') {
57
+ authority.guardFailure('guard_present', 'Completion recovery history is malformed.');
58
+ }
59
+ return value.predecessor === effective.nonce ? value : effective;
60
+ }
61
+ function parseGuard(content, feature) {
62
+ let values;
63
+ try {
64
+ values = content.split('\n').map((line) => JSON.parse(line));
65
+ }
66
+ catch {
67
+ return authority.guardFailure('guard_present', 'Completion owner record is malformed; explicit operator reconciliation is required.');
68
+ }
69
+ let effective;
70
+ const knownNonces = new Set();
71
+ for (const value of values) {
72
+ if (!isGuardRecord(value, feature)) {
73
+ authority.guardFailure('guard_present', 'Completion owner record is unsafe or unverifiable; it was retained.');
74
+ }
75
+ effective = advanceGuardHistory(effective, value, knownNonces);
76
+ knownNonces.add(value.nonce);
77
+ }
78
+ if (!effective) {
79
+ return authority.guardFailure('guard_present', 'Completion owner record is empty.');
80
+ }
81
+ return effective;
82
+ }
83
+ async function existingGuard(featDir, name, featureIdentity) {
84
+ try {
85
+ const feature = featureIdentity ?? authority.physicalIdentity(await fs.lstat(featDir));
86
+ const artifact = await authority.readArtifact(featDir, name, GUARD_LIMIT);
87
+ return { record: parseGuard(artifact.content, feature), artifact };
88
+ }
89
+ catch (error) {
90
+ if (error.code === 'ENOENT') {
91
+ return null;
92
+ }
93
+ if (error instanceof authority.CompletionGuardError && error.reason === 'guard_present') {
94
+ throw error;
95
+ }
96
+ return authority.guardFailure('guard_present', 'Completion owner record cannot be safely inspected; it was retained.');
97
+ }
98
+ }
99
+ export async function inspectCompletionGuard(featDir) {
100
+ const directories = await authority.captureDirectories(featDir);
101
+ const guard = await existingGuard(authority.lastAuthorityDirectory(directories).directory, GUARD_NAME);
102
+ await authority.revalidateDirectories(directories);
103
+ return guard
104
+ ? {
105
+ reason: guard.record.phase === 'persisting' ? 'persistence_uncertain' : 'guard_present',
106
+ phase: guard.record.phase,
107
+ }
108
+ : null;
109
+ }
110
+ export class CompletionLease {
111
+ featDir;
112
+ guardPath;
113
+ identity;
114
+ record;
115
+ directories;
116
+ recovery;
117
+ retained = false;
118
+ released = false;
119
+ persistenceWritten = false;
120
+ constructor(featDir, guardPath, identity, record, directories, recovery = false) {
121
+ this.featDir = featDir;
122
+ this.guardPath = guardPath;
123
+ this.identity = identity;
124
+ this.record = record;
125
+ this.directories = directories;
126
+ this.recovery = recovery;
127
+ }
128
+ async check(expected = this.record) {
129
+ await authority.revalidateDirectories(this.directories);
130
+ const current = await existingGuard(this.featDir, path.basename(this.guardPath));
131
+ if (!current ||
132
+ !authority.sameIdentity(current.artifact.identity, this.identity) ||
133
+ current.record.pid !== process.pid ||
134
+ JSON.stringify(Object.entries(current.record).sort(compareGuardEntries)) !==
135
+ JSON.stringify(Object.entries(expected).sort(compareGuardEntries))) {
136
+ authority.guardFailure('persistence_uncertain', 'Completion ownership changed; operational state was retained.');
137
+ }
138
+ }
139
+ async update(next) {
140
+ if (this.recovery) {
141
+ authority.guardFailure('guard_present', 'Reviewed recovery ownership is append-only.');
142
+ }
143
+ await this.check();
144
+ const handle = await fs.open(this.guardPath, fsConstants.O_RDWR | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
145
+ try {
146
+ if (!authority.sameIdentity(this.identity, authority.physicalIdentity(await handle.stat()))) {
147
+ authority.guardFailure('persistence_uncertain', 'Completion ownership changed.');
148
+ }
149
+ const bytes = Buffer.from(JSON.stringify(next));
150
+ if (bytes.length > GUARD_LIMIT) {
151
+ authority.guardFailure('guard_present', 'Completion ownership record is too large.');
152
+ }
153
+ await handle.write(bytes, 0, bytes.length, 0);
154
+ await handle.truncate(bytes.length);
155
+ await handle.sync();
156
+ }
157
+ finally {
158
+ await handle.close();
159
+ }
160
+ this.record = next;
161
+ await this.check();
162
+ }
163
+ async bind(taskId, command, snapshotDigest) {
164
+ if (!taskId ||
165
+ taskId.length > 128 ||
166
+ typeof command !== 'string' ||
167
+ !/^[a-f0-9]{64}$/u.test(snapshotDigest)) {
168
+ authority.guardFailure('contract_drift', 'Invalid completion selection binding.');
169
+ }
170
+ await this.update({
171
+ ...this.record,
172
+ taskId,
173
+ commandDigest: authority.hashArtifact(command),
174
+ snapshotDigest,
175
+ });
176
+ }
177
+ async beginPersistence() {
178
+ if (this.recovery) {
179
+ await this.check();
180
+ return;
181
+ }
182
+ await this.update({ ...this.record, phase: 'persisting' });
183
+ }
184
+ notePersistenceWrite() {
185
+ this.persistenceWritten = true;
186
+ }
187
+ retain() {
188
+ this.retained = true;
189
+ }
190
+ async release(signal) {
191
+ if (this.retained || this.released) {
192
+ return;
193
+ }
194
+ await this.check();
195
+ await authority.revalidateDirectories(this.directories);
196
+ if (this.persistenceWritten && signal?.aborted) {
197
+ this.retain();
198
+ authority.guardFailure('persistence_uncertain', 'Cancellation observed before ownership release requires reviewed reconciliation.');
199
+ }
200
+ await fs.unlink(this.guardPath);
201
+ this.released = true;
202
+ }
203
+ }
204
+ export async function acquireCompletionLease(requestedFeatDir, options) {
205
+ const directories = await authority.captureDirectories(requestedFeatDir, options?.workspaceRoot);
206
+ const feature = authority.lastAuthorityDirectory(directories);
207
+ const featDir = feature.directory;
208
+ authority.checkWritable(await fs.lstat(featDir));
209
+ const guardPath = path.join(featDir, GUARD_NAME);
210
+ let handle;
211
+ try {
212
+ handle = await fs.open(guardPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW, 0o600);
213
+ }
214
+ catch (error) {
215
+ if (error.code === 'EEXIST') {
216
+ const guard = await existingGuard(featDir, GUARD_NAME);
217
+ authority.guardFailure(guard?.record.phase === 'persisting' ? 'persistence_uncertain' : 'guard_present', 'Feature already has a completion owner; Verification was not started.');
218
+ }
219
+ throw error;
220
+ }
221
+ const record = {
222
+ version: 1,
223
+ pid: process.pid,
224
+ host: os.hostname(),
225
+ nonce: randomBytes(24).toString('hex'),
226
+ startedAt: new Date().toISOString(),
227
+ operation: options?.operation ?? 'complete',
228
+ phase: 'running',
229
+ featureDev: feature.identity.dev,
230
+ featureIno: feature.identity.ino,
231
+ };
232
+ let identity;
233
+ try {
234
+ await handle.writeFile(JSON.stringify(record), 'utf8');
235
+ await handle.sync();
236
+ identity = authority.physicalIdentity(await handle.stat());
237
+ }
238
+ finally {
239
+ await handle.close();
240
+ }
241
+ await authority.revalidateDirectories(directories);
242
+ return new CompletionLease(featDir, guardPath, identity, record, directories);
243
+ }
244
+ export async function claimStoppedCompletion(requestedFeatDir) {
245
+ const directories = await authority.captureDirectories(requestedFeatDir);
246
+ const featDir = authority.lastAuthorityDirectory(directories).directory;
247
+ const guard = await existingGuard(featDir, GUARD_NAME);
248
+ if (!guard) {
249
+ return acquireCompletionLease(featDir, { operation: 'lock' });
250
+ }
251
+ try {
252
+ process.kill(guard.record.pid, 0);
253
+ }
254
+ catch (error) {
255
+ if (error.code !== 'ESRCH') {
256
+ authority.guardFailure('guard_present', 'Completion owner liveness is unknown; recovery is blocked.');
257
+ }
258
+ const record = createRecoveryRecord(guard.record);
259
+ const guardPath = path.join(featDir, GUARD_NAME);
260
+ const handle = await fs.open(guardPath, fsConstants.O_APPEND | fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
261
+ try {
262
+ if (!authority.sameIdentity(guard.artifact.identity, authority.physicalIdentity(await handle.stat()))) {
263
+ authority.guardFailure('guard_present', 'Completion owner identity changed before reviewed recovery.');
264
+ }
265
+ await authority.revalidateDirectories(directories);
266
+ const checkpoint = await existingGuard(featDir, GUARD_NAME);
267
+ if (checkpoint?.record.nonce !== guard.record.nonce) {
268
+ authority.guardFailure('guard_present', 'Another recovery claimed this completion.');
269
+ }
270
+ const bytes = Buffer.from(`\n${JSON.stringify(record)}`);
271
+ const stat = await handle.stat();
272
+ if (stat.size + bytes.length > GUARD_LIMIT) {
273
+ authority.guardFailure('guard_present', 'Completion recovery history reached its bounded capacity; operator reconciliation is required.');
274
+ }
275
+ // One append syscall publishes the complete claim. The first claim for a
276
+ // predecessor wins; a concurrent loser never writes trinity artifacts.
277
+ const written = await handle.write(bytes, 0, bytes.length, null);
278
+ if (written.bytesWritten !== bytes.length) {
279
+ authority.guardFailure('guard_present', 'Completion recovery claim is incomplete; owner record was retained.');
280
+ }
281
+ await handle.sync();
282
+ }
283
+ finally {
284
+ await handle.close();
285
+ }
286
+ const claimed = await existingGuard(featDir, GUARD_NAME);
287
+ if (claimed?.record.nonce !== record.nonce ||
288
+ !authority.sameIdentity(claimed.artifact.identity, guard.artifact.identity)) {
289
+ authority.guardFailure('guard_present', 'Another recovery owns this completion.');
290
+ }
291
+ await authority.revalidateDirectories(directories);
292
+ return new CompletionLease(featDir, guardPath, guard.artifact.identity, record, directories, true);
293
+ }
294
+ return authority.guardFailure('guard_present', 'Completion owner is live or its PID was reused; recovery is blocked.');
295
+ }
296
+ export async function assertCatalogueAvailable(feature) {
297
+ const guard = await existingGuard(feature.directory, GUARD_NAME, feature.identity);
298
+ if (guard) {
299
+ authority.guardFailure(guard.record.phase === 'persisting' ? 'persistence_uncertain' : 'guard_present', 'Feature ownership requires completion or explicit reviewed recovery before listing.', 'ERR_VERIFICATION_FAILED');
300
+ }
301
+ }
302
+ function compareGuardEntries(left, right) {
303
+ const [leftText, rightText] = [String(left), String(right)];
304
+ return leftText < rightText ? -1 : leftText > rightText ? 1 : 0;
305
+ }
306
+ function createRecoveryRecord(predecessor) {
307
+ return {
308
+ version: 1,
309
+ pid: process.pid,
310
+ host: os.hostname(),
311
+ nonce: randomBytes(24).toString('hex'),
312
+ startedAt: new Date().toISOString(),
313
+ operation: 'lock',
314
+ phase: 'persisting',
315
+ featureDev: predecessor.featureDev,
316
+ featureIno: predecessor.featureIno,
317
+ predecessor: predecessor.nonce,
318
+ };
319
+ }
320
+ //# sourceMappingURL=completion-guard.js.map
@@ -0,0 +1,11 @@
1
+ import type { CompletionSnapshot, CompletionSnapshotOptions } from '../types/completion.js';
2
+ import { type CompletionLease } from './completion-guard.js';
3
+ /** Catalogue reads need task status and lock presence, not an execution readiness card. */
4
+ export declare function readCatalogueArtifacts(featDir: string): Promise<{
5
+ tasksContent: string;
6
+ locked: boolean;
7
+ }>;
8
+ export declare function captureCompletionSnapshot(requestedFeatDir: string, options?: CompletionSnapshotOptions): Promise<CompletionSnapshot>;
9
+ export declare function revalidateCompletionSnapshot(snapshot: CompletionSnapshot): Promise<void>;
10
+ export declare function persistCompletionSnapshot(lease: CompletionLease, snapshot: CompletionSnapshot, writtenTasks: string, signal?: AbortSignal): Promise<void>;
11
+ //# sourceMappingURL=completion-snapshot.d.ts.map
@@ -0,0 +1,155 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { CompletionGuardError, captureDirectories, lastAuthorityDirectory, checkWritable, guardFailure, hashArtifact, readArtifact, revalidateDirectories, rewriteArtifact, sameIdentity, } from './feature-authority.js';
4
+ import { assertCatalogueAvailable } from './completion-guard.js';
5
+ /** Catalogue reads need task status and lock presence, not an execution readiness card. */
6
+ export async function readCatalogueArtifacts(featDir) {
7
+ const directories = await captureDirectories(featDir);
8
+ const feature = lastAuthorityDirectory(directories);
9
+ await assertCatalogueAvailable(feature);
10
+ const tasks = await readArtifact(feature.directory, 'tasks.md', undefined, 'ERR_INVALID_ARTIFACT');
11
+ let lockStat;
12
+ try {
13
+ lockStat = await fs.lstat(path.join(feature.directory, '.lock'));
14
+ }
15
+ catch (error) {
16
+ if (error.code !== 'ENOENT') {
17
+ throw error;
18
+ }
19
+ }
20
+ if (lockStat) {
21
+ await readArtifact(feature.directory, '.lock', undefined, 'ERR_INVALID_ARTIFACT', lockStat);
22
+ }
23
+ const locked = lockStat !== undefined;
24
+ await assertCatalogueAvailable(feature);
25
+ await revalidateDirectories(directories);
26
+ return { tasksContent: tasks.content, locked };
27
+ }
28
+ export async function captureCompletionSnapshot(requestedFeatDir, options) {
29
+ const directories = await captureDirectories(requestedFeatDir, options?.workspaceRoot);
30
+ const featDir = lastAuthorityDirectory(directories).directory;
31
+ const artifacts = {};
32
+ for (const name of ['.lock', 'spec.md', 'plan.md', 'tasks.md']) {
33
+ try {
34
+ artifacts[name] = await readArtifact(featDir, name);
35
+ }
36
+ catch (error) {
37
+ if (name === '.lock' && error.code === 'ENOENT') {
38
+ throw new CompletionGuardError('contract_drift', 'Feature spec must be locked before execution.', 'ERR_SPEC_NOT_LOCKED');
39
+ }
40
+ throw error;
41
+ }
42
+ if (options?.writable && (name === 'tasks.md' || name === '.lock')) {
43
+ checkWritable(await fs.lstat(path.join(featDir, name)));
44
+ }
45
+ }
46
+ const lock = validateSnapshotLock(artifacts, options?.validateLock);
47
+ await revalidateDirectories(directories);
48
+ const digest = hashArtifact(JSON.stringify({ directories, artifacts }));
49
+ return {
50
+ featDir,
51
+ directories,
52
+ artifacts,
53
+ specContent: artifacts['spec.md'].content,
54
+ planContent: artifacts['plan.md'].content,
55
+ tasksContent: artifacts['tasks.md'].content,
56
+ lockContent: artifacts['.lock'].content,
57
+ lock,
58
+ digest,
59
+ };
60
+ }
61
+ export async function revalidateCompletionSnapshot(snapshot) {
62
+ await revalidateDirectories(snapshot.directories);
63
+ try {
64
+ for (const name of ['.lock', 'spec.md', 'plan.md', 'tasks.md']) {
65
+ const current = await readArtifact(snapshot.featDir, name);
66
+ const expected = snapshot.artifacts[name];
67
+ if (current.content !== expected.content ||
68
+ !sameIdentity(current.identity, expected.identity)) {
69
+ guardFailure('contract_drift', 'Authoritative completion snapshot changed after selection.');
70
+ }
71
+ }
72
+ await revalidateDirectories(snapshot.directories);
73
+ }
74
+ catch {
75
+ guardFailure('contract_drift', 'Authoritative completion snapshot changed after selection.');
76
+ }
77
+ }
78
+ export async function persistCompletionSnapshot(lease, snapshot, writtenTasks, signal) {
79
+ if (signal?.aborted) {
80
+ guardFailure('cancelled', 'Completion was cancelled before persistence.');
81
+ }
82
+ await revalidateCompletionSnapshot(snapshot);
83
+ await lease.beginPersistence();
84
+ if (signal?.aborted) {
85
+ guardFailure('cancelled', 'Completion was cancelled before persistence.');
86
+ }
87
+ const persistence = { writeStarted: false };
88
+ try {
89
+ await rewriteArtifact(snapshot.featDir, 'tasks.md', snapshot.artifacts['tasks.md'], writtenTasks, () => {
90
+ if (signal?.aborted) {
91
+ guardFailure('cancelled', 'Completion was cancelled before its first persistence write.');
92
+ }
93
+ // The following syscall can write a prefix even when it rejects.
94
+ persistence.writeStarted = true;
95
+ lease.notePersistenceWrite();
96
+ });
97
+ const writtenLock = JSON.stringify({ ...snapshot.lock, tasksHash: hashArtifact(writtenTasks) }, null, 2);
98
+ await revalidatePersistedContract(snapshot);
99
+ await rewriteArtifact(snapshot.featDir, '.lock', snapshot.artifacts['.lock'], writtenLock);
100
+ const readback = await captureCompletionSnapshot(snapshot.featDir);
101
+ await revalidateDirectories(snapshot.directories);
102
+ for (const name of ['spec.md', 'plan.md', 'tasks.md', '.lock']) {
103
+ if (!sameIdentity(readback.artifacts[name].identity, snapshot.artifacts[name].identity)) {
104
+ guardFailure('persistence_uncertain', 'Completion readback identity changed.');
105
+ }
106
+ }
107
+ if (readback.tasksContent !== writtenTasks ||
108
+ readback.lockContent !== writtenLock ||
109
+ readback.specContent !== snapshot.specContent ||
110
+ readback.planContent !== snapshot.planContent ||
111
+ signal?.aborted) {
112
+ guardFailure('persistence_uncertain', 'Completion readback or cancellation requires explicit reconciliation.');
113
+ }
114
+ }
115
+ catch (error) {
116
+ if (persistence.writeStarted) {
117
+ lease.retain();
118
+ guardFailure('persistence_uncertain', 'Completion persistence is uncertain; reviewed stopped-owner relock is required.');
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+ function hasSnapshotHashes(value, artifacts) {
124
+ if (!value || typeof value !== 'object') {
125
+ return false;
126
+ }
127
+ const record = value;
128
+ return (record.specHash === hashArtifact(artifacts['spec.md'].content) &&
129
+ record.planHash === hashArtifact(artifacts['plan.md'].content) &&
130
+ record.tasksHash === hashArtifact(artifacts['tasks.md'].content));
131
+ }
132
+ function validateSnapshotLock(artifacts, validateLock) {
133
+ let lock;
134
+ try {
135
+ lock = JSON.parse(artifacts['.lock'].content);
136
+ }
137
+ catch {
138
+ return guardFailure('contract_drift', 'Lock file is not valid JSON.');
139
+ }
140
+ if (validateLock !== false && !hasSnapshotHashes(lock, artifacts)) {
141
+ guardFailure('contract_drift', 'Locked trinity hashes do not match the authoritative bytes.');
142
+ }
143
+ return lock;
144
+ }
145
+ async function revalidatePersistedContract(snapshot) {
146
+ await revalidateDirectories(snapshot.directories);
147
+ for (const name of ['spec.md', 'plan.md']) {
148
+ const current = await readArtifact(snapshot.featDir, name);
149
+ if (current.content !== snapshot.artifacts[name].content ||
150
+ !sameIdentity(current.identity, snapshot.artifacts[name].identity)) {
151
+ guardFailure('persistence_uncertain', 'Locked contract changed during persistence.');
152
+ }
153
+ }
154
+ }
155
+ //# sourceMappingURL=completion-snapshot.js.map
@@ -0,0 +1,20 @@
1
+ import { type Stats } from 'node:fs';
2
+ import type { ErrorCode } from '../types/sdd-engine.js';
3
+ import type { CompletionFailureReason, PhysicalIdentity, ArtifactCapture, AuthorityDirectory } from '../types/completion.js';
4
+ export declare class CompletionGuardError extends Error {
5
+ readonly reason: CompletionFailureReason;
6
+ readonly code: ErrorCode;
7
+ constructor(reason: CompletionFailureReason, message: string, code?: ErrorCode);
8
+ }
9
+ export declare function guardFailure(reason: CompletionFailureReason, message: string, code?: ErrorCode): never;
10
+ export declare function physicalIdentity(stat: Stats): PhysicalIdentity;
11
+ export declare function sameIdentity(left: PhysicalIdentity, right: PhysicalIdentity): boolean;
12
+ export declare function checkWritable(stat: Stats): void;
13
+ export declare function captureDirectories(featDir: string, workspaceRoot?: string): Promise<AuthorityDirectory[]>;
14
+ export declare function revalidateDirectories(directories: AuthorityDirectory[]): Promise<void>;
15
+ export declare function readArtifact(featDir: string, name: string, limit?: number, nonRegularCode?: ErrorCode, initialStat?: Stats): Promise<ArtifactCapture>;
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>;
18
+ export declare function hashArtifact(content: string): string;
19
+ export declare function lastAuthorityDirectory(directories: AuthorityDirectory[]): AuthorityDirectory;
20
+ //# sourceMappingURL=feature-authority.d.ts.map