@ngockhoale/ukit 3.4.75 → 3.4.76

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.
@@ -1119,6 +1119,17 @@ export async function runBeforeAgentStart(pi, event, { projectRoot, context: ext
1119
1119
  // advisory refresh — routing continues on the previously recorded model
1120
1120
  }
1121
1121
  const metadata = runtimeMetadata(event, extensionContext);
1122
+ // Turn evidence for the UNKNOWN-ownership stop lanes: this is the bridge's only
1123
+ // signal that a NEW logical turn started. A session_stop arriving later can be
1124
+ // called "the same stop" only if NO before_agent_start fired since its block.
1125
+ try {
1126
+ const turnKey = unknownOwnershipTurnKey(projectRoot, metadata.sessionId);
1127
+ // Process-wide monotonic sequence: an evicted-then-reinserted key always receives a
1128
+ // value above any count recorded before eviction, so eviction can never masquerade
1129
+ // as "no new turn" (see unknownOwnershipRepeat).
1130
+ unknownOwnershipTurnSeq += 1;
1131
+ boundedSet(unknownOwnershipTurnCounts, turnKey, unknownOwnershipTurnSeq);
1132
+ } catch { /* evidence unavailable → anti-wedge semantics apply */ }
1122
1133
  const payload = buildHookPayload('UserPromptSubmit', {
1123
1134
  prompt: event.prompt,
1124
1135
  promptOrigin: takeOwnContinuation(metadata.sessionId, event.prompt) ? 'system' : promptOriginFromBranch(event.prompt, extensionContext),
@@ -1444,18 +1455,370 @@ async function readStopGateMaxCrashStreaks(projectRoot) {
1444
1455
  // the shared state file (.ukit/storage/cache/stop-coordinator/state.json) stay
1445
1456
  // byte-identical across both engines.
1446
1457
  const STOP_GATE_LOCK_BUDGET_MS = 600;
1458
+ // Finite-exit memory for the UNKNOWN-ownership stop lanes: block ONCE per exact
1459
+ // (session, task identity, cursor bytes, reason), then release an identical repeat
1460
+ // without completion. Properties (user acceptance):
1461
+ // DURABLE — the recorded verdict persists per key, so a host restart (a REAL new
1462
+ // process) still honors it: an identical repeat releases; a restart must not
1463
+ // resurrect the block.
1464
+ // LOGICAL-STOP BY TURN EVIDENCE, not wall-clock — omp has no stop-event id (no
1465
+ // turn linkage between before_agent_start and session_stop), but the bridge
1466
+ // OBSERVES before_agent_start: a stop that arrives after a new turn started is
1467
+ // a genuinely later stop (the continuation turn ran and stopped again with
1468
+ // unchanged evidence → finite exit); a stop with NO intervening turn is the
1469
+ // same logical stop (duplicate callback → RETAIN the block, never consume the
1470
+ // exit). Turn evidence is process-local: a different process has none and
1471
+ // fails anti-wedge (release once, sticky). A release is sticky per signature.
1472
+ // TASK-SCOPED — the key binds the route state's taskInstanceId, falling back to
1473
+ // the cursor's own RunId, then 'no-run'; the signature hashes the FULL cursor
1474
+ // bytes (streamed sha256), so even two legacy cursors without any identity
1475
+ // never share a bound — different bytes are different tasks.
1476
+ // CONSERVATIVE FINGERPRINT — the cursor is streamed in full; a cursor too large
1477
+ // to fingerprint (pathological) is NEVER released in these lanes (block).
1478
+ // OPAQUE — shard file names are sha256(session+task); shard contents are
1479
+ // sha256(reason, cursor hash) plus timestamps: no session/task id, no reason
1480
+ // text and no cursor bytes ever reach disk.
1481
+ // NO CROSS-SESSION LOSS — one shard file per hashed key: a read-modify-write —
1482
+ // even one that proceeds after its lock budget lapses — touches ONLY its own
1483
+ // key's shard, so another session's record can never be lost. The per-key lock
1484
+ // (exclusive create, stale takeover, bounded wait) serializes same-key
1485
+ // writers; atomic rename keeps every write torn-file-free.
1486
+ // BOUNDED — shards are capped (new keys beyond the cap stay in-proc only) and
1487
+ // the in-proc Map is capped as well: the fallback floor is bounded per
1488
+ // process — never a wedge, never unbounded.
1489
+ const UNKNOWN_OWNERSHIP_REPORTED_MAX = 256;
1490
+ const UNKNOWN_OWNERSHIP_CURSOR_HASH_MAX = 8 * 1024 * 1024;
1491
+ const UNKNOWN_OWNERSHIP_CURSOR_CHUNK = 64 * 1024;
1447
1492
  const unknownOwnershipReported = new Map();
1448
- async function unknownOwnershipRepeat(projectRoot, sessionId, reason) {
1449
- let fingerprint = 'no-cursor';
1493
+ const unknownOwnershipStoreQueue = new Map();
1494
+ const unknownOwnershipTurnCounts = new Map();
1495
+ // Turn count observed when the coordinator-up path last emitted a block for a session;
1496
+ // a turn after it means the cached dedupe replay must not swallow the next stop.
1497
+ const coordinatedBlockTurnMark = new Map();
1498
+ // Both in-process turn maps are bounded; eviction is never a wedge (see unknownOwnershipRepeat).
1499
+ const UNKNOWN_OWNERSHIP_STATE_MAX = 256;
1500
+ let unknownOwnershipTurnSeq = 0;
1501
+ function boundedSet(map, key, value) {
1502
+ map.delete(key);
1503
+ map.set(key, value);
1504
+ while (map.size > UNKNOWN_OWNERSHIP_STATE_MAX) map.delete(map.keys().next().value);
1505
+ }
1506
+ let unknownOwnershipTempCounter = 0;
1507
+ // Turn evidence is scoped to the project root AND session: a turn in one repo never
1508
+ // advances another repo's finite exit.
1509
+ function unknownOwnershipTurnKey(projectRoot, sessionId) {
1510
+ return `${projectRoot}\u0000${String(sessionId ?? 'no-session')}`;
1511
+ }
1512
+ // Process-local identity for the turn-evidence comparison: turn counts only mean
1513
+ // something inside the process that observed them.
1514
+ const unknownOwnershipProcessId = crypto.randomBytes(16).toString('hex');
1515
+ function unknownOwnershipStoreKey(sessionId, taskIdentity) {
1516
+ return `${sessionId ?? 'no-session'}\u0000${taskIdentity || 'no-run'}`;
1517
+ }
1518
+ function withUnknownOwnershipStore(projectRoot, mutate) {
1519
+ // Serialize same-host read-modify-write cycles per project root; a failed
1520
+ // previous write must not poison the queue.
1521
+ const prev = unknownOwnershipStoreQueue.get(projectRoot) || Promise.resolve();
1522
+ const next = prev.catch(() => {}).then(mutate);
1523
+ unknownOwnershipStoreQueue.set(projectRoot, next);
1524
+ const purge = () => {
1525
+ if (unknownOwnershipStoreQueue.get(projectRoot) === next) unknownOwnershipStoreQueue.delete(projectRoot);
1526
+ };
1527
+ next.then(purge, purge);
1528
+ return next;
1529
+ }
1530
+ // CREATE-ONLY MARKER PRIMITIVES (no lock, no reclaim). Each marker is published with
1531
+ // link(2) from a fully written temp file: link fails with EEXIST when the name exists, so a
1532
+ // reader sees either no marker or a complete one, and no two creators can both win one name.
1533
+ // Nothing is overwritten and no lock is taken over, so an orphaned lock file cannot wedge a stop.
1534
+ const UNKNOWN_OWNERSHIP_MARKER_DIR = path.join('.ukit', 'storage', 'cache', 'omp-bridge-unknown-markers');
1535
+ const UNKNOWN_OWNERSHIP_MARKER_MAX = 512;
1536
+ const UNKNOWN_OWNERSHIP_TMP_STALE_MS = 60 * 1000;
1537
+ const UNKNOWN_OWNERSHIP_MARKER_RE = /^([0-9a-f]{64})\.([0-9a-f]{64})\.(block|release)$/;
1538
+ const unknownOwnershipMarkerDir = (projectRoot) => path.join(projectRoot, UNKNOWN_OWNERSHIP_MARKER_DIR);
1539
+ const unknownOwnershipMarkerFile = (projectRoot, keyHash, sigHash, kind) => path.join(unknownOwnershipMarkerDir(projectRoot), `${keyHash}.${sigHash}.${kind}`);
1540
+ // Returns true when this call created the marker, false when the name already existed.
1541
+ // Any other error propagates (storage failure) and is never reported as EEXIST.
1542
+ async function createUnknownOwnershipMarker(file, body) {
1543
+ unknownOwnershipTempCounter += 1;
1544
+ const tmp = `${file}.tmp-${process.pid}-${unknownOwnershipTempCounter}-${crypto.randomBytes(6).toString('hex')}`;
1545
+ await fs.promises.writeFile(tmp, body, { flag: 'wx' });
1450
1546
  try {
1451
- const stat = await fs.promises.stat(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'));
1452
- fingerprint = `${stat.size}:${Math.floor(stat.mtimeMs)}`;
1453
- } catch { /* fingerprint stays constant */ }
1454
- const key = `${projectRoot}\u0000${sessionId ?? 'no-session'}`;
1455
- const signature = `${reason}\u0000${fingerprint}`;
1456
- const repeat = unknownOwnershipReported.get(key) === signature;
1457
- unknownOwnershipReported.set(key, signature);
1458
- return repeat;
1547
+ await fs.promises.link(tmp, file);
1548
+ return true;
1549
+ } catch (error) {
1550
+ if (error?.code === 'EEXIST') return false;
1551
+ throw error;
1552
+ } finally {
1553
+ await fs.promises.rm(tmp, { force: true }).catch(() => {});
1554
+ }
1555
+ }
1556
+ // ENOENT → null (absent). A published marker is whole, so an unparseable body is external
1557
+ // damage: it is reported as FOREIGN ({p:null}) and releases once, never as turn evidence.
1558
+ async function readUnknownOwnershipMarker(file) {
1559
+ let raw;
1560
+ try {
1561
+ raw = await fs.promises.readFile(file, 'utf8');
1562
+ } catch (error) {
1563
+ if (error?.code === 'ENOENT') return null;
1564
+ throw error;
1565
+ }
1566
+ try {
1567
+ const body = JSON.parse(raw);
1568
+ if (body && body.v === 2 && typeof body.p === 'string' && Number.isFinite(body.k)) return body;
1569
+ } catch { /* fall through: foreign */ }
1570
+ return { v: 2, p: null, k: null };
1571
+ }
1572
+ // A published release is sticky. Storage errors are distinct from a missing marker:
1573
+ // inaccessible storage must not trap a cached block indefinitely.
1574
+ async function releaseMarkerExists(projectRoot, keyHash, sigHash) {
1575
+ try {
1576
+ await fs.promises.stat(unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'release'));
1577
+ return true;
1578
+ } catch (error) {
1579
+ if (error?.code === 'ENOENT') return false;
1580
+ throw error;
1581
+ }
1582
+ }
1583
+ // No final marker is ever removed: only temp files from crashed writers are swept once stale.
1584
+ // Capacity is therefore NOT recovered by pruning; at the cap the store stays saturated. A stat-then-unlink prune can delete a marker that
1585
+ // another process recreated under the same hashed name in between (a delayed unlink hits the
1586
+ // successor). The admission threshold is soft: concurrent blocks may exceed it, and releases
1587
+ // bypass it. At capacity a new block is refused and that stop is FAIL-OPEN released. Only temp files are swept, and
1588
+ // their names embed a per-writer random suffix, so no later writer can recreate them.
1589
+ async function reserveUnknownOwnershipSlot(dir) {
1590
+ let names;
1591
+ // A readdir failure propagates (storage error); it is never reported as saturation.
1592
+ names = await fs.promises.readdir(dir);
1593
+ const now = Date.now();
1594
+ let finals = 0;
1595
+ for (const name of names) {
1596
+ if (name.includes('.tmp-')) {
1597
+ const full = path.join(dir, name);
1598
+ try {
1599
+ if (now - (await fs.promises.stat(full)).mtimeMs > UNKNOWN_OWNERSHIP_TMP_STALE_MS) await fs.promises.rm(full, { force: true });
1600
+ } catch { /* raced */ }
1601
+ continue;
1602
+ }
1603
+ if (UNKNOWN_OWNERSHIP_MARKER_RE.test(name)) finals += 1;
1604
+ }
1605
+ // Check-then-create: creators racing at the boundary can each pass this check, so the store may
1606
+ // exceed UNKNOWN_OWNERSHIP_MARKER_MAX by up to the number of concurrent creators. No marker is deleted.
1607
+ return finals < UNKNOWN_OWNERSHIP_MARKER_MAX;
1608
+ }
1609
+ const unknownOwnershipPendingRelease = new Map();
1610
+ const UNKNOWN_OWNERSHIP_PENDING_MAX = 256;
1611
+ async function persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, k) {
1612
+ const pendingKey = `${projectRoot}\u0000${keyHash}\u0000${sigHash}`;
1613
+ let persisted = false;
1614
+ try {
1615
+ await fs.promises.mkdir(unknownOwnershipMarkerDir(projectRoot), { recursive: true });
1616
+ await createUnknownOwnershipMarker(unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'release'), JSON.stringify({ v: 2, p: unknownOwnershipProcessId, k: k ?? 0 }));
1617
+ persisted = true;
1618
+ } catch { persisted = false; }
1619
+ unknownOwnershipPendingRelease.delete(pendingKey);
1620
+ if (!persisted) {
1621
+ unknownOwnershipPendingRelease.set(pendingKey, k ?? 0);
1622
+ while (unknownOwnershipPendingRelease.size > UNKNOWN_OWNERSHIP_PENDING_MAX) {
1623
+ unknownOwnershipPendingRelease.delete(unknownOwnershipPendingRelease.keys().next().value);
1624
+ }
1625
+ }
1626
+ return persisted;
1627
+ }
1628
+ // Marker-phase decision (create-only, no lock). A .release marker is sticky. A .block marker
1629
+ // written by THIS process decides by turn evidence (moved counter → release; missing or
1630
+ // unchanged → duplicate, block retained). A foreign or unreadable .block releases once.
1631
+ // No .block → create it exclusively; losing the create race re-reads the winner (bounded).
1632
+ async function decideUnknownOwnershipMarkers(projectRoot, keyHash, sigHash, turnKey) {
1633
+ await fs.promises.mkdir(unknownOwnershipMarkerDir(projectRoot), { recursive: true });
1634
+ const blockFile = unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'block');
1635
+ if (await releaseMarkerExists(projectRoot, keyHash, sigHash)) {
1636
+ return { decided: 'repeat', k: unknownOwnershipTurnCounts.get(turnKey) ?? 0, release: false };
1637
+ }
1638
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1639
+ const marker = await readUnknownOwnershipMarker(blockFile);
1640
+ if (marker === null) {
1641
+ const current = unknownOwnershipTurnCounts.get(turnKey) ?? 0;
1642
+ // At the soft admission limit (concurrent creators may overshoot it) no durable record is created and the stop is FAIL-OPEN released: a
1643
+ // saturated store must never wedge a stop behind an endless block, and releasing claims no
1644
+ // completion (cursor untouched). Nothing is pruned, so no existing marker is removed.
1645
+ if (!(await reserveUnknownOwnershipSlot(unknownOwnershipMarkerDir(projectRoot)))) {
1646
+ return { decided: 'degraded', reason: 'saturated', release: false, durable: false };
1647
+ }
1648
+ const created = await createUnknownOwnershipMarker(blockFile, JSON.stringify({ v: 2, p: unknownOwnershipProcessId, k: current }));
1649
+ if (created) return { decided: 'first', k: current, release: false };
1650
+ continue;
1651
+ }
1652
+ if (marker.p === unknownOwnershipProcessId) {
1653
+ const current = unknownOwnershipTurnCounts.get(turnKey);
1654
+ if (current !== undefined && current !== marker.k) return { decided: 'repeat', k: marker.k, release: true };
1655
+ return { decided: 'duplicate', k: marker.k, release: false };
1656
+ }
1657
+ return { decided: 'repeat', k: marker.k ?? 0, release: true };
1658
+ }
1659
+ throw new Error('unknown-ownership marker race did not settle');
1660
+ }
1661
+ // Test-only: drive the verdict directly and bump turn evidence without the router.
1662
+ export function unknownOwnershipTestHooks() {
1663
+ return {
1664
+ repeat: unknownOwnershipRepeat,
1665
+ bumpTurn(projectRoot, sessionId) {
1666
+ unknownOwnershipTurnSeq += 1;
1667
+ boundedSet(unknownOwnershipTurnCounts, unknownOwnershipTurnKey(projectRoot, sessionId), unknownOwnershipTurnSeq);
1668
+ },
1669
+ };
1670
+ }
1671
+ function rememberUnknownOwnership(memKey, entry) {
1672
+ unknownOwnershipReported.set(memKey, entry);
1673
+ if (unknownOwnershipReported.size > UNKNOWN_OWNERSHIP_REPORTED_MAX) {
1674
+ const oldest = unknownOwnershipReported.keys().next().value;
1675
+ if (oldest !== undefined && oldest !== memKey) unknownOwnershipReported.delete(oldest);
1676
+ }
1677
+ }
1678
+ // Full streaming fingerprint: the WHOLE cursor is hashed, so evidence changes are
1679
+ // never invisible because of a prefix cut. A pathologically large cursor is
1680
+ // unfingerprintable → the caller fails conservative (block; never release).
1681
+ async function unknownOwnershipCursorFingerprint(projectRoot) {
1682
+ const cursorPath = path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md');
1683
+ const handle = await fs.promises.open(cursorPath, 'r');
1684
+ try {
1685
+ const hash = crypto.createHash('sha256');
1686
+ const chunk = Buffer.alloc(UNKNOWN_OWNERSHIP_CURSOR_CHUNK);
1687
+ let total = 0;
1688
+ let headText = '';
1689
+ for (;;) {
1690
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
1691
+ if (bytesRead === 0) break;
1692
+ const bytes = chunk.subarray(0, bytesRead);
1693
+ hash.update(bytes);
1694
+ if (headText === '') headText = bytes.toString('utf8');
1695
+ total += bytesRead;
1696
+ if (total > UNKNOWN_OWNERSHIP_CURSOR_HASH_MAX) {
1697
+ return { unfingerprintable: true, runId: /^RunId:\s*(\S+)/im.exec(headText)?.[1] || null };
1698
+ }
1699
+ }
1700
+ return { unfingerprintable: false, hash: hash.digest('hex'), runId: /^RunId:\s*(\S+)/im.exec(headText)?.[1] || null };
1701
+ } finally {
1702
+ try { await handle.close(); } catch { /* best effort */ }
1703
+ }
1704
+ }
1705
+ // Degraded releases (cursor too large to fingerprint; store saturated; store unavailable) are
1706
+ // explicit verdicts 'degraded:<reason>' that release with a named notice. They never claim
1707
+ // completion, never touch the cursor, and are never memorized, so they cannot pin a block.
1708
+ const UNKNOWN_DEGRADED_NOTICE = {
1709
+ fingerprint: 'the handoff cursor exceeds the fingerprint bound (8 MiB), so its evidence cannot be proven unchanged',
1710
+ saturated: 'the UNKNOWN repeat store is saturated (512 durable records); capacity does not recover automatically, so this stop is released without a durable record',
1711
+ storage: 'the UNKNOWN repeat store is unavailable (storage error); this stop is released without a durable record',
1712
+ unreadable: 'the handoff cursor exists but cannot be read, so its evidence cannot be checked; this stop is released without a completion claim',
1713
+ };
1714
+ const isUnknownRelease = (verdict) => verdict === 'repeat' || (typeof verdict === 'string' && verdict.startsWith('degraded:'));
1715
+ // A plain repeat proves the evidence is unchanged. A degraded release cannot prove that, so the
1716
+ // notice states the uncertainty instead of asserting that no new evidence exists.
1717
+ function unknownReleaseClause(verdict) {
1718
+ return typeof verdict === 'string' && verdict.startsWith('degraded:')
1719
+ ? 'new evidence could not be verified (degraded release)'
1720
+ : 'no new evidence or authority exists';
1721
+ }
1722
+ function unknownDegradedNotice(verdict) {
1723
+ if (typeof verdict !== 'string' || !verdict.startsWith('degraded:')) return '';
1724
+ const notice = UNKNOWN_DEGRADED_NOTICE[verdict.slice('degraded:'.length)] ?? 'the UNKNOWN repeat store could not decide';
1725
+ return `[UKit] Degraded release (no completion claim): ${notice}.`;
1726
+ }
1727
+ // Returns 'first' (record a block), 'duplicate' (same logical stop — no new turn
1728
+ // since the block: retain the block, do NOT consume the finite exit) or 'repeat'
1729
+ // (a genuinely later stop with unchanged evidence — or already-released evidence,
1730
+ // or a record from another process: release again).
1731
+ async function unknownOwnershipRepeat(projectRoot, sessionId, reason, taskInstanceId = null, { now = Date.now() } = {}) {
1732
+ let fingerprint;
1733
+ try {
1734
+ fingerprint = await unknownOwnershipCursorFingerprint(projectRoot);
1735
+ } catch (error) {
1736
+ // A genuinely absent cursor keeps the shared 'no-cursor' bound. Any other read error (EISDIR,
1737
+ // EACCES, EIO, ...) means the evidence cannot be read: that is a DEGRADED release, never a
1738
+ // label that could be mistaken for an unchanged-evidence repeat.
1739
+ if (error?.code !== 'ENOENT') return 'degraded:unreadable';
1740
+ fingerprint = { unfingerprintable: false, hash: 'no-cursor', runId: null };
1741
+ }
1742
+ // A cursor too large to fingerprint cannot be proven unchanged. It is a DEGRADED release (no
1743
+ // completion claim, cursor untouched) — never an endless block that no repeat can clear.
1744
+ if (fingerprint.unfingerprintable) return 'degraded:fingerprint';
1745
+ // Task identity precedence: route-state taskInstanceId (what the ledger and the
1746
+ // gates bind) → the cursor's own RunId → 'no-run' (the byte hash still isolates).
1747
+ const taskIdentity = taskInstanceId || fingerprint.runId || 'no-run';
1748
+ const storeKey = unknownOwnershipStoreKey(sessionId, taskIdentity);
1749
+ // Opaque on disk: hashed shard name (no raw session/task id) and hashed
1750
+ // signature (no reason text, no cursor bytes).
1751
+ const keyHash = crypto.createHash('sha256').update(storeKey).digest('hex');
1752
+ const sigHash = crypto.createHash('sha256').update(`${reason}\u0000${fingerprint.hash}`).digest('hex');
1753
+ const signature = sigHash;
1754
+ const memKey = `${projectRoot}\u0000${storeKey}`;
1755
+ const turnKey = unknownOwnershipTurnKey(projectRoot, sessionId);
1756
+ // Every decision (memory AND marker) runs inside the per-root queue, so a concurrent
1757
+ // same-process duplicate waits for the first call's memory record.
1758
+ return withUnknownOwnershipStore(projectRoot, async () => {
1759
+ // A release this process already proved but could not persist: retry it first. Whether or
1760
+ // not it lands, the proven release is authoritative for this evidence.
1761
+ const pendingKey = `${projectRoot}\u0000${keyHash}\u0000${sigHash}`;
1762
+ if (unknownOwnershipPendingRelease.has(pendingKey)) {
1763
+ await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, unknownOwnershipPendingRelease.get(pendingKey));
1764
+ return 'repeat';
1765
+ }
1766
+ const mem = unknownOwnershipReported.get(memKey);
1767
+ if (mem && mem.s === sigHash) {
1768
+ // Same process → the turn counter is authoritative evidence. A duplicate callback
1769
+ // never mutates the record: the initial block is retained, the exit NOT consumed.
1770
+ if (mem.r === 1) return 'repeat'; // sticky: this evidence was already released
1771
+ const turns = unknownOwnershipTurnCounts.get(turnKey);
1772
+ // A MISSING counter is unknown evidence (bounded state evicted it), never proof of a
1773
+ // new turn: retain the block and do not consume the exit. A real turn re-inserts the
1774
+ // counter with a process-wide sequence value that differs from mem.k, so it releases.
1775
+ if (turns !== undefined && turns !== mem.k) {
1776
+ rememberUnknownOwnership(memKey, { s: signature, t: mem.t, r: 1, k: turns }); // sticky release
1777
+ await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, turns); // survive memory eviction
1778
+ return 'repeat'; // a turn ran since the block: genuinely later stop
1779
+ }
1780
+ // P0 stale-cached-block fix: while this r:0 record was cached, ANOTHER bridge
1781
+ // instance may have durably released this exact evidence (a .release marker is
1782
+ // create-once-sticky, so its presence proves a prior release decision). The
1783
+ // durable release outranks this process's cached block — without this check the
1784
+ // cached block would override it forever, because no turn can advance this
1785
+ // process's counter while the host idles. Adopt the durable release as sticky.
1786
+ try {
1787
+ if (await releaseMarkerExists(projectRoot, keyHash, sigHash)) {
1788
+ rememberUnknownOwnership(memKey, { s: signature, t: mem.t, r: 1, k: mem.k });
1789
+ return 'repeat';
1790
+ }
1791
+ } catch {
1792
+ return 'degraded:storage';
1793
+ }
1794
+ return 'duplicate'; // no new turn: same logical stop → retain the block
1795
+ }
1796
+ // No process-local record: consult the durable markers (possibly written by another
1797
+ // process). Turn evidence does not survive processes, so a foreign record releases once.
1798
+ // Storage failure or capacity saturation is FAIL-OPEN: release without durable state, so
1799
+ // a broken or full store can never hold a stop open. Release claims no completion.
1800
+ let k = unknownOwnershipTurnCounts.get(turnKey) ?? 0;
1801
+ try {
1802
+ const outcome = await decideUnknownOwnershipMarkers(projectRoot, keyHash, sigHash, turnKey);
1803
+ // Degraded verdicts are never memorized: they release explicitly and pin nothing.
1804
+ if (outcome.decided === 'degraded') return `degraded:${outcome.reason}`;
1805
+ if (outcome.k !== undefined) k = outcome.k;
1806
+ if (outcome.release) await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, k);
1807
+ const verdict = outcome.decided;
1808
+ rememberUnknownOwnership(memKey, { s: signature, t: now, r: verdict === 'repeat' ? 1 : 0, k });
1809
+ return verdict;
1810
+ } catch {
1811
+ return 'degraded:storage';
1812
+ }
1813
+ });
1814
+ }
1815
+
1816
+ // Test-only observability for the bounded in-process state (sizes, never contents).
1817
+ export function unknownOwnershipStateSizesForTest() {
1818
+ return { turns: unknownOwnershipTurnCounts.size, marks: coordinatedBlockTurnMark.size, reported: unknownOwnershipReported.size };
1819
+ }
1820
+ export function unknownOwnershipMarkForTest(projectRoot, sessionId) {
1821
+ return coordinatedBlockTurnMark.get(unknownOwnershipTurnKey(projectRoot, sessionId)) ?? null;
1459
1822
  }
