@kynver-app/runtime 0.2.8 → 0.2.15

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.
@@ -0,0 +1,38 @@
1
+ export declare const ADMISSION_SLOT_KEY_PREFIX = "worker-slot-n:";
2
+ export interface AdmissionSlotDecision {
3
+ admitted: boolean;
4
+ /** Set when admitted via a numbered reservation (absent in off/shadow no-op admits). */
5
+ slot?: number;
6
+ reason?: "disk_backstop" | "slots_exhausted";
7
+ }
8
+ /**
9
+ * Pre-spawn admission (enforce only; off/shadow admit unconditionally — the
10
+ * existing gate stays authoritative there). `diskActiveWorkers` MUST be a
11
+ * fresh count taken at call time, not the tick-start gate sample.
12
+ */
13
+ export declare function acquireWorkerAdmissionSlot(input: {
14
+ runId: string;
15
+ workerName: string;
16
+ maxSlots: number;
17
+ diskActiveWorkers: number;
18
+ }): AdmissionSlotDecision;
19
+ /** Free the numbered slot a worker holds (terminal transition / spawn abort). Never throws. */
20
+ export declare function releaseWorkerAdmissionSlot(runId: string, workerName: string): void;
21
+ /**
22
+ * Per-tick numbered-slot reconcile (enforce only; called from the shared
23
+ * admission reconcile): refresh slots whose owner worker is live, release
24
+ * slots whose owner is provably dead, and adopt live workers holding no
25
+ * slot (pre-flip spawns) so the reservation view converges with reality.
26
+ */
27
+ export declare function reconcileNumberedAdmissionSlots(input: {
28
+ liveWorkers: Array<{
29
+ runId: string;
30
+ workerName: string;
31
+ }>;
32
+ }): {
33
+ refreshed: number;
34
+ deadReleased: number;
35
+ adopted: number;
36
+ };
37
+ export declare function admissionEnforceCounters(): Record<string, number>;
38
+ export declare function __resetAdmissionEnforceCountersForTests(): void;
@@ -0,0 +1,56 @@
1
+ import type { LocalRunStoreSurfaceMode } from "./surface-flags.js";
2
+ export declare const ADMISSION_RESERVATION_TTL_MS: number;
3
+ /**
4
+ * Re-arm the adoption pass when the surface is observed OFF (re-review
5
+ * finding 2): workers spawned during an off window take no reservations, so
6
+ * the first reconcile after an off→active flag transition must adopt them
7
+ * silently — otherwise an operator toggling the emergency brake poisons the
8
+ * `missingForLive` metric that gates D2b. Called from the tick's off branch
9
+ * (the reconcile itself never runs while off).
10
+ */
11
+ export declare function rearmAdmissionAdoptionPass(): void;
12
+ export declare function admissionMode(env?: NodeJS.ProcessEnv): LocalRunStoreSurfaceMode;
13
+ /** Take/refresh the reservation for a spawned worker. Never throws. */
14
+ export declare function takeWorkerSlotReservation(runId: string, workerName: string): void;
15
+ /** Release on worker terminal transition. Never throws. */
16
+ export declare function releaseWorkerSlotReservation(runId: string, workerName: string): void;
17
+ export interface AdmissionShadowReconcile {
18
+ liveReservations: number;
19
+ refreshed: number;
20
+ deadReleased: number;
21
+ /** Pre-reconcile: live workers with no reservation (missed takes; 0 on the adoption pass). */
22
+ missingForLive: number;
23
+ /** Pre-reconcile: reservations with no live worker (crash backstop firing OR a missed release). */
24
+ orphaned: number;
25
+ /** True when this call was the silent adoption pass. */
26
+ adoptionPass: boolean;
27
+ }
28
+ /**
29
+ * Per-tick reconcile with PRE-reconcile classified measurement (review B —
30
+ * measuring after adoption/release repaired the evidence made the old parity
31
+ * count a tautology; comparing against a minutes-earlier disk sample made it
32
+ * noise). The instrument now compares like-for-like at the same instant,
33
+ * BEFORE repairing anything:
34
+ *
35
+ * - `missingForLive` (counted as divergence, post-adoption-pass): a live
36
+ * worker with no reservation means `takeWorkerSlotReservation` missed —
37
+ * a real lifecycle defect. Reads as: broken take → non-zero every tick.
38
+ * - `orphaned` (reported, folded into `deadSlotsReleased` when released):
39
+ * crash-terminated workers legitimately leave orphans for the reconcile
40
+ * to reap — that is the design's crash backstop, not a defect. A broken
41
+ * COMPLETION-release shows up as `deadSlotsReleased` trending with the
42
+ * completion rate instead of the (rare) crash rate.
43
+ *
44
+ * Then the repair: refresh live slots, adopt missing ones, release dead
45
+ * ones. No cross-time disk-count comparison exists anymore.
46
+ */
47
+ export declare function reconcileAdmissionShadow(input: {
48
+ /** Live workers by identity (from the same records the gate counts). */
49
+ liveWorkers: Array<{
50
+ runId: string;
51
+ workerName: string;
52
+ }>;
53
+ }): AdmissionShadowReconcile;
54
+ /** Counters snapshot for the operator-tick posture (surface active only). */
55
+ export declare function admissionShadowCounters(): Record<string, number>;
56
+ export declare function __resetAdmissionShadowCountersForTests(): void;
@@ -0,0 +1,11 @@
1
+ import { type StrandedClaimRecoveryResult } from "./dispatch-claim-recovery.js";
2
+ export declare function __resetStartupClaimRecoveryForTests(): void;
3
+ export declare function maybeRunStartupClaimRecovery(input: {
4
+ agentOsId: string;
5
+ baseUrl: string;
6
+ secret: string;
7
+ hasLiveWorker: (intent: {
8
+ runId: string;
9
+ workerName: string;
10
+ }) => boolean;
11
+ }): Promise<StrandedClaimRecoveryResult | null>;
@@ -0,0 +1,54 @@
1
+ export interface StrandedClaimRecoveryOutcome {
2
+ taskId: string;
3
+ leaseToken: string;
4
+ runId: string | null;
5
+ workerName: string | null;
6
+ action: "released" | "finalized_late" | "deferred_orphan" | "release_refused" | "deferred_transport" | "skipped";
7
+ detail?: string;
8
+ }
9
+ export interface StrandedClaimRecoveryResult {
10
+ mode: "off" | "shadow" | "enforce";
11
+ scanned: number;
12
+ outcomes: StrandedClaimRecoveryOutcome[];
13
+ }
14
+ /**
15
+ * Scan /proc for a live process whose cmdline references `pathFragment`.
16
+ * Linux only — on other platforms the probe reports no orphan, so recovery
17
+ * PROCEEDS TO RELEASE after the stall window (review A6: an unfindable
18
+ * orphan can never report anyway — it has no worker record — so the release
19
+ * narrows the pre-existing 1 h expiry window rather than adding risk; prod
20
+ * boxes are Linux). Bounded, never throws.
21
+ */
22
+ export declare function findLiveProcessByCmdlinePath(pathFragment: string): number | null;
23
+ export interface RecoverStrandedClaimsOptions {
24
+ nowMs?: number;
25
+ strandedAfterMs?: number;
26
+ /** Same liveness delegation as the shadow scan (worker.json + pid). */
27
+ hasLiveWorker: (intent: {
28
+ runId: string;
29
+ workerName: string;
30
+ }) => boolean;
31
+ /** Derive the deterministic worktree path for a claim's spawn intent. */
32
+ worktreePathFor: (intent: {
33
+ runId: string;
34
+ workerName: string;
35
+ }) => string;
36
+ /** Injectable orphan probe (defaults to the /proc cmdline scan). */
37
+ findOrphanPid?: (worktreePath: string) => number | null;
38
+ /**
39
+ * Perform the server release for one stranded claim. MUST present the
40
+ * claim's lease token (§7.7). Returns released=true only on server ack.
41
+ */
42
+ releaseClaim: (input: {
43
+ taskId: string;
44
+ leaseToken: string;
45
+ runId: string;
46
+ }) => Promise<{
47
+ released: boolean;
48
+ transportError?: boolean;
49
+ detail?: string;
50
+ }>;
51
+ }
52
+ export declare function recoverStrandedDispatchClaims(opts: RecoverStrandedClaimsOptions): Promise<StrandedClaimRecoveryResult>;
53
+ export declare function dispatchClaimRecoveryCounters(): Record<string, number>;
54
+ export declare function __resetDispatchClaimRecoveryForTests(): void;
@@ -25,6 +25,26 @@ export declare function recordCompletionAckedReceipt(identity: DispatchReceiptId
25
25
  export declare function noteCompletionReplayIfAcked(identity: DispatchReceiptIdentity): boolean;
26
26
  /** Reason-class extraction for released receipts (never the full detail text). */
27
27
  export declare function releaseReasonClass(failureDetail: string | null | undefined): string;
28
+ /**
29
+ * D1b — completion replay short-circuit: in ENFORCE mode a worker replaying a
30
+ * completion whose ack the store already holds (outcome "acknowledged") skips
31
+ * the POST entirely — the local receipt is authoritative for "the server
32
+ * already accepted this". Shadow/off keep today's behavior (POST proceeds,
33
+ * server idempotency absorbs it). The observation counter still fires via
34
+ * `noteCompletionReplayIfAcked` at the call site; this adds the decision.
35
+ */
36
+ export declare function shouldShortCircuitCompletionReplay(identity: DispatchReceiptIdentity): boolean;
37
+ export declare function recordDispatchStartFailedReceipt(taskId: string, runId: string): void;
38
+ export declare function listRecentDispatchStartFailures(runId: string, opts?: {
39
+ nowMs?: number;
40
+ windowMs?: number;
41
+ }): string[];
42
+ /**
43
+ * Attempt embedded in a lease token (`${attempt}:${uuid}`), or null. D1b R2:
44
+ * completion-ack exclusion must be attempt-aware — a PRIOR attempt's ack must
45
+ * not mask a LATER claim's stranding.
46
+ */
47
+ export declare function leaseTokenAttempt(token: string): number | null;
28
48
  export interface DispatchReceiptInvariantScan {
29
49
  scannedClaims: number;
30
50
  /** Claim receipts past the stall window with no spawned/released receipt and no live worker. */
@@ -4,7 +4,12 @@ export { LOCAL_SCHEMA_VERSION, SchemaDowngradeRefusedError, } from "./sqlite/sql
4
4
  export { FilesystemPolicyError, SqliteLocalRunStore, type OpenSqliteLocalRunStoreOptions, } from "./sqlite/sqlite-local-run-store.js";
5
5
  export { openSqliteLocalRunStoreWithRecovery, type OpenWithRecoveryResult, } from "./sqlite/sqlite-recovery.js";
6
6
  export { __resetLocalRunStoreLifecycleForTests, __setLocalRunStoreLifecycleTestOverrides, closeLocalRunStore, getLocalRunStore, getLocalRunStoreLifecycleStatus, LOCAL_RUN_STORE_OPEN_RETRY_MS, probeLocalRunStore, type LocalRunStoreLifecycleStatus, } from "./store-lifecycle.js";
7
- export { __resetDispatchReceiptCountersForTests, dispatchReceiptCounters, dispatchReceiptsMode, noteCompletionReplayIfAcked, recordCompletionAckedReceipt, recordCompletionSentReceipt, recordDispatchClaimReceipt, recordDispatchReleasedReceipt, recordDispatchSpawnedReceipt, releaseReasonClass, scanDispatchReceiptInvariants, type DispatchClaimIntent, type DispatchReceiptIdentity, type DispatchReceiptInvariantScan, } from "./dispatch-receipts.js";
7
+ export { __resetDispatchReceiptCountersForTests, dispatchReceiptCounters, dispatchReceiptsMode, noteCompletionReplayIfAcked, recordCompletionAckedReceipt, recordCompletionSentReceipt, recordDispatchClaimReceipt, recordDispatchReleasedReceipt, recordDispatchSpawnedReceipt, recordDispatchStartFailedReceipt, listRecentDispatchStartFailures, leaseTokenAttempt, releaseReasonClass, scanDispatchReceiptInvariants, shouldShortCircuitCompletionReplay, type DispatchClaimIntent, type DispatchReceiptIdentity, type DispatchReceiptInvariantScan, } from "./dispatch-receipts.js";
8
+ export { dispatchClaimRecoveryCounters, findLiveProcessByCmdlinePath, recoverStrandedDispatchClaims, __resetDispatchClaimRecoveryForTests, type RecoverStrandedClaimsOptions, type StrandedClaimRecoveryOutcome, type StrandedClaimRecoveryResult, } from "./dispatch-claim-recovery.js";
9
+ export { maybeRunStartupClaimRecovery, __resetStartupClaimRecoveryForTests, } from "./dispatch-claim-recovery-startup.js";
8
10
  export { anyLocalRunStoreSurfaceActive, LOCAL_RUN_STORE_SURFACES, parseLocalRunStoreSurfaceMode, resolveLocalRunStoreSurfaceFlags, type LocalRunStoreSurfaceDefinition, type LocalRunStoreSurfaceFlags, type LocalRunStoreSurfaceKey, type LocalRunStoreSurfaceMode, type ResolvedLocalRunStoreSurfaceFlags, } from "./surface-flags.js";
9
11
  export { buildLocalRunStoreTickPosture, type LocalRunStoreTickPosture, } from "./tick-posture.js";
12
+ export { __resetAdmissionShadowCountersForTests, admissionShadowCounters, ADMISSION_RESERVATION_TTL_MS, rearmAdmissionAdoptionPass, reconcileAdmissionShadow, releaseWorkerSlotReservation, takeWorkerSlotReservation, type AdmissionShadowReconcile, } from "./admission-shadow.js";
13
+ export { acquireWorkerAdmissionSlot, admissionEnforceCounters, ADMISSION_SLOT_KEY_PREFIX, reconcileNumberedAdmissionSlots, releaseWorkerAdmissionSlot, __resetAdmissionEnforceCountersForTests, type AdmissionSlotDecision, } from "./admission-enforce.js";
14
+ export { __resetSmallSurfaceCountersForTests, assessQuotaCooldownReservation, clearQuotaCooldownReservation, readMeshLeaseCheckpoint, recordQuotaCooldownReservation, restoreKeeperBackoffCheckpoint, saveKeeperBackoffCheckpoint, saveMeshLeaseCheckpoint, smallSurfaceCounters, type MeshLeaseGrant, } from "./small-surfaces.js";
10
15
  export { __resetRemoteSurfaceFlagsCacheForTests, extractLocalRunStoreFlagsFromOperatorTickResponse, getRemoteSurfaceFlags, persistRemoteSurfaceFlags, remoteSurfaceFlagsPath, type RemoteSurfaceModeMap, } from "./remote-surface-flags.js";
@@ -1,6 +1,7 @@
1
- var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{existsSync as Cn,mkdirSync as Qr,readFileSync as Zr,readdirSync as An,renameSync as et,rmSync as rt,statSync as On,writeFileSync as tt}from"node:fs";import{randomBytes as nt}from"node:crypto";import ot from"node:path";function De(r){console.error(r),process.exit(1)}function N(r,e){try{return JSON.parse(Zr(r,"utf8"))}catch(t){if(arguments.length>1)return e;De(`failed to read ${r}: ${t.message}`)}}function oe(r,e){Qr(ot.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${nt(4).toString("hex")}.tmp`;try{tt(t,`${JSON.stringify(e,null,2)}
2
- `),et(t,r)}catch(n){try{rt(t,{force:!0})}catch{}throw n}}var p=a(()=>{"use strict"});var st,Nn,Me=a(()=>{"use strict";st=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY"],Nn=new Set(st)});var se=a(()=>{"use strict";p();Me()});import{homedir as Ue}from"node:os";import We from"node:path";function it(r){return r==="~"?Ue():r.startsWith("~/")||r.startsWith("~\\")?We.join(Ue(),r.slice(2)):r}function ie(r){return We.resolve(it(r))}var P=a(()=>{"use strict"});var ae=a(()=>{"use strict";se();P()});function x(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"forge"}function B(r,e){return r[e]?.trim()||null}function Ke(r){let e=r?.split(":")[0]?.trim();return e?x(e):null}function O(r=process.env,e={}){let t=[],n=Ke(e.boxId),o=Ke(B(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==x(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:x(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=B(r,"KYNVER_BOX_KIND");if(i)return o&&o!==x(i)&&t.push(`KYNVER_BOX_ID=${B(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:x(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let c=B(r,"KYNVER_AGENT_OS_SLUG");return c&&t.push(`KYNVER_AGENT_OS_SLUG=${c} is a workspace slug, not box identity \u2014 set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND (defaulting box kind to forge)`),{boxKind:"forge",source:"default",slugInferenceBlocked:!!c,warnings:t}}var _=a(()=>{"use strict"});function ce(r,e){return r==="forge"?4:Math.max(1,e)}function F(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var $=a(()=>{"use strict"});var Be=a(()=>{"use strict"});var zn,Xn,le=a(()=>{"use strict";zn=25*1024*1024*1024,Xn=12*1024*1024*1024});var to,no,Fe=a(()=>{"use strict";le();to=5*1024*1024*1024,no=10*1024*1024*1024});var lo,uo,ue=a(()=>{"use strict";Fe();le();lo=30*1024*1024*1024,uo=15*1024*1024*1024});var me=a(()=>{"use strict";pe();p()});var $e=a(()=>{"use strict";me();p()});var He=a(()=>{"use strict"});var je=a(()=>{"use strict";He();p()});var Ye=a(()=>{"use strict"});var Ve=a(()=>{"use strict";Ye()});var Ge=a(()=>{"use strict";Ve();p()});var qe=a(()=>{"use strict"});var Je=a(()=>{"use strict"});var ze=a(()=>{"use strict"});var fe=a(()=>{"use strict"});var Xe=a(()=>{"use strict"});var Qe=a(()=>{"use strict";fe();Xe()});var Ze=a(()=>{"use strict";je();Ge();qe();Je();se();ze();Qe();fe();p()});var er=a(()=>{"use strict";Ze()});function rr(r,e={}){let t=e.perWorkerMemBytes??ge,n=e.memReserveBytes??ye,o=e.memUtilization??he,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,H)}var ge,ye,he,H,tr=a(()=>{"use strict";Be();v();_();$();j();ue();me();$e();er();p();ge=500*1024*1024,ye=4*1024*1024*1024,he=.85,H=64});function L(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function Re(r){let e=r.config??{},t=r.env??process.env,n=L(e.perWorkerMemBytes,ge),o=L(e.memReserveBytes,ye),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):he)),i=rr(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:L(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let u=L(e.maxConcurrentWorkers,0)||null;if(u)return{configuredMaxWorkers:Math.min(u,H),autoCap:i,workerCapSource:"config"}}let l=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&L(t.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,H),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var j=a(()=>{"use strict";tr()});import{homedir as dt}from"node:os";import mt from"node:path";var nr,Se=a(()=>{"use strict";nr=mt.join(dt(),".kynver",".env")});var or=a(()=>{"use strict"});var sr=a(()=>{"use strict";or()});var ir=a(()=>{"use strict"});var be=a(()=>{"use strict";sr();ir()});var ar=a(()=>{"use strict"});var cr=a(()=>{"use strict";ar()});var Y=a(()=>{"use strict";Se();P();v();be();cr()});var lr=a(()=>{"use strict";_();_()});var ur=a(()=>{"use strict";Se();be();Y()});import{existsSync as y,mkdirSync as yt,readdirSync as V,renameSync as dr,statSync as ht}from"node:fs";import h from"node:path";function pr(r){try{return ht(r).isDirectory()}catch{return!1}}function Rt(r){if(!y(r))return!0;for(let e of mr){let t=h.join(r,e);if(y(t)&&(!pr(t)||V(t).length>0))return!1}return!0}function St(r){let e=h.join(r,"runs");if(!y(e)||!pr(e))return!1;for(let t of V(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=h.join(e,t.name,"run.json");if(N(n,void 0)?.id)return!0}return!1}function bt(r){let e=h.join(r,"runs");if(!y(e))return!1;for(let t of V(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(N(h.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function kt(r){let e=h.join(r,"ghost");return y(e)?!y(h.join(e,"runs")):bt(r)}function fr(r){return St(r.sharedRoot)?Rt(r.forgeRoot)?kt(r.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function gr(r,e){yt(e,{recursive:!0});for(let t of mr){let n=h.join(r,t),o=h.join(e,t);if(y(n)){if(y(o)&&V(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(y(o)){dr(n,o);continue}dr(n,o)}}}var mr,yr=a(()=>{"use strict";p();mr=["runs","worktrees"]});import{existsSync as m}from"node:fs";import{homedir as xt}from"node:os";import d from"node:path";function ke(r=process.env){return r.HOME?.trim()||xt()}function xe(r=process.env){return d.join(ke(r),".kynver","harness")}function G(r){let e=d.resolve(ie(r.trim()));for(;_t.has(d.basename(e));)e=d.dirname(e);return e}function vt(r,e=process.env){return d.join(xe(e),r)}function Et(r=process.env){let e=xe(r);if(m(d.join(e,"runs")))return!0;if(m(e)&&!m(d.join(e,"ghost"))&&!m(d.join(e,"forge")))return m(e);let t=d.join(ke(r),hr);return m(t)}function q(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:G(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:G(n),source:"config"};let o=vt(r.boxKind,e);if(m(d.join(o,"runs"))||m(o)&&!Ct(o))return{harnessRoot:o,source:"box_scoped"};let i=xe(e);if(r.boxKind==="forge"){let c=fr({sharedRoot:i,forgeRoot:o});if(c.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:c.blocker};if(c.action==="migrate")return r.allowForgeLegacyMigration!==!1&&gr(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Et(e)){if(m(d.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(m(i)&&!m(d.join(i,"ghost"))&&!m(d.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=d.join(ke(e),hr);if(m(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Ct(r){if(!m(r))return!0;for(let e of["runs","worktrees"]){let t=d.join(r,e);if(m(t))return!1}return!0}var hr,_t,_e=a(()=>{"use strict";P();yr();hr=d.join(".openclaw","harness");_t=new Set(["runs","worktrees"])});import Rr from"node:os";function J(r){return r?.trim()?r.trim():null}function At(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Ot(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function z(r=S(),e=process.env,t={}){let n=O(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||J(e.KYNVER_BOX_KIND)),c=t.strict===!0||Ot(e);if((t.requireExplicitBoxKind||c)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup --box-kind forge|ghost` before dispatch"),n.slugInferenceBlocked&&!i){let Z="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";c||t.requireExplicitBoxKind?s.push(Z):o.push(`${Z} \u2014 defaulting box kind to forge`)}let l=J(r.runnerId),u=J(e.KYNVER_RUNTIME_ID)??J(e.OPENCLAW_RUNTIME_ID),g=l??u??At(n.boxKind,Rr.hostname()),C=l?"config":u?"env":"derived";C==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${g}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let I=Re({config:r,env:e,totalMemBytes:Rr.totalmem()}),Q=F(n.boxKind,I.configuredMaxWorkers??ce(n.boxKind,I.autoCap)),k=q({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return k.migrationBlocker&&s.push(k.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:g,runnerIdSource:C,maxConcurrentWorkers:Q,workerCapSource:I.workerCapSource,harnessRoot:k.harnessRoot,harnessRootSource:k.source},errors:s,warnings:o}}var X=a(()=>{"use strict";v();_();$();j();_e()});var Sr=a(()=>{"use strict";ae();_();lr();v();Y();ur();p();X()});import{existsSync as Nt,mkdirSync as ca,readFileSync as Pt,writeFileSync as la}from"node:fs";import{homedir as Lt,totalmem as da}from"node:os";import ve from"node:path";function S(){if(!Nt(br))return{};try{return JSON.parse(Pt(br,"utf8"))}catch{return{}}}var kr,br,_a,va,Ea,v=a(()=>{"use strict";ae();P();p();_();$();j();ue();Y();Sr();X();kr=ve.join(Lt(),".kynver"),br=ve.join(kr,"config.json"),_a=ve.join(kr,"credentials");va=500*1024*1024,Ea=4*1024*1024*1024});function xr(r){return G(r)}function _r(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return xr(r);let e=S(),t=e.harnessRoot?.trim();if(t)return xr(t);let n=z(e,process.env);return n.identity?n.identity.harnessRoot:q({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}var pe=a(()=>{"use strict";v();_e();X();p()});import{existsSync as Nr,realpathSync as Pr,readFileSync as Lr}from"node:fs";import Pe from"node:path";var Dr=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),Mr=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Ur(){try{return Lr("/proc/self/mounts","utf8")}catch{return null}}function Wr(r){let e=Pe.resolve(r);for(let t=0;t<64;t+=1){if(Nr(e))try{return Pr.native(e)}catch{return e}let n=Pe.dirname(e);if(n===e)return e;e=n}return e}function Kr(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Br(r){let e=[];for(let t of r.split(`
3
- `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Kr(n[1]),fsType:n[2]})}return e}function Fr(r,e){let t=null;for(let n of e){let o=n.mountPoint.endsWith("/")?n.mountPoint:`${n.mountPoint}/`;(r===n.mountPoint||`${r}/`.startsWith(o))&&(!t||n.mountPoint.length>t.mountPoint.length)&&(t=n)}return t}function re(r,e){let n=(e?.resolveRealPath??Wr)(r),o=(e?.mountsSource??Ur)();if(o===null)return{verdict:"rejected",reason:"Mount information unavailable \u2014 the filesystem type cannot be established safely, so WAL mode is refused (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let s=Fr(n,Br(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return Mr.has(i)||i.startsWith("fuse.")?{verdict:"rejected",reason:`Filesystem '${i}' is network-like or crosses an OS boundary; SQLite WAL locking is not safe there.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:Dr.has(i)?{verdict:"accepted",reason:`Local filesystem '${i}' accepted for WAL mode.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:{verdict:"rejected",reason:`Filesystem '${i}' is unknown to the qualification policy; WAL mode is refused rather than guessed (fail closed).`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}}var te=1,K=class extends Error{constructor(e,t){super(`local-run-store schema version ${e} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},$r=[`CREATE TABLE IF NOT EXISTS local_meta (
1
+ var c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{existsSync as vs,mkdirSync as on,readFileSync as sn,readdirSync as _s,renameSync as an,rmSync as cn,statSync as xs,writeFileSync as ln}from"node:fs";import{randomBytes as un}from"node:crypto";import dn from"node:path";function br(r){console.error(r),process.exit(1)}function z(r,e){try{return JSON.parse(sn(r,"utf8"))}catch(t){if(arguments.length>1)return e;br(`failed to read ${r}: ${t.message}`)}}function Ae(r,e){on(dn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${un(4).toString("hex")}.tmp`;try{ln(t,`${JSON.stringify(e,null,2)}
2
+ `),an(t,r)}catch(n){try{cn(t,{force:!0})}catch{}throw n}}function Oe(r){return String(r).replace(/\/+$/,"")}var k=c(()=>{"use strict"});var mn,Os,pn,ws,kr=c(()=>{"use strict";mn=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],Os=new Set(mn),pn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"],ws=new Set(pn)});var we=c(()=>{"use strict";k();kr()});import{homedir as vr}from"node:os";import _r from"node:path";function fn(r){return r==="~"?vr():r.startsWith("~/")||r.startsWith("~\\")?_r.join(vr(),r.slice(2)):r}function Ie(r){return _r.resolve(fn(r))}var X=c(()=>{"use strict"});var Te=c(()=>{"use strict";we();X()});function F(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"forge"}function ne(r,e){return r[e]?.trim()||null}function xr(r){let e=r?.split(":")[0]?.trim();return e?F(e):null}function Y(r=process.env,e={}){let t=[],n=xr(e.boxId),o=xr(ne(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ne(r,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ne(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:F(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let a=ne(r,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND (defaulting box kind to forge)`),{boxKind:"forge",source:"default",slugInferenceBlocked:!!a,warnings:t}}var M=c(()=>{"use strict"});function Ne(r,e){return r==="forge"?4:Math.max(1,e)}function oe(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var se=c(()=>{"use strict"});var Er=c(()=>{"use strict"});var Gs,Js,Pe=c(()=>{"use strict";Gs=25*1024*1024*1024,Js=12*1024*1024*1024});var Zs,ei,Cr=c(()=>{"use strict";Pe();Zs=5*1024*1024*1024,ei=10*1024*1024*1024});var ii,ai,Le=c(()=>{"use strict";Cr();Pe();ii=30*1024*1024*1024,ai=15*1024*1024*1024});function Ar(){return wr()}var ie=c(()=>{"use strict";Me();k()});var Ir=c(()=>{"use strict";ie();k()});var Tr=c(()=>{"use strict"});var Nr=c(()=>{"use strict";Tr();k()});var Pr=c(()=>{"use strict"});var Lr=c(()=>{"use strict";Pr()});var Dr=c(()=>{"use strict";Lr();k()});var Mr=c(()=>{"use strict"});var Fr=c(()=>{"use strict"});var Kr=c(()=>{"use strict"});var Fe=c(()=>{"use strict"});var Br=c(()=>{"use strict"});var Wr=c(()=>{"use strict";Fe();Br()});var Ur=c(()=>{"use strict";Nr();Dr();Mr();Fr();we();Kr();Wr();Fe();k()});var $r=c(()=>{"use strict";Ur()});function Hr(r,e={}){let t=e.perWorkerMemBytes??Ke,n=e.memReserveBytes??Be,o=e.memUtilization??We,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ae)}var Ke,Be,We,ae,jr=c(()=>{"use strict";Er();I();M();se();ce();Le();ie();Ir();$r();k();Ke=500*1024*1024,Be=4*1024*1024*1024,We=.85,ae=64});function Q(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function Ue(r){let e=r.config??{},t=r.env??process.env,n=Q(e.perWorkerMemBytes,Ke),o=Q(e.memReserveBytes,Be),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):We)),i=Hr(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Q(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let l=Q(e.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,ae),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Q(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,ae),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ce=c(()=>{"use strict";jr()});import{homedir as bn}from"node:os";import kn from"node:path";var Yr,$e=c(()=>{"use strict";Yr=kn.join(bn(),".kynver",".env")});var Vr=c(()=>{"use strict"});var Gr=c(()=>{"use strict";Vr()});var Jr=c(()=>{"use strict"});var He=c(()=>{"use strict";Gr();Jr()});var qr=c(()=>{"use strict"});var zr=c(()=>{"use strict";qr()});var le=c(()=>{"use strict";$e();X();I();He();zr()});var Xr=c(()=>{"use strict";M();M()});var Qr=c(()=>{"use strict";$e();He();le()});import{existsSync as T,mkdirSync as En,readdirSync as ue,renameSync as Zr,statSync as Cn}from"node:fs";import N from"node:path";function rt(r){try{return Cn(r).isDirectory()}catch{return!1}}function An(r){if(!T(r))return!0;for(let e of et){let t=N.join(r,e);if(T(t)&&(!rt(t)||ue(t).length>0))return!1}return!0}function On(r){let e=N.join(r,"runs");if(!T(e)||!rt(e))return!1;for(let t of ue(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(z(n,void 0)?.id)return!0}return!1}function wn(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of ue(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(z(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function In(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):wn(r)}function tt(r){return On(r.sharedRoot)?An(r.forgeRoot)?In(r.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function nt(r,e){En(e,{recursive:!0});for(let t of et){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&ue(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Zr(n,o);continue}Zr(n,o)}}}var et,ot=c(()=>{"use strict";k();et=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as Tn}from"node:os";import S from"node:path";function je(r=process.env){return r.HOME?.trim()||Tn()}function Ye(r=process.env){return S.join(je(r),".kynver","harness")}function de(r){let e=S.resolve(Ie(r.trim()));for(;Nn.has(S.basename(e));)e=S.dirname(e);return e}function Pn(r,e=process.env){return S.join(Ye(e),r)}function Ln(r=process.env){let e=Ye(r);if(b(S.join(e,"runs")))return!0;if(b(e)&&!b(S.join(e,"ghost"))&&!b(S.join(e,"forge")))return b(e);let t=S.join(je(r),st);return b(t)}function me(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:de(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:de(n),source:"config"};let o=Pn(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!Dn(o))return{harnessRoot:o,source:"box_scoped"};let i=Ye(e);if(r.boxKind==="forge"){let a=tt({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return r.allowForgeLegacyMigration!==!1&&nt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Ln(e)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(je(e),st);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Dn(r){if(!b(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(b(t))return!1}return!0}var st,Nn,Ve=c(()=>{"use strict";X();ot();st=S.join(".openclaw","harness");Nn=new Set(["runs","worktrees"])});import it from"node:os";function pe(r){return r?.trim()?r.trim():null}function Mn(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Fn(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function fe(r=x(),e=process.env,t={}){let n=Y(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||pe(e.KYNVER_BOX_KIND)),a=t.strict===!0||Fn(e);if((t.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup --box-kind forge|ghost` before dispatch"),n.slugInferenceBlocked&&!i){let $="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push($):o.push(`${$} \u2014 defaulting box kind to forge`)}let u=pe(r.runnerId),l=pe(e.KYNVER_RUNTIME_ID)??pe(e.OPENCLAW_RUNTIME_ID),m=u??l??Mn(n.boxKind,it.hostname()),p=u?"config":l?"env":"derived";p==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${m}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Ue({config:r,env:e,totalMemBytes:it.totalmem()}),U=oe(n.boxKind,d.configuredMaxWorkers??Ne(n.boxKind,d.autoCap)),v=me({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:m,runnerIdSource:p,maxConcurrentWorkers:U,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var ge=c(()=>{"use strict";I();M();se();ce();Ve()});var at=c(()=>{"use strict";Te();M();Xr();I();le();Qr();k();ge()});import{existsSync as lt,mkdirSync as Wn,readFileSync as ut,writeFileSync as Un}from"node:fs";import{homedir as $n,totalmem as tl}from"node:os";import Je from"node:path";function x(){if(!lt(ct))return{};try{return JSON.parse(ut(ct,"utf8"))}catch{return{}}}function dt(){if(!lt(Ge))return{};try{return JSON.parse(ut(Ge,"utf8"))}catch{return{}}}function Hn(r){Wn(qe,{recursive:!0}),Un(Ge,`${JSON.stringify(r,null,2)}
3
+ `,{mode:384})}function mt(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:dt().apiKey}function jn(r,e){Hn({...dt(),runnerToken:e,runnerTokenAgentOsId:r})}function Yn(r){let e=pt(r);return e||Gn("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function pt(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||x().apiBaseUrl;return e?Oe(String(e)):void 0}async function ft(r,e,t){let n=mt(),o=pt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!e)return{ok:!1,reason:"agentOsId is required to refresh a rejected runner token"};if(!o)return{ok:!1,reason:"KYNVER_API_URL or --base-url is required to refresh a rejected runner token"};try{let s=await Vn(e,{baseUrl:o,apiKey:n});return s&&s!==r?(jn(e,s),{ok:!0,token:s}):{ok:!1,reason:"runner credential refresh returned the rejected token"}}catch(s){return{ok:!1,reason:s.message}}}async function Vn(r,e){let t=e?.apiKey||mt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Yn(e?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(r)}/runner-credentials`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({})}),i=await s.text(),a=null;try{a=JSON.parse(i)}catch{a=null}if(!s.ok||!a?.token)throw new Error(`runner credential mint failed (${s.status}): ${a?.error??i.slice(0,200)}`);return a.token}function Gn(r){console.error(r),process.exit(1)}var qe,ct,Ge,fl,gl,I=c(()=>{"use strict";Te();X();k();M();se();ce();Le();le();at();ge();qe=Je.join($n(),".kynver"),ct=Je.join(qe,"config.json"),Ge=Je.join(qe,"credentials");fl=500*1024*1024,gl=4*1024*1024*1024});import gt from"node:path";function he(r){return de(r)}function ze(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return he(r);let e=x(),t=e.harnessRoot?.trim();if(t)return he(t);let n=fe(e,process.env);return n.identity?n.identity.harnessRoot:me({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Or(r){return gt.join(he(r),"runs")}function Jn(r){return gt.join(he(r),"worktrees")}function wr(){let r=ze();return{harnessRoot:r,runsDir:Or(r),worktreesDir:Jn(r)}}var Me=c(()=>{"use strict";I();Ve();ge();k()});import{existsSync as Kt,realpathSync as Bt,readFileSync as Wt}from"node:fs";import Rr from"node:path";var Ut=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),$t=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Ht(){try{return Wt("/proc/self/mounts","utf8")}catch{return null}}function jt(r){let e=Rr.resolve(r);for(let t=0;t<64;t+=1){if(Kt(e))try{return Bt.native(e)}catch{return e}let n=Rr.dirname(e);if(n===e)return e;e=n}return e}function Yt(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Vt(r){let e=[];for(let t of r.split(`
4
+ `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Yt(n[1]),fsType:n[2]})}return e}function Gt(r,e){let t=null;for(let n of e){let o=n.mountPoint.endsWith("/")?n.mountPoint:`${n.mountPoint}/`;(r===n.mountPoint||`${r}/`.startsWith(o))&&(!t||n.mountPoint.length>t.mountPoint.length)&&(t=n)}return t}function xe(r,e){let n=(e?.resolveRealPath??jt)(r),o=(e?.mountsSource??Ht)();if(o===null)return{verdict:"rejected",reason:"Mount information unavailable \u2014 the filesystem type cannot be established safely, so WAL mode is refused (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let s=Gt(n,Vt(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return $t.has(i)||i.startsWith("fuse.")?{verdict:"rejected",reason:`Filesystem '${i}' is network-like or crosses an OS boundary; SQLite WAL locking is not safe there.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:Ut.has(i)?{verdict:"accepted",reason:`Local filesystem '${i}' accepted for WAL mode.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:{verdict:"rejected",reason:`Filesystem '${i}' is unknown to the qualification policy; WAL mode is refused rather than guessed (fail closed).`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}}var Ee=1,te=class extends Error{constructor(e,t){super(`local-run-store schema version ${e} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},Jt=[`CREATE TABLE IF NOT EXISTS local_meta (
4
5
  key TEXT PRIMARY KEY,
5
6
  value TEXT NOT NULL
6
7
  ) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
@@ -26,7 +27,7 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
26
27
  payload_json TEXT NOT NULL,
27
28
  created_at TEXT NOT NULL,
28
29
  PRIMARY KEY (scope, seq)
29
- ) STRICT`];function Hr(r){if(!r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=r.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!t?.value)return null;let n=Number.parseInt(t.value,10);return Number.isFinite(n)?n:null}function Le(r,e){let t=Hr(r);if(t!==null&&t>1)throw new K(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of $r)r.exec(n);r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}}import{mkdirSync as jr}from"node:fs";import Yr from"node:path";import{DatabaseSync as Vr}from"node:sqlite";var T=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Gr="local-run-store.sqlite",qr=5e3,A=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=re(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new T(t.reason);jr(e.directory,{recursive:!0,mode:448});let n=Yr.join(e.directory,e.filename??Gr),o=new Vr(n,{timeout:e.busyTimeoutMs??qr}),s=e.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new T(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Le(o,s().toISOString())}catch(i){throw o.close(),i}return new r(o,n,s)}inImmediateTransaction(e){this.db.exec("BEGIN IMMEDIATE");try{let t=e();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(e){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
30
+ ) STRICT`];function qt(r){if(!r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=r.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!t?.value)return null;let n=Number.parseInt(t.value,10);return Number.isFinite(n)?n:null}function Sr(r,e){let t=qt(r);if(t!==null&&t>1)throw new te(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Jt)r.exec(n);r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}}import{mkdirSync as zt}from"node:fs";import Xt from"node:path";import{DatabaseSync as Qt}from"node:sqlite";var q=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Zt="local-run-store.sqlite",en=5e3,j=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=xe(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new q(t.reason);zt(e.directory,{recursive:!0,mode:448});let n=Xt.join(e.directory,e.filename??Zt),o=new Qt(n,{timeout:e.busyTimeoutMs??en}),s=e.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new q(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Sr(o,s().toISOString())}catch(i){throw o.close(),i}return new r(o,n,s)}inImmediateTransaction(e){this.db.exec("BEGIN IMMEDIATE");try{let t=e();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(e){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
30
31
  (process_key, pid, runtime_version, node_version, started_at, registered_at)
31
32
  VALUES (?, ?, ?, ?, ?, ?)
32
33
  ON CONFLICT(process_key) DO UPDATE SET
@@ -35,16 +36,23 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
35
36
  node_version = excluded.node_version,
36
37
  started_at = excluded.started_at,
37
38
  registered_at = excluded.registered_at`).run(e.processKey,e.pid,e.runtimeVersion,e.nodeVersion,e.startedAt,t)}),{...e,registeredAt:t}}getProcessIdentity(e){let t=this.db.prepare(`SELECT process_key, pid, runtime_version, node_version, started_at, registered_at
38
- FROM process_identity WHERE process_key = ?`).get(e);return t?{processKey:t.process_key,pid:t.pid,runtimeVersion:t.runtime_version,nodeVersion:t.node_version,startedAt:t.started_at,registeredAt:t.registered_at}:null}tryReserveAdmission(e,t,n,o){let s=o??this.now(),i=new Date(s.getTime()+n).toISOString();return this.inImmediateTransaction(()=>{let c=this.db.prepare("SELECT reservation_key, owner, expires_at FROM admission_reservations WHERE reservation_key = ?").get(e);return c&&c.expires_at>s.toISOString()&&c.owner!==t?{acquired:!1,current:{key:e,owner:c.owner,expiresAt:c.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
39
+ FROM process_identity WHERE process_key = ?`).get(e);return t?{processKey:t.process_key,pid:t.pid,runtimeVersion:t.runtime_version,nodeVersion:t.node_version,startedAt:t.started_at,registeredAt:t.registered_at}:null}tryReserveAdmission(e,t,n,o){let s=o??this.now(),i=new Date(s.getTime()+n).toISOString();return this.inImmediateTransaction(()=>{let a=this.db.prepare("SELECT reservation_key, owner, expires_at FROM admission_reservations WHERE reservation_key = ?").get(e);return a&&a.expires_at>s.toISOString()&&a.owner!==t?{acquired:!1,current:{key:e,owner:a.owner,expiresAt:a.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
39
40
  VALUES (?, ?, ?, ?)
40
41
  ON CONFLICT(reservation_key) DO UPDATE SET
41
42
  owner = excluded.owner,
42
- expires_at = excluded.expires_at`).run(e,t,i,s.toISOString()),{acquired:!0,current:{key:e,owner:t,expiresAt:i}})})}releaseAdmission(e,t){return this.inImmediateTransaction(()=>{let n=this.db.prepare("DELETE FROM admission_reservations WHERE reservation_key = ? AND owner = ?").run(e,t);return Number(n.changes)>0})}recordOperationReceipt(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare(`INSERT INTO operation_receipts (idempotency_key, operation, result_json, recorded_at)
43
+ expires_at = excluded.expires_at`).run(e,t,i,s.toISOString()),{acquired:!0,current:{key:e,owner:t,expiresAt:i}})})}releaseAdmission(e,t){return this.inImmediateTransaction(()=>{let n=this.db.prepare("DELETE FROM admission_reservations WHERE reservation_key = ? AND owner = ?").run(e,t);return Number(n.changes)>0})}listAdmissionReservations(e){let t=Math.floor(e?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(e?.keyPrefix){let u=e.keyPrefix.replace(/[\\%_]/g,l=>`\\${l}`);o.push("reservation_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}e?.includeExpired||(o.push("expires_at > ?"),s.push((e?.now??this.now()).toISOString()));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT reservation_key, owner, expires_at
44
+ FROM admission_reservations ${i}
45
+ ORDER BY expires_at ASC, reservation_key ASC
46
+ LIMIT ?`).all(...s,n).map(u=>({key:u.reservation_key,owner:u.owner,expiresAt:u.expires_at}))}recordOperationReceipt(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare(`INSERT INTO operation_receipts (idempotency_key, operation, result_json, recorded_at)
43
47
  VALUES (?, ?, ?, ?)
44
- ON CONFLICT(idempotency_key) DO NOTHING`).run(e.idempotencyKey,e.operation,e.resultJson??null,this.now().toISOString());return{deduplicated:Number(t.changes)===0}})}listOperationReceipts(e){let t=Math.floor(e?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(e?.operation&&(o.push("operation = ?"),s.push(e.operation)),e?.keyPrefix){let l=e.keyPrefix.replace(/[\\%_]/g,u=>`\\${u}`);o.push("idempotency_key LIKE ? ESCAPE '\\'"),s.push(`${l}%`)}e?.recordedAfter&&(o.push("recorded_at > ?"),s.push(e.recordedAfter));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
48
+ ON CONFLICT(idempotency_key) DO NOTHING`).run(e.idempotencyKey,e.operation,e.resultJson??null,this.now().toISOString());return{deduplicated:Number(t.changes)===0}})}listOperationReceipts(e){let t=Math.floor(e?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(e?.operation&&(o.push("operation = ?"),s.push(e.operation)),e?.keyPrefix){let u=e.keyPrefix.replace(/[\\%_]/g,l=>`\\${l}`);o.push("idempotency_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}e?.recordedAfter&&(o.push("recorded_at > ?"),s.push(e.recordedAfter));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
45
49
  FROM operation_receipts ${i}
46
50
  ORDER BY recorded_at ASC, idempotency_key ASC
47
- LIMIT ?`).all(...s,n).map(l=>({idempotencyKey:l.idempotency_key,operation:l.operation,resultJson:l.result_json,recordedAt:l.recorded_at}))}deleteOperationReceiptsByKeys(e){return e.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of e)n+=Number(t.run(o).changes);return n})}getOperationReceipt(e){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
51
+ LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(e){return e.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of e)n+=Number(t.run(o).changes);return n})}getOperationReceipt(e){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
48
52
  FROM operation_receipts WHERE idempotency_key = ?`).get(e);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(e.scope),n=Number(t.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
49
53
  VALUES (?, ?, ?, ?)`).run(e.scope,n,e.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(e){let t=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
50
- WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(e);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as Jr,renameSync as zr}from"node:fs";function Xr(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Jr(o)&&zr(o,`${t}${n}`)}return t}function ne(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=A.open(r);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=Xr(n,e);try{return{store:A.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}pe();function Dt(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function Mt(){return vr.classifyOptions??Dt()}var vr={};function Ut(r){vr=r}var Er=300*1e3,R=null,D=0;function Wt(r){D+=1;try{let e=Mt(),t=ne({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:D},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:D},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function Kt(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=Er}function E(r=Date.now()){let e=_r();return(!R||R.status.harnessRoot!==e||Kt(R,r))&&(Ce(),R=Wt(e)),R.store}function Cr(){return R?R.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:D}}function Ee(){return E(),Cr()}function Ce(){try{R?.store?.close()}catch{}R=null}function Bt(){Ce(),D=0}v();p();import{existsSync as Ft,readFileSync as $t}from"node:fs";import{homedir as Ht}from"node:os";import jt from"node:path";var Yt=3e4,f=null;function Ae(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return jt.join(Ht(),".kynver",`local-run-store-flags-${e}.json`)}function Oe(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function Vt(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:Oe(t)}function Gt(r,e){try{let t=Ae(r),n={contractVersion:1,agentOsId:r,flags:Oe(e),deliveredAt:new Date().toISOString()};oe(t,n),f={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function we(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(f&&r-f.loadedAtMs<Yt)return f.flags;try{let e=S().agentOsId?.trim();if(!e)return f={flags:{},loadedAtMs:r,file:null},f.flags;let t=Ae(e);if(!Ft(t))return f={flags:{},loadedAtMs:r,file:t},f.flags;let n=JSON.parse($t(t,"utf8")),o=n?.contractVersion===1?Oe(n.flags):{};return f={flags:o,loadedAtMs:r,file:t},o}catch{return f={flags:{},loadedAtMs:r,file:null},f.flags}}function qt(){f=null}var Ar=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function Or(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function w(r=process.env){let e={},t={},n=[],o=we();for(let s of Ar){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let u=Or(i);e[s.key]=u.mode,t[s.key]="env",u.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let l=o[s.key];if(l){e[s.key]=l,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function Jt(r){return Object.values(r).some(e=>e!=="off")}var b={storeFailures:0,completionReplaysObserved:0};function wr(r=process.env){return w(r).flags.dispatchReceipts}function Ie(r){return wr(r)!=="off"}function Ir(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function M(r,e,t){if(!Ie())return;let n=E();if(n)try{n.recordOperationReceipt({idempotencyKey:Ir(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{b.storeFailures+=1}}function zt(r){M("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function Xt(r){M("spawned",r)}function Qt(r,e){M("released",r,{reasonClass:e})}function Zt(r){M("completion-sent",r)}function en(r,e){M("completion-acked",r,{outcome:e})}function rn(r){if(!Ie())return!1;let e=E();if(!e)return!1;try{let t=e.getOperationReceipt(Ir("completion-acked",r));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return b.completionReplaysObserved+=1,!0}}catch{b.storeFailures+=1}return!1}function tn(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}var nn=900*1e3,on=10080*60*1e3,sn=1440*60*1e3,an=500,cn=300;function Te(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!Ie())return e;let t=E();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??nn;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-on).toISOString(),limit:an}),i=0,c=[];for(let u of s){let g=u.idempotencyKey.slice(15),C=Date.parse(u.recordedAt);if(!Number.isFinite(C)||n-C<o)continue;let I=t.getOperationReceipt(`dispatch:spawned:${g}`),Q=t.getOperationReceipt(`dispatch:released:${g}`);if(I||Q){n-C>=sn&&c.length+5<=cn&&c.push(u.idempotencyKey,`dispatch:spawned:${g}`,`dispatch:released:${g}`,`dispatch:completion-sent:${g}`,`dispatch:completion-acked:${g}`);continue}let k=g.split(":")[0]??"";if((k?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${k}:`,limit:1}):[]).length>0)continue;let ee=!1;if(r?.hasLiveWorker&&u.resultJson)try{let W=JSON.parse(u.resultJson);W.runId&&W.workerName&&(ee=r.hasLiveWorker({runId:W.runId,workerName:W.workerName}))}catch{ee=!1}ee||(i+=1)}let l=c.length>0?t.deleteOperationReceiptsByKeys(c):0;return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return b.storeFailures+=1,e}}function Ne(){return{"dispatchReceipts.storeFailures":b.storeFailures,"dispatchReceipts.completionReplaysObserved":b.completionReplaysObserved}}function ln(){b.storeFailures=0,b.completionReplaysObserved=0}var qa=600*1e3,U={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Tr(){return{"planOutbox.storeFailures":U.storeFailures,"planOutbox.corruptItemsSeen":U.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":U.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":U.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":U.halfArchivesCompleted}}function un(r){let e=Ee(),t=w(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,Ne());let s=Te({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates}return t.flags.planOutbox!=="off"&&Object.assign(o,Tr()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{T as FilesystemPolicyError,Er as LOCAL_RUN_STORE_OPEN_RETRY_MS,Ar as LOCAL_RUN_STORE_SURFACES,te as LOCAL_SCHEMA_VERSION,K as SchemaDowngradeRefusedError,A as SqliteLocalRunStore,ln as __resetDispatchReceiptCountersForTests,Bt as __resetLocalRunStoreLifecycleForTests,qt as __resetRemoteSurfaceFlagsCacheForTests,Ut as __setLocalRunStoreLifecycleTestOverrides,Jt as anyLocalRunStoreSurfaceActive,un as buildLocalRunStoreTickPosture,re as classifyDatabaseDirectory,Ce as closeLocalRunStore,Ne as dispatchReceiptCounters,wr as dispatchReceiptsMode,Vt as extractLocalRunStoreFlagsFromOperatorTickResponse,E as getLocalRunStore,Cr as getLocalRunStoreLifecycleStatus,we as getRemoteSurfaceFlags,rn as noteCompletionReplayIfAcked,ne as openSqliteLocalRunStoreWithRecovery,Or as parseLocalRunStoreSurfaceMode,Gt as persistRemoteSurfaceFlags,Ee as probeLocalRunStore,en as recordCompletionAckedReceipt,Zt as recordCompletionSentReceipt,zt as recordDispatchClaimReceipt,Qt as recordDispatchReleasedReceipt,Xt as recordDispatchSpawnedReceipt,tn as releaseReasonClass,Ae as remoteSurfaceFlagsPath,w as resolveLocalRunStoreSurfaceFlags,Te as scanDispatchReceiptInvariants};
54
+ WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(e);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as rn,renameSync as tn}from"node:fs";function nn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;rn(o)&&tn(o,`${t}${n}`)}return t}function Ce(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=j.open(r);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=nn(n,e);try{return{store:j.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Me();function qn(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function zn(){return ht.classifyOptions??qn()}var ht={};function Xn(r){ht=r}var yt=300*1e3,P=null,Z=0;function Qn(r){Z+=1;try{let e=zn(),t=Ce({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:Z},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:Z},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function Zn(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=yt}function f(r=Date.now()){let e=ze();return(!P||P.status.harnessRoot!==e||Zn(P,r))&&(Qe(),P=Qn(e)),P.store}function Rt(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:Z}}function Xe(){return f(),Rt()}function Qe(){try{P?.store?.close()}catch{}P=null}function eo(){Qe(),Z=0}I();k();import{existsSync as ro,readFileSync as to}from"node:fs";import{homedir as no}from"node:os";import oo from"node:path";var so=3e4,_=null;function Ze(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return oo.join(no(),".kynver",`local-run-store-flags-${e}.json`)}function er(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function io(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:er(t)}function ao(r,e){try{let t=Ze(r),n={contractVersion:1,agentOsId:r,flags:er(e),deliveredAt:new Date().toISOString()};Ae(t,n),_={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function rr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(_&&r-_.loadedAtMs<so)return _.flags;try{let e=x().agentOsId?.trim();if(!e)return _={flags:{},loadedAtMs:r,file:null},_.flags;let t=Ze(e);if(!ro(t))return _={flags:{},loadedAtMs:r,file:t},_.flags;let n=JSON.parse(to(t,"utf8")),o=n?.contractVersion===1?er(n.flags):{};return _={flags:o,loadedAtMs:r,file:t},o}catch{return _={flags:{},loadedAtMs:r,file:null},_.flags}}function co(){_=null}var St=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function bt(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=rr();for(let s of St){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let l=bt(i);e[s.key]=l.mode,t[s.key]="env",l.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function lo(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function O(r=process.env){return A(r).flags.dispatchReceipts}function tr(r){return O(r)!=="off"}function nr(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function ee(r,e,t){if(!tr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:nr(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function uo(r){ee("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function or(r){ee("spawned",r)}function ye(r,e){ee("released",r,{reasonClass:e})}function mo(r){ee("completion-sent",r)}function po(r,e){ee("completion-acked",r,{outcome:e})}function fo(r){if(!tr())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(nr("completion-acked",r));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function go(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function ho(r){if(O()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(nr("completion-acked",r));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var yo=600*1e3;function Ro(r,e){if(O()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function So(r,e){if(O()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??yo;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function V(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var bo=900*1e3,kt=10080*60*1e3,ko=1440*60*1e3,vo=500,_o=300;function sr(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!tr())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??bo;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-kt).toISOString(),limit:vo}),i=0,a=[];for(let l of s){let m=l.idempotencyKey.slice(15),p=Date.parse(l.recordedAt);if(!Number.isFinite(p)||n-p<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${m}`),U=t.getOperationReceipt(`dispatch:released:${m}`);if(d||U){n-p>=ko&&a.length+5<=_o&&a.push(l.idempotencyKey,`dispatch:spawned:${m}`,`dispatch:released:${m}`,`dispatch:completion-sent:${m}`,`dispatch:completion-acked:${m}`);continue}let v=m.split(":")[0]??"",$=V(m.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(h=>{if($===null)return!0;let H=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),D=V(H);return D===null||D>=$}))continue;let y=!1;if(r?.hasLiveWorker&&l.resultJson)try{let h=JSON.parse(l.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=a.length>0?t.deleteOperationReceiptsByKeys(a):0;if(O()==="enforce"){let l=t.listOperationReceipts({limit:100}).filter(m=>{let p=Date.parse(m.recordedAt);return Number.isFinite(p)&&n-p>=kt}).map(m=>m.idempotencyKey);if(l.length>0){let m=t.deleteOperationReceiptsByKeys(l);u+=m,R.agedReceiptsPruned+=m}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function ir(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function xo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as No,readFileSync as Po}from"node:fs";var K=900*1e3,cr="admission-shadow",ar="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Re=!1;function Eo(){Re=!1}function B(r=process.env){return A(r).flags.admission}function Se(r,e){return`${ar}${r}:${e}`}function Co(r,e){if(B()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Se(r,e),cr,K)}catch{E.storeFailures+=1}}function lr(r,e){if(B()==="off")return;let t=f();if(t)try{t.releaseAdmission(Se(r,e),cr)}catch{E.storeFailures+=1}}function Ao(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(B()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Se(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:ar,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,a=o.filter(d=>!n.has(d.key)).length,u=!Re;Re=!0,!u&&i>0&&(E.missingForLive+=i);let l=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Se(d.runId,d.workerName),cr,K),l+=1;let m=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(m+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:ar,limit:500}).length,refreshed:l,deadReleased:m,missingForLive:i,orphaned:a,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function ur(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function Oo(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Re=!1}var ve="worker-slot-n:",be=64;function vt(r){return`${ve}${r}`}function ke(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function wo(r){if(B()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(be,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=ke(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(vt(o),n,K).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function dr(r,e){if(B()==="off")return;let t=f();if(t)try{let n=ke(r,e),o=t.listAdmissionReservations({keyPrefix:ve,limit:be});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function Io(r){let e={refreshed:0,deadReleased:0,adopted:0};if(B()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(l=>ke(l.runId,l.workerName))),o=t.listAdmissionReservations({keyPrefix:ve,limit:be}),s=0,i=0,a=new Set;for(let l of o)n.has(l.owner)?(t.tryReserveAdmission(l.key,l.owner,K),a.add(l.owner),s+=1):t.releaseAdmission(l.key,l.owner)&&(i+=1);let u=0;for(let l of r.liveWorkers){let m=ke(l.runId,l.workerName);if(!a.has(m)){for(let p=0;p<be;p+=1)if(t.tryReserveAdmission(vt(p),m,K).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function mr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function To(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Lo="dispatch:claim:",Do=900*1e3,Mo=10080*60*1e3,Fo=200,w={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function _t(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=No("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Po(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function pr(r){let e=O(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=f();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Do,i=r.findOrphanPid??_t,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Mo).toISOString(),limit:Fo})}catch{return w.recoveryStoreFailures+=1,t}for(let l of u){let m=l.idempotencyKey.slice(Lo.length),p=m.split(":")[0]??"",d=m.slice(p.length+1);if(!(!p||!d))try{let U=Date.parse(l.recordedAt);if(!Number.isFinite(U)||o-U<s||n.getOperationReceipt(`dispatch:spawned:${m}`)||n.getOperationReceipt(`dispatch:released:${m}`))continue;let v=V(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${p}:`,limit:10}).some(D=>{if(v===null)return!0;let J=V(D.idempotencyKey.slice(`dispatch:completion-acked:${p}:`.length));return J===null||J>=v}))continue;let G={};try{G=l.resultJson?JSON.parse(l.resultJson):{}}catch{G={}}let y=G.runId??null,h=G.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){or({taskId:p,leaseToken:d}),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let D=r.worktreePathFor({runId:y,workerName:h}),J=D?i(D):null;if(J!==null){w.recoveryDeferredOrphans+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${J} references ${D}`});continue}}if(!y){a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let H=await r.releaseClaim({taskId:p,leaseToken:d,runId:y});H.released?(ye({taskId:p,leaseToken:d},"restart_recovery"),h&&(lr(y,h),dr(y,h)),w.recoveredStrandedClaims+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"released"})):H.transportError?a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:H.detail}):(ye({taskId:p,leaseToken:d},"restart_recovery_refused"),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:H.detail}))}catch{w.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:a}}function fr(){return{"dispatchReceipts.recoveredStrandedClaims":w.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":w.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":w.recoveryStoreFailures}}function Ko(){w.recoveredStrandedClaims=0,w.recoveryDeferredOrphans=0,w.recoveryStoreFailures=0}ie();import Jo from"node:path";var Bo="kynver-harness:",Wo="@runner:";function xt(r,e){let t=r.trim(),n=e.trim();return`${Bo}${t}${Wo}${n}`}I();import At from"node:os";var Uo="embedded-1",$o=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],Ho={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete` and a structured finalResult object. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
55
+ `),"worker.prompt.progress.compact":"Plan progress: when planId is set, report progress with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`. Do not mark rows done from the worker CLI.","worker.prompt.progress.full":["Structured plan progress (required when planId is set):","- Report checkpoints with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`.","- When a slice is finished, emit `partial` with evidence (`--evidence pr:<url>`, `--evidence path:<file>`, or `--evidence command:<cmd>`).","- Do not propose or confirm row `done` from the worker CLI."].join(`
56
+ `),"worker.prompt.merge_gate.compact":"Verification cost control: prefer local verification before requesting CI runs; do not push empty commits to re-trigger CI; record verification evidence on the PR.","worker.prompt.merge_gate.full":["Verification cost control:","- Prefer local verification of touched paths before requesting any CI run.","- Do not push empty commits to re-trigger CI.","- Record verification evidence on the PR before requesting review."].join(`
57
+ `),"worker.prompt.plan_artifacts.compact":"Plan artifacts: when authoring or revising plan documents, open a GitHub PR early and iterate from that PR branch; do not leave the canonical plan only in a local worktree.","worker.prompt.plan_artifacts.full":["Plan artifacts (when authoring or revising plan documents):","- Create a feature branch and open a GitHub PR (draft OK) before substantial drafting; commit and push the plan file.","- Iterate on that PR branch and link the PR URL on the related task and progress evidence."].join(`
58
+ `)},jo={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Et={version:Uo,generatedAt:"1970-01-01T00:00:00.000Z",personas:$o,instructions:Ho,policyThresholds:jo};var Yo=Et;function Ct(){return Yo.version}M();function L(r){return r?.trim()?r.trim():null}function Ot(r={}){let e=r.env??process.env,t=x();return{runnerId:L(t.runnerId)??L(e.KYNVER_RUNTIME_ID)??L(e.OPENCLAW_RUNTIME_ID)??L(e.HOSTNAME)??At.hostname(),hostname:L(e.HOSTNAME)??At.hostname(),profile:L(e.KYNVER_RUNNER_PROFILE)??L(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:L(e.KYNVER_HARNESS_REPO)??L(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:Ct()}}function wt(r){let e=String(r).trim();return e.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":e}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":e,"X-OpenClaw-Cron-Secret":e,"X-Kynver-Runtime-Secret":e}}I();function Tt(r){if(r!==void 0&&Number.isFinite(r)&&r>0)return Math.floor(r);let e=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e4}async function Vo(r,e){let t=Tt(e),n=new AbortController,o;try{return await Promise.race([r(n.signal),new Promise((s,i)=>{o=setTimeout(()=>{n.abort(),i(new Error(`callback timeout after ${t}ms`))},t)})])}finally{o&&clearTimeout(o)}}function Go(r,e){let t=Tt(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function It(r,e,t,n){try{return await Vo(async o=>{let s=await fetch(r,{method:"POST",headers:wt(e),body:JSON.stringify(t),signal:o}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,response:i}},n?.timeoutMs)}catch(o){return Go(o,n?.timeoutMs)}}async function Nt(r,e,t,n){let o=await It(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await ft(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await It(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Pt(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Nt(e,r.secret,{agentOsId:r.agentOsId,leaseOwner:r.leaseOwner,...r.leaseToken?.trim()?{leaseToken:r.leaseToken.trim()}:{},...r.failureDetail?{failureDetail:r.failureDetail}:{}},{agentOsId:r.agentOsId,baseUrl:r.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var gr=!1;function qo(){gr=!1}async function zo(r){if(gr||O()!=="enforce")return null;gr=!0;try{let e=Ot().runnerId,t=await pr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Jo.join(Ar().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Pt({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:xt(s,e),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return t.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${t.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),t}catch{return null}}var bu=600*1e3,re={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Lt(){return{"planOutbox.storeFailures":re.storeFailures,"planOutbox.corruptItemsSeen":re.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":re.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":re.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":re.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function W(r){return A(process.env).flags[r]}var Dt="daemon-keeper",Xo=1800*1e3;function Qo(r){if(W("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:Dt,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function Zo(){if(W("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Dt);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>Xo)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function hr(r){return`mesh-cron-lease:${r}`}function es(r,e){if(W("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(hr(r));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(e.leaseToken??null)&&(o.holderBoxId??null)===(e.holderBoxId??null)&&o.authorized===e.authorized)return}t.saveRecoveryCheckpoint({scope:hr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function rs(r,e){let t=W("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(hr(r)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(e?.leaseToken??null)||(s.holderBoxId??null)!==(e?.holderBoxId??null)||(s.authorized??null)!==(e?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&e?.updatedAt&&s?.updatedAt&&Date.parse(e.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function _e(r){return`quota-cooldown:${r}`}var Mt="quota-preflight";function ts(r,e){if(W("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(_e(r),Mt,e)}catch{g.quotaStoreFailures+=1}}function ns(r){if(W("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(_e(r),Mt)}catch{g.quotaStoreFailures+=1}}function os(r,e){let t=W("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:_e(r),limit:50}).find(i=>i.key===_e(r)),s=!!o;return s!==e&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function yr(){return{"keeper.storeFailures":g.keeperStoreFailures,"meshLease.storeFailures":g.meshStoreFailures,"meshLease.divergences":g.meshLeaseDivergences,"meshLease.enforceStaleInversions":g.meshEnforceStaleInversions,"quota.storeFailures":g.quotaStoreFailures,"quota.verdictDivergences":g.quotaVerdictDivergences}}function ss(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function is(r){let e=Xe(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,ir());let s=sr({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,fr())}return t.flags.planOutbox!=="off"&&Object.assign(o,Lt()),t.flags.admission!=="off"&&(Object.assign(o,ur()),t.flags.admission==="enforce"&&Object.assign(o,mr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,yr()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{K as ADMISSION_RESERVATION_TTL_MS,ve as ADMISSION_SLOT_KEY_PREFIX,q as FilesystemPolicyError,yt as LOCAL_RUN_STORE_OPEN_RETRY_MS,St as LOCAL_RUN_STORE_SURFACES,Ee as LOCAL_SCHEMA_VERSION,te as SchemaDowngradeRefusedError,j as SqliteLocalRunStore,To as __resetAdmissionEnforceCountersForTests,Oo as __resetAdmissionShadowCountersForTests,Ko as __resetDispatchClaimRecoveryForTests,xo as __resetDispatchReceiptCountersForTests,eo as __resetLocalRunStoreLifecycleForTests,co as __resetRemoteSurfaceFlagsCacheForTests,ss as __resetSmallSurfaceCountersForTests,qo as __resetStartupClaimRecoveryForTests,Xn as __setLocalRunStoreLifecycleTestOverrides,wo as acquireWorkerAdmissionSlot,mr as admissionEnforceCounters,ur as admissionShadowCounters,lo as anyLocalRunStoreSurfaceActive,os as assessQuotaCooldownReservation,is as buildLocalRunStoreTickPosture,xe as classifyDatabaseDirectory,ns as clearQuotaCooldownReservation,Qe as closeLocalRunStore,fr as dispatchClaimRecoveryCounters,ir as dispatchReceiptCounters,O as dispatchReceiptsMode,io as extractLocalRunStoreFlagsFromOperatorTickResponse,_t as findLiveProcessByCmdlinePath,f as getLocalRunStore,Rt as getLocalRunStoreLifecycleStatus,rr as getRemoteSurfaceFlags,V as leaseTokenAttempt,So as listRecentDispatchStartFailures,zo as maybeRunStartupClaimRecovery,fo as noteCompletionReplayIfAcked,Ce as openSqliteLocalRunStoreWithRecovery,bt as parseLocalRunStoreSurfaceMode,ao as persistRemoteSurfaceFlags,Xe as probeLocalRunStore,rs as readMeshLeaseCheckpoint,Eo as rearmAdmissionAdoptionPass,Ao as reconcileAdmissionShadow,Io as reconcileNumberedAdmissionSlots,po as recordCompletionAckedReceipt,mo as recordCompletionSentReceipt,uo as recordDispatchClaimReceipt,ye as recordDispatchReleasedReceipt,or as recordDispatchSpawnedReceipt,Ro as recordDispatchStartFailedReceipt,ts as recordQuotaCooldownReservation,pr as recoverStrandedDispatchClaims,go as releaseReasonClass,dr as releaseWorkerAdmissionSlot,lr as releaseWorkerSlotReservation,Ze as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Zo as restoreKeeperBackoffCheckpoint,Qo as saveKeeperBackoffCheckpoint,es as saveMeshLeaseCheckpoint,sr as scanDispatchReceiptInvariants,ho as shouldShortCircuitCompletionReplay,yr as smallSurfaceCounters,Co as takeWorkerSlotReservation};
@@ -59,6 +59,17 @@ export interface LocalRunStore {
59
59
  */
60
60
  tryReserveAdmission(key: string, owner: string, ttlMs: number, now?: Date): ReserveOutcome;
61
61
  releaseAdmission(key: string, owner: string): boolean;
62
+ /**
63
+ * Bounded reservation scan (durable-harness D2 shadow parity + dead-slot
64
+ * release): filter by escaped-LIKE key prefix; optionally include expired
65
+ * rows (default live-only). Oldest expiry first.
66
+ */
67
+ listAdmissionReservations(input?: {
68
+ keyPrefix?: string;
69
+ includeExpired?: boolean;
70
+ limit?: number;
71
+ now?: Date;
72
+ }): AdmissionReservation[];
62
73
  /** Record an operation receipt; a duplicate idempotency key is reported, never overwritten. */
63
74
  recordOperationReceipt(input: {
64
75
  idempotencyKey: string;
@@ -0,0 +1,37 @@
1
+ /** Matches the keeper's HEALTHY_RESET window — older counts are stale evidence. */
2
+ export declare const KEEPER_CHECKPOINT_MAX_AGE_MS: number;
3
+ export declare function saveKeeperBackoffCheckpoint(input: {
4
+ consecutiveFailures: number;
5
+ exitCode: number | null;
6
+ exitSignal: string | null;
7
+ }): void;
8
+ /** Enforce only: resume the failure count across keeper restarts. */
9
+ export declare function restoreKeeperBackoffCheckpoint(): number | null;
10
+ export interface MeshLeaseGrant {
11
+ leaseToken: string | null;
12
+ holderBoxId: string | null;
13
+ authorized: boolean;
14
+ updatedAt: string;
15
+ }
16
+ export declare function saveMeshLeaseCheckpoint(runId: string, grant: MeshLeaseGrant): void;
17
+ /**
18
+ * Enforce: the store is the read source (JSON kept for external readers).
19
+ * Shadow: returns null (JSON stays authoritative) but counts divergence
20
+ * against the JSON value the caller read.
21
+ */
22
+ export declare function readMeshLeaseCheckpoint(runId: string, jsonValue: MeshLeaseGrant | null): MeshLeaseGrant | null;
23
+ export declare function recordQuotaCooldownReservation(provider: string, cooldownMs: number): void;
24
+ export declare function clearQuotaCooldownReservation(provider: string): void;
25
+ /**
26
+ * The reservation-backed cooldown verdict. Enforce: this IS the verdict
27
+ * (race-free record/prune; a torn JSON can no longer fail open into attempt
28
+ * burns). Shadow: returns null (JSON verdict stands) but counts divergence
29
+ * against it. Returns the reservation's expiry when cooling down, null when
30
+ * clear.
31
+ */
32
+ export declare function assessQuotaCooldownReservation(provider: string, jsonBlocked: boolean): {
33
+ blocked: boolean;
34
+ retryAtIso: string | null;
35
+ } | null;
36
+ export declare function smallSurfaceCounters(): Record<string, number>;
37
+ export declare function __resetSmallSurfaceCountersForTests(): void;
@@ -1,4 +1,4 @@
1
- import type { LocalRunStore, OperationReceiptRecord, ProcessIdentityRecord, RecoveryCheckpointRecord, ReserveOutcome } from "../local-run-store.js";
1
+ import type { AdmissionReservation, LocalRunStore, OperationReceiptRecord, ProcessIdentityRecord, RecoveryCheckpointRecord, ReserveOutcome } from "../local-run-store.js";
2
2
  import { type ClassifyOptions } from "./sqlite-filesystem-policy.js";
3
3
  export declare class FilesystemPolicyError extends Error {
4
4
  constructor(reason: string);
@@ -30,6 +30,12 @@ export declare class SqliteLocalRunStore implements LocalRunStore {
30
30
  getProcessIdentity(processKey: string): ProcessIdentityRecord | null;
31
31
  tryReserveAdmission(key: string, owner: string, ttlMs: number, now?: Date): ReserveOutcome;
32
32
  releaseAdmission(key: string, owner: string): boolean;
33
+ listAdmissionReservations(input?: {
34
+ keyPrefix?: string;
35
+ includeExpired?: boolean;
36
+ limit?: number;
37
+ now?: Date;
38
+ }): AdmissionReservation[];
33
39
  recordOperationReceipt(input: {
34
40
  idempotencyKey: string;
35
41
  operation: string;
@@ -58,6 +58,15 @@ export declare function countActiveWorkers(runId: string): number;
58
58
  * infinity, never N" bug). This machine-wide count is what the gate must use.
59
59
  */
60
60
  export declare function countActiveWorkersGlobal(): number;
61
+ /**
62
+ * Identities of every active worker machine-wide (durable-harness D2a: the
63
+ * admission-shadow reconcile refreshes/releases slot reservations against
64
+ * exactly the records the gate counts).
65
+ */
66
+ export declare function listActiveWorkerIdentitiesGlobal(): Array<{
67
+ runId: string;
68
+ workerName: string;
69
+ }>;
61
70
  /**
62
71
  * Compute how many workers this host can run and how many dispatch slots remain.
63
72
  * Uses total RAM for steady-state capacity and free RAM as a hard safety gate.