@haaaiawd/skeinn 2.4.0 → 2.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.
package/cli/src/store.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  evalConditionPrompt,
26
26
  evalJudgePrompt,
27
27
  evalProbeChecklist,
28
+ checkpointProtocol,
28
29
  evalRelayBatonPrompt,
29
30
  keeperProtocol,
30
31
  shapingContext,
@@ -177,9 +178,171 @@ export function loadProject(root = findRoot()) {
177
178
  validateState(state);
178
179
  validateTasks(taskStore.tasks);
179
180
  ensureClarify(state);
181
+ ensureKeeperState(state);
180
182
  return { paths, state, taskStore, deliverableStore };
181
183
  }
182
184
 
185
+
186
+ function ensureKeeperState(state) {
187
+ if (!state.keeper || typeof state.keeper !== 'object') state.keeper = { status: 'not_run', attempts: [] };
188
+ if (!Array.isArray(state.keeper.attempts)) state.keeper.attempts = [];
189
+ if (!Array.isArray(state.keeper.findings)) state.keeper.findings = [];
190
+ if (!Array.isArray(state.keeper.checkpoints)) state.keeper.checkpoints = [];
191
+ if (!state.keeper.reviewed_digests || typeof state.keeper.reviewed_digests !== 'object') state.keeper.reviewed_digests = {};
192
+ if (typeof state.keeper.launch_completed !== 'boolean') state.keeper.launch_completed = ['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status);
193
+ return state.keeper;
194
+ }
195
+
196
+ function sha256Text(text) {
197
+ return createHash('sha256').update(text).digest('hex');
198
+ }
199
+
200
+ export function artifactDigests(paths, tasks, state = null) {
201
+ const map = {};
202
+ map['.skeinn/PROJECT.md'] = sha256Text(readFileSync(paths.project, 'utf8'));
203
+ if (existsSync(paths.structure)) map['.skeinn/STRUCTURE.md'] = sha256Text(readFileSync(paths.structure, 'utf8'));
204
+ map['.skeinn/DECISIONS.md'] = sha256Text(readFileSync(paths.decisions, 'utf8'));
205
+ if (state?.capability_exemption) map['state:capability_exemption'] = sha256Text(JSON.stringify(state.capability_exemption));
206
+ for (const name of readdirSync(paths.design).filter((file) => file.endsWith('.md')).sort()) {
207
+ map[`.skeinn/design/${name}`] = sha256Text(readFileSync(join(paths.design, name), 'utf8'));
208
+ }
209
+ for (const name of listCapabilities(paths.root)) {
210
+ const capFile = capabilityPath(paths, name);
211
+ const ref = normalizeRef(paths, capFile);
212
+ const statusPath = join(paths.capabilities, name, 'status.json');
213
+ const combined = readFileSync(capFile, 'utf8') + (existsSync(statusPath) ? readFileSync(statusPath, 'utf8') : '');
214
+ map[ref] = sha256Text(combined);
215
+ }
216
+ for (const task of tasks) {
217
+ const { progress, evidence, status, updated_at, completed_at, reopened_at, block, ...definition } = task;
218
+ map[`task:${task.id}`] = sha256Text(JSON.stringify(definition));
219
+ }
220
+ return map;
221
+ }
222
+
223
+ function overallDigest(digestMap) {
224
+ const hash = createHash('sha256');
225
+ for (const key of Object.keys(digestMap).sort()) hash.update(`${key}:${digestMap[key]}
226
+ `);
227
+ return hash.digest('hex');
228
+ }
229
+
230
+ export function activeHorizon(tasks, paths, depth = 2) {
231
+ const done = new Set(tasks.filter((t) => t.status === 'done').map((t) => t.id));
232
+ const byId = new Map(tasks.map((t) => [t.id, t]));
233
+ const selected = new Set();
234
+ let frontier = tasks
235
+ .filter((t) => t.status === 'active' || (t.status === 'open' && t.depends_on.every((d) => done.has(d))))
236
+ .map((t) => t.id);
237
+ for (const id of frontier) selected.add(id);
238
+ for (let hop = 0; hop < depth; hop += 1) {
239
+ const nextLayer = [];
240
+ for (const t of tasks) {
241
+ if (selected.has(t.id) || t.status !== 'open') continue;
242
+ if (t.depends_on.some((d) => selected.has(d)) && t.depends_on.every((d) => done.has(d) || selected.has(d))) {
243
+ nextLayer.push(t.id);
244
+ }
245
+ }
246
+ if (!nextLayer.length) break;
247
+ for (const id of nextLayer) selected.add(id);
248
+ }
249
+ const artifacts = new Set(['.skeinn/PROJECT.md', '.skeinn/DECISIONS.md']);
250
+ if (existsSync(paths.structure)) artifacts.add('.skeinn/STRUCTURE.md');
251
+ let sawCapability = false;
252
+ for (const id of selected) {
253
+ const t = byId.get(id);
254
+ if (!t) continue;
255
+ artifacts.add(`task:${t.id}`);
256
+ for (const ref of t.reads || []) {
257
+ const norm = ref.replaceAll('\\', '/');
258
+ if (norm.startsWith('.skeinn/')) artifacts.add(norm);
259
+ if (norm.startsWith('.skeinn/capabilities/')) sawCapability = true;
260
+ }
261
+ if (t.implements?.trim()) {
262
+ const ref = t.implements.trim().split('#')[0].replaceAll('\\', '/');
263
+ if (ref.startsWith('.skeinn/')) artifacts.add(ref);
264
+ }
265
+ }
266
+ // Ensure capability files (or exemption) are always audited in the horizon
267
+ if (!sawCapability) {
268
+ for (const name of listCapabilities(paths.root)) artifacts.add(normalizeRef(paths, capabilityPath(paths, name)));
269
+ }
270
+ return { taskIds: [...selected], artifacts: [...artifacts].sort() };
271
+ }
272
+
273
+ function computeDirtyArtifacts(currentMap, baselineMap, scopeKeys = null) {
274
+ const keys = scopeKeys ? scopeKeys.filter((k) => k in currentMap) : Object.keys(currentMap);
275
+ return keys.filter((k) => currentMap[k] !== baselineMap?.[k]).sort();
276
+ }
277
+
278
+ const SILENT_DRIFT_TASK_THRESHOLD = 5;
279
+
280
+ // The clean-review watermark only advances on a 'clean' checkpoint or a passed Launch.
281
+ // drift_detected/blocked verdicts deliberately do NOT refresh it — a failed audit cannot silence the bell.
282
+ function cleanReviewBaselineAt(state) {
283
+ const cleanCheckpoints = (state.keeper.checkpoints || []).filter((c) => c.verdict === 'clean');
284
+ if (cleanCheckpoints.length) return cleanCheckpoints.at(-1).at || '';
285
+ const passes = (state.keeper.attempts || []).filter((a) => ['passed', 'passed_with_advisories'].includes(a.verdict));
286
+ if (passes.length) return passes.at(-1).at || '';
287
+ return state.project?.created_at || '';
288
+ }
289
+
290
+ // Delivery Tasks finished since the last clean independent review — the silent-drift bell.
291
+ // Pure derivation: no new state field; resets automatically when a clean checkpoint records.
292
+ function deliveryTasksDoneSinceCleanReview(state, tasks) {
293
+ const baselineAt = cleanReviewBaselineAt(state);
294
+ return tasks.filter((t) => t.status === 'done' && (t.kind || 'delivery') !== 'spike' && (t.completed_at || t.updated_at || '') > baselineAt);
295
+ }
296
+
297
+ function silentDriftAlert(state, tasks) {
298
+ if (!state.keeper.launch_completed) return [];
299
+ return deliveryTasksDoneSinceCleanReview(state, tasks);
300
+ }
301
+
302
+ function normalizeFindingKey(scope, text) {
303
+ return `${(scope || 'project').trim().toLowerCase()}::${String(text || '').trim().toLowerCase()}`;
304
+ }
305
+
306
+ function upsertFindings(state, rawItems, { sourceRunId, defaultSeverity = 'blocking' } = {}) {
307
+ const keeper = ensureKeeperState(state);
308
+ const touched = [];
309
+ for (const raw of rawItems || []) {
310
+ const text = typeof raw === 'string' ? raw.trim() : (raw?.gap || raw?.text || '').trim();
311
+ if (!text) continue;
312
+ const scope = (typeof raw === 'object' && raw?.scope ? String(raw.scope).trim() : '') || 'project';
313
+ const severity = (typeof raw === 'object' && ['blocking', 'minor'].includes(raw?.severity)) ? raw.severity : defaultSeverity;
314
+ const key = normalizeFindingKey(scope, text);
315
+ const existing = keeper.findings.find((f) => f.status === 'open' && normalizeFindingKey(f.scope, f.text) === key);
316
+ if (existing) {
317
+ if (severity === 'blocking') existing.severity = 'blocking';
318
+ existing.updated_at = now();
319
+ touched.push(existing);
320
+ } else {
321
+ const entry = {
322
+ id: nextId(keeper.findings, 'FND'),
323
+ scope,
324
+ text,
325
+ severity,
326
+ status: 'open',
327
+ source_run_id: sourceRunId || '',
328
+ closure_evidence: '',
329
+ at: now(),
330
+ };
331
+ keeper.findings.push(entry);
332
+ touched.push(entry);
333
+ }
334
+ }
335
+ return touched;
336
+ }
337
+
338
+ function findingsForTask(state, task) {
339
+ const keeper = ensureKeeperState(state);
340
+ const scopes = new Set([task.id]);
341
+ for (const ref of task.reads || []) scopes.add(ref.replaceAll('\\', '/'));
342
+ if (task.implements?.trim()) scopes.add(task.implements.trim().split('#')[0].replaceAll('\\', '/'));
343
+ return keeper.findings.filter((f) => f.status === 'open' && scopes.has(f.scope));
344
+ }
345
+
183
346
  function ensureClarify(state) {
184
347
  if (!state.clarify || typeof state.clarify !== 'object') state.clarify = { active: false, reason: '', started_at: '', closed_at: '', rounds: [] };
185
348
  if (!Array.isArray(state.clarify.rounds)) state.clarify.rounds = [];
@@ -222,6 +385,7 @@ function validateTasks(tasks) {
222
385
  if (task.implements !== undefined && typeof task.implements !== 'string') throw new Error(`${task.id} implements must be a string referencing a design decision`);
223
386
  if (task.design_exemption !== undefined && (typeof task.design_exemption !== 'string' || (task.design_exemption && task.design_exemption.length < 10))) throw new Error(`${task.id} design_exemption must be a concrete reason`);
224
387
  if (task.capability_exemption !== undefined && (typeof task.capability_exemption !== 'string' || (task.capability_exemption && task.capability_exemption.length < 10))) throw new Error(`${task.id} capability_exemption must be a concrete reason`);
388
+ if (task.kind !== undefined && !['delivery', 'spike'].includes(task.kind)) throw new Error(`${task.id} kind must be delivery or spike`);
225
389
  if (task.guardrails !== undefined) {
226
390
  if (!Array.isArray(task.guardrails)) throw new Error(`${task.id} guardrails must be an array of strings`);
227
391
  for (const rule of task.guardrails) if (typeof rule !== 'string' || !rule.trim()) throw new Error(`${task.id} guardrails entries must be non-empty strings`);
@@ -242,9 +406,18 @@ function validateTasks(tasks) {
242
406
  if (task.status === 'active') active += 1;
243
407
  }
244
408
  if (active > 1) throw new Error('Only one Task may be active');
409
+ const taskById = new Map(tasks.map((task) => [task.id, task]));
245
410
  for (const task of tasks) {
246
411
  for (const dep of task.depends_on) if (!ids.has(dep)) throw new Error(`${task.id} depends on missing Task ${dep}`);
247
412
  }
413
+ // A spike produces empirical findings, not deliverables: delivery Tasks must never wire one into the DAG.
414
+ // Checked here (not at import) so `task update` cannot retro-fit a depended-on Task into a spike either.
415
+ for (const task of tasks) {
416
+ if ((task.kind || 'delivery') === 'spike') continue;
417
+ for (const dep of task.depends_on) {
418
+ if (taskById.get(dep)?.kind === 'spike') throw new Error(`${task.id} cannot depend on spike Task ${dep}; distill spike findings into Design/Capability or skeinn record instead of wiring a spike into the delivery DAG.`);
419
+ }
420
+ }
248
421
  detectCycles(tasks);
249
422
  }
250
423
 
@@ -734,6 +907,7 @@ export function importTasks(payload, root = findRoot()) {
734
907
  outcome: raw.outcome,
735
908
  acceptance: raw.acceptance || [],
736
909
  done_when: raw.done_when || [],
910
+ kind: raw.kind || 'delivery',
737
911
  boundaries: raw.boundaries || [],
738
912
  guardrails: raw.guardrails || [],
739
913
  depends_on: raw.depends_on || [],
@@ -795,7 +969,7 @@ function sectionHeadingExists(content, anchor) {
795
969
  function taskIntegrityFindings(task, designs, capabilities, paths) {
796
970
  if (task.integrity_version !== 1) return [];
797
971
  const findings = [];
798
- if (designs.length && !task.implements?.trim() && !task.design_exemption?.trim()) findings.push('is missing implements or design_exemption');
972
+ if (task.kind !== 'spike' && designs.length && !task.implements?.trim() && !task.design_exemption?.trim()) findings.push('is missing implements or design_exemption');
799
973
  if (!paths) return findings;
800
974
  if (task.implements?.trim()) {
801
975
  const raw = task.implements.trim();
@@ -857,7 +1031,7 @@ export function updateTask(id, patch, root = findRoot()) {
857
1031
  const task = taskStore.tasks.find((item) => item.id === id);
858
1032
  if (!task) throw new Error(`Task not found: ${id}`);
859
1033
  if (task.status === 'done') throw new Error(`${id} is done; reopen it first (skeinn task reopen ${id} --reason <why the completion is being revisited>) before changing its record`);
860
- const allowed = ['title', 'outcome', 'acceptance', 'done_when', 'boundaries', 'guardrails', 'depends_on', 'reads', 'touches', 'implements', 'design_exemption', 'capability_hooks', 'capability_exemption', 'covers', 'progress', 'evidence'];
1034
+ const allowed = ['title', 'kind', 'outcome', 'acceptance', 'done_when', 'boundaries', 'guardrails', 'depends_on', 'reads', 'touches', 'implements', 'design_exemption', 'capability_hooks', 'capability_exemption', 'covers', 'progress', 'evidence'];
861
1035
  for (const key of Object.keys(patch)) if (!allowed.includes(key)) throw new Error(`Task field cannot be updated: ${key}`);
862
1036
  Object.assign(task, patch, { updated_at: now() });
863
1037
  validateTasks(taskStore.tasks);
@@ -913,14 +1087,25 @@ export function reopenTask(id, options = {}, root = findRoot()) {
913
1087
 
914
1088
  export function startTask(id, root = findRoot()) {
915
1089
  const { paths, state, taskStore } = loadProject(root);
916
- const latestKeeper = state.keeper.attempts.at(-1);
917
- const attestedPass = state.keeper.status === 'passed' && latestKeeper?.review?.mode === 'independent';
918
- if (state.keeper.status === 'passed' && !attestedPass) throw new Error('The recorded Keeper pass has no independent review provenance. Obtain a fresh Keeper review (see skeinn review --help) or record an explicit skip: skeinn keeper skip --reason <limitation>.');
919
- if (!['passed', 'skipped'].includes(state.keeper.status)) throw new Error('The one-time Keeper handoff has not passed. Run skeinn keeper prompt.');
920
1090
  if (taskStore.tasks.some((task) => task.status === 'active')) throw new Error('Another Task is already active');
921
1091
  const task = taskStore.tasks.find((item) => item.id === id);
922
1092
  if (!task || task.status !== 'open') throw new Error(`${id} is not open`);
1093
+ const isSpike = task.kind === 'spike';
1094
+ if (!isSpike) {
1095
+ const latestKeeper = state.keeper.attempts.at(-1);
1096
+ const passedStatus = ['passed', 'passed_with_advisories'].includes(state.keeper.status);
1097
+ const attestedPass = passedStatus && latestKeeper?.review?.mode === 'independent';
1098
+ if (passedStatus && !attestedPass) throw new Error('The recorded Keeper pass has no independent review provenance. Obtain a fresh Keeper review (see skeinn review --help) or record an explicit skip: skeinn keeper skip --reason <limitation>.');
1099
+ if (!state.keeper.launch_completed && !['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status)) {
1100
+ throw new Error('The one-time Keeper handoff has not passed. Run skeinn keeper prompt.');
1101
+ }
1102
+ }
923
1103
  assertTaskIntegrityClassification(task, root);
1104
+ const pinned = findingsForTask(state, task);
1105
+ const blockingPinned = pinned.filter((f) => f.severity === 'blocking');
1106
+ if (blockingPinned.length) {
1107
+ throw new Error(`${id} has open blocking findings pinned to its scope:\n- ${blockingPinned.map((f) => `${f.id} [${f.scope}]: ${f.text}`).join('\n- ')}\nResolve each with skeinn keeper resolve <id> --evidence "<proof>" before starting.`);
1108
+ }
924
1109
  const done = new Set(taskStore.tasks.filter((item) => item.status === 'done').map((item) => item.id));
925
1110
  const missing = task.depends_on.filter((dep) => !done.has(dep));
926
1111
  if (missing.length) throw new Error(`${id} has incomplete dependencies: ${missing.join(', ')}`);
@@ -929,10 +1114,17 @@ export function startTask(id, root = findRoot()) {
929
1114
  task.updated_at = now();
930
1115
  validateTasks(taskStore.tasks);
931
1116
  atomicJson(paths.tasks, taskStore);
932
- state.project.status = 'building';
1117
+ if (!isSpike || state.project.status !== 'shaping') state.project.status = 'building';
933
1118
  state.project.updated_at = now();
934
1119
  atomicJson(paths.state, state);
935
- return { ...task, next: 'Run skeinn context to load the execution protocol, guardrails, and every file in reads before editing.' };
1120
+ const advisories = pinned.filter((f) => f.severity === 'minor').map((f) => `${f.id} [${f.scope}]: ${f.text}`);
1121
+ return {
1122
+ ...task,
1123
+ ...(advisories.length ? { pinned_advisories: advisories } : {}),
1124
+ next: advisories.length
1125
+ ? `This Task has ${advisories.length} pinned advisory item(s) — address them during implementation and close via skeinn keeper resolve <id> --evidence "<proof>". Run skeinn context before editing.`
1126
+ : 'Run skeinn context to load the execution protocol, guardrails, and every file in reads before editing.',
1127
+ };
936
1128
  }
937
1129
 
938
1130
  export function completeTask(id, payload, root = findRoot()) {
@@ -991,7 +1183,7 @@ export function completeTask(id, payload, root = findRoot()) {
991
1183
  return task;
992
1184
  }
993
1185
 
994
- export function markReady(root = findRoot()) {
1186
+ export function markReady(root = findRoot(), options = {}) {
995
1187
  const { paths, state, taskStore } = loadProject(root);
996
1188
  const project = readFileSync(paths.project, 'utf8');
997
1189
  const designs = listDesigns(root);
@@ -1020,67 +1212,101 @@ export function markReady(root = findRoot()) {
1020
1212
  }
1021
1213
  if (integrityErrors.length) errors.push(`Task integrity classification is unresolved:\n - ${integrityErrors.join('\n - ')}`);
1022
1214
  if (highOpen.length) errors.push(`High-impact questions remain open: ${highOpen.map((item) => item.id).join(', ')}`);
1023
- const digest = projectDigest(paths, taskStore.tasks, state);
1215
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1216
+ const digest = overallDigest(currentDigests);
1024
1217
  const latestKeeper = state.keeper.attempts.at(-1);
1025
1218
  if (['needs_revision', 'blocked'].includes(state.keeper.status) && latestKeeper?.prepared_digest === digest) {
1026
1219
  errors.push('Keeper requested revision, but project truth and Task definitions have not changed');
1027
1220
  }
1221
+ // Convergence guard: if last two failed attempts did not strictly reduce blocking count (>=), pause blind looping
1222
+ const failedAttempts = state.keeper.attempts.filter((a) => ['needs_revision', 'blocked'].includes(a.verdict));
1223
+ if (failedAttempts.length >= 2 && !options.forceRound) {
1224
+ const prev = failedAttempts.at(-2);
1225
+ const curr = failedAttempts.at(-1);
1226
+ const prevCount = typeof prev.blocking_count === 'number' ? prev.blocking_count : (prev.gaps || []).length;
1227
+ const currCount = typeof curr.blocking_count === 'number' ? curr.blocking_count : (curr.gaps || []).length;
1228
+ if (currCount > 0 && currCount >= prevCount) {
1229
+ errors.push(`Non-convergent Keeper loop detected: blocking findings did not decrease across the last two rounds (${prevCount} -> ${currCount}). Narrow the active horizon, record a bounded assumption (skeinn record), or pass --force-round --reason "<why another round will converge>"`);
1230
+ }
1231
+ }
1232
+ if (options.forceRound && (!options.reason || options.reason.trim().length < 10)) {
1233
+ errors.push('--force-round requires a concrete --reason (at least 10 characters)');
1234
+ }
1028
1235
  if (errors.length) throw new Error(`Project is not ready for Keeper:\n- ${errors.join('\n- ')}`);
1236
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1237
+ const priorBaseline = latestKeeper?.artifact_digests || state.keeper.reviewed_digests || {};
1238
+ const dirty = computeDirtyArtifacts(currentDigests, priorBaseline, horizon.artifacts);
1029
1239
  delete state.keeper.auto_passed;
1030
1240
  state.project.status = 'ready_for_keeper';
1031
1241
  state.project.updated_at = now();
1032
1242
  state.keeper.prepared_digest = digest;
1243
+ state.keeper.prepared_artifact_digests = currentDigests;
1244
+ state.keeper.prepared_horizon_tasks = horizon.taskIds;
1245
+ state.keeper.prepared_horizon_artifacts = horizon.artifacts;
1246
+ state.keeper.prepared_dirty_artifacts = dirty;
1033
1247
  state.keeper.prepared_attempt = state.keeper.attempts.length + 1;
1034
1248
  atomicJson(paths.state, state);
1035
- return { ready_for_keeper: true, digest: state.keeper.prepared_digest, next: 'Open a fresh Agent and run skeinn keeper prompt' };
1249
+ return {
1250
+ ready_for_keeper: true,
1251
+ digest: state.keeper.prepared_digest,
1252
+ attempt: state.keeper.prepared_attempt,
1253
+ delta_mode: state.keeper.prepared_attempt >= 2,
1254
+ horizon_tasks: horizon.taskIds,
1255
+ dirty_artifacts: dirty,
1256
+ next: 'Open a fresh Agent and run skeinn keeper prompt',
1257
+ };
1036
1258
  }
1037
1259
 
1038
1260
  function projectDigest(paths, tasks, state = null) {
1039
- const hash = createHash('sha256');
1040
- hash.update(readFileSync(paths.project));
1041
- if (existsSync(paths.structure)) hash.update(readFileSync(paths.structure));
1042
- hash.update(readFileSync(paths.decisions));
1043
- if (state?.capability_exemption) hash.update(JSON.stringify(state.capability_exemption));
1044
- for (const name of readdirSync(paths.design).filter((file) => file.endsWith('.md')).sort()) hash.update(readFileSync(join(paths.design, name)));
1045
- for (const name of listCapabilities()) {
1046
- hash.update(readFileSync(capabilityPath(paths, name), 'utf8'));
1047
- const statusPath = join(paths.capabilities, name, 'status.json');
1048
- if (existsSync(statusPath)) hash.update(readFileSync(statusPath, 'utf8'));
1049
- }
1050
- hash.update(JSON.stringify(tasks.map(({ progress, evidence, status, updated_at, ...definition }) => definition)));
1051
- return hash.digest('hex');
1261
+ return overallDigest(artifactDigests(paths, tasks, state));
1052
1262
  }
1053
1263
 
1054
1264
  export function getKeeperPrompt(root = findRoot()) {
1055
1265
  const { state } = loadProject(root);
1056
1266
  if (state.project.status !== 'ready_for_keeper') throw new Error('Run skeinn project ready before Keeper handoff');
1057
- return keeperProtocol({ attemptNumber: state.keeper.prepared_attempt, preparedDigest: state.keeper.prepared_digest });
1267
+ const attempt = state.keeper.prepared_attempt || 1;
1268
+ return keeperProtocol({
1269
+ attemptNumber: attempt,
1270
+ preparedDigest: state.keeper.prepared_digest,
1271
+ deltaMode: attempt >= 2,
1272
+ dirtyArtifacts: state.keeper.prepared_dirty_artifacts || [],
1273
+ horizonTaskIds: state.keeper.prepared_horizon_tasks || [],
1274
+ });
1058
1275
  }
1059
1276
 
1060
1277
  export function recordKeeper(payload, root = findRoot()) {
1061
1278
  const { paths, state, taskStore } = loadProject(root);
1062
1279
  if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper result cannot be recorded before skeinn project ready');
1063
- if (!['passed', 'needs_revision', 'blocked'].includes(payload.verdict)) throw new Error('Keeper verdict must be passed, needs_revision, or blocked');
1064
- if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Keeper result requires summary and evidence');
1065
- if (payload.verdict === 'passed') {
1066
- if (payload.gaps?.length) throw new Error('Keeper pass cannot contain unresolved gaps');
1067
- if (!payload.review || payload.review.mode !== 'independent') throw new Error('Keeper pass requires an independent review; use review.mode="independent" from a fresh Agent, or skeinn keeper skip with a concrete reason');
1068
- if (!payload.review.reviewer_id || payload.review.reviewer_id.length < 6 || !payload.review.evidence || payload.review.evidence.length < 10) throw new Error('Independent Keeper review requires reviewer_id and concrete review evidence');
1280
+ if (!['passed', 'passed_with_advisories', 'needs_revision', 'blocked'].includes(payload.verdict)) {
1281
+ throw new Error('Keeper verdict must be passed, passed_with_advisories, needs_revision, or blocked');
1069
1282
  }
1283
+ if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Keeper result requires summary and evidence');
1284
+ const isPass = ['passed', 'passed_with_advisories'].includes(payload.verdict);
1070
1285
  if (payload.evidence.some((item) => typeof item !== 'string' || !item.trim())) throw new Error('Keeper evidence entries must be non-empty strings');
1071
1286
  if (payload.gaps !== undefined && !Array.isArray(payload.gaps)) throw new Error('Keeper gaps must be an array');
1287
+ if (payload.advisories !== undefined && !Array.isArray(payload.advisories)) throw new Error('Keeper advisories must be an array');
1072
1288
  for (const gap of payload.gaps || []) {
1073
1289
  if (typeof gap === 'string' && gap.trim()) continue;
1074
1290
  if (gap && typeof gap === 'object' && typeof gap.gap === 'string' && gap.gap.trim()) continue;
1075
1291
  throw new Error('Each Keeper gap must be a non-empty string or an object with a gap field');
1076
1292
  }
1293
+ if (isPass) {
1294
+ if (payload.verdict === 'passed' && payload.gaps?.length) throw new Error('Keeper pass cannot contain unresolved gaps; use passed_with_advisories for minor-only items');
1295
+ if (payload.verdict === 'passed_with_advisories') {
1296
+ const blockingInPass = (payload.gaps || []).filter((g) => typeof g === 'string' || g.severity !== 'minor');
1297
+ if (blockingInPass.length) throw new Error('passed_with_advisories cannot include blocking gaps; use needs_revision for blocking gaps');
1298
+ }
1299
+ if (!payload.review || payload.review.mode !== 'independent') throw new Error('Keeper pass requires an independent review; use review.mode="independent" from a fresh Agent, or skeinn keeper skip with a concrete reason');
1300
+ if (!payload.review.reviewer_id || payload.review.reviewer_id.length < 6 || !payload.review.evidence || payload.review.evidence.length < 10) throw new Error('Independent Keeper review requires reviewer_id and concrete review evidence');
1301
+ }
1077
1302
 
1078
1303
  if (!payload.run_id || payload.run_id.length < 6) throw new Error('Keeper result requires a unique fresh-thread run_id');
1079
1304
  if (state.keeper.attempts.some((attempt) => attempt.run_id === payload.run_id)) throw new Error(`Keeper run_id was already used: ${payload.run_id}`);
1080
1305
  if (!payload.prepared_digest || payload.prepared_digest !== state.keeper.prepared_digest) throw new Error('Keeper result prepared_digest does not match the current ready state');
1081
- const currentDigest = projectDigest(paths, taskStore.tasks, state);
1306
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1307
+ const currentDigest = overallDigest(currentDigests);
1082
1308
  if (currentDigest !== state.keeper.prepared_digest) throw new Error('Project truth changed after skeinn project ready; prepare a new Keeper attempt');
1083
- if (payload.verdict === 'passed') {
1309
+ if (isPass) {
1084
1310
  const openFindings = new Map();
1085
1311
  for (const attempt of state.keeper.attempts) {
1086
1312
  for (const closure of attempt.closure_results || []) openFindings.delete(closure.gap);
@@ -1096,22 +1322,178 @@ export function recordKeeper(payload, root = findRoot()) {
1096
1322
  }
1097
1323
  }
1098
1324
  }
1099
- const attempt = { run_id: payload.run_id, prepared_digest: payload.prepared_digest, verdict: payload.verdict, summary: payload.summary, evidence: payload.evidence, gaps: payload.gaps || [], review: payload.review || { mode: 'unverified', reviewer_id: '', evidence: '' }, can_auto_pass: false, at: now() };
1325
+ const horizonSet = new Set([...(state.keeper.prepared_horizon_tasks || []), ...(state.keeper.prepared_horizon_artifacts || []), 'project']);
1326
+ const blockingCount = (payload.gaps || []).filter((g) => {
1327
+ if (typeof g === 'string') return true;
1328
+ const sev = g.severity || 'blocking';
1329
+ if (sev !== 'blocking') return false;
1330
+ // Out-of-horizon blocking observations auto-downgrade to minor advisory
1331
+ if (g.scope && !horizonSet.has(g.scope)) return false;
1332
+ return true;
1333
+ }).length;
1334
+ const attempt = {
1335
+ run_id: payload.run_id,
1336
+ prepared_digest: payload.prepared_digest,
1337
+ artifact_digests: currentDigests,
1338
+ verdict: payload.verdict,
1339
+ blocking_count: blockingCount,
1340
+ summary: payload.summary,
1341
+ evidence: payload.evidence,
1342
+ gaps: payload.gaps || [],
1343
+ advisories: payload.advisories || [],
1344
+ review: payload.review || { mode: 'unverified', reviewer_id: '', evidence: '' },
1345
+ can_auto_pass: false,
1346
+ closure_results: payload.closure_results || [],
1347
+ at: now(),
1348
+ };
1100
1349
  state.keeper.attempts.push(attempt);
1101
- attempt.closure_results = payload.closure_results || [];
1350
+ // Apply closures to unified findings ledger
1351
+ for (const closure of payload.closure_results || []) {
1352
+ for (const f of state.keeper.findings) {
1353
+ if (f.status === 'open' && (f.text === closure.gap || f.id === closure.id)) {
1354
+ f.status = 'closed';
1355
+ f.closure_evidence = closure.evidence;
1356
+ f.closed_at = now();
1357
+ }
1358
+ }
1359
+ }
1360
+ // Upsert findings/advisories into unified ledger (with horizon-relative severity)
1361
+ if (isPass) {
1362
+ const minorItems = [
1363
+ ...(payload.gaps || []).map((g) => (typeof g === 'string' ? { gap: g, severity: 'minor' } : { ...g, severity: 'minor' })),
1364
+ ...(payload.advisories || []).map((a) => (typeof a === 'string' ? { gap: a, severity: 'minor' } : { ...a, severity: 'minor' })),
1365
+ ];
1366
+ upsertFindings(state, minorItems, { sourceRunId: payload.run_id, defaultSeverity: 'minor' });
1367
+ // Commit reviewed horizon artifacts into reviewed_digests (birth certificate)
1368
+ const reviewedScope = state.keeper.prepared_horizon_artifacts?.length
1369
+ ? state.keeper.prepared_horizon_artifacts
1370
+ : Object.keys(currentDigests);
1371
+ for (const key of reviewedScope) {
1372
+ if (key in currentDigests) state.keeper.reviewed_digests[key] = currentDigests[key];
1373
+ }
1374
+ state.keeper.launch_completed = true;
1375
+ state.project.status = 'build_ready';
1376
+ } else {
1377
+ const normalizedGaps = (payload.gaps || []).map((g) => {
1378
+ if (typeof g === 'string') return { gap: g, scope: 'project', severity: 'blocking' };
1379
+ const scope = g.scope || 'project';
1380
+ const sev = g.severity === 'minor' || (scope !== 'project' && !horizonSet.has(scope)) ? 'minor' : 'blocking';
1381
+ return { ...g, scope, severity: sev };
1382
+ });
1383
+ upsertFindings(state, normalizedGaps, { sourceRunId: payload.run_id, defaultSeverity: 'blocking' });
1384
+ state.project.status = 'shaping';
1385
+ }
1102
1386
  state.keeper.status = payload.verdict;
1103
- if (payload.verdict === 'passed') state.project.status = 'build_ready';
1104
- else state.project.status = 'shaping';
1105
1387
  state.project.updated_at = now();
1106
1388
  atomicJson(paths.state, state);
1107
1389
  return state.keeper;
1108
1390
  }
1109
1391
 
1392
+ export function resolveFinding(id, options = {}, root = findRoot()) {
1393
+ if (!options.evidence || options.evidence.trim().length < 10) {
1394
+ throw new Error('Resolving a finding requires concrete --evidence (at least 10 characters)');
1395
+ }
1396
+ const { paths, state } = loadProject(root);
1397
+ const finding = state.keeper.findings.find((f) => f.id === id);
1398
+ if (!finding) throw new Error(`Finding not found: ${id}`);
1399
+ if (finding.status === 'closed') return finding;
1400
+ finding.status = 'closed';
1401
+ finding.closure_evidence = options.evidence.trim();
1402
+ finding.closed_at = now();
1403
+ state.project.updated_at = now();
1404
+ atomicJson(paths.state, state);
1405
+ return finding;
1406
+ }
1407
+
1408
+ export function resetKeeper(reason, root = findRoot()) {
1409
+ if (!reason || reason.trim().length < 10) throw new Error('Resetting Keeper requires a concrete --reason (at least 10 characters)');
1410
+ const { paths, state } = loadProject(root);
1411
+ state.keeper.reviewed_digests = {};
1412
+ state.keeper.launch_completed = false;
1413
+ state.keeper.status = 'not_run';
1414
+ state.project.status = 'shaping';
1415
+ state.project.updated_at = now();
1416
+ atomicJson(paths.state, state);
1417
+ recordDecision({ summary: `Keeper relaunch reset: ${reason.trim()}`, changes: ['.skeinn/state.json'] }, root);
1418
+ return { reset: true, reason: reason.trim(), next: 'Shape the revised direction, then run skeinn project ready for a fresh Launch Keeper review.' };
1419
+ }
1420
+
1421
+ export function getCheckpointPrompt(options = {}, root = findRoot()) {
1422
+ const { paths, state, taskStore } = loadProject(root);
1423
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1424
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1425
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1426
+ const openFindings = state.keeper.findings.filter((f) => f.status === 'open');
1427
+ // Even with dirty === 0 (pure code drift, no declaration churn) the reviewer needs the
1428
+ // recent delivery slice — its touches list is exactly what to diff against spec.
1429
+ const recentDone = deliveryTasksDoneSinceCleanReview(state, taskStore.tasks).map((t) => ({ id: t.id, title: t.title, implements: t.implements || '', touches: t.touches || [] }));
1430
+ return checkpointProtocol({
1431
+ milestone: options.milestone || 'in-flight',
1432
+ dirtyArtifacts: dirty,
1433
+ openFindings,
1434
+ recentDoneTasks: recentDone,
1435
+ preparedDigest: overallDigest(currentDigests),
1436
+ });
1437
+ }
1438
+
1439
+ export function recordCheckpoint(payload, root = findRoot()) {
1440
+ const { paths, state, taskStore } = loadProject(root);
1441
+ if (!['clean', 'drift_detected', 'blocked'].includes(payload.verdict)) {
1442
+ throw new Error('Checkpoint verdict must be clean, drift_detected, or blocked');
1443
+ }
1444
+ if (!payload.run_id || payload.run_id.length < 6) throw new Error('Checkpoint requires a unique run_id');
1445
+ if (state.keeper.checkpoints.some((c) => c.run_id === payload.run_id)) throw new Error(`Checkpoint run_id already used: ${payload.run_id}`);
1446
+ if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Checkpoint requires summary and evidence');
1447
+ if (!payload.review || payload.review.mode !== 'independent' || !payload.review.reviewer_id || payload.review.reviewer_id.length < 6) {
1448
+ throw new Error('Checkpoint requires independent review provenance (review.mode="independent" and reviewer_id)');
1449
+ }
1450
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1451
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1452
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1453
+ for (const closure of payload.closure_results || []) {
1454
+ if (!closure.evidence || closure.evidence.trim().length < 5) throw new Error(`Closure for ${closure.id || closure.gap} requires concrete evidence`);
1455
+ for (const f of state.keeper.findings) {
1456
+ if (f.status === 'open' && (f.id === closure.id || f.text === closure.gap)) {
1457
+ f.status = 'closed';
1458
+ f.closure_evidence = closure.evidence.trim();
1459
+ f.closed_at = now();
1460
+ }
1461
+ }
1462
+ }
1463
+ if (payload.findings?.length) {
1464
+ upsertFindings(state, payload.findings, { sourceRunId: payload.run_id, defaultSeverity: payload.verdict === 'clean' ? 'minor' : 'blocking' });
1465
+ }
1466
+ if (payload.verdict === 'clean') {
1467
+ for (const key of horizon.artifacts) {
1468
+ if (key in currentDigests) state.keeper.reviewed_digests[key] = currentDigests[key];
1469
+ }
1470
+ }
1471
+ const record = {
1472
+ id: nextId(state.keeper.checkpoints, 'CHK'),
1473
+ run_id: payload.run_id,
1474
+ milestone: payload.milestone || 'in-flight',
1475
+ verdict: payload.verdict,
1476
+ summary: payload.summary,
1477
+ dirty_artifacts: dirty,
1478
+ findings_added: (payload.findings || []).length,
1479
+ closures: (payload.closure_results || []).length,
1480
+ review: payload.review,
1481
+ evidence: payload.evidence,
1482
+ snapshot_digest: overallDigest(currentDigests),
1483
+ at: now(),
1484
+ };
1485
+ state.keeper.checkpoints.push(record);
1486
+ state.project.updated_at = now();
1487
+ atomicJson(paths.state, state);
1488
+ return record;
1489
+ }
1490
+
1110
1491
  export function skipKeeper(reason, root = findRoot()) {
1111
1492
  if (!reason || reason.length < 10) throw new Error('Skipping Keeper requires a concrete reason');
1112
1493
  const { paths, state } = loadProject(root);
1113
1494
  if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper can only be skipped after skeinn project ready');
1114
1495
  state.keeper.status = 'skipped';
1496
+ state.keeper.launch_completed = true;
1115
1497
  state.keeper.skip_reason = reason;
1116
1498
  state.project.status = 'build_ready';
1117
1499
  state.project.updated_at = now();
@@ -1269,22 +1651,60 @@ export function compileContext(options = {}, root = findRoot()) {
1269
1651
  : state.capability_exemption?.reason
1270
1652
  ? `exempted (${state.capability_exemption.reason})`
1271
1653
  : 'none';
1272
- const statusBlock = `## Current Skeinn state and recommended action\n\n- Project status: ${state.project.status}\n- Active task: ${summary.active || 'none'}\n- Work map: ${summary.total} total, ${summary.open} open, ${summary.done} done, ${summary.blocked} blocked\n${blockedLine}- Design documents: ${designs.length}\n- Capability files: ${capStatusLine}\n- Keeper status: ${state.keeper.status}\n- Clarification round: ${clarify.active ? `OPEN — ${clarify.reason} (${clarify.rounds.length} recorded)` : 'none'}\n\n**Recommended next action:** ${recommendation}\n\nThis is a recommendation, not a script. Use your judgment; if you choose differently, record the reason in \`.skeinn/DECISIONS.md\` or the active Task evidence.${options.keeper || options.full ? '' : '\n\nNeed the full runtime protocol (first entry or after a context reset)? Run skeinn context --full.'}`;
1654
+ const recentDoneTasks = silentDriftAlert(state, taskStore.tasks);
1655
+ const silentDriftLine = recentDoneTasks.length >= SILENT_DRIFT_TASK_THRESHOLD
1656
+ ? `- Silent-drift watch: ${recentDoneTasks.length} delivery tasks since the last clean Keeper review — consider \`skeinn keeper checkpoint prompt\`\n`
1657
+ : '';
1658
+ const statusBlock = `## Current Skeinn state and recommended action\n\n- Project status: ${state.project.status}\n- Active task: ${summary.active || 'none'}\n- Work map: ${summary.total} total, ${summary.open} open, ${summary.done} done, ${summary.blocked} blocked\n${blockedLine}- Design documents: ${designs.length}\n- Capability files: ${capStatusLine}\n- Keeper status: ${state.keeper.status}\n${silentDriftLine}- Clarification round: ${clarify.active ? `OPEN — ${clarify.reason} (${clarify.rounds.length} recorded)` : 'none'}\n\n**Recommended next action:** ${recommendation}\n\nThis is a recommendation, not a script. Use your judgment; if you choose differently, record the reason in \`.skeinn/DECISIONS.md\` or the active Task evidence.${options.keeper || options.full ? '' : '\n\nNeed the full runtime protocol (first entry or after a context reset)? Run skeinn context --full.'}`;
1273
1659
  const blocks = [statusBlock];
1274
1660
  if (options.full || options.keeper) blocks.push(agentProtocol({ humanChannel: options.humanChannel || 'available' }));
1275
1661
  blocks.push(shapingContext({ state, taskSummary: summary, capabilityNames: capabilityStates, designNames: designs, forKeeper: Boolean(options.keeper) }));
1276
- if (state.keeper.status === 'passed' && state.keeper.attempts.at(-1)?.review?.mode !== 'independent') {
1662
+ if (['passed', 'passed_with_advisories'].includes(state.keeper.status) && state.keeper.attempts.at(-1)?.review?.mode !== 'independent') {
1277
1663
  blocks.splice(1, 0, 'WARNING: The recorded Keeper pass has no independent review provenance. It is a legacy/unverified pass, not verified readiness. Prepare a fresh handoff before relying on it; see `skeinn review --help`.');
1278
1664
  }
1279
1665
  blocks.push(`## Project whole (${normalizeRef(paths, paths.project)})\n\n${readFileSync(paths.project, 'utf8')}`);
1280
1666
  if (existsSync(paths.structure)) blocks.push(`## Project structure (${normalizeRef(paths, paths.structure)})\n\n${readFileSync(paths.structure, 'utf8')}`);
1281
- if (options.keeper) {
1282
- blocks.unshift(keeperProtocol({ attemptNumber: state.keeper.prepared_attempt, preparedDigest: state.keeper.prepared_digest }));
1667
+ if (options.checkpoint) {
1668
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1669
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1670
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1671
+ const openFindings = state.keeper.findings.filter((f) => f.status === 'open');
1672
+ const recentDone = deliveryTasksDoneSinceCleanReview(state, taskStore.tasks);
1673
+ blocks.unshift(checkpointProtocol({ milestone: 'in-flight', dirtyArtifacts: dirty, openFindings, recentDoneTasks: recentDone.map((t) => ({ id: t.id, title: t.title, implements: t.implements || '', touches: t.touches || [] })), preparedDigest: overallDigest(currentDigests) }));
1674
+ blocks.push(`## Decision history (${normalizeRef(paths, paths.decisions)})\n\n${readFileSync(paths.decisions, 'utf8')}`);
1675
+ blocks.push(`## Dirty / newly-entering horizon artifacts (${dirty.length})\n\n${dirty.length ? dirty.map((k) => `- ${k}`).join('\n') : '- none'}`);
1676
+ blocks.push(`## Delivery Tasks completed since last clean review (${recentDone.length})\n\n${recentDone.length ? recentDone.map((t) => `- ${t.id} — ${t.title}\n implements: ${t.implements || 'n/a'}\n touches: ${(t.touches || []).join(', ')}`).join('\n') : '- none'}`);
1677
+ for (const key of dirty) {
1678
+ if (key.startsWith('.skeinn/design/')) blocks.push(`## Design document (dirty): ${basename(key)}\n\n${getDesign(basename(key), root)}`);
1679
+ else if (key.startsWith('.skeinn/capabilities/')) blocks.push(`## Capability file (dirty): ${basename(key)}\n\n${getCapability(basename(key), root)}`);
1680
+ else if (key.startsWith('task:')) {
1681
+ const t = taskStore.tasks.find((item) => item.id === key.slice(5));
1682
+ if (t) blocks.push(`## Horizon Task (dirty): ${t.id}\n\n${JSON.stringify(t, null, 2)}`);
1683
+ }
1684
+ }
1685
+ } else if (options.keeper) {
1686
+ const attempt = state.keeper.prepared_attempt || 1;
1687
+ const isDelta = attempt >= 2 && !options.full;
1688
+ const dirty = state.keeper.prepared_dirty_artifacts || [];
1689
+ const dirtySet = new Set(dirty);
1690
+ blocks.unshift(keeperProtocol({
1691
+ attemptNumber: attempt,
1692
+ preparedDigest: state.keeper.prepared_digest,
1693
+ deltaMode: attempt >= 2,
1694
+ dirtyArtifacts: dirty,
1695
+ horizonTaskIds: state.keeper.prepared_horizon_tasks || [],
1696
+ }));
1283
1697
  blocks.push(`## Decision history (${normalizeRef(paths, paths.decisions)})\n\n${readFileSync(paths.decisions, 'utf8')}`);
1284
- blocks.push(`## Work map summary\n\n${JSON.stringify(summary, null, 2)}\n\nFirst executable Task:\n\n${JSON.stringify(nextTask(taskStore.tasks), null, 2)}`);
1285
- for (const name of designs) blocks.push(`## Design document: ${name}\n\n${getDesign(name, root)}`);
1698
+ blocks.push(`## Work map summary\n\n${JSON.stringify(summary, null, 2)}\n\nActive horizon Tasks: ${(state.keeper.prepared_horizon_tasks || []).join(', ') || 'none'}\n\nFirst executable Task:\n\n${JSON.stringify(nextTask(taskStore.tasks), null, 2)}`);
1699
+ for (const name of designs) {
1700
+ const ref = `.skeinn/design/${name}`;
1701
+ if (!isDelta || dirtySet.has(ref)) blocks.push(`## Design document: ${name}\n\n${getDesign(name, root)}`);
1702
+ }
1286
1703
  if (capabilities.length) {
1287
- for (const name of capabilities) blocks.push(`## Capability file: ${name}\n\n${getCapability(name, root)}`);
1704
+ for (const name of capabilities) {
1705
+ const ref = normalizeRef(paths, capabilityPath(paths, name));
1706
+ if (!isDelta || dirtySet.has(ref)) blocks.push(`## Capability file: ${name}\n\n${getCapability(name, root)}`);
1707
+ }
1288
1708
  } else if (state.capability_exemption?.reason) {
1289
1709
  blocks.push(`## Capability exemption (audit whether standard engineering genuinely suffices)\n\n- Reason: ${state.capability_exemption.reason}\n- Recorded at: ${state.capability_exemption.at}`);
1290
1710
  }
@@ -1294,6 +1714,10 @@ export function compileContext(options = {}, root = findRoot()) {
1294
1714
  if (task.guardrails && task.guardrails.length) {
1295
1715
  blocks.push(`## Task guardrails (specialist red lines)\n\n${task.guardrails.map((rule) => `- ${rule}`).join('\n')}`);
1296
1716
  }
1717
+ const taskFindings = findingsForTask(state, task);
1718
+ if (taskFindings.length) {
1719
+ blocks.push(`## Pinned Keeper findings for ${task.id}\n\n${taskFindings.map((f) => `- ${f.id} [${f.severity}, scope: ${f.scope}]: ${f.text}`).join('\n')}\n\nClose each with \`skeinn keeper resolve <id> --evidence "<proof>"\`.`);
1720
+ }
1297
1721
  for (const ref of task.reads) {
1298
1722
  const content = readContextDocument(paths, ref);
1299
1723
  if (content && ref.replaceAll('\\', '/') !== normalizeRef(paths, paths.project)) blocks.push(`## Task context: ${ref}\n\n${content}`);
@@ -1402,7 +1826,7 @@ export function checkProject(root = findRoot()) {
1402
1826
  const hasDoneWhen = Array.isArray(task.done_when) && task.done_when.length > 0;
1403
1827
  if (!hasAcceptance && hasDoneWhen) warnings.push(`${task.id} uses done_when[] without acceptance[] — consider migrating to structured acceptance for clearer verification`);
1404
1828
  }
1405
- if (state.project.status === 'build_ready' && !['passed', 'skipped'].includes(state.keeper.status)) errors.push('Project is build_ready without Keeper pass or explicit skip');
1829
+ if (state.project.status === 'build_ready' && !['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status)) errors.push('Project is build_ready without Keeper pass or explicit skip');
1406
1830
  if (state.understanding.unresolved.some((item) => item.status === 'open' && item.impact === 'high')) warnings.push('High-impact uncertainty remains open');
1407
1831
  const decisionsContent = readFileSync(paths.decisions, 'utf8');
1408
1832
  for (const block of decisionsContent.split(/\n(?=## )/)) {
@@ -1448,7 +1872,21 @@ export function checkProject(root = findRoot()) {
1448
1872
  }
1449
1873
  }
1450
1874
  const latestKeeper = state.keeper.attempts.at(-1);
1451
- if (state.keeper.status === 'passed' && latestKeeper && latestKeeper.review?.mode !== 'independent') errors.push('Keeper pass has no independently attested review provenance; obtain a fresh review (skeinn review --help) or record skeinn keeper skip --reason <limitation>');
1875
+ if (['passed', 'passed_with_advisories'].includes(state.keeper.status) && latestKeeper && latestKeeper.review?.mode !== 'independent') errors.push('Keeper pass has no independently attested review provenance; obtain a fresh review (skeinn review --help) or record skeinn keeper skip --reason <limitation>');
1876
+ const latestCheckpoint = state.keeper.checkpoints.at(-1);
1877
+ if (latestCheckpoint && latestCheckpoint.verdict === 'drift_detected') {
1878
+ warnings.push(`Latest in-flight checkpoint (${latestCheckpoint.id}) detected drift: ${latestCheckpoint.summary}`);
1879
+ }
1880
+ if (state.keeper.launch_completed && state.project.status === 'building') {
1881
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1882
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1883
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1884
+ if (dirty.length) warnings.push(`In-flight horizon has ${dirty.length} unreviewed/changed artifact(s): ${dirty.join(', ')} — consider skeinn keeper checkpoint prompt`);
1885
+ }
1886
+ const recentDone = silentDriftAlert(state, taskStore.tasks);
1887
+ if (recentDone.length >= SILENT_DRIFT_TASK_THRESHOLD) {
1888
+ warnings.push(`${recentDone.length} delivery task(s) completed since the last clean Keeper review/checkpoint (${recentDone.map((t) => t.id).join(', ')}) — run skeinn keeper checkpoint prompt to guard against silent spec-to-code drift.`);
1889
+ }
1452
1890
  const coverage = checkDeliverableCoverage(root);
1453
1891
  if (coverage.uncovered > 0) warnings.push(`Uncovered deliverables: ${coverage.uncovered_items.map((item) => item.slug).join(', ')}`);
1454
1892
  if (coverage.covered > coverage.delivered) warnings.push(`${coverage.covered - coverage.delivered} deliverable(s) are covered only by Tasks not yet done`);