1460
1823
 
1461
1824
  const HANDOFF_PROVENANCE_PREFIX = '[ukit-stop-coordinator] handoff-cursor also requested a block: ';
@@ -1531,9 +1894,20 @@ export async function runSessionStop(
1531
1894
  pi.logger?.warn?.(`[UKit] stop-coordinator module unavailable (dedupe + handoff lanes skipped): ${error?.message || error}`);
1532
1895
  }
1533
1896
  const state = suppliedState ?? await readRouteState(projectRoot, payload);
1534
- if (coordinator && ownerStopActive(state, payload)) {
1535
- const released = await coordinator.releaseForOwnerStop({ projectRoot, payload });
1536
- pi.logger?.warn?.(`[UKit] ${released?.systemMessage ?? 'stop allowed: the owner requested STOP; nothing completed or resumed.'}`);
1897
+ if (ownerStopActive(state, payload)) {
1898
+ // The STOP marker is read from the route state (execution-ledger), not from the
1899
+ // coordinator — an unloadable coordinator module must not turn an explicit owner
1900
+ // STOP into an endless gate. `releaseForOwnerStop` (cursor → PAUSED) is a
1901
+ // best-effort side effect: without the coordinator the stop is still released,
1902
+ // the cursor stays untouched and nothing completed or resumed.
1903
+ if (coordinator) {
1904
+ const released = await coordinator.releaseForOwnerStop({ projectRoot, payload });
1905
+ pi.logger?.warn?.(`[UKit] ${released?.systemMessage ?? 'stop allowed: the owner requested STOP; nothing completed or resumed.'}`);
1906
+ } else {
1907
+ pi.logger?.warn?.('[UKit] stop allowed: the owner requested STOP (stop-coordinator module unavailable; the run cursor could not be marked PAUSED). Nothing completed or resumed; no continuation or further automatic turn is scheduled.');
1908
+ }
1909
+ // A released owner STOP is not replayable authority: clear the turn mark (same rule as finish).
1910
+ coordinatedBlockTurnMark.delete(unknownOwnershipTurnKey(projectRoot, payload.session_id));
1537
1911
  return undefined;
1538
1912
  }
1539
1913
  const ledger = suppliedLedger ?? await readExecutionLedger(projectRoot, payload) ?? {};
@@ -1542,9 +1916,16 @@ export async function runSessionStop(
1542
1916
  const initialInput = coordinator
1543
1917
  ? await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() }) : null;
