@ngockhoale/ukit 3.4.78 → 3.4.81

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.
@@ -899,26 +899,410 @@ export function parseScopeQueue(value) {
899
899
  // never "nothing left").
900
900
  // `scope` (optional Set from parseScopeQueue): when given, only the frozen slugs count, so a
901
901
  // blueprint queued after the run froze its scope never extends that run. null = legacy, all count.
902
+ // Returns eligible pending slugs PLUS slugs whose queue metadata is invalid (fail closed: an
903
+ // unprovable stale/superseded claim is never "nothing left"). Unreadable backlog → null.
902
904
  export async function pendingQueuedBlueprints(runRoot, scope = null) {
903
- const dir = path.join(runRoot, 'docs', 'AI_HANDOFF', 'queued');
904
- let entries;
905
+ const result = await classifyQueuedBlueprints(runRoot, { scope });
906
+ if (!result.ok) return null;
907
+ return [...result.eligiblePendingHandoffs, ...result.invalidOrBlockedHandoffs.map((x) => x.slug)].sort();
908
+ }
909
+
910
+ // ─── Queued blueprint lifecycle (stale / superseded detection) ─────────────
911
+ // A queued/<slug>/ package is classified from its HANDOFF.md header only; nothing is moved,
912
+ // archived or rewritten (read-only discovery). States:
913
+ // pending — no QueueIntent (legacy / mandatory overflow): consumable, counts.
914
+ // deliberate-future — separate backlog, never counts (existing contract).
915
+ // superseded|stale — `QueueIntent: superseded|stale` + `QueueSupersededBy: <ref>[, <ref>...]`
916
+ // with VERIFIED provenance; excluded with a reason.
917
+ // invalid — malformed/unprovable metadata; counts as blocking with diagnostics.
918
+ // ACTIVE / BLOCKED / COMPLETED live in RUN.md + INDEX.md (the canonical lane) — a queued package
919
+ // has no parallel state machine. A package is never auto-marked stale or done: exclusion needs
920
+ // explicit owner/planner metadata AND evidence inside this project's docs/AI_HANDOFF/.
921
+ // Reference grammar (no paths, so no traversal and no cross-project evidence):
922
+ // archive:cycle-NN — ARCHIVE/ (or legacy archive/) cycle with an 8-column INDEX snapshot in
923
+ // which EVERY task of the package is terminal and its task file archived;
924
+ // several archive refs may jointly cover a package split across cycles.
925
+ // queue:<slug> — the obligation moved to another blueprint (still queued, or consumed
926
+ // into ARCHIVE|archive/blueprints/<slug>); chains are followed, cycles and
927
+ // self-references are invalid.
928
+ const QUEUE_HEADER_CAP = 64 * 1024;
929
+ const QUEUE_INTENTS = new Set(['deliberate-future', 'stale', 'superseded']);
930
+ const QUEUE_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
931
+ const QUEUE_REF_MAX = 8;
932
+ const QUEUE_CHAIN_MAX = 16;
933
+ const QUEUE_SCAN_BATCH = 32;
934
+
935
+ /** Parse the Queue* header of a HANDOFF.md. Pure. */
936
+ export function parseQueueHeader(text) {
937
+ const values = new Map();
938
+ const diagnostics = [];
939
+ for (const line of String(text ?? '').split(/\r?\n/)) {
940
+ const m = line.match(/^(QueueIntent|QueueSupersededBy|QueueOrder):[ \t]*(.*)$/i);
941
+ if (!m) continue;
942
+ const key = m[1].toLowerCase();
943
+ const raw = m[2].replace(/\s+#.*$/, '').trim();
944
+ const value = key === 'queueintent' ? raw.toLowerCase() : raw;
945
+ if (values.has(key) && values.get(key) !== value) diagnostics.push(`conflicting ${m[1]} lines`);
946
+ else values.set(key, value);
947
+ }
948
+ const intentRaw = values.get('queueintent');
949
+ // First token decides (the legacy matcher accepted `deliberate-future (note)` too).
950
+ const intent = intentRaw === undefined ? null : (intentRaw.match(/^[A-Za-z-]+/)?.[0] || intentRaw).toLowerCase();
951
+ const supersededBy = values.get('queuesupersededby') ?? null;
952
+ const orderRaw = values.get('queueorder');
953
+ const order = orderRaw !== undefined && /^\d{1,9}$/.test(orderRaw) ? Number(orderRaw) : null;
954
+ if (intent !== null && !QUEUE_INTENTS.has(intent)) diagnostics.push(`unknown QueueIntent "${intentRaw.slice(0, 40)}"`);
955
+ if (supersededBy !== null && intent !== 'stale' && intent !== 'superseded') {
956
+ diagnostics.push('QueueSupersededBy requires QueueIntent: stale|superseded');
957
+ }
958
+ if ((intent === 'stale' || intent === 'superseded') && !supersededBy) {
959
+ diagnostics.push(`QueueIntent: ${intent} requires QueueSupersededBy evidence (archive:cycle-NN or queue:<slug>)`);
960
+ }
961
+ return { intent, supersededBy, order, diagnostics };
962
+ }
963
+
964
+ /** Parse a QueueSupersededBy value into typed references. Pure. */
965
+ export function parseSupersessionRefs(value, selfSlug = '') {
966
+ const diagnostics = [];
967
+ const refs = [];
968
+ const seen = new Set();
969
+ const parts = String(value ?? '').split(',').map((s) => s.trim()).filter(Boolean);
970
+ if (parts.length === 0) diagnostics.push('QueueSupersededBy is empty');
971
+ if (parts.length > QUEUE_REF_MAX) diagnostics.push(`QueueSupersededBy lists more than ${QUEUE_REF_MAX} references`);
972
+ for (const part of parts.slice(0, QUEUE_REF_MAX)) {
973
+ const arch = part.match(/^archive:cycle-(\d{1,6})$/i);
974
+ const queue = part.match(/^queue:(.+)$/i);
975
+ if (arch) {
976
+ const num = String(Number(arch[1]));
977
+ if (!seen.has(`a:${num}`)) refs.push({ kind: 'archive', num, label: part });
978
+ seen.add(`a:${num}`);
979
+ } else if (queue && QUEUE_SLUG_RE.test(queue[1])) {
980
+ if (queue[1] === selfSlug) diagnostics.push(`QueueSupersededBy references itself (${part})`);
981
+ else if (!seen.has(`q:${queue[1]}`)) refs.push({ kind: 'queue', slug: queue[1], label: part });
982
+ seen.add(`q:${queue[1]}`);
983
+ } else {
984
+ diagnostics.push(`unsupported QueueSupersededBy reference "${part.slice(0, 60)}" (expected archive:cycle-NN or queue:<slug>; paths are never accepted)`);
985
+ }
986
+ }
987
+ const kinds = new Set(refs.map((r) => r.kind));
988
+ if (kinds.size > 1) diagnostics.push('QueueSupersededBy mixes archive: and queue: references');
989
+ if (refs.filter((r) => r.kind === 'queue').length > 1) diagnostics.push('QueueSupersededBy names more than one replacement blueprint');
990
+ return { refs, diagnostics };
991
+ }
992
+
993
+ async function readHeadUtf8(file, cap) {
994
+ const handle = await fs.open(file, 'r');
995
+ try {
996
+ const buf = Buffer.alloc(cap);
997
+ const { bytesRead } = await handle.read(buf, 0, cap, 0);
998
+ return buf.subarray(0, bytesRead).toString('utf8');
999
+ } finally {
1000
+ await handle.close();
1001
+ }
1002
+ }
1003
+
1004
+ function insideDir(child, parent) {
1005
+ const rel = path.relative(parent, child);
1006
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
1007
+ }
1008
+
1009
+ // Archive cycle directories keyed by numeric cycle, across ARCHIVE/ and legacy archive/
1010
+ // (realpath de-duplicated, like evalFinalizedCycles). Unreadable → { ok:false }.
1011
+ async function listArchiveCycles(aiRoot) {
1012
+ const byNum = new Map();
1013
+ const seen = new Set();
1014
+ for (const spelling of ['ARCHIVE', 'archive']) {
1015
+ const base = path.join(aiRoot, spelling);
1016
+ try {
1017
+ const real = await fs.realpath(base);
1018
+ if (seen.has(real)) continue;
1019
+ seen.add(real);
1020
+ for (const entry of await fs.readdir(base, { withFileTypes: true })) {
1021
+ const m = entry.name.match(/^cycle-(\d+)$/);
1022
+ if (!m) continue;
1023
+ const num = String(Number(m[1]));
1024
+ if (!byNum.has(num)) byNum.set(num, []);
1025
+ byNum.get(num).push({ name: entry.name, dir: path.join(base, entry.name), symlink: entry.isSymbolicLink() });
1026
+ }
1027
+ } catch (error) {
1028
+ if (error?.code !== 'ENOENT') return { ok: false, byNum };
1029
+ }
1030
+ }
1031
+ return { ok: true, byNum };
1032
+ }
1033
+
1034
+ // Load one archive cycle as supersession evidence. Fails closed (diagnostic) on anything a
1035
+ // partial, foreign or tampered archive could produce.
1036
+ async function loadArchiveEvidence(ctx, num) {
1037
+ const listing = await ctx.archiveListing();
1038
+ if (!listing.ok) return { diag: 'archive history unreadable' };
1039
+ const matches = listing.byNum.get(num) || [];
1040
+ if (matches.length === 0) return { diag: `archive cycle-${num} not found` };
1041
+ if (matches.length > 1) return { diag: `archive cycle-${num} is ambiguous (${matches.map((m) => m.name).join(', ')})` };
1042
+ const cycle = matches[0];
1043
+ if (cycle.symlink) return { diag: `archive ${cycle.name} is a symlink (evidence must live in this project)` };
1044
+ try {
1045
+ const real = await fs.realpath(cycle.dir);
1046
+ if (!insideDir(real, ctx.aiReal)) return { diag: `archive ${cycle.name} resolves outside docs/AI_HANDOFF` };
1047
+ const files = await fs.readdir(cycle.dir, { withFileTypes: true });
1048
+ const snap = files.find((f) => f.name === 'INDEX.md');
1049
+ if (!snap || !snap.isFile()) {
1050
+ return { diag: `archive ${cycle.name} has no INDEX snapshot regular file (a partial archive cannot prove the package)` };
1051
+ }
1052
+ const raw = await fs.readFile(path.join(cycle.dir, 'INDEX.md'), 'utf8');
1053
+ const header = raw.match(/^#\s*Archived INDEX snapshot \(cycle[- ]?(\d+)\)/im);
1054
+ if (header && String(Number(header[1])) !== num) {
1055
+ return { diag: `archive ${cycle.name} INDEX snapshot is labelled cycle ${header[1]}` };
1056
+ }
1057
+ const snapshot = parseIndexStatuses(raw);
1058
+ if (snapshot === null) return { diag: `archive ${cycle.name} INDEX snapshot malformed (expected ${INDEX_TASK_COLUMNS}-column rows)` };
1059
+ if (snapshot.size === 0) return { diag: `archive ${cycle.name} INDEX snapshot has no task rows` };
1060
+ const taskFiles = new Set(files.filter((f) => f.isFile() && /^TASK-[\w.-]+\.md$/i.test(f.name))
1061
+ .map((f) => f.name.replace(/\.md$/i, '').toUpperCase()));
1062
+ const ids = new Set([...snapshot.keys()].map(goalTaskId));
1063
+ const graph = buildSupersessionGraph(snapshot.entries.map((e) => ({ id: e.id, cls: classifyTaskStatus(e.status, e.id, ids), successors: e.successors })));
1064
+ const covers = (id) => {
1065
+ if (!taskFiles.has(id)) return false;
1066
+ const cls = classifyTaskStatus(snapshot.get(id) || '', id, ids);
1067
+ return cls === 'delivered' || (cls === 'cancelled-grounded' && groundedCancellationResolved(id, graph));
1068
+ };
1069
+ return { name: cycle.name, covers };
1070
+ } catch {
1071
+ return { diag: `archive ${cycle.name} unreadable` };
1072
+ }
1073
+ }
1074
+
1075
+ // Task ids a package owns: tasks/TASK-*.md files plus TASK rows of its draft INDEX.md.
1076
+ async function packageTaskIds(pkgDir) {
1077
+ const ids = new Set();
905
1078
  try {
906
- entries = await fs.readdir(dir, { withFileTypes: true });
1079
+ for (const f of await fs.readdir(path.join(pkgDir, 'tasks'), { withFileTypes: true })) {
1080
+ if (f.isFile() && /^TASK-[\w.-]+\.md$/i.test(f.name)) ids.add(f.name.replace(/\.md$/i, '').toUpperCase());
1081
+ }
907
1082
  } catch (error) {
908
- return error?.code === 'ENOENT' ? [] : null;
1083
+ if (error?.code !== 'ENOENT') return null;
909
1084
  }
910
- const pending = [];
911
- for (const entry of entries) {
912
- if (!entry.isDirectory()) continue;
913
- if (scope && !scope.has(entry.name)) continue;
914
- let header = '';
1085
+ try {
1086
+ const idx = await readHeadUtf8(path.join(pkgDir, 'INDEX.md'), QUEUE_HEADER_CAP * 4);
1087
+ for (const m of idx.matchAll(/^\|\s*(TASK-[\w.-]+)\s*\|/gim)) ids.add(m[1].toUpperCase());
1088
+ } catch (error) {
1089
+ if (error?.code !== 'ENOENT') return null;
1090
+ }
1091
+ return ids;
1092
+ }
1093
+
1094
+ // Local (single-package) classification: header + archive evidence. queue: refs are
1095
+ // resolved afterwards over the whole inventory.
1096
+ async function classifyQueuedPackage(ctx, entry) {
1097
+ const slug = entry.name;
1098
+ const item = { slug, state: 'pending', intent: null, order: null, supersededBy: null, reasons: [], diagnostics: [], refs: [] };
1099
+ if (entry.isSymbolicLink()) {
1100
+ item.state = 'invalid';
1101
+ item.diagnostics.push('queued package is a symlink (packages must live in this project)');
1102
+ return item;
1103
+ }
1104
+ const pkgDir = path.join(ctx.queuedDir, slug);
1105
+ let header = '';
1106
+ try {
1107
+ const st = await fs.lstat(path.join(pkgDir, 'HANDOFF.md'));
1108
+ if (!st.isFile()) throw Object.assign(new Error('not a regular file'), { code: 'ENOTFILE' });
1109
+ header = await readHeadUtf8(path.join(pkgDir, 'HANDOFF.md'), QUEUE_HEADER_CAP);
1110
+ } catch (error) {
1111
+ if (error?.code === 'ENOENT') {
1112
+ item.reasons.push('no HANDOFF.md: legacy fold-in blueprint');
1113
+ return item;
1114
+ }
1115
+ item.state = 'invalid';
1116
+ item.diagnostics.push(error?.code === 'ENOTFILE' ? 'HANDOFF.md is not a regular file' : 'HANDOFF.md unreadable');
1117
+ return item;
1118
+ }
1119
+ const parsed = parseQueueHeader(header);
1120
+ Object.assign(item, { intent: parsed.intent, order: parsed.order, supersededBy: parsed.supersededBy });
1121
+ if (parsed.diagnostics.length > 0) {
1122
+ item.state = 'invalid';
1123
+ item.diagnostics.push(...parsed.diagnostics);
1124
+ return item;
1125
+ }
1126
+ if (parsed.intent === null) {
1127
+ item.reasons.push('no QueueIntent: consumable blueprint');
1128
+ return item;
1129
+ }
1130
+ if (parsed.intent === 'deliberate-future') {
1131
+ item.state = 'deliberate-future';
1132
+ item.reasons.push(`deliberate-future backlog${parsed.order !== null ? ` (QueueOrder ${parsed.order})` : ''}`);
1133
+ return item;
1134
+ }
1135
+ const { refs, diagnostics } = parseSupersessionRefs(parsed.supersededBy, slug);
1136
+ if (diagnostics.length > 0) {
1137
+ item.state = 'invalid';
1138
+ item.diagnostics.push(...diagnostics);
1139
+ return item;
1140
+ }
1141
+ item.refs = refs;
1142
+ item.state = parsed.intent;
1143
+ if (refs[0]?.kind === 'archive') {
1144
+ const ids = await packageTaskIds(pkgDir);
1145
+ if (ids === null) {
1146
+ item.state = 'invalid';
1147
+ item.diagnostics.push('package tasks unreadable');
1148
+ return item;
1149
+ }
1150
+ if (ids.size === 0) {
1151
+ item.state = 'invalid';
1152
+ item.diagnostics.push('package declares no TASK ids, so archive coverage cannot be proven');
1153
+ return item;
1154
+ }
1155
+ const evidence = [];
1156
+ for (const ref of refs) {
1157
+ const ev = await ctx.archive(ref.num);
1158
+ if (ev.diag) item.diagnostics.push(ev.diag);
1159
+ else evidence.push(ev);
1160
+ }
1161
+ if (item.diagnostics.length > 0) {
1162
+ item.state = 'invalid';
1163
+ return item;
1164
+ }
1165
+ const missing = [...ids].sort().filter((id) => !evidence.some((ev) => ev.covers(id)));
1166
+ if (missing.length > 0) {
1167
+ item.state = 'invalid';
1168
+ item.diagnostics.push(`archive evidence (${evidence.map((e) => e.name).join(', ')}) does not prove ${missing.length}/${ids.size} package task(s) delivered: ${missing.slice(0, 5).join(', ')}${missing.length > 5 ? ', …' : ''}`);
1169
+ return item;
1170
+ }
1171
+ item.reasons.push(`${parsed.intent}: all ${ids.size} task(s) proven delivered in ${evidence.map((e) => e.name).join(', ')}`);
1172
+ }
1173
+ return item;
1174
+ }
1175
+
1176
+ async function consumedBlueprintExists(ctx, slug) {
1177
+ for (const spelling of ['ARCHIVE', 'archive']) {
1178
+ const dir = path.join(ctx.aiRoot, spelling, 'blueprints', slug);
915
1179
  try {
916
- header = await fs.readFile(path.join(dir, entry.name, 'HANDOFF.md'), 'utf8');
917
- } catch { /* a blueprint without HANDOFF.md uses the legacy fold-in behaviour */ }
918
- if (/^QueueIntent:\s*deliberate-future\b/im.test(header)) continue;
919
- pending.push(entry.name);
1180
+ const st = await fs.lstat(dir);
1181
+ if (st.isDirectory() && insideDir(await fs.realpath(dir), ctx.aiReal)) return true;
1182
+ } catch { /* absent here */ }
1183
+ }
1184
+ return false;
1185
+ }
1186
+
1187
+ // Follow a queue: chain to the package that now carries the obligation.
1188
+ // → { carrier: item|null (null = consumed into archive/blueprints), diag? }
1189
+ async function resolveQueueChain(ctx, byslug, start) {
1190
+ const trail = [start.slug];
1191
+ let cur = start;
1192
+ for (let hop = 0; hop < QUEUE_CHAIN_MAX; hop += 1) {
1193
+ const target = cur.refs[0].slug;
1194
+ if (trail.includes(target)) return { diag: `supersession cycle: ${[...trail, target].join(' → ')}` };
1195
+ trail.push(target);
1196
+ const next = byslug.get(target);
1197
+ if (!next) {
1198
+ return (await consumedBlueprintExists(ctx, target))
1199
+ ? { carrier: null }
1200
+ : { diag: `replacement queue:${target} not found in queued/ or archive/blueprints/` };
1201
+ }
1202
+ if (next.state === 'invalid' && next.refs.length === 0) return { diag: `replacement queue:${target} has invalid queue metadata` };
1203
+ if (next.refs[0]?.kind !== 'queue') {
1204
+ return next.state === 'invalid' ? { diag: `replacement queue:${target} has invalid queue metadata` } : { carrier: next };
1205
+ }
1206
+ cur = next;
920
1207
  }
921
- return pending.sort();
1208
+ return { diag: `supersession chain longer than ${QUEUE_CHAIN_MAX} hops` };
1209
+ }
1210
+
1211
+ /**
1212
+ * Read-only inventory of docs/AI_HANDOFF/queued/. `scope` = Set from parseScopeQueue (null =
1213
+ * legacy, all in scope). Never throws; unreadable queue root → ok:false.
1214
+ * @returns {Promise<{ ok: boolean, allKnownHandoffs: object[], eligiblePendingHandoffs: string[],
1215
+ * excludedWithReasons: {slug:string,state:string,reason:string}[],
1216
+ * invalidOrBlockedHandoffs: {slug:string,diagnostics:string[]}[], warnings: string[], diagnostics: string[] }>}
1217
+ */
1218
+ export async function classifyQueuedBlueprints(runRoot, { scope = null } = {}) {
1219
+ const aiRoot = path.join(runRoot, 'docs', 'AI_HANDOFF');
1220
+ const queuedDir = path.join(aiRoot, 'queued');
1221
+ const result = { ok: true, allKnownHandoffs: [], eligiblePendingHandoffs: [], excludedWithReasons: [], invalidOrBlockedHandoffs: [], warnings: [], diagnostics: [] };
1222
+ try {
1223
+ const legacy = await fs.lstat(path.join(aiRoot, 'queue'));
1224
+ if (legacy.isDirectory()) {
1225
+ result.diagnostics.push('docs/AI_HANDOFF/queue/ exists: only queued/ is the canonical queue root; queue/ packages are not counted and are never migrated automatically');
1226
+ }
1227
+ } catch { /* no legacy root */ }
1228
+ let entries;
1229
+ try {
1230
+ entries = await fs.readdir(queuedDir, { withFileTypes: true });
1231
+ } catch (error) {
1232
+ if (error?.code === 'ENOENT') return result;
1233
+ result.ok = false;
1234
+ result.diagnostics.push('docs/AI_HANDOFF/queued/ unreadable');
1235
+ return result;
1236
+ }
1237
+ let aiReal = aiRoot;
1238
+ try { aiReal = await fs.realpath(aiRoot); } catch { /* keep lexical root */ }
1239
+ let listingPromise = null;
1240
+ const archiveCache = new Map();
1241
+ const ctx = {
1242
+ aiRoot, aiReal, queuedDir,
1243
+ archiveListing: () => (listingPromise ??= listArchiveCycles(aiRoot)),
1244
+ archive: (num) => {
1245
+ if (!archiveCache.has(num)) archiveCache.set(num, loadArchiveEvidence(ctx, num));
1246
+ return archiveCache.get(num);
1247
+ },
1248
+ };
1249
+ const packages = entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).sort((a, b) => (a.name < b.name ? -1 : 1));
1250
+ const items = [];
1251
+ for (let i = 0; i < packages.length; i += QUEUE_SCAN_BATCH) {
1252
+ items.push(...await Promise.all(packages.slice(i, i + QUEUE_SCAN_BATCH).map((e) => classifyQueuedPackage(ctx, e))));
1253
+ }
1254
+ const byslug = new Map(items.map((it) => [it.slug, it]));
1255
+ for (const item of items) {
1256
+ if (item.refs[0]?.kind !== 'queue' || item.state === 'invalid') continue;
1257
+ const { carrier, diag } = await resolveQueueChain(ctx, byslug, item);
1258
+ if (diag) {
1259
+ item.state = 'invalid';
1260
+ item.diagnostics.push(diag);
1261
+ } else if (carrier && carrier.state === 'deliberate-future') {
1262
+ // Mandatory work must not be retired into a backlog that never blocks a run.
1263
+ item.state = 'invalid';
1264
+ item.diagnostics.push(`replacement queue:${carrier.slug} is deliberate-future backlog; it cannot carry a mandatory obligation (cite archive evidence or a pending replacement)`);
1265
+ } else if (carrier && carrier.state === 'pending' && scope && scope.has(item.slug) && !scope.has(carrier.slug)) {
1266
+ item.state = 'invalid';
1267
+ item.diagnostics.push(`obligation moved to queue:${carrier.slug}, which is outside the frozen ScopeQueue (add it to ScopeQueue or cite archive evidence)`);
1268
+ } else {
1269
+ item.reasons.push(`${item.state}: obligation carried by ${carrier ? `queue:${carrier.slug} (${carrier.state})` : `consumed blueprint ${item.refs[0].slug}`}`);
1270
+ }
1271
+ }
1272
+ for (const item of items) {
1273
+ const inScope = !scope || scope.has(item.slug);
1274
+ item.inScope = inScope;
1275
+ const { refs, ...pub } = item;
1276
+ pub.supersededByRefs = refs.map((r) => r.label);
1277
+ result.allKnownHandoffs.push(pub);
1278
+ if (!inScope) {
1279
+ result.excludedWithReasons.push({ slug: item.slug, state: item.state, reason: 'outside the frozen ScopeQueue' });
1280
+ continue;
1281
+ }
1282
+ if (item.state === 'pending') result.eligiblePendingHandoffs.push(item.slug);
1283
+ else if (item.state === 'invalid') result.invalidOrBlockedHandoffs.push({ slug: item.slug, diagnostics: item.diagnostics });
1284
+ else {
1285
+ result.excludedWithReasons.push({ slug: item.slug, state: item.state, reason: item.reasons.join('; ') });
1286
+ if (scope && (item.state === 'stale' || item.state === 'superseded')) {
1287
+ result.warnings.push(`ScopeQueue selects ${item.slug}, but it is ${item.state} (${item.supersededBy}); it will not be consumed`);
1288
+ }
1289
+ }
1290
+ }
1291
+ return result;
1292
+ }
1293
+
1294
+ /** One-line summary of what keeps a run-all backlog open (for block reasons). */
1295
+ export function describeQueuedBacklog(result, limit = 5) {
1296
+ const parts = [];
1297
+ const eligible = result.eligiblePendingHandoffs;
1298
+ if (eligible.length > 0) parts.push(`${eligible.length} queued blueprint(s) remain: ${eligible.slice(0, limit).join(', ')}.`);
1299
+ const invalid = result.invalidOrBlockedHandoffs;
1300
+ if (invalid.length > 0) {
1301
+ parts.push(`${invalid.length} queued blueprint(s) have invalid stale/superseded metadata and still count (fail closed): ${invalid.slice(0, limit).map((x) => `${x.slug} [${x.diagnostics.join('; ')}]`).join(', ')}.`);
1302
+ }
1303
+ const excluded = result.excludedWithReasons.filter((x) => x.state === 'stale' || x.state === 'superseded');
1304
+ if (excluded.length > 0) parts.push(`Excluded (verified ${excluded.length > 1 ? 'stale/superseded' : excluded[0].state}): ${excluded.slice(0, limit).map((x) => x.slug).join(', ')}.`);
1305
+ return parts.join(' ');
922
1306
  }
923
1307
 
924
1308
  // ─── Exit predicate (mechanic #7 — exit-predicate-first loop) ─────────────
@@ -1131,9 +1515,11 @@ async function evalFinalizedCycles(projectRoot, goalScope, scopeQueue = '', cycl
1131
1515
  if (total === 0) return { pass: false, detail: 'INDEX.md has no task rows' };
1132
1516
  if (failing.length > 0) return { pass: false, detail: `archived task not done: ${failing.join(', ')}` };
1133
1517
  if (String(goalScope).toLowerCase() === 'run-all') {
1134
- const remaining = await pendingQueuedBlueprints(projectRoot, parseScopeQueue(scopeQueue));
1135
- if (!Array.isArray(remaining)) return { pass: false, detail: 'queued backlog unreadable' };
1136
- if (remaining.length > 0) return { pass: false, detail: `queued blueprint(s) remain: ${remaining.join(', ')}` };
1518
+ const backlog = await classifyQueuedBlueprints(projectRoot, { scope: parseScopeQueue(scopeQueue) });
1519
+ if (!backlog.ok) return { pass: false, detail: 'queued backlog unreadable' };
1520
+ if (backlog.eligiblePendingHandoffs.length > 0 || backlog.invalidOrBlockedHandoffs.length > 0) {
1521
+ return { pass: false, detail: describeQueuedBacklog(backlog) };
1522
+ }
1137
1523
  }
1138
1524
  return { pass: true, detail: `${total} archived task(s) done, index finalized` };
1139
1525
  }
@@ -1947,9 +2333,14 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1947
2333
  // Header-only INDEX = this CYCLE is finalized, not necessarily the GOAL: a run-all goal
1948
2334
  // continues while consumable queued blueprints remain (or the backlog is unreadable).
1949
2335
  if (goalScope !== 'run-all') return { kind: 'none' };
1950
- const remaining = await pendingQueuedBlueprints(runRoot, parseScopeQueue(scopeQueue));
1951
- if (Array.isArray(remaining) && remaining.length === 0) return { kind: 'none' };
1952
- openNextCycle = { remaining };
2336
+ const backlog = await classifyQueuedBlueprints(runRoot, { scope: parseScopeQueue(scopeQueue) });
2337
+ if (backlog.ok && backlog.eligiblePendingHandoffs.length === 0 && backlog.invalidOrBlockedHandoffs.length === 0) {
2338
+ // Explicitly selected stale/superseded slugs are surfaced, never silently dropped.
2339
+ return backlog.warnings.length > 0
2340
+ ? { kind: 'advisory', systemMessage: `[ukit-stop-coordinator] ${backlog.warnings.slice(0, 5).join(' | ')}` }
2341
+ : { kind: 'none' };
2342
+ }
2343
+ openNextCycle = { backlog };
1953
2344
  } else {
1954
2345
  effectivePredicate = 'all(index:all-done)';
1955
2346
  predicateIsDefault = true;
@@ -1962,18 +2353,25 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1962
2353
  // transcript, latest intent is not fullstack" releases; unknown (null) keeps
1963
2354
  // the block, so a real run is never released by a lost read.
1964
2355
  if (terminal === 'done' && openNextCycle) {
1965
- const names = openNextCycle.remaining;
2356
+ const { backlog } = openNextCycle;
2357
+ const invalidOnly = backlog.ok && backlog.eligiblePendingHandoffs.length === 0;
1966
2358
  return {
1967
2359
  kind: 'block',
1968
2360
  reason: [
1969
2361
  'UKit run-all goal: this cycle is finalized but the GOAL is not complete — ',
1970
- names === null
2362
+ !backlog.ok
1971
2363
  ? 'the queued backlog (docs/AI_HANDOFF/queued/) could not be read, so remaining work is unknown, not zero.'
1972
- : `${names.length} queued blueprint(s) remain: ${names.slice(0, 5).join(', ')}.`,
2364
+ : describeQueuedBacklog(backlog),
1973
2365
  '',
1974
- 'CONTINUE IMMEDIATELY: open the next cycle — fold the next queued blueprint into',
1975
- 'INDEX.md / tasks/ (P2), set `Phase:` to a live phase, and execute it. Archive each',
1976
- 'consumed blueprint to archive/blueprints/. Set `Phase: blocked` only for a real external blocker.',
2366
+ ...(invalidOnly
2367
+ ? ['RECONCILE: each listed blueprint claims stale/superseded but its provenance is unproven.',
2368
+ 'Either fix its HANDOFF.md (`QueueSupersededBy: archive:cycle-NN` covering EVERY package task,',
2369
+ 'or `queue:<slug>` naming the replacement), or fold it in as real work. Never archive or',
2370
+ 'delete it to silence this; set `Phase: blocked` if the owner must decide.']
2371
+ : ['CONTINUE IMMEDIATELY: open the next cycle — fold the next queued blueprint into',
2372
+ 'INDEX.md / tasks/ (P2), set `Phase:` to a live phase, and execute it. Archive each',
2373
+ 'consumed blueprint to archive/blueprints/. Set `Phase: blocked` only for a real external blocker.']),
2374
+ ...backlog.diagnostics.map((d) => `Note: ${d}`),
1977
2375
  ].join('\n').replace('— \n', '— '),
1978
2376
  };
1979
2377
  }
@@ -46,6 +46,38 @@ Semantics:
46
46
  the status vocabulary in `RULES.md` is unchanged.
47
47
  - Blueprints WITHOUT `QueueIntent` keep the legacy fold-in behaviour.
48
48
 
49
+ ## Stale / superseded blueprints (no longer work)
50
+
51
+ A blueprint whose work was delivered by an archived cycle, or replaced by another queued
52
+ blueprint, is marked in its `HANDOFF.md` header instead of being deleted or archived:
53
+
54
+ ```
55
+ QueueIntent: superseded # or: stale
56
+ QueueSupersededBy: archive:cycle-12[, archive:cycle-13] # or: queue:<replacement-slug>
57
+ ```
58
+
59
+ - `archive:cycle-NN` counts only when `ARCHIVE|archive/cycle-NN/` exists inside
60
+ `docs/AI_HANDOFF/` (no symlink escape), carries an 8-column `# Archived INDEX snapshot
61
+ (cycle-NN)` INDEX.md, and **every** task of the blueprint (`tasks/TASK-*.md` plus its
62
+ INDEX rows) is archived there with a delivered or grounded-cancelled status. A partial
63
+ archive proves nothing: the blueprint stays counted.
64
+ - `queue:<slug>` counts only when the replacement exists (queued or consumed under
65
+ `archive/blueprints/<slug>`), is not the blueprint itself, and the chain has no cycle.
66
+ - Paths, URLs, `..`, other projects and free text are never accepted as provenance.
67
+ - Invalid or unprovable metadata **fails closed**: the blueprint keeps counting as unfinished
68
+ work, with a diagnostic naming why. Never archive or delete a blueprint to silence it.
69
+ - A frozen `ScopeQueue` that names a stale/superseded blueprint gets a warning; it is not
70
+ consumed silently.
71
+ - Blueprints without these lines keep the legacy behaviour.
72
+
73
+ Inspect the lane read-only (no mutation, no archiving):
74
+ `node .claude/ukit/runtime/resumable-run.mjs queue-status <projectRoot> [--scope <slug,slug|none>]`
75
+ prints `allKnownHandoffs`, `eligiblePendingHandoffs`, `excludedWithReasons`,
76
+ `invalidOrBlockedHandoffs`, `warnings` and `diagnostics`.
77
+
78
+ `queued/` is the canonical lane. A sibling `docs/AI_HANDOFF/queue/` directory is reported as a
79
+ diagnostic and is never read or migrated automatically.
80
+
49
81
  ## Naming
50
82
 
51
83
  Use a unique `<slug>`. If `queued/<slug>/` already exists, append `-2`, `-3`, … and never