@planu/cli 8.5.1 → 8.7.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 (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +16 -4
  3. package/dist/sdd-engine/completion-guard.js +2 -3
  4. package/dist/sdd-engine/contracts.d.ts +172 -0
  5. package/dist/sdd-engine/contracts.js +235 -10
  6. package/dist/sdd-engine/evidence-checkpoints.d.ts +6 -0
  7. package/dist/sdd-engine/evidence-checkpoints.js +280 -0
  8. package/dist/sdd-engine/evidence-journal.d.ts +25 -0
  9. package/dist/sdd-engine/evidence-journal.js +326 -0
  10. package/dist/sdd-engine/feature-manifest.d.ts +2 -1
  11. package/dist/sdd-engine/host-rule-pack.d.ts +4 -0
  12. package/dist/sdd-engine/host-rule-pack.js +114 -55
  13. package/dist/sdd-engine/host-skill-reader.d.ts +8 -1
  14. package/dist/sdd-engine/host-skill-reader.js +73 -0
  15. package/dist/sdd-engine/resume-history.d.ts +35 -3
  16. package/dist/sdd-engine/resume-history.js +242 -13
  17. package/dist/sdd-engine/resume-views.d.ts +7 -6
  18. package/dist/sdd-engine/resume-views.js +246 -114
  19. package/dist/sdd-engine/task-content.d.ts +2 -1
  20. package/dist/sdd-engine/task-failures.d.ts +30 -13
  21. package/dist/sdd-engine/task-failures.js +284 -115
  22. package/dist/sdd-engine/task-window.d.ts +6 -3
  23. package/dist/sdd-engine/task-window.js +12 -23
  24. package/dist/sdd-engine/tools/compact-result.d.ts +35 -5
  25. package/dist/sdd-engine/tools/compact-result.js +279 -2
  26. package/dist/sdd-engine/tools/execution-tools.js +20 -9
  27. package/dist/sdd-engine/tools/workspace-tools.js +80 -51
  28. package/dist/sdd-engine/trinity-structure.d.ts +2 -2
  29. package/dist/sdd-engine/verification-inputs.d.ts +2 -1
  30. package/dist/sdd-engine/verification-policy.d.ts +7 -6
  31. package/dist/sdd-engine/verification-policy.js +74 -85
  32. package/dist/sdd-engine/verification-preflight.d.ts +9 -7
  33. package/dist/sdd-engine/verification-preflight.js +108 -89
  34. package/dist/sdd-engine/verification-receipts.d.ts +2 -2
  35. package/dist/sdd-engine/verification-receipts.js +2 -1
  36. package/dist/sdd-engine/verification-runner.d.ts +3 -1
  37. package/dist/sdd-engine/verification-runner.js +12 -7
  38. package/dist/types/completion.d.ts +183 -3
  39. package/dist/types/resume-views.d.ts +221 -2
  40. package/dist/types/sdd-engine.d.ts +52 -112
  41. package/dist/types/verification.d.ts +26 -9
  42. package/package.json +5 -5
  43. package/templates/AGENTS.md +4 -0
  44. package/templates/host/planu-sdd.md +4 -0
  45. package/templates/skills/preflight-guardian.md +4 -0
  46. package/templates/skills/reconciler.md +6 -0
  47. package/templates/skills/spec-architect.md +44 -0
  48. package/templates/skills/spec-executor.md +6 -0
  49. package/templates/skills/verification-auditor.md +6 -0
  50. package/dist/sdd-engine/tools/format-result.d.ts +0 -3
  51. package/dist/sdd-engine/tools/format-result.js +0 -22
@@ -0,0 +1,280 @@
1
+ import { constants } from 'node:fs';
2
+ import * as fs from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { acquireCompletionLease, inspectCompletionGuard, } from './completion-guard.js';
5
+ import { captureCompletionSnapshot, revalidateCompletionSnapshot } from './completion-snapshot.js';
6
+ import { captureVerificationRoot, revalidateVerificationInputs } from './verification-inputs.js';
7
+ import { assessVerificationPreflight } from './verification-preflight.js';
8
+ import { parseVerificationReceiptPolicy } from './feature-manifest.js';
9
+ import { activeTaskFromContent } from './task-content.js';
10
+ import { verificationCommand } from './task-window.js';
11
+ import { CompletionGuardError, guardFailure, readArtifact } from './feature-authority.js';
12
+ import { parseCheckpoint } from './contracts.js';
13
+ import * as journal from './evidence-journal.js';
14
+ import * as outcome from './tools/compact-result.js';
15
+ function requireNotCancelled(signal) {
16
+ if (signal?.aborted) {
17
+ guardFailure('cancelled', 'Checkpoint cancelled.');
18
+ }
19
+ }
20
+ function journalMatches(left, right) {
21
+ return (left?.snapshotSha256 === right?.snapshotSha256 &&
22
+ left?.headSha256 === right?.headSha256 &&
23
+ left?.count === right?.count);
24
+ }
25
+ async function prepareCheckpoint(featureId, taskId, input, workspaceRoot, featDir, capability, signal) {
26
+ const root = await captureVerificationRoot(workspaceRoot);
27
+ const snapshot = await journal.captureInitialCheckpointSnapshot(featDir, root, capability);
28
+ if (journal.evidenceAuthoritySha256(snapshot, root) !== input.expectedSnapshotSha256 ||
29
+ path.basename(snapshot.featDir) !== featureId) {
30
+ throw new outcome.CheckpointError('checkpoint_context_stale');
31
+ }
32
+ const selected = activeTaskFromContent(snapshot.tasksContent, verificationCommand);
33
+ const active = selected.success ? selected.data.activeTask : null;
34
+ if (!active) {
35
+ throw new outcome.CheckpointError('checkpoint_requires_active_task');
36
+ }
37
+ if (active.taskId !== taskId) {
38
+ throw new outcome.CheckpointError('checkpoint_context_stale');
39
+ }
40
+ const policy = parseVerificationReceiptPolicy(featureId, snapshot.planContent, snapshot.tasksContent);
41
+ if (policy.status === 'invalid') {
42
+ throw new outcome.CheckpointError('checkpoint_context_stale');
43
+ }
44
+ const task = policy.status === 'ready' ? policy.tasks.get(taskId) : undefined;
45
+ if (input.reported.kind === 'required_gate' &&
46
+ !task?.gates.some(({ id }) => id === input.reported.gateId)) {
47
+ throw new outcome.CheckpointError('checkpoint_input_invalid');
48
+ }
49
+ const assessment = await assessVerificationPreflight(snapshot, root, workspaceRoot, active, undefined, undefined, signal);
50
+ if (assessment.preflight.blockers.some(({ reason }) => reason === 'receipt_observed_baseline_drift')) {
51
+ throw new outcome.CheckpointError('checkpoint_context_stale');
52
+ }
53
+ const evidence = assessment.evidence;
54
+ const context = {
55
+ featureId,
56
+ taskId,
57
+ snapshotSha256: journal.evidenceAuthoritySha256(snapshot, root),
58
+ contract: {
59
+ specSha256: journal.hash(snapshot.specContent),
60
+ planSha256: journal.hash(snapshot.planContent),
61
+ tasksSha256: journal.hash(snapshot.tasksContent),
62
+ lockSha256: journal.hash(snapshot.lockContent),
63
+ },
64
+ candidate: evidence
65
+ ? {
66
+ workspaceSha256: evidence.workspaceSha256,
67
+ candidateSha256: evidence.candidateSha256,
68
+ observedSha256: evidence.observedSha256,
69
+ }
70
+ : null,
71
+ candidateState: evidence ? 'captured' : task ? 'unavailable' : 'not_configured',
72
+ };
73
+ return { root, snapshot, assessment, context };
74
+ }
75
+ async function validateCheckpointAuthority(prepared, workspaceRoot, capability, signal) {
76
+ requireNotCancelled(signal);
77
+ journal.checkCapability(capability);
78
+ await journal.checkCheckpointDirectories(prepared.snapshot);
79
+ const guardRead = readArtifact(prepared.snapshot.featDir, '.completion-guard', 4096);
80
+ const guard = await guardRead.catch(outcome.checkpointRevalidationError);
81
+ if (guard.identity.uid !== capability.uid) {
82
+ throw new outcome.CheckpointError('checkpoint_path_unsafe');
83
+ }
84
+ if (prepared.assessment.inputs) {
85
+ await revalidateVerificationInputs(prepared.assessment.inputs, signal);
86
+ }
87
+ const current = await captureCompletionSnapshot(prepared.snapshot.featDir, {
88
+ workspaceRoot,
89
+ }).catch(outcome.checkpointRevalidationError);
90
+ journal.requireOwnedSnapshot(current, capability);
91
+ if (journal.evidenceAuthoritySha256(current, prepared.root) !== prepared.context.snapshotSha256) {
92
+ throw new outcome.CheckpointError('checkpoint_context_stale');
93
+ }
94
+ await revalidateCompletionSnapshot(prepared.snapshot);
95
+ const root = await captureVerificationRoot(workspaceRoot);
96
+ if (root.canonical !== prepared.root.canonical ||
97
+ root.stat.dev !== prepared.root.stat.dev ||
98
+ root.stat.ino !== prepared.root.stat.ino ||
99
+ root.stat.mode !== prepared.root.stat.mode ||
100
+ root.stat.uid !== prepared.root.stat.uid ||
101
+ root.stat.gid !== prepared.root.stat.gid) {
102
+ throw new outcome.CheckpointError('checkpoint_path_unsafe');
103
+ }
104
+ }
105
+ async function openForCheckpoint(prepared, before, lease, capability, state) {
106
+ const creating = before.identity === null;
107
+ const filename = path.join(prepared.snapshot.featDir, '.evidence-checkpoints.jsonl');
108
+ if (creating) {
109
+ state.start();
110
+ }
111
+ try {
112
+ const creationFlags = creating ? constants.O_CREAT | constants.O_EXCL : 0;
113
+ const flags = constants.O_RDWR | capability.noFollow | constants.O_NONBLOCK | creationFlags;
114
+ const handle = await fs.open(filename, flags, 0o600);
115
+ if (creating) {
116
+ lease.notePersistenceWrite();
117
+ }
118
+ return handle;
119
+ }
120
+ catch (error) {
121
+ if (creating && outcome.checkpointOpenDenied(error)) {
122
+ state.reset();
123
+ }
124
+ if (creating && error instanceof Error && error.code === 'EEXIST') {
125
+ await journal.captureJournal(prepared.snapshot, prepared.root, capability);
126
+ throw new outcome.CheckpointError('checkpoint_context_stale');
127
+ }
128
+ if (outcome.checkpointUnsupported(error)) {
129
+ throw new outcome.CheckpointCapabilityError();
130
+ }
131
+ throw error;
132
+ }
133
+ }
134
+ async function verifyPrefix(handle, before, featureId) {
135
+ if (!before.reference) {
136
+ return;
137
+ }
138
+ const prefix = await journal.readChain(handle, before.size, featureId);
139
+ if (prefix.hash !== before.bytesSha256 ||
140
+ prefix.head !== before.reference.headSha256 ||
141
+ prefix.count !== before.reference.count) {
142
+ throw new outcome.CheckpointError('checkpoint_context_stale');
143
+ }
144
+ }
145
+ async function validateWriteHandle(handle, prepared, before, capability) {
146
+ const stat = await handle.stat();
147
+ const named = await fs.lstat(path.join(prepared.snapshot.featDir, '.evidence-checkpoints.jsonl'));
148
+ if (!journal.checkpointOwned(stat, capability) ||
149
+ !journal.checkpointOwned(named, capability) ||
150
+ stat.size !== before.size ||
151
+ !journal.sameCheckpointJournalIdentity(journal.journalIdentity(stat), journal.journalIdentity(named)) ||
152
+ (before.identity !== null &&
153
+ !journal.sameCheckpointJournalIdentity(before.identity, journal.journalIdentity(stat)))) {
154
+ throw new outcome.CheckpointError('checkpoint_path_unsafe');
155
+ }
156
+ await verifyPrefix(handle, before, path.basename(prepared.snapshot.featDir));
157
+ }
158
+ async function readbackCheckpoint(handle, prepared, before, record, bytes, capability) {
159
+ const readback = Buffer.alloc(bytes.length);
160
+ const read = await handle.read(readback, 0, bytes.length, before.size);
161
+ if (read.bytesRead !== bytes.length || !readback.equals(bytes)) {
162
+ guardFailure('persistence_uncertain', 'Checkpoint readback changed.');
163
+ }
164
+ await verifyPrefix(handle, before, path.basename(prepared.snapshot.featDir));
165
+ const stat = await handle.stat();
166
+ const after = await journal.captureJournal(prepared.snapshot, prepared.root, capability);
167
+ if (after.reference?.headSha256 !== record.recordSha256 ||
168
+ after.reference.count !== record.seq ||
169
+ after.size !== before.size + bytes.length ||
170
+ !after.identity ||
171
+ !journal.sameCheckpointJournalIdentity(journal.journalIdentity(stat), after.identity)) {
172
+ guardFailure('persistence_uncertain', 'Checkpoint journal changed.');
173
+ }
174
+ return after.reference;
175
+ }
176
+ async function writeRecord(prepared, before, record, lease, capability, state, workspaceRoot, signal) {
177
+ const bytes = Buffer.from(`${JSON.stringify(record)}\n`);
178
+ if (bytes.length > 4096) {
179
+ throw new outcome.CheckpointError('checkpoint_input_invalid');
180
+ }
181
+ await validateCheckpointAuthority(prepared, workspaceRoot, capability, signal);
182
+ const refreshed = await journal.captureJournal(prepared.snapshot, prepared.root, capability);
183
+ if (!journalMatches(before.reference, refreshed.reference)) {
184
+ throw new outcome.CheckpointError('checkpoint_context_stale');
185
+ }
186
+ journal.checkCapability(capability);
187
+ if (before.identity === null) {
188
+ await lease.beginPersistence();
189
+ }
190
+ requireNotCancelled(signal);
191
+ const handle = await openForCheckpoint(prepared, before, lease, capability, state);
192
+ try {
193
+ await validateWriteHandle(handle, prepared, before, capability);
194
+ await validateCheckpointAuthority(prepared, workspaceRoot, capability, signal);
195
+ requireNotCancelled(signal);
196
+ await lease.beginPersistence();
197
+ requireNotCancelled(signal);
198
+ state.start();
199
+ lease.notePersistenceWrite();
200
+ const written = await handle.write(bytes, 0, bytes.length, before.size);
201
+ if (written.bytesWritten !== bytes.length) {
202
+ guardFailure('persistence_uncertain', 'Checkpoint write was incomplete.');
203
+ }
204
+ await handle.sync();
205
+ const reference = await readbackCheckpoint(handle, prepared, before, record, bytes, capability);
206
+ await validateCheckpointAuthority(prepared, workspaceRoot, capability, signal);
207
+ return reference;
208
+ }
209
+ finally {
210
+ await handle.close();
211
+ }
212
+ }
213
+ async function acquireCheckpoint(featDir, workspaceRoot) {
214
+ return await acquireCompletionLease(featDir, { operation: 'checkpoint', workspaceRoot }).catch(async (error) => {
215
+ if (error instanceof CompletionGuardError || !outcome.checkpointAcquireIoError(error)) {
216
+ throw error;
217
+ }
218
+ const guard = await inspectCompletionGuard(featDir).catch(outcome.checkpointGuardInspectionError);
219
+ if (guard) {
220
+ guardFailure(guard.reason, 'Checkpoint guard requires inspection.');
221
+ }
222
+ if (outcome.checkpointOpenUnsupported(error)) {
223
+ throw new outcome.CheckpointCapabilityError();
224
+ }
225
+ throw new outcome.CheckpointError('checkpoint_path_unsafe');
226
+ });
227
+ }
228
+ export async function appendEvidenceCheckpoint(featureId, taskId, input, workspaceRoot, featDir, capability, signal) {
229
+ const checkpoint = parseCheckpoint(featureId, taskId, input);
230
+ if (!checkpoint) {
231
+ return outcome.checkpointError('checkpoint_input_invalid');
232
+ }
233
+ let lease;
234
+ let started = false;
235
+ const state = {
236
+ start: () => {
237
+ started = true;
238
+ },
239
+ reset: () => {
240
+ started = false;
241
+ },
242
+ started: () => started,
243
+ };
244
+ let result;
245
+ try {
246
+ journal.checkCapability(capability);
247
+ requireNotCancelled(signal);
248
+ lease = await acquireCheckpoint(featDir, workspaceRoot);
249
+ const prepared = await prepareCheckpoint(featureId, taskId, checkpoint, workspaceRoot, featDir, capability, signal);
250
+ const before = await journal.captureJournal(prepared.snapshot, prepared.root, capability);
251
+ if (!journalMatches(before.reference, checkpoint.expectedJournal)) {
252
+ result = outcome.checkpointError('checkpoint_context_stale');
253
+ }
254
+ else {
255
+ const record = journal.makeRecord(prepared.context, checkpoint, before.reference);
256
+ const reference = await writeRecord(prepared, before, record, lease, capability, state, workspaceRoot, signal);
257
+ result = outcome.checkpointSuccess(record.seq, record.recordSha256, reference);
258
+ }
259
+ }
260
+ catch (error) {
261
+ if (state.started() && lease) {
262
+ lease.retain();
263
+ result = outcome.checkpointError('persistence_uncertain');
264
+ }
265
+ else {
266
+ result = outcome.checkpointException(error, error instanceof outcome.CheckpointCapabilityError);
267
+ }
268
+ }
269
+ if (lease) {
270
+ try {
271
+ await lease.release(signal);
272
+ }
273
+ catch {
274
+ lease.retain();
275
+ return state.started() ? outcome.checkpointError('persistence_uncertain') : result;
276
+ }
277
+ }
278
+ return result;
279
+ }
280
+ //# sourceMappingURL=evidence-checkpoints.js.map
@@ -0,0 +1,25 @@
1
+ import { type Stats } from 'node:fs';
2
+ import * as fs from 'node:fs/promises';
3
+ import type { CheckpointCapability, CompletionSnapshot, CheckpointJournalIdentity, CheckpointJournalCapture, WorkspaceRoot } from '../types/completion.js';
4
+ import type { EvidenceCheckpointRecord } from '../types/resume-views.js';
5
+ import type { EvidenceCheckpointInput, CheckpointJournalReference } from '../types/sdd-engine.js';
6
+ import * as authority from './feature-authority.js';
7
+ export declare function evidenceAuthoritySha256(snapshot: CompletionSnapshot, root: WorkspaceRoot): string;
8
+ export declare function checkpointCapability(): CheckpointCapability | null;
9
+ export declare function requireOwnedSnapshot(snapshot: CompletionSnapshot, capability: CheckpointCapability): void;
10
+ export declare function checkCapability(capability: CheckpointCapability): void;
11
+ export declare function captureInitialCheckpointSnapshot(featDir: string, root: WorkspaceRoot, capability: CheckpointCapability): Promise<CompletionSnapshot>;
12
+ export declare function checkCheckpointDirectories(snapshot: CompletionSnapshot): Promise<void>;
13
+ export declare function journalIdentity(stat: Stats): CheckpointJournalIdentity;
14
+ export declare function sameCheckpointJournalIdentity(left: CheckpointJournalIdentity, right: CheckpointJournalIdentity): boolean;
15
+ export declare function checkpointOwned(stat: Stats, capability: CheckpointCapability): boolean;
16
+ export declare const hash: typeof authority.hashArtifact;
17
+ export declare function checkpointRecordHash(record: Omit<EvidenceCheckpointRecord, 'recordSha256'>): string;
18
+ export declare function makeRecord(context: EvidenceCheckpointRecord['context'], input: EvidenceCheckpointInput, reference: CheckpointJournalReference | null): EvidenceCheckpointRecord;
19
+ export declare function readChain(handle: fs.FileHandle, length: number, featureId: string, collect?: (record: EvidenceCheckpointRecord) => void): Promise<{
20
+ count: number;
21
+ head: string;
22
+ hash: string;
23
+ }>;
24
+ export declare function captureJournal(snapshot: CompletionSnapshot, root: WorkspaceRoot, capability: CheckpointCapability, collect?: (record: EvidenceCheckpointRecord) => void): Promise<CheckpointJournalCapture>;
25
+ //# sourceMappingURL=evidence-journal.d.ts.map
@@ -0,0 +1,326 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import * as fs from 'node:fs/promises';
4
+ import * as path from 'node:path';
5
+ import { parseCheckpointJournalRecord, CheckpointRecordSchema, isInitialCheckpointLock, } from './contracts.js';
6
+ import { captureVerificationRoot } from './verification-inputs.js';
7
+ import { CheckpointCapabilityError, CheckpointError, checkpointUnsupported, checkpointInitialLockError, checkpointDirectoryError, checkpointRevalidationError, } from './tools/compact-result.js';
8
+ import * as authority from './feature-authority.js';
9
+ import { captureCompletionSnapshot } from './completion-snapshot.js';
10
+ const JOURNAL = '.evidence-checkpoints.jsonl';
11
+ const MAX_LINE = 4096;
12
+ function failure() {
13
+ throw new CheckpointError('checkpoint_path_unsafe');
14
+ }
15
+ function safeNumber(value) {
16
+ return Number.isSafeInteger(value) && value >= 0 ? value : failure();
17
+ }
18
+ function rootProjection(root) {
19
+ const { dev, ino, mode, uid, gid } = root.stat;
20
+ if ([dev, ino, mode, uid, gid].some((value) => typeof value !== 'bigint' || value < 0n)) {
21
+ return failure();
22
+ }
23
+ return {
24
+ canonical: root.canonical,
25
+ dev: dev.toString(),
26
+ ino: ino.toString(),
27
+ mode: mode.toString(),
28
+ uid: uid.toString(),
29
+ gid: gid.toString(),
30
+ };
31
+ }
32
+ function directoryIdentity(value) {
33
+ return {
34
+ dev: safeNumber(value.dev),
35
+ ino: safeNumber(value.ino),
36
+ mode: safeNumber(value.mode),
37
+ uid: safeNumber(value.uid),
38
+ };
39
+ }
40
+ function stablePhysical(snapshot, root) {
41
+ return {
42
+ root: rootProjection(root),
43
+ directories: snapshot.directories.map(({ directory, identity: item }) => ({
44
+ directory,
45
+ ...directoryIdentity(item),
46
+ })),
47
+ };
48
+ }
49
+ export function evidenceAuthoritySha256(snapshot, root) {
50
+ const physical = stablePhysical(snapshot, root);
51
+ const artifacts = ['.lock', 'spec.md', 'plan.md', 'tasks.md'].map((name) => {
52
+ const { content, identity: item } = snapshot.artifacts[name];
53
+ return {
54
+ name,
55
+ content,
56
+ identity: { ...directoryIdentity(item), nlink: safeNumber(item.nlink) },
57
+ };
58
+ });
59
+ const preimage = ['planu.evidence-authority.v1', physical.root, physical.directories, artifacts];
60
+ return hash(JSON.stringify(preimage));
61
+ }
62
+ export function checkpointCapability() {
63
+ if (process.platform !== 'darwin' && process.platform !== 'linux') {
64
+ return null;
65
+ }
66
+ const mutationFlags = constants.O_CREAT | constants.O_EXCL | constants.O_APPEND;
67
+ const accessFlags = constants.O_WRONLY | constants.O_RDWR | constants.O_NONBLOCK;
68
+ if (typeof process.getuid !== 'function' ||
69
+ !Number.isSafeInteger(constants.O_NOFOLLOW) ||
70
+ constants.O_NOFOLLOW <= 0 ||
71
+ constants.O_NOFOLLOW > 0x7fffffff ||
72
+ (constants.O_NOFOLLOW & (mutationFlags | accessFlags)) !== 0) {
73
+ return null;
74
+ }
75
+ try {
76
+ const uid = process.getuid();
77
+ return Number.isSafeInteger(uid) && uid >= 0 ? { uid, noFollow: constants.O_NOFOLLOW } : null;
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ export function requireOwnedSnapshot(snapshot, capability) {
84
+ const wrongOwner = Object.values(snapshot.artifacts).some(({ identity }) => identity.uid !== capability.uid);
85
+ if (wrongOwner) {
86
+ throw new CheckpointError('checkpoint_path_unsafe');
87
+ }
88
+ }
89
+ export function checkCapability(capability) {
90
+ const current = checkpointCapability();
91
+ if (current?.uid !== capability.uid || current.noFollow !== capability.noFollow) {
92
+ throw new CheckpointCapabilityError();
93
+ }
94
+ }
95
+ export async function captureInitialCheckpointSnapshot(featDir, root, capability) {
96
+ const directories = await authority.captureDirectories(featDir, root.canonical);
97
+ const initial = await authority
98
+ .readArtifact(authority.lastAuthorityDirectory(directories).directory, '.lock')
99
+ .catch(checkpointInitialLockError);
100
+ await authority.revalidateDirectories(directories).catch(checkpointDirectoryError);
101
+ if (initial.identity.uid !== capability.uid) {
102
+ throw new CheckpointError('checkpoint_path_unsafe');
103
+ }
104
+ if (!isInitialCheckpointLock(initial.content)) {
105
+ throw new CheckpointError('checkpoint_requires_lock');
106
+ }
107
+ const snapshot = await captureCompletionSnapshot(featDir, {
108
+ workspaceRoot: root.canonical,
109
+ }).catch(checkpointRevalidationError);
110
+ requireOwnedSnapshot(snapshot, capability);
111
+ if (initial.content !== snapshot.lockContent ||
112
+ !authority.sameIdentity(initial.identity, snapshot.artifacts['.lock'].identity)) {
113
+ throw new CheckpointError('checkpoint_context_stale');
114
+ }
115
+ return snapshot;
116
+ }
117
+ export async function checkCheckpointDirectories(snapshot) {
118
+ try {
119
+ await authority.revalidateDirectories(snapshot.directories);
120
+ }
121
+ catch {
122
+ throw new CheckpointError('checkpoint_path_unsafe');
123
+ }
124
+ }
125
+ export function journalIdentity(stat) {
126
+ const item = authority.physicalIdentity(stat);
127
+ if (!Number.isFinite(stat.ctimeMs) || !Number.isFinite(stat.birthtimeMs)) {
128
+ return failure();
129
+ }
130
+ return {
131
+ ...directoryIdentity(item),
132
+ nlink: safeNumber(item.nlink),
133
+ ctimeMs: stat.ctimeMs,
134
+ birthtimeMs: stat.birthtimeMs,
135
+ };
136
+ }
137
+ export function sameCheckpointJournalIdentity(left, right) {
138
+ return (authority.sameIdentity(left, right) &&
139
+ left.ctimeMs === right.ctimeMs &&
140
+ left.birthtimeMs === right.birthtimeMs);
141
+ }
142
+ export function checkpointOwned(stat, capability) {
143
+ return (stat.isFile() &&
144
+ stat.nlink === 1 &&
145
+ stat.uid === capability.uid &&
146
+ Number.isSafeInteger(stat.size) &&
147
+ stat.size >= 0);
148
+ }
149
+ export const hash = authority.hashArtifact;
150
+ export function checkpointRecordHash(record) {
151
+ const context = CheckpointRecordSchema.shape.context.parse(record.context);
152
+ const reported = CheckpointRecordSchema.shape.reported.parse(record.reported);
153
+ return hash(JSON.stringify([
154
+ 'planu.evidence-checkpoint.v1',
155
+ record.seq,
156
+ record.recordedAt,
157
+ record.previousSha256,
158
+ context,
159
+ reported,
160
+ ]));
161
+ }
162
+ export function makeRecord(context, input, reference) {
163
+ const seq = (reference?.count ?? 0) + 1;
164
+ if (!Number.isSafeInteger(seq)) {
165
+ throw new CheckpointError('checkpoint_sequence_exhausted');
166
+ }
167
+ const body = {
168
+ version: 1,
169
+ seq,
170
+ recordedAt: new Date().toISOString(),
171
+ previousSha256: reference?.headSha256 ?? null,
172
+ context,
173
+ reported: {
174
+ ...input.reported,
175
+ provenance: 'caller_reported',
176
+ certification: 'none',
177
+ },
178
+ };
179
+ return { ...body, recordSha256: checkpointRecordHash(body) };
180
+ }
181
+ function validateRecord(line, seq, previous) {
182
+ const value = parseCheckpointJournalRecord(line);
183
+ if (value?.seq !== seq ||
184
+ value.previousSha256 !== previous ||
185
+ checkpointRecordHash(value) !== value.recordSha256 ||
186
+ JSON.stringify(value) !== line) {
187
+ throw new CheckpointError('checkpoint_history_invalid');
188
+ }
189
+ return value;
190
+ }
191
+ export async function readChain(handle, length, featureId, collect) {
192
+ const buffer = Buffer.alloc(MAX_LINE);
193
+ const hasher = createHash('sha256');
194
+ let position = 0, count = 0, previous = null, pending = Buffer.alloc(0);
195
+ while (position < length) {
196
+ const size = Math.min(buffer.length, length - position);
197
+ const result = await handle.read(buffer, 0, size, position).catch(checkpointRevalidationError);
198
+ if (!result.bytesRead) {
199
+ throw new CheckpointError('checkpoint_history_invalid');
200
+ }
201
+ const chunk = buffer.subarray(0, result.bytesRead);
202
+ hasher.update(chunk);
203
+ position += result.bytesRead;
204
+ let start = 0;
205
+ for (let i = 0; i < chunk.length; i++) {
206
+ if (chunk[i] !== 10) {
207
+ continue;
208
+ }
209
+ const part = chunk.subarray(start, i + 1);
210
+ if (pending.length + part.length > MAX_LINE) {
211
+ throw new CheckpointError('checkpoint_history_invalid');
212
+ }
213
+ const line = Buffer.concat([pending, part]);
214
+ let decoded;
215
+ try {
216
+ decoded = new TextDecoder('utf-8', {
217
+ fatal: true,
218
+ ignoreBOM: true,
219
+ }).decode(line.subarray(0, -1));
220
+ }
221
+ catch {
222
+ throw new CheckpointError('checkpoint_history_invalid');
223
+ }
224
+ const record = validateRecord(decoded, count + 1, previous);
225
+ if (record.context.featureId !== featureId) {
226
+ throw new CheckpointError('checkpoint_history_invalid');
227
+ }
228
+ count = record.seq;
229
+ previous = record.recordSha256;
230
+ collect?.(record);
231
+ pending = Buffer.alloc(0);
232
+ start = i + 1;
233
+ }
234
+ const rest = chunk.subarray(start);
235
+ if (pending.length + rest.length >= MAX_LINE) {
236
+ throw new CheckpointError('checkpoint_history_invalid');
237
+ }
238
+ pending = Buffer.concat([pending, rest]);
239
+ }
240
+ if (pending.length || !count || !previous) {
241
+ throw new CheckpointError('checkpoint_history_invalid');
242
+ }
243
+ return { count, head: previous, hash: hasher.digest('hex') };
244
+ }
245
+ async function revalidateRoot(root) {
246
+ const current = await captureVerificationRoot(root.canonical);
247
+ if (JSON.stringify(rootProjection(current)) !== JSON.stringify(rootProjection(root))) {
248
+ failure();
249
+ }
250
+ }
251
+ async function openJournal(filename, capability) {
252
+ try {
253
+ return await fs.open(filename, constants.O_RDONLY | capability.noFollow | constants.O_NONBLOCK);
254
+ }
255
+ catch (error) {
256
+ if (checkpointUnsupported(error)) {
257
+ throw new CheckpointCapabilityError();
258
+ }
259
+ return checkpointRevalidationError(error);
260
+ }
261
+ }
262
+ export async function captureJournal(snapshot, root, capability, collect) {
263
+ checkCapability(capability);
264
+ const filename = path.join(snapshot.featDir, JOURNAL);
265
+ let before;
266
+ try {
267
+ before = await fs.lstat(filename);
268
+ }
269
+ catch (error) {
270
+ if (!(error instanceof Error) || error.code !== 'ENOENT') {
271
+ return checkpointRevalidationError(error);
272
+ }
273
+ await checkCheckpointDirectories(snapshot);
274
+ await revalidateRoot(root);
275
+ return { reference: null, identity: null, size: 0, bytesSha256: hash('') };
276
+ }
277
+ if (!checkpointOwned(before, capability)) {
278
+ return failure();
279
+ }
280
+ const handle = await openJournal(filename, capability);
281
+ try {
282
+ const opened = await handle.stat();
283
+ if (!checkpointOwned(opened, capability) ||
284
+ !sameCheckpointJournalIdentity(journalIdentity(before), journalIdentity(opened))) {
285
+ return failure();
286
+ }
287
+ const chain = await readChain(handle, opened.size, path.basename(snapshot.featDir), collect);
288
+ const after = await handle.stat();
289
+ const named = await fs.lstat(filename);
290
+ if (!checkpointOwned(after, capability) ||
291
+ !checkpointOwned(named, capability) ||
292
+ !sameCheckpointJournalIdentity(journalIdentity(opened), journalIdentity(after)) ||
293
+ !sameCheckpointJournalIdentity(journalIdentity(after), journalIdentity(named)) ||
294
+ opened.size !== after.size ||
295
+ after.size !== named.size) {
296
+ return failure();
297
+ }
298
+ await checkCheckpointDirectories(snapshot);
299
+ await revalidateRoot(root);
300
+ const physical = {
301
+ ...stablePhysical(snapshot, root),
302
+ journal: journalIdentity(after),
303
+ };
304
+ const authorityDigest = evidenceAuthoritySha256(snapshot, root);
305
+ const preimage = ['planu.evidence-journal-snapshot.v1', authorityDigest, physical];
306
+ preimage.push(chain.count, chain.head);
307
+ const referenceHash = hash(JSON.stringify(preimage));
308
+ return {
309
+ reference: {
310
+ snapshotSha256: referenceHash,
311
+ headSha256: chain.head,
312
+ count: chain.count,
313
+ },
314
+ identity: journalIdentity(after),
315
+ size: after.size,
316
+ bytesSha256: chain.hash,
317
+ };
318
+ }
319
+ catch (error) {
320
+ return checkpointRevalidationError(error);
321
+ }
322
+ finally {
323
+ await handle.close().catch(checkpointRevalidationError);
324
+ }
325
+ }
326
+ //# sourceMappingURL=evidence-journal.js.map
@@ -1,4 +1,5 @@
1
- import type { ReceiptPolicyResult, ReceiptSealFailure } from '../types/sdd-engine.js';
1
+ import type { ReceiptPolicyResult } from '../types/completion.js';
2
+ import type { ReceiptSealFailure } from '../types/sdd-engine.js';
2
3
  export { assessTrinityCompleteness, parseManifestContent, toPosixPath, } from './trinity-structure.js';
3
4
  export declare function parseVerificationReceiptPolicy(featureId: string, plan: string, taskText: string): ReceiptPolicyResult;
4
5
  export declare function receiptSealFailure(featureId: string, plan: string, tasks: string): ReceiptSealFailure | undefined;
@@ -1,4 +1,6 @@
1
1
  import type { HostSkillDiagnostics } from '../types/sdd-engine.js';
2
+ import type { SetupDiagnostics, SetupHost } from '../types/resume-views.js';
3
+ export declare const MISSING_SDD_HINT = "No .sdd directory in the client project. Call sdd_init_workspace with scope=project. MCP hosts should advertise roots; do not pin PLANU_WORKSPACE globally.";
2
4
  export declare function isStaleV6HostDoc(content: string): boolean;
3
5
  export declare function copyGlobalRules(workspaceRoot: string, force?: boolean): Promise<'preserved' | 'replaced' | 'created'>;
4
6
  export declare function inspectHostSkillPack(workspaceRoot: string): Promise<string | undefined>;
@@ -6,6 +8,8 @@ export declare function inspectHostSkillPackDetailed(workspaceRoot: string, bund
6
8
  hostSkills: HostSkillDiagnostics;
7
9
  hint?: string;
8
10
  }>;
11
+ export declare function inspectSetupDiagnostics(root: string, version: string, selectedHost: SetupHost | 'all', client: unknown): Promise<SetupDiagnostics>;
12
+ export declare function copySkillTemplates(skillsDir: string): Promise<void>;
9
13
  export declare function installHostSkillPack(workspaceRoot: string): Promise<string[]>;
10
14
  export declare function installCursorGuard(workspaceRoot: string): Promise<string[]>;
11
15
  export declare function installHostRulePack(workspaceRoot: string): Promise<string[]>;