@planu/cli 8.3.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +86 -2
  3. package/dist/sdd-engine/contracts.d.ts +13 -3
  4. package/dist/sdd-engine/contracts.js +48 -10
  5. package/dist/sdd-engine/feature-manifest.d.ts +2 -5
  6. package/dist/sdd-engine/feature-manifest.js +109 -184
  7. package/dist/sdd-engine/host-rule-pack.d.ts +5 -0
  8. package/dist/sdd-engine/host-rule-pack.js +106 -43
  9. package/dist/sdd-engine/host-skill-reader.d.ts +6 -0
  10. package/dist/sdd-engine/host-skill-reader.js +187 -0
  11. package/dist/sdd-engine/lock-integrity.d.ts +1 -0
  12. package/dist/sdd-engine/lock-integrity.js +25 -17
  13. package/dist/sdd-engine/receipt-assessment.d.ts +12 -0
  14. package/dist/sdd-engine/receipt-assessment.js +223 -0
  15. package/dist/sdd-engine/resume-history.d.ts +6 -0
  16. package/dist/sdd-engine/resume-history.js +117 -0
  17. package/dist/sdd-engine/resume-views.d.ts +9 -0
  18. package/dist/sdd-engine/resume-views.js +149 -0
  19. package/dist/sdd-engine/server.js +2 -4
  20. package/dist/sdd-engine/task-content.d.ts +18 -0
  21. package/dist/sdd-engine/task-content.js +36 -1
  22. package/dist/sdd-engine/task-window.d.ts +1 -0
  23. package/dist/sdd-engine/task-window.js +8 -1
  24. package/dist/sdd-engine/tools/compact-result.d.ts +6 -0
  25. package/dist/sdd-engine/tools/compact-result.js +66 -0
  26. package/dist/sdd-engine/tools/execution-tools.d.ts +1 -11
  27. package/dist/sdd-engine/tools/execution-tools.js +14 -32
  28. package/dist/sdd-engine/tools/workspace-tools.d.ts +1 -1
  29. package/dist/sdd-engine/tools/workspace-tools.js +17 -9
  30. package/dist/sdd-engine/tools.d.ts +2 -1
  31. package/dist/sdd-engine/tools.js +4 -2
  32. package/dist/sdd-engine/trinity-structure.d.ts +25 -0
  33. package/dist/sdd-engine/trinity-structure.js +317 -0
  34. package/dist/sdd-engine/verification-preflight.d.ts +11 -0
  35. package/dist/sdd-engine/verification-preflight.js +275 -0
  36. package/dist/sdd-engine/verification-receipts.d.ts +2 -10
  37. package/dist/sdd-engine/verification-receipts.js +2 -169
  38. package/dist/sdd-engine/workspace-root.d.ts +1 -0
  39. package/dist/sdd-engine/workspace-root.js +1 -0
  40. package/dist/types/completion.d.ts +9 -2
  41. package/dist/types/resume-views.d.ts +55 -0
  42. package/dist/types/resume-views.js +2 -0
  43. package/dist/types/sdd-engine.d.ts +78 -0
  44. package/package.json +1 -1
  45. package/templates/AGENTS.md +12 -0
  46. package/templates/host/planu-sdd.md +12 -0
