@ngockhoale/ukit 3.4.74 → 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.
- package/CHANGELOG.md +110 -95
- package/manifests/platform.full.yaml +15 -0
- package/package.json +14 -4
- package/src/cli/commands/markerStore.js +15 -0
- package/src/cli/index.js +7 -0
- package/src/core/markerStoreMigration.js +122 -0
- package/template_project/.claude/hooks/completion-gate.sh +10 -1
- package/template_project/.claude/hooks/handoff-resume.sh +9 -0
- package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
- package/template_project/.claude/hooks/skill-router.sh +262 -28
- package/template_project/.claude/settings.json +11 -1
- package/template_project/.claude/ukit/index/publication-intent.mjs +144 -18
- package/template_project/.claude/ukit/index/route-task.mjs +91 -9
- package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +11 -4
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +369 -29
- package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
- package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +161 -32
- package/template_project/.omp/hooks/pre/ukit-bridge.js +552 -4
- package/scripts/bug/triage.mjs +0 -76
- package/scripts/dev/worktree-preflight.mjs +0 -166
- package/scripts/docs/render-instructions.mjs +0 -66
- package/scripts/index/build-index.mjs +0 -102
- package/scripts/index/query-index.mjs +0 -128
- package/scripts/index/refresh-index.mjs +0 -195
- package/scripts/install/sync-installed-mirror.mjs +0 -263
- package/scripts/measure-decision-gateway.mjs +0 -306
- package/scripts/probe/codex-capability-probe.mjs +0 -169
- package/scripts/skill/audit-skill.mjs +0 -68
- package/scripts/test/run-handoff-isolated.mjs +0 -178
|
@@ -18,7 +18,10 @@ import {
|
|
|
18
18
|
markNotified,
|
|
19
19
|
readExecutionLedger,
|
|
20
20
|
readRouteState,
|
|
21
|
+
ownerStopActive,
|
|
22
|
+
ownerStopGovernsStart,
|
|
21
23
|
} from '../../../.claude/ukit/runtime/execution-ledger.mjs';
|
|
24
|
+
import { classifyOwnerControl } from '../../../.claude/ukit/index/publication-intent.mjs';
|
|
22
25
|
import {
|
|
23
26
|
PAYLOAD_INLINE_MAX_BYTES,
|
|
24
27
|
createPayloadReferenceAsync,
|
|
@@ -261,6 +264,28 @@ export function isSubagentSession(context = {}) {
|
|
|
261
264
|
}
|
|
262
265
|
}
|
|
263
266
|
|
|
267
|
+
export function parentSessionIdOf(context = {}) {
|
|
268
|
+
try {
|
|
269
|
+
const parent = context?.sessionManager?.getHeader?.()?.parentSession;
|
|
270
|
+
if (typeof parent !== 'string' || !parent) return undefined;
|
|
271
|
+
const match = /^[^_]*_(.+)\.jsonl$/.exec(parent.split(/[/\\]/).pop());
|
|
272
|
+
return match ? match[1] : undefined;
|
|
273
|
+
} catch {
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const OWNER_STOP_START_REASON = 'Owner STOP is in effect for this session: no new tool, shell command, edit or subagent may start until the owner sends a new request. Do not retry; report the stop and wait.';
|
|
279
|
+
export async function ownerStopBlocksStart(projectRoot, event = {}, context = {}) {
|
|
280
|
+
try {
|
|
281
|
+
const meta = runtimeMetadata(event, context);
|
|
282
|
+
const own = context?.sessionManager?.getSessionId?.();
|
|
283
|
+
return await ownerStopGovernsStart(projectRoot, [meta.sessionId, own, meta.parentSessionId]);
|
|
284
|
+
} catch {
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
264
289
|
function runtimeMetadata(event = {}, context = {}) {
|
|
265
290
|
const sessionManager = context?.sessionManager;
|
|
266
291
|
const transcriptPath = event.transcriptPath ?? event.transcript_path ?? sessionManager?.getSessionFile?.();
|
|
@@ -276,9 +301,71 @@ function runtimeMetadata(event = {}, context = {}) {
|
|
|
276
301
|
cwd: context?.cwd ?? event.cwd,
|
|
277
302
|
transcriptPath,
|
|
278
303
|
subagentSession: isSubagentSession(context) ? true : undefined,
|
|
304
|
+
parentSessionId: parentSessionIdOf(context),
|
|
279
305
|
};
|
|
280
306
|
}
|
|
281
307
|
|
|
308
|
+
const OWN_CONTINUATION_TTL_MS = 10 * 60 * 1000;
|
|
309
|
+
const ownContinuations = new Map();
|
|
310
|
+
function rememberOwnContinuation(sessionId, text, now = Date.now()) {
|
|
311
|
+
const key = String(sessionId ?? '').trim();
|
|
312
|
+
const value = String(text ?? '').trim();
|
|
313
|
+
if (!key || !value) return;
|
|
314
|
+
const list = (ownContinuations.get(key) || []).filter((entry) => now - entry.ts <= OWN_CONTINUATION_TTL_MS);
|
|
315
|
+
list.push({ text: value, ts: now });
|
|
316
|
+
ownContinuations.set(key, list.slice(-4));
|
|
317
|
+
}
|
|
318
|
+
function takeOwnContinuation(sessionId, prompt, now = Date.now()) {
|
|
319
|
+
const key = String(sessionId ?? '').trim();
|
|
320
|
+
const value = String(prompt ?? '').trim();
|
|
321
|
+
if (!key || !value) return false;
|
|
322
|
+
const list = (ownContinuations.get(key) || []).filter((entry) => now - entry.ts <= OWN_CONTINUATION_TTL_MS);
|
|
323
|
+
const index = list.findIndex((entry) => entry.text === value);
|
|
324
|
+
if (index < 0) { ownContinuations.set(key, list); return false; }
|
|
325
|
+
list.splice(index, 1);
|
|
326
|
+
ownContinuations.set(key, list);
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const ownerInputs = new Map();
|
|
331
|
+
const OWNER_INPUT_KEEP = 32;
|
|
332
|
+
let ownerInputHostSeen = false;
|
|
333
|
+
function ownerInputKey(event, context) {
|
|
334
|
+
return String(event?.sessionId ?? event?.session_id ?? context?.sessionManager?.getSessionId?.()
|
|
335
|
+
?? context?.sessionManager?.getSessionFile?.() ?? '').trim();
|
|
336
|
+
}
|
|
337
|
+
export function observeOwnerInput(event, context = {}) {
|
|
338
|
+
const key = ownerInputKey(event, context);
|
|
339
|
+
const text = String(event?.text ?? '').trim();
|
|
340
|
+
if (!key || !text) return;
|
|
341
|
+
ownerInputHostSeen = true;
|
|
342
|
+
const book = ownerInputs.get(key) || { seq: 0, stopSeq: 0, pending: [] };
|
|
343
|
+
book.seq += 1;
|
|
344
|
+
const stop = classifyOwnerControl(text).kind === 'stop';
|
|
345
|
+
if (stop) book.stopSeq = book.seq;
|
|
346
|
+
book.pending.push({ seq: book.seq, text, stop });
|
|
347
|
+
if (book.pending.length > OWNER_INPUT_KEEP) book.pending.splice(0, book.pending.length - OWNER_INPUT_KEEP);
|
|
348
|
+
ownerInputs.set(key, book);
|
|
349
|
+
}
|
|
350
|
+
export function takeOwnerInputOrder(sessionId, prompt) {
|
|
351
|
+
if (!ownerInputHostSeen) return undefined;
|
|
352
|
+
const book = ownerInputs.get(String(sessionId ?? '').trim());
|
|
353
|
+
const value = String(prompt ?? '').trim();
|
|
354
|
+
if (!book || !value) return 'unproven';
|
|
355
|
+
for (let start = 0; start < book.pending.length; start += 1) {
|
|
356
|
+
let joined = '';
|
|
357
|
+
for (let end = start; end < book.pending.length; end += 1) {
|
|
358
|
+
joined = end === start ? book.pending[end].text : `${joined}\n\n${book.pending[end].text}`;
|
|
359
|
+
if (joined !== value) continue;
|
|
360
|
+
const parts = book.pending.slice(start, end + 1);
|
|
361
|
+
book.pending.splice(0, end + 1);
|
|
362
|
+
if (parts.some((part) => part.stop)) return 'contains-stop';
|
|
363
|
+
return parts.some((part) => part.seq < book.stopSeq) ? 'before-stop' : 'after-stop';
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return 'unproven';
|
|
367
|
+
}
|
|
368
|
+
|
|
282
369
|
// OMP 18.12.5 before_agent_start has no origin field. Recover only the nearest
|
|
283
370
|
// native prompt-bearing branch entry, never a prefix claimed by prompt text.
|
|
284
371
|
export function promptOriginFromBranch(prompt, context = {}) {
|
|
@@ -315,7 +402,9 @@ function buildHookPayload(hookEventName, fields = {}) {
|
|
|
315
402
|
['transcriptPath', 'transcript_path'],
|
|
316
403
|
['source', 'source'],
|
|
317
404
|
['promptOrigin', 'ukit_prompt_origin'],
|
|
405
|
+
['ownerInput', 'ukit_owner_input'],
|
|
318
406
|
['subagentSession', 'ukit_subagent_session'],
|
|
407
|
+
['parentSessionId', 'ukit_parent_session_id'],
|
|
319
408
|
];
|
|
320
409
|
for (const [field, payloadField] of mappings) {
|
|
321
410
|
if (fields[field] !== undefined && fields[field] !== null) {
|
|
@@ -888,6 +977,9 @@ async function readAllowUnsafeEval(projectRoot) {
|
|
|
888
977
|
}
|
|
889
978
|
|
|
890
979
|
export async function runToolCall(pi, event, { projectRoot, context: extensionContext = {}, allowUnsafeEval } = {}) {
|
|
980
|
+
if (await ownerStopBlocksStart(projectRoot, event, extensionContext)) {
|
|
981
|
+
return { block: true, toolName: null, invoked: [], context: [], reason: OWNER_STOP_START_REASON };
|
|
982
|
+
}
|
|
891
983
|
const rawToolName = event.toolName ?? event.tool;
|
|
892
984
|
if (String(rawToolName ?? '').trim().toLowerCase() === 'eval') {
|
|
893
985
|
const allowed = allowUnsafeEval ?? await readAllowUnsafeEval(projectRoot);
|
|
@@ -1027,9 +1119,21 @@ export async function runBeforeAgentStart(pi, event, { projectRoot, context: ext
|
|
|
1027
1119
|
// advisory refresh — routing continues on the previously recorded model
|
|
1028
1120
|
}
|
|
1029
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 */ }
|
|
1030
1133
|
const payload = buildHookPayload('UserPromptSubmit', {
|
|
1031
1134
|
prompt: event.prompt,
|
|
1032
|
-
promptOrigin: promptOriginFromBranch(event.prompt, extensionContext),
|
|
1135
|
+
promptOrigin: takeOwnContinuation(metadata.sessionId, event.prompt) ? 'system' : promptOriginFromBranch(event.prompt, extensionContext),
|
|
1136
|
+
ownerInput: takeOwnerInputOrder(metadata.sessionId, event.prompt),
|
|
1033
1137
|
...metadata,
|
|
1034
1138
|
});
|
|
1035
1139
|
const result = await runScriptChain(pi, HOOK_EVENT_MAP.before_agent_start, payload, { projectRoot });
|
|
@@ -1351,6 +1455,372 @@ async function readStopGateMaxCrashStreaks(projectRoot) {
|
|
|
1351
1455
|
// the shared state file (.ukit/storage/cache/stop-coordinator/state.json) stay
|
|
1352
1456
|
// byte-identical across both engines.
|
|
1353
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;
|
|
1492
|
+
const unknownOwnershipReported = new Map();
|
|
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' });
|
|
1546
|
+
try {
|
|
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;
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1354
1824
|
const HANDOFF_PROVENANCE_PREFIX = '[ukit-stop-coordinator] handoff-cursor also requested a block: ';
|
|
1355
1825
|
|
|
1356
1826
|
let stopCoordinatorModulePromise = null;
|
|
@@ -1424,15 +1894,38 @@ export async function runSessionStop(
|
|
|
1424
1894
|
pi.logger?.warn?.(`[UKit] stop-coordinator module unavailable (dedupe + handoff lanes skipped): ${error?.message || error}`);
|
|
1425
1895
|
}
|
|
1426
1896
|
const state = suppliedState ?? await readRouteState(projectRoot, payload);
|
|
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));
|
|
1911
|
+
return undefined;
|
|
1912
|
+
}
|
|
1427
1913
|
const ledger = suppliedLedger ?? await readExecutionLedger(projectRoot, payload) ?? {};
|
|
1428
1914
|
const authority = () => ({ state, ledger: suppliedLedger ?? null });
|
|
1429
1915
|
const claimToken = crypto.randomUUID();
|
|
1430
1916
|
const initialInput = coordinator
|
|
1431
1917
|
? await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() }) : null;
|
|
1432
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);
|
|
1433
1926
|
if (coordinator && await coordinator.alreadyCoordinatedThisStop({
|
|
1434
1927
|
projectRoot, sessionKey: key, now,
|
|
1435
|
-
dedupeWindowMs:
|
|
1928
|
+
dedupeWindowMs: effectiveDedupeMs,
|
|
1436
1929
|
lockBudgetMs, replayOnlyBlocked: true, claimToken,
|
|
1437
1930
|
})) {
|
|
1438
1931
|
try {
|
|
@@ -1443,6 +1936,19 @@ export async function runSessionStop(
|
|
|
1443
1936
|
return { continue: true, additionalContext: 'UKit completion gate: Stop evaluation ownership is pending or unavailable (duplicate, claim capacity, or lock contention). No evaluator was admitted and no completion has been verified; a subsequent Stop can recheck ownership.' };
|
|
1444
1937
|
}
|
|
1445
1938
|
const finish = async (output) => {
|
|
1939
|
+
if (output && (output.continue === true || output.decision === 'block')) {
|
|
1940
|
+
rememberOwnContinuation(payload.session_id, output.additionalContext ?? output.reason);
|
|
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
|
+
}
|
|
1446
1952
|
if (coordinator) {
|
|
1447
1953
|
const evaluatedInput = await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() });
|
|
1448
1954
|
await coordinator.publishStopDecision({
|
|
@@ -1497,6 +2003,19 @@ export async function runSessionStop(
|
|
|
1497
2003
|
} catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
|
|
1498
2004
|
}
|
|
1499
2005
|
if (cursorActive && ownership.status === 'UNKNOWN') {
|
|
2006
|
+
const unknownVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason, state?.taskInstanceId, { now });
|
|
2007
|
+
if (isUnknownRelease(unknownVerdict)) {
|
|
2008
|
+
sendContext(pi, [
|
|
2009
|
+
unknownDegradedNotice(unknownVerdict),
|
|
2010
|
+
`[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and ${unknownReleaseClause(unknownVerdict)}. `
|
|
2011
|
+
+ 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
|
|
2012
|
+
+ 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it.',
|
|
2013
|
+
], 'nextTurn', { display: true });
|
|
2014
|
+
await recordEpisode();
|
|
2015
|
+
return finish(undefined);
|
|
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.
|
|
1500
2019
|
return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
|
|
1501
2020
|
}
|
|
1502
2021
|
handoff = await coordinator.evaluateHandoffCursor({
|
|
@@ -1508,9 +2027,34 @@ export async function runSessionStop(
|
|
|
1508
2027
|
});
|
|
1509
2028
|
} catch (error) {
|
|
1510
2029
|
pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed: ${error?.message || error}`);
|
|
1511
|
-
if (cursorActive)
|
|
2030
|
+
if (cursorActive) {
|
|
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 });
|
|
2034
|
+
await recordEpisode();
|
|
2035
|
+
return finish(undefined);
|
|
2036
|
+
}
|
|
2037
|
+
return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: provenance or cursor evaluation failed; completion is unproven.' });
|
|
2038
|
+
}
|
|
1512
2039
|
}
|
|
1513
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).
|
|
1514
2058
|
return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
|
|
1515
2059
|
}
|
|
1516
2060
|
const handoffBlock = handoff?.kind === 'block' ? handoff.reason : null;
|
|
@@ -1620,11 +2164,15 @@ export default function hook(pi) {
|
|
|
1620
2164
|
});
|
|
1621
2165
|
});
|
|
1622
2166
|
pi.on('tool_result', (event, context) => runToolResult(pi, event, { projectRoot, context }));
|
|
2167
|
+
pi.on('input', (event, context) => { observeOwnerInput(event, context); });
|
|
1623
2168
|
pi.on('before_agent_start', (event, context) => runBeforeAgentStart(pi, event, { projectRoot, context }));
|
|
1624
2169
|
pi.on('session.compacting', (event, context) => runSessionCompacting(pi, event, { projectRoot, context }));
|
|
1625
2170
|
pi.on('session_start', (event, context) => runSessionStart(pi, event, { projectRoot, context }));
|
|
1626
2171
|
pi.on('session_switch', (event, context) => runSessionSwitch(pi, event, { projectRoot, context }));
|
|
1627
2172
|
pi.on('session_compact', (event, context) => runSessionCompact(pi, event, { projectRoot, context }));
|
|
1628
2173
|
pi.on('session_stop', (event, context) => runSessionStop(pi, event, { projectRoot, context }));
|
|
1629
|
-
pi.on('before_subagent_spawn', (event, context) =>
|
|
2174
|
+
pi.on('before_subagent_spawn', async (event, context) => {
|
|
2175
|
+
if (await ownerStopBlocksStart(projectRoot, event, context)) return { block: true, reason: OWNER_STOP_START_REASON };
|
|
2176
|
+
return selectWorkerModel(event, { projectRoot, context });
|
|
2177
|
+
});
|
|
1630
2178
|
}
|