1544
1918
  const key = initialInput ? `omp:${initialInput.key}` : null;
1919
+ // Turn evidence overrides the coordinator's wall-clock dedupe: once a turn has run
1920
+ // since this session's last coordinated block, the cached block is a stale replay of
1921
+ // an EARLIER logical stop and must not swallow the new one (window forced to zero).
1922
+ const turnKeyForDedupe = unknownOwnershipTurnKey(projectRoot, payload.session_id);
1923
+ const turnsSinceBlock = (unknownOwnershipTurnCounts.get(turnKeyForDedupe) || 0) - (coordinatedBlockTurnMark.get(turnKeyForDedupe) ?? 0);
1924
+ const effectiveDedupeMs = coordinatedBlockTurnMark.has(turnKeyForDedupe) && turnsSinceBlock > 0
1925
+ ? 0 : (dedupeWindowMs ?? coordinator?.DEDUPE_WINDOW_MS);
1545
1926
  if (coordinator && await coordinator.alreadyCoordinatedThisStop({
1546
1927
  projectRoot, sessionKey: key, now,
1547
- dedupeWindowMs: dedupeWindowMs ?? coordinator.DEDUPE_WINDOW_MS,
1928
+ dedupeWindowMs: effectiveDedupeMs,
1548
1929
  lockBudgetMs, replayOnlyBlocked: true, claimToken,
1549
1930
  })) {
1550
1931
  try {
@@ -1558,6 +1939,16 @@ export async function runSessionStop(
1558
1939
  if (output && (output.continue === true || output.decision === 'block')) {
1559
1940
  rememberOwnContinuation(payload.session_id, output.additionalContext ?? output.reason);
1560
1941
  }
1942
+ // Mark the turn count at every coordinated continuation (block AND continue:true —
1943
+ // the coordinator stores both as a replayable 'block' decision) so a later turn can be
1944
+ // told apart from a duplicate callback of this same stop (see effectiveDedupeMs above).
1945
+ // A release clears the mark: a released stop is not a replayable authority.
1946
+ const markKey = unknownOwnershipTurnKey(projectRoot, payload.session_id);
1947
+ if (output && (output.continue === true || output.decision === 'block')) {
1948
+ boundedSet(coordinatedBlockTurnMark, markKey, unknownOwnershipTurnCounts.get(markKey) || 0);
1949
+ } else {
1950
+ coordinatedBlockTurnMark.delete(markKey);
1951
+ }
1561
1952
  if (coordinator) {
1562
1953
  const evaluatedInput = await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() });
1563
1954
  await coordinator.publishStopDecision({
@@ -1612,15 +2003,19 @@ export async function runSessionStop(
1612
2003
  } catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
1613
2004
  }
1614
2005
  if (cursorActive && ownership.status === 'UNKNOWN') {
1615
- if (await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason)) {
2006
+ const unknownVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason, state?.taskInstanceId, { now });
2007
+ if (isUnknownRelease(unknownVerdict)) {
1616
2008
  sendContext(pi, [
1617
- `[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and no new evidence or authority exists. `
2009
+ unknownDegradedNotice(unknownVerdict),
2010
+ `[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and ${unknownReleaseClause(unknownVerdict)}. `
1618
2011
  + 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
1619
2012
  + 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it.',
1620
2013
  ], 'nextTurn', { display: true });
1621
2014
  await recordEpisode();
1622
2015
  return finish(undefined);
1623
2016
  }
2017
+ // 'first' records the block; 'duplicate' is the same logical stop again —
2018
+ // it retains the initial block instead of consuming the finite exit.
1624
2019
  return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
1625
2020
  }
1626
2021
  handoff = await coordinator.evaluateHandoffCursor({
@@ -1633,8 +2028,9 @@ export async function runSessionStop(
1633
2028
  } catch (error) {
1634
2029
  pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed: ${error?.message || error}`);
1635
2030
  if (cursorActive) {
1636
- if (await unknownOwnershipRepeat(projectRoot, payload.session_id, `evaluation failed: ${error?.message || error}`)) {
1637
- sendContext(pi, ['[UKit] Handoff provenance evaluation still fails; stop released without completion and without touching the handoff cursor (unproven, unfinished work preserved).'], 'nextTurn', { display: true });
2031
+ const failureVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, `evaluation failed: ${error?.message || error}`, state?.taskInstanceId, { now });
2032
+ if (isUnknownRelease(failureVerdict)) {
2033
+ sendContext(pi, ['[UKit] Handoff provenance evaluation still fails; stop released without completion and without touching the handoff cursor (unproven, unfinished work preserved).', unknownDegradedNotice(failureVerdict)], 'nextTurn', { display: true });
1638
2034
  await recordEpisode();
1639
2035
  return finish(undefined);
1640
2036
  }
@@ -1642,6 +2038,23 @@ export async function runSessionStop(
1642
2038
  }
1643
2039
  }
1644
2040
  } else if (cursorActive) {
2041
+ // Same finite lifecycle as the two UNKNOWN lanes above: an unloadable
2042
+ // coordinator is an infrastructure failure, not proof of an owner — block once,
2043
+ // then release an identical repeat WITHOUT completion and without touching the
2044
+ // cursor, so a broken module can never wedge a session behind an endless gate.
2045
+ const downVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, 'stop coordinator unavailable', state?.taskInstanceId, { now });
2046
+ if (isUnknownRelease(downVerdict)) {
2047
+ sendContext(pi, [
2048
+ unknownDegradedNotice(downVerdict),
2049
+ `[UKit] Handoff ownership is still UNKNOWN (stop coordinator unavailable) and ${unknownReleaseClause(downVerdict)}. `
2050
+ + 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
2051
+ + 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it. '
2052
+ + 'Run `ukit install` to repair the runtime.',
2053
+ ], 'nextTurn', { display: true });
2054
+ await recordEpisode();
2055
+ return finish(undefined);
2056
+ }
2057
+ // 'first' records the block; 'duplicate' retains it (same logical stop).
1645
2058
  return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
1646
2059
  }
1647
2060
  const handoffBlock = handoff?.kind === 'block' ? handoff.reason : null;
@@ -1,76 +0,0 @@
1
- #!/usr/bin/env node
2
- import path from 'node:path';
3
-
4
- import { triageBug } from '../../src/bug/triageBug.js';
5
-
6
- async function main() {
7
- const args = process.argv.slice(2);
8
- const { value: rootArg, args: remainingArgs } = extractFlagValue(args, '--root');
9
- const rootDir = rootArg ? path.resolve(rootArg) : process.cwd();
10
-
11
- // Everything after `--` is signature text; before it, only positional args
12
- // are — the --root value was already consumed by extractFlagValue.
13
- const separatorIndex = remainingArgs.indexOf('--');
14
- const positional = separatorIndex === -1 ? remainingArgs : remainingArgs.slice(0, separatorIndex);
15
- const afterSeparator = separatorIndex === -1 ? [] : remainingArgs.slice(separatorIndex + 1);
16
- const unknown = positional.filter((arg) => arg.startsWith('--'));
17
- if (unknown.length > 0) {
18
- throw new Error(`unknown argument: ${unknown[0]}`);
19
- }
20
- const signature = [...positional, ...afterSeparator].join(' ').trim();
21
-
22
- if (!signature) {
23
- console.error('Usage: yarn bug:triage -- "<error signature>"');
24
- process.exitCode = 1;
25
- return;
26
- }
27
-
28
- const result = await triageBug({ rootDir, signature });
29
- console.log('[bug:triage]');
30
- console.log(`lane: ${result.lane}`);
31
- console.log(`confidence: ${result.confidence.toFixed(2)}`);
32
- console.log(`signature: ${result.signature}`);
33
- console.log(`suspects: ${result.suspectFiles.join(', ') || 'none'}`);
34
- console.log(`test: ${result.recommendedTestCommand}`);
35
- }
36
-
37
- function extractFlagValue(argv, flag) {
38
- let value = null;
39
- const nextArgs = [];
40
-
41
- for (let i = 0; i < argv.length; i += 1) {
42
- const arg = argv[i];
43
-
44
- if (arg === flag) {
45
- if (value !== null) {
46
- nextArgs.push(arg);
47
- continue;
48
- }
49
- const maybeValue = argv[i + 1];
50
- if (!maybeValue || maybeValue.startsWith('--')) {
51
- throw new Error(`Missing value for ${flag}.`);
52
- }
53
- value = maybeValue;
54
- i += 1;
55
- continue;
56
- }
57
-
58
- if (arg.startsWith(`${flag}=`)) {
59
- if (value === null) {
60
- value = arg.slice(flag.length + 1);
61
- continue;
62
- }
63
- }
64
-
65
- nextArgs.push(arg);
66
- }
67
-
68
- return { value, args: nextArgs };
69
- }
70
-
71
- try {
72
- await main();
73
- } catch (error) {
74
- console.error(error && error.message ? error.message : error);
75
- process.exit(1);
76
- }
@@ -1,66 +0,0 @@
1
- #!/usr/bin/env node
2
- // DOC-102 renderer CLI (SPEC §8.2).
3
- // node scripts/docs/render-instructions.mjs --write (default) regenerate all outputs
4
- // node scripts/docs/render-instructions.mjs --parity check installed root instructions read-only
5
- // `--parity` takes precedence over `--check`/`--write`; `--parity-root` overrides only the
6
- // comparison target directory for fixture/testing use, never the source/layout root.
7
- import path from 'node:path';
8
- import fs from 'node:fs';
9
- import { fileURLToPath } from 'node:url';
10
-
11
- import {
12
- renderInstructionsFromDisk,
13
- checkRenderedInstructions,
14
- } from '../../src/render/instructionRenderer.js';
15
-
16
- const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
17
-
18
-
19
- const USAGE = 'usage: render-instructions.mjs [--write|--check|--parity] [--parity-root <dir>]';
20
- const args = process.argv.slice(2);
21
- const parityRootArg = args.indexOf('--parity-root');
22
- const parityRoot = parityRootArg === -1 ? repoRoot : path.resolve(args[parityRootArg + 1] || '');
23
- const unknown = args.filter((a, i) => a !== '--write' && a !== '--check' && a !== '--parity'
24
- && a !== '--parity-root' && !(parityRootArg !== -1 && i === parityRootArg + 1));
25
- if (unknown.length > 0 || (parityRootArg !== -1 && !args[parityRootArg + 1])) {
26
- console.error(`${USAGE}\nunknown flag or missing value: ${unknown[0] || '--parity-root'}`);
27
- process.exit(2);
28
- }
29
- if (parityRootArg !== -1 && !args.includes('--parity')) {
30
- console.error(`${USAGE}\n--parity-root requires --parity`);
31
- process.exit(2);
32
- }
33
-
34
- const mode = args.includes('--check') ? 'check' : 'write';
35
- const parity = args.includes('--parity');
36
-
37
- try {
38
- if (parity) {
39
- const rendered = await renderInstructionsFromDisk({ repoRoot, write: false });
40
- const targets = [...rendered].filter(([target]) => target === 'CLAUDE.md' || target === 'AGENTS.md');
41
- const drift = targets.filter(([target, content]) => {
42
- const file = path.join(parityRoot, target);
43
- return !fs.existsSync(file) || !fs.readFileSync(file).equals(Buffer.from(content));
44
- });
45
- for (const [target] of drift) console.log(`DRIFT ${target}`);
46
- if (drift.length > 0) process.exit(1);
47
- console.log(`PARITY OK ${targets.length} files`);
48
- process.exit(0);
49
- }
50
-
51
- if (mode === 'check') {
52
- const drift = await checkRenderedInstructions({ repoRoot });
53
- for (const target of drift) {
54
- console.log(`DRIFT ${target}`);
55
- }
56
- process.exit(drift.length > 0 ? 1 : 0);
57
- }
58
-
59
- const rendered = await renderInstructionsFromDisk({ repoRoot, write: true });
60
- for (const [target, content] of rendered) {
61
- console.log(`WROTE ${target} (${content.split('\n').length - 1} lines)`);
62
- }
63
- } catch (err) {
64
- console.error(err && err.message ? err.message : err);
65
- process.exit(1);
66
- }