@@ -0,0 +1,223 @@
1
+ import { createHash, createPublicKey, verify } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ export const maxVerificationReceipts = 32;
4
+ export const gateIdPattern = /^[a-z][a-z0-9-]{0,31}$/u;
5
+ export const taskIdPattern = /^TASK-[1-9][0-9]{0,18}$/u;
6
+ export const featureIdPattern = /^FEAT[-_][A-Z0-9_-]{1,123}$/u;
7
+ export const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/u);
8
+ function decodeCanonicalBase64Url(value) {
9
+ if (!/^[A-Za-z0-9_-]+$/u.test(value)) {
10
+ return undefined;
11
+ }
12
+ const decoded = Buffer.from(value, 'base64url');
13
+ return decoded.toString('base64url') === value ? decoded : undefined;
14
+ }
15
+ export function importReceiptPublicKey(value) {
16
+ const der = value.length <= 128 ? decodeCanonicalBase64Url(value) : undefined;
17
+ if (!der) {
18
+ return undefined;
19
+ }
20
+ try {
21
+ const key = createPublicKey({ key: der, format: 'der', type: 'spki' });
22
+ if (key.asymmetricKeyType !== 'ed25519') {
23
+ return undefined;
24
+ }
25
+ return key.export({ format: 'der', type: 'spki' }).equals(der) ? key : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ const receiptSchema = z.strictObject({
32
+ version: z.literal(1),
33
+ featureId: z.string().regex(featureIdPattern),
34
+ taskId: z.string().regex(taskIdPattern),
35
+ workspaceSha256: sha256Schema,
36
+ lockSha256: sha256Schema,
37
+ candidateSha256: sha256Schema,
38
+ observedSha256: sha256Schema,
39
+ gateId: z.string().regex(gateIdPattern),
40
+ procedureSha256: sha256Schema,
41
+ environmentSha256: sha256Schema,
42
+ outcome: z.enum(['pass', 'fail', 'skipped', 'partial']),
43
+ evidenceSha256: sha256Schema,
44
+ signature: z.string().regex(/^[A-Za-z0-9_-]{86}$/u),
45
+ });
46
+ const RECEIPT_KEY_COUNT = Object.keys(receiptSchema.shape).length;
47
+ function receiptMessage(receipt) {
48
+ return [
49
+ 'planu.verification-receipt.v1',
50
+ receipt.featureId,
51
+ receipt.taskId,
52
+ receipt.workspaceSha256,
53
+ receipt.lockSha256,
54
+ receipt.candidateSha256,
55
+ receipt.observedSha256,
56
+ receipt.gateId,
57
+ receipt.procedureSha256,
58
+ receipt.environmentSha256,
59
+ receipt.outcome,
60
+ receipt.evidenceSha256,
61
+ ];
62
+ }
63
+ function decodeReceipt(input) {
64
+ if (typeof input !== 'object' ||
65
+ input === null ||
66
+ Object.keys(input).length !== RECEIPT_KEY_COUNT) {
67
+ return undefined;
68
+ }
69
+ const parsed = receiptSchema.safeParse(input);
70
+ if (!parsed.success) {
71
+ return undefined;
72
+ }
73
+ const signature = decodeCanonicalBase64Url(parsed.data.signature);
74
+ if (signature?.length !== 64) {
75
+ return undefined;
76
+ }
77
+ return {
78
+ receipt: parsed.data,
79
+ message: receiptMessage(parsed.data),
80
+ signature,
81
+ };
82
+ }
83
+ function matchCoverage(signed, gates) {
84
+ const required = new Set(gates.map((gate) => gate.id));
85
+ const byGate = new Map();
86
+ for (const entry of signed) {
87
+ const gateId = entry.receipt.gateId;
88
+ if (!required.has(gateId)) {
89
+ return { ok: false, reason: 'receipt_unexpected' };
90
+ }
91
+ if (byGate.has(gateId)) {
92
+ return { ok: false, reason: 'receipt_duplicate', gateId };
93
+ }
94
+ byGate.set(gateId, entry);
95
+ }
96
+ const matched = [];
97
+ for (const gate of gates) {
98
+ const entry = byGate.get(gate.id);
99
+ if (!entry) {
100
+ return { ok: false, reason: 'receipt_missing', gateId: gate.id };
101
+ }
102
+ matched.push({ ...entry, gate });
103
+ }
104
+ return { ok: true, matched };
105
+ }
106
+ function validateClaims(matched, challenge) {
107
+ const checks = [
108
+ [
109
+ (receipt) => receipt.workspaceSha256 === challenge.workspaceSha256 &&
110
+ receipt.featureId === challenge.featureId &&
111
+ receipt.taskId === challenge.taskId &&
112
+ receipt.lockSha256 === challenge.lockSha256,
113
+ 'receipt_context_mismatch',
114
+ ],
115
+ [
116
+ (receipt) => receipt.candidateSha256 === challenge.candidateSha256,
117
+ 'receipt_candidate_mismatch',
118
+ ],
119
+ [(receipt) => receipt.observedSha256 === challenge.observedSha256, 'receipt_observed_mismatch'],
120
+ [
121
+ (receipt, gate) => receipt.procedureSha256 === gate.procedureSha256,
122
+ 'receipt_procedure_mismatch',
123
+ ],
124
+ [
125
+ (receipt, gate) => receipt.environmentSha256 === gate.environmentSha256,
126
+ 'receipt_environment_mismatch',
127
+ ],
128
+ [(receipt) => receipt.outcome === 'pass', 'receipt_non_pass'],
129
+ ];
130
+ for (const [accepts, reason] of checks) {
131
+ const failed = matched.find(({ receipt, gate }) => !accepts(receipt, gate));
132
+ if (failed) {
133
+ return { ok: false, reason, gateId: failed.gate.id };
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+ function validateReceiptSet(input, challenge, publicKey) {
139
+ const gates = [...challenge.gates].sort((left, right) => left.id < right.id ? -1 : left.id === right.id ? 0 : 1);
140
+ if (input === undefined) {
141
+ const gateId = gates[0]?.id;
142
+ return {
143
+ ok: false,
144
+ reason: 'receipt_missing',
145
+ ...(gateId ? { gateId } : {}),
146
+ };
147
+ }
148
+ if (!Array.isArray(input) || input.length < 1 || input.length > maxVerificationReceipts) {
149
+ return { ok: false, reason: 'receipt_malformed' };
150
+ }
151
+ const signed = [];
152
+ for (const raw of input) {
153
+ const receipt = decodeReceipt(raw);
154
+ if (!receipt) {
155
+ return { ok: false, reason: 'receipt_malformed' };
156
+ }
157
+ signed.push(receipt);
158
+ }
159
+ const coverage = matchCoverage(signed, gates);
160
+ if (!coverage.ok) {
161
+ return coverage;
162
+ }
163
+ for (const { receipt, message, signature } of coverage.matched) {
164
+ if (!verify(null, Buffer.from(JSON.stringify(message), 'utf8'), publicKey, signature)) {
165
+ return {
166
+ ok: false,
167
+ reason: 'receipt_invalid_signature',
168
+ gateId: receipt.gateId,
169
+ };
170
+ }
171
+ }
172
+ const rejected = validateClaims(coverage.matched, challenge);
173
+ if (rejected) {
174
+ return rejected;
175
+ }
176
+ const entries = coverage.matched.map(({ message, receipt }) => [message, receipt.signature]);
177
+ const receiptSetSha256 = createHash('sha256')
178
+ .update(JSON.stringify(['planu.verification-receipt-set.v1', entries]), 'utf8')
179
+ .digest('hex');
180
+ return { ok: true, gateCount: entries.length, receiptSetSha256 };
181
+ }
182
+ export function assessVerificationReceiptSet(input, challenge, publicKey) {
183
+ const result = validateReceiptSet(input, challenge, publicKey);
184
+ const gates = [...challenge.gates]
185
+ .sort((left, right) => (left.id < right.id ? -1 : left.id === right.id ? 0 : 1))
186
+ .slice(0, maxVerificationReceipts)
187
+ .map((gate) => {
188
+ const subset = Array.isArray(input) && input.length >= 1 && input.length <= maxVerificationReceipts
189
+ ? input.filter((entry) => typeof entry === 'object' &&
190
+ entry !== null &&
191
+ 'gateId' in entry &&
192
+ entry.gateId === gate.id)
193
+ : input;
194
+ const selected = Array.isArray(input) && input.length >= 1 && Array.isArray(subset) && subset.length === 0
195
+ ? undefined
196
+ : subset;
197
+ const checked = validateReceiptSet(selected, { ...challenge, gates: [gate] }, publicKey);
198
+ if (checked.ok) {
199
+ return { gateId: gate.id, state: 'receipt_valid' };
200
+ }
201
+ return {
202
+ gateId: gate.id,
203
+ state: checked.reason === 'receipt_missing' ? 'receipt_missing' : 'receipt_rejected',
204
+ reason: checked.reason,
205
+ };
206
+ });
207
+ const reasons = new Set();
208
+ if (!result.ok && !gates.some((gate) => gate.reason === result.reason)) {
209
+ reasons.add(result.reason);
210
+ }
211
+ return {
212
+ result,
213
+ gates,
214
+ blockers: [...reasons]
215
+ .sort()
216
+ .slice(0, 16)
217
+ .map((reason) => ({ reason })),
218
+ };
219
+ }
220
+ export function validateVerificationReceiptSet(input, challenge, publicKey) {
221
+ return validateReceiptSet(input, challenge, publicKey);
222
+ }
223
+ //# sourceMappingURL=receipt-assessment.js.map
@@ -0,0 +1,6 @@
1
+ import type { RelockHistoryPage } from '../types/resume-views.js';
2
+ import type { RelockHistoryCursor, SddResult } from '../types/sdd-engine.js';
3
+ export declare function getRelockHistory(tasksPath: string, workspaceRoot: string, cursor?: RelockHistoryCursor, signal?: AbortSignal): Promise<SddResult<{
4
+ relockHistory: RelockHistoryPage;
5
+ }>>;
6
+ //# sourceMappingURL=resume-history.d.ts.map
@@ -0,0 +1,117 @@
1
+ import * as path from 'node:path';
2
+ import { CompletionGuardError, hashArtifact } from './feature-authority.js';
3
+ import { captureVerificationRoot } from './verification-inputs.js';
4
+ import { assertGuardAbsent, captureReadSnapshot, revalidateReadSnapshot, } from './verification-preflight.js';
5
+ import { compactFailure, compactReadError } from './tools/compact-result.js';
6
+ const hashPattern = /^[a-f0-9]{64}$/u;
7
+ class InvalidHistoryError extends Error {
8
+ }
9
+ function historyRecords(lockContent) {
10
+ const raw = JSON.parse(lockContent);
11
+ const history = raw.relockHistory;
12
+ if (history !== undefined && !Array.isArray(history)) {
13
+ throw new InvalidHistoryError();
14
+ }
15
+ return Array.isArray(history) ? history : [];
16
+ }
17
+ function validTimestamp(value) {
18
+ return (typeof value === 'string' &&
19
+ value.length <= 27 &&
20
+ Number.isFinite(Date.parse(value)) &&
21
+ new Date(value).toISOString() === value);
22
+ }
23
+ function cursorFailure(cursor, count, digest) {
24
+ if (!cursor) {
25
+ return undefined;
26
+ }
27
+ if (!Number.isSafeInteger(cursor.startIndex) ||
28
+ cursor.startIndex < 0 ||
29
+ !hashPattern.test(cursor.snapshotSha256) ||
30
+ count === 0) {
31
+ return compactFailure('history_cursor_invalid', 'ERR_INVALID_SLICE');
32
+ }
33
+ if (cursor.snapshotSha256 !== digest) {
34
+ return compactFailure('history_cursor_stale', 'ERR_INVALID_SLICE');
35
+ }
36
+ return cursor.startIndex >= count
37
+ ? compactFailure('history_cursor_invalid', 'ERR_INVALID_SLICE')
38
+ : undefined;
39
+ }
40
+ function projectRecord(record, index) {
41
+ if (typeof record !== 'object' || record === null || Array.isArray(record)) {
42
+ throw new InvalidHistoryError();
43
+ }
44
+ const fields = record;
45
+ const { lockedAt, specHash, planHash, tasksHash, reason } = fields;
46
+ if (!validTimestamp(lockedAt) ||
47
+ typeof specHash !== 'string' ||
48
+ !hashPattern.test(specHash) ||
49
+ typeof planHash !== 'string' ||
50
+ !hashPattern.test(planHash) ||
51
+ (tasksHash !== undefined && (typeof tasksHash !== 'string' || !hashPattern.test(tasksHash))) ||
52
+ typeof reason !== 'string') {
53
+ throw new InvalidHistoryError();
54
+ }
55
+ return {
56
+ index,
57
+ lockedAt,
58
+ specHash,
59
+ planHash,
60
+ ...(typeof tasksHash === 'string' ? { tasksHash } : {}),
61
+ // Complete parsed record: ECMAScript JSON normalization, including extra fields.
62
+ recordSha256: hashArtifact(JSON.stringify(record)),
63
+ // Node UTF-8 encoding intentionally normalizes lone surrogates to U+FFFD.
64
+ reasonSha256: hashArtifact(reason),
65
+ };
66
+ }
67
+ function selectPage(history, startIndex) {
68
+ const records = [];
69
+ for (let index = startIndex; index >= Math.max(0, startIndex - 7); index--) {
70
+ records.push(projectRecord(history[index], index));
71
+ }
72
+ return records;
73
+ }
74
+ function assertReadActive(signal) {
75
+ if (signal?.aborted) {
76
+ throw new CompletionGuardError('cancelled', 'Compact read was cancelled.');
77
+ }
78
+ }
79
+ export async function getRelockHistory(tasksPath, workspaceRoot, cursor, signal) {
80
+ try {
81
+ assertReadActive(signal);
82
+ const root = await captureVerificationRoot(workspaceRoot);
83
+ const snapshot = await captureReadSnapshot(path.dirname(tasksPath), root);
84
+ await assertGuardAbsent(snapshot.feature);
85
+ if (!snapshot.locked) {
86
+ await revalidateReadSnapshot(snapshot, root, workspaceRoot);
87
+ assertReadActive(signal);
88
+ return compactFailure('unlocked', 'ERR_SPEC_NOT_LOCKED');
89
+ }
90
+ const locked = snapshot.locked;
91
+ const history = historyRecords(locked.lockContent);
92
+ const startIndex = cursor?.startIndex ?? history.length - 1;
93
+ const invalid = cursorFailure(cursor, history.length, locked.digest);
94
+ if (invalid) {
95
+ return invalid;
96
+ }
97
+ const records = history.length ? selectPage(history, startIndex) : [];
98
+ const relockHistory = {
99
+ version: 1,
100
+ featureId: path.basename(snapshot.feature),
101
+ lockSha256: hashArtifact(locked.lockContent),
102
+ count: history.length,
103
+ records,
104
+ nextCursor: startIndex >= 8 ? { snapshotSha256: locked.digest, startIndex: startIndex - 8 } : null,
105
+ };
106
+ assertReadActive(signal);
107
+ await revalidateReadSnapshot(snapshot, root, workspaceRoot);
108
+ assertReadActive(signal);
109
+ return { success: true, data: { relockHistory } };
110
+ }
111
+ catch (error) {
112
+ return error instanceof InvalidHistoryError
113
+ ? compactFailure('history_invalid')
114
+ : compactReadError(error);
115
+ }
116
+ }
117
+ //# sourceMappingURL=resume-history.js.map
@@ -0,0 +1,9 @@
1
+ import type { ResumeCheckpoint } from '../types/resume-views.js';
2
+ import type { SddResult, SddWorkspaceHandle } from '../types/sdd-engine.js';
3
+ import type { ScopedPolicy, VerificationPolicy } from '../types/verification.js';
4
+ import { formatCompactResult } from './tools/compact-result.js';
5
+ export declare function getResumeCheckpoint(tasksPath: string, workspaceRoot: string, extractCommand: (markdown: string) => string | null, receipts?: unknown, scopedPolicy?: ScopedPolicy, signal?: AbortSignal): Promise<SddResult<{
6
+ resume: ResumeCheckpoint;
7
+ }>>;
8
+ export declare function getResumeToolResult(rawArgs: unknown, workspace: SddWorkspaceHandle, policy?: VerificationPolicy, signal?: AbortSignal): Promise<ReturnType<typeof formatCompactResult>>;
9
+ //# sourceMappingURL=resume-views.d.ts.map
@@ -0,0 +1,149 @@
1
+ import * as path from 'node:path';
2
+ import { getRelockHistory } from './resume-history.js';
3
+ import { GetActiveTaskInputSchema } from './contracts.js';
4
+ import { verificationCommand } from './task-window.js';
5
+ import { homeFallbackFailure } from './workspace-root.js';
6
+ import { CompletionGuardError, hashArtifact } from './feature-authority.js';
7
+ import { summarizeTaskContent } from './task-content.js';
8
+ import { captureVerificationRoot } from './verification-inputs.js';
9
+ import { assertGuardAbsent, assessVerificationPreflight, captureReadSnapshot, revalidateReadSnapshot, } from './verification-preflight.js';
10
+ import { compactFailure, compactReadError, formatCompactResult } from './tools/compact-result.js';
11
+ class InvalidResumeHistoryError extends Error {
12
+ }
13
+ function contractReference(snapshot) {
14
+ const locked = snapshot.locked;
15
+ return locked
16
+ ? {
17
+ specSha256: hashArtifact(locked.specContent),
18
+ planSha256: hashArtifact(locked.planContent),
19
+ tasksSha256: hashArtifact(locked.tasksContent),
20
+ lockSha256: hashArtifact(locked.lockContent),
21
+ }
22
+ : null;
23
+ }
24
+ function historyReference(snapshot) {
25
+ const locked = snapshot.locked;
26
+ if (!locked) {
27
+ return null;
28
+ }
29
+ const raw = JSON.parse(locked.lockContent);
30
+ const history = raw.relockHistory;
31
+ if (history !== undefined && !Array.isArray(history)) {
32
+ throw new InvalidResumeHistoryError();
33
+ }
34
+ const count = Array.isArray(history) ? history.length : 0;
35
+ return {
36
+ count,
37
+ lockSha256: hashArtifact(locked.lockContent),
38
+ firstCursor: count ? { snapshotSha256: locked.digest, startIndex: count - 1 } : null,
39
+ };
40
+ }
41
+ function checkpoint(snapshot, summary, assessment) {
42
+ const presentation = checkpointPresentation(snapshot, summary, assessment);
43
+ const evidence = assessment?.evidence;
44
+ return {
45
+ version: 1,
46
+ featureId: path.basename(snapshot.feature),
47
+ progress: summary.progress,
48
+ ...presentation,
49
+ contract: contractReference(snapshot),
50
+ candidate: evidence
51
+ ? {
52
+ workspaceSha256: evidence.workspaceSha256,
53
+ candidateSha256: evidence.candidateSha256,
54
+ observedSha256: evidence.observedSha256,
55
+ }
56
+ : null,
57
+ gates: assessment?.preflight.gates ?? [],
58
+ history: historyReference(snapshot),
59
+ };
60
+ }
61
+ function checkpointStatus(snapshot, summary) {
62
+ if (!snapshot.locked) {
63
+ return 'unlocked';
64
+ }
65
+ if (!summary.progress.total) {
66
+ return 'no_tasks';
67
+ }
68
+ return summary.current.success && summary.current.data.activeTask ? 'active' : 'complete';
69
+ }
70
+ function checkpointPresentation(snapshot, summary, assessment) {
71
+ const status = checkpointStatus(snapshot, summary);
72
+ const active = summary.current.success ? summary.current.data.activeTask : null;
73
+ if (status === 'active' && active && assessment) {
74
+ return {
75
+ status,
76
+ task: { id: active.taskId, index: active.taskIndex },
77
+ readiness: assessment.preflight.status,
78
+ integration: 'pending',
79
+ blockers: assessment.preflight.blockers,
80
+ nextAction: assessment.preflight.nextAction,
81
+ };
82
+ }
83
+ return {
84
+ status,
85
+ task: null,
86
+ readiness: status === 'unlocked' ? 'blocked' : 'not_applicable',
87
+ integration: 'not_applicable',
88
+ blockers: status === 'unlocked' ? [{ reason: 'unlocked' }] : [],
89
+ nextAction: status === 'unlocked' ? 'review_lock' : status === 'no_tasks' ? 'inspect_tasks' : 'none',
90
+ };
91
+ }
92
+ function validIdentifier(id) {
93
+ return id.length <= 128 && /^[A-Z0-9_-]+$/u.test(id);
94
+ }
95
+ export async function getResumeCheckpoint(tasksPath, workspaceRoot, extractCommand, receipts, scopedPolicy, signal) {
96
+ try {
97
+ const root = await captureVerificationRoot(workspaceRoot);
98
+ const snapshot = await captureReadSnapshot(path.dirname(tasksPath), root);
99
+ await assertGuardAbsent(snapshot.feature);
100
+ const summary = summarizeTaskContent(snapshot.artifacts['tasks.md']?.content ?? '', extractCommand);
101
+ const active = summary.current.success ? summary.current.data.activeTask : null;
102
+ if (!validIdentifier(path.basename(snapshot.feature)) ||
103
+ (active && !validIdentifier(active.taskId))) {
104
+ return compactFailure('compact_identifier_invalid');
105
+ }
106
+ const assessment = snapshot.locked && active
107
+ ? await assessVerificationPreflight(snapshot.locked, root, workspaceRoot, active, receipts, scopedPolicy, signal)
108
+ : undefined;
109
+ const resume = checkpoint(snapshot, summary, assessment);
110
+ if (signal?.aborted) {
111
+ throw new CompletionGuardError('cancelled', 'Compact read was cancelled.');
112
+ }
113
+ await revalidateReadSnapshot(snapshot, root, workspaceRoot);
114
+ if (signal?.aborted) {
115
+ return compactFailure('cancelled', 'ERR_VERIFICATION_FAILED');
116
+ }
117
+ return { success: true, data: { resume } };
118
+ }
119
+ catch (error) {
120
+ return error instanceof InvalidResumeHistoryError
121
+ ? compactFailure('history_invalid')
122
+ : compactReadError(error);
123
+ }
124
+ }
125
+ export async function getResumeToolResult(rawArgs, workspace, policy, signal) {
126
+ try {
127
+ const parsed = GetActiveTaskInputSchema.safeParse(rawArgs);
128
+ if (!parsed.success) {
129
+ return formatCompactResult(compactFailure('compact_input_invalid'));
130
+ }
131
+ const args = parsed.data;
132
+ if (!validIdentifier(args.feature_id)) {
133
+ return formatCompactResult(compactFailure('compact_identifier_invalid'));
134
+ }
135
+ const resolved = await workspace.resolve();
136
+ if (homeFallbackFailure(resolved, 'sdd_get_active_task')) {
137
+ return formatCompactResult(compactFailure('workspace_unresolved', 'ERR_WORKSPACE_UNRESOLVED'));
138
+ }
139
+ const tasksPath = path.join(resolved.sddDir, 'features', args.feature_id, 'tasks.md');
140
+ if (args.view === 'relock_history') {
141
+ return formatCompactResult(await getRelockHistory(tasksPath, resolved.workspaceRoot, args.history_cursor, signal));
142
+ }
143
+ return formatCompactResult(await getResumeCheckpoint(tasksPath, resolved.workspaceRoot, verificationCommand, args.verification_receipts, policy?.mode === 'scoped' ? policy : undefined, signal));
144
+ }
145
+ catch (error) {
146
+ return formatCompactResult(compactReadError(error));
147
+ }
148
+ }
149
+ //# sourceMappingURL=resume-views.js.map
@@ -1,9 +1,7 @@
1
- import { readFileSync } from 'node:fs';
2
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
3
  import { captureVerificationPolicy, resolveVerificationPolicy } from './verification-policy.js';
5
- import { registerUltralightSddTools } from './tools.js';
6
- const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
4
+ import { bundledPackageVersion as version, registerUltralightSddTools } from './tools.js';
7
5
  export function createUltralightSddServer(workspaceRoot, options) {
8
6
  const policy = resolveVerificationPolicy(options?.verificationPolicy, workspaceRoot);
9
7
  const server = new McpServer({ name: 'sdd-engine', version }, {
@@ -11,7 +9,7 @@ export function createUltralightSddServer(workspaceRoot, options) {
11
9
  instructions: 'First use: call sdd_list_features. If setup is missing or unverified, call sdd_init_workspace(scope=project) only for the identified project and requested setup. Then use sdd_read_file_slice to read .agents/skills/planu-preflight-guardian/SKILL.md and the matching role. Keep one active task, the locked File Manifest and all nine tools. Installed files do not prove a host catalog reload; explain client-dependent discovery and never initialize on connect.',
12
10
  });
13
11
  const pinnedRoot = policy.mode === 'scoped' ? policy.workspaceRoot : workspaceRoot;
14
- const tasks = registerUltralightSddTools(server, pinnedRoot, policy);
12
+ const tasks = registerUltralightSddTools(server, pinnedRoot, policy, version);
15
13
  {
16
14
  const close = server.close.bind(server);
17
15
  server.close = async () => {
@@ -1,5 +1,12 @@
1
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 summarizeTaskContent(content: string, extractCommand: (markdown: string) => string | null): {
4
+ current: SddResult<ActiveTaskResult>;
5
+ progress: {
6
+ total: number;
7
+ completed: number;
8
+ };
9
+ };
3
10
  export declare function taskBlocks(content: string): TaskBlock[];
4
11
  export declare function markTaskVerified(lines: string[], taskId: string, cleanOutput: string): string[] | null;
5
12
  export declare function markReceiptTaskVerified(content: string, lineIndex: number, summary: string): string | undefined;
@@ -12,4 +19,15 @@ export declare function hasReceiptDirective(line: string): boolean;
12
19
  export declare function receiptCommand(block: TaskBlock): string | undefined;
13
20
  export declare function countTaskIds(blocks: readonly TaskBlock[]): Map<string, number>;
14
21
  export declare function dueTaskOrdinals(blocks: readonly TaskBlock[], counts: ReadonlyMap<string, number>): Map<string, number>;
22
+ export declare function sliceNumberedSource(fileData: string, startLine: number, endLine: number): {
23
+ ok: true;
24
+ totalLines: number;
25
+ startLine: number;
26
+ endLine: number;
27
+ truncated: boolean;
28
+ text: string;
29
+ } | {
30
+ ok: false;
31
+ totalLines: number;
32
+ };
15
33
  //# sourceMappingURL=task-content.d.ts.map
@@ -1,6 +1,13 @@
1
1
  const UNLOCKED_CARD = { locked: false, trinity: 'unlocked', manifest: [] };
2
2
  export function activeTaskFromContent(content, extractCommand) {
3
- return buildActiveTaskResult(parseTasks(content.split('\n')), extractCommand);
3
+ return summarizeTaskContent(content, extractCommand).current;
4
+ }
5
+ export function summarizeTaskContent(content, extractCommand) {
6
+ const acc = parseTasks(content.split('\n'));
7
+ return {
8
+ current: buildActiveTaskResult(acc, extractCommand),
9
+ progress: { total: acc.totalTasks, completed: acc.completedTasks },
10
+ };
4
11
  }
5
12
  function buildActiveTaskResult(acc, extractCommand) {
6
13
  if (acc.totalTasks === 0) {
@@ -226,4 +233,32 @@ export function dueTaskOrdinals(blocks, counts) {
226
233
  }
227
234
  return due;
228
235
  }
236
+ const SLICE_LINE_CAP = 200;
237
+ function sourceLines(fileData) {
238
+ if (fileData.length === 0) {
239
+ return [];
240
+ }
241
+ const parts = fileData.split('\n');
242
+ if (fileData.endsWith('\n')) {
243
+ parts.pop();
244
+ }
245
+ return parts;
246
+ }
247
+ export function sliceNumberedSource(fileData, startLine, endLine) {
248
+ const lines = sourceLines(fileData);
249
+ if (startLine > lines.length) {
250
+ return { ok: false, totalLines: lines.length };
251
+ }
252
+ const requestedEnd = Math.min(endLine, lines.length);
253
+ const cappedEnd = Math.min(requestedEnd, startLine + SLICE_LINE_CAP - 1);
254
+ const slice = lines.slice(startLine - 1, cappedEnd);
255
+ return {
256
+ ok: true,
257
+ totalLines: lines.length,
258
+ startLine,
259
+ endLine: cappedEnd,
260
+ truncated: cappedEnd < requestedEnd,
261
+ text: slice.map((content, index) => `${startLine + index}: ${content}`).join('\n'),
262
+ };
263
+ }
229
264
  //# sourceMappingURL=task-content.js.map
@@ -10,6 +10,7 @@ export declare class TaskWindowManager {
10
10
  private activeTaskFromContent;
11
11
  private selectScopedTask;
12
12
  getActiveTask(tasksFilePath: string): Promise<SddResult<ActiveTaskResult>>;
13
+ getVerificationPreflight(tasksPath: string, workspaceRoot: string, receipts?: unknown, signal?: AbortSignal): Promise<SddResult<ActiveTaskResult>>;
13
14
  getCatalogueEntry(featDir: string): Promise<SddResult<FeatureSummary>>;
14
15
  completeTask(tasksFilePath: string, taskId: string, workspaceRoot: string, _verificationOutput: string, signal?: AbortSignal, receipts?: unknown): Promise<SddResult<CompleteTaskResult>>;
15
16
  private completeOwned;
@@ -1,6 +1,7 @@
1
1
  import * as path from 'node:path';
2
2
  import { ScopedVerificationCoordinator, runScopedVerification } from './verification-runner.js';
3
3
  import { isScopedVerificationFeature, persistScopedCompletionFiles, scopedFeaturePathFailure, } from './verification-policy.js';
4
+ import { getVerificationPreflight } from './verification-preflight.js';
4
5
  import { executionCard } from './lock-integrity.js';
5
6
  import { parseVerificationReceiptPolicy } from './feature-manifest.js';
6
7
  import { completeReceiptTask } from './verification-receipts.js';
@@ -75,6 +76,9 @@ export class TaskWindowManager {
75
76
  return completionError(error, 'sdd_get_active_task');
76
77
  }
77
78
  }
79
+ async getVerificationPreflight(tasksPath, workspaceRoot, receipts, signal) {
80
+ return getVerificationPreflight(tasksPath, workspaceRoot, verificationCommand, receipts, this.scopedPolicy, signal);
81
+ }
78
82
  async getCatalogueEntry(featDir) {
79
83
  const id = path.basename(featDir);
80
84
  try {
@@ -106,7 +110,10 @@ export class TaskWindowManager {
106
110
  if (pathFailure) {
107
111
  return pathFailure;
108
112
  }
109
- const lease = await acquireCompletionLease(feature, { operation: 'complete', workspaceRoot });
113
+ const lease = await acquireCompletionLease(feature, {
114
+ operation: 'complete',
115
+ workspaceRoot,
116
+ });
110
117
  try {
111
118
  const snapshot = await captureCompletionSnapshot(feature, {
112
119
  writable: true,
@@ -0,0 +1,6 @@
1
+ import type { ErrorCode, SddResult, ToolResult } from '../../types/sdd-engine.js';
2
+ import type { CompactFailureReason } from '../../types/resume-views.js';
3
+ export declare function compactFailure(reason: CompactFailureReason, code?: ErrorCode): SddResult<never>;
4
+ export declare function compactReadError(error: unknown): SddResult<never>;
5
+ export declare function formatCompactResult<T>(result: SddResult<T>): ToolResult;
6
+ //# sourceMappingURL=compact-result.d.ts.map