@zortexhq/install 0.1.23

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,541 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var ED=Object.defineProperty;var vD=($)=>$;function bD($,Z){this[$]=vD.bind(null,Z)}var h0=($,Z)=>{for(var Q in Z)ED($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:bD.bind(Z,Q)})};var E=($,Z)=>()=>($&&(Z=$($=0)),Z);function _($,Z){return{err:{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:$===""?Z:`${$}: ${Z}`}}}function M($,Z){if(typeof Z==="number")return`${$}[${Z}]`;return $===""?Z:`${$}.${Z}`}function h($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function c($,Z,Q){if(typeof $!=="string")return _(Z,"expected a string");if(Q?.nonEmpty&&$.length===0)return _(Z,"must not be empty");if(Q?.maxLength!==void 0&&$.length>Q.maxLength)return _(Z,`must be \u2264 ${Q.maxLength} chars`);return H($)}function X$($,Z,Q){if(typeof $!=="number"||!Number.isFinite($))return _(Z,"expected a finite number");if(Q?.integer&&!Number.isInteger($))return _(Z,"expected an integer");if(Q?.min!==void 0&&$<Q.min)return _(Z,`must be \u2265 ${Q.min}`);if(Q?.max!==void 0&&$>Q.max)return _(Z,`must be \u2264 ${Q.max}`);return H($)}function u0($,Z){if(typeof $!=="boolean")return _(Z,"expected a boolean");return H($)}function s($,Z,Q){if(typeof $!=="string"||!Z.includes($))return _(Q,`expected one of ${Z.join("|")}`);return H($)}function D$($,Z){if(!Array.isArray($))return _(Z,"expected an array of strings");for(let Q=0;Q<$.length;Q++)if(typeof $[Q]!=="string")return _(M(Z,Q),"expected a string");return H($)}function $$($,Z){if(typeof $!=="string"||!gD.test($))return _(Z,"expected a 26-char Crockford-base32 ULID");return H($)}function M0($,Z){if(typeof $!=="string"||!fD.test($))return _(Z,"expected a lowercase 64-char hex sha-256");return H($)}function h$($,Z){if(typeof $!=="string"||!kD.test($))return _(Z,"expected an RFC 3339 UTC instant ('Z' or '+00:00' \u2014 non-UTC offsets are forbidden)");let Q=Date.parse($);if(Number.isNaN(Q)||new Date(Q).toISOString().slice(0,19)!==$.slice(0,19))return _(Z,"expected an RFC 3339 UTC instant ('Z' or '+00:00' \u2014 non-UTC offsets are forbidden)");return H($)}function b$($,Z,Q){for(let X of Object.keys($))if(!Z.includes(X))return _(M(Q,X),"unknown field");return H(!0)}function VV($,Z,Q){for(let X of Z)if($[X]===void 0)return _(M(Q,X),"required field missing");return H(!0)}var gD,fD,kD;var M$=E(()=>{J$();gD=/^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/;fD=/^[0-9a-f]{64}$/;kD=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|\+00:00)$/});function H($){return{ok:$}}function G$($){return{empty:{checked:!0,how:$}}}function v($){return{err:$}}function K($){return typeof $==="object"&&$!==null&&"ok"in $}function f$($){return typeof $==="object"&&$!==null&&"empty"in $}function r($){return typeof $==="object"&&$!==null&&"err"in $}function D9($,Z="StructuredError"){if(!h($))return _(Z,"expected an object");let{code:Q,layer:X,retryability:z,message:Y,cause:j,...W}=$,V=Object.keys(W);if(V.length>0)return _(M(Z,V[0]),"unknown field");if(typeof Q!=="string"||!v5.includes(Q))return _(M(Z,"code"),`expected one of ${v5.join("|")}`);if(typeof X!=="string"||!CZ.includes(X))return _(M(Z,"layer"),`expected one of ${CZ.join("|")}`);if(typeof z!=="string"||!p4.includes(z))return _(M(Z,"retryability"),`expected one of ${p4.join("|")}`);if(typeof Y!=="string")return _(M(Z,"message"),"expected a string");if(j!==void 0){let q=D9(j,M(Z,"cause"));if(!K(q))return q}return H($)}var v5,CZ,p4;var J$=E(()=>{M$();v5=["invalid_argument","not_found","already_exists","permission_denied","unauthenticated","resource_exhausted","failed_precondition","aborted","deadline_exceeded","unavailable","data_loss","internal"],CZ=["ui","plugin","skill","ice","kernel","connector","auth","storage","upstream"],p4=["transient","throttling","non-retryable","retry-at-higher-level"]});var KV=()=>{};var qV=()=>{};import{randomBytes as wD}from"crypto";function q$($){return typeof $==="string"&&mD.test($)}function hD($){let Z=$,Q=Array(26);for(let X=25;X>=0;X--)Q[X]=m2.charAt(Number(Z&31n)),Z>>=5n;return Q.join("")}function uD($){let Z=$(10),Q=0n;for(let X of Z)Q=Q<<8n|BigInt(X);return Q}function V$($={}){let Z=$.now??Date.now,Q=$.random??((j)=>Uint8Array.from(wD(j))),X=(1n<<80n)-1n,z=null,Y=-1;return function(){let W=Z(),V;if(z!==null&&W<=Y)V=z+1n;else V=BigInt(W)<<80n|uD(Q)&X,Y=W;return z=V,hD(V)}}var m2="0123456789ABCDEFGHJKMNPQRSTVWXYZ",mD,HV;var FZ=E(()=>{mD=/^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/;HV=V$()});function C$($){return h2($)}function JV($){if(BV!==void 0){if(!BV.call($))throw TypeError("JCS: lone surrogate is not valid Unicode");return}for(let Z=0;Z<$.length;Z++){let Q=$.charCodeAt(Z);if(Q>=55296&&Q<=56319){let X=$.charCodeAt(Z+1);if(!(X>=56320&&X<=57343))throw TypeError("JCS: lone high surrogate is not valid Unicode");Z++}else if(Q>=56320&&Q<=57343)throw TypeError("JCS: lone low surrogate is not valid Unicode")}}function h2($){if($===null)return"null";switch(typeof $){case"boolean":return $?"true":"false";case"number":{if(!Number.isFinite($))throw TypeError("JCS: non-finite numbers are not JSON");return JSON.stringify($)}case"string":return JV($),JSON.stringify($);case"object":{if(Array.isArray($)){let z="[";for(let Y=0;Y<$.length;Y++){let j=$[Y];if(j===void 0)throw TypeError("JCS: undefined array element");if(Y>0)z+=",";z+=h2(j)}return`${z}]`}let Z=$,Q=Object.keys(Z).filter((z)=>Z[z]!==void 0).sort(),X="{";for(let z=0;z<Q.length;z++){let Y=Q[z];if(JV(Y),z>0)X+=",";X+=`${JSON.stringify(Y)}:${h2(Z[Y])}`}return`${X}}`}default:throw TypeError(`JCS: ${typeof $} is not JSON`)}}var BV;var l4=E(()=>{BV=String.prototype.isWellFormed});import{createHash as pD}from"crypto";function L$($){let Z=pD("sha256");if(typeof $==="string")Z.update($,"utf8");else Z.update($);return Z.digest("hex")}var B8=()=>{};function c4($){let Z=new Uint8Array(8+$.length);return new DataView(Z.buffer).setBigUint64(0,BigInt($.length),!1),Z.set($,8),Z}function GV($){let Z=$.reduce((z,Y)=>z+Y.length,0),Q=new Uint8Array(Z),X=0;for(let z of $)Q.set(z,X),X+=z.length;return Q}function lD($){let Z=new Uint8Array($.length/2);for(let Q=0;Q<Z.length;Q++)Z[Q]=Number.parseInt($.slice(Q*2,Q*2+2),16);return Z}function cD($,Z){let Q=Math.min($.length,Z.length);for(let X=0;X<Q;X++){let z=$[X]-Z[X];if(z!==0)return z}return $.length-Z.length}function dD($){let Z=u2.encode($.kind),Q=u2.encode($.body.normalize("NFC")),X=$.payload===void 0?new Uint8Array(0):u2.encode(C$($.payload)),z=new Uint8Array(0);if($.blobs&&$.blobs.length>0){let Y=$.blobs.map((j)=>{if(!p2.test(j.sha256))throw Error(`canon: blob sha256 is not hex64: ${j.sha256}`);return lD(j.sha256.toLowerCase())});Y.sort(cD),z=GV(Y)}return GV([c4(Z),c4(Q),c4(X),c4(z)])}function Z0($){return L$(dD($))}function X5($){let Z=$ instanceof Date?$:new Date($);if(Number.isNaN(Z.getTime()))throw Error(`canon: unparseable instant: ${String($)}`);return Z.toISOString()}function nD($,Z){if(!p2.test($))throw Error("occurrenceSourceId: contentHash must be hex64");return L$($.toLowerCase()+X5(Z))}function NZ($,Z,Q){if(!p2.test(Z))throw Error("noneSourceId: contentHash must be hex64");return $==="state"?Z.toLowerCase():nD(Z,Q)}var J8=1,u2,p2;var UV=E(()=>{B8();l4();u2=new TextEncoder;p2=/^[0-9a-fA-F]{64}$/});function G8($){return!$.includes("#")}function DV($){if(G8($))return!0;let Z=LV.exec($);return Z!==null&&G8(Z[1])}function MV($,Z){if(!Number.isInteger(Z)||Z<1)throw Error(`mintConflictRev: n must be a 1-based integer, got ${Z}`);if(!G8($))throw Error("mintConflictRev: base rev must be connector-legal (no '#')");return`${$}#c${Z}`}function AZ($){let Z=LV.exec($);if(Z===null||!G8(Z[1]))return null;return{base:Z[1],n:Number(Z[2])}}function PV($,Z,Q){let X=AZ($),z=AZ(Z),Y=X?X.base:$,j=z?z.base:Z,W=Q(Y,j);if(W!==0)return W;return(X?.n??0)-(z?.n??0)}var LV;var l2=E(()=>{J$();M$();LV=/^(.*)#c([1-9][0-9]*)$/});function iD($){let Z=[],Q=0;while(Q<$.length){let X=$.charAt(Q);if(X===" "||X==="\t"||X===`
4
+ `||X==="\r"){Q++;continue}if(X==='"'){let Y=Q+1,j="";while(Y<$.length&&$.charAt(Y)!=='"'){if($.charAt(Y)==="\\"){let W=$.charAt(Y+1);if(W==='"'||W==="\\"){j+=W,Y+=2;continue}return`unsupported string escape \\${W}`}j+=$.charAt(Y),Y++}if(Y>=$.length)return"unterminated string literal";Z.push({t:"str",v:j}),Q=Y+1;continue}if(/[0-9]/.test(X)||X==="-"&&/[0-9]/.test($.charAt(Q+1))){let Y=/^-?[0-9]+(\.[0-9]+)?/.exec($.slice(Q));if(!Y)return`bad number at ${Q}`;Z.push({t:"num",v:Number(Y[0])}),Q+=Y[0].length;continue}if(/[A-Za-z_]/.test(X)){let j=/^[A-Za-z_][A-Za-z0-9_]*/.exec($.slice(Q))[0];Z.push({t:"ident",v:j}),Q+=j.length;continue}let z=$.slice(Q,Q+2);if(CV.includes(z)){Z.push({t:"punct",v:z}),Q+=2;continue}if(CV.includes(X)){Z.push({t:"punct",v:X}),Q+=1;continue}return`character '${X}' is outside the Cedar subset`}return Z}class FV{tokens;pos=0;constructor($){this.tokens=$}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}eatPunct($){let Z=this.peek();if(Z&&Z.t==="punct"&&Z.v===$)return this.pos++,!0;return!1}parseExpr(){let $=this.parseAnd();while(this.eatPunct("||")){let Z=this.parseAnd();$={kind:"or",left:$,right:Z}}return $}parseAnd(){let $=this.parseUnary();while(this.eatPunct("&&")){let Z=this.parseUnary();$={kind:"and",left:$,right:Z}}return $}parseUnary(){if(this.eatPunct("!"))return{kind:"not",expr:this.parseUnary()};return this.parseRel()}parseRel(){let $=this.parsePrimary(),Z=this.peek();if(Z&&Z.t==="punct"&&["<","<=",">",">=","==","!="].includes(Z.v)){this.pos++;let Q=this.parsePrimary();return{kind:"cmp",op:Z.v,left:$,right:Q}}if(Z&&Z.t==="ident"&&Z.v==="in"){this.pos++;let Q=this.parseSetOrRef();return{kind:"in",left:$,set:Q}}return $}parseSetOrRef(){if(this.eatPunct("["))return this.parseSetTail();let $=this.peek();if($&&$.t==="ident")return this.parseRef();throw Error("'in' expects a set literal or an allowlist ref")}parseSetTail(){let $=[];if(this.eatPunct("]"))return{kind:"set",items:$};for(;;){let Z=this.next();if(!Z)throw Error("unterminated set literal");if(Z.t==="num"||Z.t==="str")$.push(Z.v);else if(Z.t==="ident"&&(Z.v==="true"||Z.v==="false"))$.push(Z.v==="true");else throw Error("set literals hold only number/string/boolean literals");if(this.eatPunct("]"))break;if(!this.eatPunct(","))throw Error("expected ',' or ']' in set literal")}return{kind:"set",items:$}}parsePrimary(){let $=this.next();if(!$)throw Error("unexpected end of predicate");if($.t==="num"||$.t==="str")return{kind:"lit",value:$.v};if($.t==="ident"){if($.v==="true"||$.v==="false")return{kind:"lit",value:$.v==="true"};if(c2.has($.v)||$.v==="in")throw Error(`'${$.v}' is outside the Cedar subset`);return this.pos--,this.parseRef()}if($.t==="punct"&&$.v==="("){let Z=this.parseExpr();if(!this.eatPunct(")"))throw Error("expected ')'");return Z}if($.t==="punct"&&$.v==="[")return this.parseSetTail();throw Error(`unexpected token '${String($.v)}'`)}parseRef(){let $=this.next();if(!$||$.t!=="ident")throw Error("expected identifier");if(c2.has($.v))throw Error(`'${$.v}' is outside the Cedar subset`);let Z=[$.v];while(this.eatPunct(".")){let Q=this.next();if(!Q||Q.t!=="ident")throw Error("expected identifier after '.'");if(c2.has(Q.v))throw Error(`'${Q.v}' is outside the Cedar subset`);Z.push(Q.v)}return{kind:"ref",path:Z}}atEnd(){return this.pos>=this.tokens.length}}function d2($){let Z=iD($);if(typeof Z==="string")return _("predicate",Z);if(Z.length===0)return _("predicate","empty predicate");let Q=new FV(Z);try{let X=Q.parseExpr();if(!Q.atEnd())return _("predicate","trailing tokens \u2014 outside the Cedar subset");return H(X)}catch(X){return _("predicate",X instanceof Error?X.message:String(X))}}function Q0($,Z){return{err:{code:$,layer:"kernel",retryability:"non-retryable",message:Z}}}function NV($,Z){let Q=Z;for(let X of $){if(Q===null||typeof Q!=="object"||Array.isArray(Q))return Q0("not_found",`predicate ref '${$.join(".")}' not found in context`);if(Q=Q[X],Q===void 0)return Q0("not_found",`predicate ref '${$.join(".")}' not found in context`)}return H(Q)}function _Z($,Z){switch($.kind){case"lit":return H($.value);case"set":return H($.items);case"ref":{let Q=NV($.path,Z);if(!K(Q))return Q;let X=Q.ok;if(typeof X==="number"||typeof X==="string"||typeof X==="boolean")return H(X);if(Array.isArray(X)&&X.every((z)=>typeof z==="number"||typeof z==="string"||typeof z==="boolean"))return H(X);return Q0("invalid_argument",`predicate ref '${$.path.join(".")}' is not a primitive or primitive set`)}default:{let Q=b5($,Z);if(!K(Q))return Q;return H(Q.ok)}}}function b5($,Z){switch($.kind){case"lit":if(typeof $.value==="boolean")return H($.value);return Q0("invalid_argument","non-boolean literal where a condition is required");case"ref":{let Q=_Z($,Z);if(!K(Q))return Q;if(typeof Q.ok==="boolean")return H(Q.ok);return Q0("invalid_argument",`ref '${$.path.join(".")}' is not boolean`)}case"not":{let Q=b5($.expr,Z);if(!K(Q))return Q;return H(!Q.ok)}case"and":{let Q=b5($.left,Z);if(!K(Q))return Q;if(!Q.ok)return H(!1);return b5($.right,Z)}case"or":{let Q=b5($.left,Z);if(!K(Q))return Q;if(Q.ok)return H(!0);return b5($.right,Z)}case"cmp":{let Q=_Z($.left,Z);if(!K(Q))return Q;let X=_Z($.right,Z);if(!K(X))return X;let z=Q.ok,Y=X.ok;if(Array.isArray(z)||Array.isArray(Y))return Q0("invalid_argument","sets support only 'in' membership");if($.op==="=="||$.op==="!="){if(typeof z!==typeof Y)return Q0("invalid_argument",`type mismatch: ${typeof z} ${$.op} ${typeof Y}`);return H($.op==="=="?z===Y:z!==Y)}if(typeof z!=="number"||typeof Y!=="number")return Q0("invalid_argument",`ordering comparison requires numbers, got ${typeof z} ${$.op} ${typeof Y}`);switch($.op){case"<":return H(z<Y);case"<=":return H(z<=Y);case">":return H(z>Y);case">=":return H(z>=Y)}return Q0("internal","unreachable comparison operator")}case"in":{let Q=_Z($.left,Z);if(!K(Q))return Q;let X=_Z($.set,Z);if(!K(X))return X;if(Array.isArray(Q.ok))return Q0("invalid_argument","'in' left side must be a primitive");if(!Array.isArray(X.ok))return Q0("invalid_argument","'in' right side must be a set");return H(X.ok.includes(Q.ok))}case"set":return Q0("invalid_argument","a set literal is not a condition");default:return Q0("internal","unreachable expression kind")}}function AV($,Z){if(typeof $==="string"){let Q=d2($);if(!K(Q))return Q;return b5(Q.ok,Z)}return b5($,Z)}function _V($,Z,Q={}){if(Z.min!==void 0&&$<Z.min)return H(!1);if(Z.max!==void 0&&$>Z.max)return H(!1);if(Z.ref!==void 0){let X=NV(Z.ref.split("."),Q);if(!K(X))return X;if(typeof X.ok!=="number")return Q0("invalid_argument",`bound ref '${Z.ref}' is not a number`);if($>X.ok)return H(!1)}return H(!0)}var CV,c2;var n2=E(()=>{J$();M$();CV=["||","&&","<=",">=","==","!=","<",">","!","(",")","[","]",",","."],c2=new Set(["if","then","else","has","like","is"])});function TV($){if(typeof $!=="string"||!$.startsWith("$"))return _("paramsFrom","path must start with '$'");let Z=[],Q=1;while(Q<$.length){let X=$.charAt(Q);if(X==="."){if($.charAt(Q+1)===".")return _("paramsFrom","recursive descent '..' is outside the subset");let z=/^[A-Za-z_$][A-Za-z0-9_$-]*/.exec($.slice(Q+1));if(!z)return _("paramsFrom",`expected identifier after '.' at offset ${Q}`);Z.push(z[0]),Q+=1+z[0].length;continue}if(X==="["){let z=$.slice(Q+1),Y=/^([0-9]+)\]/.exec(z);if(Y){Z.push(Number(Y[1])),Q+=1+Y[1].length+1;continue}let j=/^"((?:[^"\\]|\\.)*)"\]/.exec(z),W=/^'((?:[^'\\]|\\.)*)'\]/.exec(z),V=j??W;if(V){Z.push(V[1].replace(/\\(.)/g,"$1")),Q+=1+V[0].length;continue}return _("paramsFrom",`expected index or quoted name in '[\u2026]' at offset ${Q} (wildcards/slices/filters are outside the subset)`)}return _("paramsFrom",`unexpected character '${X}' at offset ${Q}`)}return H(Z)}var i2=E(()=>{J$();M$()});var SV=E(()=>{l4();B8()});function TZ($,Z="connector",Q="nk",X){if(!h($))return _(Q,"expected an object");for(let V of Object.keys($))if(!sD.includes(V))return _(M(Q,V),"unknown field");for(let V of["source","stream"]){let q=c($[V],M(Q,V));if(!("ok"in q))return q}if(Z==="stored"){for(let V of["sourceId","rev"]){let q=c($[V],M(Q,V));if(!("ok"in q))return q}if(!DV($.rev))return _(M(Q,"rev"),"stored rev may carry at most one framework-minted '#c<n>' suffix");return H($)}for(let V of["sourceId","rev"])if($[V]!==void 0){let q=c($[V],M(Q,V));if(!("ok"in q))return q}let z=$.rev??"",Y=$.sourceId??"";if(!G8(z))return _(M(Q,"rev"),"'#' is framework-reserved (conflict suffixes) \u2014 forbidden in connector-emitted rev");let j=X?.quality;if(j==="none"){if(Y!=="")return _(M(Q,"sourceId"),"quality 'none': normalize leaves sourceId EMPTY \u2014 appender-computed per I-1 noneIdentity (connectors \xA72.4)");if(z!=="")return _(M(Q,"rev"),"quality 'none': normalize leaves rev EMPTY \u2014 appender-assigned ('0') per I-1 (connectors \xA72.4)")}else if(j==="synthetic"){if(Y!=="")return _(M(Q,"sourceId"),"quality 'synthetic': normalize leaves sourceId EMPTY \u2014 the framework's versioned synthesizer mints it (connectors \xA72.4)")}else if(j!==void 0){if(Y==="")return _(M(Q,"sourceId"),`REQUIRED for quality '${j}' \u2014 normalize fills the upstream id (connectors \xA72.4)`)}let W=X?.revOrder;if(W==="head-compare"){if(z!=="")return _(M(Q,"rev"),"appender-assigned on head-compare streams (= contentHash, which only the appender computes) \u2014 connectors omit it (I-1 rev authorship)")}else if((W==="upstream-version"||W==="event-ts")&&j!=="none"){if(z==="")return _(M(Q,"rev"),`connector-emitted rev REQUIRED for revOrder '${W}' (I-1 rev authorship)`)}return H($)}function SZ($,Z="nkBase"){if(!h($))return _(Z,"expected an object");for(let Q of Object.keys($))if(!["source","stream","sourceId"].includes(Q))return _(M(Z,Q),"unknown field");for(let Q of["source","stream","sourceId"]){let X=c($[Q],M(Z,Q));if(!("ok"in X))return X}return H($)}function RV($,Z="coverage"){if(!h($))return _(Z,"expected an object");for(let X of Object.keys($))if(!["phase","syncRun"].includes(X))return _(M(Z,X),"unknown field");let Q=s($.phase,s2,M(Z,"phase"));if(!("ok"in Q))return Q;if($.syncRun!==void 0){let X=$$($.syncRun,M(Z,"syncRun"));if(!("ok"in X))return X}return H($)}var d4,n4,U8,i4,s2,sD;var M9=E(()=>{J$();M$();l2();d4=["upstream-version","event-ts","head-compare"],n4=["durable","durable-with-exceptions","container-scoped","synthetic","none"],U8=["path","url","hash"],i4=["state","occurrence"],s2=["live","backfill","snapshot"],sD=["source","stream","sourceId","rev"]});function OV($,Z="mention"){if(!h($))return _(Z,"expected an object");for(let z of Object.keys($))if(!["role","kind","raw","handle"].includes(z))return _(M(Z,z),"unknown field");let Q=s($.role,a2,M(Z,"role"));if(!K(Q))return Q;if($.kind!==void 0){let z=s($.kind,r2,M(Z,"kind"));if(!K(z))return z}let X=c($.raw,M(Z,"raw"));if(!K(X))return X;if($.handle!==void 0){let z=xV($.handle,M(Z,"handle"));if(!K(z))return z}return H($)}function xV($,Z="handle"){if(!h($))return _(Z,"expected an object");let Q=c($.ns,M(Z,"ns"),{nonEmpty:!0});if(!K(Q))return Q;let X=c($.value,M(Z,"value"));if(!K(X))return X;for(let z of Object.keys($))if(!["ns","value"].includes(z))return _(M(Z,z),"unknown field");return H($)}function o2($,Z="selector"){if(!h($))return _(Z,"expected HandleSelector {ns,value} or MentionSelector {event,idx} \u2014 selectors are never EntityId-scoped");if("ns"in $)return xV($,Z);if("event"in $||"idx"in $){let Q=$$($.event,M(Z,"event"));if(!K(Q))return Q;let X=X$($.idx,M(Z,"idx"),{integer:!0,min:0});if(!K(X))return X;for(let z of Object.keys($))if(!["event","idx"].includes(z))return _(M(Z,z),"unknown field");return H($)}return _(Z,"expected HandleSelector {ns,value} or MentionSelector {event,idx}")}function s4($,Z){let Q=D$($,Z);if(!K(Q))return Q;for(let X=0;X<Q.ok.length;X++){let z=$$(Q.ok[X],M(Z,X));if(!K(z))return z}return H(Q.ok)}function IV($,Z="identity.assert"){if(!h($))return _(Z,"expected an object");for(let W of Object.keys($))if(!["match","entity","confidence","method","evidence"].includes(W))return _(M(Z,W),"unknown field");let Q=o2($.match,M(Z,"match"));if(!K(Q))return Q;let X=$$($.entity,M(Z,"entity"));if(!K(X))return X;let z=X$($.confidence,M(Z,"confidence"),{min:0,max:1});if(!K(z))return z;let Y=c($.method,M(Z,"method"),{nonEmpty:!0});if(!K(Y))return Y;let j=s4($.evidence,M(Z,"evidence"));if(!K(j))return j;return H($)}function yV($,Z="identity.retract"){if(!h($))return _(Z,"expected an object");let Q=$$($.assertionId,M(Z,"assertionId"));if(!K(Q))return Q;let X=c($.reason,M(Z,"reason"),{nonEmpty:!0});if(!K(X))return X;return H($)}function EV($,Z="identity.distinct"){if(!h($))return _(Z,"expected an object");let Q=o2($.a,M(Z,"a"));if(!K(Q))return Q;let X=o2($.b,M(Z,"b"));if(!K(X))return X;let z=s($.authority,["user","agent"],M(Z,"authority"));if(!K(z))return z;let Y=c($.reason,M(Z,"reason"),{nonEmpty:!0});if(!K(Y))return Y;let j=s4($.evidence,M(Z,"evidence"));if(!K(j))return j;return H($)}function P9($,Z="identity.rebind"){if(!h($))return _(Z,"expected an object");let Q=SZ($.from,M(Z,"from"));if(!K(Q))return Q;let X=SZ($.to,M(Z,"to"));if(!K(X))return X;let z=s($.reason,t2,M(Z,"reason"));if(!K(z))return z;if($.evidence!==void 0){let Y=s4($.evidence,M(Z,"evidence"));if(!K(Y))return Y}if($.rebindId!==void 0){let Y=$$($.rebindId,M(Z,"rebindId"));if(!K(Y))return Y}return H($)}function RZ($,Z="sync.identity.rebound"){if(!h($))return _(Z,"expected an object");let Q=c($.source,M(Z,"source"),{nonEmpty:!0});if(!K(Q))return Q;let X=$$($.grantId,M(Z,"grantId"));if(!K(X))return X;let z=$$($.rebindId,M(Z,"rebindId"));if(!K(z))return z;let Y=SZ($.from,M(Z,"from"));if(!K(Y))return Y;let j=SZ($.to,M(Z,"to"));if(!K(j))return j;if(Y.ok.source!==Q.ok||j.ok.source!==Q.ok)return _(Z,"source must equal both rebind endpoints");return H($)}function vV($,Z="identity.cluster.changed"){if(!h($))return _(Z,"expected an object");let Q=s4($.affected,M(Z,"affected"));if(!K(Q))return Q;let X=$$($.cause,M(Z,"cause"));if(!K(X))return X;let z=s($.change,e2,M(Z,"change"));if(!K(z))return z;return H($)}var a2,r2,t2,e2;var OZ=E(()=>{M9();J$();M$();a2=["actor","participant","subject","mentioned"],r2=["person","org","place","thing","unknown"],t2=["provider-documented","derivation-heuristic"],e2=["merge","split","membership","rebind"]});function QX($,...Z){let Q=$;for(let X of Z)if(bV[X]<bV[Q])Q=X;return Q}function o4($,Z="trust"){if(!h($))return _(Z,"expected an object {level, sources}");for(let z of Object.keys($))if(!["level","sources"].includes(z))return _(M(Z,z),"unknown field");let Q=s($.level,xZ,M(Z,"level"));if(!K(Q))return Q;let X=D$($.sources,M(Z,"sources"));if(!K(X))return X;if(X.ok.length>$X+1)return _(M(Z,"sources"),`capped at ${$X} entries plus the '+more' sentinel`);return H($)}var xZ,$X=32,ZX="+more",bV;var IZ=E(()=>{J$();M$();xZ=["untrusted","user","system"],bV={untrusted:0,user:1,"user-direct":2,system:3}});function YX($,Z="origin"){if(!h($))return _(Z,"expected an object");let Q=s($.kind,zX,M(Z,"kind"));if(!K(Q))return Q;if(Q.ok==="connector"){let X=c($.source,M(Z,"source"),{nonEmpty:!0});if(!K(X))return X;let z=$$($.grant,M(Z,"grant"));if(!K(z))return z;for(let Y of Object.keys($))if(!["kind","source","grant"].includes(Y))return _(M(Z,Y),"unknown field")}else for(let X of Object.keys($))if(X!=="kind")return _(M(Z,X),"unknown field");return H($)}function yZ($,Z="blob"){if(!h($))return _(Z,"expected an object");for(let z of Object.keys($))if(!["sha256","bytes","mime","name"].includes(z))return _(M(Z,z),"unknown field");let Q=M0($.sha256,M(Z,"sha256"));if(!K(Q))return Q;let X=X$($.bytes,M(Z,"bytes"),{integer:!0,min:0});if(!K(X))return X;if($.mime!==void 0){let z=c($.mime,M(Z,"mime"));if(!K(z))return z}if($.name!==void 0){let z=c($.name,M(Z,"name"));if(!K(z))return z}return H($)}function oD($,Z="ref"){if(!h($))return _(Z,"expected an object");let Q=c($.rel,M(Z,"rel"),{nonEmpty:!0});if(!K(Q))return Q;let X=$.to;if(typeof X==="string"){let z=$$(X,M(Z,"to"));if(!K(z))return z}else if(h(X))if("sourceId"in X)for(let z of["source","stream","sourceId"]){let Y=c(X[z],M(M(Z,"to"),z));if(!K(Y))return Y}else if("ns"in X){let z=c(X.ns,M(M(Z,"to"),"ns"),{nonEmpty:!0});if(!K(z))return z;let Y=c(X.value,M(M(Z,"to"),"value"));if(!K(Y))return Y}else return _(M(Z,"to"),"expected Ulid | NkRef {source,stream,sourceId} | ClaimRef {ns,value}");else return _(M(Z,"to"),"expected Ulid | NkRef | ClaimRef");return H($)}function kV($,Z,Q,X){let z=Q==="stored"?TZ($.nk,"stored",M(Z,"nk")):TZ($.nk,"connector",M(Z,"nk"),X);if(!K(z))return z;let Y=h$($.ts,M(Z,"ts"));if(!K(Y))return Y;let j=s($.tier,XX,M(Z,"tier"));if(!K(j))return j;let W=c($.kind,M(Z,"kind"),{nonEmpty:!0});if(!K(W))return W;let V=X$($.schemaVersion,M(Z,"schemaVersion"),{integer:!0,min:1});if(!K(V))return V;if($.coverage!==void 0){let B=RV($.coverage,M(Z,"coverage"));if(!K(B))return B}if(!Array.isArray($.mentions))return _(M(Z,"mentions"),"expected an array");for(let B=0;B<$.mentions.length;B++){let G=OV($.mentions[B],M(M(Z,"mentions"),B));if(!K(G))return G}let q=c($.body,M(Z,"body"));if(!K(q))return q;if($.lang!==void 0){let B=c($.lang,M(Z,"lang"));if(!K(B))return B}if($.blobs!==void 0){if(!Array.isArray($.blobs))return _(M(Z,"blobs"),"expected an array");for(let B=0;B<$.blobs.length;B++){let G=yZ($.blobs[B],M(M(Z,"blobs"),B));if(!K(G))return G}}if($.refs!==void 0){if(!Array.isArray($.refs))return _(M(Z,"refs"),"expected an array");for(let B=0;B<$.refs.length;B++){let G=oD($.refs[B],M(M(Z,"refs"),B));if(!K(G))return G}}return H(!0)}function a4($,Z,Q="protoEvent"){if(!h($))return _(Q,"expected an object");for(let z of gV)if($[z]!==void 0)return _(M(Q,z),"appender-assigned field \u2014 never caller-supplied");for(let z of Object.keys($))if(!fV.includes(z))return _(M(Q,z),"unknown field");let X=kV($,Q,"connector",Z);if(!K(X))return X;return H($)}function g5($,Z="event"){if(!h($))return _(Z,"expected an object");for(let q of Object.keys($))if(!aD.includes(q))return _(M(Z,q),"unknown field");let Q=$$($.id,M(Z,"id"));if(!K(Q))return Q;let X=h$($.observedTs,M(Z,"observedTs"));if(!K(X))return X;let z=M0($.contentHash,M(Z,"contentHash"));if(!K(z))return z;let Y=X$($.canon,M(Z,"canon"),{integer:!0,min:1});if(!K(Y))return Y;if($.trust===void 0)return _(M(Z,"trust"),"required field missing (always present \u2014 framework-stamped)");let j=o4($.trust,M(Z,"trust"));if(!K(j))return j;if($.origin===void 0)return _(M(Z,"origin"),"required field missing (persisted provenance)");let W=YX($.origin,M(Z,"origin"));if(!K(W))return W;if($.policyVersion!==void 0){let q=X$($.policyVersion,M(Z,"policyVersion"),{integer:!0,min:1});if(!K(q))return q}let V=kV($,Z,"stored");if(!K(V))return V;return H($)}var XX,zX,gV,fV,aD;var L8=E(()=>{M9();IZ();OZ();J$();M$();XX=["api","mcp-wrapped","local-app","extension","browser-driven","screen","first-party"],zX=["connector","kernel","derivation","projector","user"],gV=["id","observedTs","contentHash","canon","trust","origin","policyVersion"];fV=["nk","ts","tier","kind","schemaVersion","coverage","mentions","body","lang","payload","blobs","refs"];aD=[...fV,...gV]});function t4($,Z="contract"){if(!h($))return _(Z,"expected an object");for(let A of Object.keys($))if(!rD.includes(A))return _(M(Z,A),"unknown field");let Q=c($.name,M(Z,"name"),{nonEmpty:!0});if(!K(Q))return Q;let X=c($.description,M(Z,"description"),{nonEmpty:!0});if(!K(X))return X;if(!h($.params))return _(M(Z,"params"),"expected a JSON Schema object");let z=$.effect;if(!h(z))return _(M(Z,"effect"),"expected an object");for(let A of Object.keys(z))if(!["class","category","reversibility","compensation","scope"].includes(A))return _(M(M(Z,"effect"),A),"unknown field");let Y=s(z.class,D8,M(Z,"effect.class"));if(!K(Y))return Y;if(z.category!==void 0){let A=s(z.category,EZ,M(Z,"effect.category"));if(!K(A))return A}if(Y.ok==="dispatch"&&z.category===void 0)return _(M(Z,"effect.category"),"REQUIRED for dispatch-class actions (D6 fuse floors and the FM-25 firewall key on it)");let j=s(z.reversibility,vZ,M(Z,"effect.reversibility"));if(!K(j))return j;let W=s(z.scope,jX,M(Z,"effect.scope"));if(!K(W))return W;if(j.ok==="compensatable"){let A=z.compensation;if(!h(A))return _(M(Z,"effect.compensation"),"REQUIRED iff reversibility is 'compensatable' (a TESTED obligation)");let N=c(A.action,M(Z,"effect.compensation.action"),{nonEmpty:!0});if(!K(N))return N;let S=c(A.paramsFrom,M(Z,"effect.compensation.paramsFrom"),{nonEmpty:!0});if(!K(S))return S;let R=TV(S.ok);if(!K(R))return _(M(Z,"effect.compensation.paramsFrom"),"must parse under the pinned JSONPath subset over {intent, effect}")}else if(z.compensation!==void 0)return _(M(Z,"effect.compensation"),"only compensatable actions declare compensation");if($.escalateWhen!==void 0){if(!Array.isArray($.escalateWhen))return _(M(Z,"escalateWhen"),"expected an array");let A=$.escalateWhen;for(let N=0;N<A.length;N++){let S=A[N],R=M(M(Z,"escalateWhen"),N);if(!h(S))return _(R,"expected {predicate, class}");let O=c(S.predicate,`${R}.predicate`,{nonEmpty:!0});if(!K(O))return O;let T=d2(O.ok);if(!K(T)){let k=r(T)?T.err.message:"unparseable";return _(`${R}.predicate`,`must parse under the pinned Cedar subset (${k})`)}let m=s(S.class,D8,`${R}.class`);if(!K(m))return m}}let V=$.idempotency;if(!h(V))return _(M(Z,"idempotency"),"expected an object");let q=u0(V.supported,M(Z,"idempotency.supported"));if(!K(q))return q;if(V.keyParam!==void 0){let A=c(V.keyParam,M(Z,"idempotency.keyParam"));if(!K(A))return A}if(V.windowDays!==void 0){let A=X$(V.windowDays,M(Z,"idempotency.windowDays"),{min:0});if(!K(A))return A}if(V.onPriorFailure!==void 0){let A=s(V.onPriorFailure,["replay","retry"],M(Z,"idempotency.onPriorFailure"));if(!K(A))return A}let B=$.dryRun;if(!h(B))return _(M(Z,"dryRun"),"expected an object");let G=u0(B.supported,M(Z,"dryRun.supported"));if(!K(G))return G;let J=$.verification;if(!h(J))return _(M(Z,"verification"),"expected an object");let U=s(J.method,VX,M(Z,"verification.method"));if(!K(U))return U;if(J.probeRef!==void 0){let A=c(J.probeRef,M(Z,"verification.probeRef"));if(!K(A))return A}if($.constraints!==void 0){let A=$.constraints;if(!h(A))return _(M(Z,"constraints"),"expected an object");for(let N of Object.keys(A))if(!["ratePerHour","maxPerDay","paramBounds","allowlistRef"].includes(N))return _(M(M(Z,"constraints"),N),"unknown field");for(let N of["ratePerHour","maxPerDay"])if(A[N]!==void 0){let S=X$(A[N],M(M(Z,"constraints"),N),{min:0});if(!K(S))return S}if(A.allowlistRef!==void 0){let N=c(A.allowlistRef,M(Z,"constraints.allowlistRef"));if(!K(N))return N}if(A.paramBounds!==void 0){let N=A.paramBounds;if(!h(N))return _(M(Z,"constraints.paramBounds"),"expected an object of Bounds");for(let[S,R]of Object.entries(N)){let O=`${M(Z,"constraints.paramBounds")}.${S}`;if(!h(R))return _(O,"expected {min?, max?, ref?}");for(let T of Object.keys(R))if(!["min","max","ref"].includes(T))return _(M(O,T),"unknown field");for(let T of["min","max"])if(R[T]!==void 0){let m=X$(R[T],M(O,T));if(!K(m))return m}if(R.ref!==void 0){let T=c(R.ref,M(O,"ref"),{nonEmpty:!0});if(!K(T))return T}}}}let L=s($.fuse,WX,M(Z,"fuse"));if(!K(L))return L;let D=z.category;if(Y.ok==="dispatch"&&j.ok==="irreversible"&&L.ok==="none")return _(M(Z,"fuse"),"dispatch \u2227 irreversible \u21D2 fuse at least 'standard' (I-3 lint)");if(D!==void 0&&["pay","post","send","delete-at-source"].includes(D)&&L.ok!=="floor")return _(M(Z,"fuse"),"category \u2208 {pay, post, send, delete-at-source} \u21D2 fuse 'floor' (D6; send joined by P24 ruling 2026-07-02 \u2014 OQ-19 resolved)");let P=s($.taint,r4,M(Z,"taint"));if(!K(P))return P;let F=Y.ok==="dispatch"&&L.ok!=="none";if($.taintFlow!==void 0){if(!Array.isArray($.taintFlow))return _(M(Z,"taintFlow"),"expected an array");let A=$.taintFlow;for(let N=0;N<A.length;N++){let S=A[N],R=M(M(Z,"taintFlow"),N);if(!h(S))return _(R,"expected {param, accepts, policyRef?}");let O=c(S.param,`${R}.param`,{nonEmpty:!0});if(!K(O))return O;let T=s(S.accepts,["any","untainted-only"],`${R}.accepts`);if(!K(T))return T;if(S.policyRef!==void 0){let m=c(S.policyRef,`${R}.policyRef`);if(!K(m))return m}if(F&&T.ok==="any"&&S.policyRef===void 0)return _(`${R}.policyRef`,"REQUIRED: every param of a fused dispatch action is 'untainted-only' unless explicitly declared otherwise WITH a policyRef (I-3 lint, FM-25 parameter-provenance firewall)");for(let m of Object.keys(S))if(!["param","accepts","policyRef"].includes(m))return _(M(R,m),"unknown field")}}return H($)}function wV($,Z){let Q=$.taintFlow?.find((X)=>X.param===Z);if(Q!==void 0)return Q.accepts;return $.effect.class==="dispatch"&&$.fuse!=="none"?"untainted-only":void 0}var D8,EZ,vZ,jX,WX,r4,VX,rD;var M8=E(()=>{J$();M$();n2();i2();D8=["read","create","update","delete","dispatch"],EZ=["pay","post","send","delete-at-source","other"],vZ=["reversible","compensatable","irreversible"],jX=["vault","source","world"],WX=["none","standard","floor"],r4=["quoted-only","summarized-only","unrestricted"],VX=["read-after-write","event-confirm","none"],rD=["name","description","params","effect","escalateWhen","idempotency","dryRun","verification","constraints","fuse","taint","taintFlow"]});var f5,KX,P8,qX="fuse-policy@v1";var e4=E(()=>{J$();M$();f5=["pay","post","send","delete-at-source","dispatch-other","calendar-dispatch"],KX={rows:{pay:{baseMs:90000,floorMs:30000,capMs:600000,decay:"none"},post:{baseMs:90000,floorMs:30000,capMs:600000,decay:"none"},"delete-at-source":{baseMs:90000,floorMs:30000,capMs:600000,decay:"none"},send:{baseMs:90000,floorMs:30000,capMs:600000,decay:"none"},"calendar-dispatch":{baseMs:60000,floorMs:0,capMs:300000,decay:"none"},"dispatch-other":{baseMs:60000,floorMs:0,capMs:300000,decay:"none"}}},P8=KX});function BX($,Z="evidence"){if(!h($))return _(Z,"expected an object");for(let Y of Object.keys($))if(!["ref","hash","producedAt"].includes(Y))return _(M(Z,Y),"unknown field");let Q=c($.ref,M(Z,"ref"),{nonEmpty:!0});if(!K(Q))return Q;let X=M0($.hash,M(Z,"hash"));if(!K(X))return X;let z=h$($.producedAt,M(Z,"producedAt"));if(!K(z))return z;return H($)}function tD($,Z="criterion"){if(!h($))return _(Z,"expected an object");for(let W of Object.keys($))if(!["n","statement","check","evidence"].includes(W))return _(M(Z,W),"unknown field");let Q=X$($.n,M(Z,"n"),{integer:!0,min:1});if(!K(Q))return Q;let X=c($.statement,M(Z,"statement"),{nonEmpty:!0});if(!K(X))return X;let z=$.check;if(!h(z))return _(M(Z,"check"),"expected {kind, ref}");let Y=s(z.kind,HX,M(Z,"check.kind"));if(!K(Y))return Y;let j=c(z.ref,M(Z,"check.ref"),{nonEmpty:!0});if(!K(j))return j;if($.evidence!==void 0){let W=BX($.evidence,M(Z,"evidence"));if(!K(W))return W}return H($)}function $3($,Z="order"){if(!h($))return _(Z,"expected an object");for(let B of Object.keys($))if(!eD.includes(B))return _(M(Z,B),"unknown field");let Q=$$($.id,M(Z,"id"));if(!K(Q))return Q;let X=s($.kind,C8,M(Z,"kind"));if(!K(X))return X;let z=c($.requirement,M(Z,"requirement"),{nonEmpty:!0});if(!K(z))return z;if($.shapeAnalysis!==void 0){let B=$.shapeAnalysis,G=M(Z,"shapeAnalysis");if(!h(B))return _(G,"expected an object");let J=D$(B.touchedBlocks,M(G,"touchedBlocks"));if(!K(J))return J;let U=D$(B.existing,M(G,"existing"));if(!K(U))return U;let L=c(B.delta,M(G,"delta"),{nonEmpty:!0});if(!K(L))return L}else if(X.ok==="build"||X.ok==="fix")return _(M(Z,"shapeAnalysis"),"REQUIRED for build/fix kinds (FM-20: the plan derives from a system-shape analysis)");if(!Array.isArray($.acceptance)||$.acceptance.length===0)return _(M(Z,"acceptance"),"expected a non-empty array of numbered criteria");let Y=$.acceptance;for(let B=0;B<Y.length;B++){let G=tD(Y[B],M(M(Z,"acceptance"),B));if(!K(G))return G}if($.ladder!==void 0){if(!Array.isArray($.ladder))return _(M(Z,"ladder"),"expected an array");let B=$.ladder;for(let G=0;G<B.length;G++){let J=B[G],U=M(M(Z,"ladder"),G);if(!h(J))return _(U,"expected {rung, proves, exitCriterion}");let L=X$(J.rung,M(U,"rung"),{integer:!0,min:1});if(!K(L))return L;let D=c(J.proves,M(U,"proves"),{nonEmpty:!0});if(!K(D))return D;if(!Array.isArray(J.exitCriterion))return _(M(U,"exitCriterion"),"expected an array of criterion numbers")}}let j=D$($.leases,M(Z,"leases"));if(!K(j))return j;let W=$.budget;if(!h(W))return _(M(Z,"budget"),"expected {tokens, usd, wallClockMin}");for(let B of["tokens","usd","wallClockMin"]){let G=X$(W[B],M(M(Z,"budget"),B),{min:0});if(!K(G))return G}if($.slice!==void 0){let B=$.slice;if(!h(B))return _(M(Z,"slice"),"expected {demandId}");let G=c(B.demandId,M(Z,"slice.demandId"),{nonEmpty:!0});if(!K(G))return G}let V=$.provenance;if(!h(V))return _(M(Z,"provenance"),"expected {spawnedBy, parent?}");let q=V.spawnedBy;if(!(typeof q==="string"&&(["kernel","user","gauntlet"].includes(q)||q$(q))))return _(M(Z,"provenance.spawnedBy"),"expected 'kernel'|'user'|'gauntlet' or a spawning Ulid");if(V.parent!==void 0){let B=$$(V.parent,M(Z,"provenance.parent"));if(!K(B))return B}return H($)}var C8,HX,eD;var bZ=E(()=>{J$();M$();FZ();C8=["build","fix","sync","derive","research","repair","review","distill","harness"],HX=["test","eval","probe","replay","e2e-motion","artifact","lint","cli-drive"];eD=["id","kind","requirement","shapeAnalysis","acceptance","ladder","leases","budget","slice","provenance"]});function mV($){if($>=48&&$<=57)return $-48;if($>=65&&$<=70)return $-55;if($>=97&&$<=102)return $-87;return-1}function jM($){return $>=65&&$<=90||$>=97&&$<=122||$>=48&&$<=57||$===45||$===46||$===95||$===126}function hV($,Z){let Q=[],X=0,z=0,Y=!1,j=!1,W=!1,V=(G)=>{let J=XM.encode($.slice(X,G));for(let U of J)Q.push(U)};while(z<$.length){if((z&2047)===0&&Z())return{kind:"aborted"};if($.charCodeAt(z)!==37){z+=1;continue}if(z+2>=$.length){j=!0,z+=1;continue}let G=mV($.charCodeAt(z+1)),J=mV($.charCodeAt(z+2));if(G<0||J<0){j=!0,z+=1;continue}V(z);let U=G<<4|J;Q.push(U),W||=jM(U),z+=3,X=z,Y=!0}if(!Y)return{kind:"ok",value:$,changed:!1,malformed:j,encodedUnreserved:W};V($.length);let q=Uint8Array.from(Q),B;try{B=YM.decode(q)}catch{j=!0,B=zM.decode(q)}return{kind:"ok",value:B,changed:!0,malformed:j,encodedUnreserved:W}}function z5($,Z=()=>!1){let Q=[$],X=$,z=!1,Y=!1;for(let W=0;W<QM;W+=1){let V=hV(X,Z);if(V.kind==="aborted")return V;if(z||=V.malformed,Y||=V.encodedUnreserved,!V.changed||V.value===X)return{kind:"ok",values:Q,malformed:z,encodedUnreserved:Y};X=V.value,Q.push(X)}let j=hV(X,Z);if(j.kind==="aborted")return j;if(z||=j.malformed,Y||=j.encodedUnreserved,j.changed&&j.value!==X)return{kind:"ambiguous",malformed:z,encodedUnreserved:Y};return{kind:"ok",values:Q,malformed:z,encodedUnreserved:Y}}function F8($,Z="capabilityRefs"){if(!Array.isArray($))return _(Z,"expected an array of secret-free capability references");if($.length>Z3)return _(Z,`must contain at most ${Z3} references`);let Q=new Set;for(let X=0;X<$.length;X++){let z=M(Z,X),Y=$[X];if(!h(Y))return _(z,"expected {kind,id}");for(let q of Object.keys(Y))if(!["kind","id"].includes(q))return _(M(z,q),"unknown field");let j=c(Y.kind,M(z,"kind"),{nonEmpty:!0,maxLength:$M});if(!K(j))return j;let W=c(Y.id,M(z,"id"),{nonEmpty:!0,maxLength:ZM});if(!K(W))return W;if(/[/,\u0000-\u001f\u007f]/u.test(W.ok))return _(M(z,"id"),"must not contain slash, comma, or control characters");if(/[,\u0000-\u001f\u007f]/u.test(j.ok))return _(M(z,"kind"),"must not contain comma or control characters");let V=`${j.ok}\x00${W.ok}`;if(Q.has(V))return _(z,"duplicate capability reference");Q.add(V)}return H($)}function Q3($,Z="grant"){if(!h($))return _(Z,"expected an object");for(let j of Object.keys($))if(!["id","source","account","scopes","expiresAt"].includes(j))return _(M(Z,j),"unknown field");let Q=$$($.id,M(Z,"id"));if(!K(Q))return Q;let X=c($.source,M(Z,"source"),{nonEmpty:!0});if(!K(X))return X;if(X.ok.includes(":"))return _(M(Z,"source"),"must be the BARE connector id \u2014 encoding the account into source breaks every consumer that joins handles to connector ids");if($.account!==void 0){let j=c($.account,M(Z,"account"));if(!K(j))return j}let z=D$($.scopes,M(Z,"scopes"));if(!K(z))return z;let Y=h$($.expiresAt,M(Z,"expiresAt"));if(!K(Y))return Y;return H($)}function uV($,Z="auth"){if(!h($))return _(Z,"expected an object");for(let V of Object.keys($))if(!["provider","method","scopes","multiAccount","probe"].includes(V))return _(M(Z,V),"unknown field");let Q=c($.provider,M(Z,"provider"),{nonEmpty:!0});if(!K(Q))return Q;let X=s($.method,JX,M(Z,"method"));if(!K(X))return X;let z=D$($.scopes,M(Z,"scopes"));if(!K(z))return z;let Y=u0($.multiAccount,M(Z,"multiAccount"));if(!K(Y))return Y;let j=$.probe;if(!h(j))return _(M(Z,"probe"),"expected {op}");let W=c(j.op,M(Z,"probe.op"),{nonEmpty:!0});if(!K(W))return W;return H($)}var Z3=32,$M=128,ZM=1024,QM=4,XM,zM,YM,JX;var N8=E(()=>{J$();M$();XM=new TextEncoder,zM=new TextDecoder,YM=new TextDecoder("utf-8",{fatal:!0});JX=["oauth-pkce","device-flow","api-key","client-secret","cookie-session","local-permission","none"]});function pV($,Z="run"){if(!h($))return _(Z,"expected an object");for(let J of Object.keys($))if(!["id","orderId","workerType","skillVersions","sandbox","heartbeatEverySec"].includes(J))return _(M(Z,J),"unknown field");let Q=$$($.id,M(Z,"id"));if(!K(Q))return Q;let X=$$($.orderId,M(Z,"orderId"));if(!K(X))return X;let z=c($.workerType,M(Z,"workerType"),{nonEmpty:!0});if(!K(z))return z;if(!Array.isArray($.skillVersions))return _(M(Z,"skillVersions"),"expected an array");let Y=$.skillVersions;for(let J=0;J<Y.length;J++){let U=Y[J],L=M(M(Z,"skillVersions"),J);if(!h(U))return _(L,"expected {skill, version}");let D=c(U.skill,M(L,"skill"),{nonEmpty:!0});if(!K(D))return D;let P=c(U.version,M(L,"version"),{nonEmpty:!0});if(!K(P))return P}let j=$.sandbox;if(!h(j))return _(M(Z,"sandbox"),"expected an object");let W=M(Z,"sandbox");if(j.worktree!==void 0){let J=c(j.worktree,M(W,"worktree"),{nonEmpty:!0});if(!K(J))return J}let V=D$(j.leases,M(W,"leases"));if(!K(V))return V;if(!Array.isArray(j.credentials))return _(M(W,"credentials"),"expected an array of GrantHandles");let q=j.credentials;for(let J=0;J<q.length;J++){let U=Q3(q[J],M(M(W,"credentials"),J));if(!K(U))return U}let B=j.budgets;if(!h(B))return _(M(W,"budgets"),"expected {tokens, usd, wallClockMin}");for(let J of["tokens","usd","wallClockMin"]){let U=X$(B[J],M(M(W,"budgets"),J),{min:0});if(!K(U))return U}let G=X$($.heartbeatEverySec,M(Z,"heartbeatEverySec"),{integer:!0,min:1});if(!K(G))return G;return H($)}function gZ($,Z="worker.exited"){if(!h($))return _(Z,"expected an object");for(let q of Object.keys($))if(!["runId","status","evidence","spend","traceId"].includes(q))return _(M(Z,q),"unknown field");let Q=$$($.runId,M(Z,"runId"));if(!K(Q))return Q;let X=s($.status,GX,M(Z,"status"));if(!K(X))return X;if(!Array.isArray($.evidence))return _(M(Z,"evidence"),"expected an array (sparse: undefined per unevidenced criterion)");let z=$.evidence;for(let q=0;q<z.length;q++){if(z[q]===void 0||z[q]===null)continue;let B=BX(z[q],M(M(Z,"evidence"),q));if(!K(B))return B}let Y=$.spend;if(!h(Y))return _(M(Z,"spend"),"expected {tokens, usd}");let j=X$(Y.tokens,M(Z,"spend.tokens"),{min:0});if(!K(j))return j;let W=X$(Y.usd,M(Z,"spend.usd"),{min:0});if(!K(W))return W;let V=$$($.traceId,M(Z,"traceId"));if(!K(V))return V;return H($)}function LX($,Z="gauntlet.verdict"){if(!h($))return _(Z,"expected an object");for(let V of Object.keys($))if(!["orderId","runId","disposition","grading","violations","reExecHashes"].includes(V))return _(M(Z,V),"unknown field");let Q=$$($.orderId,M(Z,"orderId"));if(!K(Q))return Q;let X=$$($.runId,M(Z,"runId"));if(!K(X))return X;let z=s($.disposition,UX,M(Z,"disposition"));if(!K(z))return z;if(!Array.isArray($.grading))return _(M(Z,"grading"),"expected an array");let Y=$.grading;for(let V=0;V<Y.length;V++){let q=Y[V],B=M(M(Z,"grading"),V);if(!h(q))return _(B,"expected {criterion, result}");let G=X$(q.criterion,M(B,"criterion"),{integer:!0,min:1});if(!K(G))return G;let J=s(q.result,["pass","fail"],M(B,"result"));if(!K(J))return J}if(!Array.isArray($.violations))return _(M(Z,"violations"),"expected an array");let j=$.violations;for(let V=0;V<j.length;V++){let q=j[V],B=M(M(Z,"violations"),V);if(!h(q))return _(B,"expected {law, detail}");let G=c(q.law,M(B,"law"),{nonEmpty:!0});if(!K(G))return G;let J=c(q.detail,M(B,"detail"));if(!K(J))return J}if(!Array.isArray($.reExecHashes))return _(M(Z,"reExecHashes"),"expected an array");let W=$.reExecHashes;for(let V=0;V<W.length;V++){let q=M0(W[V],M(M(Z,"reExecHashes"),V));if(!K(q))return q}return H($)}var GX,UX;var X3=E(()=>{bZ();N8();J$();M$();GX=["done","blocked","failed","reaped","model-refused","model-substituted"],UX=["pass","fail","errored"]});function z3($,Z="trace.span"){if(!h($))return _(Z,"expected an object");for(let V of Object.keys($))if(!["traceId","spanId","parentSpanId","name","attrs","status","error","startTs","durationMs"].includes(V))return _(M(Z,V),"unknown field");let Q=$$($.traceId,M(Z,"traceId"));if(!K(Q))return Q;let X=$$($.spanId,M(Z,"spanId"));if(!K(X))return X;if($.parentSpanId!==void 0){let V=$$($.parentSpanId,M(Z,"parentSpanId"));if(!K(V))return V}let z=c($.name,M(Z,"name"),{nonEmpty:!0});if(!K(z))return z;if(!h($.attrs))return _(M(Z,"attrs"),"expected an object");let Y=s($.status,["ok","error"],M(Z,"status"));if(!K(Y))return Y;if($.error!==void 0){if(Y.ok!=="error")return _(M(Z,"error"),"present only when status is 'error' (broken \u2260 ok)");let V=D9($.error,M(Z,"error"));if(!K(V))return V}let j=h$($.startTs,M(Z,"startTs"));if(!K(j))return j;let W=X$($.durationMs,M(Z,"durationMs"),{min:0});if(!K(W))return W;return H($)}var DX;var MX=E(()=>{J$();M$();DX={"connector.pull":["source","stream","grant.id","batch.count","appended.count","deduped.count","cursor.state","exhausted","coverage.pct"],"ice.assemble":["demand.id","demand.kind","requester.workerType","candidates.count","slice.items","slice.tokens","degraded","stage.ms"],"worker.run":["run.id","order.id","order.kind","worker.type","harness","provider","model","tokens.in","tokens.out","tokens.cache_read","tokens.cache_write","cost.usd","turns","exit.status","heartbeats.missed","skills"],"action.execute":["intent.id","contract","effect.class","reversibility","fuse.ms","idempotency.key","attempt","verify.method","verify.result","breaker.name","breaker.state"],"llm.call":["provider","model","operation","tokens.in","tokens.out","cost.usd","latency.ms","stop.reason","request.temperature"],"probe.run":["probe.ref","layer","result","latency.ms","budget.ms","budget.met"]}});var PX=E(()=>{FZ()});var lV=E(()=>{J$()});var Y3=E(()=>{J$();M$()});var j3=E(()=>{J$();M$()});function cV($,Z="rec.consequence"){if(!h($))return _(Z,"expected an object");for(let W of Object.keys($))if(!["recId","outcome","horizon","evidence","attributionConfidence"].includes(W))return _(M(Z,W),"unknown field");let Q=$$($.recId,M(Z,"recId"));if(!K(Q))return Q;let X=s($.outcome,CX,M(Z,"outcome"));if(!K(X))return X;let z=s($.horizon,FX,M(Z,"horizon"));if(!K(z))return z;if(!Array.isArray($.evidence))return _(M(Z,"evidence"),"expected an array of Ulids");let Y=$.evidence;for(let W=0;W<Y.length;W++){let V=$$(Y[W],M(M(Z,"evidence"),W));if(!K(V))return V}if(X.ok==="completed"&&Y.length===0)return _(M(Z,"evidence"),"an unfalsifiable 'completed' is FM-15 \u2014 world events proving it are required");let j=X$($.attributionConfidence,M(Z,"attributionConfidence"),{min:0,max:1});if(!K(j))return j;return H($)}var CX,FX;var W3=E(()=>{J$();M$();CX=["completed","reverted","abandoned"],FX=["1h","1d","1w","1mo"]});var dV=()=>{};function iV($,Z="egress"){if(!h($))return _(Z,"expected an object");for(let V of Object.keys($))if(!["id","channel","payloadRef","actor","grantId","contract"].includes(V))return _(M(Z,V),"unknown field");let Q=$$($.id,M(Z,"id"));if(!K(Q))return Q;let X=s($.channel,V3,M(Z,"channel"));if(!K(X))return X;let z=yZ($.payloadRef,M(Z,"payloadRef"));if(!K(z))return z;let Y=$.actor;if(!h(Y))return _(M(Z,"actor"),"expected {workerId, workerType, demandId?}");let j=c(Y.workerId,M(Z,"actor.workerId"),{nonEmpty:!0});if(!K(j))return j;let W=c(Y.workerType,M(Z,"actor.workerType"),{nonEmpty:!0});if(!K(W))return W;if(Y.demandId!==void 0){let V=$$(Y.demandId,M(Z,"actor.demandId"));if(!K(V))return V}if($.grantId!==void 0){let V=$$($.grantId,M(Z,"grantId"));if(!K(V))return V}if($.contract!==void 0){let V=$.contract,q=M(Z,"contract");if(!h(V))return _(q,"expected {action, class, category?, reversibility}");let B=c(V.action,M(q,"action"),{nonEmpty:!0});if(!K(B))return B;let G=s(V.class,D8,M(q,"class"));if(!K(G))return G;if(V.category!==void 0){let U=s(V.category,EZ,M(q,"category"));if(!K(U))return U}let J=s(V.reversibility,vZ,M(q,"reversibility"));if(!K(J))return J}return H($)}function NX($,Z="capabilities"){if(!h($))return _(Z,"expected an object");for(let Y of Object.keys($))if(!["actionClasses","taintExposure"].includes(Y))return _(M(Z,Y),"unknown field");if(!Array.isArray($.actionClasses))return _(M(Z,"actionClasses"),"expected an array");let Q=$.actionClasses;for(let Y=0;Y<Q.length;Y++){let j=s(Q[Y],nV,M(M(Z,"actionClasses"),Y));if(!K(j))return j}let X=s($.taintExposure,["raw","mediated"],M(Z,"taintExposure"));if(!K(X))return X;let z=Q;if(X.ok==="raw"){let Y=z.find((j)=>WM.includes(j));if(Y!==void 0)return _(M(Z,"taintExposure"),`INVARIANT 1: irreversible class '${Y}' requires 'mediated'`);if(z.includes("fetch"))return _(M(Z,"taintExposure"),"INVARIANT 2: 'raw' + 'fetch' is a FORBIDDEN PAIRING (injection\u2192exfil)")}return H($)}var V3,nV,WM;var AX=E(()=>{L8();M8();J$();M$();V3=["connector_action","gateway_slice","llm_inference","channel_notice","distill_transfer","cloud_sync","marketplace_publish","fetch_url","telemetry_aggregate","diag_donation"],nV=["read","vault_write","fetch","send","pay","post","delete_at_source"],WM=["send","pay","post","delete_at_source"]});var _X=E(()=>{J$();M$()});function oV($){if(VM.includes($))return!0;if($.startsWith("error:"))return v5.includes($.slice(6));return!1}function tV($){let Z=/^(.+)@v(0|[1-9][0-9]*)$/.exec($);if(!Z)return null;return{id:Z[1],n:Number(Z[2])}}function KM($,Z="cohort"){if(!h($))return _(Z,"expected an object");for(let j of Object.keys($))if(!["platform","appBand","stackBins","usageBand"].includes(j))return _(M(Z,j),"unknown field");let Q=s($.platform,aV,M(Z,"platform"));if(!K(Q))return Q;let X=c($.appBand,M(Z,"appBand"),{nonEmpty:!0});if(!K(X))return X;let z=D$($.stackBins,M(Z,"stackBins"));if(!K(z))return z;let Y=s($.usageBand,rV,M(Z,"usageBand"));if(!K(Y))return Y;return H($)}function ZK($,Z="t2.aggregate"){if(!h($))return _(Z,"expected an object");for(let W of Object.keys($))if(!["objectType","objectRef","window","funnel","failures","cohort"].includes(W))return _(M(Z,W),"unknown field");let Q=s($.objectType,sV,M(Z,"objectType"));if(!K(Q))return Q;let X=c($.objectRef,M(Z,"objectRef"),{nonEmpty:!0});if(!K(X))return X;if(tV(X.ok)===null)return _(M(Z,"objectRef"),"expected '<id>@v<n>'");let z=s($.window,["24h"],M(Z,"window"));if(!K(z))return z;let Y=$.funnel;if(!h(Y))return _(M(Z,"funnel"),"expected counts per bucket");for(let[W,V]of Object.entries(Y)){let q=X$(V,`${M(Z,"funnel")}.${W}`,{integer:!0,min:0});if(!K(q))return q}if($.failures!==void 0){let W=$.failures;if(!h(W))return _(M(Z,"failures"),"expected counts per FailureBucket");for(let[V,q]of Object.entries(W)){if(!oV(V))return _(M(Z,"failures"),`'${V}' is not a FailureBucket ('error:<I-6 code>' | probe-fail | auth-blocked | sync-rot)`);let B=X$(q,`${M(Z,"failures")}.${V}`,{integer:!0,min:0});if(!K(B))return B}}let j=KM($.cohort,M(Z,"cohort"));if(!K(j))return j;return H($)}function QK($,Z="episode"){if(!h($))return _(Z,"expected an object");for(let q of Object.keys($))if(!["runId","orderId","demandId","skillVersions","class","signal","evidence","deltaHint","weight","delayed"].includes(q))return _(M(Z,q),"unknown field");let Q=$$($.runId,M(Z,"runId"));if(!K(Q))return Q;let X=$$($.orderId,M(Z,"orderId"));if(!K(X))return X;if($.demandId!==void 0){let q=c($.demandId,M(Z,"demandId"),{nonEmpty:!0});if(!K(q))return q}if(!Array.isArray($.skillVersions))return _(M(Z,"skillVersions"),"expected an array");let z=$.skillVersions;for(let q=0;q<z.length;q++){let B=z[q],G=M(M(Z,"skillVersions"),q);if(!h(B))return _(G,"expected {skill, version}");let J=c(B.skill,M(G,"skill"),{nonEmpty:!0});if(!K(J))return J;let U=c(B.version,M(G,"version"),{nonEmpty:!0});if(!K(U))return U}let Y=s($.class,eV,M(Z,"class"));if(!K(Y))return Y;let j=s($.signal,$K,M(Z,"signal"));if(!K(j))return j;if(!Array.isArray($.evidence))return _(M(Z,"evidence"),"expected an array of Ulids");let W=$.evidence;for(let q=0;q<W.length;q++){let B=$$(W[q],M(M(Z,"evidence"),q));if(!K(B))return B}let V=X$($.weight,M(Z,"weight"),{min:0});if(!K(V))return V;if($.delayed!==void 0){let q=$.delayed,B=M(Z,"delayed");if(!h(q))return _(B,"expected {outcomeId, ageDays, attributionConfidence}");let G=$$(q.outcomeId,M(B,"outcomeId"));if(!K(G))return G;let J=X$(q.ageDays,M(B,"ageDays"),{min:0});if(!K(J))return J;let U=X$(q.attributionConfidence,M(B,"attributionConfidence"),{min:0,max:1});if(!K(U))return U}return H($)}var sV,VM,aV,rV,eV,$K;var TX=E(()=>{J$();J$();B8();M$();sV=["skill","connector","pack","weight-config","candidate-source"],VM=["probe-fail","auth-blocked","sync-rot"];aV=["macos-arm","macos-intel"],rV=["light","daily","heavy"];eV=["win","partial","loss"],$K=["gauntlet_pass_attempt0","gauntlet_pass_retry","gauntlet_fail_final","worker_reaped","claim_survived_cited","claim_revised","claim_retracted","output_acted_on","output_edited","action_recalled","output_ignored","doc_reused_delayed","engaged_then_dropped","output_dismissed","probe_green_7d","re_rot_7d","feedback_explicit"]});var SX,rO,tO,eO;var XK=E(()=>{J$();FZ();M$();SX={version:"registry-v1",deltaFleet:0.03,kPublish:5,maxLose:1,artifactMaxBytes:2048,cohortKFloor:50,escrowExpiryDays:90},rO=SX.deltaFleet,tO=SX.cohortKFloor,eO=SX.artifactMaxBytes});var zK;var RX=E(()=>{L8();J$();M$();zK=["action","insight","question","draft","repair","pack-suggestion","fuse-notice"]});var YK=()=>{};var jK=()=>{};function qM($,Z="stream"){if(!h($))return _(Z,"expected an object");for(let V of Object.keys($))if(!["stream","kinds","deleteKind","identity","revOrder","revField"].includes(V))return _(M(Z,V),"unknown field");let Q=c($.stream,M(Z,"stream"),{nonEmpty:!0});if(!K(Q))return Q;let X=D$($.kinds,M(Z,"kinds"));if(!K(X))return X;if($.deleteKind!==void 0){let V=c($.deleteKind,M(Z,"deleteKind"),{nonEmpty:!0});if(!K(V))return V}let z=$.identity,Y=M(Z,"identity");if(!h(z))return _(Y,"expected an object");for(let V of Object.keys(z))if(!["quality","idField","rebindOn","epochField","synthesizer","noneIdentity"].includes(V))return _(M(Y,V),"unknown field");if(z.quality==="sender-claimed")return _(M(Y,"quality"),"'sender-claimed' is NOT declarable \u2014 forbidden as identity (I-1); usable only as dangling refs");let j=s(z.quality,n4,M(Y,"quality"));if(!K(j))return j;if(z.idField!==void 0){let V=c(z.idField,M(Y,"idField"),{nonEmpty:!0});if(!K(V))return V}switch(j.ok){case"durable-with-exceptions":if(z.rebindOn===void 0)return _(M(Y,"rebindOn"),"REQUIRED iff quality 'durable-with-exceptions' (documented exception conditions)");break;case"container-scoped":if(z.epochField===void 0)return _(M(Y,"epochField"),"REQUIRED iff quality 'container-scoped' (the upstream epoch token)");break;case"synthetic":if(z.synthesizer===void 0)return _(M(Y,"synthesizer"),"REQUIRED iff quality 'synthetic' (framework synthesizer \u2014 connectors never hand-roll identity)");break;case"none":if(z.noneIdentity===void 0)return _(M(Y,"noneIdentity"),"REQUIRED iff quality 'none' (I-1 wave-5 amendment: 'state' | 'occurrence')");break;default:break}if(z.rebindOn!==void 0){let V=D$(z.rebindOn,M(Y,"rebindOn"));if(!K(V))return V}if(z.epochField!==void 0){let V=c(z.epochField,M(Y,"epochField"),{nonEmpty:!0});if(!K(V))return V}if(z.synthesizer!==void 0){let V=s(z.synthesizer,U8,M(Y,"synthesizer"));if(!K(V))return V}if(z.noneIdentity!==void 0){let V=s(z.noneIdentity,i4,M(Y,"noneIdentity"));if(!K(V))return V}let W=s($.revOrder,d4,M(Z,"revOrder"));if(!K(W))return W;if(W.ok==="upstream-version"&&$.revField===void 0)return _(M(Z,"revField"),"REQUIRED iff revOrder 'upstream-version' (the field carrying it)");if($.revField!==void 0){let V=c($.revField,M(Z,"revField"),{nonEmpty:!0});if(!K(V))return V}return H($)}function qK($,Z="manifest"){if(!h($))return _(Z,"expected an object");for(let U of Object.keys($))if(!HM.includes(U))return _(M(Z,U),"unknown field");let Q=c($.source,M(Z,"source"),{nonEmpty:!0});if(!K(Q))return Q;let X=s($.tier,WK,M(Z,"tier"));if(!K(X))return X;let z=uV($.auth,M(Z,"auth"));if(!K(z))return z;if($.tccPermissions!==void 0){let U=D$($.tccPermissions,M(Z,"tccPermissions"));if(!K(U))return U}if($.vendored!==void 0){let U=$.vendored,L=M(Z,"vendored");if(!h(U))return _(L,"expected {repo, commit, license, scanReport}");for(let D of["repo","commit","license","scanReport"]){let P=c(U[D],M(L,D),{nonEmpty:!0});if(!K(P))return P}}if(!Array.isArray($.streams))return _(M(Z,"streams"),"expected an array");let Y=$.streams;for(let U=0;U<Y.length;U++){let L=qM(Y[U],M(M(Z,"streams"),U));if(!K(L))return L}if(!Array.isArray($.actions))return _(M(Z,"actions"),"expected an array");let j=$.actions;for(let U=0;U<j.length;U++){let L=t4(j[U],M(M(Z,"actions"),U));if(!K(L))return L}if($.actionScopes!==void 0){let U=$.actionScopes;if(!h(U))return _(M(Z,"actionScopes"),"expected an object of scope arrays");for(let[L,D]of Object.entries(U)){let P=D$(D,`${M(Z,"actionScopes")}.${L}`);if(!K(P))return P}}let W=s($.defaultTaint,KK,M(Z,"defaultTaint"));if(!K(W))return W;if((X.ok==="mcp-wrapped"||X.ok==="browser-driven")&&W.ok!=="quoted-only")return _(M(Z,"defaultTaint"),"tier 'mcp-wrapped' | 'browser-driven' MUST declare 'quoted-only'");let V=s($.coverageProbe,fZ,M(Z,"coverageProbe"));if(!K(V))return V;let q=$.healthProbe;if(!h(q))return _(M(Z,"healthProbe"),"expected {kind: 'fetch-one', intervalMin}");let B=s(q.kind,["fetch-one"],M(Z,"healthProbe.kind"));if(!K(B))return B;let G=X$(q.intervalMin,M(Z,"healthProbe.intervalMin"),{min:1});if(!K(G))return G;let J=s($.retaliationRisk,VK,M(Z,"retaliationRisk"));if(!K(J))return J;return H($)}var WK,fZ,VK,KK,HM;var kZ=E(()=>{M9();M8();N8();J$();M$();WK=["api","mcp-wrapped","local-app","extension","browser-driven","screen"],fZ=["count-api","pagination-exhaustion","census"],VK=["tolerant","hostile","banning"],KK=["quoted-only","summarized-only"];HM=["source","tier","auth","tccPermissions","vendored","streams","actions","actionScopes","defaultTaint","coverageProbe","healthProbe","retaliationRisk"]});function BM($,Z,Q){if(Q==="user-disable")return $!=="DISABLED"&&Z==="DISABLED";switch(`${$}->${Z}`){case"IDLE->DISCOVERING":return Q==="schedule"||Q==="event";case"DISCOVERING->PULLING":return Q==="census-ok";case"DISCOVERING->AUTH_BLOCKED":case"PULLING->AUTH_BLOCKED":case"RECONCILING->AUTH_BLOCKED":return Q==="auth-error";case"PULLING->RETRY_WAIT":return Q==="page-error:transient"||Q==="page-error:throttling";case"PULLING->ERRORED":return Q.startsWith("non-retryable:")&&Q.length>14;case"DISCOVERING->IDLE":return Q==="run-failed"||Q==="timeout:DISCOVERING";case"PULLING->IDLE":return Q==="run-failed"||Q==="stream-stall"||Q==="timeout:PULLING";case"RECONCILING->IDLE":return Q==="run-failed"||Q==="reconcile-clean"||Q==="gap-attributed"||Q==="timeout:RECONCILING";case"RETRY_WAIT->PULLING":return Q==="backoff-due";case"PULLING->RECONCILING":return Q==="exhausted";case"RECONCILING->PULLING":return Q==="heal:1"||Q==="heal:2";case"RECONCILING->INCIDENT":return Q==="gap-persists-at-K"||Q==="duplicate-object-signal";case"AUTH_BLOCKED->DISCOVERING":return Q==="auth-repaired";case"ERRORED->DISCOVERING":return Q==="repair-completed"||Q==="user-retry"||Q==="scheduled-reprobe";case"INCIDENT->IDLE":return Q==="incident-resolved";case"DISABLED->DISCOVERING":return Q==="user-enable";case"DISCOVERING->DISCOVERING":case"PULLING->DISCOVERING":case"RECONCILING->DISCOVERING":return Q==="crash-recovery";default:return!1}}function IX($,Z,Q){if(!h($))return _(Q,"expected an object");let X=VV($,Z,Q);if(!K(X))return X;return H($)}function HK($,Z){let Q=c($.source,M(Z,"source"),{nonEmpty:!0,maxLength:128});if(!K(Q))return Q;let X=$$($.grantId,M(Z,"grantId"));if(!K(X))return X;return H(!0)}function Y5($,Z,Q){if(Q&&$===null)return H(!0);let X=$$($,Z);return K(X)?H(!0):X}function wZ($,Z){let Q=h$($,Z);return K(Q)?H(!0):Q}function mZ($,Z){let Q=c($,Z,{nonEmpty:!0,maxLength:256});return K(Q)?H(!0):Q}function OX($,Z){if(!Array.isArray($)||$.length>1024)return _(Z,"expected at most 1024 partial-reason rows");for(let Q=0;Q<$.length;Q++){let X=$[Q];if(!h(X))return _(M(Z,Q),"expected an object");let z=b$(X,["reason","count"],M(Z,Q));if(!K(z))return z;let Y=c(X.reason,M(M(Z,Q),"reason"),{nonEmpty:!0,maxLength:256});if(!K(Y))return Y;if(X.count!==void 0){let j=X$(X.count,M(M(Z,Q),"count"),{integer:!0,min:0});if(!K(j))return j}}return H(!0)}function UM($,Z){let Q=c($,Z,{nonEmpty:!0,maxLength:128});if(!K(Q))return Q;return JM.test(Q.ok)?H(!0):_(Z,"expected a bounded lowercase machine-code reason")}function BK($,Z="census"){let Q=IX($,["asOf","streams"],Z);if(!K(Q))return Q;let X=b$(Q.ok,["asOf","streams"],Z);if(!K(X))return X;let z=h$(Q.ok.asOf,M(Z,"asOf"));if(!K(z))return z;let Y=Q.ok.streams;if(!h(Y))return _(M(Z,"streams"),"expected an object");let j=Object.entries(Y);if(j.length>1024)return _(M(Z,"streams"),"must contain at most 1024 streams");for(let[W,V]of j){let q=c(W,M(Z,"streams"),{nonEmpty:!0,maxLength:128});if(!K(q))return q;let B=`${M(Z,"streams")}.${W}`;if(!h(V))return _(B,"expected an object");let G=b$(V,["total","method","partialReasons"],B);if(!K(G))return G;let J=s(V.method,fZ,M(B,"method"));if(!K(J))return J;if(V.total!==void 0){let U=X$(V.total,M(B,"total"),{integer:!0,min:0});if(!K(U))return U}if(V.partialReasons!==void 0){let U=OX(V.partialReasons,M(B,"partialReasons"));if(!K(U))return U}}return H($)}function LM($,Z){if(!Array.isArray($)||$.length>4096)return _(Z,"expected at most 4096 coverage verdicts");for(let Q=0;Q<$.length;Q++){let X=$[Q],z=M(Z,Q);if(!h(X))return _(z,"expected an object");let Y=c(X.stream,M(z,"stream"),{nonEmpty:!0,maxLength:128});if(!K(Y))return Y;let j=s(X.kind,["clean","attributed","unattributed-gap","duplicate-object","no-total"],M(z,"kind"));if(!K(j))return j;let W=(V,q=0)=>X$(X[V],M(z,V),{integer:!0,min:q});if(j.ok==="clean"){let V=b$(X,["stream","kind"],z);if(!K(V))return V}else if(j.ok==="attributed"){let V=b$(X,["stream","kind","reasons"],z);if(!K(V))return V;let q=OX(X.reasons,M(z,"reasons"));if(!K(q))return q}else if(j.ok==="no-total"){let V=b$(X,["stream","kind","enumerated","reasons"],z);if(!K(V))return V;let q=W("enumerated");if(!K(q))return q;if(X.reasons!==void 0){let B=OX(X.reasons,M(z,"reasons"));if(!K(B))return B}}else{let V=j.ok==="unattributed-gap"?"gap":"surplus",q=b$(X,["stream","kind","expected","covered",V],z);if(!K(q))return q;for(let B of["expected","covered",V]){let G=W(B,B===V?1:0);if(!K(G))return G}}}return H(!0)}function w$($,Z,Q=$){let X=IX(Z,["source","grantId"],Q);if(!K(X))return X;let z=HK(X.ok,Q);if(!K(z))return z;let Y=X.ok,j;switch($){case"sync.run.transition":{if(j=b$(Y,["source","grantId","runId","from","to","cause","attempt","healAttempt","pendingBackfill","backoffDueAt","lastSynced","at","error","reasons","gap","detail"],Q),!K(j))return j;for(let U of["runId","from","to","cause","attempt","healAttempt","pendingBackfill","backoffDueAt","lastSynced","at"])if(Y[U]===void 0)return _(M(Q,U),"required field missing");let W=Y5(Y.runId,M(Q,"runId"),!0);if(!K(W))return W;for(let U of["from","to"]){let L=s(Y[U],xX,M(Q,U));if(!K(L))return L}let V=mZ(Y.cause,M(Q,"cause"));if(!K(V))return V;if(!BM(Y.from,Y.to,Y.cause))return _(Q,`undeclared sync transition ${String(Y.from)} -> ${String(Y.to)} for cause '${String(Y.cause)}'`);let q=X$(Y.attempt,M(Q,"attempt"),{integer:!0,min:0,max:5});if(!K(q))return q;let B=X$(Y.healAttempt,M(Q,"healAttempt"),{integer:!0,min:0,max:2});if(!K(B))return B;let G=u0(Y.pendingBackfill,M(Q,"pendingBackfill"));if(!K(G))return G;for(let U of["backoffDueAt","lastSynced"])if(Y[U]!==null){let L=h$(Y[U],M(Q,U));if(!K(L))return L}let J=wZ(Y.at,M(Q,"at"));if(!K(J))return J;if(Y.error!==void 0){let U=D9(Y.error,M(Q,"error"));if(!K(U))return U}if(Y.reasons!==void 0&&!Array.isArray(Y.reasons)&&!h(Y.reasons))return _(M(Q,"reasons"),"expected an object or array");for(let U of["gap","detail"])if(Y[U]!==void 0&&!h(Y[U]))return _(M(Q,U),"expected an object");break}case"sync.run.aborted":{if(j=b$(Y,["source","grantId","runId","cause","at"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;let V=mZ(Y.cause,M(Q,"cause"));if(!K(V))return V;let q=wZ(Y.at,M(Q,"at"));if(!K(q))return q;break}case"sync.incident.filed":{if(j=b$(Y,["source","grantId","runId","cause","class","detail","at"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!0);if(!K(W))return W;let V=mZ(Y.cause,M(Q,"cause"));if(!K(V))return V;let q=c(Y.class,M(Q,"class"),{nonEmpty:!0,maxLength:128});if(!K(q))return q;let B=wZ(Y.at,M(Q,"at"));if(!K(B))return B;break}case"sync.incident.resolved":case"sync.repair.completed":{if(j=b$(Y,["source","grantId","cause","at"],Q),!K(j))return j;let W=mZ(Y.cause,M(Q,"cause"));if(!K(W))return W;let V=wZ(Y.at,M(Q,"at"));if(!K(V))return V;break}case"sync.repair.filed":case"sync.cursor.expired":{if(j=b$(Y,["source","grantId","runId",...$==="sync.repair.filed"?["cause"]:[],"at"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!0);if(!K(W))return W;if($==="sync.repair.filed"){let q=mZ(Y.cause,M(Q,"cause"));if(!K(q))return q}let V=wZ(Y.at,M(Q,"at"));if(!K(V))return V;break}case"sync.census.observed":{if(j=b$(Y,["source","grantId","runId","census"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;let V=BK(Y.census,M(Q,"census"));if(!K(V))return V;break}case"sync.coverage.reconciled":{if(j=b$(Y,["source","grantId","runId","verdicts"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;let V=LM(Y.verdicts,M(Q,"verdicts"));if(!K(V))return V;break}case"sync.coverage.omission.observed":{if(j=b$(Y,["source","grantId","runId","stream","reason","parent"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;let V=c(Y.stream,M(Q,"stream"),{nonEmpty:!0,maxLength:128});if(!K(V))return V;let q=UM(Y.reason,M(Q,"reason"));if(!K(q))return q;if(!h(Y.parent))return _(M(Q,"parent"),"expected an object");let B=Y.parent,G=b$(B,["stream","sourceId"],M(Q,"parent"));if(!K(G))return G;for(let J of["stream","sourceId"]){let U=c(B[J],M(M(Q,"parent"),J),{nonEmpty:!0,maxLength:J==="stream"?128:1024});if(!K(U))return U}break}case"sync.cursor.advanced":{if(j=b$(Y,["source","grantId","runId","cursor"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;if(Y.cursor!==null){let V=c(Y.cursor,M(Q,"cursor"),{maxLength:16384});if(!K(V))return V}break}case"sync.security.token-carryover":{if(j=b$(Y,["source","grantId","runId","stream","pattern","class","identity"],Q),!K(j))return j;let W=Y5(Y.runId,M(Q,"runId"),!1);if(!K(W))return W;for(let q of["stream","class"]){let B=c(Y[q],M(Q,q),{nonEmpty:!0,maxLength:128});if(!K(B))return B}let V=c(Y.pattern,M(Q,"pattern"),{nonEmpty:!0,maxLength:uZ});if(!K(V))return V;if(Y.identity!==void 0){let q=c(Y.identity,M(Q,"identity"),{nonEmpty:!0,maxLength:64});if(!K(q))return q;if(!GM.test(q.ok))return _(M(Q,"identity"),"expected a lowercase sha256 containment digest")}break}}return H(Z)}function JK($,Z="sync.certificate.issued"){let Q=IX($,["source","grantId","runId","authMethod","manifestStreams","manifestTreeHash","coverageTableHash","eventCount","terminalEventUlid","censusEventUlid","reconciliationEventUlid","recallEventUlid"],Z);if(!K(Q))return Q;let X=b$(Q.ok,["source","grantId","runId","authMethod","manifestStreams","manifestTreeHash","coverageTableHash","eventCount","terminalEventUlid","censusEventUlid","reconciliationEventUlid","recallEventUlid","pipelineOrderUlid","lawfulLeaf"],Z);if(!K(X))return X;let z=HK(Q.ok,Z);if(!K(z))return z;for(let q of["runId","terminalEventUlid","censusEventUlid","reconciliationEventUlid","recallEventUlid"]){let B=$$(Q.ok[q],M(Z,q));if(!K(B))return B}for(let q of["authMethod"]){let B=c(Q.ok[q],M(Z,q),{nonEmpty:!0,maxLength:128});if(!K(B))return B}let Y=D$(Q.ok.manifestStreams,M(Z,"manifestStreams"));if(!K(Y)||K(Y)&&Y.ok.length>1024)return K(Y)?_(M(Z,"manifestStreams"),"must contain at most 1024 streams"):Y;for(let q of["manifestTreeHash","coverageTableHash"]){let B=M0(Q.ok[q],M(Z,q));if(!K(B))return B}let j=X$(Q.ok.eventCount,M(Z,"eventCount"),{integer:!0,min:0});if(!K(j))return j;let W=Q.ok.pipelineOrderUlid!==void 0,V=Q.ok.lawfulLeaf!==void 0;if(W===V)return _(Z,"exactly one of pipelineOrderUlid or lawfulLeaf is required");if(W){let q=$$(Q.ok.pipelineOrderUlid,M(Z,"pipelineOrderUlid"));if(!K(q))return q}else{let q=c(Q.ok.lawfulLeaf,M(Z,"lawfulLeaf"),{nonEmpty:!0,maxLength:256});if(!K(q))return q}return H($)}var xX,hZ,uZ=1024,JM,GM;var GK=E(()=>{kZ();J$();M$();xX=["IDLE","DISCOVERING","PULLING","RECONCILING","RETRY_WAIT","AUTH_BLOCKED","ERRORED","INCIDENT","DISABLED"],hZ=["sync.run.transition","sync.run.aborted","sync.incident.filed","sync.incident.resolved","sync.repair.filed","sync.repair.completed","sync.census.observed","sync.coverage.reconciled","sync.coverage.omission.observed","sync.cursor.advanced","sync.cursor.expired","sync.security.token-carryover"];JM=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,GM=/^[0-9a-f]{64}$/});var UK=E(()=>{B8();J$();kZ();M$()});var LK,AM,_M,yX,K3,TM,DK,SM,dx,RM,nx,ix;var MK=E(()=>{J$();M9();OZ();L8();IZ();M8();e4();bZ();X3();N8();Y3();j3();W3();AX();_X();TX();RX();kZ();LK={type:"string",pattern:"^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$"},AM={type:"string",pattern:"^[0-9a-f]{64}$"},_M={type:"string",format:"date-time"},yX={type:"string"},K3={type:"integer"},TM={type:"boolean"},DK={type:"array",items:yX},SM={type:"array",items:LK},dx={$id:"indra:contracts:TaintTag",type:"object",required:["level","sources"],additionalProperties:!1,properties:{level:{enum:xZ},sources:{...DK,maxItems:33}}},RM={$id:"indra:contracts:BlobRef",type:"object",required:["sha256","bytes"],additionalProperties:!1,properties:{sha256:AM,bytes:K3,mime:yX,name:yX}},nx={$id:"indra:contracts:FusePolicy",type:"object",required:["rows"],additionalProperties:!1,properties:{rows:{type:"object",required:f5,additionalProperties:!1,properties:Object.fromEntries(f5.map(($)=>[$,{type:"object",required:["baseMs","floorMs","capMs","decay"],additionalProperties:!1,properties:{baseMs:K3,floorMs:K3,capMs:K3,decay:{enum:["earned","none"]}}}]))}}},ix={$id:"indra:contracts:FeedItem",type:"object",required:["recId","kind","headline","why","actions","provenance","explore","deliver"],additionalProperties:!1,properties:{recId:LK,kind:{enum:zK},headline:{type:"string",maxLength:140},why:{...DK,minItems:1,maxItems:3},body:RM,actions:{type:"array",minItems:1,maxItems:3},provenance:SM,explore:TM,deliver:{enum:["feed","notify"]},expiresAt:_M}}});var CK=E(()=>{J$();M9();OZ();L8();IZ();M8();e4();bZ();X3();MX();N8();PX();Y3();j3();W3()});var f=E(()=>{M$();J$();KV();qV();FZ();l4();B8();UV();l2();n2();i2();SV();M9();OZ();L8();IZ();M8();e4();bZ();X3();MX();N8();PX();lV();Y3();j3();W3();dV();AX();_X();TX();XK();RX();YK();jK();kZ();GK();UK();MK();CK()});function T$($,Z,Q,X){let z={code:$,layer:"auth",retryability:Z,message:Q};if(X!==void 0)z.cause=X;return z}function I($,Z,Q,X){return v(T$($,Z,Q,X))}function j5($,Z,Q){let{code:X,retryability:z}=FK[$];return I(X,z,Z,Q)}function p0($){return I("failed_precondition","non-retryable",`blocked by G2: '${$}' requires a real provider flow/network \u2014 fabricate against fixture IdPs only`)}function EX($){return I("permission_denied","non-retryable",`hard-blocked by F21: automating the '${$}' login form is forbidden (account survival outranks automation purity; D9 retaliation-risk doctrine)`)}function vX($){return I("permission_denied","non-retryable",`blocked by the D9 retaliation-risk gate: provider '${$}' is retaliationRisk 'banning' \u2014 no driver at all, passive/screen tiers only (auth.md \xA74.7)`)}function q3($){return p0(`rung-B driven-browser flow '${$}'`)}var FK;var X0=E(()=>{f();FK={upstreamDefinitive:{code:"unauthenticated",retryability:"non-retryable"},upstreamUnknown:{code:"unavailable",retryability:"transient"},upstreamThrottled:{code:"resource_exhausted",retryability:"throttling"},lockedOverlay:{code:"failed_precondition",retryability:"retry-at-higher-level"},heartbeatStale:{code:"failed_precondition",retryability:"non-retryable"},handleExpired:{code:"unauthenticated",retryability:"retry-at-higher-level"},allowlistReject:{code:"invalid_argument",retryability:"non-retryable"},scopeViolation:{code:"permission_denied",retryability:"non-retryable"},authorizationHeaderPresent:{code:"invalid_argument",retryability:"non-retryable"}}});class B3{values=new Map([["ZTXCANARY-v1-4d1f8a2be97c-do-not-emit",1]]);register($){if($!==void 0&&$.length>=8)this.values.set($,(this.values.get($)??0)+1)}unregister($){if($===void 0||$==="ZTXCANARY-v1-4d1f8a2be97c-do-not-emit")return;let Z=this.values.get($);if(Z===void 0)return;if(Z<=1)this.values.delete($);else this.values.set($,Z-1)}hits($){let Z=[];for(let Q of this.values.keys()){let X=0;for(;;){let z=$.indexOf(Q,X);if(z===-1)break;Z.push({pattern:"stored-value",index:z,length:Q.length}),X=z+Q.length}}return Z}firstHit($,Z){for(let Q of this.values.keys()){if(Z())return{complete:!1,hit:null};let X=$.indexOf(Q);if(Z())return{complete:!1,hit:null};if(X!==-1)return{complete:!0,hit:{pattern:"stored-value",index:X,length:Q.length}}}return{complete:!0,hit:null}}}function l0($,Z){let Q=[];for(let{name:X,re:z}of gX){z.lastIndex=0;let Y;while((Y=z.exec($))!==null)if(Q.push({pattern:X,index:Y.index,length:Y[0].length}),Y[0].length===0)z.lastIndex++}if(Z!==void 0)Q.push(...Z.hits($));return Q}function fX($,Z,Q){for(let{name:X,re:z}of gX){if(Q())return{complete:!1,hit:null};z.lastIndex=0;let Y=z.exec($);if(Q())return{complete:!1,hit:null};if(Y!==null)return{complete:!0,hit:{pattern:X,index:Y.index,length:Y[0].length}}}return Z?.firstHit($,Q)??{complete:!0,hit:null}}function NK($,Z){let Q=l0($,Z);if(Q.length===0)return{text:$,hits:Q};let X=[...Q].sort((Y,j)=>j.index-Y.index||j.length-Y.length),z=$;for(let Y of X)z=z.slice(0,Y.index)+"[REDACTED:token]"+z.slice(Y.index+Y.length);return{text:z,hits:Q}}function J3($,Z){let{text:Q,hits:X}=NK($.message,Z),z={...$,message:Q};if($.cause!==void 0){let Y=J3($.cause,Z);z.cause=Y.error,X.push(...Y.hits)}return{error:z,hits:X}}var H3="ZTXCANARY-v1-4d1f8a2be97c-do-not-emit",bX="[REDACTED:token]",gX;var A8=E(()=>{gX=[{name:"provider secret key (sk-\u2026)",re:/\bsk-[A-Za-z0-9_-]{16,}/g},{name:"google-access (ya29.)",re:/ya29\.[A-Za-z0-9_.\-]{8,}/g},{name:"google-refresh (1//)",re:/\b1\/\/[A-Za-z0-9_\-]{8,}/g},{name:"github classic token (ghp/ghs)",re:/\bgh[ps]_[A-Za-z0-9]{20,}/g},{name:"github (gho_/ghu_/ghr_)",re:/\bgh[our]_[A-Za-z0-9]{8,}/g},{name:"github fine-grained PAT",re:/\bgithub_pat_[A-Za-z0-9_]{20,}/g},{name:"slack (xox[bpae]-)",re:/\bxox[bpae]-[A-Za-z0-9\-]{8,}/g},{name:"slack legacy (xoxr/xoxs)",re:/\bxox[rs]-[A-Za-z0-9\-]{8,}/g},{name:"slack-rotating (xoxe)",re:/\bxoxe[.\-][A-Za-z0-9\-]{8,}/g},{name:"notion (secret_)",re:/\bsecret_[A-Za-z0-9]{16,}/g},{name:"notion (ntn_)",re:/\bntn_[A-Za-z0-9]{16,}/g},{name:"posthog-personal (phx_)",re:/phx_[A-Za-z0-9_\-]{32,}/g},{name:"google-drive-resource-key",re:/(?:"(?:resourceKey|targetResourceKey)"\s*:\s*"[^"\r\n]{8,}"|[?&]resourcekey=[^&"'\s\\]{8,})/giu},{name:"aws access key id",re:/\bAKIA[0-9A-Z]{16}\b/g},{name:"bearer credential",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g},{name:"jwt (eyJ)",re:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{4,}/g},{name:"vault-canary",re:new RegExp("ZTXCANARY-v1-4d1f8a2be97c-do-not-emit".replace(/[.*+?^${}()|[\]\\-]/g,"\\$&"),"g")}]});import{chmodSync as xM,existsSync as G3,mkdirSync as AK,readFileSync as _K,writeFileSync as TK}from"fs";import{spawnSync as IM}from"child_process";import{join as SK}from"path";import{createHash as yM,randomBytes as mX}from"crypto";function c0($){return I("failed_precondition","retry-at-higher-level",`keychain master key unreadable: ${$} (LOCKED overlay, auth.md \xA74.3 \u2014 no plaintext fallback ever)`)}function wX($){let Z=$.trim();if(!EM.test(Z))return c0("stored payload is not a 64-char hex 32-byte key");let Q=new Uint8Array(C9);for(let X=0;X<C9;X++)Q[X]=parseInt(Z.slice(X*2,X*2+2),16);return H(Q)}function RK($){return Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class U3{kind="file-double";path;locked=!1;constructor($){AK($,{recursive:!0}),this.path=SK($,"master.key")}lock(){this.locked=!0}unlock(){this.locked=!1}getMasterKey(){if(this.locked)return c0("keystore locked (simulated login-keychain lock)");if(!G3(this.path))return c0("no master key item exists");return wX(_K(this.path,"utf8"))}ensureMasterKey(){if(this.locked)return c0("keystore locked (simulated login-keychain lock)");if(!G3(this.path)){let $=mX(C9);TK(this.path,RK(Uint8Array.from($)),{mode:384}),xM(this.path,384)}return this.getMasterKey()}}class uX{account;runner;kind="macos-keychain";constructor($,Z=hX){this.account=$;this.runner=Z}findArgv(){return["security","find-generic-password","-s",kX,"-a",this.account,"-w"]}addArgv($){return["security","add-generic-password","-s",kX,"-a",this.account,"-w",$,"-U"]}getMasterKey(){let $=this.runner(this.findArgv());if($.exitCode!==0)return c0(`security find-generic-password exited ${$.exitCode}: ${$.stderr.trim()}`);return wX($.stdout)}ensureMasterKey(){let $=this.runner(this.findArgv());if($.exitCode===0)return wX($.stdout);let Z=RK(Uint8Array.from(mX(C9))),Q=this.runner(this.addArgv(Z));if(Q.exitCode!==0)return c0(`security add-generic-password exited ${Q.exitCode}: ${Q.stderr.trim()}`);return this.getMasterKey()}}class pX{runner;kind="windows-dpapi";path;entropy;constructor($,Z,Q=OK){this.runner=Q;AK($,{recursive:!0}),this.path=SK($,"master.dpapi"),this.entropy=Uint8Array.from(yM("sha256").update(`zortex.windows-dpapi.v1\x00${Z}`).digest())}getMasterKey(){if(!G3(this.path))return c0("no CurrentUser DPAPI master-key blob exists");let $=_K(this.path,"utf8").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test($))return c0("stored DPAPI blob is malformed");let Z=this.runner("unprotect",Uint8Array.from(Buffer.from($,"base64")),this.entropy);if(!("ok"in Z))return Z;if(Z.ok.length!==C9)return c0("DPAPI plaintext is not a 32-byte master key");return Z}ensureMasterKey(){if(G3(this.path))return this.getMasterKey();let $=Uint8Array.from(mX(C9)),Z=this.runner("protect",$,this.entropy);if(!("ok"in Z))return Z;try{TK(this.path,Buffer.from(Z.ok).toString("base64"),{encoding:"utf8",mode:384,flag:"wx"})}catch(Q){if(Q.code==="EEXIST")return this.getMasterKey();return c0(`cannot write CurrentUser DPAPI blob: ${Q instanceof Error?Q.message:String(Q)}`)}return this.getMasterKey()}}function pZ($){let Z=$.env.ZORTEX_KEYSTORE??"file-double";if(Z==="macos-keychain"){let Q=$.platform??process.platform;if(Q!=="darwin"&&$.runner===void 0)return I("failed_precondition","non-retryable",`ZORTEX_KEYSTORE=macos-keychain requires macOS (login keychain, auth.md \xA72); platform is '${Q}'`);return H(new uX($.account,$.runner??hX))}if(Z==="windows-dpapi"){let Q=$.platform??process.platform;if(Q!=="win32")return I("failed_precondition","non-retryable",`ZORTEX_KEYSTORE=windows-dpapi requires Windows; platform is '${Q}'`);return H(new pX($.dir,$.account))}if(Z==="file-double"){if($.production===!0)return I("failed_precondition","non-retryable","ZORTEX_KEYSTORE=file-double is a test-only keystore and is refused in a production profile");return H(new U3($.dir))}return I("invalid_argument","non-retryable",`unknown ZORTEX_KEYSTORE '${Z}' (expected 'macos-keychain' | 'windows-dpapi' | 'file-double')`)}var kX="com.zortex.vault-master",C9=32,EM,hX=($)=>{let Z=Bun.spawnSync($,{stdout:"pipe",stderr:"pipe"});return{exitCode:Z.exitCode,stdout:Z.stdout.toString(),stderr:Z.stderr.toString()}},vM,OK=($,Z,Q)=>{if(process.platform!=="win32")return I("failed_precondition","non-retryable",`Windows DPAPI requires Windows; platform is '${process.platform}'`);let X=JSON.stringify({data:Buffer.from(Z).toString("base64"),entropy:Buffer.from(Q).toString("base64")}),z=Buffer.from(vM[$],"utf16le").toString("base64"),Y=IM("powershell.exe",["-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",z],{input:Buffer.from(X),encoding:"buffer"});if(Y.error!==void 0||Y.status!==0){let W=Buffer.from(Y.stderr??[]).toString().trim().replace(/\s+/g," ").slice(0,240),V=Y.status??-1;return I("failed_precondition","retry-at-higher-level",`Windows DPAPI ${$} failed (PowerShell exit ${V}${W===""?"":`: ${W}`})`)}let j=Buffer.from(Y.stdout??[]).toString().trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(j))return I("failed_precondition","retry-at-higher-level",`Windows DPAPI ${$} returned an invalid protected blob`);return H(Uint8Array.from(Buffer.from(j,"base64")))};var lX=E(()=>{f();X0();EM=/^[0-9a-f]{64}$/;vM={protect:["Add-Type -AssemblyName System.Security","$payload = [Console]::In.ReadToEnd() | ConvertFrom-Json","$data = [Convert]::FromBase64String([string]$payload.data)","$entropy = [Convert]::FromBase64String([string]$payload.entropy)","$out = [System.Security.Cryptography.ProtectedData]::Protect($data, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Convert]::ToBase64String($out))"].join("; "),unprotect:["Add-Type -AssemblyName System.Security","$payload = [Console]::In.ReadToEnd() | ConvertFrom-Json","$data = [Convert]::FromBase64String([string]$payload.data)","$entropy = [Convert]::FromBase64String([string]$payload.entropy)","$out = [System.Security.Cryptography.ProtectedData]::Unprotect($data, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Convert]::ToBase64String($out))"].join("; ")}});import{createCipheriv as bM,createDecipheriv as gM,randomBytes as fM}from"crypto";function F9($,Z,Q){let X=fM(_8),z=bM("aes-256-gcm",$,X);z.setAAD(Buffer.from(Z,"utf8"));let Y=Buffer.concat([z.update(Buffer.from(Q,"utf8")),z.final()]),j=z.getAuthTag();return L3+Buffer.concat([X,j,Y]).toString("base64")}function N9($,Z,Q){if(!Q.startsWith(L3))return I("data_loss","non-retryable",`secret cell is not '${L3}' format \u2014 vault row corrupt`);let X=Buffer.from(Q.slice(L3.length),"base64");if(X.length<_8+cX)return I("data_loss","non-retryable","secret cell truncated \u2014 vault row corrupt");let z=X.subarray(0,_8),Y=X.subarray(_8,_8+cX),j=X.subarray(_8+cX);try{let W=gM("aes-256-gcm",$,z);W.setAAD(Buffer.from(Z,"utf8")),W.setAuthTag(Y);let V=Buffer.concat([W.update(j),W.final()]);return H(V.toString("utf8"))}catch{return I("failed_precondition","retry-at-higher-level","secret cell failed AES-GCM authentication (wrong master key, moved cell, or tampered bytes) \u2014 recovery is re-auth, never replay (I-8)")}}var L3="gcm1:",_8=12,cX=16;var dX=E(()=>{f();X0()});import{Database as kM}from"bun:sqlite";import{existsSync as wM,mkdirSync as mM,readFileSync as hM,rmSync as uM,writeFileSync as pM}from"fs";import{join as xK}from"path";function iX($){let Z={grantId:$.grant_id,source:$.source,account:{id:$.account_id,label:$.account_label},provider:$.provider,method:$.method,clientMode:$.client_mode,scopes:JSON.parse($.scopes),state:$.state,authorityVersion:$.authority_version,stateAt:$.state_at,issuedAt:$.issued_at,lastUsedAt:$.last_used_at,lastRefreshOkAt:$.last_refresh_ok_at};if($.client_id!==null)Z.clientId=$.client_id;if($.refresh_at!==null)Z.refreshAt=$.refresh_at;if($.keepalive_at!==null)Z.keepaliveAt=$.keepalive_at;if($.at_expires_at!==null)Z.atExpiresAt=$.at_expires_at;if($.dispatch_eligible_at!==null)Z.dispatchEligibleAt=$.dispatch_eligible_at;if($.retry_n!==null&&$.retry_next_at!==null&&$.retry_first_fail_at!==null)Z.retry={n:$.retry_n,nextAt:$.retry_next_at,firstFailAt:$.retry_first_fail_at};return Z}function IK($,Z,Q){let X=["state = ?","state_at = ?"],z=[$,Z];if(Q?.refreshAt!==void 0)X.push("refresh_at = ?"),z.push(Q.refreshAt);if(Q?.keepaliveAt!==void 0)X.push("keepalive_at = ?"),z.push(Q.keepaliveAt);if(Q?.atExpiresAt!==void 0)X.push("at_expires_at = ?"),z.push(Q.atExpiresAt);if(Q?.lastUsedAt!==void 0)X.push("last_used_at = ?"),z.push(Q.lastUsedAt);if(Q?.dispatchEligibleAt!==void 0)X.push("dispatch_eligible_at = ?"),z.push(Q.dispatchEligibleAt);if(Q?.retry!==void 0)X.push("retry_n = ?","retry_next_at = ?","retry_first_fail_at = ?"),z.push(Q.retry.n,Q.retry.nextAt,Q.retry.firstFailAt);else if(Q?.clearRetry===!0)X.push("retry_n = NULL","retry_next_at = NULL","retry_first_fail_at = NULL");return{sets:X,args:z}}function lZ($){return I("failed_precondition","non-retryable",`${$}: grant authority mutation requires an atomic transition audit`)}function yK($,Z){return I("failed_precondition","non-retryable",`${$}: no-op grant transition ${Z} \u2192 ${Z} is forbidden`)}class k5{instanceId;registry;db;key;lockPath;keyStore;ulid=V$();closed=!1;constructor($,Z,Q,X,z){this.db=$,this.key=Z,this.keyStore=Q.keyStore,this.registry=Q.registry??new B3,this.instanceId=X,this.lockPath=z}static open($){mM($.dir,{recursive:!0});let Z=xK($.dir,".writer.lock");if(wM(Z)){let V=JSON.parse(hM(Z,"utf8")),q=!1;try{process.kill(V.pid,0),q=V.pid!==process.pid}catch{q=!1}if(q)return I("failed_precondition","non-retryable",`grants.db writer lock held by live pid ${V.pid} \u2014 ONE writer, the broker thread (FM-23, auth.md \xA74.1)`)}let Q=$.keyStore.ensureMasterKey();if(!K(Q))return Q;let X=Q.ok,z=new kM(xK($.dir,"grants.db"),{create:!0});z.exec("PRAGMA journal_mode = WAL;"),z.exec(`
5
+ CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
6
+ CREATE TABLE IF NOT EXISTS grants (
7
+ grant_id TEXT PRIMARY KEY,
8
+ source TEXT NOT NULL,
9
+ account_id TEXT NOT NULL,
10
+ account_label TEXT NOT NULL,
11
+ provider TEXT NOT NULL,
12
+ method TEXT NOT NULL,
13
+ client_mode TEXT NOT NULL,
14
+ client_id TEXT,
15
+ scopes TEXT NOT NULL,
16
+ state TEXT NOT NULL,
17
+ state_at TEXT NOT NULL,
18
+ authority_version INTEGER NOT NULL DEFAULT 0,
19
+ refresh_at TEXT, keepalive_at TEXT,
20
+ retry_n INTEGER, retry_next_at TEXT, retry_first_fail_at TEXT,
21
+ issued_at TEXT NOT NULL, last_used_at TEXT NOT NULL, last_refresh_ok_at TEXT NOT NULL,
22
+ at_expires_at TEXT, dispatch_eligible_at TEXT,
23
+ secrets TEXT NOT NULL DEFAULT '{}',
24
+ UNIQUE(source, account_id)
25
+ );
26
+ CREATE TABLE IF NOT EXISTS flows (
27
+ flow_id TEXT PRIMARY KEY,
28
+ flow_type TEXT NOT NULL,
29
+ source TEXT NOT NULL,
30
+ provider TEXT NOT NULL,
31
+ account_hint TEXT,
32
+ scopes TEXT NOT NULL,
33
+ state TEXT NOT NULL,
34
+ state_at TEXT NOT NULL,
35
+ stuck_class TEXT,
36
+ batch_id TEXT,
37
+ redirect_port INTEGER,
38
+ state_nonce TEXT,
39
+ grant_id TEXT,
40
+ resume_used INTEGER NOT NULL DEFAULT 0,
41
+ cells TEXT NOT NULL DEFAULT '{}'
42
+ );
43
+ CREATE TABLE IF NOT EXISTS grant_transition_outbox (
44
+ grant_id TEXT NOT NULL,
45
+ authority_version INTEGER NOT NULL,
46
+ prior_authority_version INTEGER NOT NULL,
47
+ from_state TEXT NOT NULL,
48
+ to_state TEXT NOT NULL,
49
+ reason TEXT NOT NULL,
50
+ transition_at TEXT NOT NULL,
51
+ recovered_by TEXT,
52
+ delivered_at TEXT,
53
+ PRIMARY KEY (grant_id, authority_version)
54
+ );
55
+ `);try{if(!z.query("PRAGMA table_info(grants)").all().some(({name:B})=>B==="authority_version"))z.transaction(()=>{z.exec("ALTER TABLE grants ADD COLUMN authority_version INTEGER NOT NULL DEFAULT 0"),z.query("INSERT OR REPLACE INTO meta (k, v) VALUES ('migration:grant-authority-version:v1', 'applied')").run()})();if(z.query("SELECT authority_version FROM grants").all().some(({authority_version:B})=>!Number.isSafeInteger(B)||B<0))return z.close(),I("data_loss","non-retryable","grant authority generation is malformed; encrypted vault rows were left unchanged")}catch{return z.close(),I("data_loss","non-retryable","grant authority generation migration failed; encrypted vault rows were left unchanged")}let Y=z.query("SELECT v FROM meta WHERE k='instance'").get()?.v;if(Y===void 0)Y=V$()(),z.query("INSERT INTO meta (k, v) VALUES ('instance', ?)").run(Y);let j=z.query("SELECT v FROM meta WHERE k='canary'").get()?.v;if(j===void 0)z.query("INSERT INTO meta (k, v) VALUES ('canary', ?)").run(F9(X,"meta:canary",H3));else{let V=N9(X,"meta:canary",j);if(!K(V)||V.ok!==H3)return z.close(),I("failed_precondition","retry-at-higher-level","master key does not decrypt this vault's canary cell \u2014 wrong keychain item or replaced grants.db; restore = bulk re-auth (auth.md \xA74.1/\xA74.8), never a plaintext fallback")}pM(Z,JSON.stringify({pid:process.pid}));let W=new k5(z,X,$,Y,Z);return W.registerAllSecretValues(),H(W)}checkCustody(){let $=this.keyStore.getMasterKey();if(!K($))return $;for(let Z=0;Z<this.key.length;Z++)if($.ok[Z]!==this.key[Z])return I("failed_precondition","retry-at-higher-level","keychain master key changed under the running broker \u2014 LOCKED overlay (auth.md \xA74.3)");return H(!0)}close(){if(this.closed)return;this.closed=!0;let $=[];try{this.db.close()}catch(Z){$.push(Z)}try{uM(this.lockPath,{force:!0})}catch(Z){$.push(Z)}if($.length===1)throw $[0];if($.length>1)throw AggregateError($,"vault database and writer-lock cleanup both failed")}upsertGrant($){if(this.closed)return I("failed_precondition","non-retryable","vault closed");let Z=this.db.query("SELECT grant_id, state, authority_version FROM grants WHERE source = ? AND account_id = ?").get($.source,$.account.id);if(Z!==null&&Z.state!=="ACTIVE"&&$.transitionReason===void 0)return I("failed_precondition","non-retryable","an existing non-ACTIVE grant cannot re-enter ACTIVE without an explicit transition reason");let Q=Z?.grant_id??this.ulid();return this.db.transaction(()=>{if(Z===null)this.db.query(`INSERT INTO grants (grant_id, source, account_id, account_label, provider, method,
56
+ client_mode, client_id, scopes, state, state_at, refresh_at, keepalive_at,
57
+ issued_at, last_used_at, last_refresh_ok_at, at_expires_at, secrets)
58
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE', ?, ?, ?, ?, ?, ?, ?, '{}')`).run(Q,$.source,$.account.id,$.account.label,$.provider,$.method,$.clientMode,$.clientId??null,JSON.stringify($.scopes),$.now,$.refreshAt??null,$.keepaliveAt??null,$.now,$.now,$.now,$.atExpiresAt??null);else if(this.db.query(`UPDATE grants SET account_label = ?, provider = ?, method = ?, client_mode = ?,
59
+ client_id = COALESCE(?, client_id), scopes = ?, state = 'ACTIVE', state_at = ?,
60
+ refresh_at = ?, keepalive_at = ?, issued_at = ?, last_refresh_ok_at = ?,
61
+ at_expires_at = ?, retry_n = NULL, retry_next_at = NULL, retry_first_fail_at = NULL,
62
+ dispatch_eligible_at = NULL, authority_version = authority_version + 1
63
+ WHERE grant_id = ?`).run($.account.label,$.provider,$.method,$.clientMode,$.clientId??null,JSON.stringify($.scopes),$.now,$.refreshAt??null,$.keepaliveAt??null,$.now,$.now,$.atExpiresAt??null,Q),Z.state!=="ACTIVE"&&$.transitionReason!==void 0)this.insertTransitionAudit({grantId:Q,from:Z.state,to:"ACTIVE",reason:$.transitionReason,priorAuthorityVersion:Z.authority_version,authorityVersion:Z.authority_version+1,transitionAt:$.now});if($.secrets!==void 0)this.writeSecrets(Q,$.secrets)})(),H({grantId:Q,created:Z===null})}getGrant($){let Z=this.db.query("SELECT * FROM grants WHERE grant_id = ?").get($);if(Z===null)return I("not_found","non-retryable",`no grant '${$}'`);return H(iX(Z))}findGrant($,Z){let Q=this.db.query("SELECT * FROM grants WHERE source = ? AND account_id = ?").get($,Z);if(Q===null)return G$(`grants table scanned for (source='${$}', account.id='${Z}') \u2014 no row`);return H(iX(Q))}listGrants($){let Z="SELECT * FROM grants",Q=[],X=[];if($?.source!==void 0)X.push("source = ?"),Q.push($.source);if($?.state!==void 0)X.push("state = ?"),Q.push($.state);if(X.length>0)Z+=" WHERE "+X.join(" AND ");return this.db.query(Z+" ORDER BY grant_id").all(...Q).map(iX)}setState($,Z,Q,X,z){let Y=this.getGrant($);if(!K(Y))return Y;let j=Y.ok.state!==Z,{sets:W,args:V}=IK(Z,Q,X);if(!j)return V.push($),this.db.query(`UPDATE grants SET ${W.join(", ")} WHERE grant_id = ?`).run(...V),H(!0);if(z===void 0)return lZ("setState");return W.push("authority_version = authority_version + 1"),V.push($),this.db.transaction(()=>{this.db.query(`UPDATE grants SET ${W.join(", ")} WHERE grant_id = ?`).run(...V),this.insertTransitionAudit({grantId:$,from:Y.ok.state,to:Z,reason:z.reason,priorAuthorityVersion:Y.ok.authorityVersion,authorityVersion:Y.ok.authorityVersion+1,transitionAt:Q,...z.recoveredBy!==void 0?{recoveredBy:z.recoveredBy}:{}})})(),H(!0)}casState($,Z,Q,X,z){if(z===void 0)return lZ("casState");if(Z===Q)return yK("casState",Z);let Y=this.db.query("SELECT state, authority_version FROM grants WHERE grant_id = ?").get($);if(Y===null||Y.state!==Z)return H(!1);let j=0;return this.db.transaction(()=>{if(j=this.db.query(`UPDATE grants SET state = ?, state_at = ?, authority_version = authority_version + 1
64
+ WHERE grant_id = ? AND state = ? AND authority_version = ?`).run(Q,X,$,Z,Y.authority_version).changes,j===1)this.insertTransitionAudit({grantId:$,from:Z,to:Q,reason:z.reason,priorAuthorityVersion:Y.authority_version,authorityVersion:Y.authority_version+1,transitionAt:X,...z.recoveredBy!==void 0?{recoveredBy:z.recoveredBy}:{}})})(),H(j===1)}compareAndTransition($,Z,Q,X,z){if(z===void 0)return lZ("compareAndTransition");if($.state===Z)return yK("compareAndTransition",Z);let{sets:Y,args:j}=IK(Z,Q,X);Y.push("authority_version = authority_version + 1"),j.push($.grantId,$.state,$.authorityVersion);let W=0;this.db.transaction(()=>{if(W=this.db.query(`UPDATE grants SET ${Y.join(", ")}
65
+ WHERE grant_id = ? AND state = ? AND authority_version = ?`).run(...j).changes,W===1)this.insertTransitionAudit({grantId:$.grantId,from:$.state,to:Z,reason:z.reason,priorAuthorityVersion:$.authorityVersion,authorityVersion:$.authorityVersion+1,transitionAt:Q,...z.recoveredBy!==void 0?{recoveredBy:z.recoveredBy}:{}})})();let q=this.getGrant($.grantId);if(!K(q))return q;if(W===1)return H({kind:"applied",value:q.ok});return H({kind:"superseded",observed:{grantId:q.ok.grantId,state:q.ok.state,authorityVersion:q.ok.authorityVersion}})}listPendingGrantTransitions($){return($===void 0?this.db.query(`SELECT * FROM grant_transition_outbox
66
+ WHERE delivered_at IS NULL
67
+ ORDER BY grant_id, authority_version`).all():this.db.query(`SELECT * FROM grant_transition_outbox
68
+ WHERE delivered_at IS NULL AND grant_id = ?
69
+ ORDER BY authority_version`).all($)).map((Q)=>({grantId:Q.grant_id,from:Q.from_state,to:Q.to_state,reason:Q.reason,priorAuthorityVersion:Q.prior_authority_version,authorityVersion:Q.authority_version,transitionAt:Q.transition_at,...Q.recovered_by==="engine-start"?{recoveredBy:"engine-start"}:{},...Q.delivered_at!==null?{deliveredAt:Q.delivered_at}:{}}))}acknowledgeGrantTransition($,Z,Q){if(this.db.query(`UPDATE grant_transition_outbox SET delivered_at = ?
70
+ WHERE grant_id = ? AND authority_version = ? AND delivered_at IS NULL`).run(Q,$,Z).changes===1)return H(!0);let z=this.db.query(`SELECT delivered_at FROM grant_transition_outbox
71
+ WHERE grant_id = ? AND authority_version = ?`).get($,Z);if(z?.delivered_at!==null&&z!==null)return H(!0);return I("not_found","non-retryable","transition outbox acknowledgement has no matching authority generation")}insertTransitionAudit($){this.db.query(`INSERT INTO grant_transition_outbox (
72
+ grant_id, authority_version, prior_authority_version, from_state,
73
+ to_state, reason, transition_at, recovered_by, delivered_at
74
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)`).run($.grantId,$.authorityVersion,$.priorAuthorityVersion,$.from,$.to,$.reason,$.transitionAt,$.recoveredBy??null)}writeSecrets($,Z){let Q=this.db.query("SELECT secrets FROM grants WHERE grant_id = ?").get($),X=JSON.parse(Q?.secrets??"{}");for(let z of nX){let Y=Z[z];if(Y===void 0)continue;X[z]=F9(this.key,`${$}:${z}`,Y),this.registry.register(Y)}this.db.query("UPDATE grants SET secrets = ? WHERE grant_id = ?").run(JSON.stringify(X),$)}putSecrets($,Z){let Q=this.getGrant($);if(!K(Q))return Q;return this.db.transaction(()=>{this.writeSecrets($,Z),this.db.query("UPDATE grants SET authority_version = authority_version + 1 WHERE grant_id = ?").run($)})(),H(!0)}getSecret($,Z){let Q=this.db.query("SELECT secrets FROM grants WHERE grant_id = ?").get($);if(Q===null)return I("not_found","non-retryable",`no grant '${$}'`);let z=JSON.parse(Q.secrets)[Z];if(z===void 0)return G$(`grant '${$}' secrets JSON has no '${Z}' cell`);return N9(this.key,`${$}:${Z}`,z)}listSecretCells($){let Z=this.db.query("SELECT secrets FROM grants WHERE grant_id = ?").get($);if(Z===null)return I("not_found","non-retryable",`no grant '${$}'`);try{let Q=JSON.parse(Z.secrets);if(Q===null||typeof Q!=="object"||Array.isArray(Q))return I("data_loss","non-retryable",`grant '${$}' secret-cell envelope is not an object`);if(Object.keys(Q).filter((Y)=>!nX.includes(Y)).length>0)return I("data_loss","non-retryable",`grant '${$}' secret-cell envelope contains unknown cell names`);return H(nX.filter((Y)=>Object.prototype.hasOwnProperty.call(Q,Y)))}catch{return I("data_loss","non-retryable",`grant '${$}' secret-cell envelope is not valid JSON`)}}commitRefreshSuccess($,Z,Q){if(Q===void 0)return lZ("commitRefreshSuccess");let X=this.getGrant($);if(!K(X))return X;let z=this.getSecret($,"rt");if(this.db.transaction(()=>{let j={at:Z.at};if(Z.rt!==void 0)j.rt=Z.rt;this.writeSecrets($,j),this.db.query(`UPDATE grants SET state = 'ACTIVE', state_at = ?, refresh_at = ?, keepalive_at = COALESCE(?, keepalive_at),
75
+ at_expires_at = COALESCE(?, at_expires_at), last_refresh_ok_at = ?,
76
+ retry_n = NULL, retry_next_at = NULL, retry_first_fail_at = NULL, dispatch_eligible_at = NULL,
77
+ authority_version = authority_version + 1
78
+ WHERE grant_id = ?`).run(Z.now,Z.refreshAt??null,Z.keepaliveAt??null,Z.atExpiresAt??null,Z.now,$),this.insertTransitionAudit({grantId:$,from:X.ok.state,to:"ACTIVE",reason:Q.reason,priorAuthorityVersion:X.ok.authorityVersion,authorityVersion:X.ok.authorityVersion+1,transitionAt:Z.now,...Q.recoveredBy!==void 0?{recoveredBy:Q.recoveredBy}:{}})})(),Z.rt!==void 0&&K(z)&&z.ok!==Z.rt)this.registry.register(z.ok);return H(!0)}commitRefreshSuccessFenced($,Z,Q){if(Q===void 0)return lZ("commitRefreshSuccessFenced");let X=[],z;if(this.db.transaction(()=>{let j=this.db.query("SELECT state, authority_version, secrets FROM grants WHERE grant_id = ?").get($.grantId);if(j===null)return;if(j.state!==$.state||j.authority_version!==$.authorityVersion){z={kind:"superseded",observed:{grantId:$.grantId,state:j.state,authorityVersion:j.authority_version}};return}let W=JSON.parse(j.secrets);if(W.at=F9(this.key,`${$.grantId}:at`,Z.at),X=[Z.at],Z.rt!==void 0)W.rt=F9(this.key,`${$.grantId}:rt`,Z.rt),X.push(Z.rt);if(this.db.query(`UPDATE grants SET secrets = ?, state = 'ACTIVE', state_at = ?, refresh_at = ?,
79
+ keepalive_at = COALESCE(?, keepalive_at), at_expires_at = COALESCE(?, at_expires_at),
80
+ last_refresh_ok_at = ?, retry_n = NULL, retry_next_at = NULL,
81
+ retry_first_fail_at = NULL, dispatch_eligible_at = NULL,
82
+ authority_version = authority_version + 1
83
+ WHERE grant_id = ? AND state = ? AND authority_version = ?`).run(JSON.stringify(W),Z.now,Z.refreshAt??null,Z.keepaliveAt??null,Z.atExpiresAt??null,Z.now,$.grantId,$.state,$.authorityVersion).changes!==1)return;this.insertTransitionAudit({grantId:$.grantId,from:$.state,to:"ACTIVE",reason:Q.reason,priorAuthorityVersion:$.authorityVersion,authorityVersion:$.authorityVersion+1,transitionAt:Z.now,...Q.recoveredBy!==void 0?{recoveredBy:Q.recoveredBy}:{}});let q=this.getGrant($.grantId);if(K(q))z={kind:"applied",value:q.ok}})(),z===void 0){let j=this.getGrant($.grantId);if(!K(j))return j;z={kind:"superseded",observed:{grantId:j.ok.grantId,state:j.ok.state,authorityVersion:j.ok.authorityVersion}}}if(z.kind==="applied")for(let j of X)this.registry.register(j);return H(z)}wipeAllSecrets(){this.db.query("UPDATE grants SET secrets = '{}', authority_version = authority_version + 1").run()}importRebuiltGrant($,Z){let Q=this.db.query("SELECT grant_id FROM grants WHERE source = ? AND account_id = ?").get($.source,$.accountId);if(Q!==null)return H(Q.grant_id);return this.db.query(`INSERT INTO grants (grant_id, source, account_id, account_label, provider, method,
84
+ client_mode, scopes, state, state_at, issued_at, last_used_at, last_refresh_ok_at, secrets)
85
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'AUTH_BLOCKED', ?, ?, ?, ?, '{}')`).run($.grantId,$.source,$.accountId,$.accountId,$.provider,$.method,$.clientMode,JSON.stringify($.scopes),Z,Z,Z,Z),H($.grantId)}registerAllSecretValues(){let $=this.db.query("SELECT grant_id, secrets FROM grants").all();for(let Q of $){let X=JSON.parse(Q.secrets);for(let[z,Y]of Object.entries(X)){let j=N9(this.key,`${Q.grant_id}:${z}`,Y);if(K(j))this.registry.register(j.ok)}}let Z=this.db.query("SELECT flow_id, cells FROM flows").all();for(let Q of Z){let X=JSON.parse(Q.cells);for(let[z,Y]of Object.entries(X)){let j=N9(this.key,`flow:${Q.flow_id}:${z}`,Y);if(K(j))this.registry.register(j.ok)}}}putFlow($){return this.db.query(`INSERT OR REPLACE INTO flows (flow_id, flow_type, source, provider, account_hint, scopes,
86
+ state, state_at, stuck_class, batch_id, redirect_port, state_nonce, grant_id, resume_used,
87
+ cells)
88
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
89
+ COALESCE((SELECT cells FROM flows WHERE flow_id = ?), '{}'))`).run($.flowId,$.flowType,$.source,$.provider,$.accountHint??null,JSON.stringify($.scopes),$.state,$.stateAt,$.stuckClass??null,$.batchId??null,$.redirectPort??null,$.stateNonce??null,$.grantId??null,$.resumeUsed?1:0,$.flowId),H(!0)}getFlow($){let Z=this.db.query("SELECT * FROM flows WHERE flow_id = ?").get($);if(Z===null)return I("not_found","non-retryable",`no flow '${$}'`);let Q={flowId:Z.flow_id,flowType:Z.flow_type,source:Z.source,provider:Z.provider,scopes:JSON.parse(Z.scopes),state:Z.state,stateAt:Z.state_at,resumeUsed:Z.resume_used===1};if(Z.account_hint!==null)Q.accountHint=Z.account_hint;if(Z.stuck_class!==null)Q.stuckClass=Z.stuck_class;if(Z.batch_id!==null)Q.batchId=Z.batch_id;if(Z.redirect_port!==null)Q.redirectPort=Z.redirect_port;if(Z.state_nonce!==null)Q.stateNonce=Z.state_nonce;if(Z.grant_id!==null)Q.grantId=Z.grant_id;return H(Q)}listFlows($){let Z=this.db.query("SELECT flow_id FROM flows ORDER BY flow_id").all(),Q=[];for(let{flow_id:X}of Z){let z=this.getFlow(X);if(!K(z))continue;if($?.batchId!==void 0&&z.ok.batchId!==$.batchId)continue;if($?.nonTerminal===!0&&["DONE","ABANDONED"].includes(z.ok.state))continue;Q.push(z.ok)}return Q}putFlowCell($,Z,Q){let X=this.getFlow($);if(!K(X))return X;let z=this.db.query("SELECT cells FROM flows WHERE flow_id = ?").get($),Y=JSON.parse(z.cells);return Y[Z]=F9(this.key,`flow:${$}:${Z}`,Q),this.registry.register(Q),this.db.query("UPDATE flows SET cells = ? WHERE flow_id = ?").run(JSON.stringify(Y),$),H(!0)}getFlowCell($,Z){let Q=this.db.query("SELECT cells FROM flows WHERE flow_id = ?").get($);if(Q===null)return I("not_found","non-retryable",`no flow '${$}'`);let z=JSON.parse(Q.cells)[Z];if(z===void 0)return G$(`flow '${$}' has no staged '${Z}' cell`);return N9(this.key,`flow:${$}:${Z}`,z)}}var nX;var sX=E(()=>{f();dX();X0();A8();nX=["at","rt","clientSecret","apiKey","cookies","password"]});class S8{sink;registry;now;buffer=[];bufferedTransitionKeys=new Set;stopped=!1;lastEmissionDurable=!1;transcript=[];constructor($,Z,Q){this.sink=$;this.registry=Z;this.now=Q}isStopped(){return this.stopped}bufferedCount(){return this.buffer.length}emit($,Z,Q){return this.emitProto(this.proto($,Z,{source:"zortex",stream:"auth"},Q?.at),$,Z)}wasLastEmissionDurable(){return this.lastEmissionDurable}emitSpan($){let Z=$,Q=this.proto("trace.span",Z,{source:"zortex",stream:"trace",sourceId:$.spanId,rev:"0"});return this.emitProto(Q,"trace.span",Z)}proto($,Z,Q,X){return{nk:Q,ts:X??this.now(),tier:"first-party",kind:$,schemaVersion:1,mentions:[],body:"",payload:Z}}emitProto($,Z,Q){if(this.lastEmissionDurable=!1,this.stopped)return v(T$("failed_precondition","retry-at-higher-level","auth event emission STOPPED (buffer overflow past 10k while the event log was unwritable) \u2014 LOCKED-equivalent, custody never silently unaudited (auth.md \xA77.2)"));let X=l0(JSON.stringify(Q),this.registry);if(X.length>0&&Z!=="auth.incident.token_leak"){let V={where:"event",pattern:X[0].pattern,artifactRef:Z};return this.emitProto(this.proto("auth.incident.token_leak",V,{source:"zortex",stream:"auth"}),"auth.incident.token_leak",V),v(T$("permission_denied","non-retryable",`raw-token guard: emit of '${Z}' HARD-FAILED \u2014 payload matched token pattern '${X[0].pattern}' (I-7 security incident, FM-25)`))}let z=Z==="auth.grant.state"?`${Z}\x00${$.ts}\x00${JSON.stringify(Q)}`:void 0,Y=z!==void 0&&this.bufferedTransitionKeys.has(z),j=Y?[...this.buffer]:[...this.buffer,$],W=this.sink.append(j,lM);if(K(W))return this.buffer=[],this.bufferedTransitionKeys.clear(),this.lastEmissionDurable=!0,this.transcript.push({kind:Z,payload:Q}),H(!0);if(!Y){if(this.buffer.push($),z!==void 0)this.bufferedTransitionKeys.add(z)}if(this.buffer.length>EK)return this.stopped=!0,v(T$("failed_precondition","retry-at-higher-level","auth event buffer exceeded 10k with the event log unwritable \u2014 entering LOCKED-equivalent loud stop (auth.md \xA77.2)","err"in W?W.err:void 0));return this.transcript.push({kind:Z,payload:Q}),H(!0)}}var T8,EK=1e4,lM;var oX=E(()=>{f();X0();A8();T8={source:"zortex",stream:"auth",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},lM={kind:"kernel"}});function z0($){return typeof $==="string"&&$.length>0&&$.length<=256&&!/[\u0000-\u001f\u007f]/u.test($)}function rX($){if($===void 0)return H([]);if(!Array.isArray($)||$.length>32)return I("invalid_argument","non-retryable","response capability policy requires at most 32 declarative rules");let Z=new Map;for(let Q of $){if(Q===null||typeof Q!=="object"||!z0(Q.kind))return I("invalid_argument","non-retryable","response capability rule requires a non-empty bounded kind");let{response:X,request:z}=Q;if(X===void 0||!z0(X.method)||!z0(X.pathExact)||!X.pathExact.startsWith("/")||X.pathExact.includes("?")||X.pathExact.includes("#"))return I("invalid_argument","non-retryable",`response capability '${Q.kind}' requires an exact absolute response path and method`);if(z===void 0||!z0(z.method)||!z0(z.pathPrefix)||!z.pathPrefix.startsWith("/")||!z.pathPrefix.endsWith("/")||z.pathPrefix.includes("?")||z.pathPrefix.includes("#")||!z0(z.header)||!dM.test(z.header)||cM.has(z.header.toLowerCase())||z.format!=="id/slash/secret")return I("invalid_argument","non-retryable",`response capability '${Q.kind}' has an invalid request binding/header`);if(!Number.isInteger(Q.maxEntries)||Q.maxEntries<1||Q.maxEntries>1e4)return I("invalid_argument","non-retryable",`response capability '${Q.kind}' maxEntries must be 1..10000`);if(!Array.isArray(Q.captures)||Q.captures.length===0||Q.captures.length>16)return I("invalid_argument","non-retryable",`response capability '${Q.kind}' requires 1..16 capture paths`);for(let W of Q.captures){if(!Array.isArray(W.rowsPath)||W.rowsPath.length===0||W.rowsPath.some((V)=>!z0(V)||!cZ.test(V))||W.objectPath!==void 0&&(!Array.isArray(W.objectPath)||W.objectPath.some((V)=>!z0(V)||!cZ.test(V)))||!z0(W.idField)||!cZ.test(W.idField)||!z0(W.secretField)||!cZ.test(W.secretField)||W.idField===W.secretField)return I("invalid_argument","non-retryable",`response capability '${Q.kind}' has an invalid capture path`);if(W.urlFields===void 0!==(W.secretQueryParam===void 0)||W.urlFields!==void 0&&(W.urlFields.length===0||W.urlFields.some((V)=>!z0(V)||!cZ.test(V)))||W.secretQueryParam!==void 0&&!z0(W.secretQueryParam))return I("invalid_argument","non-retryable",`response capability '${Q.kind}' URL scrub declaration is incomplete`)}for(let W of X.requiredQuery??[])if(!z0(W.name)||!Array.isArray(W.contains)||W.contains.length===0||W.contains.some((V)=>!z0(V)))return I("invalid_argument","non-retryable",`response capability '${Q.kind}' has an invalid required query selector`);let Y=JSON.stringify({method:z.method.toUpperCase(),pathPrefix:z.pathPrefix,header:z.header.toLowerCase(),format:z.format}),j=Z.get(Q.kind);if(j!==void 0&&j!==Y)return I("invalid_argument","non-retryable",`response capability '${Q.kind}' has conflicting request bindings`);Z.set(Q.kind,Y)}return H($)}function w5($){let Q=aX.find((Y)=>Y.provider===$.provider)??($.profile===void 0?void 0:{provider:$.provider,...$.profile,hosts:[],ops:[]});if(Q===void 0)return I("not_found","non-retryable",`provider '${$.provider}' has no custody posture for a production read policy; fail closed`);let X=[...new Set($.hosts)];if(X.length===0||X.some((Y)=>Y===""||Y.includes("://")||Y.includes("/")))return I("invalid_argument","non-retryable","production read policy requires bare, non-empty host allowlist entries");if($.ops.length===0||$.ops.some((Y)=>Y.op===""||Y.pathPrefix[0]!=="/"))return I("invalid_argument","non-retryable","production read policy requires named operations with absolute path prefixes");let z=rX($.responseCapabilities);if(!K(z))return z;return H({...Q,provider:$.provider,hosts:X,ops:$.ops.map((Y)=>({...Y,method:Y.method.toUpperCase(),scopes:[...Y.scopes]})),...$.responseCapabilities!==void 0?{responseCapabilities:$.responseCapabilities.map((Y)=>({...Y,response:{...Y.response,method:Y.response.method.toUpperCase()},captures:Y.captures.map((j)=>({...j,rowsPath:[...j.rowsPath],...j.objectPath!==void 0?{objectPath:[...j.objectPath]}:{},...j.urlFields!==void 0?{urlFields:[...j.urlFields]}:{}})),request:{...Y.request,method:Y.request.method.toUpperCase()}}))}:{}})}class dZ{rows=new Map;constructor($=[],Z=aX){for(let Q of Z)this.rows.set(Q.provider,Q);for(let Q of $)this.rows.set(Q.provider,Q)}get($){let Z=this.rows.get($);if(Z===void 0)return I("not_found","non-retryable",`provider '${$}' has no policy-matrix row (\xA74.7) \u2014 fail closed, never a default posture`);let Q=rX(Z.responseCapabilities);if(!K(Q))return Q;return H(Z)}assertDriverAllowed($){let Z=this.get($);if(!("ok"in Z))return Z;if(Z.ok.retaliationRisk==="banning"||Z.ok.recommendedRung==="none")return vX($);return Z}assertLoginFormAutomationAllowed($){return EX($)}resolveOp($,Z,Q,X){let z=this.get($);if(!("ok"in z))return z;let Y=z.ok;if(Q.protocol!=="https:")return I("invalid_argument","non-retryable",`scheme '${Q.protocol}' is not allowed for provider '${$}' (\xA74.2 \u2014 HTTPS required)`);if(Q.username!==""||Q.password!=="")return I("invalid_argument","non-retryable",`URL userinfo is forbidden for provider '${$}' (\xA74.2 \u2014 credentials stay in falcon custody)`);if(Q.hash!=="")return I("invalid_argument","non-retryable",`URL fragments are forbidden for provider '${$}' (\xA74.2 \u2014 authorize and execute one identical URL)`);if(!Y.hosts.includes(Q.host))return I("invalid_argument","non-retryable",`host '${Q.host}' is not in provider '${$}' allowlist (\xA74.2 \u2014 fail closed)`);let j=Y.ops.find((W)=>{let V=Q.pathname===W.pathPrefix||(W.pathPrefix.endsWith("/")?Q.pathname.startsWith(W.pathPrefix):Q.pathname.startsWith(`${W.pathPrefix}/`));return W.method.toUpperCase()===Z.toUpperCase()&&V});if(j===void 0)return I("invalid_argument","non-retryable",`(${Z}, ${Q.pathname}) resolves to no known op for provider '${$}' (\xA74.7 op map \u2014 fail closed)`);if(j.scopes.length>0&&!j.scopes.some((W)=>X.includes(W)))return I("permission_denied","non-retryable",`op '${j.op}' requires one of [${j.scopes.join(", ")}] \u2014 handle scopes do not license it (least-scope, \xA74.2)`);return H(j)}}var aX,D3=3600,cM,dM,cZ;var M3=E(()=>{f();X0();aX=[{provider:"google",botDetection:"hard-blocks-login",registrationExposure:"console walk with user's live session: gray-zone, low observed flag rate; own Desktop client is the sanctioned shape (F16)",tokenCliffs:{testingRtDays:7,rtCapPerClientAccount:100,rtCapAlarmAt:80,idleRevocationDays:180,rotation:"none",notes:"Testing 7d cliff \u2192 escape = own client Production-unverified (F12/F13); 100-RT cap oldest silently killed (F14); password change revokes Gmail-scope RTs; device flow scope-capped to uselessness (F15)"},dcr:!1,recommendedRung:"A",probeOp:"tokeninfo",retaliationRisk:"low",hosts:[],ops:[]},{provider:"microsoft",botDetection:"hard-blocks-login",registrationExposure:"app-registration walk comparable",tokenCliffs:{slidingWindowDays:90,rotation:"none",notes:"RT 90d sliding, non-configurable (F17) \u2014 \xA74.3's 30d keepalive covers it"},dcr:!1,recommendedRung:"A",probeOp:"graph /me",retaliationRisk:"low",hosts:[],ops:[]},{provider:"github",botDetection:"n/a",registrationExposure:"none \u2014 shared client fine",tokenCliffs:{rotation:"rotating-single-use",notes:"classic OAuth gho_ non-expiring; GitHub App: AT 8h, RT 6-month single-use rotating (F7/F18)"},dcr:!1,recommendedRung:"C",probeOp:"/user",retaliationRisk:"low",hosts:[],ops:[]},{provider:"slack",botDetection:"moderate",registrationExposure:"app-creation walk required for user tokens",tokenCliffs:{rotation:"opt-in-irreversible",notes:"rotation opt-in and irreversible; AT fixed 12h; RT single-use w/ short grace; 2-active-token limit (F18)"},dcr:!1,recommendedRung:"A",probeOp:"auth.test",retaliationRisk:"moderate",hosts:[],ops:[]},{provider:"notion",botDetection:"moderate",registrationExposure:"integration-creation walk",tokenCliffs:{rotation:"rotating-single-use",notes:"rotating RT; expiry undocumented \u2192 scheduled as 1h AT (F18)"},dcr:!1,recommendedRung:"A",probeOp:"/users/me",retaliationRisk:"moderate",hosts:[],ops:[]},{provider:"mcp-native",botDetection:"n/a",registrationExposure:"n/a",tokenCliffs:{notes:"per server"},dcr:!0,recommendedRung:"A",probeOp:"server ping",retaliationRisk:"low",hosts:[],ops:[]},{provider:"wechat-class",botDetection:"hard-blocks-login",registrationExposure:"not attempted",tokenCliffs:{notes:"protocol automation \u21D2 bans"},dcr:!1,recommendedRung:"none",probeOp:"n/a",retaliationRisk:"banning",hosts:[],ops:[]}],cM=new Set(["authorization","cookie","proxy-authorization","x-api-key","api-key"]),dM=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,cZ=/^[A-Za-z0-9_.-]+$/u});function K$($,Z){return I($,"non-retryable",Z)}function nZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function vK($,Z){let Q=$;for(let X of Z){if(!nZ(Q))return;Q=Q[X]}return Q}function fK($){return $.length>=8&&$.length<=4096&&!/[/,\u0000-\u001f\u007f]/u.test($)}function bK($){return $.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}function iM($,Z){let Q=new Set,X=0;for(let z of $){if(Z())return"aborted";let Y;try{Y=encodeURIComponent(z)}catch{return"ambiguous"}for(let j of[z,Y]){if(Q.has(j))continue;let W=bK(j);if(X+=W.length+1,X>nM)return"ambiguous";Q.add(j)}}if(Q.size===0)return/$^/u;try{return new RegExp([...Q].map(bK).join("|"),"u")}catch{return"ambiguous"}}function gK($,Z,Q){let X=z5($,Q);if(X.kind!=="ok")return X.kind;for(let z of X.values){if(Q())return"aborted";if(Z.test(z))return"found";if(Q())return"aborted"}return"clean"}function P3($,Z,Q){if(Z.size===0)return"clean";let X=iM(Z,Q);if(X==="aborted"||X==="ambiguous")return X;let z=[$];while(z.length>0){if(Q())return"aborted";let Y=z.pop();if(typeof Y==="string"){let j=gK(Y,X,Q);if(j!=="clean")return j;continue}if(Array.isArray(Y)){z.push(...Y);continue}if(!nZ(Y))continue;for(let[j,W]of Object.entries(Y)){let V=gK(j,X,Q);if(V!=="clean")return V;z.push(W)}}return"clean"}function kK($){let Z=$.indexOf("://");if(Z<=0)return K$("invalid_argument","response capability request URL is not absolute");let Q=Z+3,X=$.length;for(let Y of["/","\\","?","#"]){let j=$.indexOf(Y,Q);if(j>=0&&j<X)X=j}if(X===$.length||$[X]==="?"||$[X]==="#")return{ok:"/"};let z=$.length;for(let Y of["?","#"]){let j=$.indexOf(Y,X);if(j>=0&&j<z)z=j}return{ok:$.slice(X,z)||"/"}}function eX($){let Z=$.search.startsWith("?")?$.search.slice(1):$.search;if(Z==="")return[];return Z.split("&").map((Q)=>{let X=Q.indexOf("=");return X<0?{name:Q,value:""}:{name:Q.slice(0,X),value:Q.slice(X+1)}})}function tX(){return I("deadline_exceeded","retry-at-higher-level","response capability route normalization exceeded the I-7 return deadline")}function sM($,Z,Q,X,z){if($.response.method.toUpperCase()!==Z.toUpperCase())return{ok:"inactive"};let Y=z5(X,z);if(Y.kind==="aborted")return tX();if(Y.kind==="ambiguous"||Y.malformed)return K$("invalid_argument","response capability route path has ambiguous percent encoding");if(X!==$.response.pathExact){if(Q.pathname===$.response.pathExact||Y.values.includes($.response.pathExact))return K$("invalid_argument","response capability route path must use its canonical exact spelling");return{ok:"inactive"}}if(Q.pathname!==$.response.pathExact)return K$("invalid_argument","response capability raw and parsed paths disagree");let j=$.response.requiredQuery??[];if(j.length===0)return{ok:"active"};let W=eX(Q),V=[];for(let q of j){let B=[];for(let L of W){let D=z5(L.name,z);if(D.kind==="aborted")return tX();if(D.kind==="ambiguous"||D.malformed)return K$("invalid_argument","response capability selector name has ambiguous percent encoding");if(!D.values.includes(q.name))continue;if(L.name!==q.name||D.encodedUnreserved||D.values.length!==1)return K$("invalid_argument","response capability selector name must use its canonical exact spelling");B.push(L)}if(B.length===0)return K$("invalid_argument","response capability endpoint omitted its declared selector");if(B.length!==1)return K$("invalid_argument","response capability endpoint duplicated its declared selector");let G=z5(B[0].value,z);if(G.kind==="aborted")return tX();if(G.kind==="ambiguous"||G.malformed||G.encodedUnreserved||G.values.length>2)return K$("invalid_argument","response capability selector value has ambiguous percent encoding");let J=G.values[G.values.length-1]??"",U=q.contains.filter((L)=>J.includes(L)).length;if(U===0)V.push("inactive");else if(U===q.contains.length)V.push("active");else return K$("invalid_argument","response capability selector requested only part of its declared capability fields")}if(V.every((q)=>q==="active"))return{ok:"active"};if(V.every((q)=>q==="inactive"))return{ok:"inactive"};return K$("invalid_argument","response capability selectors disagreed about capture activation")}function oM($,Z){if(Z.urlFields===void 0||Z.secretQueryParam===void 0)return{ok:null};let Q=null;for(let X of Z.urlFields){let z=$[X];if(z===void 0)continue;if(typeof z!=="string")return K$("data_loss","response capability URL field is not a string");let Y;try{Y=new URL(z)}catch{return K$("data_loss","response capability URL field is not an absolute URL")}let j=new Set;for(let W of eX(Y)){let V=z5(W.name);if(V.kind!=="ok"||V.malformed)return K$("data_loss","response capability URL query name exceeded bounded normalization");if(V.values.some((q)=>q.toLowerCase()===Z.secretQueryParam.toLowerCase()))try{j.add(decodeURIComponent(W.name.replace(/\+/gu," ")))}catch{return K$("data_loss","response capability URL query name is malformed")}}for(let W of j){let V=Y.searchParams.getAll(W);for(let q of V){if(!fK(q))return K$("data_loss","response capability URL contained malformed secret material");if(Q!==null&&Q!==q)return K$("data_loss","response capability URL carried conflicting values");Q=q}Y.searchParams.delete(W)}$[X]=Y.toString()}return{ok:Q}}function aM($,Z,Q,X){let z=$.get(Z);if(z!==void 0){if(z!==null&&Q!==null&&z!==Q)return K$("data_loss","response capability response carried conflicting values for one object id");if(z===null&&Q!==null)$.set(Z,Q);return{ok:void 0}}if($.size>=X)return I("resource_exhausted","retry-at-higher-level","response capability snapshot exceeded its policy bound");return $.set(Z,Q),{ok:void 0}}function $7($,Z,Q,X,z,Y,j=Q.pathname){let W=[],V=X>=200&&X<300;for(let L of $??[]){let D=sM(L,Z,Q,j,Y);if(!K(D))return D;if(D.ok==="active")W.push(L)}if(W.length===0)return{ok:{bodyText:z,snapshots:new Map,capturedSecrets:[],captureCount:0}};if(Y())return I("deadline_exceeded","retry-at-higher-level","response capability capture exceeded the I-7 return deadline");let q;try{q=JSON.parse(z)}catch{return K$("data_loss","declared response capability capture endpoint returned malformed JSON")}if(!nZ(q))return K$("data_loss","declared response capability capture endpoint returned a non-object body");let B=new Map,G=new Set;for(let L of W){let D=B.get(L.kind)??new Map;B.set(L.kind,D);for(let P of L.captures){if(Y())return I("deadline_exceeded","retry-at-higher-level","response capability capture exceeded the I-7 return deadline");let F=vK(q,P.rowsPath);if(F===void 0)continue;if(!Array.isArray(F))return K$("data_loss","response capability row path is not an array");for(let A of F){if(Y())return I("deadline_exceeded","retry-at-higher-level","response capability capture exceeded the I-7 return deadline");if(!nZ(A))return K$("data_loss","response capability row is not an object");let N=vK(A,P.objectPath??[]);if(N===void 0&&(P.objectPath?.length??0)>0)continue;if(!nZ(N))return K$("data_loss","response capability object path is not an object");let S=N[P.idField];if(typeof S!=="string"||S.length===0||S.length>1024||/[/,\u0000-\u001f\u007f]/u.test(S))return K$("data_loss","response capability object id is malformed");let R=oM(N,P);if(!K(R))return R;let O=N[P.secretField],T=null;if(O!==void 0){if(typeof O!=="string"||!fK(O))return K$("data_loss","response capability secret field is malformed");T=O}if(R.ok!==null){if(T!==null&&T!==R.ok)return K$("data_loss","response capability field and URL carried conflicting values");T=R.ok}delete N[P.secretField];let m=aM(D,S,T,L.maxEntries);if(!K(m))return m;if(T!==null)G.add(T)}}}if(Y())return I("deadline_exceeded","retry-at-higher-level","response capability capture exceeded the I-7 return deadline");let J=P3(q,G,Y);if(J==="aborted")return I("deadline_exceeded","retry-at-higher-level","response capability capture exceeded the I-7 return deadline");if(J==="found")return K$("permission_denied","response capability material remained after broker sanitization");if(J==="ambiguous")return K$("data_loss","response capability residual encoding exceeded bounded normalization");let U;try{U=JSON.stringify(q)}catch{return K$("data_loss","response capability response could not be serialized after sanitization")}return{ok:{bodyText:U,snapshots:V?B:new Map,capturedSecrets:[...G],captureCount:V?G.size:0}}}function rM($,Z,Q){if($.request.method.toUpperCase()!==Z.toUpperCase()||!Q.pathname.startsWith($.request.pathPrefix))return{ok:null};let z=Q.pathname.slice($.request.pathPrefix.length).split("/",1)[0]??"";if(z==="")return{ok:null};try{return{ok:decodeURIComponent(z)}}catch{return K$("invalid_argument","authorized capability request resource id has malformed percent encoding")}}function wK($){return new Set(($??[]).map((Z)=>Z.request.header.toLowerCase()))}function mK($,Z){let Q=new Set;for(let X of $??[])for(let z of X.captures)if(z.secretQueryParam!==void 0)Q.add(z.secretQueryParam.toLowerCase());return eX(Z).some((X)=>{let z=z5(X.name);if(z.kind!=="ok"||z.malformed)return!0;return z.values.some((Y)=>Q.has(Y.toLowerCase()))})}function hK($,Z,Q,X,z){let Y=[];for(let B of $??[]){let G=rM(B,X,z);if(!K(G))return G;if(G.ok!==null)Y.push({rule:B,id:G.ok})}if(Y.length===0){if(Q!==void 0&&(!Array.isArray(Q)||Q.length>0))return K$("invalid_argument","capability references do not match an authorized request binding");return{ok:{headers:{},injectionCount:0}}}if(Q===void 0)return K$("failed_precondition","provider object read requires a broker capability observation reference");let j=F8(Q);if(!K(j))return r(j)?{err:{...j.err,layer:"auth"}}:K$("internal","capability reference validation returned an impossible empty result");let W=j.ok;if(W.length===0)return K$("failed_precondition","provider object read requires a broker capability observation reference");let V=new Map,q=0;for(let B of W){let G=Y.find((P)=>P.rule.kind===B.kind);if(G===void 0)return K$("invalid_argument","capability reference kind does not match the authorized request binding");if(G.id!==B.id)return K$("invalid_argument","capability reference id does not match the authorized request resource id");let J=Z.get(B.kind);if(J===void 0||!J.has(B.id))return K$("failed_precondition","capability reference was not observed by this live broker handle");let U=J.get(B.id)??null;if(U===null)continue;let L=G.rule.request.header,D=V.get(L)??[];D.push(`${B.id}/${U}`),V.set(L,D),q++}return{ok:{headers:Object.fromEntries([...V].map(([B,G])=>[B,G.join(",")])),injectionCount:q}}}var nM=131072;var Z7=E(()=>{f();X0()});function iZ($,Z,Q,X,z=Math.random){let Y=X??D3,W=Math.min((Q??Number.POSITIVE_INFINITY)*1000,Y/2*1000)*(1+(z()*2-1)*tM);return Math.max($,Z+W-j7)}function sZ($,Z){return $+(Z??D3)*1000-j7}class oZ{vault;emitter;matrix;provider;nowMs;rng;hooks;asyncPhaseTimeoutMs;incidentsFired=new Set;constructor($){this.vault=$.vault,this.emitter=$.emitter,this.matrix=$.matrix,this.provider=$.provider,this.nowMs=$.nowMs,this.rng=$.rng??Math.random,this.hooks=$.hooks??{},this.asyncPhaseTimeoutMs=Math.max(1,Math.floor($.asyncPhaseTimeoutMs??Q7))}transition($,Z,Q){let X=this.vault.getGrant($);if(!K(X))return X;let z=X.ok.state;if(!(Q==="restore"&&Z==="AUTH_BLOCKED")&&!Y7[z].includes(Z))return I("failed_precondition","non-retryable",`illegal grant transition ${z} \u2192 ${Z} (auth.md \xA74.3, FM-22)`);if(z===Z)return I("failed_precondition","non-retryable",`no-op transition ${z} \u2192 ${Z} refused (every transition is an event)`);let j=S$(this.nowMs()),W=Z==="ACTIVE"?{clearRetry:!0}:void 0,V=this.vault.compareAndTransition({grantId:$,state:X.ok.state,authorityVersion:X.ok.authorityVersion},Z,j,W,{reason:Q});if(!K(V))return V;if(V.ok.kind==="superseded")return I("aborted","non-retryable","grant transition lost its exact authority generation");return this.emitAppliedTransition($,z,Z,Q,X.ok.authorityVersion,V.ok.value)}recoverOnStart(){for(let $ of this.vault.listGrants({state:"PROBING"}))this.transition($.grantId,"AUTH_BLOCKED","unauthenticated");for(let $ of this.vault.listGrants({state:"REFRESHING"})){let Z=this.transition($.grantId,"PROBING","unavailable");if(K(Z))this.runProbeRefresh(Z.ok)}}tick(){let $=this.nowMs();for(let X of this.vault.listGrants({state:"REFRESHING"}))if($-O0(X.stateAt)>=Q7){let z=this.transition(X.grantId,"PROBING","deadline_exceeded");if(K(z))this.runProbeRefresh(z.ok)}for(let X of this.vault.listGrants({state:"PROBING"}))if($-O0(X.stateAt)>=pK)this.enterRetryWait(X,"deadline_exceeded");for(let X of this.vault.listGrants({state:"ACTIVE"}))if(X.refreshAt!==void 0&&O0(X.refreshAt)<=$||X.keepaliveAt!==void 0&&O0(X.keepaliveAt)<=$){let Y=Math.floor(this.rng()*iK);this.vault.setState(X.grantId,X.state,X.stateAt,{dispatchEligibleAt:S$($+Y)}),this.transition(X.grantId,"REFRESH_DUE","scheduled")}for(let X of this.vault.listGrants({state:"RETRY_WAIT"})){if(X.retry!==void 0&&$-O0(X.retry.firstFailAt)>=cK){let z=`retry-cumulative-24h:${X.grantId}`;if(!this.incidentsFired.has(z))this.incidentsFired.add(z),this.hooks.onIncident?.("retry-cumulative-24h",X.grantId)}if(X.retry!==void 0&&O0(X.retry.nextAt)<=$)this.vault.setState(X.grantId,X.state,X.stateAt,{dispatchEligibleAt:S$($)}),this.transition(X.grantId,"REFRESH_DUE","scheduled")}let Z=0,Q=new Map;for(let X of this.vault.listGrants({state:"REFRESH_DUE"})){let z=X.dispatchEligibleAt!==void 0?O0(X.dispatchEligibleAt):O0(X.stateAt);if(z>$)continue;let Y=Q.get(X.provider)??0;if(Z>=dK||Y>=nK){this.vault.setState(X.grantId,X.state,X.stateAt,{dispatchEligibleAt:S$($)});continue}if($-z>lK){let j=`refresh-starvation:${X.grantId}`;if(!this.incidentsFired.has(j))this.incidentsFired.add(j),this.hooks.onIncident?.("refresh-starvation",X.grantId)}Z++,Q.set(X.provider,Y+1),this.dispatchRefresh(X.grantId)}}dispatchRefresh($){if(this.provider.mode!=="sync")return I("failed_precondition","non-retryable","synchronous refresh is unavailable for an async lifecycle provider");let Z=this.vault.getGrant($);if(!K(Z))return Z;let Q=this.vault.compareAndTransition({grantId:$,state:"REFRESH_DUE",authorityVersion:Z.ok.authorityVersion},"REFRESHING",S$(this.nowMs()),void 0,{reason:"scheduled"});if(!K(Q))return Q;if(Q.ok.kind==="superseded")return I("aborted","non-retryable",`refresh singleflight: grant '${$}' is not REFRESH_DUE (concurrent refresh would be self-inflicted family revocation, F20)`);let X=this.emitAppliedTransition($,"REFRESH_DUE","REFRESHING","scheduled",Z.ok.authorityVersion,Q.ok.value);if(!K(X))return X;let z=X.ok;if(z.method==="api-key"||z.method==="cookie-session")return this.keepaliveProbe($,z);let Y=this.vault.getSecret($,"rt");if(r(Y))return this.lockedAbort($,Y.err.message);if(f$(Y))return this.transition($,"AUTH_BLOCKED","unauthenticated");let j=this.refreshReq(z,Y.ok);if(!K(j))return this.enterRetryWait(z,"unavailable"),j;let W=this.provider.transport.refresh(j.ok);if(r(W))return W;if(f$(W))return I("internal","non-retryable","refresh transport returned empty \u2014 transport contract violation");switch(W.ok.kind){case"ok":return this.commitAndActivate($,z,W.ok);case"invalid_grant":return this.transition($,"AUTH_BLOCKED","unauthenticated");case"throttled":{let V=this.vault.getGrant($);if(K(V))this.enterRetryWait(V.ok,"resource_exhausted");return this.vault.getGrant($)}case"network":{let V=this.transition($,"PROBING","unavailable");if(!K(V))return V;return this.runProbeRefresh(V.ok)}}}async dispatchRefreshAsync($){if(this.provider.mode!=="async")return I("failed_precondition","non-retryable","async refresh is unavailable for a synchronous lifecycle provider");let Z=this.vault.getGrant($);if(!K(Z))return Z;let Q=this.transition($,"REFRESHING","scheduled");if(!K(Q)){let Y=this.vault.getGrant($);if(K(Y)&&Y.ok.state==="REFRESHING"&&Y.ok.authorityVersion===Z.ok.authorityVersion+1){let j=Y.ok.method==="api-key"||Y.ok.method==="cookie-session"?"keepalive":"refresh";return this.settleAuditFailure({grantId:$,state:"REFRESHING",authorityVersion:Y.ok.authorityVersion,phase:j},Y.ok,"RETRY_WAIT",Q)}return Q}let X=Q.ok.method==="api-key"||Q.ok.method==="cookie-session"?"keepalive":"refresh",z={grantId:$,state:"REFRESHING",authorityVersion:Q.ok.authorityVersion,phase:X};try{if(X==="keepalive")return await this.keepaliveProbeAsync(z,Q.ok);return await this.runInitialRefreshAsync(z,Q.ok)}catch{return this.enterRetryWaitFenced(z,Q.ok,"internal","internal")}}async advanceGrantOnStartAsync($){if(this.provider.mode!=="async")return I("failed_precondition","non-retryable","async startup advance requires an asynchronous lifecycle provider");let Z=this.reconcilePendingTransitions($);if(!K(Z))return Z;let Q=this.vault.getGrant($);if(!K(Q))return Q;if(Q.ok.state==="REFRESHING"||Q.ok.state==="PROBING")return this.recoverGrantOnStartAsync($);if(Q.ok.state==="AUTH_BLOCKED"){let z=this.invokeRepairHook(Q.ok,"repair");return K(z)?Q:z}if(Q.ok.state==="DISABLED")return Q;let X=this.nowMs();if(Q.ok.state==="ACTIVE"){if(![Q.ok.refreshAt,Q.ok.keepaliveAt,Q.ok.atExpiresAt].some((j)=>j!==void 0&&O0(j)<=X))return Q;let Y=this.transition($,"REFRESH_DUE","scheduled");if(!K(Y))return Y;return this.dispatchRefreshAsync($)}if(Q.ok.state==="RETRY_WAIT"){if(Q.ok.retry===void 0||O0(Q.ok.retry.nextAt)>X)return Q;let z=this.transition($,"REFRESH_DUE","scheduled");if(!K(z))return z;return this.dispatchRefreshAsync($)}if(Q.ok.state==="REFRESH_DUE"){let z=Q.ok.dispatchEligibleAt??Q.ok.stateAt;if(O0(z)>X)return Q;return this.dispatchRefreshAsync($)}return Q}async recoverGrantOnStartAsync($){if(this.provider.mode!=="async")return I("failed_precondition","non-retryable","async crash recovery requires an asynchronous lifecycle provider");let Z=this.reconcilePendingTransitions($);if(!K(Z))return Z;let Q=this.vault.getGrant($);if(!K(Q))return Q;if(Q.ok.state==="PROBING"){let j={grantId:$,state:"PROBING",authorityVersion:Q.ok.authorityVersion,phase:"probe"};return this.transitionFence(j,"AUTH_BLOCKED","unauthenticated","internal",void 0,"engine-start")}if(Q.ok.state!=="REFRESHING")return Q;let X={grantId:$,state:"REFRESHING",authorityVersion:Q.ok.authorityVersion,phase:Q.ok.method==="api-key"||Q.ok.method==="cookie-session"?"keepalive":"refresh"},z=this.transitionFence(X,"PROBING","unavailable","internal",void 0,"engine-start");if(!K(z)){let j=this.vault.getGrant($);if(K(j)&&j.ok.state==="PROBING"&&j.ok.authorityVersion===X.authorityVersion+1)return this.settleAuditFailure({grantId:$,state:"PROBING",authorityVersion:j.ok.authorityVersion,phase:"probe"},j.ok,"AUTH_BLOCKED",z);return z}let Y={grantId:$,state:"PROBING",authorityVersion:z.ok.authorityVersion,phase:"probe"};try{return await this.runProbeRefreshAsync(Y,z.ok)}catch{return this.enterRetryWaitFenced(Y,z.ok,"internal","internal")}}async runInitialRefreshAsync($,Z){let Q=this.vault.getSecret(Z.grantId,"rt");if(r(Q))return this.settleCheckedFailure($,Z,"unavailable","internal",Q);if(f$(Q))return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");let X=this.refreshReq(Z,Q.ok);if(!K(X))return this.settleCheckedFailure($,Z,"unavailable","internal",X);let z=await this.callRefreshAsync(X.ok);if(z.kind==="rejected")return this.enterProbeAndRunAsync($,Z,"rejected");if(z.kind==="deadline")return this.enterProbeAndRunAsync($,Z,"transient");let Y=z.result;if(r(Y))return this.settleCheckedFailure($,Z,"unavailable","transient",Y);if(f$(Y))return this.enterProbeAndRunAsync($,Z,"empty");switch(Y.ok.kind){case"ok":return this.commitAndActivateFenced($,Y.ok);case"invalid_grant":return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");case"throttled":return this.enterRetryWaitFenced($,Z,"resource_exhausted","transient");case"network":return this.enterProbeAndRunAsync($,Z,"transient")}}async enterProbeAndRunAsync($,Z,Q){let X=this.transitionFence($,"PROBING","unavailable",Q);if(!K(X)){let Y=this.vault.getGrant(Z.grantId);if(K(Y)&&Y.ok.state==="PROBING"&&Y.ok.authorityVersion===$.authorityVersion+1)return this.settleAuditFailure({grantId:Z.grantId,state:"PROBING",authorityVersion:Y.ok.authorityVersion,phase:"probe"},Y.ok,"AUTH_BLOCKED",X);return X}let z={grantId:Z.grantId,state:"PROBING",authorityVersion:X.ok.authorityVersion,phase:"probe"};try{return await this.runProbeRefreshAsync(z,X.ok)}catch{return this.enterRetryWaitFenced(z,X.ok,"internal","internal")}}async callRefreshAsync($){if(this.provider.mode!=="async")return{kind:"rejected"};let Z;try{Z=this.provider.transport.refresh($)}catch{return{kind:"rejected"}}let Q=Z.then((j)=>({kind:"result",result:this.sanitizeProviderResult(j)}),()=>({kind:"rejected"})),X,z=new Promise((j)=>{X=setTimeout(()=>j({kind:"deadline"}),this.asyncPhaseTimeoutMs)}),Y=await Promise.race([Q,z]);if(X!==void 0)clearTimeout(X);return Y}async callProbeAsync($){if(this.provider.mode!=="async")return{kind:"rejected"};let Z;try{Z=this.provider.transport.probe($)}catch{return{kind:"rejected"}}let Q=Z.then((j)=>({kind:"result",result:this.sanitizeProviderResult(j)}),()=>({kind:"rejected"})),X,z=new Promise((j)=>{X=setTimeout(()=>j({kind:"deadline"}),this.asyncPhaseTimeoutMs)}),Y=await Promise.race([Q,z]);if(X!==void 0)clearTimeout(X);return Y}sanitizeProviderResult($){if(r($))return I($.err.code,$.err.retryability,"provider lifecycle callback returned a checked failure");if(f$($))return G$("provider lifecycle callback returned checked empty");return $}async runProbeRefreshAsync($,Z){if(Z.method==="api-key"||Z.method==="cookie-session")return this.keepaliveProbeAsync($,Z);let Q=this.vault.getSecret(Z.grantId,"rt");if(r(Q))return this.settleCheckedFailure($,Z,"unavailable","internal",Q);if(f$(Q))return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");let X=this.refreshReq(Z,Q.ok);if(!K(X))return this.settleCheckedFailure($,Z,"unavailable","internal",X);let z=await this.callRefreshAsync(X.ok);if(z.kind==="rejected")return this.enterRetryWaitFenced($,Z,"unavailable","rejected");if(z.kind==="deadline")return this.enterRetryWaitFenced($,Z,"deadline_exceeded","transient");let Y=z.result;if(r(Y))return this.settleCheckedFailure($,Z,"unavailable","transient",Y);if(f$(Y))return this.enterRetryWaitFenced($,Z,"unavailable","empty");switch(Y.ok.kind){case"ok":return this.commitAndActivateFenced($,Y.ok);case"invalid_grant":return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");case"throttled":return this.enterRetryWaitFenced($,Z,"resource_exhausted","transient");case"network":return this.enterRetryWaitFenced($,Z,"unavailable","transient")}}async keepaliveProbeAsync($,Z){let Q=Z.method==="api-key"?"apiKey":"cookies",X=this.vault.getSecret(Z.grantId,Q);if(r(X))return this.settleCheckedFailure($,Z,"unavailable","internal",X);if(f$(X))return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");let z=this.matrix.get(Z.provider),Y=K(z)?z.ok.probeOp:"probe",j=await this.callProbeAsync({provider:Z.provider,op:Y,secret:X.ok});if(j.kind==="rejected")return this.enterRetryWaitFenced($,Z,"unavailable","rejected");if(j.kind==="deadline")return this.enterRetryWaitFenced($,Z,"deadline_exceeded","transient");let W=j.result;if(r(W))return this.settleCheckedFailure($,Z,"unavailable","transient",W);if(f$(W))return this.enterRetryWaitFenced($,Z,"unavailable","empty");switch(W.ok.kind){case"ok":{let V=this.nowMs();return this.transitionFence($,"ACTIVE","scheduled","success",{keepaliveAt:S$(V+A9),clearRetry:!0})}case"unauthorized":return this.transitionFence($,"AUTH_BLOCKED","unauthenticated","definitive");case"network":return this.enterRetryWaitFenced($,Z,"unavailable","transient")}}transitionFence($,Z,Q,X,z,Y){if(!Y7[$.state].includes(Z))return I("failed_precondition","non-retryable","illegal fenced grant transition");let j=this.vault.compareAndTransition($,Z,S$(this.nowMs()),z,{reason:Q,...Y!==void 0?{recoveredBy:Y}:{}});if(!K(j))return j;if(j.ok.kind==="superseded")return this.discardSuperseded($,j.ok.observed,X);return this.emitAppliedTransition($.grantId,$.state,Z,Q,$.authorityVersion,j.ok.value,Y)}enterRetryWaitFenced($,Z,Q,X){let z=this.nowMs(),Y=(Z.retry?.n??0)+1,j=Math.min(X7*2**(Y-1),z7),W=Math.round(j*(1+(this.rng()*2-1)*uK));return this.transitionFence($,"RETRY_WAIT",Q,X,{retry:{n:Y,nextAt:S$(z+W),firstFailAt:Z.retry?.firstFailAt??S$(z)}})}settleCheckedFailure($,Z,Q,X,z){let Y=this.enterRetryWaitFenced($,Z,Q,X);if(!K(Y))return Y;return z}settleAuditFailure($,Z,Q,X){if(Q==="RETRY_WAIT")this.enterRetryWaitFenced($,Z,"internal","internal");else this.transitionFence($,"AUTH_BLOCKED","internal","internal");let z=this.vault.getGrant($.grantId);if(K(z)&&z.ok.state===$.state&&z.ok.authorityVersion===$.authorityVersion)return I("internal","retry-at-higher-level","lifecycle audit failure settlement did not release its owned authority fence");return X}commitAndActivateFenced($,Z){let Q=this.nowMs(),X={at:Z.accessToken,atExpiresAt:S$(sZ(Q,Z.expiresInSec)),refreshAt:S$(iZ(Q,Q,Z.refreshInSec,Z.expiresInSec,this.rng)),keepaliveAt:S$(Q+A9),now:S$(Q)};if(Z.refreshToken!==void 0)X.rt=Z.refreshToken;let z=this.vault.commitRefreshSuccessFenced($,X,{reason:"scheduled"});if(!K(z))return z;if(z.ok.kind==="superseded")return this.discardSuperseded($,z.ok.observed,"success");return this.incidentsFired.delete(`retry-cumulative-24h:${$.grantId}`),this.emitAppliedTransition($.grantId,$.state,"ACTIVE","scheduled",$.authorityVersion,z.ok.value)}discardSuperseded($,Z,Q){let X=this.emitter.emit("auth.grant.outcome_discarded",{grantId:$.grantId,phase:$.phase,outcomeClass:Q,expectedState:$.state,expectedAuthorityVersion:$.authorityVersion,observedState:Z.state,observedAuthorityVersion:Z.authorityVersion,reason:"superseded"});if(!K(X))return X;return I("aborted","non-retryable","asynchronous lifecycle outcome was superseded by a newer grant authority generation")}emitAppliedTransition($,Z,Q,X,z,Y,j){let W={grantId:$,from:Z,to:Q,reason:X,priorAuthorityVersion:z,authorityVersion:Y.authorityVersion,transitionAt:Y.stateAt,...j!==void 0?{recoveredBy:j}:{}},V=this.emitTransitionAudit(W);if(!K(V))return V;if(Q==="AUTH_BLOCKED"){this.incidentsFired.delete(`retry-cumulative-24h:${$}`);let q=this.invokeRepairHook(Y,String(X));if(!K(q))return q}return H(Y)}reconcilePendingTransitions($){for(let Z of this.vault.listPendingGrantTransitions($)){let Q=this.emitTransitionAudit(Z);if(!K(Q))return Q}return H(!0)}emitTransitionAudit($){let Z;try{Z=this.emitter.emit("auth.grant.state",{grantId:$.grantId,from:$.from,to:$.to,reason:$.reason,priorAuthorityVersion:$.priorAuthorityVersion,authorityVersion:$.authorityVersion,...$.recoveredBy!==void 0?{recoveredBy:$.recoveredBy}:{}},{at:$.transitionAt})}catch{return I("internal","retry-at-higher-level","lifecycle transition audit emitter threw before returning a checked result")}if(!K(Z))return Z;if(this.emitter.wasLastEmissionDurable()){let Q=this.vault.acknowledgeGrantTransition($.grantId,$.authorityVersion,S$(this.nowMs()));if(!K(Q))return Q}return H(!0)}invokeRepairHook($,Z){if(this.hooks.onRepairNeeded===void 0)return H(void 0);try{let Q=this.hooks.onRepairNeeded($.grantId,Z,$.authorityVersion);if(Q===void 0||typeof Q==="number")return H(void 0);if(!K(Q))return Q;return H(void 0)}catch{return I("internal","retry-at-higher-level","AUTH_BLOCKED repair-order hook threw before returning a checked result")}}runProbeRefresh($){if(this.provider.mode!=="sync")return I("failed_precondition","non-retryable","synchronous probe refresh is unavailable for an async lifecycle provider");if($.method==="api-key"||$.method==="cookie-session")return this.keepaliveProbe($.grantId,$);let Z=this.vault.getSecret($.grantId,"rt");if(r(Z))return this.lockedAbort($.grantId,Z.err.message);if(f$(Z))return this.transition($.grantId,"AUTH_BLOCKED","unauthenticated");let Q=this.refreshReq($,Z.ok);if(!K(Q))return this.enterRetryWait($,"unavailable"),Q;let X=this.provider.transport.refresh(Q.ok);if(r(X))return X;if(f$(X))return I("internal","non-retryable","refresh transport returned empty \u2014 transport contract violation");switch(X.ok.kind){case"ok":return this.commitAndActivate($.grantId,$,X.ok);case"invalid_grant":return this.transition($.grantId,"AUTH_BLOCKED","unauthenticated");case"throttled":case"network":{let z=this.vault.getGrant($.grantId);if(K(z))this.enterRetryWait(z.ok,X.ok.kind==="throttled"?"resource_exhausted":"unavailable");return this.vault.getGrant($.grantId)}}}keepaliveProbe($,Z){if(this.provider.mode!=="sync")return I("failed_precondition","non-retryable","synchronous keepalive is unavailable for an async lifecycle provider");let Q=Z.method==="api-key"?"apiKey":"cookies",X=this.vault.getSecret($,Q);if(r(X))return this.lockedAbort($,X.err.message);if(f$(X))return this.transition($,"AUTH_BLOCKED","unauthenticated");let z=this.matrix.get(Z.provider),Y=K(z)?z.ok.probeOp:"probe",j=this.provider.transport.probe({provider:Z.provider,op:Y,secret:X.ok});if(r(j))return j;if(f$(j))return I("internal","non-retryable","probe transport returned empty \u2014 transport contract violation");switch(j.ok.kind){case"ok":{let W=this.nowMs(),V=this.vault.getGrant($);if(!K(V))return V;return this.vault.setState($,V.ok.state,S$(W),{keepaliveAt:S$(W+A9)}),this.transition($,"ACTIVE","scheduled")}case"unauthorized":return this.transition($,"AUTH_BLOCKED","unauthenticated");case"network":{let W=this.vault.getGrant($);if(K(W))this.enterRetryWait(W.ok,"unavailable");return this.vault.getGrant($)}}}commitAndActivate($,Z,Q){let X=this.nowMs(),z={at:Q.accessToken,atExpiresAt:S$(sZ(X,Q.expiresInSec)),refreshAt:S$(iZ(X,X,Q.refreshInSec,Q.expiresInSec,this.rng)),keepaliveAt:S$(X+A9),now:S$(X)};if(Q.refreshToken!==void 0)z.rt=Q.refreshToken;let Y=this.vault.commitRefreshSuccess($,z,{reason:"scheduled"});if(!K(Y))return Y;let j=this.vault.getGrant($);if(!K(j))return j;return this.incidentsFired.delete(`retry-cumulative-24h:${$}`),this.emitAppliedTransition($,Z.state,"ACTIVE","scheduled",Z.authorityVersion,j.ok)}enterRetryWait($,Z){let Q=this.nowMs(),X=($.retry?.n??0)+1,z=Math.min(X7*2**(X-1),z7),Y=Math.round(z*(1+(this.rng()*2-1)*uK)),j={n:X,nextAt:S$(Q+Y),firstFailAt:$.retry?.firstFailAt??S$(Q)},W=this.vault.getGrant($.grantId);if(!K(W))return;this.vault.setState($.grantId,W.ok.state,W.ok.stateAt,{retry:j}),this.transition($.grantId,"RETRY_WAIT",Z)}lockedAbort($,Z){return j5("lockedOverlay",`refresh of grant '${$}' aborted: ${Z}`)}refreshReq($,Z){let Q={provider:$.provider,refreshToken:Z};if($.clientId!==void 0)Q.clientId=$.clientId;let X;try{X=this.vault.getSecret($.grantId,"clientSecret")}catch{return I("internal","retry-at-higher-level","client-secret custody read threw before returning a checked result")}if(r(X))return X;if(K(X))Q.clientSecret=X.ok;return H(Q)}}var Q7=20000,pK=20000,lK=60000,X7=60000,z7=3600000,uK=0.2,cK=86400000,A9=2592000000,j7=300000,tM=0.1,dK=16,nK=4,iK=60000,Y7,S$=($)=>new Date($).toISOString(),O0=($)=>Date.parse($);var C3=E(()=>{f();X0();M3();Y7={ACTIVE:["REFRESH_DUE","DISABLED","AUTH_BLOCKED"],REFRESH_DUE:["REFRESHING","DISABLED","AUTH_BLOCKED"],REFRESHING:["ACTIVE","AUTH_BLOCKED","PROBING","RETRY_WAIT","DISABLED"],PROBING:["ACTIVE","AUTH_BLOCKED","RETRY_WAIT","DISABLED"],RETRY_WAIT:["REFRESH_DUE","AUTH_BLOCKED","DISABLED"],AUTH_BLOCKED:["ACTIVE","DISABLED"],DISABLED:["REFRESH_DUE"]}});function x$($,Z,Q,X,z,Y={}){let j=$.getFlow(X);if(!K(j))return j;let W={...j.ok,state:z,stateAt:eM(Q)};if(Y.stuckClass!==void 0)W.stuckClass=Y.stuckClass;if(z!=="STUCK")delete W.stuckClass;if(Y.grantId!==void 0)W.grantId=Y.grantId;if(Y.resumeUsed!==void 0)W.resumeUsed=Y.resumeUsed;let V=$.putFlow(W);if(!K(V))return V;let q={flowId:X,flowType:W.flowType,source:W.source,state:z};if(W.stuckClass!==void 0)q.stuckClass=W.stuckClass;let B=z==="STUCK"?"auth.flow.stuck":z==="RESUMED"?"auth.flow.resumed":z==="DONE"?"auth.flow.completed":z==="ABANDONED"?"auth.flow.abandoned":"auth.flow.state";return Z.emit(B,q),H(W)}var W7,V7=604800000,eM=($)=>new Date($).toISOString();var F3=E(()=>{f();W7={PREP:30000,WAIT_HUMAN:900000,DRIVE:900000,MAILBOX_2FA:600000,EXCHANGE:30000,PERSIST:5000}});function $P($){return Number.isFinite($.x)&&Number.isFinite($.y)&&Number.isFinite($.w)&&Number.isFinite($.h)&&$.w>0&&$.h>0}function K7($,Z){let Q;try{Q=new RegExp(Z.pattern,"g")}catch{return I("invalid_argument","non-retryable","blind-copy: extraction pattern is not a valid expression")}let X=Z.domSelector,z=X===void 0?[]:$.elements.filter((G)=>G.selector===X);if(X!==void 0&&z.length===0)return I("not_found","non-retryable",`blind-copy: selector '${X}' resolves to no element in the rung-B DOM snapshot`);let Y=X===void 0?[$.domSnapshot]:z.map((G)=>G.text),j;for(let G of Y){Q.lastIndex=0;let J=Q.exec(G);if(J!==null&&(J[1]??J[0])!==""){j=J[1]??J[0];break}}if(j===void 0)return I("not_found","non-retryable","blind-copy: pattern matched nothing on the console page");let W=new Set([j]);Q.lastIndex=0;for(let G of $.domSnapshot.matchAll(Q)){let J=G[1]??G[0];if(J!=="")W.add(J)}for(let G of z)if(G.text!=="")W.add(G.text);let V=[],q=new Set;for(let G of $.elements){let J=!1;for(let L of W)if(G.text.includes(L)){J=!0;break}if(!J)continue;if(!$P(G.region))return I("failed_precondition","non-retryable",`blind-copy: element '${G.selector}' displays the value but its capture region is not a maskable rect \u2014 fail closed (auth.md \xA74.5)`);let U=`${G.region.x},${G.region.y},${G.region.w},${G.region.h}`;if(q.has(U))continue;q.add(U),V.push({...G.region})}if(V.length===0)return I("failed_precondition","non-retryable","blind-copy: the value is on the page but no captured element carries it \u2014 its screenshot region cannot be masked, fail closed (auth.md \xA74.5)");let B=$.domSnapshot;for(let G of[...W].sort((J,U)=>U.length-J.length))B=B.split(G).join(bX);return H({secret:j,redactionMask:V,redactedDomSnapshot:B})}function q7($,Z){return l0(`${$.redactedDomSnapshot}
90
+ ${JSON.stringify($.redactionMask)}`,Z)}var H7=E(()=>{f();X0();A8()});import{createHash as sK,randomBytes as oK}from"crypto";import{performance as ZP}from"perf_hooks";function B7($,Z){return`upstream response I-7 return guard exceeded its ${L7}ms monotonic deadline (phase: ${$})${Z===void 0?"":`; bodyBytes=${Z}`}`}class rZ{vault;emitter;matrix;lifecycle;runs;declaredScopes;nowMs;upstream;upstreamAsync;tokens;hooks;scanNowMs;ulid=V$();handles=new Map;pendingFlows=new Map;listener=null;closed=!1;lockedIncidentFired=!1;rtIssuance=new Map;constructor($){this.vault=$.vault,this.emitter=$.emitter,this.matrix=$.matrix,this.lifecycle=$.lifecycle,this.runs=$.runs,this.declaredScopes=$.declaredScopes,this.nowMs=$.nowMs,this.upstream=$.upstream??tK,this.upstreamAsync=$.upstreamAsync??XP,this.tokens=$.tokens??eK,this.hooks=$.hooks??{},this.scanNowMs=$.scanNowMs??(()=>ZP.now())}close(){this.closed=!0;let $;try{this.listener?.stop(!0)}catch{$=T$("internal","non-retryable","broker listener threw during close")}finally{this.listener=null;for(let Z of this.handles.values()){if(!Z.revoked)Z.revoked=!0,this.clearHandleCapabilities(Z);if(Z.inFlight===null){let Q=this.emitHandleSummary(Z);if(!K(Q)&&$===void 0)$=r(Q)?Q.err:T$("internal","non-retryable","broker close summary returned empty")}}}return $===void 0?H(void 0):v($)}custody(){if(this.closed)return I("failed_precondition","non-retryable","broker is closed");if(this.emitter.isStopped())return j5("lockedOverlay","event log unwritable past the 10k buffer \u2014 custody never silently unaudited (auth.md \xA77.2, LOCKED-equivalent)");let $=this.vault.checkCustody();if(!K($)){let Z=r($)?$.err.message:"custody check returned empty \u2014 contract violation";if(!this.lockedIncidentFired)this.lockedIncidentFired=!0,this.hooks.onIncident?.("locked-overlay",{detail:Z});return j5("lockedOverlay",`LOCKED: ${Z}`)}return this.lockedIncidentFired=!1,H(!0)}deny($,Z,Q){return this.emitter.emit("auth.handle.denied",{orderId:$,source:Z,reason:Q.code}),v(this.redactOutgoing(Q.layer==="auth"?Q:T$(Q.code,Q.retryability,Q.message,Q)))}mint($,Z,Q,X,z,Y){let j=this.custody();if(r(j))return this.deny($,Q,j.err);if(!this.runs.isLive(Z)||this.runs.orderIdFor(Z)!==$)return this.deny($,Q,{code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:`mint requires a live, matching (WorkOrder, WorkerRun) pair \u2014 run '${Z}' is not live for order '${$}' (\xA74.2 rule 1)`});let W=this.vault.findGrant(Q,X);if(r(W))return this.deny($,Q,W.err);if(f$(W))return this.deny($,Q,{code:"not_found",layer:"auth",retryability:"non-retryable",message:`no grant for (source '${Q}', account '${X}') \u2014 enrollment is the driver's job (D11)`});let V=W.ok;if(V.state==="AUTH_BLOCKED"||V.state==="DISABLED")return this.deny($,Q,{code:"failed_precondition",layer:"auth",retryability:"retry-at-higher-level",message:`grant '${V.grantId}' is ${V.state} \u2014 repair/re-enable before minting (never empty success, FM-21)`});let q=this.declaredScopes(Q);if(q===void 0)return this.deny($,Q,{code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:`source '${Q}' has no manifest scope declaration \u2014 the ceiling is unverifiable, fail closed (\xA74.2 rule 2)`});let B=z.filter((F)=>!q.includes(F));if(B.length>0)return this.emitter.emit("auth.grant.scope_violation",{orderId:$,source:Q,requested:z,declared:q}),this.hooks.onIncident?.("scope-violation",{orderId:$,source:Q,requested:z.join(" ")}),this.deny($,Q,{code:"permission_denied",layer:"auth",retryability:"non-retryable",message:`scope violation: requested [${B.join(", ")}] exceeds the manifest declaration (incident filed, \xA74.6)`});let G=z.filter((F)=>!V.scopes.includes(F));if(G.length>0)return this.deny($,Q,{code:"permission_denied",layer:"auth",retryability:"non-retryable",message:`requested [${G.join(", ")}] not in the GRANTED set (partial consent narrows the ceiling \u2014 FM-18 permission-scoped, not an incident)`});let J=this.runs.remainingWallClockMs(Z);if(J===null)return this.deny($,Q,{code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:`run '${Z}' has no wallClock budget on record \u2014 handles die with their run (\xA74.2 rule 3)`});let U=Math.min((Y??J7)*1000,J),L=this.nowMs(),D={id:this.ulid(),source:V.source,scopes:[...z],expiresAt:m5(L+U)};if(V.account.label!=="")D.account=V.account.label;let P=Q3(D);if(!K(P))return P;return this.handles.set(D.id,{handleId:D.id,grantId:V.grantId,orderId:$,runId:Z,scopes:[...z],expiresAt:D.expiresAt,revoked:!1,calls:0,denials:0,byOp:{},capabilities:new Map,capabilityCaptures:0,capabilityInjections:0,inFlight:null}),this.emitter.emit("auth.handle.minted",{handleId:D.id,grantId:V.grantId,orderId:$,runId:Z,scopes:[...z],expiresAt:D.expiresAt}),H(D)}renew($){let Z=this.custody();if(!K(Z))return Z;let Q=this.handles.get($);if(Q===void 0||Q.revoked)return I("not_found","non-retryable",`no live handle '${$}'`);if(!this.runs.isLive(Q.runId)||this.runs.orderIdFor(Q.runId)!==Q.orderId)return j5("heartbeatStale",`renew refused: run '${Q.runId}' is not a current member of order '${Q.orderId}' (I-7 \u2014 renewal requires a live WorkOrder/WorkerRun pair)`);let X=this.runs.remainingWallClockMs(Q.runId)??0,z=this.nowMs();Q.expiresAt=m5(z+Math.min(J7*1000,X));let Y=this.vault.getGrant(Q.grantId);if(!K(Y))return Y;let j={id:Q.handleId,source:Y.ok.source,scopes:[...Q.scopes],expiresAt:Q.expiresAt};if(Y.ok.account.label!=="")j.account=Y.ok.account.label;return this.emitter.emit("auth.handle.minted",{handleId:Q.handleId,grantId:Q.grantId,orderId:Q.orderId,runId:Q.runId,scopes:[...Q.scopes],expiresAt:Q.expiresAt}),H(j)}describe($){let Z=this.handles.get($);if(Z===void 0)return I("not_found","non-retryable",`no handle '${$}'`);let Q=this.vault.getGrant(Z.grantId);if(!K(Q))return Q;return H({source:Q.ok.source,accountId:Q.ok.account.id,accountLabel:Q.ok.account.label,scopes:[...Z.scopes],expiresAt:Z.expiresAt})}revoke($){let Z=this.handles.get($);if(Z===void 0)return I("not_found","non-retryable",`no handle '${$}'`);if(!Z.revoked)Z.revoked=!0,this.clearHandleCapabilities(Z);if(Z.inFlight!==null)return H(void 0);return this.emitHandleSummary(Z)}emitHandleSummary($){if($.inFlight!==null)return I("failed_precondition","retry-at-higher-level","terminal handle summary is pending an in-flight provider call");let Z=this.emitter.emit("auth.handle.summary",{handleId:$.handleId,calls:$.calls,denials:$.denials,byOp:$.byOp,capabilityCaptures:$.capabilityCaptures,capabilityInjections:$.capabilityInjections});if(!K(Z))return Z;if(this.handles.get($.handleId)===$)this.handles.delete($.handleId);return H(void 0)}clearHandleCapabilities($){for(let Z of $.capabilities.values())for(let Q of Z.values())if(Q!==null)this.vault.registry.unregister(Q);$.capabilities.clear()}commitHandleCapabilities($,Z,Q){let X=new Map,z=$.capabilityCaptures;for(let[Y,j]of Z){X.set(Y,$.capabilities.get(Y));for(let V of j.values())if(V!==null)this.vault.registry.register(V);let W=$.capabilities.get(Y);if(W!==void 0){for(let V of W.values())if(V!==null)this.vault.registry.unregister(V)}$.capabilities.set(Y,j)}return $.capabilityCaptures+=Q,()=>{for(let[Y,j]of X){let W=$.capabilities.get(Y);if(W!==void 0){for(let V of W.values())if(V!==null)this.vault.registry.unregister(V)}if(j===void 0){$.capabilities.delete(Y);continue}for(let V of j.values())if(V!==null)this.vault.registry.register(V);$.capabilities.set(Y,j)}$.capabilityCaptures=z}}resolve($){let Z=this.custody();if(!K(Z))return Z;let Q=this.handles.get($);if(Q===void 0||Q.revoked)return I("not_found","non-retryable",`no live handle '${$}'`);if(N3(Q.expiresAt)<=this.nowMs())return j5("handleExpired",`handle '${$}' expired \u2014 renew (with a live run) is the remedy`);let X=this.vault.getGrant(Q.grantId);if(!K(X))return X;let z=X.ok;if(z.state==="AUTH_BLOCKED"||z.state==="DISABLED")return j5("upstreamDefinitive",`grant '${z.grantId}' is ${z.state} \u2014 AUTH_BLOCKED-class, never empty success (FM-21)`);let Y=z.method==="api-key"?"apiKey":z.method==="cookie-session"?"cookies":"at",j=this.vault.getSecret(z.grantId,Y);if(r(j))return j;if(f$(j))return I("unavailable","transient",`grant '${z.grantId}' holds no live '${Y}' credential`);if(Y==="at"&&z.atExpiresAt!==void 0&&N3(z.atExpiresAt)<=this.nowMs())return I("unavailable","transient",`grant '${z.grantId}' AT expired and refresh has not landed \u2014 transient, refresher owns recovery (\xA74.3)`);return H({grantId:z.grantId,grantState:z.state,grantAuthorityVersion:z.authorityVersion,scheme:Y==="cookies"?"cookie":"bearer",secret:j.ok})}execute($,Z){let Q=this.prepareExecution($,Z);if(!K(Q))return Q;let X;try{X=this.upstream.perform(Q.ok.upstream)}catch{X=I("unavailable","transient","upstream transport threw before returning a checked result")}return this.finishExecution(Q.ok,X)}async executeAsync($,Z){let Q=this.prepareExecution($,Z);if(!K(Q))return Q;let X;try{X=this.upstreamAsync.perform(Q.ok.upstream)}catch{X=Promise.resolve(I("unavailable","transient","asynchronous upstream transport rejected before returning a checked result"))}let z=X.then((V)=>({kind:"response",response:V}),()=>({kind:"response",response:I("unavailable","transient","asynchronous upstream transport rejected before returning a checked result")})),Y,j=new Promise((V)=>{Y=setTimeout(()=>V({kind:"deadline"}),Q.ok.upstream.timeoutMs)}),W=await Promise.race([z,j]);if(Y!==void 0)clearTimeout(Y);if(W.kind==="deadline")return this.finishDeadlineExecution(Q.ok);return this.finishExecution(Q.ok,W.response)}prepareExecution($,Z){let Q=this.handles.get($),X=(R)=>{if(Q!==void 0)Q.denials++;return v(this.redactOutgoing(R))},z=this.snapshotExecRequest(Z);if(!K(z))return X(r(z)?z.err:T$("internal","non-retryable","request snapshot returned empty"));let Y=z.ok;if(Q===void 0||Q.revoked)return X({code:"not_found",layer:"auth",retryability:"non-retryable",message:`no live handle '${$}'`});if(Q.inFlight!==null)return X({code:"failed_precondition",layer:"auth",retryability:"retry-at-higher-level",message:`handle '${$}' already has one provider call in flight`});if(!this.runs.isLive(Q.runId)||this.runs.orderIdFor(Q.runId)!==Q.orderId)return X({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:`run '${Q.runId}' is not a live member of order '${Q.orderId}' \u2014 handles die with their WorkOrder/WorkerRun pair (\xA74.2)`});let j=Object.keys(Y.headers).find((R)=>T3.has(R.toLowerCase()));if(j!==void 0){let{code:R,retryability:O}={code:"invalid_argument",retryability:"non-retryable"};return X({code:R,layer:"auth",retryability:O,message:`credential header '${j}' FORBIDDEN in ExecRequest \u2014 the broker injects credentials server-side (I-7)`})}let W;try{W=new URL(Y.url)}catch{return X({code:"invalid_argument",layer:"auth",retryability:"non-retryable",message:"unparseable request URL"})}let V=kK(Y.url);if(!K(V))return X(V.err);let q=this.vault.getGrant(Q.grantId);if(!K(q))return X(r(q)?q.err:T$("internal","non-retryable","grant row vanished under a live handle"));let B=this.matrix.get(q.ok.provider);if(!K(B))return X(r(B)?B.err:T$("internal","non-retryable","provider policy lookup returned empty"));let G=wK(B.ok.responseCapabilities),J=Object.keys(Y.headers).find((R)=>G.has(R.toLowerCase()));if(J!==void 0)return X({code:"invalid_argument",layer:"auth",retryability:"non-retryable",message:`response-derived capability header '${J}' FORBIDDEN in ExecRequest \u2014 the broker alone injects it (I-7)`});if(mK(B.ok.responseCapabilities,W))return X({code:"invalid_argument",layer:"auth",retryability:"non-retryable",message:"response-derived capability query material is FORBIDDEN in ExecRequest \u2014 use a secret-free broker reference (I-7)"});let U=this.matrix.resolveOp(q.ok.provider,Y.method,W,Q.scopes);if(!K(U))return X(U.err);let L=hK(B.ok.responseCapabilities,Q.capabilities,Y.capabilityRefs,Y.method,W);if(!K(L))return X(L.err);let D=this.resolve($);if(!K(D))return X(D.err);let P={...Y.headers,...L.ok.headers};if(D.ok.scheme==="cookie")P.Cookie=D.ok.secret;else P.Authorization=`Bearer ${D.ok.secret}`;let F=this.runs.remainingWallClockMs(Q.runId),A=N3(Q.expiresAt)-this.nowMs();if(F===null||F<=0||A<=0)return X({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:`run or handle authority expired before provider dispatch for run '${Q.runId}'`});let N=Math.max(1,Math.floor(Math.min(Y.timeoutMs??aK,F,A))),S=this.ulid();return Q.inFlight=S,Q.calls++,Q.byOp[U.ok.op]=(Q.byOp[U.ok.op]??0)+1,Q.capabilityInjections+=L.ok.injectionCount,H({handle:Q,executionId:S,source:q.ok.source,op:U.ok.op,url:W,requestMethod:Y.method,rawRequestPath:V.ok,grantState:D.ok.grantState,grantAuthorityVersion:D.ok.grantAuthorityVersion,upstream:{method:Y.method,url:Y.url,headers:P,timeoutMs:N,...Y.body!==void 0?{body:new Uint8Array(Y.body)}:{}},started:this.nowMs(),capabilityRules:B.ok.responseCapabilities})}finishExecution($,Z){let Q;try{Q=this.finishOwnedExecution($,Z)}catch{$.handle.denials++,Q=I("internal","non-retryable","broker response finalization threw before returning a checked result")}if($.handle.inFlight===$.executionId)$.handle.inFlight=null;if($.handle.revoked){let X=this.emitHandleSummary($.handle);if(!K(X))return X}return Q}finishDeadlineExecution($){let Z=$.handle,Q=this.emitExecutionSpan($,"deadline-exceeded");if(Z.denials++,!K(Q)){if(Z.inFlight===$.executionId)Z.inFlight=null;return r(Q)?v(this.redactOutgoing(Q.err)):I("internal","non-retryable","terminal auth span emission returned empty")}if(Z.inFlight===$.executionId)Z.inFlight=null;if(Z.revoked){let X=this.emitHandleSummary(Z);if(!K(X))return X}return I("deadline_exceeded","retry-at-higher-level","asynchronous upstream call exceeded its broker-owned deadline")}emitExecutionSpan($,Z){let Q=$.handle;try{let X=this.emitter.emitSpan({traceId:Q.runId,spanId:this.ulid(),name:"auth.execute",attrs:{handleId:Q.handleId,source:$.source,op:$.op,host:$.url.host,status:String(Z)},status:Z===200?"ok":"error",startTs:m5($.started),durationMs:this.nowMs()-$.started});if(!K(X))return X;return H(void 0)}catch{return I("internal","non-retryable","terminal auth span emission threw")}}executionAuthorityCurrent($){let Z=$.handle,Q=this.vault.getGrant(Z.grantId);return!this.closed&&this.handles.get(Z.handleId)===Z&&Z.inFlight===$.executionId&&!Z.revoked&&this.runs.isLive(Z.runId)&&this.runs.orderIdFor(Z.runId)===Z.orderId&&N3(Z.expiresAt)>this.nowMs()&&K(Q)&&Q.ok.state===$.grantState&&Q.ok.authorityVersion===$.grantAuthorityVersion}finishOwnedExecution($,Z){let Q=$.handle,X=(J)=>{return this.emitExecutionSpan($,J)},z=(J)=>{if(r(J))return v(this.redactOutgoing(J.err));return I("internal","non-retryable","terminal auth span emission returned empty")},Y=()=>{let J=X("authority-changed");if(Q.denials++,!K(J))return z(J);return v(this.redactOutgoing({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"provider response refused because its handle/run authority changed while the call was in flight"}))};if(!this.executionAuthorityCurrent($))return Y();if(!K(Z)){let J=X("transport-error");if(!K(J))return Q.denials++,z(J);return v(this.redactOutgoing(Z.err))}let j=this.scanNowMs()+L7,W=this.snapshotResponseStatus(Z.ok,j);if(!K(W)){let J=X("response-guard-limit");if(Q.denials++,!K(J))return z(J);return W}let V=W.ok;if(!this.executionAuthorityCurrent($))return Y();if(V===401){let J=this.lifecycle.transition(Q.grantId,"AUTH_BLOCKED","unauthenticated");Q.denials++;let U=X(V);if(!K(U))return z(U);if(!K(J))return v(this.redactOutgoing(r(J)?J.err:T$("internal","non-retryable","AUTH_BLOCKED transition returned empty")));return v(this.redactOutgoing({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:`upstream 401 (definitive) \u2014 grant '${Q.grantId}' flipped AUTH_BLOCKED (\xA74.3)`}))}let q=this.guardOutgoingResponse(Z.ok,V,j,Q,$.requestMethod,$.url,$.rawRequestPath,$.capabilityRules);if(!K(q)){let J=r(q)&&q.err.code==="permission_denied",U=X(J?"credential-reflection":"response-guard-limit");if(Q.denials++,!K(U))return z(U);return q}let B=this.scanNowMs()<=j;if(!this.executionAuthorityCurrent($))return Y();if(V===429){let J=X(V);if(!K(J))return Q.denials++,z(J);return v(this.redactOutgoing({code:"resource_exhausted",layer:"auth",retryability:"throttling",message:"upstream 429 \u2014 throttling class (\xA73 table)"}))}if(V>=500){let J=X(V);if(!K(J))return Q.denials++,z(J);return v(this.redactOutgoing({code:"unavailable",layer:"auth",retryability:"transient",message:`upstream ${V} \u2014 outcome-unknown class, transient (\xA73 table)`}))}if(!B){Q.denials++;let J=X("response-guard-limit");if(!K(J))return z(J);return I("deadline_exceeded","retry-at-higher-level",B7("release"))}let G=X(V);if(!K(G))return Q.denials++,z(G);if(!this.executionAuthorityCurrent($))return Q.denials++,v(this.redactOutgoing({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"provider response refused because its handle/run authority changed before release"}));return this.commitHandleCapabilities(Q,q.ok.snapshots,q.ok.captureCount),H(q.ok.response)}snapshotExecRequest($){let Z,Q,X,z,Y,j;try{let G=$;Z=G.method,Q=G.url,X=G.headers,z=G.capabilityRefs,Y=G.body,j=G.timeoutMs}catch{return I("invalid_argument","non-retryable","request field getter failed during broker ownership transfer")}if(typeof Z!=="string"||Z==="")return I("invalid_argument","non-retryable","request method must be a non-empty string");if(typeof Q!=="string"||Q==="")return I("invalid_argument","non-retryable","request URL must be a non-empty string");if(X===null||typeof X!=="object"||Array.isArray(X))return I("invalid_argument","non-retryable","request headers must be an object");let W={},V;try{V=Object.keys(X);for(let G of V){let J=X[G];if(typeof J!=="string")return I("invalid_argument","non-retryable","request header values must be strings");Object.defineProperty(W,G,{value:J,enumerable:!0,configurable:!1,writable:!1})}}catch{return I("invalid_argument","non-retryable","request header snapshot failed")}let q;if(z!==void 0){if(!Array.isArray(z))return I("invalid_argument","non-retryable","request capability references must be an array");let G;try{G=z.length}catch{return I("invalid_argument","non-retryable","request capability reference length getter failed")}if(!Number.isSafeInteger(G)||G<0||G>Z3)return I("invalid_argument","non-retryable","request capability reference count is outside its bound");let J=[];try{for(let L=0;L<G;L++){let D=z[L];if(D===null||typeof D!=="object"||Array.isArray(D))return I("invalid_argument","non-retryable","request capability reference must be an object");if(Object.keys(D).some((A)=>A!=="kind"&&A!=="id"))return I("invalid_argument","non-retryable","request capability reference contains an unknown field");let F=D;J.push({kind:F.kind,id:F.id})}}catch{return I("invalid_argument","non-retryable","request capability reference snapshot failed")}let U=F8(J);if(!K(U))return r(U)?{err:{...U.err,layer:"auth"}}:I("internal","non-retryable","request capability reference validation returned empty");q=U.ok.map((L)=>({kind:L.kind,id:L.id}))}let B;if(Y!==void 0){if(!(Y instanceof Uint8Array))return I("invalid_argument","non-retryable","request body must be a Uint8Array");try{let G=Y.byteLength;B=new Uint8Array(G),Uint8Array.prototype.set.call(B,Y)}catch{return I("invalid_argument","non-retryable","request body snapshot failed")}}if(j!==void 0&&(typeof j!=="number"||!Number.isFinite(j)||j<=0))return I("invalid_argument","non-retryable","request timeout must be a positive finite number");return H({method:Z,url:Q,headers:W,...q!==void 0?{capabilityRefs:q}:{},...B!==void 0?{body:B}:{},...j!==void 0?{timeoutMs:j}:{}})}recordTokenLeak($,Z){if(Z.length===0)return;this.emitter.emit("auth.incident.token_leak",{where:"artifact",pattern:Z[0].pattern,artifactRef:$}),this.hooks.onIncident?.("token-carryover",{where:$,pattern:Z[0].pattern})}snapshotResponseStatus($,Z){let Q=()=>this.scanNowMs()>Z?I("deadline_exceeded","retry-at-higher-level",B7("status")):null,X=Q();if(X!==null)return X;let z;try{z=$.status}catch{return I("unavailable","transient","upstream response status getter failed inside the I-7 return guard")}if(X=Q(),X!==null)return X;if(!Number.isFinite(z)||!Number.isInteger(z))return I("data_loss","non-retryable","upstream response status is not a finite integer");return H(z)}guardOutgoingResponse($,Z,Q,X,z,Y,j,W){let V,q=()=>this.scanNowMs()>Q?I("deadline_exceeded","retry-at-higher-level",B7("scan",V)):null,B=q();if(B!==null)return B;if(B=q(),B!==null)return B;let G;try{G=$.headers}catch{return I("unavailable","transient","upstream response headers getter failed inside the I-7 return guard")}if(B=q(),B!==null)return B;if(G===null||typeof G!=="object")return I("data_loss","non-retryable","upstream response headers are not an object");let J;try{J=Object.keys(G)}catch{return I("unavailable","transient","upstream response header enumeration failed inside the I-7 return guard")}if(B=q(),B!==null)return B;if(J.length>G7)return I("resource_exhausted","retry-at-higher-level",`upstream response exceeded the ${G7}-header I-7 return-guard limit`);let U=[],L=0,D={};for(let p of J){if(B=q(),B!==null)return B;let o;try{o=G[p]}catch{return I("unavailable","transient","upstream response header getter failed inside the I-7 return guard")}if(B=q(),B!==null)return B;if(typeof o!=="string")return I("data_loss","non-retryable","upstream response header value is not a string");if(L+=p.length+o.length,L>U7)return I("resource_exhausted","retry-at-higher-level",`upstream response exceeded the ${U7}-character header I-7 return-guard limit`);U.push(p,o),Object.defineProperty(D,p,{value:o,enumerable:!0,configurable:!1,writable:!1})}if(B=q(),B!==null)return B;let P;try{P=$.body}catch{return I("unavailable","transient","upstream response body getter failed inside the I-7 return guard")}if(B=q(),B!==null)return B;if(!(P instanceof Uint8Array))return I("data_loss","non-retryable","upstream response body is not a Uint8Array");let F;try{F=P.byteLength}catch{return I("unavailable","transient","upstream response body length failed inside the I-7 return guard")}if(F>aZ)return I("resource_exhausted","retry-at-higher-level",`upstream response exceeded the ${aZ}-byte body I-7 return-guard limit`);V=F;let A;try{A=new Uint8Array(F),Uint8Array.prototype.set.call(A,P)}catch{return I("unavailable","transient","upstream response body copy failed inside the I-7 return guard")}if(B=q(),B!==null)return B;let N=U.join(`
91
+ `);if(B=q(),B!==null)return B;let S=new TextDecoder().decode(A);if(B=q(),B!==null)return B;let R=()=>this.scanNowMs()>Q,O=$7(W,z,Y,Z,S,R,j);if(!K(O)){if(r(O)&&O.err.code==="permission_denied")this.recordTokenLeak("broker.response-capability",[{pattern:"response-capability",index:0,length:0}]);return O}let T=O.ok.bodyText,m=A;if(T!==S){if(m=new TextEncoder().encode(T),m.byteLength>aZ)return I("resource_exhausted","retry-at-higher-level",`sanitized upstream response exceeded the ${aZ}-byte I-7 return-guard limit`)}let k=new Set(O.ok.capturedSecrets);for(let p of X.capabilities.values())for(let o of p.values())if(o!==null)k.add(o);let d=k.size===0?"clean":P3([N],k,R),y=new Set(k);for(let p of O.ok.capturedSecrets)y.delete(p);let b=d==="clean"?y.size===0?"clean":P3([T],y,R):d;if(b==="aborted")return q()??I("deadline_exceeded","retry-at-higher-level","upstream response I-7 capability scan did not complete");if(b==="found")return this.recordTokenLeak("broker.response-capability",[{pattern:"response-capability",index:0,length:0}]),I("permission_denied","non-retryable","upstream response reflected response-derived capability material and was blocked by the I-7 return chokepoint");if(b==="ambiguous")return I("data_loss","non-retryable","response capability encoding exceeded bounded normalization");let g=fX(N,this.vault.registry,R);if(!g.complete)return q()??I("deadline_exceeded","retry-at-higher-level","upstream response I-7 header scan did not complete");let w=g.hit===null?fX(T,this.vault.registry,R):{complete:!0,hit:null};if(!w.complete)return q()??I("deadline_exceeded","retry-at-higher-level","upstream response I-7 body scan did not complete");if(B=q(),B!==null)return B;let u=g.hit??w.hit;if(u===null){let p=Object.freeze({status:Z,headers:Object.freeze(D),body:m});return H({response:p,snapshots:O.ok.snapshots,captureCount:O.ok.captureCount})}return this.recordTokenLeak("broker.response",[u]),I("permission_denied","non-retryable","upstream response contained credential material and was blocked by the I-7 return chokepoint")}redactOutgoing($){let{error:Z,hits:Q}=J3($,this.vault.registry);return this.recordTokenLeak("broker.error",Q),Z}ensureListener(){if(this.listener!==null)return H(this.listener.port??0);try{return this.listener=Bun.serve({hostname:"127.0.0.1",port:0,fetch:($)=>this.handleCallback($)}),H(this.listener.port??0)}catch($){return I("unavailable","transient",`loopback listener failed to bind: ${String($)}`)}}beginFlow($,Z,Q,X){let z=this.custody();if(!K(z))return z;let Y=X.flowType??"oauth-consent";if(Y!=="oauth-consent")return p0(`rung-B driven-browser flow '${Y}'`);let j=this.matrix.assertDriverAllowed(X.provider);if(!K(j))return j;let W=j.ok.authorizeUrl;if(W===void 0)return p0(`OAuth consent flow against real provider '${X.provider}'`);let V=this.ensureListener();if(!K(V))return V;let q=this.ulid(),B=A3(oK(48)),G=A3(sK("sha256").update(B).digest()),J=A3(oK(24)),U=`http://127.0.0.1:${V.ok}/callback`,L={flowId:q,flowType:Y,source:$,provider:X.provider,scopes:[...Q],state:"QUEUED",stateAt:m5(this.nowMs()),stateNonce:J,redirectPort:V.ok,resumeUsed:!1,...Z!==void 0?{accountHint:Z}:{},...X.batchId!==void 0?{batchId:X.batchId}:{}},D=this.vault.putFlow(L);if(!K(D))return D;let P=this.vault.putFlowCell(q,_3,B);if(!K(P))return P;this.emitter.emit("auth.flow.started",{flowId:q,flowType:Y,source:$,state:"QUEUED"});let F,A=new Promise((R)=>{F=R}),N={flowId:q,provider:X.provider,source:$,scopes:[...Q],redirectUri:U,settledPromise:A,trigger:X.trigger??"onboard",...X.clientId!==void 0?{clientId:X.clientId}:{}};N.settled=F,this.pendingFlows.set(J,N);let S=new URL(W);if(S.searchParams.set("response_type","code"),S.searchParams.set("redirect_uri",U),S.searchParams.set("state",J),S.searchParams.set("code_challenge",G),S.searchParams.set("code_challenge_method","S256"),S.searchParams.set("scope",Q.join(" ")),X.clientId!==void 0)S.searchParams.set("client_id",X.clientId);if(Z!==void 0)S.searchParams.set("account_hint",Z);return H({flowId:q,authUrl:S.toString()})}flowSettled($){for(let Z of this.pendingFlows.values())if(Z.flowId===$)return Z.settledPromise;return}handleCallback($){let Z=new URL($.url);if(Z.pathname!=="/callback")return new Response("not found",{status:404});let Q=Z.searchParams.get("state")??"",X=Z.searchParams.get("code")??"",z=this.pendingFlows.get(Q);if(z===void 0||X==="")return new Response("state nonce unknown \u2014 flow expired or CSRF",{status:400});this.pendingFlows.delete(Q);let Y=this.exchangeAndPersist(z,X);return z.settled?.(Y),K(Y)?new Response("Connected. You can close this tab.",{status:200}):new Response("Flow failed \u2014 see inbox.",{status:500})}exchangeAndPersist($,Z){let Q=this.nowMs();x$(this.vault,this.emitter,Q,$.flowId,"EXCHANGE");let X=this.vault.getFlowCell($.flowId,_3);if(!K(X))return x$(this.vault,this.emitter,Q,$.flowId,"STUCK",{stuckClass:"structural"}),I("internal","non-retryable","PKCE verifier missing broker-side \u2014 structural");let z=I("internal","non-retryable","exchange not attempted");for(let D=0;D<3;D++)if(z=this.tokens.exchange({provider:$.provider,code:Z,codeVerifier:X.ok,redirectUri:$.redirectUri,...$.clientId!==void 0?{clientId:$.clientId}:{}}),K(z)||r(z)&&z.err.retryability!=="transient"&&z.err.retryability!=="throttling")break;if(!K(z))return x$(this.vault,this.emitter,this.nowMs(),$.flowId,"STUCK",{stuckClass:"structural"}),v(this.redactOutgoing(r(z)?z.err:{code:"internal",layer:"auth",retryability:"non-retryable",message:"token endpoint returned empty"}));x$(this.vault,this.emitter,this.nowMs(),$.flowId,"PERSIST");let Y=z.ok,j=this.vault.findGrant($.source,Y.account.id),W=K(j)?j.ok.state:void 0,V=$.trigger==="restore"?"restore":$.trigger==="repair"?"repair":"user",q=W!==void 0&&W!=="ACTIVE",B=$.clientId!==void 0?"own-client-prod-unverified":"shared-client",G=this.vault.upsertGrant({source:$.source,account:Y.account,provider:$.provider,method:"oauth-pkce",clientMode:B,scopes:Y.grantedScopes,now:m5(Q),secrets:{at:Y.accessToken,...Y.refreshToken!==void 0?{rt:Y.refreshToken}:{}},atExpiresAt:m5(sZ(Q,Y.expiresInSec)),refreshAt:m5(iZ(Q,Q,Y.refreshInSec,Y.expiresInSec)),keepaliveAt:m5(Q+A9),...$.clientId!==void 0?{clientId:$.clientId}:{},transitionReason:V});if(!K(G))return x$(this.vault,this.emitter,this.nowMs(),$.flowId,"STUCK",{stuckClass:"structural"}),G;let J=G.ok.grantId;this.emitter.emit("auth.grant.issued",{grantId:J,source:$.source,accountId:Y.account.id,provider:$.provider,scopes:Y.grantedScopes,method:"oauth-pkce",clientMode:B});let U=`${$.clientId??"shared"} ${Y.account.id}`,L=(this.rtIssuance.get(U)??0)+1;if(this.rtIssuance.set(U,L),L===rK)this.hooks.onIncident?.("rt-cap-alarm",{key:U,count:L});if(q){let D=this.lifecycle.reconcilePendingTransitions(J);if(!K(D))return x$(this.vault,this.emitter,this.nowMs(),$.flowId,"STUCK",{stuckClass:"structural"}),D}return x$(this.vault,this.emitter,this.nowMs(),$.flowId,"DONE",{grantId:J}),H({grantId:J})}rtIssuanceCount($,Z){return this.rtIssuance.get(`${$??"shared"} ${Z}`)??0}rearmFlow($,Z="onboard"){let Q=this.custody();if(!K(Q))return Q;let X=this.vault.getFlow($);if(!K(X))return X;if(["DONE","ABANDONED"].includes(X.ok.state))return I("failed_precondition","non-retryable",`flow '${$}' is terminal (${X.ok.state}) \u2014 nothing to re-arm`);let z=X.ok.stateNonce;if(z===void 0)return I("internal","non-retryable",`flow '${$}' has no persisted state nonce`);let Y=this.vault.getFlowCell($,_3);if(!K(Y))return I("internal","non-retryable",`flow '${$}' has no persisted PKCE verifier`);let j=this.matrix.get(X.ok.provider);if(!K(j))return j;if(j.ok.authorizeUrl===void 0)return p0(`OAuth consent flow against real provider '${X.ok.provider}'`);let W=this.ensureListener();if(!K(W))return W;let V=`http://127.0.0.1:${W.ok}/callback`,q=A3(sK("sha256").update(Y.ok).digest());if(this.vault.putFlow({...X.ok,redirectPort:W.ok}),!this.pendingFlows.has(z)){let G,J=new Promise((L)=>{G=L}),U={flowId:$,provider:X.ok.provider,source:X.ok.source,scopes:X.ok.scopes,redirectUri:V,settledPromise:J,trigger:Z};U.settled=G,this.pendingFlows.set(z,U)}let B=new URL(j.ok.authorizeUrl);if(B.searchParams.set("response_type","code"),B.searchParams.set("redirect_uri",V),B.searchParams.set("state",z),B.searchParams.set("code_challenge",q),B.searchParams.set("code_challenge_method","S256"),B.searchParams.set("scope",X.ok.scopes.join(" ")),X.ok.accountHint!==void 0)B.searchParams.set("account_hint",X.ok.accountHint);return H({authUrl:B.toString()})}captureSecretFromText($,Z,Q){let X=this.custody();if(!K(X))return X;let Y=new RegExp(Z.pattern).exec(Q);if(Y===null)return I("not_found","non-retryable","captureSecret: pattern matched nothing on the console page");let j=Y[1]??Y[0],W=this.stagingCell(Z.cell);if(!K(W))return W;let V=this.vault.putFlowCell($,W.ok,j);if(!K(V))return V;let q=Q.split(j).join("[REDACTED:token]");return H({stored:!0,redactedPage:q})}stagingCell($){let Z=$??"staged";if(QP.has(Z))return I("invalid_argument","non-retryable",`captureSecret: '${Z}' is a broker-private flow cell and is not a legal staging target`);return H(Z)}captureSecretFromCapture($,Z,Q){let X=this.custody();if(!K(X))return X;let z=this.stagingCell(Z.cell);if(!K(z))return z;let Y=this.vault.getFlow($);if(!K(Y))return I("failed_precondition","non-retryable",`captureSecret: no flow '${$}' \u2014 a custody move that cannot be audited does not happen (auth.md \xA77.2)`);let j=K7(Q,Z);if(!K(j))return j;let W=this.vault.putFlowCell($,z.ok,j.ok.secret);if(!K(W))return W;this.emitter.emit("auth.flow.state",{flowId:$,flowType:Y.ok.flowType,source:Y.ok.source,state:Y.ok.state});let V={redactionMask:j.ok.redactionMask,redactedDomSnapshot:j.ok.redactedDomSnapshot},q=q7(V,this.vault.registry);if(q.length>0)return this.recordTokenLeak(`blind-copy:${$}`,q),I("permission_denied","non-retryable",`blind-copy payload matched token pattern '${q[0].pattern}' \u2014 REFUSED before it could reach the driver's context (I-7, auth.md \xA74.5)`);return H({stored:!0,...V})}captureSecret($,Z){return p0("broker.captureSecret against a live driven-browser DOM (rung B)")}}var J7=900,aK=30000,G7=256,U7=65536,aZ=1048576,L7=5,_3="verifier",QP,T3,rK=80,tK,XP,eK,m5=($)=>new Date($).toISOString(),N3=($)=>Date.parse($),A3=($)=>$.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var D7=E(()=>{f();H7();X0();C3();A8();F3();Z7();QP=new Set([_3]);T3=new Set(["authorization","cookie","proxy-authorization","x-api-key","api-key"]),tK={perform:()=>p0("broker.execute upstream call (real network)")},XP={perform:async()=>p0("broker.executeAsync upstream call (real network)")},eK={exchange:()=>p0("OAuth code\u2192token exchange against a real provider")}});class M7{broker;vault;emitter;matrix;lifecycle;authSpec;browser;nowMs;clientIds;hooks;ulid=V$();authUrls=new Map;batches=new Map;queued=[];contextTranscript=[];constructor($){this.broker=$.broker,this.vault=$.vault,this.emitter=$.emitter,this.matrix=$.matrix,this.lifecycle=$.lifecycle,this.authSpec=$.authSpec,this.browser=$.browser,this.nowMs=$.nowMs,this.clientIds=$.clientIds??(()=>{return}),this.hooks=$.hooks??{}}see($){this.contextTranscript.push($)}enroll($,Z="onboard"){let Q=this.ulid(),X=[];for(let z of $){let Y=this.authSpec(z.source);if(Y===void 0){X.push(this.stillbornFlow(z.source,"unknown-source","structural",Q));continue}let j=this.matrix.assertDriverAllowed(Y.provider);if(!K(j)){X.push(this.stillbornFlow(z.source,Y.provider,"forbidden",Q));continue}if(Y.method!=="oauth-pkce"&&Y.method!=="client-secret"){X.push(this.stillbornFlow(z.source,Y.provider,"structural",Q));continue}let W=z.account!==void 0?[z.account]:Y.multiAccount?this.multiAccountTargets(Y.provider):[void 0];for(let V of W){let q=this.broker.beginFlow(z.source,V,Y.scopes,{provider:Y.provider,batchId:Q,trigger:Z,...this.clientIds(z.source)!==void 0?{clientId:this.clientIds(z.source)}:{}});if(!K(q)){X.push(this.stillbornFlow(z.source,Y.provider,"forbidden",Q));continue}this.authUrls.set(q.ok.flowId,q.ok.authUrl),this.see(`flow ${q.ok.flowId} prepared authUrl=${q.ok.authUrl.split("?")[0]}`),this.queued.push(q.ok.flowId),X.push(q.ok.flowId)}}return this.batches.set(Q,{batchId:Q,trigger:Z,flowIds:X,settled:!1}),this.emitter.emit("auth.batch.started",{batchId:Q,trigger:Z,flowIds:X}),X}multiAccountTargets($){let Z=this.browser.listAccounts($);return Z.length>0?Z:[void 0]}stillbornFlow($,Z,Q,X){let z=this.ulid();return this.vault.putFlow({flowId:z,flowType:"oauth-consent",source:$,provider:Z,scopes:[],state:"QUEUED",stateAt:$q(this.nowMs()),batchId:X,resumeUsed:!1}),this.emitter.emit("auth.flow.started",{flowId:z,flowType:"oauth-consent",source:$,state:"QUEUED"}),x$(this.vault,this.emitter,this.nowMs(),z,"STUCK",{stuckClass:Q}),this.escalate(z,Q),z}repair($){let Z=this.vault.getGrant($);if(!K(Z))return Z;let X=this.enroll([{source:Z.ok.source,account:Z.ok.account.id}],"repair")[0];if(X===void 0)return I("internal","non-retryable","repair enroll produced no flow");return H(X)}restore($){let Z=$q(this.nowMs());for(let Q of $){let X=this.vault.findGrant(Q.source,Q.accountId);if(K(X)){if(X.ok.state!=="AUTH_BLOCKED")this.lifecycle.transition(X.ok.grantId,"AUTH_BLOCKED","restore");continue}this.vault.importRebuiltGrant(Q,Z),this.emitter.emit("auth.grant.state",{grantId:Q.grantId,from:"ACTIVE",to:"AUTH_BLOCKED",reason:"restore"})}return this.enroll($.map((Q)=>({source:Q.source,account:Q.accountId})),"restore")}async resume($,Z){let Q=this.vault.getFlow($);if(!K(Q))return Q;if(!["STUCK","WAIT_HUMAN"].includes(Q.ok.state))return I("failed_precondition","non-retryable",`flow '${$}' is ${Q.ok.state} \u2014 nothing to resume`);if(Q.ok.resumeUsed)return I("permission_denied","non-retryable",`resume token for flow '${$}' already used (single-use, \xA74.5)`);if(x$(this.vault,this.emitter,this.nowMs(),$,"RESUMED",{resumeUsed:!0}),Z!==void 0)this.see(`flow ${$} resumed with human input (length ${Z.length})`);let X=this.broker.rearmFlow($);if(!K(X))return x$(this.vault,this.emitter,this.nowMs(),$,"STUCK",{stuckClass:"structural"}),X;return this.authUrls.set($,X.ok.authUrl),this.driveFlow($,{humanClick:!0})}async runPending(){for(;;){let $=this.queued.shift();if($===void 0)break;await this.driveFlow($,{humanClick:!1})}this.settleBatches()}async driveFlow($,Z){let Q=this.authUrls.get($);if(Q===void 0)return x$(this.vault,this.emitter,this.nowMs(),$,"STUCK",{stuckClass:"crash-recovered"}),this.escalate($,"crash-recovered"),I("failed_precondition","non-retryable",`flow '${$}' has no live authUrl \u2014 crash-recovered, resume to re-arm`);x$(this.vault,this.emitter,this.nowMs(),$,"PREP");let X=this.broker.flowSettled($),z=await this.browser.open(Q,{humanClick:Z.humanClick});if(!K(z))return this.see(`flow ${$} browser open failed`),x$(this.vault,this.emitter,this.nowMs(),$,"STUCK",{stuckClass:"structural"}),this.escalate($,"structural"),I("unavailable","transient",`flow '${$}': browser open failed`);if(z.ok.outcome==="interstitial")return this.see(`flow ${$} consent interstitial \u2014 WAIT_HUMAN`),x$(this.vault,this.emitter,this.nowMs(),$,"WAIT_HUMAN"),this.escalate($,"awaiting-human"),H(void 0);if(this.see(`flow ${$} consent redirected via loopback`),X!==void 0){let Y=await X;if(!K(Y))return this.see(`flow ${$} settled with failure`),I("internal","non-retryable",`flow '${$}' failed broker-side (see flow events)`);this.see(`flow ${$} DONE (grant persisted broker-side)`)}return H(void 0)}escalate($,Z){this.hooks.onNeedsAttention?.($,`zortex://auth/resume/${$}`,Z)}settleBatches(){for(let $ of this.batches.values()){if($.settled)continue;let Z=[],Q=[],X=[],z=0;for(let Y of $.flowIds){let j=this.vault.getFlow(Y);if(!K(j))continue;switch(j.ok.state){case"DONE":Z.push(Y);break;case"STUCK":case"WAIT_HUMAN":Q.push(Y);break;case"ABANDONED":X.push(Y);break;default:z++}}if(z===0)$.settled=!0,this.emitter.emit("auth.batch.settled",{batchId:$.batchId,done:Z,needsAttention:Q,abandoned:X})}}tick(){let $=this.nowMs();for(let Z of this.vault.listFlows({nonTerminal:!0})){let Q=$-zP(Z.stateAt);if(Z.state==="STUCK"){if(Q>=V7)x$(this.vault,this.emitter,$,Z.flowId,"ABANDONED"),this.hooks.onIncident?.("flow-abandoned",Z.flowId);continue}let X=W7[Z.state];if(X===void 0||Q<X)continue;let z=Z.state==="WAIT_HUMAN"?"awaiting-human":"structural";x$(this.vault,this.emitter,$,Z.flowId,"STUCK",{stuckClass:z}),this.escalate(Z.flowId,z)}this.settleBatches()}recoverOnStart(){for(let $ of this.vault.listFlows({nonTerminal:!0})){if($.state==="STUCK"||$.state==="WAIT_HUMAN")continue;let Z=this.broker.rearmFlow($.flowId);if(K(Z)){if(this.authUrls.set($.flowId,Z.ok.authUrl),x$(this.vault,this.emitter,this.nowMs(),$.flowId,"QUEUED"),this.queued.push($.flowId),$.batchId!==void 0&&!this.batches.has($.batchId))this.batches.set($.batchId,{batchId:$.batchId,trigger:"onboard",flowIds:[$.flowId],settled:!1});else if($.batchId!==void 0){let Q=this.batches.get($.batchId);if(!Q.flowIds.includes($.flowId))Q.flowIds.push($.flowId)}}else x$(this.vault,this.emitter,this.nowMs(),$.flowId,"STUCK",{stuckClass:"crash-recovered"}),this.escalate($.flowId,"crash-recovered")}}registrationWalk($){return q3("console-registration")}cookieCapture($){return q3("cookie-capture")}}var $q=($)=>new Date($).toISOString(),zP=($)=>Date.parse($);var P7=E(()=>{f();X0();F3()});var C7=E(()=>{f();X0()});class jP{failing=!1;protos=[];appended=[];u=V$();append($,Z){if(this.failing)return v(T$("unavailable","transient","sink down (drill)"));let Q=[];for(let X of $)this.protos.push(X),this.appended.push({kind:X.kind,payload:X.payload??null}),Q.push({id:this.u(),outcome:"appended"});return H(Q)}}var LE;var Zq=E(()=>{f();D7();P7();X0();oX();C7();lX();C3();M3();sX();LE=Date.parse("2026-07-01T00:00:00.000Z")});var _9=E(()=>{X0();A8();lX();dX();sX();oX();M3();Z7();C3();F3();D7();H7();P7();C7();Zq()});import{closeSync as JP,existsSync as R3,fsyncSync as GP,mkdirSync as UP,openSync as LP,renameSync as DP,unlinkSync as MP,writeSync as PP,readFileSync as CP}from"fs";import{dirname as FP,join as NP}from"path";class O3{dir;constructor($){this.dir=$}path($){return NP(this.dir,$.slice(0,2),$)}put($,Z){let Q=L$($),X=this.path(Q);if(!R3(X)){UP(FP(X),{recursive:!0});let Y=`${X}.tmp.${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,j=LP(Y,"wx");PP(j,$),GP(j),JP(j),DP(Y,X)}let z={sha256:Q,bytes:$.length};if(Z?.mime!==void 0)z.mime=Z.mime;if(Z?.name!==void 0)z.name=Z.name;return z}get($){let Z=this.path($);if(!R3(Z))return v({code:"not_found",layer:"storage",retryability:"non-retryable",message:`blob ${$} missing from ${this.dir} \u2014 repair order, never an empty body`});return H(new Uint8Array(CP(Z)))}has($){return R3(this.path($))}unlink($){let Z=this.path($);if(R3(Z))MP(Z)}}var y7=E(()=>{f()});class x3{crc=4294967295;update($){let Z=typeof $==="string"?_P.encode($):$;for(let Q=0;Q<Z.length;Q++)this.crc=AP[(this.crc^Z[Q])&255]^this.crc>>>8;return this}hex(){return((this.crc^4294967295)>>>0).toString(16).padStart(8,"0")}}function R8($){return new x3().update($).hex()}var AP,_P;var E7=E(()=>{AP=(()=>{let $=new Uint32Array(256);for(let Z=0;Z<256;Z++){let Q=Z;for(let X=0;X<8;X++)Q=Q&1?2197175160^Q>>>1:Q>>>1;$[Z]=Q>>>0}return $})(),_P=new TextEncoder});import{closeSync as Wq,openSync as Vq}from"fs";import{basename as y3,dirname as E3}from"path";import{dlopen as eZ,ptr as jq,read as v3}from"bun:ffi";function b3($){if($.includes("\x00"))throw Error("atomic pathname exchange refuses an embedded NUL");return Buffer.from(`${$}\x00`)}function g3($){if($.includes("\x00"))throw Error("atomic pathname move refuses an embedded NUL");return Buffer.from(`${$}\x00`,"utf16le")}function TP(){if(I3!==null)return I3;let $=eZ("kernel32.dll",{MoveFileExW:{args:["ptr","ptr","u32"],returns:"bool"},GetLastError:{args:[],returns:"u32"}});return I3={moveNoReplace:(Z,Q)=>$.symbols.MoveFileExW(jq(Z),jq(Q),0),lastError:()=>$.symbols.GetLastError()},I3}function SP($,Z){let Q=TP(),X=g3($),z=g3(Z);if(Q.moveNoReplace(X,z))return;let j=Q.lastError(),W=j===80||j===183?17:j;throw new F$(`native atomic no-replace move failed with Windows error ${j}`,!1,W)}function RP(){if(O8!==null)return O8;if(process.platform==="darwin"){let $=eZ("/usr/lib/libSystem.B.dylib",{renameatx_np:{args:["i32","cstring","i32","cstring","u32"],returns:"i32"},__error:{args:[],returns:"ptr"}});return O8=(Z,Q,X)=>{let z=$.symbols.renameatx_np(Z,Q,Z,X,2),Y=z===0?null:$.symbols.__error();return{result:z,errno:Y===null?0:v3.i32(Y)}},O8}if(process.platform==="linux"){let $=eZ("libc.so.6",{renameat2:{args:["i32","cstring","i32","cstring","u32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}});return O8=(Z,Q,X)=>{let z=$.symbols.renameat2(Z,Q,Z,X,2),Y=z===0?null:$.symbols.__errno_location();return{result:z,errno:Y===null?0:v3.i32(Y)}},O8}throw Error(`atomic pathname exchange is unsupported on ${process.platform}`)}function OP(){if(x8!==null)return x8;if(process.platform==="darwin"){let $=eZ("/usr/lib/libSystem.B.dylib",{renameatx_np:{args:["i32","cstring","i32","cstring","u32"],returns:"i32"},__error:{args:[],returns:"ptr"}});return x8=(Z,Q,X)=>{let z=$.symbols.renameatx_np(Z,Q,Z,X,4),Y=z===0?null:$.symbols.__error();return{result:z,errno:Y===null?0:v3.i32(Y)}},x8}if(process.platform==="linux"){let $=eZ("libc.so.6",{renameat2:{args:["i32","cstring","i32","cstring","u32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}});return x8=(Z,Q,X)=>{let z=$.symbols.renameat2(Z,Q,Z,X,1),Y=z===0?null:$.symbols.__errno_location();return{result:z,errno:Y===null?0:v3.i32(Y)}},x8}throw Error(`atomic no-replace pathname move is unsupported on ${process.platform}`)}var $Q,F$,O8=null,x8=null,I3=null,v7=($,Z)=>{let Q=E3($);if(Q!==E3(Z))throw Error("atomic pathname exchange requires two names in the same directory");if(process.platform==="win32")throw g3($),g3(Z),new $Q("atomic pathname exchange is unsupported on win32",!1);let X=b3(y3($)),z=b3(y3(Z)),Y=RP(),j=Vq(Q,"r"),W=!1,V=null;try{let B=Y(j,X,z);if(B.result!==0)throw Error(`native atomic pathname exchange failed with result ${B.result}, errno ${B.errno}`);W=!0}catch(B){V=B}let q=null;try{Wq(j)}catch(B){q=B}if(V!==null||q!==null)throw new $Q(`${V===null?"atomic exchange completed":String(V)}${q===null?"":`; directory descriptor close failed: ${String(q)}`}`,W)},G0=($,Z)=>{let Q=E3($);if(Q!==E3(Z))throw new F$("atomic no-replace pathname move requires two names in the same directory",!1,null);if(process.platform==="win32"){SP($,Z);return}let X=b3(y3($)),z=b3(y3(Z)),Y;try{Y=OP()}catch(G){throw new F$(String(G),!1,null)}let j;try{j=Vq(Q,"r")}catch(G){throw new F$(`atomic no-replace directory open failed: ${String(G)}`,!1,null)}let W=!1,V=null,q=null;try{let G=Y(j,X,z);if(G.result!==0)throw q=G.errno,Error(`native atomic no-replace move failed with result ${G.result}, errno ${G.errno}`);W=!0}catch(G){V=G}let B=null;try{Wq(j)}catch(G){B=G}if(V!==null||B!==null)throw new F$(`${V===null?"atomic no-replace move completed":String(V)}${B===null?"":`; directory descriptor close failed: ${String(B)}`}`,W,B===null?q:null)};var ZQ=E(()=>{$Q=class $Q extends Error{exchanged;constructor($,Z){super($);this.name="AtomicPathExchangeError",this.exchanged=Z}};F$=class F$ extends Error{moved;errno;constructor($,Z,Q){super($);this.name="AtomicPathMoveNoReplaceError",this.moved=Z,this.errno=Q}}});function Kq($){if(typeof $!=="object"||$===null)return!1;let Z=$;return typeof Z.code==="string"&&typeof Z.layer==="string"&&typeof Z.retryability==="string"&&typeof Z.message==="string"}function yP($){if(typeof $!=="object"||$===null)return null;let Z=$;if(Kq(Z.structured))return Z.structured;if(Kq(Z.recoveryFailure))return Z.recoveryFailure;return null}function EP($){let Z=new Set,Q=[{value:$,depth:0}],X=new Set;while(Q.length>0){let z=Q.pop();if(z===void 0||z.depth>8)continue;let Y=z.value;if(typeof Y!=="object"||Y===null||X.has(Y))continue;X.add(Y);let j=Y;if(typeof j.code==="string")Z.add(j.code.toUpperCase());if(j.cause!==void 0)Q.push({value:j.cause,depth:z.depth+1});if(Array.isArray(j.errors))for(let W of j.errors)Q.push({value:W,depth:z.depth+1})}return Z}function qq($,Z,Q){for(let X of $)if(Z.has(X)||Q.some((z)=>X.startsWith(z)))return!0;return!1}function U$($,Z,Q){let X=yP($);if(X!==null)return{...X,message:`${Z}: ${X.message}`};let z=EP($);return{...qq(z,xP,["SQLITE_FULL_","SQLITE_NOMEM_"])?{code:"resource_exhausted",retryability:"throttling"}:qq(z,IP,["SQLITE_BUSY","SQLITE_LOCKED","SQLITE_IOERR","SQLITE_CANTOPEN_","SQLITE_READONLY_","SQLITE_CORRUPT_"])?{code:"unavailable",retryability:"transient"}:Q,layer:"storage",message:`${Z}: ${String($)}`}}var xP,IP;var b7=E(()=>{xP=new Set(["EDQUOT","EFBIG","ENOMEM","ENOSPC","SQLITE_FULL","SQLITE_NOMEM"]),IP=new Set(["EACCES","EAGAIN","EBUSY","EIO","EMFILE","ENOENT","ENFILE","ENOTDIR","EPERM","ESTALE","SQLITE_CANTOPEN","SQLITE_CORRUPT","SQLITE_INTERRUPT","SQLITE_NOTADB","SQLITE_PROTOCOL","SQLITE_READONLY"])});import{CString as Gq,dlopen as vP,ptr as T9,read as f3}from"bun:ffi";function QQ($){if($.includes("\x00"))throw Error("system SQLite input contains an embedded NUL");return Buffer.from(`${$}\x00`,"utf8")}function fP($){return Buffer.concat([Buffer.from($,"utf8"),Buffer.from([0])])}function kP(){if(w3!==null&&Bq!==null)return w3;let $=process.platform==="darwin"?"/usr/lib/libsqlite3.dylib":process.platform==="linux"?"libsqlite3.so.0":process.platform==="win32"?"winsqlite3.dll":null;if($===null)throw Object.assign(Error(`system SQLite FFI is unsupported on ${process.platform}`),{code:"SQLITE_CANTOPEN"});let Z=vP($,{sqlite3_open:{args:["cstring","ptr"],returns:"i32"},sqlite3_close:{args:["ptr"],returns:"i32"},sqlite3_exec:{args:["ptr","cstring","ptr","ptr","ptr"],returns:"i32"},sqlite3_prepare_v2:{args:["ptr","cstring","i32","ptr","ptr"],returns:"i32"},sqlite3_bind_text:{args:["ptr","i32","cstring","i32","i64"],returns:"i32"},sqlite3_bind_int64:{args:["ptr","i32","i64"],returns:"i32"},sqlite3_step:{args:["ptr"],returns:"i32"},sqlite3_reset:{args:["ptr"],returns:"i32"},sqlite3_clear_bindings:{args:["ptr"],returns:"i32"},sqlite3_column_text:{args:["ptr","i32"],returns:"ptr"},sqlite3_column_bytes:{args:["ptr","i32"],returns:"i32"},sqlite3_column_int64:{args:["ptr","i32"],returns:"i64"},sqlite3_finalize:{args:["ptr"],returns:"i32"},sqlite3_errmsg:{args:["ptr"],returns:"ptr"},sqlite3_extended_errcode:{args:["ptr"],returns:"i32"},sqlite3_file_control:{args:["ptr","cstring","i32","ptr"],returns:"i32"}});return Bq=Z,w3=Z.symbols,w3}function Jq($){switch($&255){case 5:return"SQLITE_BUSY";case 6:return"SQLITE_LOCKED";case 7:return"SQLITE_NOMEM";case 8:return"SQLITE_READONLY";case 10:return"SQLITE_IOERR";case 11:return"SQLITE_CORRUPT";case 13:return"SQLITE_FULL";case 14:return"SQLITE_CANTOPEN";case 26:return"SQLITE_NOTADB";default:return`SQLITE_${$}`}}class m3{symbols;handle;closed=!1;constructor($,Z){this.symbols=$;this.handle=Z}static openTemporary(){let $=kP(),Z=new BigUint64Array(1),Q=$.sqlite3_open(QQ(""),T9(Z)),X=f3.ptr(T9(Z));if(X===0)throw Object.assign(Error(`system SQLite temporary open returned no handle (${Q})`),{code:Jq(Q)});let z=new m3($,X);if(Q!==P0){let Y=z.failure("system SQLite temporary open",Q);try{z.close()}catch(j){throw AggregateError([Y,j],Y.message)}throw Y}return z}exec($){this.assertOpen();let Z=this.symbols.sqlite3_exec(this.handle,QQ($),null,null,null);if(Z!==P0)throw this.failure("system SQLite exec",Z)}prepare($){this.assertOpen();let Z=new BigUint64Array(1),Q=QQ($),X=this.symbols.sqlite3_prepare_v2(this.handle,Q,Q.length-1,T9(Z),null),z=f3.ptr(T9(Z));if(X!==P0||z===0)throw this.failure("system SQLite prepare",X);return new Uq(this,this.symbols,z)}queryText($){return this.queryValue($,(Z)=>Z.text(0))}queryInteger($){return this.queryValue($,(Z)=>Z.integer(0))}queryValue($,Z){let Q=this.prepare($),X=null,z=null;try{X=Q.get([],Z)}catch(j){z=j}let Y=null;try{Q.finalize()}catch(j){Y=j}if(z!==null&&Y!==null)throw AggregateError([z,Y],`system SQLite query and finalize failed: ${String(z)} | ${String(Y)}`);if(z!==null)throw z;if(Y!==null)throw Y;return X}hasVfsFile(){this.assertOpen();let $=new BigUint64Array(1);return this.symbols.sqlite3_file_control(this.handle,QQ("main"),bP,T9($))===P0&&f3.ptr(T9($))!==0}mmapSize(){this.assertOpen();let $=new BigInt64Array([-1n]),Z=this.symbols.sqlite3_file_control(this.handle,QQ("main"),gP,T9($));if(Z===12)return null;if(Z!==P0)throw this.failure("system SQLite mmap-size proof",Z);let Q=Number($[0]);if(!Number.isSafeInteger(Q))throw Object.assign(Error("system SQLite mmap-size proof exceeds JavaScript safe range"),{code:"SQLITE_TOOBIG"});return Q}close(){if(this.closed)return;let $=this.symbols.sqlite3_close(this.handle);if($!==P0)throw this.failure("system SQLite close",$);this.closed=!0}failure($,Z){let Q=this.symbols.sqlite3_extended_errcode(this.handle),X=this.symbols.sqlite3_errmsg(this.handle),z=X===0?"unknown SQLite failure":new Gq(X).toString(),Y=Q===P0?Z??Q:Q;return Object.assign(Error(`${$}: ${z} (${Y})`),{code:Jq(Y),errno:Y})}assertOpen(){if(this.closed)throw Object.assign(Error("system SQLite database is closed"),{code:"ESTALE"})}}class Uq{db;symbols;statement;finalized=!1;constructor($,Z,Q){this.db=$;this.symbols=Z;this.statement=Q}run($){this.withBindings($,()=>{let Z=this.symbols.sqlite3_step(this.statement);if(Z!==k3)throw this.db.failure("system SQLite statement run",Z)})}get($,Z){return this.withBindings($,()=>{let Q=this.symbols.sqlite3_step(this.statement);if(Q===k3)return null;if(Q!==Hq)throw this.db.failure("system SQLite statement query",Q);let X=Z(this),z=this.symbols.sqlite3_step(this.statement);if(z!==k3)throw this.db.failure("system SQLite query completion",z);return X})}forEach($,Z){return this.withBindings($,()=>{let Q=0;while(!0){let X=this.symbols.sqlite3_step(this.statement);if(X===k3)return Q;if(X!==Hq)throw this.db.failure("system SQLite statement iteration",X);Z(this),Q++}})}text($){let Z=this.symbols.sqlite3_column_text(this.statement,$);if(Z===0)throw this.db.failure(`system SQLite column ${$} is null`);let Q=this.symbols.sqlite3_column_bytes(this.statement,$);return new Gq(Z,0,Q).toString()}integer($){let Z=this.symbols.sqlite3_column_int64(this.statement,$),Q=Number(Z);if(!Number.isSafeInteger(Q))throw Object.assign(Error(`system SQLite integer column ${$} exceeds JavaScript safe range`),{code:"SQLITE_TOOBIG"});return Q}finalize(){if(this.finalized)return;let $=this.symbols.sqlite3_finalize(this.statement);if(this.finalized=!0,$!==P0)throw this.db.failure("system SQLite statement finalize",$)}withBindings($,Z){if(this.finalized)throw Object.assign(Error("system SQLite statement is finalized"),{code:"ESTALE"});let Q=null,X;try{for(let W=0;W<$.length;W++){let V=$[W],q=typeof V==="string"?(()=>{let B=fP(V);return this.symbols.sqlite3_bind_text(this.statement,W+1,B,B.length-1,-1n)})():this.symbols.sqlite3_bind_int64(this.statement,W+1,BigInt(V));if(q!==P0)throw this.db.failure(`system SQLite bind ${W+1}`,q)}X=Z()}catch(W){Q=W}let z=this.symbols.sqlite3_reset(this.statement),Y=this.symbols.sqlite3_clear_bindings(this.statement),j=z!==P0||Y!==P0?this.db.failure("system SQLite statement reset",z!==P0?z:Y):null;if(Q!==null&&j!==null)throw Object.assign(AggregateError([Q,j],`system SQLite statement operation and reset failed: ${String(Q)} | ${j.message}`),{code:j.code});if(Q!==null)throw Q;if(j!==null)throw j;return X}}var P0=0,Hq=100,k3=101,bP=7,gP=18,w3=null,Bq=null;var Lq=()=>{};import{createHash as wP}from"crypto";function Dq($,Z){return Object.keys($).sort().join(",")===Z}function pP($){if($===null||typeof $!=="object"||Array.isArray($))return null;let Z=$;if(!Dq(Z,"count,maxTs,minTs,nkBase"))return null;let Q=Z.nkBase;if(Q===null||typeof Q!=="object"||Array.isArray(Q))return null;let X=Q;if(!Dq(X,"source,stream"))return null;if(typeof X.source!=="string"||typeof X.stream!=="string"||!Number.isSafeInteger(Z.count)||Z.count<=0||typeof Z.minTs!=="string"||typeof Z.maxTs!=="string")return null;return{source:X.source,stream:X.stream,count:Z.count,minTs:Z.minTs,maxTs:Z.maxTs}}function lP($){let Z="";for(let Q=0;Q<$.length;Q++)Z+=$.charCodeAt(Q).toString(16).padStart(4,"0");return Z}class XQ{db;upsert;match;emit;inTransaction=!1;transactionRecords=0;maxTransactionRecords=0;aggregatorRowsInHeap=0;maxAggregatorRowsInHeap=0;validated=!1;emissionPasses=0;closed=!1;constructor($,Z,Q,X){this.db=$;this.upsert=Z;this.match=Q;this.emit=X}static create(){let $=null,Z=null,Q=null,X=null;try{$=m3.openTemporary();let z=$.queryText("PRAGMA journal_mode");$.exec(`
92
+ PRAGMA journal_mode = MEMORY;
93
+ PRAGMA locking_mode = EXCLUSIVE;
94
+ PRAGMA temp_store = FILE;
95
+ PRAGMA cache_size = -${g7};
96
+ PRAGMA cache_spill = ON;
97
+ PRAGMA mmap_size = 0;
98
+ ${hP}
99
+ `);let Y=$.queryText("PRAGMA journal_mode"),j=$.queryText("PRAGMA locking_mode"),W=$.queryInteger("PRAGMA cache_size"),V=$.queryInteger("PRAGMA temp_store"),q=$.queryInteger("PRAGMA cache_spill"),B=$.mmapSize();if(z!=="delete"||Y!=="memory"||j!=="exclusive"||W!==-g7||V!==1||q===null||q<=0||B!==null&&B!==0||!$.hasVfsFile())throw Object.assign(Error("stream manifest did not retain its disk/pager configuration"),{code:"SQLITE_CANTOPEN"});return Z=$.prepare(uP),Q=$.prepare(`
100
+ UPDATE stream_manifest
101
+ SET matched = 1
102
+ WHERE source = ? AND stream = ? AND matched = 0
103
+ RETURNING count, min_ts, max_ts, first_line
104
+ `),X=$.prepare(`
105
+ SELECT source, stream, count, min_ts, max_ts, first_line, sort_key
106
+ FROM stream_manifest
107
+ ORDER BY sort_key, first_line
108
+ `),new XQ($,Z,Q,X)}catch(z){let Y=[];if(X!==null)try{X.finalize()}catch(j){Y.push(j)}if(Q!==null)try{Q.finalize()}catch(j){Y.push(j)}if(Z!==null)try{Z.finalize()}catch(j){Y.push(j)}if($!==null)try{$.close()}catch(j){Y.push(j)}if(Y.length>0)throw AggregateError([z,...Y],`stream-manifest initialization cleanup failed: ${String(z)}`);throw z}}stage($,Z,Q,X){if(this.assertWritable(),this.emissionPasses>0)throw Object.assign(Error("private stream manifest cannot change after footer emission begins"),{code:"ESTALE"});this.beginTransaction(),this.upsert.run([$,Z,Q,Q,X,lP(`${$} ${Z}`)]),this.noteTransactionRecord()}forEachFooterRow($){this.assertWritable(),this.commitTransaction();let Z=wP("sha256"),Q=null,X=-1,z=this.emit.forEach([],(j)=>{let W={source:j.text(0),stream:j.text(1),count:j.integer(2),minTs:j.text(3),maxTs:j.text(4)},V=j.integer(5),q=j.text(6);if(Q!==null&&(q<Q||q===Q&&V<X))throw Object.assign(Error("system SQLite stream manifest violated its declared footer order"),{code:"SQLITE_CORRUPT"});Q=q,X=V,this.aggregatorRowsInHeap++,this.maxAggregatorRowsInHeap=Math.max(this.maxAggregatorRowsInHeap,this.aggregatorRowsInHeap);try{for(let B of[W.source,W.stream,String(W.count),W.minTs,W.maxTs,String(V)])Z.update(`${Buffer.byteLength(B)}:`),Z.update(B);$(W)}finally{this.aggregatorRowsInHeap--}}),Y=this.distinctStreams();if(z!==Y)throw Object.assign(Error(`system SQLite stream manifest emitted ${z} of ${Y} rows`),{code:"SQLITE_CORRUPT"});return this.emissionPasses++,{distinctStreams:Y,orderDigest:Z.digest("hex")}}matchesFooter($){if(this.assertWritable(),this.commitTransaction(),!Array.isArray($))return!1;let Z=this.distinctStreams();if($.length!==Z)return!1;let Q=null,X=-1;for(let Y of $){let j=pP(Y);if(j===null)return!1;if(this.beginTransaction(),!this.inspectMaterializedRow(()=>this.match.get([j.source,j.stream],(V)=>({count:V.integer(0),min_ts:V.text(1),max_ts:V.text(2),first_line:V.integer(3)})),(V)=>{if(V.count!==j.count||V.min_ts!==j.minTs||V.max_ts!==j.maxTs)return!1;let q=`${j.source} ${j.stream}`;if(Q!==null&&(q<Q||q===Q&&V.first_line<X))return!1;return Q=q,X=V.first_line,!0}))return!1}this.commitTransaction();let z=this.db.queryInteger("SELECT COUNT(*) FROM stream_manifest WHERE matched = 1");return this.validated=z===Z,this.validated}evidence(){if(!this.validated)throw Error("stream-manifest evidence requested before exact footer validation");return this.collectEvidence()}emissionEvidence(){if(this.emissionPasses<2)throw Error("stream-manifest emission evidence requested before two stable footer passes");return this.collectEvidence()}collectEvidence(){let $=this.db.queryInteger("PRAGMA page_count"),Z=this.db.queryInteger("PRAGMA page_size"),Q=this.db.mmapSize();if($===null||Z===null||!this.db.hasVfsFile())throw Object.assign(Error("system SQLite stream manifest lost its VFS backing proof"),{code:"SQLITE_IOERR"});if(Q!==null&&Q!==0)throw Object.assign(Error(`system SQLite stream manifest mmap limit changed to ${Q}`),{code:"SQLITE_IOERR"});let X=this.distinctStreams();return{strategy:"sqlite-system-temp-disk",backing:"vfs-delete-on-close",vfsFilePointer:!0,initialJournalMode:"delete",journalMode:"memory",lockingMode:"exclusive",pagerCacheKiB:g7,cacheSpill:!0,tempStore:"file",mmapBytes:0,mmapProof:Q===null?"unsupported":"zero",distinctStreams:X,maxAggregatorRowsInHeap:this.maxAggregatorRowsInHeap,maxTransactionRecords:this.maxTransactionRecords,catalogBytes:$*Z}}close(){if(this.closed)return;let $=[];if(this.inTransaction){try{this.db.exec("ROLLBACK")}catch(Z){$.push(Z)}this.inTransaction=!1,this.transactionRecords=0}try{this.emit.finalize()}catch(Z){$.push(Z)}try{this.match.finalize()}catch(Z){$.push(Z)}try{this.upsert.finalize()}catch(Z){$.push(Z)}try{this.db.close()}catch(Z){$.push(Z)}if(this.closed=!0,$.length===1)throw $[0];if($.length>1)throw AggregateError($,"private stream-manifest rollback, close, or cleanup failed")}distinctStreams(){let $=this.db.queryInteger("SELECT COUNT(*) FROM stream_manifest");if($===null)throw Error("system SQLite stream manifest count returned no row");return $}assertWritable(){if(this.closed)throw Object.assign(Error("private stream manifest is closed"),{code:"ESTALE"});if(this.validated)throw Error("private stream manifest is already validated")}beginTransaction(){if(this.inTransaction)return;this.db.exec("BEGIN IMMEDIATE"),this.inTransaction=!0,this.transactionRecords=0}inspectMaterializedRow($,Z){let Q=$();if(Q!==null)this.aggregatorRowsInHeap++,this.maxAggregatorRowsInHeap=Math.max(this.maxAggregatorRowsInHeap,this.aggregatorRowsInHeap);try{return this.noteTransactionRecord(),Q!==null&&Z(Q)}finally{if(Q!==null)this.aggregatorRowsInHeap--}}noteTransactionRecord(){if(this.transactionRecords++,this.maxTransactionRecords=Math.max(this.maxTransactionRecords,this.transactionRecords),this.transactionRecords>=mP)this.commitTransaction()}commitTransaction(){if(!this.inTransaction)return;this.db.exec("COMMIT"),this.inTransaction=!1,this.transactionRecords=0}}var mP=2048,g7=256,hP=`
109
+ CREATE TABLE stream_manifest (
110
+ source TEXT NOT NULL,
111
+ stream TEXT NOT NULL,
112
+ count INTEGER NOT NULL CHECK(count > 0),
113
+ min_ts TEXT NOT NULL,
114
+ max_ts TEXT NOT NULL,
115
+ first_line INTEGER NOT NULL,
116
+ sort_key TEXT NOT NULL,
117
+ matched INTEGER NOT NULL DEFAULT 0 CHECK(matched IN (0, 1)),
118
+ PRIMARY KEY (source, stream)
119
+ ) WITHOUT ROWID;
120
+ CREATE UNIQUE INDEX idx_stream_manifest_order
121
+ ON stream_manifest(sort_key, first_line);
122
+ `,uP=`
123
+ INSERT INTO stream_manifest (source, stream, count, min_ts, max_ts, first_line, sort_key)
124
+ VALUES (?, ?, 1, ?, ?, ?, ?)
125
+ ON CONFLICT(source, stream) DO UPDATE SET
126
+ count = stream_manifest.count + 1,
127
+ min_ts = CASE
128
+ WHEN excluded.min_ts < stream_manifest.min_ts THEN excluded.min_ts
129
+ ELSE stream_manifest.min_ts
130
+ END,
131
+ max_ts = CASE
132
+ WHEN excluded.max_ts > stream_manifest.max_ts THEN excluded.max_ts
133
+ ELSE stream_manifest.max_ts
134
+ END
135
+ `;var Mq=E(()=>{Lq()});import{createHash as cP}from"crypto";import{closeSync as u$,fstatSync as I$,ftruncateSync as u3,fsyncSync as x0,lstatSync as Pq,mkdirSync as Sq,openSync as y0,readFileSync as p7,readSync as l7,statSync as S9,writeSync as WQ}from"fs";import{basename as dP,dirname as nP,join as Rq}from"path";function i($,Z,Q=$==="unavailable"?"transient":$==="resource_exhausted"?"throttling":"non-retryable"){return v({code:$,layer:"storage",retryability:Q,message:Z})}function c7($,Z,Q){if(!Q&&$.code==="ENOENT")return i("not_found",`segment unreadable: ${Z}: ${String($)}`);return{err:U$($,`segment unreadable: ${Z}`,{code:"not_found",retryability:"non-retryable"})}}function iP($){let Z=JSON.stringify($),Q=R8(Z);return`${Z.slice(0,-1)},"crc":"${Q}"}`}function sP($,Z){let Q=0,X=!1,z=!1,Y=0;for(let j=0;j<$.length;j++){let W=$[j];if(X){if(z)z=!1;else if(W==="\\")z=!0;else if(W==='"')X=!1;continue}if(W==='"')X=!0;else if(W==="{"||W==="[")Q++;else if(W==="}"||W==="]")Q--;else if(W===","&&Q===1&&++Y===Z)return j}throw Error(`JCS object has no separator after member ${Z}`)}function oP($){if($.crc!==void 0)throw Error("h3 encoder input already contains crc");let Z=C$($),Q=`"crc":"${R8(Z)}"`,X=Object.keys($).filter((W)=>$[W]!==void 0).sort(),z=X.findIndex((W)=>W>"crc"),Y=z<0?X.length:z;if(X.length===0)return`{${Q}}`;if(Y===0)return`{${Q},${Z.slice(1)}`;if(Y===X.length)return`${Z.slice(0,-1)},${Q}}`;let j=sP(Z,Y);return`${Z.slice(0,j+1)}${Q},${Z.slice(j+1)}`}function h5($,Z){return Z===3?oP($):iP($)}function aP($,Z){try{return C$($)===C$(Z)}catch{return!1}}function p3($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let Z=$;return Object.keys(Z).sort().join(",")==="batchId,chainHead,count,firstId,lastId,prevChain"&&q$(Z.batchId)&&Number.isSafeInteger(Z.count)&&Z.count>0&&q$(Z.firstId)&&q$(Z.lastId)&&typeof Z.prevChain==="string"&&/^[0-9a-f]{64}$/.test(Z.prevChain)&&typeof Z.chainHead==="string"&&/^[0-9a-f]{64}$/.test(Z.chainHead)}function tP($){if(typeof $!=="string"||!rP.test($))return!1;let Z=Date.parse($);return Number.isFinite(Z)&&new Date(Z).toISOString().slice(0,19)===$.slice(0,19)}function xq($,Z,Q){let X=Object.keys(Q).sort().join(",");if(X!=="batch,crc,f,prev,rec"&&X!=="crc,f,prev,rec")return i("data_loss",`segment ${$} line ${Z}: frame has missing or unknown fields`);if(Q.f!==1||typeof Q.prev!=="string"||!w7.test(Q.prev)||typeof Q.crc!=="string"||!Oq.test(Q.crc)||Q.batch!==void 0&&!p3(Q.batch))return i("data_loss",`segment ${$} line ${Z}: malformed frame envelope`);let z=g5(Q.rec,`segment ${$} line ${Z}.rec`);if(!K(z)){let Y="err"in z?z.err.message:z.empty.how;return i("data_loss",`segment ${$} line ${Z}: invalid stored event envelope: ${Y}`)}try{if(Z0(z.ok)!==z.ok.contentHash)return i("data_loss",`segment ${$} line ${Z}: event contentHash does not match its envelope`)}catch(Y){return i("data_loss",`segment ${$} line ${Z}: malformed event envelope: ${String(Y)}`)}return H(Q)}function Iq($,Z,Q){let X=Object.keys(Q).sort().join(",");if(X!=="batch,contentHash,crc,id,kind,nk,prev,t,tomb,ts"&&X!=="contentHash,crc,id,kind,nk,prev,t,tomb,ts")return i("data_loss",`segment ${$} line ${Z}: tomb has missing or unknown fields`);let z=TZ(Q.nk,"stored",`segment ${$} line ${Z}.nk`),Y=K(z)?"":`: ${"err"in z?z.err.message:z.empty.how}`;if(!K(z)||Q.t!==1||!q$(Q.id)||!tP(Q.ts)||typeof Q.kind!=="string"||Q.kind.length===0||typeof Q.contentHash!=="string"||!w7.test(Q.contentHash)||!q$(Q.tomb)||typeof Q.prev!=="string"||!w7.test(Q.prev)||typeof Q.crc!=="string"||!Oq.test(Q.crc)||Q.batch!==void 0&&!p3(Q.batch))return i("data_loss",`segment ${$} line ${Z}: malformed closed tomb${Y}`);return H(Q)}function $C($){let Z=eP.exec($);if(Z===null)return null;return{body:`${Z[1]}}`,crc:Z[2]}}function d7($,Z,Q){try{let X=JSON.parse(Q);if(X===null||typeof X!=="object"||Array.isArray(X))return i("data_loss",`segment ${$} ${Z}: record is not a JSON object`);return H(X)}catch{return i("data_loss",`segment ${$} ${Z}: unparseable JSON`)}}function I8($,Z,Q){try{return H(QC.decode(Q))}catch{return i("data_loss",`segment ${$} ${Z}: invalid UTF-8 bytes`)}}function XC($,Z,Q){let X=$C(Q);if(X===null)return i("data_loss",`segment ${$} ${Z}: malformed record (no crc trailer)`);if(R8(X.body)!==X.crc)return i("data_loss",`segment ${$} ${Z}: CRC-32C mismatch \u2014 segment quarantined`);return d7($,Z,Q)}function zC($,Z,Q){let X=d7($,Z,Q);if(!("ok"in X))return X;let z=X.ok;if(typeof z.crc!=="string"||!/^[0-9a-f]{8}$/.test(z.crc))return i("data_loss",`segment ${$} ${Z}: malformed h3 crc`);let Y,j;try{Y=C$(z);let W={...z};delete W.crc,j=C$(W)}catch(W){return i("data_loss",`segment ${$} ${Z}: h3 record is outside RFC 8785 JSON: ${String(W)}`)}if(Y!==Q)return i("data_loss",`segment ${$} ${Z}: h3 record bytes are not RFC 8785 canonical`);if(R8(j)!==z.crc)return i("data_loss",`segment ${$} ${Z}: CRC-32C mismatch \u2014 segment quarantined`);return H(z)}function YQ($,Z,Q,X){return X===3?zC($,Z,Q):XC($,Z,Q)}function n7($,Z,Q){let X=d7($,Z,Q);if(!("ok"in X))return X;let z=X.ok.h;if(z!==1&&z!==2&&z!==3)return i("data_loss",`segment ${$} ${Z}: unsupported segment format version`);return YQ($,Z,Q,z)}function yq($){return`seg-${$}.zev`}function i7($,Z){let Q=yq(Z);if(dP($)!==Q)return i("data_loss",`segment ${$}: header names ${Z}, but canonical basename is ${Q}`);return H(!0)}function s7($,Z){if(Z.h===1&&Z.batchFraming===void 0)return H(!0);if((Z.h===2||Z.h===3)&&Z.batchFraming===1)return H(!0);return i("data_loss",`segment ${$}: ambiguous or unsupported header/framing version`)}function a$($,Z){return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}function Eq($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function k$($){return`${String($.dev)}:${String($.ino)}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}function y8($){return $.split(":",2).join(":")}function f7($,Z){return $.segmentId===Z.segmentId&&$.fileDigest===Z.fileDigest&&y8($.fingerprint)===y8(Z.fingerprint)}function k7($,Z,Q){let X=null,z=null;try{X=y0($,"r+");let Y=I$(X);if(y8(k$(Y))!==Z)z="pathname no longer names the proven inode";else if(Q!==void 0){let j=p7(X),W=I$(X);if(!a$(Y,W)||L$(j)!==Q)z="proven inode changed or its exact byte digest no longer matches"}if(z===null)u3(X,0),x0(X)}catch(Y){z=String(Y)}if(X!==null)try{u$(X)}catch(Y){z=`${z===null?"descriptor scrub completed":z}; close failed: ${String(Y)}`}return z===null?H(!0):i("unavailable",`refused to scrub uncertain surgery path ${$}: ${z}`)}function Cq($,Z,Q,X){let z=0;while(z<Q){let Y=l7($,Z,z,Q-z,X+z);if(Y===0)break;z+=Y}return z}function W5($){let Z=null;try{Z=y0($,"r");let Q=I$(Z),X=(T)=>{let m=I$(Z),k=S9($);return a$(Q,m)&&a$(m,k)?T:i("unavailable",`segment ${$}: file identity changed during bounded summary`)};if(Q.size===0)return X(H({state:"recovery-required",path:$,reason:"uncommitted-header",fingerprint:k$(Q),bytesRead:0,maxBufferedBytes:0}));let z=Math.min(Q.size,ZC),Y=Buffer.allocUnsafe(z);if(Cq(Z,Y,z,0)!==z)return i("unavailable",`segment ${$}: short header-edge read; refusing an unstable identity`);let j=Y.indexOf(10);if(j<0)return X(H({state:"recovery-required",path:$,reason:z===Q.size?"uncommitted-header":"edge-line-exceeds-bound",fingerprint:k$(Q),bytesRead:z,maxBufferedBytes:z}));let W=I8($,"line 0",Y.subarray(0,j));if(!("ok"in W)){if(z===Q.size&&j===Q.size-1)return X(H({state:"recovery-required",path:$,reason:"uncommitted-header",fingerprint:k$(Q),bytesRead:z,maxBufferedBytes:z}));return X(W)}let V=W.ok,q=n7($,"line 0",V);if(!("ok"in q)){if(z===Q.size&&j===Q.size-1)return X(H({state:"recovery-required",path:$,reason:"uncommitted-header",fingerprint:k$(Q),bytesRead:z,maxBufferedBytes:z}));return X(q)}let B=q.ok;if(B.h!==1&&B.h!==2&&B.h!==3||typeof B.segment!=="string"||!Number.isInteger(B.rewriteGen))return X(i("data_loss",`segment ${$}: line 0 is not a segment header`));let G=s7($,B);if(!("ok"in G))return X(G);let J=i7($,B.segment);if(!("ok"in J))return X(J);if(Cq(Z,Y,z,Q.size-z)!==z)return i("unavailable",`segment ${$}: short footer-edge read; refusing an unstable identity`);let U=Y.lastIndexOf(10);if(U<0)return X(H({state:"recovery-required",path:$,reason:"edge-line-exceeds-bound",fingerprint:k$(Q),bytesRead:z*2,maxBufferedBytes:z}));let L=U!==Y.length-1,D=Y.lastIndexOf(10,U-1);if(D<0){if(!L&&z<Q.size){let T=p5($);if(K(T)){if(T.ok.frames===0)return X(H({state:"recovery-required",path:$,reason:"empty-canonical",fingerprint:k$(Q),bytesRead:z*2+T.ok.bytesRead,maxBufferedBytes:Math.max(z,T.ok.maxBufferedBytes)}));if(T.ok.fingerprint!==k$(Q))return i("unavailable",`segment ${$}: descriptor generation changed between edge summary and streaming verification`);return X(H({state:"sealed",path:$,segmentId:T.ok.segment,rewriteGen:T.ok.rewriteGen,count:T.ok.frames,maxId:T.ok.maxId,fingerprint:T.ok.fingerprint,bytesRead:z*2+T.ok.bytesRead,maxBufferedBytes:Math.max(z,T.ok.maxBufferedBytes)}))}if(!("err"in T))return i("internal",`segment ${$}: streaming verifier returned no classification`);if(T.err.code!=="data_loss")return T}return X(H({state:"recovery-required",path:$,reason:z===Q.size?"active-or-torn":"edge-line-exceeds-bound",fingerprint:k$(Q),bytesRead:z*2,maxBufferedBytes:z}))}let P=I8($,"footer",Y.subarray(D+1,U));if(!("ok"in P))return X(P);let F=P.ok,A=!1;if(!L)try{A=JSON.parse(F).foot===1}catch{A=!1}if(L||!A)return X(H({state:"recovery-required",path:$,reason:"active-or-torn",fingerprint:k$(Q),bytesRead:z*2,maxBufferedBytes:z}));let N=YQ($,"footer",F,B.h);if(!("ok"in N))return X(N);let S=N.ok;if(S.foot!==1||!Number.isInteger(S.count)||S.count<0||typeof S.maxId!=="string"||!Number.isInteger(S.rewriteGen)||S.rewriteGen!==B.rewriteGen)return X(i("data_loss",`segment ${$}: final line is not a valid segment footer`));if(S.count===0)return X(H({state:"recovery-required",path:$,reason:"empty-canonical",fingerprint:k$(Q),bytesRead:z*2,maxBufferedBytes:z}));let R=I$(Z),O=S9($);if(!a$(Q,R)||!a$(R,O))return i("unavailable",`segment ${$}: file identity changed during bounded summary`);return H({state:"sealed",path:$,segmentId:B.segment,rewriteGen:B.rewriteGen,count:S.count,maxId:S.maxId,fingerprint:k$(R),bytesRead:z*2,maxBufferedBytes:z})}catch(Q){return c7(Q,$,Z!==null)}finally{if(Z!==null)u$(Z)}}function u5($){return L$(`zev1:${$}`)}function I0($,Z,Q){return L$(`${$}:${Z}:${Q}`)}function h3($,Z){let Q,X,z=null;try{z=y0($,"r");let y=I$(z);Q=p7(z);let b=I$(z),g=S9($);if(!a$(y,b)||!a$(b,g))return i("unavailable",`segment ${$}: file identity changed during strict read`);X=k$(b)}catch(y){return c7(y,$,z!==null)}finally{if(z!==null)u$(z)}let Y=Q.length>0&&Q[Q.length-1]===10,j=0,W;if(Y){let y=I8($,"file",Q);if(!("ok"in y))return y;W=y.ok}else{let y=Q.lastIndexOf(10),b=y<0?Buffer.alloc(0):Q.subarray(0,y+1),g=Q.subarray(y+1),w=I8($,"complete record prefix",b);if(!("ok"in w))return w;let u=I8($,"unterminated tail",g);if("ok"in u)W=`${w.ok}${u.ok}`;else W=w.ok,j=g.length}let V=W.split(`
136
+ `);if(V.length>0&&V[V.length-1]==="")V.pop();if(V.length===0)return i("data_loss",`segment ${$}: no header line`);let q=n7($,"line 0",V[0]);if(!("ok"in q))return q;let B=q.ok.h,G=j===0?null:`[invalid UTF-8 tail: ${j} bytes]`,J=!1;if(!Y&&j===0&&V.length>0){let y=V[V.length-1];if("ok"in YQ($,`line ${V.length-1}`,y,B))J=!0;else G=V.pop()}let U=[],L=0;for(let y of V)U.push(L),L+=Buffer.byteLength(y)+1;let D=[q.ok];for(let y=1;y<V.length;y++){let b=V[y],g=YQ($,`line ${y}`,b,B);if(!("ok"in g))return g;D.push(g.ok)}let P=D[0];if(!P||P.h!==1&&P.h!==2&&P.h!==3||typeof P.segment!=="string")return i("data_loss",`segment ${$}: line 0 is not a segment header`);if(Z){let y=i7($,P.segment);if(!("ok"in y))return y}let F=s7($,P);if(!("ok"in F))return F;let A=P.h===2||P.h===3,N=[],S=[],R=-1,O=-1,T=null,m=u5(P.segment),k=null,d=(y,b,g,w,u)=>{if(S.length===0){if(!p3(w))return"first frame has no valid embedded batch commit";if(w.batchId!==b||w.firstId!==b||w.prevChain!==m)return"embedded batch commit does not bind its first frame or incoming chain";R=u,O=U[u],T=w}else if(w!==void 0)return"non-first frame carries a second embedded batch commit";S.push(y),m=I0(m,b,g);let p=T;if(S.length>p.count)return"frame run exceeds its declared batch count";if(S.length===p.count){if(p.lastId!==b||p.chainHead!==m)return"embedded batch commit does not bind the final frame or outgoing chain";N.push(...S),S=[],R=-1,O=-1,T=null}return null};for(let y=1;y<D.length;y++){let b=D[y];if(b.f===1){let g=xq($,y,b);if(!K(g))return g;let w=g.ok;if(A&&w.prev!==m)return i("data_loss",`segment ${$} line ${y}: identity hash chain mismatch`);let u={kind:"frame",line:y,raw:V[y],frame:w};if(A){let p=d(u,w.rec.id,w.rec.contentHash,w.batch,y);if(p!==null)return i("data_loss",`segment ${$} line ${y}: ${p}`)}else N.push(u),m=I0(m,w.rec.id,w.rec.contentHash)}else if(b.t===1){let g=Iq($,y,b);if(!K(g))return g;let w=g.ok;if(A&&w.prev!==m)return i("data_loss",`segment ${$} line ${y}: identity hash chain mismatch`);let u={kind:"tomb",line:y,raw:V[y],tomb:w};if(A){let p=d(u,w.id,w.contentHash,w.batch,y);if(p!==null)return i("data_loss",`segment ${$} line ${y}: ${p}`)}else N.push(u),m=I0(m,w.id,w.contentHash)}else if(b.foot===1){if(y!==D.length-1)return i("data_loss",`segment ${$} line ${y}: footer before end of file`);if(S.length>0)return i("data_loss",`segment ${$}: sealed footer follows an uncommitted frame batch`);k=b}else return i("data_loss",`segment ${$} line ${y}: unknown record shape`)}if(k!==null){let y=D.length-1,b=V.slice(0,y),g=b.reduce((p,o)=>p+Buffer.byteLength(o)+1,0),w=b.reduce((p,o)=>p+o.length+1,0);if(!(P.h===3?k.bytes===g:k.bytes===g||k.bytes===w))return i("data_loss",`segment ${$}: footer bytes does not match the encoded frame prefix`);if(!aP(k.streams,bq(N)))return i("data_loss",`segment ${$}: footer stream accounting does not match parsed frames`)}return H({path:$,segmentId:P.segment,header:P,entries:N,footer:k,tornTail:G,missingFinalNewline:J,uncommittedBatch:S.length===0?null:{fromLine:R,byteOffset:O,count:S.length},fingerprint:X,fileDigest:L$(Q)})}function d0($){return h3($,!0)}function E8($){let Z=u5($.segmentId),Q=!0,X=0,z=0;for(let Y of $.entries){if(Y.kind==="frame")try{if(Z0(Y.frame.rec)!==Y.frame.rec.contentHash)Q=!1}catch{Q=!1}let j=Y.kind==="frame"?Y.frame.prev:Y.tomb.prev,W=Y.kind==="frame"?Y.frame.rec.id:Y.tomb.id,V=Y.kind==="frame"?Y.frame.rec.contentHash:Y.tomb.contentHash;if(j!==Z)Q=!1;if(Z=I0(Z,W,V),Y.kind==="frame")X++;else z++}if($.footer&&$.footer.chainHead!==Z)Q=!1;return{segment:$.segmentId,frames:$.entries.length,crcFailures:[],chainIntact:Q,accounting:{readable:X,tombstoned:z,lost:$.tornTail===null?0:1}}}function Fq($){if($.footer===null)return"sealed segment has no footer";if($.tornTail!==null)return"sealed segment retains a torn tail";if($.missingFinalNewline)return"sealed segment lacks its final LF";if($.uncommittedBatch!==null)return"sealed segment retains an uncommitted batch";if(!E8($).chainIntact)return"identity hash chain is not intact";let Q=$.entries.map((Y)=>Y.kind==="frame"?Y.frame.rec.id:Y.tomb.id),X=Q.length===0?"":Q.reduce((Y,j)=>Y<j?Y:j),z=Q.length===0?"":Q.reduce((Y,j)=>Y>j?Y:j);if($.footer.count!==$.entries.length)return"footer count does not match records";if($.footer.minId!==X||$.footer.maxId!==z)return"footer id range does not match records";if($.footer.rewriteGen!==$.header.rewriteGen)return"footer rewrite generation does not match header";return null}function p5($,Z,Q){let X=null,z=null,Y=(j)=>{let W=[],V=z;if(z=null,V!==null)try{V.close()}catch(J){W.push(J)}let q=X;if(X=null,q!==null)try{u$(q)}catch(J){W.push(J)}if(W.length===0)return j;let B="err"in j?j.err.message:"stream verification otherwise succeeded",G=AggregateError(W,`stream verification cleanup failed after ${B}: ${W.map(String).join(" | ")}`);return{err:U$(G,`segment unreadable: ${$}`,{code:"unavailable",retryability:"transient"})}};try{X=y0($,"r");let j=I$(X);if(j.size===0)return Y(i("data_loss",`segment ${$}: no header line`));z=XQ.create();let W=z,V=Buffer.allocUnsafe(vq),q=0,B=[],G=0,J=V.length,U=0,L=null,D=0,P="",F=0,A=0,N="",S="",R=!1,O=!1,T=null,m=0,k=null,d=0,y=0,b=(p,o,Z$)=>{if(!O)return P=I0(P,p,o),H(!0);if(m===0){if(!p3(Z$))return i("data_loss",`segment ${$}: first frame has no valid embedded batch commit`);if(Z$.batchId!==p||Z$.firstId!==p||Z$.prevChain!==P)return i("data_loss",`segment ${$}: embedded batch commit does not bind its first frame or incoming chain`);k=Z$}else if(Z$!==void 0)return i("data_loss",`segment ${$}: non-first frame carries a second embedded batch commit`);P=I0(P,p,o),m++;let H$=k;if(m>H$.count)return i("data_loss",`segment ${$}: frame run exceeds its declared batch count`);if(m===H$.count){if(H$.lastId!==p||H$.chainHead!==P)return i("data_loss",`segment ${$}: embedded batch commit does not bind the final frame or outgoing chain`);m=0,k=null}return H(!0)},g=(p,o)=>{J=Math.max(J,p.length+V.length);let Z$=I8($,`line ${U}`,p);if(!("ok"in Z$))return Z$;let H$=Z$.ok,A$=U===0?n7($,`line ${U}`,H$):YQ($,`line ${U}`,H$,T);if(!("ok"in A$))return A$;let e=A$.ok;if(U===0){if(e.h!==1&&e.h!==2&&e.h!==3||typeof e.segment!=="string"||!Number.isInteger(e.rewriteGen))return i("data_loss",`segment ${$}: line 0 is not a segment header`);let a=i7($,e.segment);if(!("ok"in a))return a;L=e.segment,D=e.rewriteGen;let Q$=s7($,e);if(!("ok"in Q$))return Q$;T=e.h,O=e.h===2||e.h===3,P=u5(L)}else if(e.f===1){if(R)return i("data_loss",`segment ${$} line ${U}: frame follows footer`);let a=xq($,U,e);if(!K(a))return a;let Q$=a.ok;if(Q$.prev!==P)return i("data_loss",`segment ${$} line ${U}: identity hash chain mismatch`);let n$=b(Q$.rec.id,Q$.rec.contentHash,Q$.batch);if(!("ok"in n$))return n$;W.stage(Q$.rec.nk.source,Q$.rec.nk.stream,Q$.rec.ts,U),F++,N=N===""||Q$.rec.id<N?Q$.rec.id:N,S=Q$.rec.id>S?Q$.rec.id:S,Q?.(Q$.rec,U)}else if(e.t===1){if(R)return i("data_loss",`segment ${$} line ${U}: tomb follows footer`);let a=Iq($,U,e);if(!K(a))return a;let Q$=a.ok;if(Q$.prev!==P)return i("data_loss",`segment ${$} line ${U}: identity hash chain mismatch`);let n$=b(Q$.id,Q$.contentHash,Q$.batch);if(!("ok"in n$))return n$;W.stage(Q$.nk.source,Q$.nk.stream,Q$.ts,U),A++,Z?.(Q$,U),N=N===""||Q$.id<N?Q$.id:N,S=Q$.id>S?Q$.id:S}else if(e.foot===1){if(R)return i("data_loss",`segment ${$} line ${U}: duplicate footer`);if(m>0)return i("data_loss",`segment ${$}: sealed footer follows an uncommitted frame batch`);let a=e,Q$=F+A;if(a.count!==Q$||a.minId!==N||a.maxId!==S||a.rewriteGen!==D||a.chainHead!==P||(T===3?a.bytes!==d:a.bytes!==d&&a.bytes!==y)||!W.matchesFooter(a.streams))return i("data_loss",`segment ${$}: footer accounting does not match streamed frames`);R=!0}else return i("data_loss",`segment ${$} line ${U}: unknown record shape`);if(!o)return i("data_loss",`segment ${$}: complete final record lacks LF terminator; recovery required before verify`);return d+=p.length+1,y+=H$.length+1,U++,H(!0)};while(q<j.size){let p=l7(X,V,0,Math.min(V.length,j.size-q),q);if(p===0)return Y(i("unavailable",`segment ${$}: short streaming read`));q+=p;let o=0;for(let Z$=0;Z$<p;Z$++){if(V[Z$]!==10)continue;let H$=Buffer.from(V.subarray(o,Z$)),A$=B.length===0?H$:Buffer.concat([...B,H$],G+H$.length);B=[],G=0;let e=g(A$,!0);if(!("ok"in e))return Y(e);o=Z$+1}if(o<p){let Z$=Buffer.from(V.subarray(o,p));B.push(Z$),G+=Z$.length,J=Math.max(J,G+V.length)}}if(G>0){let p=g(Buffer.concat(B,G),!1);if(!("ok"in p))return Y(p)}if(L===null)return Y(i("data_loss",`segment ${$}: no header line`));if(m>0)return Y(i("data_loss",`segment ${$}: active segment ends with an uncommitted frame batch`));if(!R)return Y(i("data_loss",`segment ${$}: active segment has no footer; recovery required before verify`));let w=I$(X),u=S9($);if(!a$(j,w)||!a$(w,u))return Y(i("unavailable",`segment ${$}: file identity changed during streaming verification`));return Y(H({segment:L,frames:F+A,crcFailures:[],chainIntact:!0,accounting:{readable:F,tombstoned:A,lost:0},fingerprint:k$(w),rewriteGen:D,maxId:S,bytesRead:q,maxBufferedBytes:J,streamManifest:W.evidence()}))}catch(j){return Y(c7(j,$,X!==null))}}function bq($){let Z=new Map;for(let Q of $){let X=Q.kind==="frame"?Q.frame.rec.nk:Q.tomb.nk,z=Q.kind==="frame"?Q.frame.rec.ts:Q.tomb.ts;m7(Z,X.source,X.stream,z)}return h7(Z)}function m7($,Z,Q,X){let z=`${Z}\x00${Q}`,Y=$.get(z);if(Y===void 0)$.set(z,{source:Z,stream:Q,count:1,minTs:X,maxTs:X});else{if(Y.count++,X<Y.minTs)Y.minTs=X;if(X>Y.maxTs)Y.maxTs=X}}function h7($){return[...$.values()].sort((Z,Q)=>Z.source+" "+Z.stream<Q.source+" "+Q.stream?-1:1).map((Z)=>({nkBase:{source:Z.source,stream:Z.stream},count:Z.count,minTs:Z.minTs,maxTs:Z.maxTs}))}function u7($,Z,Q,X,z,Y,j,W,V){return h5({foot:1,count:$,minId:Z,maxId:Q,chainHead:z,rewriteGen:Y,lineage:j,streams:X,bytes:W},V)}function gq($,Z,Q,X,z,Y){let j=$.map((W)=>W.kind==="frame"?W.frame.rec.id:W.tomb.id);return u7($.length,j.length>0?j.reduce((W,V)=>W<V?W:V):"",j.length>0?j.reduce((W,V)=>W>V?W:V):"",bq($),Z,Q,X,z,Y)}function o7($,Z=WQ){let Q=[];if(!E8($).chainIntact)return i("data_loss",`segment ${$.path}: identity hash chain mismatch during open recovery`);let z=null;try{z=y0($.path,"r+");let W=I$(z),V=S9($.path);if(k$(W)!==$.fingerprint||!a$(W,V))return i("unavailable",`segment ${$.path}: pathname identity changed before open recovery`);let q=(J)=>{let U=I$(z).size,L=Z(z,J,0,J.length,U);if(L!==J.length)throw Error(`short append (${L}/${J.length})`)};if($.uncommittedBatch!==null)u3(z,$.uncommittedBatch.byteOffset),Q.push("uncommitted-batch-truncated");else if($.missingFinalNewline)q(Buffer.from(`
137
+ `)),Q.push("final-newline-restored");else if($.tornTail!==null){let U=p7(z).lastIndexOf(10);if(U<0)return i("data_loss",`segment ${$.path}: torn tail has no valid newline boundary`);u3(z,U+1),Q.push("torn-tail-truncated")}if($.footer===null){let J=u5($.segmentId);for(let L of $.entries){let D=L.kind==="frame"?L.frame.rec.id:L.tomb.id,P=L.kind==="frame"?L.frame.rec.contentHash:L.tomb.contentHash;J=I0(J,D,P)}let U=gq($.entries,J,$.header.rewriteGen,[],I$(z).size,$.header.h);q(Buffer.from(`${U}
138
+ `)),Q.push("active-sealed")}x0(z);let B=I$(z),G=S9($.path);if(!Eq(B,G))return i("unavailable",`segment ${$.path}: pathname was replaced during open recovery`)}catch(W){return{err:U$(W,`segment ${$.path}: open recovery failed`,{code:"unavailable",retryability:"transient"})}}finally{if(z!==null)u$(z)}let Y=d0($.path);if(!("ok"in Y))return Y;if(!E8(Y.ok).chainIntact||Y.ok.footer===null||Y.ok.tornTail!==null||Y.ok.missingFinalNewline)return i("data_loss",`segment ${$.path}: recovered segment did not pass sealed full verification`);return H({parsed:Y.ok,actions:Q})}function jQ($,Z,Q=WQ){let X=0;while(X<Z.length){let z=Z.length-X,Y=Q($,Z,X,z);if(Y<=0||Y>z)throw Error(`invalid append progress ${Y} (${X}/${Z.length})`);X+=Y}}function zQ($,Z){let Q=null,X=[];try{Q=y0(nP($),"r"),Z(Q)}catch(z){X.push(String(z))}finally{if(Q!==null)try{u$(Q)}catch(z){X.push(`close: ${String(z)}`)}}if(X.length>0)return i("unavailable",`segment ${$}: parent-directory durability failed after atomic rename: ${X.join(" | ")}`,"transient");return H(!0)}function Nq($,Z,Q){let X=I$($);if(Q!==void 0&&!a$(Q,X))return i("unavailable",`uncommitted segment ${Z}: source identity changed before exact-byte proof`);let z=cP("sha256"),Y=Buffer.allocUnsafe(vq),j=0;while(j<X.size){let V=l7($,Y,0,Math.min(Y.length,X.size-j),j);if(V===0)return i("unavailable",`uncommitted segment ${Z}: short descriptor read during exact-byte proof`);z.update(Y.subarray(0,V)),j+=V}let W=I$($);if(!a$(X,W))return i("unavailable",`uncommitted segment ${Z}: source identity changed during exact-byte proof`);return H({identity:W,digest:z.digest("hex")})}function VQ($,Z,Q=()=>{},X){let z=null,Y;try{z=y0($,"r");let j=I$(z),W=Pq($);if(!(X===void 0||(typeof X==="string"?k$(j)===X:a$(X,j))))Y=i("unavailable",`uncommitted segment ${$}: opened source does not match the caller's descriptor proof`);else if(!a$(j,W))Y=i("unavailable",`uncommitted segment ${$}: pathname identity changed before preservation`);else{let q=Nq(z,$,j);if(!K(q))Y=q;else{let B=`${$}.${Z}.${process.pid}.${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,G=null,J=null;for(let U=0;U<64;U++){let L=U===0?B:`${B}.${U}`;Q(L);try{G0($,L),G=L;break}catch(D){if(D instanceof F$&&!D.moved&&D.errno===17)continue;if(D instanceof F$&&D.moved){G=L,J=D;break}throw D}}if(G===null)Y=i("unavailable",`uncommitted segment ${$}: exhausted bounded audit-name collision retries`);else{let U=zQ(G,x0);if(!K(U))Y=U;else{let L=Nq(z,G),D=Pq(G);if(!(K(L)&&Eq(q.ok.identity,L.ok.identity)&&q.ok.identity.size===L.ok.identity.size&&q.ok.identity.mtimeMs===L.ok.identity.mtimeMs&&q.ok.digest===L.ok.digest&&a$(L.ok.identity,D))){let F=[];try{G0(G,$);let N=zQ($,x0);if(!K(N))F.push("err"in N?N.err.message:N.empty.how)}catch(N){F.push(String(N))}let A=!K(L)?`; proof failed: ${"err"in L?L.err.message:L.empty.how}`:"";Y=i("unavailable",`uncommitted segment ${$}: moved pathname did not retain the opened source inode and exact bytes; raced bytes preserved${A}${F.length===0?"":`; restoration failed: ${F.join(" | ")}`}`)}else if(J!==null)Y={err:U$(J,`uncommitted segment ${$} was preserved at ${G}, but the atomic move did not complete cleanly`,{code:"unavailable",retryability:"transient"})};else Y=H({auditPath:G})}}}}}catch(j){Y={err:U$(j,`failed to preserve uncommitted segment ${$}`,{code:"unavailable",retryability:"transient"})}}if(z!==null)try{u$(z)}catch(j){let W=`uncommitted segment ${$}: source descriptor close failed: ${String(j)}`;if("err"in Y)Y={err:{...Y.err,message:`${Y.err.message}; ${W}`}};else Y=i("unavailable",W)}return Y}class l3{canonVersion;now;writeChunk;dir;segmentId=null;filePath=null;lineCount=0;fd=null;chain="";bytes=0;entryCount=0;minId="";maxId="";streamStats=new Map;sealed=!1;poisoned=!1;createdAtMs=null;rotation;constructor($,Z,Q,X=WQ,z={maxBytes:YC,maxAgeMs:jC}){this.canonVersion=Z;this.now=Q;this.writeChunk=X;if(this.dir=$,!Number.isSafeInteger(z.maxBytes)||z.maxBytes<=0)throw Error("SegmentWriter: rotation maxBytes must be a positive safe integer");if(!Number.isSafeInteger(z.maxAgeMs)||z.maxAgeMs<=0)throw Error("SegmentWriter: rotation maxAgeMs must be a positive safe integer");this.rotation=z}get acceptsAppends(){return!this.sealed&&!this.poisoned}previewBatch($,Z=this.lineCount){let Q=this.chain,X=Array($.length);for(let B=0;B<$.length;B++){let G=$[B];X[B]=Q,Q=I0(Q,G.id,G.contentHash)}let z=$[0],Y=$[$.length-1],j={batchId:z.id,count:$.length,firstId:z.id,lastId:Y.id,prevChain:this.chain,chainHead:Q},W="",V=[];for(let B=0;B<$.length;B++){let G=$[B],J={f:1,rec:G,prev:X[B],...B===0?{batch:j}:{}},U=h5(J,3);W+=`${U}
139
+ `,V.push({id:G.id,line:Z+B})}let q=Buffer.from(W);return{encoded:q,bytes:q.length,nextChain:Q,locs:V}}candidateSealedBytes($,Z){let Q=new Map;for(let[W,V]of this.streamStats)Q.set(W,{...V});let X=this.minId,z=this.maxId;for(let W of $){if(X===""||W.id<X)X=W.id;if(z===""||W.id>z)z=W.id;m7(Q,W.nk.source,W.nk.stream,W.ts)}let Y=this.bytes+Z.bytes,j=u7(this.entryCount+$.length,X,z,h7(Q),Z.nextChain,0,[],Y,3);return Y+Buffer.byteLength(j)+1}shouldRotateBefore($,Z){if(this.fd===null||this.entryCount===0)return!1;let Q=Date.parse(this.now());if(!Number.isFinite(Q)||this.createdAtMs===null)throw Error("SegmentWriter: rotation clock returned an invalid instant");if(Q-this.createdAtMs>=this.rotation.maxAgeMs)return!0;let X=this.bytes+Z.bytes;if(X>this.rotation.maxBytes)return!0;if(X*2+WC<=this.rotation.maxBytes)return!1;return this.candidateSealedBytes($,Z)>this.rotation.maxBytes}resetAfterRotation(){this.segmentId=null,this.filePath=null,this.lineCount=0,this.fd=null,this.chain="",this.bytes=0,this.entryCount=0,this.minId="",this.maxId="",this.streamStats.clear(),this.createdAtMs=null}sealCurrent(){if(this.fd===null||this.segmentId===null||this.filePath===null)throw Error("SegmentWriter: no active segment to seal");if(this.poisoned)throw u$(this.fd),this.fd=null,Error("SegmentWriter: poisoned session left ACTIVE for writer-open recovery");let $=this.segmentId,Z=this.filePath,Q=this.entryCount,X=u7(Q,this.minId,this.maxId,h7(this.streamStats),this.chain,0,[],this.bytes,3),z=this.fd,Y="";try{jQ(z,Buffer.from(`${X}
140
+ `),this.writeChunk),x0(z),Y=k$(I$(z)),u$(z),this.fd=null}catch(W){this.poisoned=!0;try{u$(z)}finally{this.fd=null}throw W}let j=p5(Z);if(!("ok"in j)){this.poisoned=!0;let W="err"in j?j.err.message:j.empty.how;throw Error(`SegmentWriter: sealed segment failed full verification: ${W}`)}if(j.ok.segment!==$||j.ok.frames!==Q||j.ok.fingerprint!==Y)throw this.poisoned=!0,Error(`SegmentWriter: sealed descriptor generation diverged from canonical verification for ${$}`);return{segment:$,path:Z,count:Q,fingerprint:j.ok.fingerprint}}appendFrames($,Z){if(this.sealed)throw Error("SegmentWriter: appending to a sealed segment (never reopen committed segments)");if(this.poisoned)throw Error("SegmentWriter: prior incomplete write poisoned this session; close and reopen for recovery");if($.length===0){if(this.segmentId===null)throw Error("SegmentWriter: empty first batch cannot name a segment");return{segment:this.segmentId,locs:[],rotated:null}}let Q=this.fd===null?null:this.previewBatch($),X=null;if(Q!==null&&this.shouldRotateBefore($,Q))X=this.sealCurrent(),this.resetAfterRotation(),Q=null;let z=null,Y=this.lineCount,j=0,W=this.fd===null;try{if(W){let J=$[0];this.segmentId=J.id,this.filePath=Rq(this.dir,`seg-${J.id}.zev`),Sq(this.dir,{recursive:!0}),this.fd=y0(this.filePath,"ax"),this.chain=u5(J.id);let U=this.now(),L=Date.parse(U);if(!Number.isFinite(L))throw Error("SegmentWriter: segment clock returned an invalid instant");let D={h:3,segment:J.id,canon:this.canonVersion,rewriteGen:0,createdTs:U,batchFraming:1},P=h5(D,3);z=Buffer.from(`${P}
141
+ `),j=z.length,Y=1,this.createdAtMs=L}let V=Q??this.previewBatch($,Y),q=V.locs,B=V.nextChain;Y+=$.length;let G=z===null?V.encoded:Buffer.concat([z,V.encoded]);if(jQ(this.fd,G,this.writeChunk),Z)x0(this.fd);this.bytes+=G.length,this.lineCount=Y;for(let J of $){if(this.entryCount++,this.minId===""||J.id<this.minId)this.minId=J.id;if(this.maxId===""||J.id>this.maxId)this.maxId=J.id;m7(this.streamStats,J.nk.source,J.nk.stream,J.ts)}return this.chain=B,{segment:this.segmentId,locs:q,rotated:X}}catch(V){if(this.poisoned=!0,W&&this.fd!==null){let q=this.filePath,B=!1,G=null,J=[];try{G=I$(this.fd),B=j===0||G.size<j}catch(U){J.push(`fstat: ${String(U)}`),B=!0}if(B){let U=G===null?i("unavailable",`cannot preserve ${q} without its writer descriptor proof`):VQ(q,"uncommitted-header",()=>{},G);try{u$(this.fd)}catch(F){J.push(`close: ${String(F)}`)}this.fd=null,this.sealed=!0;let L=null;if(K(U))L=U.ok.auditPath,this.filePath=L,this.segmentId=null;else J.push(`preserve: ${"err"in U?U.err.message:U.empty.how}`);let D=V instanceof Error?V.message:String(V),P=L!==null?`incomplete header preserved at ${L}`:`incomplete header remains at canonical path ${q}`;throw Error(`${D}; ${P}${J.length>0?`; cleanup failures: ${J.join(" | ")}`:""}`)}}throw V}}seal(){if(this.fd===null||this.sealed)return null;try{return this.sealCurrent()}finally{this.sealed=!0}}closeWithoutSeal(){if(this.fd===null)return;u$(this.fd),this.fd=null,this.sealed=!0}}function Aq($){return $.kind==="frame"?$.event.id:$.tomb.id}function _q($){return C$({count:$.count,maxTs:$.maxTs,minTs:$.minTs,nkBase:{source:$.source,stream:$.stream}})}function Tq($,Z,Q,X,z,Y){let j=(W)=>C$(W);return`{"bytes":${j($)},"chainHead":${j(Z)},"count":${j(Q)}`+(Y===void 0?"":`,"crc":${j(Y)}`)+`,"foot":1,"lineage":[],"maxId":${j(z)},"minId":${j(X)},"rewriteGen":0,"streams":[`}function fq($,Z,Q,X,z=WQ){let Y=Z[Symbol.iterator](),j=Y.next();if(j.done===!0)return i("invalid_argument","DB-ahead recovery requires at least one survivor");let W=Aq(j.value),V=Rq($,yq(W));Sq($,{recursive:!0});let q=null,B=null,G=null,J=null,U=!1,L=u5(W),D=0,P="",F="",A=0,N=(O)=>{let T=`${O}
142
+ `;jQ(q,Buffer.from(T),z),A+=Buffer.byteLength(T)},S=(O)=>{let T=Buffer.from(O);jQ(q,T,z),A+=T.length},R=(O)=>{let T=Aq(O),m=O.kind==="frame"?O.event.contentHash:O.tomb.contentHash,k=I0(L,T,m),d={batchId:T,count:1,firstId:T,lastId:T,prevChain:L,chainHead:k};if(O.kind==="frame"){let y={f:1,rec:O.event,prev:L,batch:d};N(h5(y,3)),B.stage(O.event.nk.source,O.event.nk.stream,O.event.ts,D+1)}else{let y={t:1,...O.tomb,prev:L,batch:d};N(h5(y,3)),B.stage(O.tomb.nk.source,O.tomb.nk.stream,O.tomb.ts,D+1)}L=k,D++,P=P===""||T<P?T:P,F=F===""||T>F?T:F};try{q=y0(V,"wx"),U=!0,B=XQ.create();let O={h:3,segment:W,canon:Q,rewriteGen:0,createdTs:X(),batchFraming:1};N(h5(O,3)),R(j.value);for(let u=Y.next();u.done!==!0;u=Y.next())R(u.value);let T=A,m=Tq(T,L,D,P,F),k=new x3().update(m),d=!0,y=B.forEachFooterRow((u)=>{if(!d)k.update(",");k.update(_q(u)),d=!1});k.update("]}");let b=k.hex();S(Tq(T,L,D,P,F,b)),d=!0;let g=B.forEachFooterRow((u)=>{if(!d)S(",");S(_q(u)),d=!1});if(S(`]}
143
+ `),g.distinctStreams!==y.distinctStreams||g.orderDigest!==y.orderDigest)throw Object.assign(Error("stream manifest changed between CRC and footer emission passes"),{code:"SQLITE_CORRUPT"});x0(q),J=I$(q),G=B.emissionEvidence(),B.close(),B=null,u$(q),q=null;let w=y0($,"r");try{x0(w)}finally{u$(w)}}catch(O){let T=[];if(B!==null){try{B.close()}catch(k){T.push(`manifest close: ${String(k)}`)}B=null}if(U)try{let k=J;if(q!==null)try{k=I$(q)}catch(y){if(J===null)throw y}if(k===null)throw Error("no survivor segment descriptor proof remains");let d=VQ(V,A===0?"uncommitted-header":"uncommitted-segment",()=>{},k);if(!K(d))T.push(`preserve: ${"err"in d?d.err.message:d.empty.how}`)}catch(k){T.push(`preserve proof: ${String(k)}`)}if(q!==null){try{u$(q)}catch(k){T.push(`close: ${String(k)}`)}q=null}let m=U$(O,`failed to serialize DB-ahead survivors into ${V}`,{code:"unavailable",retryability:"transient"});return{err:{...m,message:`${m.message}${T.length>0?`; cleanup failures: ${T.join(" | ")}`:""}`}}}if(G===null)return i("unavailable",`DB-ahead survivor segment ${V} has no manifest evidence`);return H({segment:W,path:V,count:D,streamManifest:G})}function a7($,Z,Q=WQ,X=x0,z=()=>{},Y=()=>{}){let j=d0($);if(!("ok"in j))return j;let W=j.ok,V=W.fileDigest,q=W.header.rewriteGen+1,B=W.header.h===3?3:1,G=[],J=[],U=!1,L="",D={h:B,segment:W.header.segment,canon:W.header.canon,rewriteGen:q,createdTs:W.header.createdTs,...B===3?{batchFraming:1}:{}},P=h5(D,B);L+=`${P}
144
+ `;for(let g of W.entries)if(g.kind==="frame"&&Z.has(g.frame.rec.id)){let w=g.frame.rec,u={t:1,id:w.id,nk:w.nk,ts:w.ts,kind:w.kind,contentHash:w.contentHash,tomb:Z.get(w.id),prev:g.frame.prev,...B===3&&g.frame.batch!==void 0?{batch:g.frame.batch}:{}},p=h5(u,B);L+=`${p}
145
+ `,J.push({kind:"tomb",line:g.line,raw:p,tomb:{...u,crc:""}}),G.push(w.id),U=!0}else if(g.kind==="tomb"&&Z.has(g.tomb.id)){let w=Z.get(g.tomb.id);if(g.tomb.tomb!==w)return i("data_loss",`segment ${$}: existing tomb ${g.tomb.id} cites ${g.tomb.tomb}, expected ${w}`);L+=`${g.raw}
146
+ `,J.push(g),G.push(g.tomb.id)}else L+=`${g.raw}
147
+ `,J.push(g);let F=[...Z.keys()].sort(),A=[...new Set(G)].sort();if(F.length!==A.length||F.some((g,w)=>g!==A[w]))return i("data_loss",`segment ${$}: surgery target mismatch (requested ${F.length}, applied ${A.length})`);if(!U){try{if(k$(S9($))!==W.fingerprint)return i("unavailable",`segment ${$}: canonical predecessor changed during idempotent surgery`)}catch(w){return i("unavailable",`segment ${$}: cannot revalidate canonical predecessor: ${String(w)}`)}let g=zQ($,X);if(!("ok"in g))return g;return H({segment:W.segmentId,rewriteGen:W.header.rewriteGen,applied:G})}let N=u5(W.segmentId);for(let g of J){let w=g.kind==="frame"?g.frame.rec.id:g.tomb.id,u=g.kind==="frame"?g.frame.rec.contentHash:g.tomb.contentHash;N=I0(N,w,u)}let S=L;if(W.footer!==null){let g=[...W.footer.lineage,V];S+=`${gq(J,N,q,g,Buffer.byteLength(L),B)}
148
+ `}let R=`${$}.surgery-receipt.${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,O=null,T="unowned",m=null,k=!1;try{O=y0(R,"wx"),T="rewrite",m=y8(k$(I$(O))),k=!0,jQ(O,Buffer.from(S),Q),x0(O),u$(O),O=null;let g=h3(R,!1);if(!("ok"in g)){let Z$="err"in g?g.err.message:g.empty.how;throw Error(`staged rewrite verification failed: ${Z$}`)}let w=Fq(g.ok);if(w!==null||g.ok.segmentId!==W.segmentId||g.ok.header.h!==B||g.ok.header.rewriteGen!==q)throw Error(`staged rewrite verification failed: ${w??"segment identity or generation mismatch"}`);z();try{v7(R,$),T="unknown",k=!0}catch(Z$){if(Z$ instanceof $Q&&Z$.exchanged)T="unknown",k=!0;throw Z$}let u=h3(R,!1),p=d0($);if(!("ok"in u)||!f7(W,u.ok)||!("ok"in p)||!f7(g.ok,p.ok)){let Z$=!1;try{v7(R,$),k=!0;let H$=h3(R,!1);if(Z$="ok"in H$&&f7(g.ok,H$.ok),Z$)T="rewrite"}catch(H$){throw Error(`canonical predecessor changed at atomic exchange and exchange-back failed: ${String(H$)}`)}if(!Z$)throw Error("canonical predecessor changed at atomic exchange; uncertain displaced path preserved");throw Error("canonical predecessor changed at atomic exchange; concurrent replacement restored")}T="predecessor",Y(R);let o=k7(R,y8(W.fingerprint),W.fileDigest);if(!("ok"in o)){T="unknown";let Z$="err"in o?o.err.message:o.empty.how;throw Error(Z$)}T="receipt"}catch(g){let w=[];if(O!==null){try{u3(O,0),x0(O),T="receipt"}catch(u){w.push(`scrub-open-temp: ${String(u)}`)}try{u$(O)}catch(u){w.push(`close-temp: ${String(u)}`)}O=null}if(O===null&&T==="rewrite"&&m!==null){let u=k7(R,m);if("ok"in u)T="receipt";else w.push(`scrub-rewrite: ${"err"in u?u.err.message:u.empty.how}`)}else if(T==="predecessor"){let u=k7(R,y8(W.fingerprint),W.fileDigest);if("ok"in u)T="receipt";else w.push(`scrub-predecessor: ${"err"in u?u.err.message:u.empty.how}`)}else if(T==="unknown")w.push("scrub-temp: uncertain displaced path preserved");else if(T==="unowned")w.push("scrub-temp: pre-existing unowned path preserved");if(k){let u=zQ($,X);if(!("ok"in u))w.push(`directory-sync: ${"err"in u?u.err.message:u.empty.how}`)}return i("unavailable",`segment ${$}: surgery atomic install failed: ${String(g)}${w.length>0?`; cleanup failures: ${w.join(" | ")}`:""}`)}let d=zQ($,X),y=d0($);if(!("ok"in y))return y;let b=Fq(y.ok);if(b!==null)return i("data_loss",`segment ${$}: verification failed after surgery: ${b}`);if(!("ok"in d))return d;return H({segment:W.segmentId,rewriteGen:q,applied:G})}var w7,Oq,rP,eP,ZC=262144,QC,vq=262144,YC=67108864,jC=604800000,WC=4096;var r7=E(()=>{f();E7();ZQ();b7();Mq();w7=/^[0-9a-f]{64}$/,Oq=/^[0-9a-f]{8}$/,rP=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|\+00:00)$/;eP=/^(.*),"crc":"([0-9a-f]{8})"\}$/s;QC=new TextDecoder("utf-8",{fatal:!0})});function Y0($,Z){return`${$}\x00${Z}`}function e7($){let Z=new Map;for(let Q of kq)Z.set(Y0(Q.source,Q.stream),Q);for(let Q of $)Z.set(Y0(Q.source,Q.stream),Q);return Z}function c3($){return Object.prototype.hasOwnProperty.call(t7,$)?t7[$]:void 0}var kq,t7;var $z=E(()=>{f();kq=[{source:"zortex",stream:"identity",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"trace",revOrder:"upstream-version",quality:"durable"},{source:"zortex",stream:"ingest",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"erasure",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"security",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"schema",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"user",stream:"file",revOrder:"head-compare",quality:"synthetic"}];t7={"identity.assert":{allowedOrigins:["derivation"],validatePayload:($)=>IV($)},"identity.retract":{allowedOrigins:["derivation","user"],validatePayload:($)=>yV($)},"identity.distinct":{allowedOrigins:["derivation","user"],validatePayload:($)=>EV($)},"identity.rebind":{allowedOrigins:["kernel","derivation"],validatePayload:($)=>P9($)},"identity.cluster.changed":{allowedOrigins:["derivation"],validatePayload:($)=>vV($)},"trace.span":{allowedOrigins:["kernel","derivation","projector","user"],validatePayload:($)=>z3($)},"worker.exited":{allowedOrigins:["kernel"],verdictClass:!0,validatePayload:($)=>gZ($)},"gauntlet.verdict":{allowedOrigins:["kernel"],verdictClass:!0,validatePayload:($)=>LX($)},"sync.run.transition":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.run.transition",$)},"sync.run.aborted":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.run.aborted",$)},"sync.incident.filed":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.incident.filed",$)},"sync.incident.resolved":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.incident.resolved",$)},"sync.repair.filed":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.repair.filed",$)},"sync.repair.completed":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.repair.completed",$)},"sync.census.observed":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.census.observed",$)},"sync.coverage.reconciled":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.coverage.reconciled",$)},"sync.coverage.omission.observed":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.coverage.omission.observed",$)},"sync.cursor.advanced":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.cursor.advanced",$)},"sync.cursor.expired":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.cursor.expired",$)},"sync.security.token-carryover":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>w$("sync.security.token-carryover",$)},"sync.identity.rebound":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>RZ($)},"sync.certificate.issued":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>JK($)},"incident.filed":{allowedOrigins:["kernel"],fm15OnForgery:!0},"ingest.anomaly":{allowedOrigins:["kernel"],internalOnly:!0},"ingest.unknown-kind":{allowedOrigins:["kernel"],internalOnly:!0},"erasure.requested":{allowedOrigins:["user"],internalOnly:!0,securityOnForgery:!0},"erasure.tombstone":{allowedOrigins:["kernel"],internalOnly:!0,securityOnForgery:!0},"erasure.suppressed":{allowedOrigins:["kernel"],internalOnly:!0,securityOnForgery:!0},"security.incident":{allowedOrigins:["kernel"],internalOnly:!0},"projection.conflict":{allowedOrigins:["projector"]},"schema.registered":{allowedOrigins:["kernel"]},"file.created":{allowedOrigins:["user"]},"file.changed":{allowedOrigins:["user"]},"file.deleted":{allowedOrigins:["user"]},"external.action.detected":{allowedOrigins:["derivation"]},"learning.episode":{allowedOrigins:["derivation"],fm15OnForgery:!0,validatePayload:($)=>QK($)},"credit.assigned":{allowedOrigins:["derivation"],fm15OnForgery:!0},"rec.consequence":{allowedOrigins:["derivation","kernel"],fm15OnForgery:!0,validatePayload:($)=>cV($)},"skill.mutation.proposed":{allowedOrigins:["derivation"],fm15OnForgery:!0},"skill.rebase":{allowedOrigins:["derivation"],fm15OnForgery:!0},"skill.lifecycle":{allowedOrigins:["kernel"],fm15OnForgery:!0},"transfer.stage":{allowedOrigins:["kernel"],fm15OnForgery:!0},"transfer.candidate":{allowedOrigins:["kernel"],fm15OnForgery:!0},"fleet.validation":{allowedOrigins:["kernel"],fm15OnForgery:!0},"t2.aggregate":{allowedOrigins:["kernel"],fm15OnForgery:!0,validatePayload:($)=>ZK($)},"feedback.explicit":{allowedOrigins:["user"],fm15OnForgery:!0}}});function y$($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function j0($){if($.byteLength<52)throw Error(`Windows file identity buffer is too short: ${$.byteLength}`);let Z=new DataView($.buffer,$.byteOffset,$.byteLength);return{dev:BigInt(Z.getUint32(28,!0)),ino:BigInt(Z.getUint32(44,!0))<<32n|BigInt(Z.getUint32(48,!0))}}import{fstatSync as VC,fsyncSync as KC,lstatSync as qC}from"fs";import{dlopen as HC,ptr as wq}from"bun:ffi";function CC(){if(d3!==null)return d3;let $=HC("kernel32.dll",{CreateFileW:{args:["ptr","u32","u32","ptr","u32","u32","ptr"],returns:"i64"},FlushFileBuffers:{args:["i64"],returns:"bool"},GetFileInformationByHandle:{args:["i64","ptr"],returns:"bool"},CloseHandle:{args:["i64"],returns:"bool"},GetLastError:{args:[],returns:"u32"}});return d3={openDirectory:(Z)=>$.symbols.CreateFileW(wq(Z),BC,JC,null,GC,UC|LC,null),flush:(Z)=>$.symbols.FlushFileBuffers(Z),fileInformation:(Z,Q)=>$.symbols.GetFileInformationByHandle(Z,wq(Q)),close:(Z)=>$.symbols.CloseHandle(Z),lastError:()=>$.symbols.GetLastError()},d3}function FC($){if($.includes("\x00"))throw Error("directory durability path contains an embedded NUL");return Buffer.from(`${$}\x00`,"utf16le")}function NC($,Z){let Q=CC(),X=Q.openDirectory(FC(Z));if(X===PC)throw Error(`Windows directory durability open failed for ${Z} with error ${Q.lastError()}`);let z=null;try{let j=Buffer.alloc(52);if(!Q.fileInformation(X,j))z=Error(`Windows directory durability identity query failed for ${Z} with error ${Q.lastError()}`);else{let W=j.readUInt32LE(0),V=VC($,{bigint:!0}),q=qC(Z,{bigint:!0}),B=j0(j),G={dev:V.dev,ino:V.ino},J={dev:q.dev,ino:q.ino};if((W&DC)===0||(W&MC)!==0||!V.isDirectory()||!q.isDirectory()||!y$(B,G)||!y$(B,J))z=Error(`Windows directory durability identity changed before flush for ${Z}`)}if(z===null&&!Q.flush(X))z=Error(`Windows directory durability flush failed for ${Z} with error ${Q.lastError()}`)}catch(j){z=j}let Y=null;try{if(!Q.close(X))Y=Error(`Windows directory durability handle close failed for ${Z} with error ${Q.lastError()}`)}catch(j){Y=j}if(z!==null&&Y!==null)throw AggregateError([z,Y],"Windows directory durability flush and close failed");if(z!==null)throw z;if(Y!==null)throw Y}function n3($,Z){if(process.platform==="win32"){if(Z===void 0)throw Error("Windows directory durability requires the exact directory path");NC($,Z);return}KC($)}var BC=1073741824,JC=7,GC=3,UC=33554432,LC=2097152,DC=16,MC=1024,PC,d3=null;var Zz=E(()=>{PC=-1n});import{closeSync as r3,constants as Qz,fstatSync as R9,fsyncSync as lq,ftruncateSync as cq,lstatSync as s3,openSync as dq,writeSync as AC}from"fs";import{basename as t3,dirname as Yz,join as nq}from"path";import{dlopen as _C,ptr as Xz}from"bun:ffi";function e3(){if(i3!==null)return i3;let $=_C("kernel32.dll",{CreateFileW:{args:["ptr","u32","u32","ptr","u32","u32","ptr"],returns:"i64"},GetFileInformationByHandle:{args:["i64","ptr"],returns:"bool"},CloseHandle:{args:["i64"],returns:"bool"},GetLastError:{args:[],returns:"u32"}});return i3={open:(Z)=>$.symbols.CreateFileW(Xz(Z),SC,mq,null,hq,IC|uq,null),openDeleteProbe:(Z)=>$.symbols.CreateFileW(Xz(Z),RC,mq,null,hq,uq,null),information:(Z,Q)=>$.symbols.GetFileInformationByHandle(Z,Xz(Q)),close:(Z)=>$.symbols.CloseHandle(Z),lastError:()=>$.symbols.GetLastError()},i3}function aq($){if($.includes("\x00"))throw Error("owned path contains an embedded NUL");return Buffer.from(`${$}\x00`,"utf16le")}function rq($){if($.nativeHandle===null)throw Error(`${$.path}: native descriptor is closed`);let Z=Buffer.alloc(52),Q=e3();if(!Q.information($.nativeHandle,Z))throw Error(`${$.path}: native identity query failed with Windows error ${Q.lastError()}`);return Z}function $1($){let Z=$.readUInt32LE(0);return(Z&OC)===0&&(Z&xC)===0}function EC($){return $.fd!==null||$.nativeHandle!==null}function p$($,Z){let Q={code:"unavailable",layer:"storage",retryability:"transient",message:$};return Object.assign(Error($,Z===void 0?void 0:{cause:Z}),{code:"ESTALE",structured:Q})}function KQ($){if(!EC($))return null;let Z=$.fd;$.fd=null;let Q=[];if($.nativeHandle!==null){let X=$.nativeHandle;$.nativeHandle=null;let z=e3();if(!z.close(X))Q.push(`native descriptor close failed with Windows error ${z.lastError()}`)}if(Z===null)return Q.length===0?null:`${$.path}: ${Q.join("; ")}`;try{r3(Z)}catch(X){Q.push(`descriptor close failed: ${String(X)}`)}return Q.length===0?null:`${$.path}: ${Q.join("; ")}`}function r$($,Z=$.path){try{if(process.platform==="win32"){let X=s3(Z,{bigint:!0});return X.isFile()&&y$(X,$)}if(typeof $.dev==="bigint"||typeof $.ino==="bigint"){let X=s3(Z,{bigint:!0});return X.isFile()&&y$(X,$)}let Q=s3(Z);return Q.isFile()&&y$(Q,$)}catch(Q){if(Q.code==="ENOENT")return!1;throw Q}}function tq($){try{return s3($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}function o3($){if(process.platform==="win32"){if($.nativeHandle===null)return!1;let Q=rq($);return $1(Q)&&y$(j0(Q),$)}if($.fd===null)return!1;if(typeof $.dev==="bigint"||typeof $.ino==="bigint"){let Q=R9($.fd,{bigint:!0});return Q.isFile()&&y$(Q,$)}let Z=R9($.fd);return Z.isFile()&&y$(Z,$)}function l5($){let Z=Yz($),Q=dq(Z,"r"),X=null;try{n3(Q,Z)}catch(Y){X=Y}let z=null;try{r3(Q)}catch(Y){z=Y}if(X!==null||z!==null)throw p$(`directory durability failed for ${Z}: ${String(X??z)}`,X??z)}function qQ($,Z,Q){if(!o3($)||!r$($,Z))throw p$(`${Q}: exact reserved descriptor/path identity was lost`)}function eq($,Z){let Q=e3(),X=Q.openDeleteProbe(aq($));if(X===oq)return{opened:!1,windowsError:Q.lastError()};let z=Buffer.alloc(52),Y,j=!1;try{if(!Q.information(X,z))throw Error(`identity query failed with Windows error ${Q.lastError()}`)}catch(q){j=!0,Y=q}let W,V=!1;if(!Q.close(X))V=!0,W=Error(`close failed with Windows error ${Q.lastError()}`);if(j||V){let q=[...j?[Y]:[],...V?[W]:[]];throw p$(`${Z}: DELETE-access probe cleanup failed`,q.length===1?q[0]:AggregateError(q,`${Z}: DELETE-access probe and close failed`))}return{opened:!0,information:z}}function $H($,Z,Q=$.path){if(process.platform!=="win32")return;qQ($,Q,Z);let X=eq(Q,Z);if(!X.opened)throw p$(`${Z}: reservation blocked the DELETE-access probe with Windows error ${X.windowsError}`);if(!$1(X.information)||!y$(j0(X.information),$))throw p$(`${Z}: DELETE-access probe opened a different or non-regular path`);qQ($,Q,Z)}function ZH($,Z,Q=$.path){if(process.platform!=="win32")return;qQ($,Q,Z);let X=eq(Q,Z);if(X.opened){let z=$1(X.information)&&y$(j0(X.information),$);throw qQ($,Q,Z),p$(`${Z}: DELETE-access probe succeeded${z?" against the exact SQLite pathname":" against a different pathname identity"}; SQLite pathname exclusion is unavailable`)}if(X.windowsError!==pq)throw p$(`${Z}: DELETE-access probe failed with Windows error ${X.windowsError}, not sharing violation ${pq}`);qQ($,Q,Z)}function QH($,Z,Q){let X=null,z=!0;try{let Y=R9(Z,{bigint:!0});if(!Y.isFile())throw p$(`${Q}: ${$} is not a regular file`);if(process.platform==="win32"){if(X=O9($,Q),X===null)throw p$(`${Q}: ${$} disappeared during descriptor adoption`);if(!y$(Y,X))throw p$(`${Q}: ${$} changed identity during descriptor adoption`);return X.fd=Z,z=!1,X}if(X={path:$,fd:Z,nativeHandle:null,dev:Y.dev,ino:Y.ino},z=!1,!r$(X))throw p$(`${Q}: ${$} changed identity during descriptor adoption`);return X}catch(Y){let j=[];if(X!==null)j.push(...t$(X));if(z)try{r3(Z)}catch(W){j.push(`${$}: descriptor close failed: ${String(W)}`)}if(j.length===0)throw Y;throw AggregateError([Y,...j.map((W)=>Error(W))],`${Q}: descriptor adoption and cleanup failed`)}}function O9($,Z){if(process.platform==="win32"){let X=e3(),z=X.open(aq($));if(z===oq){let W=X.lastError();if(W===2||W===3)return null;throw p$(`${Z}: native no-follow open failed for ${$} with Windows error ${W}`)}let Y={path:$,fd:null,nativeHandle:z,dev:0n,ino:0n},j=null;try{let W=rq(Y),V=j0(W);if(j={...Y,...V},Y.nativeHandle=null,!$1(W)||!r$(j))throw p$(`${Z}: ${$} is not one stable no-follow regular inode`);return j}catch(W){let V=KQ(j??Y);throw p$(`${Z}: could not bind ${$}${V===null?"":`; ${V}`}`,W)}}let Q=null;try{let X=Qz.O_RDWR|Qz.O_NONBLOCK|Qz.O_NOFOLLOW;try{Q=dq($,X)}catch(j){if(j.code==="ENOENT")return null;throw j}let z=R9(Q),Y={path:$,fd:Q,nativeHandle:null,dev:z.dev,ino:z.ino};if(!z.isFile()||!r$(Y))throw p$(`${Z}: ${$} is not one stable regular inode`);return Q=null,Y}catch(X){let z=null;if(Q!==null)try{r3(Q)}catch(Y){z=Y}throw p$(`${Z}: could not bind ${$}${z===null?"":`; close failed: ${String(z)}`}`,X)}}function vC($,Z){let Q=Math.random().toString(36).slice(2,10)||"0";return nq(Yz($),`.owned-isolation.${process.pid}.${Date.now().toString(36)}.${Q}${Z.toString(36)}.${t3($)}.receipt`)}function bC($,Z){let Q=Math.random().toString(36).slice(2,10)||"0";return nq(Yz($),`.owned-replacement.${process.pid}.${Date.now().toString(36)}.${Q}${Z.toString(36)}.${t3($)}.audit`)}function a3($,Z){for(let Q=0;Q<iq;Q++){let X=bC($,Q),z=null;try{G0($,X)}catch(W){if(W instanceof F$&&W.moved)z=String(W);else if(W instanceof F$&&W.errno===sq)continue;else return{err:`${Z}: unexpected path ${$} could not be retained outside the canonical namespace: ${String(W)}`}}let Y=null;try{l5(X)}catch(W){Y=String(W)}let j=[z,Y].filter((W)=>W!==null).join("; ")||null;return{ok:{retainedPath:X,warning:j}}}return{err:`${Z}: exhausted non-reclaim audit names for unexpected path ${$}`}}function zz($,Z,Q){let X=[];try{G0($,Z)}catch(z){X.push(`${Q}: replacement restore retained at ${$}: ${String(z)}`)}try{l5(Z)}catch(z){X.push(`${Q}: replacement restore directory sync failed: ${String(z)}`)}return X}function HQ($,Z,Q,X={},z={}){if(Z!==null){if(Z.fd===null)return{err:`${Q}: ownership descriptor for ${$} is closed`};try{if(!o3(Z))return{err:`${Q}: ownership descriptor for ${$} changed identity`}}catch(Y){return{err:`${Q}: ownership descriptor proof failed for ${$}: ${String(Y)}`}}}for(let Y=0;Y<iq;Y++){let j=vC($,Y),W=null;try{X.beforeIsolationMove?.(Q,$,j),G0($,j)}catch(V){if(V instanceof F$&&V.moved)W=String(V);else if(V instanceof F$&&V.errno===sq)continue;else if(V instanceof F$&&V.errno===TC){if(Z===null)return{ok:{kind:"absent"}};try{let q=Z.fd===null?null:R9(Z.fd);if(q!==null&&q.nlink===0)return{ok:{kind:"absent"}}}catch(q){return{err:`${Q}: vanished path descriptor proof failed: ${String(q)}`}}return{err:`${Q}: ${$} vanished or moved while its owned inode remains linked`}}else return{err:`${Q}: atomic isolation of ${$} failed: ${String(V)}`}}try{X.afterIsolationMove?.(Q,$,j)}catch(V){let q=zz(j,$,Q);return{err:`${Q}: post-isolation hook failed: ${String(V)}${q.length===0?"":`; ${q.join("; ")}`}`}}if(Z===null||!r$(Z,j)){if(z.retainRepopulatedSourceOutsideCanonical&&yC.test(t3($))){let q=a3(j,Q);return{err:`${Q}: ${$} changed identity before atomic isolation; replacement ${"err"in q?`could not leave reclaim grammar (${q.err})`:`was retained outside the canonical namespace at ${q.ok.retainedPath}${q.ok.warning===null?"":`; retention durability warning: ${q.ok.warning}`}`}`}}let V=zz(j,$,Q);return{err:`${Q}: ${$} changed identity before atomic isolation; replacement ${V.length===0?"was restored byte-identically":`was retained (${V.join("; ")})`}`}}try{if(!o3(Z)){let q=zz(j,$,Q);return{err:`${Q}: isolated ${$} no longer matches its retained descriptor${q.length===0?"":`; ${q.join("; ")}`}`}}if(tq($)){if(z.retainRepopulatedSourceOutsideCanonical){let q=a3($,Q);if("err"in q)return{err:`${Q}: source ${$} was repopulated after isolation; exact owned bytes retained at ${j}; ${q.err}`};return{err:`${Q}: source ${$} was repopulated after isolation; replacement retained outside the canonical namespace at ${q.ok.retainedPath}; exact owned bytes retained at ${j}${q.ok.warning===null?"":`; retention durability warning: ${q.ok.warning}`}`}}return{err:`${Q}: source ${$} was repopulated after isolation; replacement preserved at source and exact owned bytes retained at ${j}`}}let V=R9(Z.fd).size;if(l5($),W!==null)return{err:`${Q}: isolation completed but its directory descriptor failed: ${W}; retained at ${j}`};return{ok:{kind:"isolated",isolated:{context:Q,sourcePath:$,isolationPath:j,owned:Z,originalBytes:V}}}}catch(V){return{err:`${Q}: isolated descriptor proof failed; retained at ${j}: ${String(V)}`}}}return{err:`${Q}: exhausted exclusive isolation receipt names for ${$}`}}function jz($,Z={}){let Q=[];if(!r$($.owned,$.isolationPath))return Q.push(`${$.context}: rollback receipt ${$.isolationPath} changed identity`),Q;let X=null;try{Z.beforeRestoreMove?.($.context,$.sourcePath,$.isolationPath),G0($.isolationPath,$.sourcePath)}catch(z){if(z instanceof F$&&z.moved)X=String(z);else return Q.push(`${$.context}: rollback retained at ${$.isolationPath}: ${String(z)}`),Q}try{if(!r$($.owned,$.sourcePath)){let z=a3($.sourcePath,`${$.context} rollback`);if("err"in z)Q.push(`${$.context}: restored source ${$.sourcePath} does not name the expected inode; ${z.err}`);else Q.push(`${$.context}: restored source did not name the expected inode; unexpected bytes retained outside the canonical namespace at ${z.ok.retainedPath}${z.ok.warning===null?"":`; retention durability warning: ${z.ok.warning}`}`);return Q}if(l5($.sourcePath),X!==null)Q.push(`${$.context}: rollback moved but directory descriptor close failed: ${X}`)}catch(z){Q.push(`${$.context}: rollback proof failed: ${String(z)}`)}return Q}function Wz($,Z={}){let Q=[],{owned:X}=$;if(X.fd===null)return[`${$.context}: cleanup descriptor is already closed`];try{if(!r$(X,$.isolationPath)){Q.push(`${$.context}: cleanup receipt ${$.isolationPath} changed identity before finalization; exact owned bytes were not truncated`);let W=KQ(X);if(W!==null)Q.push(W);return Q}if(!Z.sourceMayNameInstalledSuccessor&&tq($.sourcePath)){let W=a3($.sourcePath,$.context);Q.push("err"in W?`${$.context}: source ${$.sourcePath} was repopulated before cleanup receipt finalization; exact owned bytes retained at ${$.isolationPath}; ${W.err}`:`${$.context}: source ${$.sourcePath} was repopulated before cleanup receipt finalization; replacement retained outside the canonical namespace at ${W.ok.retainedPath}; exact owned bytes retained at ${$.isolationPath}${W.ok.warning===null?"":`; retention durability warning: ${W.ok.warning}`}`);let V=KQ(X);if(V!==null)Q.push(V);return Q}if(!o3(X))throw p$(`${$.context}: cleanup descriptor changed identity`);let Y=Buffer.from(`${JSON.stringify({kind:"indra-owned-path-cleanup",version:1,source:t3($.sourcePath),originalBytes:$.originalBytes,dev:String(X.dev),ino:String(X.ino)})}
149
+ `);cq(X.fd,0);let j=0;while(j<Y.length){let W=AC(X.fd,Y,j,Y.length-j,j);if(W<=0)throw Error(`short cleanup receipt write at ${j}/${Y.length}`);j+=W}if(lq(X.fd),!r$(X,$.isolationPath))Q.push(`${$.context}: cleanup receipt pathname changed identity; replacement preserved at ${$.isolationPath}`);l5($.isolationPath)}catch(Y){Q.push(`${$.context}: descriptor-bound cleanup failed; retained at ${$.isolationPath}: ${String(Y)}`)}let z=KQ(X);if(z!==null)Q.push(z);return Q}function t$($){if($===null)return[];let Z=KQ($);return Z===null?[]:[Z]}function C0($,Z,Q={}){let X=HQ($.path,$,Z,Q,{retainRepopulatedSourceOutsideCanonical:!0});if("err"in X)return[X.err,...t$($)];if(X.ok.kind==="absent"){let z=[];try{if($.fd!==null)if(R9($.fd).nlink===0)cq($.fd,0),lq($.fd);else z.push(`${Z}: ${$.path} vanished while its owned inode remains linked elsewhere`)}catch(Y){z.push(`${Z}: unlinked descriptor cleanup failed: ${String(Y)}`)}return[...z,...t$($)]}return Wz(X.ok.isolated)}var iq=100,TC=2,sq=17,SC=3221225472,RC=65536,mq=7,hq=3,OC=16,xC=1024,IC=33554432,uq=2097152,oq,pq=32,yC,i3=null;var Vz=E(()=>{ZQ();Zz();oq=-1n,yC=/^\.(?:recovery-catalog|verify-authority)\.[0-9]+\.[0-9a-z]+\.[0-9a-z]+\.db(?:-(?:wal|shm))?$/});function gC($,Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return!1;let Q=Z;return Q.source===$.source&&Q.stream===$.stream&&Q.sourceId===$.sourceId&&Q.rev===$.rev}function Z1($,Z){if(Z===null)return`cites missing authorization ${$.tomb}`;if(Z.id!==$.tomb)return`resolved the wrong authorization event ${Z.id}`;if(Z.kind!=="erasure.tombstone"||Z.origin.kind!=="kernel"||Z.tier!=="first-party"||Z.nk.source!=="zortex"||Z.nk.stream!=="erasure"||Z.body!=="")return`cites ${Z.id}, which is not a falcon-owned first-party zortex/erasure tombstone event`;try{if(Z0(Z)!==Z.contentHash)return`cites ${Z.id}, whose envelope content hash is invalid`}catch{return`cites ${Z.id}, whose envelope is malformed`}let Q=Z.payload;if(Q===null||typeof Q!=="object"||Array.isArray(Q))return`cites ${Z.id}, whose authorization payload is absent or malformed`;let X=Q;if(X.erasedId!==$.id||!gC($.nk,X.nk)||X.ts!==$.ts||X.kind!==$.kind||X.contentHash!==$.contentHash)return`cites ${Z.id}, whose authorization tuple does not match the retained tomb skeleton`;return null}var Kz=E(()=>{f()});import{closeSync as fC,fstatSync as XH,lstatSync as kC,mkdirSync as wC,openSync as mC}from"fs";import{basename as BQ,join as hC}from"path";import{Database as zH,constants as uC}from"bun:sqlite";function jH($){try{return kC($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}function E0($){let Z={code:"unavailable",layer:"storage",retryability:"transient",message:$};return Object.assign(Error($),{code:"ESTALE",structured:Z})}function qz($){let Z={code:"data_loss",layer:"storage",retryability:"non-retryable",message:$};return Object.assign(Error($),{code:"data_loss",structured:Z})}function x9($,Z,Q){let X=new Int32Array(1),z=$.fileControl("main",uC.SQLITE_FCNTL_HAS_MOVED,X),Y=process.platform==="win32"&&z===12;if(z!==0&&!Y)throw Object.assign(Error(`${Q}: SQLite main-file movement probe failed with code ${z}`),{code:"SQLITE_IOERR"});if(!Y&&X[0]!==0||!r$(Z))throw E0(`${Q}: SQLite main file moved or its reserved pathname was replaced`);if(Y)ZH(Z,Q)}function lC($){if($.fd===null)return;fC($.fd),$.fd=null}function v8($){let Z=[];for(let Q of[$,...$.sidecars.values()])try{lC(Q)}catch(X){Z.push(X)}if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,`catalog family descriptor close failed for ${$.path}`)}function n0($,Z){for(let Q of["-wal","-shm"]){let X=$+Q,z=Z.get(X);if(z!==void 0){if(jH(X)&&!r$(z))throw E0(`owned SQLite sidecar ${X} changed identity`);continue}let Y=O9(X,"SQLite sidecar ownership");if(Y===null)continue;if(!r$(Y))throw t$(Y),E0(`owned SQLite sidecar ${X} changed identity`);Z.set(X,Y)}}function Q1($,Z,Q,X={}){let z=[];for(let Y of["-wal","-shm"]){let j=$.path+Y,W=Z.get(j);if(W===void 0){if(!jH(j))continue;z.push(`${j}: unowned ${Q} sidecar; refusing pathname cleanup`);continue}z.push(...C0(W,`${Q} sidecar cleanup`,X))}return z.push(...C0($,`${Q} base cleanup`,X)),z}function WH($,Z){wC($,{recursive:!0});for(let Q=0;Q<100;Q++){let z=`${Math.random().toString(36).slice(2,10)||"0"}${Q.toString(36)}`,Y=hC($,`.${Z}.${process.pid}.${Date.now().toString(36)}.${z}.db`),j=[];try{for(let V of["","-wal","-shm"]){let q=Y+V,B=mC(q,"wx"),G=QH(q,B,"catalog exclusive reservation");if(j.push(G),!r$(G))throw Error(`catalog reservation ${q} changed identity before SQLite initialization`)}let W=j[0];if(W===void 0)throw Error(`catalog reservation ${Y} created no base member`);for(let V of j)$H(V,`catalog reservation ${V.path} pre-SQLite DELETE-access proof`);return{...W,sidecars:new Map(j.slice(1).map((V)=>[V.path,V]))}}catch(W){let V=[];for(let q of[...j].reverse())V.push(...C0(q,"catalog reservation cleanup").map((B)=>Error(B)));if(V.length>0)throw AggregateError([W,...V],`catalog reservation cleanup failed for ${Y}`);if(W.code==="EEXIST")continue;throw W}}throw Error(`could not allocate an exclusive ${Z} path`)}function JQ($,Z){return v({code:$,layer:"storage",retryability:"non-retryable",message:Z})}function VH($){if($.record_type!=="tomb"||$.tomb===null)throw Error(`recovery catalog row ${$.id} is not a tomb skeleton`);return{id:$.id,nk:{source:$.source,stream:$.stream,sourceId:$.source_id,rev:$.rev},ts:$.ts,kind:$.kind,contentHash:$.content_hash,tomb:$.tomb}}function GQ($){if($.record_type!=="frame"||$.event_jcs===null)return JQ("data_loss",`recovery catalog row ${$.id} has no full event envelope`);try{let Z=JSON.parse($.event_jcs),Q=g5(Z);if(!K(Q)){let X="err"in Q?Q.err.message:Q.empty.how;return JQ("data_loss",`recovery catalog event ${$.id} is invalid: ${X}`)}if(Z.id!==$.id||Z0(Z)!==Z.contentHash)return JQ("data_loss",`recovery catalog event ${$.id} does not match its indexed envelope`);return H(Z)}catch(Z){return JQ("data_loss",`recovery catalog event ${$.id} cannot be decoded: ${String(Z)}`)}}function X1($){if($.record_type==="tomb")return H({kind:"tomb",tomb:VH($)});let Z=GQ($);return K(Z)?H({kind:"frame",event:Z.ok}):Z}class z1{strategy;ownedPath;path;db;inSegment=!1;pendingRecords=0;transactionRecords=0;maxTransactionRecords=0;segmentCount=0;recordCount=0;bytesRead=0;maxBufferedBytes=0;maxManifestDistinctStreams=0;maxManifestAggregatorRowsInHeap=0;maxManifestTransactionRecords=0;maxManifestCatalogBytes=0;manifestMmapProof="not-observed";dbAheadSurvivors=0;dbDonorDisposition="twin-unavailable";closed=!1;ownedSidecars;constructor($,Z,Q,X){this.strategy=Q;this.ownedPath=X;this.path=$,this.db=Z,this.ownedSidecars=new Map(X.sidecars)}static create($,Z="sealed-sqlite-catalog"){let Q=WH($,"recovery-catalog"),X=Q.path,z=null;try{z=new zH(X,{create:!0}),x9(z,Q,`recovery catalog ${X} SQLite open`),z.exec("PRAGMA journal_mode = WAL"),z.exec("PRAGMA synchronous = NORMAL"),z.exec("PRAGMA temp_store = FILE"),z.exec("PRAGMA cache_size = -4096"),z.exec("PRAGMA cache_spill = ON"),z.exec("PRAGMA mmap_size = 0"),z.exec(pC),x9(z,Q,`recovery catalog ${X} initialization`);let Y=new z1(X,z,Z,Q);return n0(X,Y.ownedSidecars),Y}catch(Y){let j=[],W=new Map(Q.sidecars);if(z!==null){try{n0(X,W)}catch(V){j.push(V)}try{z.close()}catch(V){j.push(V)}}j.push(...Q1(Q,W,"catalog").map((V)=>Error(V)));try{v8(Q)}catch(V){j.push(V)}if(j.length>0)throw AggregateError([Y,...j],`recovery catalog initialization cleanup failed for ${X}: ${String(Y)}`);throw Y}}beginSegment(){if(this.inSegment)throw Error("recovery catalog already has an active segment transaction");this.assertOwned("recovery catalog segment begin"),this.db.exec("BEGIN IMMEDIATE"),this.inSegment=!0,this.pendingRecords=0,this.transactionRecords=0}noteStagedRecord(){if(this.pendingRecords++,!this.inSegment)return;if(this.transactionRecords++,this.maxTransactionRecords=Math.max(this.maxTransactionRecords,this.transactionRecords),this.transactionRecords<YH)return;this.db.exec("COMMIT"),this.inSegment=!1,this.assertOwned("recovery catalog bounded chunk commit"),this.db.exec("BEGIN IMMEDIATE"),this.inSegment=!0,this.transactionRecords=0}assertRecordAvailable($,Z,Q){if(this.db.query("SELECT 1 AS present FROM records WHERE id = ?").get($)!==null)throw qz(`duplicate event id ${$} in prospective recovery generation`);if(Q){let X=this.db.query(`SELECT id FROM records
150
+ WHERE source = ? AND stream = ? AND source_id = ? AND rev = ? AND unique_nk = 1`).get(Z.source,Z.stream,Z.sourceId,Z.rev);if(X!==null)throw qz(`unique natural key collision between ${X.id} and ${$} in prospective recovery generation`)}}stageEvent($,Z,Q,X){this.assertRecordAvailable($.id,$.nk,X),this.db.query(`INSERT INTO records (
151
+ id, record_type, segment, line, event_jcs, source, stream, source_id, rev,
152
+ ts, kind, content_hash, tomb, unique_nk
153
+ ) VALUES (?, 'frame', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)`).run($.id,Z,Q,C$($),$.nk.source,$.nk.stream,$.nk.sourceId,$.nk.rev,$.ts,$.kind,$.contentHash,X?1:0),this.noteStagedRecord()}stageTomb($,Z,Q,X){this.assertRecordAvailable($.id,$.nk,X),this.db.query(`INSERT INTO records (
154
+ id, record_type, segment, line, event_jcs, source, stream, source_id, rev,
155
+ ts, kind, content_hash, tomb, unique_nk
156
+ ) VALUES (?, 'tomb', ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run($.id,Z,Q,$.nk.source,$.nk.stream,$.nk.sourceId,$.nk.rev,$.ts,$.kind,$.contentHash,$.tomb,X?1:0),this.noteStagedRecord()}commitSegment($,Z){if(!this.inSegment)throw Error("recovery catalog has no active segment transaction");if($.fingerprint!==Z.fingerprint)throw E0(`streamed segment ${$.segmentId} descriptor fingerprint diverged from its bounded summary`);if($.segmentId!==Z.segment||$.count!==this.pendingRecords||Z.frames!==this.pendingRecords)throw Error(`streamed segment ${$.segmentId} accounting diverged from its bounded summary`);this.db.query(`INSERT INTO segments (segment, path, file, rewrite_gen, count, fingerprint, bytes, verified)
157
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1)`).run($.segmentId,$.path,BQ($.path),$.rewriteGen,$.count,Z.fingerprint,Z.bytesRead),this.db.exec("COMMIT"),this.inSegment=!1,this.assertOwned(`recovery catalog segment ${$.segmentId} commit`),this.segmentCount++,this.recordCount+=this.pendingRecords,this.bytesRead+=Z.bytesRead,this.maxBufferedBytes=Math.max(this.maxBufferedBytes,Z.maxBufferedBytes),this.noteStreamManifest(Z),this.pendingRecords=0,this.transactionRecords=0}commitProvisionalSegment($,Z){if(!this.inSegment)throw Error("recovery catalog has no active segment transaction");if($.entries.length!==this.pendingRecords)throw Error(`provisional tail ${$.segmentId} accounting diverged from its parsed committed prefix`);this.db.query(`INSERT INTO segments (segment, path, file, rewrite_gen, count, fingerprint, bytes, verified)
158
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0)`).run($.segmentId,$.path,BQ($.path),$.header.rewriteGen,$.entries.length,$.fingerprint,Z),this.db.exec("COMMIT"),this.inSegment=!1,this.assertOwned(`recovery catalog provisional segment ${$.segmentId} commit`),this.segmentCount++,this.recordCount+=this.pendingRecords,this.bytesRead+=Z,this.maxBufferedBytes=Math.max(this.maxBufferedBytes,Z),this.pendingRecords=0,this.transactionRecords=0}finalizeProvisionalSegment($,Z,Q){if(Z.segmentId!==$||Q.segment!==$||Z.fingerprint!==Q.fingerprint||Z.count!==Q.frames)throw E0(`recovered tail ${$} descriptor proof diverged from its streamed summary`);let X=this.db.query("SELECT path, rewrite_gen, count, verified FROM segments WHERE segment = ?").get($);if(X===null||X.verified!==0||X.path!==Z.path||X.rewrite_gen!==Z.rewriteGen||X.count!==Z.count)throw E0(`recovered tail ${$} does not match its provisional catalog segment`);this.db.query(`UPDATE segments
159
+ SET file = ?, fingerprint = ?, bytes = ?, verified = 1
160
+ WHERE segment = ?`).run(BQ(Z.path),Q.fingerprint,Q.bytesRead,$),this.assertOwned(`recovery catalog provisional segment ${$} finalization`),this.bytesRead+=Q.bytesRead,this.maxBufferedBytes=Math.max(this.maxBufferedBytes,Q.maxBufferedBytes),this.noteStreamManifest(Q)}rollbackSegment(){if(!this.inSegment)return;this.db.exec("ROLLBACK"),this.inSegment=!1,this.pendingRecords=0,this.transactionRecords=0}stageDbEvent($,Z,Q,X){this.db.exec("BEGIN IMMEDIATE");try{this.stageEvent($,Z,Q,X),this.db.query("INSERT INTO survivors (id, original_segment, original_line) VALUES (?, ?, ?)").run($.id,Z,Q),this.db.exec("COMMIT"),this.assertOwned(`recovery catalog DB survivor ${$.id} stage`),this.recordCount++,this.dbAheadSurvivors++,this.maxTransactionRecords=Math.max(this.maxTransactionRecords,1),this.pendingRecords=0}catch(z){throw this.db.exec("ROLLBACK"),this.pendingRecords=0,z}}stageDbTomb($,Z,Q,X){this.db.exec("BEGIN IMMEDIATE");try{this.stageTomb($,Z,Q,X),this.db.query("INSERT INTO survivors (id, original_segment, original_line) VALUES (?, ?, ?)").run($.id,Z,Q),this.db.exec("COMMIT"),this.recordCount++,this.dbAheadSurvivors++,this.maxTransactionRecords=Math.max(this.maxTransactionRecords,1),this.pendingRecords=0}catch(z){throw this.db.exec("ROLLBACK"),this.pendingRecords=0,z}}hasRecord($){return this.db.query("SELECT 1 AS present FROM records WHERE id = ?").get($)!==null}setDbDonorDisposition($){this.dbDonorDisposition=$}validateTombAuthorizations(){let $=this.db.query("SELECT * FROM records WHERE id = ?");for(let Z of this.db.query("SELECT * FROM records WHERE record_type = 'tomb' ORDER BY id").iterate()){let Q=VH(Z),X=$.get(Q.tomb),z=null;if(X!==null&&X.record_type==="frame"){let j=GQ(X);if(!K(j))return j;z=j.ok}let Y=Z1(Q,z);if(Y!==null)return JQ("data_loss",`prospective recovery tomb ${Q.id} ${Y}`)}return H(!0)}*recordsInReplayOrder(){yield*this.db.query("SELECT * FROM records ORDER BY id").iterate()}*segments(){yield*this.db.query("SELECT * FROM segments ORDER BY segment").iterate()}*recordsForSegment($){yield*this.db.query(`SELECT records.* FROM records
161
+ WHERE records.segment = ?
162
+ AND NOT EXISTS (SELECT 1 FROM survivors WHERE survivors.id = records.id)
163
+ ORDER BY records.line, records.id`).iterate($)}*survivorGroups(){for(let $ of this.db.query("SELECT DISTINCT original_segment FROM survivors ORDER BY original_segment").iterate())yield $.original_segment}*survivorRecords($){yield*this.db.query(`SELECT records.* FROM survivors
164
+ JOIN records ON records.id = survivors.id
165
+ WHERE survivors.original_segment = ?
166
+ ORDER BY survivors.original_line, survivors.id`).iterate($)}firstSurvivorRecord($){return this.db.query(`SELECT records.* FROM survivors
167
+ JOIN records ON records.id = survivors.id
168
+ WHERE survivors.original_segment = ?
169
+ ORDER BY survivors.original_line, survivors.id
170
+ LIMIT 1`).get($)}relocateSurvivorGroup($,Z,Q){this.db.exec("BEGIN IMMEDIATE");try{if(Z.segmentId!==Q.segment||Z.fingerprint!==Q.fingerprint)throw E0(`DB-ahead recovery segment ${Z.segmentId} descriptor proof diverged from its streamed summary`);let X=1,z=0,Y=this.db.query("UPDATE records SET segment = ?, line = ? WHERE id = ?");for(let j of this.db.query("SELECT id FROM survivors WHERE original_segment = ? ORDER BY original_line, id").iterate($))Y.run(Z.segmentId,X++,j.id),z++;if(z!==Z.count||Q.frames!==z)throw Error(`DB-ahead recovery segment ${Z.segmentId} serialized ${z} of ${Z.count} rows`);return this.db.query(`INSERT INTO segments (segment, path, file, rewrite_gen, count, fingerprint, bytes, verified)
171
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1)`).run(Z.segmentId,Z.path,BQ(Z.path),Z.rewriteGen,Z.count,Q.fingerprint,Q.bytesRead),this.db.exec("COMMIT"),this.assertOwned(`recovery catalog survivor segment ${Z.segmentId} relocation`),this.segmentCount++,this.bytesRead+=Q.bytesRead,this.maxBufferedBytes=Math.max(this.maxBufferedBytes,Q.maxBufferedBytes),this.noteStreamManifest(Q),z}catch(X){throw this.db.exec("ROLLBACK"),X}}recordById($){return this.db.query("SELECT * FROM records WHERE id = ?").get($)}count(){return this.db.query("SELECT COUNT(*) AS count FROM records").get().count}evidence(){return{strategy:this.strategy,segmentCount:this.segmentCount,recordCount:this.recordCount,bytesRead:this.bytesRead,maxBufferedBytes:this.maxBufferedBytes,maxTransactionRecords:this.maxTransactionRecords,catalogBytes:this.storageBytes(),dbAheadSurvivors:this.dbAheadSurvivors,dbDonorDisposition:this.dbDonorDisposition,streamManifest:{strategy:"sqlite-system-temp-disk",backing:"vfs-delete-on-close",vfsFilePointer:!0,initialJournalMode:"delete",journalMode:"memory",lockingMode:"exclusive",pagerCacheKiB:256,cacheSpill:!0,tempStore:"file",mmapBytes:0,mmapProof:this.manifestMmapProof,maxDistinctStreams:this.maxManifestDistinctStreams,maxAggregatorRowsInHeap:this.maxManifestAggregatorRowsInHeap,maxTransactionRecords:this.maxManifestTransactionRecords,maxCatalogBytes:this.maxManifestCatalogBytes}}}noteStreamManifestEvidence($){this.manifestMmapProof=this.manifestMmapProof==="not-observed"?$.mmapProof:this.manifestMmapProof===$.mmapProof?this.manifestMmapProof:"mixed",this.maxManifestDistinctStreams=Math.max(this.maxManifestDistinctStreams,$.distinctStreams),this.maxManifestAggregatorRowsInHeap=Math.max(this.maxManifestAggregatorRowsInHeap,$.maxAggregatorRowsInHeap),this.maxManifestTransactionRecords=Math.max(this.maxManifestTransactionRecords,$.maxTransactionRecords),this.maxManifestCatalogBytes=Math.max(this.maxManifestCatalogBytes,$.catalogBytes)}noteStreamManifest($){this.noteStreamManifestEvidence($.streamManifest)}checkpoint(){this.assertOwned("recovery catalog checkpoint start"),this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)"),this.assertOwned("recovery catalog checkpoint completion"),n0(this.path,this.ownedSidecars)}storageBytes(){if(this.assertOwned("recovery catalog size accounting"),n0(this.path,this.ownedSidecars),this.ownedPath.fd===null)throw E0(`recovery catalog ${this.path} descriptor is closed`);let $=XH(this.ownedPath.fd).size;for(let Z of this.ownedSidecars.values()){if(!r$(Z))continue;if(Z.fd===null)throw E0(`recovery catalog sidecar ${Z.path} descriptor is closed`);$+=XH(Z.fd).size}return $}assertOwned($){if(this.closed)throw E0(`${$}: recovery catalog is closed`);x9(this.db,this.ownedPath,$)}close(){if(this.closed)return;let $=[];try{if(this.inSegment)this.rollbackSegment();this.assertOwned("recovery catalog close"),n0(this.path,this.ownedSidecars)}catch(Z){$.push(Z)}try{this.db.close()}catch(Z){$.push(Z)}try{v8(this.ownedPath)}catch(Z){$.push(Z)}if(this.closed=!0,$.length===1)throw $[0];if($.length>1)throw AggregateError($,`recovery catalog close failed for ${this.path}`)}remove($={}){let Z=[];if(this.closed)return[`catalog cleanup ownership was already released for ${this.path}`];try{if(this.inSegment)this.rollbackSegment();this.assertOwned("recovery catalog cleanup"),n0(this.path,this.ownedSidecars)}catch(Q){Z.push(`pre-close proof: ${String(Q)}`)}try{this.db.close()}catch(Q){Z.push(`database close: ${String(Q)}`)}this.closed=!0;try{Z.push(...Q1(this.ownedPath,this.ownedSidecars,"catalog",$))}catch(Q){Z.push(`owned-file cleanup threw: ${String(Q)}`)}try{v8(this.ownedPath)}catch(Q){Z.push(`descriptor close: ${String(Q)}`)}return Z}}class Y1{ownedPath;path;db;inSegment=!1;transactionRecords=0;pendingRecords=0;closed=!1;ownedSidecars;constructor($,Z,Q){this.ownedPath=Q;this.path=$,this.db=Z,this.ownedSidecars=new Map(Q.sidecars)}static create($){let Z=WH($,"verify-authority"),Q=Z.path,X=null;try{X=new zH(Q,{create:!0}),x9(X,Z,`verification authority catalog ${Q} SQLite open`),X.exec("PRAGMA journal_mode = WAL"),X.exec("PRAGMA synchronous = NORMAL"),X.exec("PRAGMA temp_store = FILE"),X.exec("PRAGMA cache_size = -2048"),X.exec("PRAGMA cache_spill = ON"),X.exec("PRAGMA mmap_size = 0"),X.exec(cC),x9(X,Z,`verification authority catalog ${Q} initialization`);let z=new Y1(Q,X,Z);return n0(Q,z.ownedSidecars),z}catch(z){let Y=[],j=new Map(Z.sidecars);if(X!==null){try{n0(Q,j)}catch(W){Y.push(W)}try{X.close()}catch(W){Y.push(W)}}Y.push(...Q1(Z,j,"authority").map((W)=>Error(W)));try{v8(Z)}catch(W){Y.push(W)}if(Y.length>0)throw AggregateError([z,...Y],`verification catalog initialization cleanup failed for ${Q}: ${String(z)}`);throw z}}beginSegment(){if(this.inSegment)throw Error("verification authority catalog already has an active transaction");this.assertOwned("verification authority segment begin"),this.db.exec("BEGIN IMMEDIATE"),this.inSegment=!0,this.transactionRecords=0,this.pendingRecords=0}noteStagedRecord(){if(this.pendingRecords++,this.transactionRecords++,this.transactionRecords<YH)return;this.db.exec("COMMIT"),this.inSegment=!1,this.assertOwned("verification authority bounded chunk commit"),this.db.exec("BEGIN IMMEDIATE"),this.inSegment=!0,this.transactionRecords=0}assertId($){if(this.db.query("SELECT 1 AS present FROM records WHERE id = ?").get($)!==null)throw qz(`duplicate event id ${$} in verified segment generation`)}stageEvent($,Z,Q){this.assertId($.id),this.db.query(`INSERT INTO records (id, record_type, segment, line, event_jcs, kind)
172
+ VALUES (?, 'frame', ?, ?, ?, ?)`).run($.id,Z,Q,$.kind==="erasure.tombstone"?C$($):null,$.kind),this.noteStagedRecord()}stageTomb($,Z,Q){this.assertId($.id),this.db.query(`INSERT INTO records (
173
+ id, record_type, segment, line, event_jcs, source, stream, source_id, rev, ts, kind, content_hash, tomb
174
+ ) VALUES (?, 'tomb', ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?)`).run($.id,Z,Q,$.nk.source,$.nk.stream,$.nk.sourceId,$.nk.rev,$.ts,$.kind,$.contentHash,$.tomb),this.noteStagedRecord()}commitSegment($,Z){if(!this.inSegment)throw Error("verification authority catalog has no active transaction");if(Z.frames!==this.pendingRecords||BQ($)!==`seg-${Z.segment}.zev`)throw Error(`verification authority coverage for ${$} is ${this.pendingRecords}/${Z.frames}`);this.db.query("INSERT INTO segments (file, segment, count, fingerprint) VALUES (?, ?, ?, ?)").run($,Z.segment,Z.frames,Z.fingerprint),this.db.exec("COMMIT"),this.inSegment=!1,this.assertOwned(`verification authority segment ${$} commit`),this.transactionRecords=0,this.pendingRecords=0}rollbackSegment(){if(!this.inSegment)return;this.db.exec("ROLLBACK"),this.inSegment=!1,this.transactionRecords=0,this.pendingRecords=0}*segments(){this.assertOwned("verification authority segment enumeration"),yield*this.db.query("SELECT * FROM segments ORDER BY file").iterate()}*physicalRows(){this.assertOwned("verification authority physical-row enumeration"),yield*this.db.query("SELECT id, record_type, segment, line FROM records ORDER BY id").iterate()}*tombs(){this.assertOwned("verification authority tomb enumeration"),yield*this.db.query("SELECT * FROM records WHERE record_type = 'tomb' ORDER BY id").iterate()}authorizer($){this.assertOwned("verification authority authorizer lookup");let Z=this.db.query("SELECT event_jcs FROM records WHERE id = ? AND record_type = 'frame'").get($);if(Z?.event_jcs===null||Z?.event_jcs===void 0)return null;let Q=JSON.parse(Z.event_jcs),X=g5(Q);if(!K(X)||Q.id!==$||Z0(Q)!==Q.contentHash)throw Error(`physical tomb authorizer ${$} is not a valid complete envelope`);return Q}tombCount(){return this.assertOwned("verification authority tomb count"),this.db.query("SELECT COUNT(*) AS count FROM records WHERE record_type = 'tomb'").get().count}close(){if(this.closed)return;let $=[];try{if(this.inSegment)this.rollbackSegment();x9(this.db,this.ownedPath,"verification authority catalog close"),n0(this.path,this.ownedSidecars)}catch(Z){$.push(Z)}try{this.db.close()}catch(Z){$.push(Z)}try{v8(this.ownedPath)}catch(Z){$.push(Z)}if(this.closed=!0,$.length===1)throw $[0];if($.length>1)throw AggregateError($,`verification authority catalog close failed for ${this.path}`)}assertOwned($){if(this.closed)throw E0(`${$}: verification authority catalog is closed`);x9(this.db,this.ownedPath,$)}remove($={}){let Z=[];if(this.closed)return[`authority cleanup ownership was already released for ${this.path}`];try{if(this.inSegment)this.rollbackSegment();this.assertOwned("verification authority catalog cleanup"),n0(this.path,this.ownedSidecars)}catch(Q){Z.push(`pre-close proof: ${String(Q)}`)}try{this.db.close()}catch(Q){Z.push(`database close: ${String(Q)}`)}this.closed=!0;try{Z.push(...Q1(this.ownedPath,this.ownedSidecars,"authority",$))}catch(Q){Z.push(`owned-file cleanup threw: ${String(Q)}`)}try{v8(this.ownedPath)}catch(Q){Z.push(`descriptor close: ${String(Q)}`)}return Z}}var pC=`
175
+ CREATE TABLE records (
176
+ id TEXT PRIMARY KEY,
177
+ record_type TEXT NOT NULL CHECK(record_type IN ('frame', 'tomb')),
178
+ segment TEXT NOT NULL,
179
+ line INTEGER NOT NULL,
180
+ event_jcs TEXT,
181
+ source TEXT NOT NULL,
182
+ stream TEXT NOT NULL,
183
+ source_id TEXT NOT NULL,
184
+ rev TEXT NOT NULL,
185
+ ts TEXT NOT NULL,
186
+ kind TEXT NOT NULL,
187
+ content_hash TEXT NOT NULL,
188
+ tomb TEXT,
189
+ unique_nk INTEGER NOT NULL CHECK(unique_nk IN (0, 1)),
190
+ CHECK((record_type = 'frame' AND event_jcs IS NOT NULL AND tomb IS NULL)
191
+ OR (record_type = 'tomb' AND event_jcs IS NULL AND tomb IS NOT NULL))
192
+ );
193
+ CREATE UNIQUE INDEX uq_catalog_nk
194
+ ON records(source, stream, source_id, rev) WHERE unique_nk = 1;
195
+ CREATE INDEX idx_catalog_order ON records(id);
196
+ CREATE INDEX idx_catalog_tombs ON records(record_type, tomb);
197
+ CREATE TABLE segments (
198
+ segment TEXT PRIMARY KEY,
199
+ path TEXT NOT NULL UNIQUE,
200
+ file TEXT NOT NULL,
201
+ rewrite_gen INTEGER NOT NULL,
202
+ count INTEGER NOT NULL,
203
+ fingerprint TEXT NOT NULL,
204
+ bytes INTEGER NOT NULL,
205
+ verified INTEGER NOT NULL CHECK(verified IN (0, 1))
206
+ );
207
+ CREATE TABLE survivors (
208
+ id TEXT PRIMARY KEY REFERENCES records(id),
209
+ original_segment TEXT NOT NULL,
210
+ original_line INTEGER NOT NULL
211
+ );
212
+ CREATE INDEX idx_survivor_group ON survivors(original_segment, original_line, id);
213
+ `,YH=2048,cC=`
214
+ CREATE TABLE records (
215
+ id TEXT PRIMARY KEY,
216
+ record_type TEXT NOT NULL CHECK(record_type IN ('frame', 'tomb')),
217
+ segment TEXT NOT NULL,
218
+ line INTEGER NOT NULL,
219
+ event_jcs TEXT,
220
+ source TEXT,
221
+ stream TEXT,
222
+ source_id TEXT,
223
+ rev TEXT,
224
+ ts TEXT,
225
+ kind TEXT,
226
+ content_hash TEXT,
227
+ tomb TEXT,
228
+ CHECK((record_type = 'frame' AND tomb IS NULL)
229
+ OR (record_type = 'tomb' AND event_jcs IS NULL AND tomb IS NOT NULL))
230
+ );
231
+ CREATE INDEX idx_authority_tombs ON records(record_type, tomb);
232
+ CREATE TABLE segments (
233
+ file TEXT PRIMARY KEY,
234
+ segment TEXT NOT NULL UNIQUE,
235
+ count INTEGER NOT NULL,
236
+ fingerprint TEXT NOT NULL
237
+ );
238
+ `;var KH=E(()=>{f();Vz();Kz()});import{Database as qH}from"bun:sqlite";function Hz($){if(j1.has($))return $;let Z=new Set;return j1.set($,Z),Object.defineProperty($,"query",{configurable:!0,value:function(Q){let X=Reflect.apply(qH.prototype.query,this,[Q]);if(typeof X?.finalize==="function")Z.add(X);return X}}),Object.defineProperty($,"prepare",{configurable:!0,value:function(Q){let X=Reflect.apply(qH.prototype.prepare,this,[Q]);if(typeof X?.finalize==="function")Z.add(X);return X}}),$}function UQ($,Z){let Q=[],X=j1.get($)??new Set;j1.delete($);for(let z of X)try{z.finalize()}catch(Y){Q.push(Y)}X.clear();try{$.close(!0)}catch(z){Q.push(z)}if(Q.length===1)throw Q[0];if(Q.length>1)throw AggregateError(Q,`${Z} statement finalization and database close failed`)}var j1;var W1=E(()=>{j1=new WeakMap});import{Database as BH}from"bun:sqlite";function I9($,Z){let Q=HH.get($);if(Q===void 0)Q=new Map,HH.set($,Q);let X=Q.get(Z);if(X!==void 0)return X;let z=$.query(Z);return Q.set(Z,z),z}function JH($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec(dC),$.query("SELECT value FROM meta WHERE key = ?").get(b8)?.value===g8)return;let Q=$.query("SELECT COUNT(*) AS count FROM events").get().count;$.exec("BEGIN IMMEDIATE");try{if($.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(b8,g8),Q>0)$.query("INSERT OR IGNORE INTO meta (key, value) VALUES ('twin-dirty', ?)").run(K1);$.exec("COMMIT")}catch(X){throw $.exec("ROLLBACK"),X}}function GH($){return new BH($,{readwrite:!0})}function Bz($,Z=JH){Z($)}function Jz($,Z=JH){let Q=Hz(new BH($,{create:!0}));try{return Bz(Q,Z),Q}catch(X){try{UQ(Q,"twin initialization")}catch(z){throw AggregateError([X,z],`twin initialization failed and its database handle could not close: ${String(X)}`)}throw X}}function V1($){return $===void 0?null:C$($)}function q1($,Z,Q,X,z){I9($,`INSERT INTO events (id, source, stream, source_id, rev, content_hash, canon, ts, observed_ts,
239
+ trust, origin, tier, kind, schema_version, policy_version, coverage, mentions, body, lang,
240
+ payload, blobs, refs, segment, line, unique_nk, erased, tomb)
241
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL)`).run(Z.id,Z.nk.source,Z.nk.stream,Z.nk.sourceId,Z.nk.rev,Z.contentHash,Z.canon,Z.ts,Z.observedTs,C$(Z.trust),C$(Z.origin),Z.tier,Z.kind,Z.schemaVersion,Z.policyVersion??null,V1(Z.coverage),C$(Z.mentions),Z.body,Z.lang??null,V1(Z.payload),V1(Z.blobs),V1(Z.refs),Q,X,z?1:0)}function UH($,Z,Q,X,z){$.query(`INSERT INTO events (id, source, stream, source_id, rev, content_hash, canon, ts, observed_ts,
242
+ trust, origin, tier, kind, schema_version, policy_version, coverage, mentions, body, lang,
243
+ payload, blobs, refs, segment, line, unique_nk, erased, tomb)
244
+ VALUES (?, ?, ?, ?, ?, ?, NULL, ?, NULL, NULL, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL,
245
+ NULL, NULL, NULL, ?, ?, ?, 1, ?)`).run(Z.id,Z.nk.source,Z.nk.stream,Z.nk.sourceId,Z.nk.rev,Z.contentHash,Z.ts,Z.kind,Q,X,z?1:0,Z.tomb)}function V5($){let Z={id:$.id,nk:{source:$.source,stream:$.stream,sourceId:$.source_id,rev:$.rev},contentHash:$.content_hash,canon:$.canon,ts:$.ts,observedTs:$.observed_ts,trust:JSON.parse($.trust),origin:JSON.parse($.origin),tier:$.tier,kind:$.kind,schemaVersion:$.schema_version,mentions:JSON.parse($.mentions),body:$.body};if($.policy_version!==null)Z.policyVersion=$.policy_version;if($.coverage!==null)Z.coverage=JSON.parse($.coverage);if($.lang!==null)Z.lang=$.lang;if($.payload!==null)Z.payload=JSON.parse($.payload);if($.blobs!==null)Z.blobs=JSON.parse($.blobs);if($.refs!==null)Z.refs=JSON.parse($.refs);return Z}function H1($){return{id:$.id,nk:{source:$.source,stream:$.stream,sourceId:$.source_id,rev:$.rev},ts:$.ts,erasedKind:$.kind}}function nC($){if(!$.blobs||$.blobs.length===0)return[];return[...new Set($.blobs.map((Z)=>Z.sha256))]}function LH($,Z,Q,X){return I9($,"SELECT MIN(id) AS m FROM events WHERE source = ? AND stream = ? AND source_id = ?").get(Z,Q,X)?.m??null}function Gz($,Z){let Q=I9($,`SELECT rowid AS rid, from_id, rel FROM pending_refs
246
+ WHERE source = ? AND stream = ? AND source_id = ?
247
+ LIMIT 256`),X=Q.all(Z.source,Z.stream,Z.sourceId);if(X.length===0)return;let z=LH($,Z.source,Z.stream,Z.sourceId);if(z===null)return;while(!0){for(let Y of X)$.query("INSERT INTO resolved_refs (from_id, rel, to_id) VALUES (?, ?, ?)").run(Y.from_id,Y.rel,z),$.query("DELETE FROM pending_refs WHERE rowid = ?").run(Y.rid);if(X=Q.all(Z.source,Z.stream,Z.sourceId),X.length===0)return}}function B1($,Z){for(let X of nC(Z))$.query(`INSERT INTO blob_refs (sha256, refcount) VALUES (?, 1)
248
+ ON CONFLICT(sha256) DO UPDATE SET refcount = refcount + 1`).run(X);if(Z.refs)for(let X of Z.refs){let z=X.to;if(typeof z==="string")$.query("INSERT INTO resolved_refs (from_id, rel, to_id) VALUES (?, ?, ?)").run(Z.id,X.rel,z);else if("sourceId"in z){let Y=LH($,z.source,z.stream,z.sourceId);if(Y!==null)$.query("INSERT INTO resolved_refs (from_id, rel, to_id) VALUES (?, ?, ?)").run(Z.id,X.rel,Y);else $.query("INSERT INTO pending_refs (from_id, rel, source, stream, source_id) VALUES (?, ?, ?, ?, ?)").run(Z.id,X.rel,z.source,z.stream,z.sourceId)}else $.query("INSERT INTO claims (from_id, rel, ns, value) VALUES (?, ?, ?, ?)").run(Z.id,X.rel,z.ns,z.value)}Gz($,Z.nk);let Q=Z.payload;if(Z.kind==="identity.rebind"&&Q!==void 0){let X=P9(Q);if(K(X))$.query(`INSERT OR IGNORE INTO rebinds (from_source, from_stream, from_source_id, to_source, to_stream, to_source_id, event_id)
249
+ VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X.ok.from.source,X.ok.from.stream,X.ok.from.sourceId,X.ok.to.source,X.ok.to.stream,X.ok.to.sourceId,Z.id)}else if(Z.kind==="ingest.unknown-kind"&&Q!==void 0)$.query("INSERT OR IGNORE INTO unknown_kinds (source, kind, first_event_id) VALUES (?, ?, ?)").run(String(Q.source),String(Q.kind),String(Q.firstEventId));else if(Z.kind==="erasure.tombstone"&&Q!==void 0){let X=Q.nk;$.query(`INSERT OR REPLACE INTO tombstones (source, stream, source_id, rev, content_hash, tomb_id, future_too, ts, kind)
250
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(X.source,X.stream,X.sourceId,X.rev,String(Q.contentHash),Z.id,Q.futureToo===!0?1:0,String(Q.ts),String(Q.kind))}else if(Z.kind==="erasure.requested")$.query(`INSERT OR IGNORE INTO erasure_jobs (job_id, state, request, requested_ts, updated_ts)
251
+ VALUES (?, 'REQUESTED', ?, ?, ?)`).run(Z.id,C$(Z.payload??null),Z.ts,Z.ts);else if(Z.kind==="trace.span"&&Q!==void 0&&Q.name==="erasure.step"){let X=Q.attrs??{},z=X.jobId,Y=X.state;if(typeof z==="string"&&typeof Y==="string")$.query(`UPDATE erasure_jobs SET state = ?,
252
+ scope = COALESCE(?, scope),
253
+ last_completed = COALESCE(?, last_completed),
254
+ error = ?,
255
+ updated_ts = ?
256
+ WHERE job_id = ?`).run(Y,X.scope!==void 0?C$(X.scope):null,typeof X.lastCompleted==="string"?X.lastCompleted:null,X.error!==void 0?C$(X.error):null,String(Q.startTs),z)}}function Uz($,Z,Q){let X=$.query("SELECT * FROM events WHERE id = ?").get(Z);if(X===null||X.erased===1)return;if(X.blobs!==null){let z=JSON.parse(X.blobs);for(let Y of[...new Set(z.map((j)=>j.sha256))])$.query("UPDATE blob_refs SET refcount = refcount - 1 WHERE sha256 = ?").run(Y)}$.query("DELETE FROM pending_refs WHERE from_id = ?").run(Z),$.query("DELETE FROM resolved_refs WHERE from_id = ?").run(Z),$.query("DELETE FROM claims WHERE from_id = ?").run(Z),$.query(`UPDATE events SET canon = NULL, observed_ts = NULL, trust = NULL, origin = NULL, tier = NULL,
257
+ schema_version = NULL, policy_version = NULL, coverage = NULL, mentions = NULL, body = NULL,
258
+ lang = NULL, payload = NULL, blobs = NULL, refs = NULL, erased = 1, tomb = ?
259
+ WHERE id = ?`).run(Q,Z)}function DH($){let Z=(Q)=>$.query(Q).all();return{events:Z("SELECT * FROM events ORDER BY id"),pending_refs:Z("SELECT from_id, rel, source, stream, source_id FROM pending_refs ORDER BY from_id, rel, source, stream, source_id"),resolved_refs:Z("SELECT from_id, rel, to_id FROM resolved_refs ORDER BY from_id, rel, to_id"),claims:Z("SELECT from_id, rel, ns, value FROM claims ORDER BY from_id, rel, ns, value"),tombstones:Z("SELECT * FROM tombstones ORDER BY source, stream, source_id, rev"),rebinds:Z("SELECT * FROM rebinds ORDER BY from_source, from_stream, from_source_id"),unknown_kinds:Z("SELECT * FROM unknown_kinds ORDER BY source, kind"),blob_refs:Z("SELECT * FROM blob_refs WHERE refcount > 0 ORDER BY sha256"),erasure_jobs:Z("SELECT * FROM erasure_jobs ORDER BY job_id"),segments:Z("SELECT * FROM segments ORDER BY segment"),meta:Z("SELECT * FROM meta WHERE key NOT LIKE 'open-recovery:%' AND key NOT LIKE 'segment-verify:%' ORDER BY key")}}var b8="twin-codec-version",g8="1",K1="twin-codec-migration-required",HH,dC=`
260
+ CREATE TABLE IF NOT EXISTS events (
261
+ id TEXT PRIMARY KEY,
262
+ source TEXT NOT NULL, stream TEXT NOT NULL, source_id TEXT NOT NULL, rev TEXT NOT NULL,
263
+ content_hash TEXT NOT NULL, canon INTEGER,
264
+ ts TEXT NOT NULL, observed_ts TEXT,
265
+ trust TEXT, origin TEXT, tier TEXT, kind TEXT NOT NULL,
266
+ schema_version INTEGER, policy_version INTEGER,
267
+ coverage TEXT, mentions TEXT, body TEXT, lang TEXT,
268
+ payload TEXT, blobs TEXT, refs TEXT,
269
+ segment TEXT NOT NULL, line INTEGER NOT NULL,
270
+ unique_nk INTEGER NOT NULL DEFAULT 1,
271
+ erased INTEGER NOT NULL DEFAULT 0, tomb TEXT
272
+ );
273
+ CREATE INDEX IF NOT EXISTS idx_events_nkbase ON events(source, stream, source_id);
274
+ -- Source-scoped replay is also id-ordered. Without this access path SQLite
275
+ -- materializes the complete source history into a temporary order-by tree
276
+ -- before yielding the first bounded worker batch (WO-ELOG-SOURCE-ORDER-001).
277
+ CREATE INDEX IF NOT EXISTS idx_events_source_id ON events(source, id);
278
+ CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind);
279
+ -- (kind, id): a kind-filtered scan with an afterSeq floor (the obligations
280
+ -- miner's shape \u2014 message kinds over a 14-day window) must SEEK each kind to
281
+ -- the floor instead of walking that kind's full history (P1.1: 660ms \u2192 ~30ms
282
+ -- on the owner twin).
283
+ CREATE INDEX IF NOT EXISTS idx_events_kind_id ON events(kind, id);
284
+ CREATE INDEX IF NOT EXISTS idx_events_segment_line ON events(segment, line);
285
+ -- THE dedup index (I-1): unbounded, partial over unique-key revOrder streams
286
+ -- (head-compare chains legitimately revisit a rev on genuine A->B->A reversions).
287
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_nk ON events(source, stream, source_id, rev) WHERE unique_nk = 1;
288
+ CREATE TABLE IF NOT EXISTS pending_refs (
289
+ from_id TEXT NOT NULL, rel TEXT NOT NULL,
290
+ source TEXT NOT NULL, stream TEXT NOT NULL, source_id TEXT NOT NULL
291
+ );
292
+ CREATE INDEX IF NOT EXISTS idx_pending_target ON pending_refs(source, stream, source_id);
293
+ CREATE TABLE IF NOT EXISTS resolved_refs (
294
+ from_id TEXT NOT NULL, rel TEXT NOT NULL, to_id TEXT NOT NULL
295
+ );
296
+ CREATE TABLE IF NOT EXISTS claims (
297
+ from_id TEXT NOT NULL, rel TEXT NOT NULL, ns TEXT NOT NULL, value TEXT NOT NULL
298
+ );
299
+ CREATE TABLE IF NOT EXISTS tombstones (
300
+ source TEXT NOT NULL, stream TEXT NOT NULL, source_id TEXT NOT NULL, rev TEXT NOT NULL,
301
+ content_hash TEXT NOT NULL, tomb_id TEXT NOT NULL, future_too INTEGER NOT NULL DEFAULT 0,
302
+ ts TEXT NOT NULL, kind TEXT NOT NULL,
303
+ PRIMARY KEY (source, stream, source_id, rev)
304
+ );
305
+ CREATE TABLE IF NOT EXISTS rebinds (
306
+ from_source TEXT NOT NULL, from_stream TEXT NOT NULL, from_source_id TEXT NOT NULL,
307
+ to_source TEXT NOT NULL, to_stream TEXT NOT NULL, to_source_id TEXT NOT NULL,
308
+ event_id TEXT NOT NULL,
309
+ PRIMARY KEY (from_source, from_stream, from_source_id)
310
+ );
311
+ CREATE TABLE IF NOT EXISTS unknown_kinds (
312
+ source TEXT NOT NULL, kind TEXT NOT NULL, first_event_id TEXT NOT NULL,
313
+ PRIMARY KEY (source, kind)
314
+ );
315
+ CREATE TABLE IF NOT EXISTS blob_refs (
316
+ sha256 TEXT PRIMARY KEY, refcount INTEGER NOT NULL
317
+ );
318
+ CREATE TABLE IF NOT EXISTS erasure_jobs (
319
+ job_id TEXT PRIMARY KEY, state TEXT NOT NULL, request TEXT NOT NULL,
320
+ scope TEXT, last_completed TEXT, error TEXT,
321
+ requested_ts TEXT NOT NULL, updated_ts TEXT NOT NULL
322
+ );
323
+ CREATE TABLE IF NOT EXISTS segments (
324
+ segment TEXT PRIMARY KEY, file TEXT NOT NULL, sealed INTEGER NOT NULL,
325
+ rewrite_gen INTEGER NOT NULL, count INTEGER NOT NULL
326
+ );
327
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
328
+ INSERT OR IGNORE INTO meta (key, value) VALUES ('projection-epoch', '0');
329
+ -- Semantic row substitution cannot hide behind unchanged counts/watermarks. All
330
+ -- event-row writes mark the projection dirty; the sole event-log writer clears the
331
+ -- marker in the same transaction only after segment+twin accounting is complete.
332
+ CREATE TRIGGER IF NOT EXISTS trg_events_insert_dirty AFTER INSERT ON events BEGIN
333
+ INSERT OR REPLACE INTO meta (key, value) VALUES ('twin-dirty', 'events-inserted-outside-complete-fold');
334
+ END;
335
+ CREATE TRIGGER IF NOT EXISTS trg_events_update_dirty AFTER UPDATE ON events BEGIN
336
+ INSERT OR REPLACE INTO meta (key, value) VALUES ('twin-dirty', 'events-updated-outside-complete-fold');
337
+ END;
338
+ CREATE TRIGGER IF NOT EXISTS trg_events_delete_dirty AFTER DELETE ON events BEGIN
339
+ INSERT OR REPLACE INTO meta (key, value) VALUES ('twin-dirty', 'events-deleted-outside-complete-fold');
340
+ END;
341
+ -- Existing-row changes can occur below an unchanged append watermark. Separate,
342
+ -- versioned triggers install on legacy twins whose dirty triggers already exist.
343
+ CREATE TRIGGER IF NOT EXISTS trg_events_update_projection_epoch_v1 AFTER UPDATE ON events BEGIN
344
+ UPDATE meta SET value = CAST(value AS INTEGER) + 1 WHERE key = 'projection-epoch';
345
+ END;
346
+ CREATE TRIGGER IF NOT EXISTS trg_events_delete_projection_epoch_v1 AFTER DELETE ON events BEGIN
347
+ UPDATE meta SET value = CAST(value AS INTEGER) + 1 WHERE key = 'projection-epoch';
348
+ END;
349
+ `;var MH=E(()=>{f();W1();HH=new WeakMap});var Lz=8,PH=256,Dz=1024,Mz=5000,y9=30000,Pz=10;function LQ($){if($===void 0)return;try{$.terminate()}catch(Z){}}function i0($,Z){return v({code:$,layer:"storage",retryability:$==="invalid_argument"?"non-retryable":"transient",message:Z})}function sC($){return $.code==="unavailable"&&iC.has($.message)}class CH{released=!1;release(){if(this.released)return;this.released=!0,Cz--}}function J1(){if(Cz>=Lz)return i0("resource_exhausted",`event-log read connection cap reached (${Lz}); no connection was opened`);return Cz++,H(new CH)}class Fz{worker;queued=[];pending=null;terminalError=null;constructor($){this.worker=$;$.onmessage=(Z)=>{let Q=this.pending;if(Q!==null)this.pending=null,Q.resolve(Z.data);else this.queued.push(Z.data)},$.onerror=(Z)=>{let Q=Error(Z.message||"event-log read worker crashed");this.terminalError=Q;let X=this.pending;if(X!==null)this.pending=null,X.reject(Q)}}receive(){let $=this.queued.shift();if($!==void 0)return Promise.resolve($);if(this.terminalError!==null)return Promise.reject(this.terminalError);if(this.pending!==null)return Promise.reject(Error("event-log read worker protocol has two pending receives"));return new Promise((Z,Q)=>{this.pending={resolve:Z,reject:Q}})}}async function DQ($){let Z;try{return await Promise.race([$.receive(),new Promise((Q,X)=>{Z=setTimeout(()=>X(Error(`event-log read worker timed out after ${Mz}ms`)),Mz)})])}finally{if(Z!==void 0)clearTimeout(Z)}}function G1($,Z){if($ instanceof l$)return $;if($ instanceof SyntaxError)return new l$({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${Z}: malformed JSON in synchronized event metadata`});return new l$({code:"unavailable",layer:"storage",retryability:"transient",message:`${Z}: ${$ instanceof Error?$.message:String($)}`})}class MQ{mailbox;permit;idleTimeoutMs;onIdleExpiry;generation;terminal=!1;terminalFailure=null;idleTimer;idleLeaseEpoch=0;expiry=null;constructor($,Z,Q,X,z){this.mailbox=$;this.permit=Z;this.idleTimeoutMs=Q;this.onIdleExpiry=X;this.generation=z;this.armIdleLease()}static async open($,Z=y9,Q){let X=J1();if(!K(X))return X;let z=X.ok,Y=null;try{for(let j=0;j<2;j++){Y=new Fz(new Worker(new URL("./read-worker.ts",import.meta.url).href)),Y.worker.postMessage($);let W=await DQ(Y);if(W.type==="failure"){if(LQ(Y.worker),j===0&&sC(W.error)){Y=null,await new Promise((V)=>setTimeout(V,10));continue}return z.release(),{err:W.error}}if(W.type!=="ready")return LQ(Y.worker),z.release(),i0("internal",`event-log read worker returned '${W.type}' while opening a scan`);return H(new MQ(Y,z,Z,Q,W.generation))}return z.release(),i0("internal","event-log read worker exhausted its bounded open retry")}catch(j){return LQ(Y?.worker),z.release(),i0("unavailable",`event-log read worker open failed: ${j instanceof Error?j.message:String(j)}`)}}async nextBatch(){if(this.clearIdleLease(),this.expiry!==null)await this.expiry;if(this.terminalFailure!==null)return{err:this.terminalFailure};if(this.terminal)return H({rows:[],done:!0});try{this.mailbox.worker.postMessage({type:"next"});let $=await DQ(this.mailbox);if($.type==="failure")return this.finish(),{err:$.error};if($.type!=="batch")return this.finish(),i0("internal",`event-log read worker returned '${$.type}' while stepping a scan`);if($.done)this.finish();else this.armIdleLease();return H({rows:$.rows,done:$.done})}catch($){return this.finish(),i0("unavailable",`event-log read worker step failed: ${$ instanceof Error?$.message:String($)}`)}}renewIdleLease(){if(this.terminalFailure!==null)return{err:this.terminalFailure};if(this.terminal)return H(!0);return this.clearIdleLease(),this.armIdleLease(),H(!0)}async close(){if(this.clearIdleLease(),this.expiry!==null)await this.expiry;if(this.terminalFailure!==null)return{err:this.terminalFailure};if(this.terminal)return H(!0);try{this.mailbox.worker.postMessage({type:"close"});let $=await DQ(this.mailbox);if(this.finish(),$.type==="failure")return{err:$.error};if($.type!=="closed")return i0("internal",`event-log read worker returned '${$.type}' while closing a scan`);return H(!0)}catch($){return this.finish(),i0("unavailable",`event-log read worker close failed: ${$ instanceof Error?$.message:String($)}`)}}finish(){this.clearIdleLease(),this.terminal=!0,LQ(this.mailbox.worker),this.permit.release()}armIdleLease(){if(this.terminal||this.idleTimer!==void 0)return;let $=++this.idleLeaseEpoch;this.idleTimer=setTimeout(()=>this.expireLeaseIfCurrent($),this.idleTimeoutMs)}expireLeaseIfCurrent($){if($!==this.idleLeaseEpoch)return;this.idleTimer=void 0,this.expireIdleLease()}clearIdleLease(){if(this.idleLeaseEpoch++,this.idleTimer===void 0)return;clearTimeout(this.idleTimer),this.idleTimer=void 0}expireIdleLease(){if(this.terminal||this.expiry!==null)return;this.terminalFailure={code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:`event-log read session idle lease expired after ${this.idleTimeoutMs}ms; transaction closed`},this.expiry=this.closeExpiredWorker();try{this.onIdleExpiry?.(this.terminalFailure,this.generation)}catch($){this.terminalFailure={...this.terminalFailure,message:`${this.terminalFailure.message}; expiry observer failed`,cause:{code:"internal",layer:"storage",retryability:"non-retryable",message:$ instanceof Error?$.message:String($)}}}}async closeExpiredWorker(){try{this.mailbox.worker.postMessage({type:"close"});let $=await DQ(this.mailbox);if($.type==="failure")this.terminalFailure={...this.terminalFailure,message:`${this.terminalFailure.message}; worker cleanup failed`,cause:$.error};else if($.type!=="closed")this.terminalFailure={...this.terminalFailure,message:`${this.terminalFailure.message}; worker returned '${$.type}' during cleanup`}}catch($){this.terminalFailure={...this.terminalFailure,message:`${this.terminalFailure.message}; cleanup transport failed`,cause:{code:"unavailable",layer:"storage",retryability:"transient",message:$ instanceof Error?$.message:String($)}}}finally{this.finish()}}}async function FH($){let Z=J1();if(!K(Z))return Z;let Q=Z.ok,X=null;try{X=new Fz(new Worker(new URL("./read-worker.ts",import.meta.url).href)),X.worker.postMessage({type:"open",operation:"generation",dbPath:$});let z=await DQ(X);if(z.type==="failure")return{err:z.error};if(z.type!=="generation")return i0("internal",`event-log read worker returned '${z.type}' for a generation read`);return H(z.generation)}catch(z){return i0("unavailable",`event-log generation read failed: ${z instanceof Error?z.message:String(z)}`)}finally{LQ(X?.worker),Q.release()}}var Cz=0,iC,l$;var NH=E(()=>{f();iC=new Set(["event-log read open failed: file is not a database","event-log read open failed: Cannot use a closed database","event-log read open failed: cannot start a transaction within a transaction"]);l$=class l$ extends Error{structuredError;constructor($){super($.message);this.structuredError=$;this.name="EventLogReadError"}}});import{closeSync as RH,constants as Nz,fstatSync as PQ,fsyncSync as Az,lstatSync as OH,openSync as Oz,readSync as oC,writeSync as aC}from"fs";import{dirname as xH,join as rC}from"path";import{dlopen as Tz,ptr as f8,read as AH}from"bun:ffi";function LF(){if(k8!==null)return k8;if(process.platform==="darwin"){let $=Tz("/usr/lib/libSystem.B.dylib",{flock:{args:["i32","i32"],returns:"i32"},__error:{args:[],returns:"ptr"}});return k8=(Z,Q)=>{let X=$.symbols.flock(Z,Q),z=X===0?null:$.symbols.__error();return{result:X,errno:z===null?0:AH.i32(z)}},k8}if(process.platform==="linux"){let $=Tz("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}});return k8=(Z,Q)=>{let X=$.symbols.flock(Z,Q),z=X===0?null:$.symbols.__errno_location();return{result:X,errno:z===null?0:AH.i32(z)}},k8}throw Error(`writer-lock advisory flock is unsupported on ${process.platform}`)}function yH($,Z){return LF()($,Z)}function E9(){if(L1!==null)return L1;let $=Tz("kernel32.dll",{CreateFileW:{args:["ptr","u32","u32","ptr","u32","u32","ptr"],returns:"i64"},LockFileEx:{args:["i64","u32","u32","u32","u32","ptr"],returns:"bool"},UnlockFileEx:{args:["i64","u32","u32","u32","ptr"],returns:"bool"},SetFilePointerEx:{args:["i64","i64","ptr","u32"],returns:"bool"},ReadFile:{args:["i64","ptr","u32","ptr","ptr"],returns:"bool"},GetFileInformationByHandle:{args:["i64","ptr"],returns:"bool"},CloseHandle:{args:["i64"],returns:"bool"},GetLastError:{args:[],returns:"u32"}});return L1={createFile:(Z)=>$.symbols.CreateFileW(f8(Z),WF,VF,null,KF,qF|JF|GF,null),lockFile:(Z,Q,X)=>$.symbols.LockFileEx(Z,Q,0,_H,0,f8(X)),unlockFile:(Z,Q)=>$.symbols.UnlockFileEx(Z,0,_H,0,f8(Q)),setFilePointer:(Z,Q)=>$.symbols.SetFilePointerEx(Z,Q,null,0),readFile:(Z,Q,X)=>$.symbols.ReadFile(Z,f8(Q),Q.byteLength,f8(X),null),fileIdentity:(Z,Q)=>$.symbols.GetFileInformationByHandle(Z,f8(Q)),closeHandle:(Z)=>$.symbols.CloseHandle(Z),lastError:()=>$.symbols.GetLastError()},L1}function EH($){if($.includes("\x00"))throw Error("writer-lock path contains an embedded NUL");return Buffer.from(`${$}\x00`,"utf16le")}function DF($,Z,Q){let X=Buffer.alloc(52);if(!$.fileIdentity(Z,X))return!1;return y$(j0(X),Q)}function CQ($,Z){let Q=Buffer.alloc(52);return $.fileIdentity(Z,Q)?Q:null}function P1($){let Z=$.readUInt32LE(0);return(Z&HF)===0&&(Z&BF)===0}function TH($){return BigInt($.readUInt32LE(32))<<32n|BigInt($.readUInt32LE(36))}function M1($){if($.nativeHandle===null)return null;let Z=$.nativeHandle;$.nativeHandle=null;let Q=E9();if(Q.closeHandle(Z))return null;return`native writer-lock handle ${Z} close failed with Windows error ${Q.lastError()}`}function MF($,Z){if($.nativeHandle===null)return B$("writer-lock native receipt read received a closed handle");let Q=E9();if(!Q.setFilePointer($.nativeHandle,0n))return B$(`events/log/.writer.lock native receipt seek failed with Windows error ${Q.lastError()}`);let X=Buffer.alloc(Z),z=0;while(z<X.length){let Y=X.subarray(z),j=Buffer.alloc(4);if(!Q.readFile($.nativeHandle,Y,j))return B$(`events/log/.writer.lock native receipt read failed with Windows error ${Q.lastError()}`);let W=j.readUInt32LE(0);if(W<=0||W>Y.length)return B$(`events/log/.writer.lock short native receipt read at ${z}/${X.length}`);z+=W}return H(X)}function vH($,Z={}){if(process.platform!=="win32"){if($.fd===null)return{result:-1,errno:9};return yH($.fd,$F|ZF)}let Q=E9(),X=$.nativeHandle;if(X===null){if(X=Q.createFile(EH($.path)),X===IH)return{result:-1,errno:Q.lastError()};$.nativeHandle=X}let z=CQ(Q,X);if(z===null||!P1(z)||!y$(j0(z),$)){let j=Q.lastError(),W=M1($);return{result:-1,errno:j||1168,...W===null?{}:{cleanup:W}}}let Y=Buffer.alloc(32);if(!Q.lockFile(X,zF|YF,Y)){let j=Q.lastError(),W=M1($);return{result:-1,errno:j===jF?13:j,...W===null?{}:{cleanup:W}}}try{if(Z.beforeLockedPathCheck?.($),DF(Q,X,$)&&c5($))return{result:0,errno:0};let j=Sz($,$.fd);return{result:-1,errno:1168,detail:"post-lock exact descriptor/path identity was lost",...j.length===0?{}:{cleanup:j.join("; ")}}}catch(j){let W=Sz($,$.fd);return{result:-1,errno:1168,detail:`post-lock ownership proof failed: ${String(j)}`,...W.length===0?{}:{cleanup:W.join("; ")}}}}function Sz($,Z){if(process.platform!=="win32"){if(Z===null)return["advisory unlock failed: writer-lock descriptor is absent"];try{let Y=yH(Z,QF);return Y.result===0?[]:[`descriptor ${Z} advisory unlock failed with errno ${Y.errno}`]}catch(Y){return[`descriptor ${Z} advisory unlock failed: ${String(Y)}`]}}if($.nativeHandle===null)return[`descriptor ${String(Z)} advisory unlock failed: native writer-lock handle is absent`];let Q=E9(),X=[];if(!Q.unlockFile($.nativeHandle,Buffer.alloc(32)))X.push(`native writer-lock handle ${$.nativeHandle} advisory unlock failed with Windows error ${Q.lastError()}`);let z=M1($);if(z!==null)X.push(z);return X}function B$($){return v({code:"unavailable",layer:"storage",retryability:"transient",message:$})}function v0($){return v({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:$})}function c5($,Z=$.path){try{let Q=OH(Z,{bigint:!0});return Q.isFile()&&y$(Q,$)}catch(Q){if(Q.code==="ENOENT")return!1;throw Q}}function xz($){try{return RH($),null}catch(Z){return`descriptor ${$} close failed: ${String(Z)}`}}function c$($,Z){if($.fd===null&&$.nativeHandle===null)return[];let Q=$.fd;$.fd=null;let X=[];if(Z)X.push(...Sz($,Q));else{let z=M1($);if(z!==null)X.push(z)}if(Q!==null){let z=xz(Q);if(z!==null)X.push(z)}return X}function _z($){let Z=null,Q=null,X=null,z=xH($);try{Z=Oz(z,"r"),n3(Z,z)}catch(Y){Q=Y}finally{if(Z!==null)try{RH(Z)}catch(Y){X=Y}}if(Q===null&&X===null)return null;return`writer-lock directory sync failed: ${String(Q??X)}`}function PF($,Z){let Q=0;while(Q<Z.length){let X=aC($,Z,Q,Z.length-Q,Q);if(X<=0)throw Error(`writer-lock short write at ${Q}/${Z.length}`);Q+=X}}function Rz($){try{if(process.platform==="win32"){if($.nativeHandle===null)return B$("writer-lock receipt read received a closed native handle");let Y=E9(),j=CQ(Y,$.nativeHandle);if(j===null||!P1(j))return v0("events/log/.writer.lock is nonregular or its native identity is unavailable");let W=TH(j);if(W>BigInt(U1))return v0(`events/log/.writer.lock exceeds ${U1} bytes; preserving it`);let V=MF($,Number(W));if(!("ok"in V))return V;let q=CQ(Y,$.nativeHandle);if(q===null||!y$(j0(j),j0(q))||TH(q)!==W||!j.subarray(20,28).equals(q.subarray(20,28))||!c5($))return B$("events/log/.writer.lock changed while its descriptor receipt was read");return H(V.ok.toString("utf8"))}if($.fd===null)return B$("writer-lock receipt read received a closed descriptor");let Z=PQ($.fd,{bigint:!0});if(!Z.isFile()||Z.size>BigInt(U1))return v0(`events/log/.writer.lock is nonregular or exceeds ${U1} bytes; preserving it`);let Q=Buffer.alloc(Number(Z.size)),X=0;while(X<Q.length){let Y=oC($.fd,Q,X,Q.length-X,X);if(Y<=0)return B$(`events/log/.writer.lock short receipt read at ${X}/${Q.length}`);X+=Y}let z=PQ($.fd,{bigint:!0});if(!y$(Z,z)||Z.size!==z.size||Z.mtimeNs!==z.mtimeNs||Z.ctimeNs!==z.ctimeNs||!c5($))return B$("events/log/.writer.lock changed while its descriptor receipt was read");return H(Q.toString("utf8"))}catch(Z){return B$(`events/log/.writer.lock descriptor read failed: ${String(Z)}`)}}function CF($){try{let Z=JSON.parse($);if(typeof Z.pid!=="number"||!Number.isSafeInteger(Z.pid)||Z.pid<=0)return null;return{pid:Z.pid}}catch{return null}}function FF($){if($===process.pid)return H(!1);try{return process.kill($,0),H(!1)}catch(Z){if(Z.code==="ESRCH")return H(!0);return v0(`events/log/.writer.lock legacy holder pid ${$} liveness is indeterminate; preserving it: ${String(Z)}`)}}function W0($,Z){let Q="err"in $?$:B$($.empty.how);if(Z.length===0)return Q;return B$(`${Q.err.message}; cleanup failures: ${Z.join("; ")}`)}function NF($,Z){if(process.platform==="win32"){let z=E9(),Y=z.createFile(EH($));if(Y===IH){let q=z.lastError();if(q===2||q===3)return{retry:!0};try{if(!OH($,{bigint:!0}).isFile())return v0("events/log/.writer.lock is a nonregular or reparse path; preserving it")}catch(B){if(B.code==="ENOENT")return{retry:!0}}return B$(`events/log/.writer.lock native no-follow open failed with Windows error ${q}`)}let j=CQ(z,Y);if(j===null){let q={path:$,fd:null,nativeHandle:Y,dev:0n,ino:0n};return W0(B$(`events/log/.writer.lock native identity query failed with Windows error ${z.lastError()}`),c$(q,!1))}let W=j0(j),V={path:$,fd:null,nativeHandle:Y,...W};try{if(Z.beforeCandidatePathCheck?.(V),!P1(j)||!c5(V))return W0(v0("events/log/.writer.lock is not one stable no-follow regular inode; preserving it"),c$(V,!1));return{ok:{owned:V}}}catch(q){return W0(B$(`events/log/.writer.lock native descriptor open failed: ${String(q)}`),c$(V,!1))}}let Q=null,X=null;try{let z=Nz.O_RDWR|Nz.O_NONBLOCK|Nz.O_NOFOLLOW;try{Q=Oz($,z)}catch(j){let W=j.code;if(W==="ENOENT")return{retry:!0};if(W==="ELOOP"||W==="EISDIR"||W==="ENXIO")return v0(`events/log/.writer.lock is a nonregular path; preserving it: ${String(j)}`);return B$(`events/log/.writer.lock no-follow open failed: ${String(j)}`)}let Y=PQ(Q,{bigint:!0});if(X={path:$,fd:Q,nativeHandle:null,dev:Y.dev,ino:Y.ino},Z.beforeCandidatePathCheck?.(X),!Y.isFile()||!c5(X)){Q=null;let j=c$(X,!1);return W0(v0("events/log/.writer.lock is not one stable regular inode; preserving it"),j)}return Q=null,{ok:{owned:X}}}catch(z){let Y;if(X!==null)Y=c$(X,!1),Q=null;else Y=Q===null?[]:[xz(Q)].filter((j)=>j!==null);return W0(B$(`events/log/.writer.lock descriptor open failed: ${String(z)}`),Y)}}function SH($,Z,Q){let X=Math.random().toString(36).slice(2,10)||"0";return rC(xH($),`.writer-lock-init.${process.pid}.${Date.now().toString(36)}.${X}${Z.toString(36)}${Q.toString(36)}.receipt`)}function AF($,Z,Q){let X=SH($,Z,0),z=null,Y=null,j=!1;try{for(let P=0;P<eC;P++){X=SH($,Z,P);try{z=Oz(X,"wx+",384);break}catch(F){if(F.code==="EEXIST")continue;throw F}}if(z===null)throw Error("writer-lock initialization exhausted exclusive receipt names");let W=PQ(z,{bigint:!0});if(Y={path:X,fd:z,nativeHandle:null,dev:W.dev,ino:W.ino},Q.beforeCandidatePathCheck?.(Y),!W.isFile()||!c5(Y))throw Error(`writer-lock initialization receipt ${X} is not its opened regular inode`);z=null,PF(Y.fd,UF),Az(Y.fd);let V=vH(Y,Q);if(V.result!==0)throw Error(`private writer-lock initialization advisory lock failed with errno ${V.errno}${V.detail===void 0?"":`; ${V.detail}`}${V.cleanup===void 0?"":`; ${V.cleanup}`}`);j=!0,Q.beforeInitialPublish?.(Y);let q=Rz(Y);if(!("ok"in q)||q.ok!==D1){let P="err"in q?q.err.message:("empty"in q)?q.empty.how:"private initialization receipt bytes are not the canonical sentinel";throw Error(`writer-lock private initialization proof failed: ${P}`)}let B=null;try{G0(X,$)}catch(P){if(P instanceof F$&&P.moved)B=String(P);else if(P instanceof F$&&P.errno===17){let F=_z(X),A=c$(Y,!0);if(F!==null)A.push(F);if(A.length>0)return B$(`writer-lock initialization collision retained ${X}; cleanup failed: ${A.join("; ")}`);return{collision:!0}}else throw P}let G={path:$,fd:Y.fd,nativeHandle:Y.nativeHandle,dev:Y.dev,ino:Y.ino};Y.fd=null,Y.nativeHandle=null;let J=d5(G),U=Rz(G),L=_z($),D=!("ok"in U)||U.ok!==D1;if(!("ok"in J)||D||L!==null||B!==null){let P=c$(G,!0),F=[!("ok"in J)?"err"in J?J.err.message:J.empty.how:null,D?"err"in U?U.err.message:("empty"in U)?U.empty.how:"published receipt bytes are not the canonical sentinel":null,L,B,...P].filter((A)=>A!==null);return B$(`writer-lock initialization publication failed: ${F.join("; ")}`)}return{ok:G}}catch(W){let V=[];if(Y!==null){if(Y.fd!==null)try{Az(Y.fd)}catch(B){V.push(`initialization receipt fsync failed: ${String(B)}`)}V.push(...c$(Y,j)),z=null}else if(z!==null){try{Az(z)}catch(G){V.push(`initialization receipt fsync failed: ${String(G)}`)}let B=xz(z);if(B!==null)V.push(B);z=null}let q=_z(X);if(q!==null)V.push(q);return B$(`writer-lock initialization retained ${X}: ${String(W)}${V.length===0?"":`; cleanup failures: ${V.join("; ")}`}`)}}function d5($){try{if(process.platform==="win32"){if($.nativeHandle===null)return B$("writer-lock ownership native descriptor is closed");let Q=E9(),X=CQ(Q,$.nativeHandle);if(X===null||!P1(X)||!y$(j0(X),$)||!c5($))return B$("events/log/.writer.lock no longer names the locked descriptor inode");return H(!0)}if($.fd===null)return B$("writer-lock ownership descriptor is closed");let Z=PQ($.fd,{bigint:!0});if(!Z.isFile()||!y$(Z,$)||!c5($))return B$("events/log/.writer.lock no longer names the locked descriptor inode");return H(!0)}catch(Z){return B$(`events/log/.writer.lock ownership proof failed: ${String(Z)}`)}}function C1($,Z,Q){try{Z.beforeMutationOwnershipCheck?.(Q,$)}catch(X){return B$(`writer-lock ${Q} ownership hook failed: ${String(X)}`)}return d5($)}function bH($,Z={}){for(let Q=0;Q<tC;Q++){let X=NF($,Z);if("retry"in X){let j=AF($,Q,Z);if("collision"in j)continue;if("ok"in j)return H(j.ok);return j}if(!("ok"in X))return X;let{owned:z}=X.ok,Y=!1;try{let j=vH(z,Z);if(j.result!==0){let J=c$(z,!1);if(j.cleanup!==void 0)J.unshift(j.cleanup);let U=XF.has(j.errno)?v0("events/log/.writer.lock is held by another writer; a second appender fails loudly and never queues"):B$(`events/log/.writer.lock advisory acquisition failed with errno ${j.errno}${j.detail===void 0?"":`; ${j.detail}`}`);return W0(U,J)}Y=!0;let W=d5(z);if(!("ok"in W))return W0(W,c$(z,!0));let V=Rz(z);if(!("ok"in V))return W0(V,c$(z,!0));if(V.ok===D1)return H(z);let q=CF(V.ok);if(q===null)return W0(v0("events/log/.writer.lock has a malformed bounded receipt; preserving it"),c$(z,!0));let B=FF(q.pid);if(!("ok"in B))return W0(B,c$(z,!0));if(!B.ok)return W0(v0(`events/log/.writer.lock legacy receipt names live pid ${q.pid}; refusing mixed-version ownership`),c$(z,!0));Z.beforeOwnershipCheck?.("stale-reclaim",z);let G=d5(z);if(!("ok"in G))return W0(G,c$(z,!0));return H(z)}catch(j){return W0(B$(`events/log/.writer.lock advisory acquisition failed: ${String(j)}`),c$(z,Y))}}return B$("events/log/.writer.lock disappeared during every bounded acquisition attempt")}function Iz($,Z={}){if($.fd===null&&$.nativeHandle===null)return B$("writer-lock release received an already-closed ownership descriptor");let Q;try{Z.beforeOwnershipCheck?.("release",$),Q=d5($),Z.afterOwnershipCheck?.("release",$,$.path);let z=d5($);if(!("ok"in z))Q=z}catch(z){Q=B$(`writer-lock release failed before unlock: ${String(z)}`)}let X=c$($,!0);if(!("ok"in Q))return W0(Q,X);if(X.length>0)return B$(`writer-lock release failed: ${X.join("; ")}`);return H(!0)}var tC=3,eC=100,U1=4096,$F=2,ZF=4,QF=8,XF,_H=1,zF=1,YF=2,jF=33,WF=3221225472,VF=7,KF=3,qF=128,HF=16,BF=1024,JF=33554432,GF=2097152,IH,D1=`{"kind":"indra-writer-lock-sentinel","version":1}
350
+ `,UF,k8=null,L1=null;var gH=E(()=>{f();ZQ();Zz();XF=new Set([11,13,35]),IH=-1n,UF=Buffer.from(D1)});import{existsSync as F1,mkdirSync as fH,openSync as yz,closeSync as gz,fstatSync as N1,fsyncSync as kH,lstatSync as fz,readdirSync as Ez,readSync as _F,statfsSync as TF,statSync as wH,writeSync as SF}from"fs";import{basename as FQ,dirname as _1,join as _$,resolve as RF}from"path";import{fileURLToPath as OF}from"url";import{isDeepStrictEqual as K5}from"util";import{Database as xF,constants as IF}from"bun:sqlite";function sH($){return`event '${$}' is erased \u2014 tombstone retained; erased is not never-existed`}function n($,Z,Q="non-retryable",X="storage"){return v({code:$,layer:X,retryability:Q,message:Z})}function bF($,Z){if($!==null&&typeof $==="object"&&$.kind==="user")return!0;return Array.isArray(Z)&&Z.some((Q)=>{if(Q===null||typeof Q!=="object")return!1;let X=Q.kind;return typeof X==="string"&&(X.startsWith("erasure.")||X.startsWith("action."))})}function Y$($,Z){let Q=$(Z);if(K(Q))return;let X="err"in Q?Q.err:{code:"unavailable",layer:"storage",retryability:"transient",message:Q.empty.how};throw Object.assign(Error(`${Z}: ${X.message}`),{code:"ESTALE",structured:X})}function gF($){let Z=[];try{for(let Q of["","-wal","-shm"]){let X=$+Q;Z.push({path:X,expected:O9(X,"dead twin canonical family")})}return{basePath:$,members:Z}}catch(Q){let X=Z.flatMap((z)=>t$(z.expected));throw Object.assign(Error(`dead twin canonical family binding failed: ${String(Q)}${X.length===0?"":`; descriptor cleanup failed: ${X.join(" | ")}`}`),{code:"ESTALE"})}}function v9($){return $.members.flatMap((Z)=>t$(Z.expected))}function q5($,Z=$.path){try{let Q=fz(Z);return Q.isFile()&&Q.dev===$.dev&&Q.ino===$.ino}catch(Q){if(Q.code==="ENOENT")return!1;throw Q}}function R$($){let Z={code:"unavailable",layer:"storage",retryability:"transient",message:$};return Object.assign(Error($),{code:"ESTALE",structured:Z})}function NQ($,Z,Q,X=Z.path){let z=new Int32Array(1),Y=$.fileControl("main",IF.SQLITE_FCNTL_HAS_MOVED,z);if(Y!==0)throw Object.assign(R$(`${Q}: SQLite main-file movement probe failed with code ${Y}`),{code:"SQLITE_IOERR"});if(z[0]!==0||!q5(Z,X))throw R$(`${Q}: SQLite main file moved or its reserved pathname was replaced`)}function pH($,Z){for(let Q of["-wal","-shm"]){let X=$+Q,z;try{z=fz(X)}catch(j){if(j.code==="ENOENT")continue;throw j}if(!z.isFile())throw R$(`shadow sidecar ${X} is not a regular file`);let Y=Z.get(X);if(Y!==void 0&&!q5(Y))throw R$(`shadow sidecar ${X} changed identity`);if(Y===void 0)Z.set(X,{path:X,fd:null,nativeHandle:null,dev:z.dev,ino:z.ino})}}function vz($){let Z=[];for(let Q of[$,...$.sidecars.values()]){if(Q.fd===null)continue;try{gz(Q.fd),Q.fd=null}catch(X){Z.push(X)}}if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,`shadow family descriptor close failed for ${$.path}`)}function lH($,Z){for(let Q=0;Q<100;Q++){let X=Math.random().toString(36).slice(2,10)||"0",z=Q===0?Z:`${$}.unexpected-install.${process.pid}.${Date.now().toString(36)}.${X}.${Q}.receipt`,Y=null;try{G0($,z)}catch(W){if(W instanceof F$&&W.moved)Y=String(W);else if(W instanceof F$&&W.errno===17)continue;else if(W instanceof F$&&W.errno===2)return{retainedPath:null,durabilityWarning:null};else throw R$(`unexpected installed twin at ${$} could not be retained without overwrite: ${String(W)}`)}let j=null;try{l5(z)}catch(W){j=String(W)}return{retainedPath:z,durabilityWarning:[Y,j].filter((W)=>W!==null).join("; ")||null}}throw R$(`unexpected installed twin at ${$} exhausted retained audit names`)}function cH($){if($===void 0)return H(y9);if(!Number.isInteger($)||$<Pz||$>y9)return n("invalid_argument",`readSessionIdleMs must be an integer between ${Pz} and ${y9}`);return H($)}function dH($,Z){if($.kind==="connector")return{level:"untrusted",sources:[Z.source]};if($.kind==="user")return{level:"user",sources:[]};return{level:"system",sources:[]}}function nH($,Z){if($.kind==="user")return!0;return Z.some((Q)=>Q.startsWith("erasure.")||Q.startsWith("action."))}function fF($,Z){let Q=Number($),X=Number(Z);if(Number.isFinite(Q)&&Number.isFinite(X)&&Q!==X)return Q<X?-1:1;if(Number.isFinite(Q)&&Number.isFinite(X))return 0;return $<Z?-1:$>Z?1:0}function bz($,Z){return $<Z?-1:$>Z?1:0}function b0($){return"erasedKind"in $}class l{eventsDir;logDir;blobs;db;writer;streams;ulid;now;policyVersion;opts;writerLock;ownsWriterLock;readPermit;readSessionIdleMs;closed=!1;writeRecoveryRequired=!1;immediateAppendQueue=[];groupAppendQueue=[];appendQueueScheduled=!1;lastQueuedAppendClass="group";constructor($,Z,Q={}){this.opts=$,this.eventsDir=$.eventsDir??T1,this.logDir=_$(this.eventsDir,"log"),this.blobs=new O3(_$(this.eventsDir,"blobs")),this.db=Z,this.streams=e7($.streams??[]),this.now=$.now??(()=>new Date().toISOString()),this.ulid=V$(),this.policyVersion=$.policyVersion??(()=>1),this.writerLock=Q.writerLock??null,this.ownsWriterLock=this.writerLock!==null,this.readPermit=Q.readPermit??null,this.readSessionIdleMs=$.readSessionIdleMs??y9,this.writer=new l3(this.logDir,J8,this.now)}static open($={}){let Z=cH($.readSessionIdleMs);if(!K(Z))return Z;let Q=performance.now(),X=($.now??(()=>new Date().toISOString()))(),z=$.eventsDir??T1,Y=_$(z,"log");fH(Y,{recursive:!0}),fH(_$(z,"blobs"),{recursive:!0});let j=_$(Y,".writer.lock"),W=bH(j,$.writerLockRaceHooks);if(!K(W))return W;let V=(J)=>C1(W.ok,$.writerLockRaceHooks??{},J),q=null,B=!1,G;try{G=(()=>{let J=l.reclaimStaleCatalogs(Y,X,V,$.ownedPathRaceHooks,$.recoveryRaceHooks);if(!K(J))return J;let U=l.summarizeAllSegments(Y);if(!K(U))return U;let L=U.ok,D=L.filter((y)=>y.state==="sealed"),P=L.filter((y)=>y.state!=="sealed"),F=_$(Y,"log.db"),A=!1,N=P.map((y)=>`segment-${y.reason}`),S=()=>{let y=q;if(q=null,y===null)return H(!0);try{return y.close(),H(!0)}catch(b){return n("unavailable",`unreadable twin could not be closed before shadow recovery: ${String(b)}`,"transient")}};try{if(Y$(V,"twin-open-initialization"),q=Jz(F),L.length===0&&l.eventDerivedTwinIsEmpty(q))Y$(V,"empty-generation-authority-stamp"),q.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(w8,m8);let y=l.twinConsistency(q,D);if(y.reasons.includes("twin-consistency-probe-failed")){N.push(...y.reasons);let b=S();if(!K(b))return b;A=!1}else if(P.length===0&&y.reasons.length===1&&y.reasons[0]==="tomb-authority-proof-missing"){let g=l.verifySegmentsStreamingGeneration(Y,q,X,V,$.ownedPathRaceHooks);if(!K(g))return g;A=!0}else N.push(...y.reasons),A=P.length===0&&y.healthy}catch(y){A=!1,N.push("twin-open-failed");let b=S();if(!K(b))return b}let R=[],O,T="full-rebuild";if(!A){let y=JSON.stringify({ts:X,reasons:[...new Set(N)]});if(q!==null){Y$(V,"recovery-attempt-admission"),q.query("INSERT OR IGNORE INTO meta (key, value) VALUES ('open-recovery:attempt', ?)").run(y);let u=q.query("SELECT value FROM meta WHERE key = 'open-recovery:attempt'").get();if(u===null)return n("internal","event-log recovery attempt marker vanished after durable admission","transient");y=u.value}let b=e7($.streams??[]),g=[];for(let u of P){if(u.reason==="uncommitted-header"){Y$(V,"uncommitted-header-preservation");let o=VQ(u.path,"uncommitted-header",()=>{},u.fingerprint);if(!K(o))return o;R.push({segment:l.segmentIdOfSummaryPath(u.path),actions:["uncommitted-header-preserved"]});continue}let p=d0(u.path);if(!K(p))return p;if(p.ok.entries.length===0){Y$(V,"uncommitted-segment-preservation");let o=VQ(u.path,"uncommitted-segment",()=>{},p.ok.fingerprint);if(!K(o))return o;R.push({segment:p.ok.segmentId,actions:["uncommitted-segment-preserved"]});continue}g.push({path:p.ok.path,segmentId:p.ok.segmentId})}let w=l.recoverSealedGeneration(q,F,Y,D,b,X,y,q!==null&&!N.includes("twin-dirty"),$.now??(()=>new Date().toISOString()),g,V,$.recoveryRaceHooks,$.ownedPathRaceHooks);if(!K(w))return w;if(q=w.ok.db,O=w.ok.evidence,R.push(...w.ok.recovered),w.ok.evidence.dbAheadSurvivors>0)N.push("db-ahead-survivors")}if(!A)try{Y$(V,"open-recovery-trail"),l.recordOpenRecovery(q,X,performance.now()-Q,R,T,[...new Set(N.length>0?N:["strict-recovery-required"])],O)}catch(y){return n("internal",`event-log recovery succeeded but its twin trail write failed: ${String(y)}`,"transient")}let m=l.flushCatalogReclaimTrail(q,Y,V,$.ownedPathRaceHooks,$.recoveryRaceHooks);if(!K(m))return m;let k=new l({...$,readSessionIdleMs:Z.ok},q,{writerLock:W.ok}),d=k.verifySegmentsIfDue();if(!K(d))return d;return B=!0,H(k)})()}catch(J){G={err:U$(J,"event-log writer open failed",{code:"internal",retryability:"transient"})}}if(!B){let J=[];if(q!==null)try{q.close()}catch(L){J.push(`twin close failed: ${String(L)}`)}let U=Iz(W.ok,$.writerLockRaceHooks);if(!K(U))J.push("err"in U?U.err.message:U.empty.how);if(J.length>0){let L="err"in G?`${G.err.code}: ${G.err.message}`:("empty"in G)?`empty: ${String(G.empty.how)}`:"writer open did not transfer ownership";return n("unavailable",`event-log writer open failed (${L}); cleanup also failed: ${J.join("; ")}`,"transient")}}return G}static recordOpenRecovery($,Z,Q,X,z,Y,j){$.exec("BEGIN IMMEDIATE");try{let W=$.query("SELECT value FROM meta WHERE key = 'open-recovery:count'").get()?.value??"0";$.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('open-recovery:count', ?)").run(String(Number.parseInt(W,10)+1)),$.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('open-recovery:last', ?)").run(JSON.stringify({ts:Z,tookMs:Math.round(Q*10)/10,mode:z,reasons:Y,segments:X,evidence:j})),$.query("DELETE FROM meta WHERE key = 'open-recovery:attempt'").run(),$.exec("COMMIT")}catch(W){try{$.exec("ROLLBACK")}catch(V){}throw W}}openRecoveryTrail(){let $=this.db.query("SELECT value FROM meta WHERE key = 'open-recovery:count'").get()?.value;if($===void 0||$===null)return null;let Z=this.db.query("SELECT value FROM meta WHERE key = 'open-recovery:last'").get()?.value,Q=null;if(Z!==void 0&&Z!==null)Q=JSON.parse(Z);return{count:Number.parseInt($,10),last:Q}}static openReadOnly($={}){let Z=cH($.readSessionIdleMs);if(!K(Z))return Z;let Q=$.eventsDir??T1,X=_$(Q,"log","log.db");if(!F1(X))return n("unavailable",`event-log read-only twin missing at ${X} \u2014 ${iH}`,"transient");let z=J1();if(!K(z))return z;let Y=z.ok,j=null;try{if(j=new xF(X,{readonly:!0}),j.query("SELECT value FROM meta WHERE key = ?").get(b8)?.value!==g8)return j.close(),j=null,Y.release(),n("data_loss","event-log read-only twin codec is stale; segment-authoritative writer reopen is required");if(j.query("SELECT 1 AS present FROM meta WHERE key = 'twin-dirty'").get()!==null)return j.close(),j=null,Y.release(),n("data_loss","event-log read-only twin is dirty; no last-good content view exists until segment-authoritative reopen recovery");let V=l.validateTwinWatermark(j,"event-log read-only open");if(!K(V))return j.close(),j=null,Y.release(),V;let q=l.validateProjectionEpoch(j,"event-log read-only open");if(!K(q))return j.close(),j=null,Y.release(),q;let B=l.validateTombAuthorityVersion(j,"event-log read-only open");if(!K(B))return j.close(),j=null,Y.release(),B;let G=new l({...$,readOnly:!0,readSessionIdleMs:Z.ok},j,{readPermit:Y});return j=null,H(G)}catch(W){let V=null;if(j!==null)try{j.close()}catch(B){V=B}Y.release();let q=V===null?"":`; constructed handle close also failed: ${String(V)}`;return n("unavailable",`event-log read-only twin open failed at ${X}: ${W instanceof Error?W.message:String(W)}${q}`,"transient")}}static liveDbEvent($,Z){let Q=$.query("SELECT * FROM events WHERE id = ?").get(Z);if(Q===null||Q.erased!==0)return null;try{return V5(Q)}catch(X){let z={code:"data_loss",layer:"storage",retryability:"non-retryable",message:`synchronized event ${Z} has a malformed stored envelope: ${String(X)}`};throw Object.assign(Error(z.message),{code:"data_loss",structured:z})}}static eventDerivedTwinIsEmpty($){return vF.every((Z)=>$.query(`SELECT COUNT(*) AS c FROM ${Z}`).get().c===0)}static erasedRowMatchesTomb($,Z){let Q=[$.canon,$.observed_ts,$.trust,$.origin,$.tier,$.schema_version,$.policy_version,$.coverage,$.mentions,$.body,$.lang,$.payload,$.blobs,$.refs];return $.erased===1&&$.source===Z.nk.source&&$.stream===Z.nk.stream&&$.source_id===Z.nk.sourceId&&$.rev===Z.nk.rev&&$.ts===Z.ts&&$.kind===Z.kind&&$.content_hash===Z.contentHash&&$.tomb===Z.tomb&&Q.every((X)=>X===null)}static tombFromErasedRow($){if($.erased!==1||$.tomb===null||!q$($.id)||!q$($.tomb))return n("data_loss",`erased SQLite survivor ${$.id} has no canonical authorizing tomb id`);let Z={id:$.id,nk:{source:$.source,stream:$.stream,sourceId:$.source_id,rev:$.rev},ts:$.ts,kind:$.kind,contentHash:$.content_hash,tomb:$.tomb};return l.erasedRowMatchesTomb($,Z)?H(Z):n("data_loss",`erased SQLite survivor ${$.id} retains non-skeleton envelope content`)}static validateTombAuthorization($,Z,Q){let X=Z1($,Z);return X===null?H(!0):n("data_loss",`${Q}: tomb ${$.id} ${X}`)}static validateTwinTombGeneration($,Z){for(let z of Z.tombs()){if(z.source===null||z.stream===null||z.source_id===null||z.rev===null||z.ts===null||z.kind===null||z.content_hash===null||z.tomb===null)return n("data_loss",`segment verification found incomplete tomb skeleton ${z.id}`);let Y={id:z.id,nk:{source:z.source,stream:z.stream,sourceId:z.source_id,rev:z.rev},ts:z.ts,kind:z.kind,contentHash:z.content_hash,tomb:z.tomb},j=$.query("SELECT * FROM events WHERE id = ?").get(Y.id);if(j===null||!l.erasedRowMatchesTomb(j,Y))return n("data_loss",`segment verification found tomb ${Y.id} without an exact synchronized erased row`);let W;try{W=Z.authorizer(Y.tomb)}catch(B){return{err:U$(B,`segment verification could not decode raw authorizer ${Y.tomb}`,{code:"data_loss",retryability:"non-retryable"})}}let V=l.validateTombAuthorization(Y,W,"segment verification");if(!K(V))return V;let q=l.liveDbEvent($,Y.tomb);if(W===null||q===null||!K5(q,W))return n("data_loss",`segment verification found raw authorizer ${Y.tomb} without an exact synchronized live envelope`)}let Q=$.query("SELECT COUNT(*) AS c FROM events WHERE erased = 1").get().c,X=Z.tombCount();if(Q!==X)return n("data_loss",`segment verification found ${X} physical tombs but ${Q} synchronized erased rows`);return H(!0)}static validateTwinAuthorityAccounting($,Z,Q){let X=[...Q.segments()],z=$.query("SELECT segment, file, sealed, rewrite_gen, count FROM segments ORDER BY segment").all();if(z.length!==X.length)return n("data_loss",`segment verification found ${X.length} physical segments but ${z.length} twin segments`);let Y=new Map(z.map((L)=>[L.segment,L])),j=0,W=0;for(let L of X){let D=W5(_$(Z,L.file));if(!K(D))return D;if(D.ok.state!=="sealed"||D.ok.segmentId!==L.segment||D.ok.count!==L.count||D.ok.fingerprint!==L.fingerprint)return n("unavailable",`segment verification descriptor changed while checking twin accounting at ${L.file}`,"transient");let P=Y.get(L.segment);if(P===void 0||P.file!==L.file||P.sealed!==1||P.rewrite_gen!==D.ok.rewriteGen||P.count!==L.count)return n("data_loss",`segment verification twin accounting differs at ${L.file}`);if($.query("SELECT value FROM meta WHERE key = ?").get(l.segmentFingerprintKey(L.segment))?.value!==L.fingerprint)return n("data_loss",`segment verification twin fingerprint differs at ${L.file}`);j+=L.count,W+=D.ok.rewriteGen,Y.delete(L.segment)}if(Y.size!==0)return n("data_loss","segment verification twin contains unproved segment rows");let V=$.query("SELECT segment, line, erased FROM events WHERE id = ?"),q=0,B=b9;for(let L of Q.physicalRows()){let D=V.get(L.id);if(D===null||D.segment!==L.segment||D.line!==L.line||D.erased!==(L.record_type==="tomb"?1:0))return n("data_loss",`segment verification twin locator differs for physical id ${L.id}`);if(q++,L.id>B)B=L.id}let G=$.query("SELECT COUNT(*) AS count FROM events").get().count;if(q!==j||G!==q)return n("data_loss",`segment verification record accounting differs: physical=${q}, footer=${j}, twin=${G}`);let J=$.query("SELECT value FROM meta WHERE key = 'watermark'").get()?.value??b9;if(J!==B)return n("data_loss",`segment verification twin watermark ${J} differs from physical ${B}`);let U=Number($.query("SELECT value FROM meta WHERE key = 'projection-epoch'").get()?.value);if(!Number.isSafeInteger(U)||U!==W)return n("data_loss",`segment verification projection epoch ${String(U)} differs from physical ${W}`);return H(!0)}static summarizeAllSegments($){let Z=l.listSegmentFiles($);if(!K(Z))return Z;let Q=Z.ok,X=[];for(let z of Q){let Y=W5(_$($,z));if(!K(Y))return Y;X.push(Y.ok)}return H(X)}static listSegmentFiles($){if(!F1($))return H([]);let Z;try{Z=Ez($).filter((X)=>X.endsWith(".zev")).sort()}catch(X){return{err:U$(X,`could not enumerate event-log segment candidates in ${$}`,{code:"unavailable",retryability:"transient"})}}let Q=Z.find((X)=>!yF.test(X));if(Q!==void 0)return n("data_loss",`non-canonical segment candidate ${_$($,Q)} \u2014 refusing to treat broken history as empty`);return H(Z)}static syncLogDirectory($){let Z=yz($,"r");try{kH(Z)}finally{gz(Z)}}static reclaimStaleCatalogs($,Z,Q,X={},z={}){let Y;try{Y=Ez($).filter((U)=>uH.test(U)).sort()}catch(U){return n("unavailable",`could not enumerate disposable recovery catalogs: ${String(U)}`,"transient")}if(Y.length===0)return H([]);let j=[];try{for(let U of Y){let L=_$($,U),D=O9(L,"stale catalog reclaim");if(D===null)throw Object.assign(Error(`stale catalog ${L} vanished after enumeration`),{code:"ESTALE"});j.push(D)}}catch(U){let L=j.flatMap((D)=>t$(D));return n("unavailable",`could not bind stale recovery catalogs before reclaim: ${String(U)}${L.length===0?"":`; descriptor cleanup failed: ${L.join(" | ")}`}`,"transient")}let W=Math.random().toString(36).slice(2,10)||"0",V=`.catalog-reclaim.${process.pid}.${Date.now().toString(36)}.${W}.receipt.json`,q=_$($,V),B=null,G=null;try{Y$(Q,"catalog-reclaim-receipt-create"),B=yz(q,"wx");let U=N1(B);if(!U.isFile())throw Error(`catalog-reclaim receipt ${q} is not regular`);G={path:q,fd:B,nativeHandle:null,dev:U.dev,ino:U.ino},B=null;let L=Buffer.from(JSON.stringify({ts:Z,files:Y})),D=0;while(D<L.length){let P=SF(G.fd,L,D,L.length-D);if(P<=0)throw Error(`short reclaim-receipt write at ${D}/${L.length}`);D+=P}kH(G.fd),z.afterReclaimReceiptFsync?.(q),l.syncLogDirectory($)}catch(U){let L=[];if(B!==null)try{gz(B)}catch(D){L.push(`raw receipt descriptor close failed: ${String(D)}`)}if(G!==null)L.push(...C0(G,"failed catalog-reclaim receipt cleanup",X));return L.push(...j.flatMap((D)=>t$(D))),n("unavailable",`could not persist catalog-reclaim receipt: ${String(U)}${L.length===0?"":`; cleanup failed: ${L.join(" | ")}`}`,"transient")}let J=[];for(let U of j)try{Y$(Q,"stale-catalog-isolation"),J.push(...C0(U,"stale catalog cleanup",X))}catch(L){J.push(`${U.path}: ${String(L)}`,...t$(U))}if(G!==null)J.push(...t$(G));try{l.syncLogDirectory($)}catch(U){J.push(`directory fsync: ${String(U)}`)}return J.length===0?H(Y):n("unavailable",`catalog-reclaim failed after durable receipt ${V}: ${J.join(" | ")}`,"transient")}static flushCatalogReclaimTrail($,Z,Q,X={},z={}){let Y;try{Y=Ez(Z).filter((U)=>EF.test(U)).sort()}catch(U){return n("unavailable",`could not enumerate catalog-reclaim receipts: ${String(U)}`,"transient")}if(Y.length===0)return H([]);let j=new Set,W=mH,V=[],q=()=>V.flatMap((U)=>t$(U));try{for(let U of Y){let L=_$(Z,U),D=O9(L,"catalog-reclaim trail receipt");if(D===null||D.fd===null)throw Object.assign(Error(`catalog-reclaim receipt ${U} vanished after enumeration`),{code:"ESTALE"});V.push(D);let P=N1(D.fd);if(P.size>65536)throw Error(`catalog-reclaim receipt ${U} exceeds its content-free size bound`);let F=Buffer.alloc(P.size),A=0;while(A<F.length){let O=_F(D.fd,F,A,F.length-A,A);if(O<=0)throw Error(`short catalog-reclaim receipt read at ${A}/${F.length}`);A+=O}let N=N1(D.fd),S=fz(L);if(P.dev!==N.dev||P.ino!==N.ino||P.size!==N.size||S.dev!==D.dev||S.ino!==D.ino)throw Object.assign(Error(`catalog-reclaim receipt ${U} changed during descriptor read`),{code:"ESTALE"});let R=JSON.parse(F.toString("utf8"));if(typeof R.ts!=="string"||!Array.isArray(R.files)||R.files.length>1e4||R.files.some((O)=>typeof O!=="string"||!uH.test(O)))throw Error(`catalog-reclaim receipt ${U} has an invalid content-free shape`);if(R.ts>W)W=R.ts;for(let O of R.files)j.add(O)}}catch(U){let L=q(),D=U.code==="ESTALE";return n(D?"unavailable":"data_loss",`catalog-reclaim receipt could not be decoded: ${String(U)}${L.length===0?"":`; descriptor cleanup failed: ${L.join(" | ")}`}`,D?"transient":"non-retryable")}let B=[...j].sort(),G=!1;try{Y$(Q,"catalog-reclaim-trail"),$.exec("BEGIN IMMEDIATE"),G=!0,$.query(`INSERT OR REPLACE INTO meta (key, value)
351
+ VALUES ('open-recovery:catalog-reclaim:last', ?)`).run(JSON.stringify({ts:W,files:B})),Y$(Q,"catalog-reclaim-trail-commit"),$.exec("COMMIT"),G=!1,z.afterReclaimTrailCommit?.(V.map((U)=>U.path))}catch(U){if(G)try{$.exec("ROLLBACK")}catch(D){let P=q();return n("internal",`catalog-reclaim trail and rollback both failed: ${String(U)} | ${String(D)}${P.length===0?"":`; receipt descriptor cleanup failed: ${P.join(" | ")}`}`,"transient")}let L=q();return n("internal",`catalog-reclaim trail write failed: ${String(U)}${L.length===0?"":`; receipt descriptor cleanup failed: ${L.join(" | ")}`}`,"transient")}let J=[];for(let U of V)try{Y$(Q,"catalog-reclaim-receipt-cleanup"),J.push(...C0(U,"catalog-reclaim committed receipt cleanup",X))}catch(L){J.push(`${U.path}: ${String(L)}`,...t$(U))}try{l.syncLogDirectory(Z)}catch(U){J.push(`directory fsync: ${String(U)}`)}return J.length===0?H(B):n("unavailable",`catalog-reclaim trail committed but receipt cleanup failed: ${J.join(" | ")}`,"transient")}static segmentFingerprintKey($){return`segment-fingerprint:${$}`}static clearTwinDirty($){$.query("DELETE FROM meta WHERE key = 'twin-dirty'").run()}static refreshProjectionEpoch($){let Z=$.query("SELECT COALESCE(SUM(rewrite_gen), 0) AS epoch FROM segments").get();if(!Number.isSafeInteger(Z.epoch)||Z.epoch<0)throw Error(`segment rewrite generation sum is outside the safe integer range: ${String(Z.epoch)}`);$.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('projection-epoch', ?)").run(String(Z.epoch))}static markTwinDirty($,Z){$.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('twin-dirty', ?)").run(Z)}twinIsDirty(){return this.db.query("SELECT 1 AS present FROM meta WHERE key = 'twin-dirty'").get()!==null}static validateTwinWatermark($,Z){let Q=$.query("SELECT value FROM meta WHERE key = 'watermark'").get(),X=$.query("SELECT id FROM events ORDER BY id DESC LIMIT 1").get();if(Q===null&&X===null)return H(b9);if(Q===null||!q$(Q.value)||X===null||Q.value!==X.id)return n("data_loss",`${Z} refused: event-log watermark is missing, malformed, or inconsistent with the synchronized event projection`);return H(Q.value)}static validateProjectionEpoch($,Z){let Q=$.query("SELECT value FROM meta WHERE key = 'projection-epoch'").get(),X=$.query("SELECT COALESCE(SUM(rewrite_gen), 0) AS epoch FROM segments").get().epoch,z=Number(Q?.value);if(Q===null||!Number.isSafeInteger(z)||z<0||!Number.isSafeInteger(X)||X<0||z!==X)return n("data_loss",`${Z} refused: event-log projection epoch is missing, malformed, or inconsistent with segment rewrite truth`);return H(z)}static validateTombAuthorityVersion($,Z){return $.query("SELECT value FROM meta WHERE key = ?").get(w8)?.value===m8?H(!0):n("data_loss",`${Z} refused: tomb authorization proof is missing or stale; segment-authoritative writer reopen is required`)}static validateTwinWriteState($,Z){let Q=$.query(`
352
+ SELECT
353
+ (SELECT value FROM meta WHERE key = 'twin-dirty') AS dirty,
354
+ (SELECT value FROM meta WHERE key = 'watermark') AS watermark,
355
+ (SELECT id FROM events ORDER BY id DESC LIMIT 1) AS max_id,
356
+ (SELECT value FROM meta WHERE key = 'projection-epoch') AS projection_epoch,
357
+ (SELECT COALESCE(SUM(rewrite_gen), 0) FROM segments) AS expected_epoch,
358
+ (SELECT value FROM meta WHERE key = ?) AS tomb_proof
359
+ `).get(w8);if(Q.dirty!==null)return{code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${Z} refused: synchronized twin changed outside the event-log transaction; close and reopen for segment-authoritative replay`};if(Q.watermark===null!==(Q.max_id===null)||Q.watermark!==null&&(!q$(Q.watermark)||Q.watermark!==Q.max_id))return{code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${Z} refused: event-log watermark is missing, malformed, or inconsistent with the synchronized event projection`};let X=Number(Q.projection_epoch);if(Q.projection_epoch===null||!Number.isSafeInteger(X)||X<0||!Number.isSafeInteger(Q.expected_epoch)||Q.expected_epoch<0||X!==Q.expected_epoch)return{code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${Z} refused: event-log projection epoch is missing, malformed, or inconsistent with segment rewrite truth`};if(Q.tomb_proof!==m8)return{code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${Z} refused: tomb authorization proof is missing or stale; segment-authoritative writer reopen is required`};return null}twinReadError($){if(this.twinIsDirty())return{code:"data_loss",layer:"storage",retryability:"non-retryable",message:`${$} refused: synchronized twin is dirty; reopen for segment-authoritative recovery before reading event content`};let Z=l.validateTwinWatermark(this.db,$);if(!K(Z))return Z.err;let Q=l.validateProjectionEpoch(this.db,$);if(!K(Q))return Q.err;let X=l.validateTombAuthorityVersion(this.db,$);return K(X)?null:X.err}writeHandleError($){if(this.closed)return{code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:`${$} refused: event log closed`};if(this.opts.readOnly===!0)return{code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:`${$} refused on read-only event-log handle`};if(this.writeRecoveryRequired)return{code:"failed_precondition",layer:"storage",retryability:"retry-at-higher-level",message:`${$} refused: physical segment truth advanced without a synchronized twin commit; close and reopen for recovery before retry`};if(!this.writer.acceptsAppends)return{code:"failed_precondition",layer:"storage",retryability:"retry-at-higher-level",message:`${$} refused: segment writer session is poisoned after an incomplete write; close and reopen for recovery`};return null}twinWriteError($){let Z=this.writeHandleError($);if(Z!==null)return Z;let Q=this.writerLockError($);if(Q!==null)return Q;return l.validateTwinWriteState(this.db,$)}lockedWriteError($){let Z=this.writeHandleError($);if(Z!==null)return Z;let Q=this.writerLockError($);if(Q!==null)return Q;return l.validateTwinWriteState(this.db,$)}writerLockError($){if(this.writerLock===null)return this.writeRecoveryRequired=!0,{code:"failed_precondition",layer:"storage",retryability:"retry-at-higher-level",message:`${$} refused: writer-lock descriptor ownership is missing`};let Z=d5(this.writerLock);if(K(Z))return null;this.writeRecoveryRequired=!0;let Q="err"in Z?Z.err:{code:"unavailable",layer:"storage",retryability:"transient",message:Z.empty.how};return{...Q,message:`${$} refused: ${Q.message}`}}assertTwinReadable($){let Z=this.twinReadError($);if(Z!==null)throw new l$(Z)}static recordSealedFingerprint($,Z,Q=!0){let X=W5(Z);if(!K(X))throw Error(X.err.message);if(X.ok.state!=="sealed"){if(Q)throw Error(`sealed segment ${Z} did not produce a sealed open summary`);return}$.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(l.segmentFingerprintKey(X.ok.segmentId),X.ok.fingerprint)}static recordSealedProof($,Z){let Q=$.query("SELECT count FROM segments WHERE segment = ?").get(Z.segment);if(Q===null||Q.count!==Z.count)throw Object.assign(Error(`sealed descriptor proof for ${Z.segment} counted ${Z.count}, twin has ${Q?.count??"no row"}`),{code:"data_loss"});$.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(l.segmentFingerprintKey(Z.segment),Z.fingerprint)}static segmentIdOfSummaryPath($){let Z=FQ($);return Z.startsWith("seg-")&&Z.endsWith(".zev")?Z.slice(4,-4):Z}static twinConsistency($,Z){try{let Q=[],X=$.query("SELECT value FROM meta WHERE key = 'twin-dirty'").get();if(X!==null){if(Q.push("twin-dirty"),X.value===K1)Q.push(K1)}if($.query("SELECT value FROM meta WHERE key = 'open-recovery:attempt'").get()!==null)Q.push("open-recovery-attempt-pending");if($.query("SELECT value FROM meta WHERE key = ?").get(w8)?.value!==m8)Q.push("tomb-authority-proof-missing");if(Z.length===0&&!l.eventDerivedTwinIsEmpty($))Q.push("empty-generation-projection-mismatch");let j=$.query("SELECT segment, sealed, rewrite_gen, count FROM segments ORDER BY segment").all();if(j.length!==Z.length)Q.push("segment-row-count-mismatch");let W=new Map(j.map((P)=>[P.segment,P])),V=0,q=b9;for(let P of Z){let F=W.get(P.segmentId);if(!F){Q.push("segment-row-missing");continue}if(F.count!==P.count)Q.push("segment-count-mismatch");if(F.rewrite_gen!==P.rewriteGen)Q.push("segment-rewrite-mismatch");if(F.sealed!==1)Q.push("segment-unsealed");if(V+=P.count,P.maxId>q)q=P.maxId;let A=$.query("SELECT value FROM meta WHERE key = ?").get(l.segmentFingerprintKey(P.segmentId));if(A===null)Q.push("identity-stamp-missing");else if(A.value!==P.fingerprint)Q.push("identity-stamp-changed")}if($.query("SELECT COUNT(*) AS c FROM events").get().c!==V)Q.push("event-count-mismatch");if(($.query("SELECT value FROM meta WHERE key = 'watermark'").get()?.value??b9)!==q)Q.push("watermark-mismatch");let J=$.query("SELECT value FROM meta WHERE key = 'projection-epoch'").get()?.value,U=Z.reduce((P,F)=>P+F.rewriteGen,0),L=J===void 0?Number.NaN:Number(J);if(!Number.isSafeInteger(L)||L<0||L!==U)Q.push("projection-epoch-mismatch");let D=[...new Set(Q)];return{healthy:D.length===0,reasons:D}}catch(Q){return{healthy:!1,reasons:["twin-consistency-probe-failed"]}}}static validateRecoveryCatalogRecords($){for(let Z of $.recordsInReplayOrder()){if(Z.record_type!=="frame")continue;let Q=GQ(Z);if(!K(Q))return Q}return $.validateTombAuthorizations()}static stageDbAheadSurvivorsSnapshot($,Z,Q,X){let z=!1,Y=(j)=>{throw Object.assign(Error(j.message),{recoveryFailure:j})};try{$.exec("BEGIN"),z=!0;let j=$.query(`
360
+ SELECT
361
+ (SELECT value FROM meta WHERE key = 'twin-dirty') AS dirty,
362
+ (SELECT value FROM meta WHERE key = ?) AS codec,
363
+ (SELECT value FROM meta WHERE key = 'open-recovery:attempt') AS attempt
364
+ `).get(b8);if(j.dirty!==null||j.codec!==g8||j.attempt!==X)return $.exec("COMMIT"),z=!1,H("disqualified");for(let W of $.query("SELECT * FROM events ORDER BY segment, line, id").iterate()){if(Z.hasRecord(W.id))continue;if(W.erased===1){let G=l.tombFromErasedRow(W),J="ok"in G?G.ok:Y("err"in G?G.err:{code:"data_loss",layer:"storage",retryability:"non-retryable",message:G.empty.how}),U=Q.get(Y0(J.nk.source,J.nk.stream));Z.stageDbTomb(J,W.segment,W.line,l.uniqueNkFor(U,J.nk.rev,J.contentHash));continue}let V=(()=>{try{return V5(W)}catch(G){return Y({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`SQLite survivor ${W.id} has a malformed full envelope: ${String(G)}`})}})(),q=g5(V);if(!K(q)||Z0(V)!==V.contentHash){let G=!K(q)?"err"in q?q.err.message:q.empty.how:"content hash mismatch";Y({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`SQLite survivor ${W.id} has an invalid full envelope: ${G}`})}let B=Q.get(Y0(V.nk.source,V.nk.stream));Z.stageDbEvent(V,W.segment,W.line,l.uniqueNkFor(B,V.nk.rev,V.contentHash))}return $.exec("COMMIT"),z=!1,H("eligible")}catch(j){let W=null;if(z)try{$.exec("ROLLBACK")}catch(q){W=q}return{err:U$(W===null?j:AggregateError([j,W]),`DB-ahead donor snapshot failed${W===null?"":" and rollback failed"}`,{code:"internal",retryability:"transient"})}}}static verifyPhysicalCatalogRows($,Z,Q){let X=$[Symbol.iterator](),z=0,Y=null,j=(B)=>{throw Y={code:"data_loss",layer:"storage",retryability:"non-retryable",message:B},Error(B)},W=(B,G)=>{let J=X.next();if(z++,J.done===!0)j(`${Q} ${Z} contains an unexpected record at line ${G}`);if(G!==z)j(`${Q} ${Z} locator ${G} diverges from staged line ${z}`);let U=X1(J.value),L="ok"in U?U.ok:j("err"in U?U.err.message:U.empty.how);if(B.kind!==L.kind||B.kind==="frame"&&L.kind==="frame"&&!K5(B.event,L.event)||B.kind==="tomb"&&L.kind==="tomb"&&!K5(B.tomb,L.tomb))j(`${Q} ${Z} record ${J.value.id} differs from its staged catalog row`)},V=p5(Z,(B,G)=>W({kind:"tomb",tomb:{id:B.id,nk:B.nk,ts:B.ts,kind:B.kind,contentHash:B.contentHash,tomb:B.tomb}},G),(B,G)=>W({kind:"frame",event:B},G));if(Y!==null)return{err:Y};if(!K(V))return V;let q=X.next();if(q.done!==!0)return n("data_loss",`${Q} ${Z} omitted staged catalog row ${q.value.id}`);return V}static verifyParsedCatalogRows($,Z,Q){let X=[...$];if(X.length!==Z.entries.length)return n("unavailable",`${Q} ${Z.path} changed staged count ${X.length}/${Z.entries.length}`,"transient");for(let z=0;z<X.length;z++){let Y=X[z],j=Z.entries[z];if(Y===void 0||j===void 0||Y.line!==z+1)return n("unavailable",`${Q} ${Z.path} changed staged locator ${z+1}`,"transient");let W=X1(Y);if(!K(W))return W;let V=j.kind==="frame"?{kind:"frame",event:j.frame.rec}:{kind:"tomb",tomb:{id:j.tomb.id,nk:j.tomb.nk,ts:j.tomb.ts,kind:j.tomb.kind,contentHash:j.tomb.contentHash,tomb:j.tomb.tomb}};if(!K5(W.ok,V))return n("unavailable",`${Q} ${Z.path} changed staged record ${Y.id}`,"transient")}return H(!0)}static verifySerializedSurvivorGroup($,Z,Q){return l.verifyPhysicalCatalogRows($.survivorRecords(Z),Q,"DB-ahead recovery segment")}static validateRecoveryCatalogCandidateSet($){let Z=_1($.path),Q=l.listSegmentFiles(Z);if(!K(Q))return Q;let X=[...$.segments()].map((z)=>z.file).sort();return K5(Q.ok,X)?H(!0):n("unavailable","recovery candidate set changed after catalog enumeration","transient")}static validateRecoveryCatalogFiles($){let Z=[...$.segments()],Q=_1($.path),X=l.validateRecoveryCatalogCandidateSet($);if(!K(X))return X;for(let z of Z){if(z.verified!==1)return n("data_loss",`recovery catalog segment ${z.file} was never physically verified`);if(z.path!==_$(Q,z.file))return n("data_loss",`sealed recovery catalog contains a non-canonical path for ${z.file}`);let Y=W5(z.path);if(!K(Y))return Y;if(Y.ok.state!=="sealed"||Y.ok.segmentId!==z.segment||Y.ok.rewriteGen!==z.rewrite_gen||Y.ok.count!==z.count||Y.ok.fingerprint!==z.fingerprint)return n("unavailable",`sealed recovery generation changed after verification at ${z.file}; refusing catalog replay`,"transient")}return l.validateRecoveryCatalogCandidateSet($)}static preflightRecoveryDisk($,Z){try{let Q=TF(_1(Z)),X=Number(Q.bavail)*Number(Q.bsize),z=0;try{z=wH(Z).size}catch(j){if(F1(Z))throw j}let Y=Math.max(z,$.storageBytes())+134217728;if(!Number.isFinite(X)||X<Y)return n("resource_exhausted",`sealed recovery requires ${Y} free bytes for its catalog/replay generation but only ${X} are available`,"throttling");return H(!0)}catch(Q){return n("unavailable",`could not preflight sealed recovery disk capacity: ${String(Q)}`,"transient")}}static rebuildTwinFromCatalog($,Z,Q,X,z,Y,j){let W=z?$.query("SELECT key, value FROM meta WHERE key LIKE 'open-recovery:%'").all():[];if(j!==void 0)Y$(j,"twin-replay-begin");$.exec("BEGIN IMMEDIATE");try{if(z)for(let J of["pending_refs","resolved_refs","claims","tombstones","rebinds","unknown_kinds","blob_refs","erasure_jobs","segments","events","meta"])$.exec(`DELETE FROM ${J}`);for(let J of Z.segments()){if(J.verified!==1)throw Object.assign(Error(`recovery catalog segment ${J.file} reached replay before physical verification`),{code:"data_loss"});$.query(`INSERT INTO segments (segment, file, sealed, rewrite_gen, count)
365
+ VALUES (?, ?, 1, ?, ?)`).run(J.segment,J.file,J.rewrite_gen,J.count),$.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(l.segmentFingerprintKey(J.segment),J.fingerprint)}let V=b9,q=0;for(let J of Z.recordsInReplayOrder()){if(J.id>V)V=J.id;if(J.record_type==="frame"){let U=GQ(J);if(!K(U)){let P=U.err;throw Object.assign(Error(P.message),{code:P.code})}let L=U.ok,D=Q.get(Y0(L.nk.source,L.nk.stream));q1($,L,J.segment,J.line,l.uniqueNkFor(D,L.nk.rev,L.contentHash)),B1($,L)}else{if(J.tomb===null)throw Error(`catalog tomb ${J.id} has no authorizer id`);let U={id:J.id,nk:{source:J.source,stream:J.stream,sourceId:J.source_id,rev:J.rev},ts:J.ts,kind:J.kind,contentHash:J.content_hash,tomb:J.tomb},L=Q.get(Y0(U.nk.source,U.nk.stream));UH($,U,J.segment,J.line,l.uniqueNkFor(L,U.nk.rev,U.contentHash)),Gz($,{source:U.nk.source,stream:U.nk.stream,sourceId:U.nk.sourceId})}q++}let B=Z.count();if(q!==B)throw Error(`catalog replay counted ${q} rows but the prospective generation contains ${B}`);if(q===0)$.query("DELETE FROM meta WHERE key = 'watermark'").run();else $.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('watermark', ?)").run(V);if($.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(b8,g8),$.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(w8,m8),$.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('segment-verify:last-success', ?)").run(X),Y!==void 0)$.query("INSERT OR IGNORE INTO meta (key, value) VALUES ('open-recovery:attempt', ?)").run(Y);for(let J of W)$.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(J.key,J.value);l.refreshProjectionEpoch($);let G=l.validateRecoveryCatalogFiles(Z);if(!K(G)){let J=G.err;throw Object.assign(Error(J.message),{code:J.code})}if(l.clearTwinDirty($),j!==void 0)Y$(j,"twin-replay-commit");$.exec("COMMIT")}catch(V){try{$.exec("ROLLBACK")}catch(q){throw AggregateError([V,q],`catalog replay and rollback both failed: ${String(V)}`)}throw V}}static installRebuiltTwinFromCatalog($,Z,Q,X,z,Y,j={},W={}){let V=gF($),q="",B=null;for(let F=0;F<100;F++){let A=Math.random().toString(36).slice(2,10)||"0",N=`${$}.rebuild.${process.pid}.${Date.now().toString(36)}.${A}.${F}`,S=[];try{for(let O of["","-wal","-shm"]){let T=N+O;Y$(Y,"shadow-family-reservation");let m=yz(T,"wx"),k=N1(m);if(!k.isFile())throw R$(`shadow reservation ${T} is not a regular file`);let d={path:T,fd:m,nativeHandle:null,dev:k.dev,ino:k.ino};if(S.push(d),!q5(d))throw R$(`shadow reservation ${T} changed identity before SQLite open`)}let R=S[0];if(R===void 0)throw Error(`shadow reservation ${N} created no base member`);B={...R,sidecars:new Map(S.slice(1).map((O)=>[O.path,O]))},q=N;break}catch(R){let O=null;try{Y$(Y,"shadow-reservation-failure-cleanup")}catch(m){O=m}if(O!==null){let m=S.flatMap((b)=>t$(b)).map((b)=>Error(b));m.push(...v9(V).map((b)=>Error(b)));let k=S.map((b)=>b.path).join(", "),d=AggregateError([R,O,...m],`writer-lock ownership was lost during shadow reservation; descriptor-only cleanup retained${k===""?" no created names":`: ${k}`}`),y=O.structured??R.structured;throw y===void 0?Object.assign(d,{code:"ESTALE"}):Object.assign(d,{code:"ESTALE",structured:y})}let T=[];for(let m of[...S].reverse())T.push(...C0(m,"shadow reservation cleanup",j).map((k)=>Error(k)));if(T.length>0)throw T.push(...v9(V).map((m)=>Error(m))),AggregateError([R,...T],"exclusive shadow family reservation cleanup failed");if(R.code!=="EEXIST"){let m=v9(V);if(m.length>0)throw AggregateError([R,...m.map((k)=>Error(k))]);throw R}}}if(q===""||B===null){let F=v9(V);throw AggregateError([Error("could not allocate an exclusive twin rebuild shadow"),...F.map((A)=>Error(A))])}let G=null,J=null,U=!1,L=new Map(B.sidecars),D=[],P=null;try{if(!q5(B))throw R$(`shadow ${q} changed identity before SQLite open`);if(Y$(Y,"shadow-replay-open"),G=Jz(q),NQ(G,B,"shadow SQLite open"),l.rebuildTwinFromCatalog(G,Z,Q,X,!0,z,Y),NQ(G,B,"shadow replay completion"),G.exec("PRAGMA wal_checkpoint(TRUNCATE)"),NQ(G,B,"shadow checkpoint completion"),pH(q,L),G.close(),G=null,!q5(B))throw R$(`shadow ${q} changed identity after close`);let F=l.validateRecoveryCatalogFiles(Z);if(!K(F)){let y=F.err;throw Object.assign(Error(y.message),{code:y.code,structured:y})}if(!q5(B))throw R$(`shadow ${q} changed identity after post-close generation proof`);let A=[];for(let y of["-wal","-shm"]){let b=L.get(q+y);if(b===void 0)continue;Y$(Y,"shadow-checkpoint-sidecar-cleanup"),A.push(...C0(b,"shadow checkpointed sidecar cleanup",j))}if(A.length>0)throw R$(`shadow sidecar cleanup failed: ${A.join(" | ")}`);let N=l.validateRecoveryCatalogFiles(Z);if(!K(N)){let y=N.err;throw Object.assign(Error(y.message),{code:y.code,structured:y})}if(!q5(B))throw R$(`shadow ${q} changed identity at the canonical install boundary`);let S=[...V.members].sort((y,b)=>{let g=(w)=>w.endsWith("-wal")?0:w.endsWith("-shm")?1:2;return g(y.path)-g(b.path)});for(let y of S){Y$(Y,"dead-twin-canonical-isolation");let b=HQ(y.path,y.expected,`dead twin canonical ${FQ(y.path)}`,j);if("err"in b)throw R$(b.err);if(b.ok.kind==="isolated")D.push(b.ok.isolated)}W.afterDeadTwinCanonicalIsolation?.($);for(let y of["-wal","-shm"]){Y$(Y,"dead-twin-sidecar-install-recheck");let b=HQ($+y,null,`dead twin canonical ${FQ($+y)} install recheck`,j);if("err"in b)throw R$(b.err)}let R=l.validateRecoveryCatalogFiles(Z);if(!K(R)){let y=R.err;throw Object.assign(Error(y.message),{code:y.code,structured:y})}W.beforeShadowSourceInstall?.(q),Y$(Y,"dead-twin-shadow-source-isolation");let O=HQ(q,B,`dead twin shadow source ${FQ(q)}`,j);if("err"in O)throw R$(O.err);if(O.ok.kind!=="isolated")throw R$(`dead twin shadow source ${q} vanished before install`);if(P=O.ok.isolated,Y$(Y,"dead-twin-shadow-install"),!q5(B,P.isolationPath))throw R$(`dead twin shadow isolation receipt ${P.isolationPath} changed identity before install`);W.afterShadowSourceIsolation?.(q,P.isolationPath);let T=null,m=!1;try{G0(P.isolationPath,$),m=!0}catch(y){if(y instanceof F$&&y.moved)m=!0,T=String(y);else if(y instanceof F$&&y.errno===17)throw R$(`dead twin shadow install refused canonical main collision at ${$}: ${String(y)}`);else throw y}if(!m)throw R$(`dead twin shadow install did not move ${q}`);if(!q5(B,$)){Y$(Y,"dead-twin-unexpected-install-retain");let y=lH($,q);throw R$(`installed twin ${$} does not name the reserved shadow inode; unexpected bytes ${y.retainedPath===null?"vanished before retention":`retained at ${y.retainedPath}`}${y.durabilityWarning===null?"":`; retention durability warning: ${y.durabilityWarning}`}`)}l5($),Y$(Y,"installed-twin-open");try{J=GH($),NQ(J,B,"installed twin canonical raw open",$),Y$(Y,"installed-twin-initialize"),Bz(J),NQ(J,B,"installed twin canonical initialized open",$),U=!0}catch(y){let b=[];if(J!==null)try{J.close(),J=null}catch(p){b.push(p)}let g="could not be retained";try{Y$(Y,"dead-twin-unexpected-open-retain");let p=lH($,q);g=p.retainedPath===null?"vanished before retention":`retained at ${p.retainedPath}${p.durabilityWarning===null?"":`; retention durability warning: ${p.durabilityWarning}`}`}catch(p){b.push(p),g=`retention failed: ${String(p)}`}let w=`installed twin canonical open did not bind the reserved shadow inode: ${String(y)}; unexpected bytes ${g}${b.length===0?"":`; open-boundary failures: ${b.map(String).join(" | ")}`}`,u={code:"unavailable",layer:"storage",retryability:"transient",message:w};throw Object.assign(AggregateError([y,...b],w),{code:"ESTALE",structured:u})}vz(B);let k=[];for(let y of D)Y$(Y,"dead-twin-canonical-receipt-finalization"),k.push(...Wz(y,{sourceMayNameInstalledSuccessor:!0}));if(k.push(...v9(V)),T!==null)k.push(`shadow install directory descriptor failed: ${T}`);if(k.length>0)throw R$(`installed twin is healthy but rollback-receipt finalization failed: ${k.join(" | ")}`);let d=J;return J=null,d}catch(F){let A=[],N=null;try{Y$(Y,"shadow-recovery-failure-cleanup")}catch(S){N=S}if(G!==null)try{if(N===null)pH(q,L);G.close()}catch(S){A.push(S)}if(J!==null)try{J.close()}catch(S){A.push(S)}if(N!==null){try{vz(B)}catch(T){A.push(T)}A.push(...v9(V).map((T)=>Error(T)));let S=[B.path,...[...B.sidecars.values()].map((T)=>T.path),...P===null?[]:[P.isolationPath],...D.map((T)=>T.isolationPath)].join(", "),R=AggregateError([F,N,...A],`writer-lock ownership was lost during shadow recovery; descriptor-only cleanup retained paths: ${S}`),O=N.structured??F.structured;throw O===void 0?Object.assign(R,{code:"ESTALE"}):Object.assign(R,{code:"ESTALE",structured:O})}if(!U){if(P!==null)A.push(...jz(P,j).map((S)=>Error(S)));for(let S of[...D].reverse())A.push(...jz(S,j).map((R)=>Error(R)));for(let S of["-wal","-shm"]){let R=L.get(q+S);if(R===void 0||R.fd===null)continue;A.push(...C0(R,"failed shadow sidecar cleanup",j).map((O)=>Error(O)))}A.push(...C0(B,"failed shadow base cleanup",j).map((S)=>Error(S)))}try{vz(B)}catch(S){A.push(S)}if(A.push(...v9(V).map((S)=>Error(S))),A.length>0){let S=D.map((T)=>T.isolationPath).join(", "),R=AggregateError([F,...A],`shadow recovery and descriptor-bound cleanup failed${S===""?"":`; rollback receipts: ${S}`}`),O=F.structured;if(O!==void 0)throw Object.assign(R,{code:O.code,structured:O});throw R}throw F}}static recoverSealedGeneration($,Z,Q,X,z,Y,j,W,V,q=[],B,G={},J={}){let U;try{Y$(B,"recovery-catalog-create"),U=z1.create(Q,q.length===0?"sealed-sqlite-catalog":"mixed-sqlite-catalog")}catch(F){return{err:U$(F,"could not create sealed recovery catalog",{code:"unavailable",retryability:"transient"})}}let L=!1,D=()=>{if(L)return{ok:[]};L=!0;try{return{ok:U.remove(J)}}catch(F){let A=null;try{U.close()}catch(N){A=N}return{err:U$(A===null?F:AggregateError([F,A]),`sealed recovery catalog cleanup threw${A===null?"":" and descriptor close failed"}`,{code:"unavailable",retryability:"transient"})}}},P=(F)=>{if(L)return{err:F};let A=null;try{Y$(B,"recovery-catalog-cleanup")}catch(R){A=U$(R,"recovery catalog cleanup refused after writer-lock loss",{code:"unavailable",retryability:"transient"})}if(A!==null){L=!0;try{U.close()}catch(R){A={...A,message:`${A.message}; retained catalog close failed: ${String(R)}`}}return{err:A}}let N=D();if("err"in N)return n("unavailable",`${F.message}; ${N.err.message}`,"transient","storage");let S=N.ok;if(S.length===0)return{err:F};return n("unavailable",`${F.message}; recovery catalog cleanup failed: ${S.join(" | ")}`,"transient","storage")};try{for(let b of X){Y$(B,"recovery-catalog-segment-stage"),U.beginSegment();let g=null,w=p5(b.path,(u,p)=>{try{let o=z.get(Y0(u.nk.source,u.nk.stream));U.stageTomb(u,b.segmentId,p,l.uniqueNkFor(o,u.nk.rev,u.contentHash))}catch(o){throw g=o,o}},(u,p)=>{try{let o=z.get(Y0(u.nk.source,u.nk.stream));U.stageEvent(u,b.segmentId,p,l.uniqueNkFor(o,u.nk.rev,u.contentHash))}catch(o){throw g=o,o}});if(g!==null)return U.rollbackSegment(),P(U$(g,`sealed recovery catalog rejected ${b.path}`,{code:"data_loss",retryability:"non-retryable"}));if(!K(w))return U.rollbackSegment(),P(w.err);try{Y$(B,"recovery-catalog-segment-commit"),U.commitSegment(b,w.ok)}catch(u){return U.rollbackSegment(),P(U$(u,`sealed recovery catalog accounting failed for ${b.path}`,{code:"data_loss",retryability:"non-retryable"}))}}let F=new Map;for(let b of q){Y$(B,"recovery-catalog-tail-stage");let g=d0(b.path);if(!K(g))return P(g.err);let w=g.ok;if(w.segmentId!==b.segmentId||w.entries.length===0)return P({code:"unavailable",layer:"storage",retryability:"transient",message:`mixed recovery tail ${b.path} changed before provisional staging`});F.set(w.path,w.fingerprint),U.beginSegment();try{for(let u of w.entries)if(u.kind==="frame"){let p=u.frame.rec,o=z.get(Y0(p.nk.source,p.nk.stream));U.stageEvent(p,w.segmentId,u.line,l.uniqueNkFor(o,p.nk.rev,p.contentHash))}else{let p=u.tomb,o=z.get(Y0(p.nk.source,p.nk.stream));U.stageTomb(p,w.segmentId,u.line,l.uniqueNkFor(o,p.nk.rev,p.contentHash))}U.commitProvisionalSegment(w,wH(w.path).size)}catch(u){return U.rollbackSegment(),P(U$(u,`mixed recovery catalog rejected tail ${w.path}`,{code:"data_loss",retryability:"non-retryable"}))}}let A=l.validateRecoveryCatalogCandidateSet(U);if(!K(A))return P(A.err);if($===null)U.setDbDonorDisposition("twin-unavailable");else if(!W)U.setDbDonorDisposition("ineligible-at-open");else{let b=l.stageDbAheadSurvivorsSnapshot($,U,z,j);if(!K(b))return P(b.err);U.setDbDonorDisposition(b.ok==="eligible"?"eligible-snapshot":"disqualified-late")}let N=l.validateRecoveryCatalogRecords(U);if(!K(N))return P(N.err);let S=l.preflightRecoveryDisk(U,Z);if(!K(S))return P(S.err);let R=[];for(let b of q){G.beforeTailSeal?.(b.path),Y$(B,"mixed-tail-seal");let g=d0(b.path);if(!K(g))return P(g.err);if(g.ok.segmentId!==b.segmentId||g.ok.entries.length===0)return P({code:"unavailable",layer:"storage",retryability:"transient",message:`mixed recovery tail ${b.path} changed before recovery`});let w=g.ok;if(w.fingerprint!==F.get(w.path))return P({code:"unavailable",layer:"storage",retryability:"transient",message:`mixed recovery tail ${w.path} changed descriptor fingerprint before recovery`});let u=l.verifyParsedCatalogRows(U.recordsForSegment(w.segmentId),w,"mixed recovery tail");if(!K(u))return P(u.err);Y$(B,"mixed-tail-seal");let p=o7(w);if(!K(p))return P(p.err);let o=W5(w.path);if(!K(o))return P(o.err);if(o.ok.state!=="sealed")return P({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`mixed recovery tail ${w.path} did not reach SEALED`});let Z$=l.verifyPhysicalCatalogRows(U.recordsForSegment(w.segmentId),w.path,"mixed recovery tail");if(!K(Z$))return P(Z$.err);try{U.finalizeProvisionalSegment(w.segmentId,o.ok,Z$.ok)}catch(H$){return P(U$(H$,`mixed recovery tail ${w.path} could not bind its exact physical proof`,{code:"data_loss",retryability:"non-retryable"}))}R.push({segment:w.segmentId,actions:[...p.ok.actions,"mixed-tail-catalog-verified"]})}for(let b of U.survivorGroups()){let g=U.firstSurvivorRecord(b);if(g===null)continue;let w=_$(Q,`seg-${g.id}.zev`);if(F1(w))return P({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`DB-ahead survivor ${g.id} collides with an existing canonical segment`});function*u(){for(let H$ of U.survivorRecords(b)){let A$=X1(H$);if(!K(A$)){let e=A$.err;throw Object.assign(Error(e.message),{code:e.code})}yield A$.ok}}Y$(B,"db-survivor-segment-create");let p=fq(Q,u(),J8,V);if(!K(p))return P(p.err);U.noteStreamManifestEvidence(p.ok.streamManifest);let o=W5(p.ok.path);if(!K(o))return P(o.err);if(o.ok.state!=="sealed")return P({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`DB-ahead recovery segment ${p.ok.path} did not seal`});let Z$=l.verifySerializedSurvivorGroup(U,b,p.ok.path);if(!K(Z$))return P(Z$.err);try{U.relocateSurvivorGroup(b,o.ok,Z$.ok)}catch(H$){return P(U$(H$,`DB-ahead recovery segment ${p.ok.path} could not bind its exact physical proof`,{code:"data_loss",retryability:"non-retryable"}))}R.push({segment:o.ok.segmentId,actions:["db-survivor-serialized","catalog-verified"]})}if(N=l.validateRecoveryCatalogRecords(U),!K(N))return P(N.err);let O=l.validateRecoveryCatalogFiles(U);if(!K(O))return P(O.err);U.checkpoint();let T=l.preflightRecoveryDisk(U,Z);if(!K(T))return P(T.err);let m=U.evidence(),k;try{if($!==null)l.rebuildTwinFromCatalog($,U,z,Y,!0,j,B),k=$;else k=l.installRebuiltTwinFromCatalog(Z,U,z,Y,j,B,J,G)}catch(b){return U.close(),{err:U$(b,`twin rebuild from sealed recovery catalog failed; catalog retained at ${U.path}`,{code:b.code==="data_loss"?"data_loss":"internal",retryability:b.code==="data_loss"?"non-retryable":"transient"})}}Y$(B,"recovery-catalog-cleanup");let d=D(),y="err"in d?d.err.message:d.ok.length===0?null:d.ok.join(" | ");if(y!==null){let b=[];if($===null)try{k.close()}catch(g){b.push(String(g))}return n("unavailable",`sealed recovery completed but catalog cleanup failed: ${y}${b.length===0?"":`; recovered twin close failed: ${b.join(" | ")}`}`,"transient")}return H({db:k,evidence:m,recovered:R})}catch(F){return P(U$(F,"sealed recovery catalog failed",{code:"data_loss",retryability:"non-retryable"}))}}static uniqueNkFor($,Z,Q){if($!==void 0)return $.revOrder!=="head-compare";return Z!==Q}synchronizeWriterAppend($,Z,Q,X){if($.length===0||Q===null)throw Error("appender bug: a physical batch has no provisional twin location");if(Z.locs.length!==$.length||Z.locs.some((Y,j)=>Y.id!==$[j]?.id))throw Error("appender bug: segment locators do not bind the complete logical batch");let z=Z.segment!==Q||Z.locs.some((Y,j)=>Y.line!==X+j);if(z){let Y=this.db.query("SELECT segment, line FROM events WHERE id = ?"),j=this.db.query("UPDATE events SET segment = ?, line = ? WHERE id = ?");for(let W=0;W<Z.locs.length;W++){let V=Z.locs[W],q=Y.get(V.id);if(q?.segment!==Q||q.line!==X+W)throw Error(`appender bug: provisional row ${V.id} moved before rotation synchronization`);j.run(Z.segment,V.line,V.id);let B=Y.get(V.id);if(B?.segment!==Z.segment||B.line!==V.line)throw Error(`appender bug: could not relocate provisional row ${V.id} after rotation`)}}if(Z.rotated!==null){if(FQ(Z.rotated.path)!==`seg-${Z.rotated.segment}.zev`)throw Error("appender bug: rotated segment path is not canonical");if(this.db.query("UPDATE segments SET sealed = 1 WHERE segment = ? AND count = ?").run(Z.rotated.segment,Z.rotated.count).changes!==1)throw Error(`appender bug: rotated segment ${Z.rotated.segment} has no exact twin accounting row`);this.db.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(l.segmentFingerprintKey(Z.rotated.segment),Z.rotated.fingerprint)}if(this.db.query(`INSERT INTO segments (segment, file, sealed, rewrite_gen, count) VALUES (?, ?, 0, 0, ?)
366
+ ON CONFLICT(segment) DO UPDATE SET count = count + excluded.count`).run(Z.segment,`seg-${Z.segment}.zev`,$.length),z)l.refreshProjectionEpoch(this.db)}append($,Z){if(this.opts.readOnly===!0)return n("failed_precondition","append refused on read-only event-log handle \u2014 query fallback may read last-good state only");let Q=this.now(),X=performance.now(),z={mutated:!1,admissionProven:!1},Y=this.appendCore($,Z,!1,z),j={};if(K(Y))for(let W of Y.ok)j[W.outcome]=(j[W.outcome]??0)+1;if(!this.closed)this.emitSpan("append.batch",Q,performance.now()-X,{origin:Z?.kind??"invalid",count:$?.length??0,outcomes:j},K(Y)?void 0:Y.err,z.mutated||!K(Y),z.admissionProven);return Y}appendAsync($,Z){if(this.closed)return Promise.resolve(n("failed_precondition","append refused because the event-log session is closed"));if(this.writeRecoveryRequired)return Promise.resolve(n("failed_precondition","append refused because the event-log session requires close and reopen recovery"));let Q;try{Q=structuredClone({batch:$,origin:Z})}catch(X){return Promise.resolve(n("invalid_argument",`appendAsync input is not cloneable: ${String(X)}`))}return new Promise((X)=>{let z={batch:Q.batch,origin:Q.origin,resolve:X};if(bF(Q.origin,Q.batch))this.immediateAppendQueue.push(z);else this.groupAppendQueue.push(z);this.scheduleQueuedAppend()})}pendingAppendQueueDepth(){return this.immediateAppendQueue.length+this.groupAppendQueue.length}scheduleQueuedAppend(){if(this.appendQueueScheduled||this.pendingAppendQueueDepth()===0)return;this.appendQueueScheduled=!0,setTimeout(()=>{this.appendQueueScheduled=!1;let $=this.nextQueuedAppend();if($===void 0)return;let Z;try{if(this.closed)Z=n("failed_precondition","queued append refused because the event-log session is closed");else if(this.writeRecoveryRequired)Z=n("failed_precondition","queued append refused because the event-log session requires close and reopen recovery");else Z=this.append($.batch,$.origin)}catch(Q){this.writeRecoveryRequired=!0,Z=n("aborted",`queued append threw before returning a result; close and reopen before retry: ${String(Q)}`,"retry-at-higher-level")}if($.resolve(Z),this.writeRecoveryRequired){this.refuseQueuedAppends();return}this.scheduleQueuedAppend()},0)}nextQueuedAppend(){if(this.immediateAppendQueue.length>0&&(this.groupAppendQueue.length===0||this.lastQueuedAppendClass!=="immediate"))return this.lastQueuedAppendClass="immediate",this.immediateAppendQueue.shift();if(this.groupAppendQueue.length>0)return this.lastQueuedAppendClass="group",this.groupAppendQueue.shift();if(this.immediateAppendQueue.length>0)return this.lastQueuedAppendClass="immediate",this.immediateAppendQueue.shift();return}refuseQueuedAppends(){let $=n("failed_precondition","queued append refused because the event-log session is closing");for(let Z of this.immediateAppendQueue.splice(0))Z.resolve($);for(let Z of this.groupAppendQueue.splice(0))Z.resolve($)}appendCore($,Z,Q,X){let z=this.twinWriteError("append");if(z!==null)return{err:z};if(X.admissionProven=!0,!Array.isArray($))return n("invalid_argument","append: batch must be an array");if($.length===0)return H([]);if($.length>n5)return n("invalid_argument",`append: batch of ${$.length} exceeds the \xA76 txn unit (${n5})`);let Y=YX(Z);if(!K(Y))return Y;for(let U of $){let L=this.validateHard(U,Z,Q);if(L!==null)return{err:L}}let j=this.writer.filePath===null?1:this.writer.lineCount,W=[],V=[],q=this.writer.segmentId,B=!1,G=()=>j+W.length;this.db.exec("BEGIN IMMEDIATE");let J=this.lockedWriteError("append");if(J!==null)return this.db.exec("ROLLBACK"),X.admissionProven=!1,{err:J};try{let U=(D,P)=>{if(q===null)q=D.id;q1(this.db,D,q,G(),P),W.push(D),B1(this.db,D)},L=(D,P,F={kind:"kernel"})=>{let A=this.stampInternal({kind:D,payload:P,origin:F});return U(A,!0),A};for(let D of $){let P=this.streams.get(Y0(D.nk.source,D.nk.stream)),F=Z0({kind:D.kind,body:D.body,payload:D.payload,blobs:D.blobs}),A,N,S=!1;if(P?.quality==="none")A=NZ(P.noneIdentity??"occurrence",F,D.ts),N="0";else{A=D.nk.sourceId;let b=D.nk.rev??"";if(P?.revOrder==="head-compare"||P===void 0&&b==="")N=F,S=!0;else if(P?.revOrder==="event-ts")N=X5(D.ts);else N=b}let R={source:D.nk.source,stream:D.nk.stream,sourceId:A,rev:N},O=D.coverage?.phase??"live",T=this.checkTombstones(R,F,L);if(T!==null){V.push(T);continue}let m=null,k=null;if(!S){let b=I9(this.db,"SELECT id, content_hash FROM events WHERE source = ? AND stream = ? AND source_id = ? AND rev = ?").get(R.source,R.stream,R.sourceId,R.rev);if(b!==null){if(b.content_hash===F){V.push({id:b.id,outcome:"duplicate"});continue}let g=this.conflictSiblingWithHash(R,N,F);if(g!==null){V.push({id:g.id,outcome:"duplicate"});continue}let w=this.nextConflictN(R);k={existingId:b.id,existingHash:b.content_hash},R.rev=MV(N,w)}}else{let g=this.chainRowsForBase({source:R.source,stream:R.stream,sourceId:R.sourceId}).filter((u)=>u.erased===0),w=g.length>0?g[g.length-1]:null;if(O==="live"){if(w!==null&&w.content_hash===F){V.push({id:w.id,outcome:"head-noop"});continue}}else if(g.some((u)=>u.content_hash===F)){V.push({id:w.id,outcome:"head-noop"});continue}}let d={id:this.ulid(),nk:R,contentHash:F,canon:J8,ts:D.ts,observedTs:this.now(),trust:dH(Z,R),origin:Z,tier:D.tier,kind:D.kind,schemaVersion:D.schemaVersion,policyVersion:this.policyVersion(),mentions:D.mentions,body:D.body};if(D.coverage!==void 0)d.coverage=D.coverage;if(D.lang!==void 0)d.lang=D.lang;if(D.payload!==void 0)d.payload=D.payload;if(D.blobs!==void 0)d.blobs=D.blobs;if(D.refs!==void 0)d.refs=D.refs;let y=this.detectRebindConflict(d);if(U(d,!S),k!==null){let b=L("ingest.anomaly",{class:"nk-conflict",nk:{source:R.source,stream:R.stream,sourceId:R.sourceId,rev:N},existingId:k.existingId,newId:d.id,hashes:[k.existingHash,F]});this.maybeEscalateRecurringConflicts(R,L),m={id:d.id,outcome:"anomaly",anomalyId:b.id}}else if(y!==null){let b=L("ingest.anomaly",{class:"rebind-conflict",...y,eventId:d.id});m={id:d.id,outcome:"anomaly",anomalyId:b.id}}else{let b=c3(d.kind);if(b===void 0){if(this.db.query("SELECT 1 AS x FROM unknown_kinds WHERE source = ? AND kind = ?").get(R.source,d.kind)===null)L("ingest.unknown-kind",{source:R.source,kind:d.kind,firstEventId:d.id});m={id:d.id,outcome:"appended"}}else if(b.validatePayload!==void 0){let g=b.validatePayload(d.payload);if(!K(g)){let w="err"in g?g.err.message:"payload empty",u=L("ingest.anomaly",{class:"schema-violation",eventId:d.id,kind:d.kind,detail:w});m={id:d.id,outcome:"anomaly",anomalyId:u.id}}else m={id:d.id,outcome:"appended"}}else m={id:d.id,outcome:"appended"}}V.push(m)}if(W.length>0){let D=this.writer.appendFrames(W,nH(Z,W.map((P)=>P.kind)));B=!0,X.mutated=!0,this.synchronizeWriterAppend(W,D,q,j),this.db.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('watermark', ?)").run(W[W.length-1].id)}l.clearTwinDirty(this.db),this.db.exec("COMMIT")}catch(U){let L=null;try{this.db.exec("ROLLBACK")}catch(D){L=D}if(B||!this.writer.acceptsAppends||L!==null)return X.mutated=!0,X.admissionProven=!1,this.writeRecoveryRequired=!0,n("aborted",`append failed after physical segment truth may have changed; a durable physical batch may exist without synchronized twin accounting (${String(U)}${L===null?"":`; twin rollback also failed: ${String(L)}`}). Same-handle retry is forbidden; close and reopen for segment-authoritative recovery before retry`,"retry-at-higher-level");return n("internal",`append failed before physical segment mutation; synchronized twin transaction rolled back: ${String(U)}`,"transient")}return H(V)}validateHard($,Z,Q){if($===null||typeof $!=="object")return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"protoEvent: expected an object"};let X=this.streams.get(Y0($.nk?.source,$.nk?.stream)),z=X===void 0?void 0:{revOrder:X.revOrder,...X.quality!==void 0&&X.quality!=="synthetic"?{quality:X.quality}:{}},Y=a4($,z);if(!K(Y))return Y.err;let j=$.nk.sourceId??"";if(X?.quality==="synthetic"&&j==="")return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: quality 'synthetic' stream reached the appender un-synthesized \u2014 the framework's '${X.stream}' synthesizer runs BEFORE append (\xA72.3 step 0)`};if(X===void 0&&j==="")return{code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:`nk.sourceId: undeclared stream '${$.nk.source}/${$.nk.stream}' cannot synthesize identity \u2014 declare the stream's I-1 quality`};if(Z.kind==="connector"&&$.nk.source!==Z.source)return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:`origin 'connector:${Z.source}' may append only nk.source == its own source; got '${$.nk.source}' (\xA72.2)`};let W=c3($.kind);if(W!==void 0){let V=W.internalOnly===!0&&!Q,q=!W.allowedOrigins.includes(Z.kind);if(V||q){if(W.verdictClass===!0||W.securityOnForgery===!0||W.fm15OnForgery===!0)this.appendInternalUnlessClosed([{kind:"security.incident",payload:{class:W.verdictClass===!0?"verdict-forgery":W.securityOnForgery===!0?"erasure-forgery":"fm15-append-authority",kind:$.kind,origin:Z.kind,detail:"write-authority violation at the single write gate (I-5 isolation, event-log \xA72.2; flywheel \xA73.2)"}}]);return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:V?`kind '${$.kind}' is appender/erasure-job emitted only \u2014 a caller append is a forgery (\xA72.5)`:`kind '${$.kind}' allows origins [${W.allowedOrigins.join(", ")}]; origin '${Z.kind}' denied (\xA72.2 kind-level ACL)`}}}return null}checkTombstones($,Z,Q){let X=I9(this.db,"SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND content_hash = ?").get($.source,$.stream,$.sourceId,Z);if(X!==null)return{id:X.tomb_id,outcome:"erased-suppressed"};let z=I9(this.db,"SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND future_too = 1").get($.source,$.stream,$.sourceId);if(z!==null){if(this.db.query(`SELECT id FROM events
367
+ WHERE kind = 'erasure.suppressed' AND erased = 0
368
+ AND json_extract(payload, '$.tomb') = ?
369
+ AND json_extract(payload, '$.nk.source') = ?
370
+ AND json_extract(payload, '$.nk.stream') = ?
371
+ AND json_extract(payload, '$.nk.sourceId') = ?`).get(z.tomb_id,$.source,$.stream,$.sourceId)===null)Q("erasure.suppressed",{nk:{source:$.source,stream:$.stream,sourceId:$.sourceId},tomb:z.tomb_id});return{id:z.tomb_id,outcome:"erased-suppressed"}}return null}conflictSiblingWithHash($,Z,Q){let X=this.db.query("SELECT id, rev FROM events WHERE source = ? AND stream = ? AND source_id = ? AND content_hash = ? AND erased = 0").all($.source,$.stream,$.sourceId,Q);for(let z of X){let Y=AZ(z.rev);if(Y!==null&&Y.base===Z)return{id:z.id}}return null}nextConflictN($){let Z=this.db.query("SELECT rev FROM events WHERE source = ? AND stream = ? AND source_id = ? AND rev LIKE ?").all($.source,$.stream,$.sourceId,`${$.rev}#c%`),Q=0;for(let X of Z){let z=AZ(X.rev);if(z!==null&&z.base===$.rev&&z.n>Q)Q=z.n}return Q+1}maybeEscalateRecurringConflicts($,Z){let Q=this.db.query("SELECT payload FROM events WHERE kind = 'ingest.anomaly' AND erased = 0").all(),X=0;for(let z of Q){if(z.payload===null)continue;let Y=JSON.parse(z.payload);if(Y.class==="nk-conflict"&&Y.nk?.source===$.source&&Y.nk?.stream===$.stream)X++}if(X===5)Z("security.incident",{class:"recurring-nk-conflict",source:$.source,stream:$.stream,detail:"5 nk-conflicts on one stream \u2014 injection signature (FM-25, event-log \xA72.3 step 4)"})}detectRebindConflict($){if($.kind!=="identity.rebind"||$.payload===void 0)return null;let Z=$.payload;if(!Z.from||!Z.to)return null;let Q=this.db.query("SELECT to_source, to_stream, to_source_id FROM rebinds WHERE from_source = ? AND from_stream = ? AND from_source_id = ?").get(Z.from.source,Z.from.stream,Z.from.sourceId);if(Q===null)return null;if(Q.to_source===Z.to.source&&Q.to_stream===Z.to.stream&&Q.to_source_id===Z.to.sourceId)return null;return{from:{source:Z.from.source,stream:Z.from.stream,sourceId:Z.from.sourceId},existingTo:{source:Q.to_source,stream:Q.to_stream,sourceId:Q.to_source_id},attemptedTo:{source:Z.to.source,stream:Z.to.stream,sourceId:Z.to.sourceId}}}stampInternal($){let Z=$.origin??{kind:"kernel"},Q=$.ts??this.now(),X=$.kind,z=Z0({kind:X,body:"",payload:$.payload}),Y;if($.nk!==void 0&&$.nk.sourceId!==void 0&&$.nk.rev!==void 0)Y={source:$.nk.source,stream:$.nk.stream,sourceId:$.nk.sourceId,rev:$.nk.rev};else Y={source:"zortex",stream:X.startsWith("identity.")?"identity":X.startsWith("ingest.")?"ingest":X.startsWith("erasure.")?"erasure":X.startsWith("security.")?"security":"system",sourceId:NZ("occurrence",z,Q),rev:"0"};let j={id:this.ulid(),nk:Y,contentHash:z,canon:J8,ts:Q,observedTs:this.now(),trust:dH(Z,Y),origin:Z,tier:"first-party",kind:X,schemaVersion:1,policyVersion:this.policyVersion(),mentions:[],body:""};if($.payload!==void 0)j.payload=$.payload;return j}appendInternalUnlessClosed($,Z=!1){if(this.closed||$.length===0)return[];let Q=this.writeHandleError("internal event append");if(Q!==null)throw Object.assign(Error(Q.message),{code:Q.code,structuredError:Q});if(!Z){let V=l.validateTwinWriteState(this.db,"internal event append");if(V!==null)throw Object.assign(Error(V.message),{code:V.code,structuredError:V})}let X=$.map((V)=>this.stampInternal(V)),z=this.writer.filePath===null?1:this.writer.lineCount,Y=this.writer.segmentId,j=!1;this.db.exec("BEGIN IMMEDIATE");let W=this.lockedWriteError("internal event append");if(W!==null)throw this.db.exec("ROLLBACK"),Object.assign(Error(W.message),{code:W.code,structuredError:W});try{let V=z;for(let B of X){if(Y===null)Y=B.id;q1(this.db,B,Y,V,!0),B1(this.db,B),V++}let q=this.writer.appendFrames(X,nH(X[0]?.origin??{kind:"kernel"},X.map((B)=>B.kind)));j=!0,this.synchronizeWriterAppend(X,q,Y,z),this.db.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('watermark', ?)").run(X[X.length-1].id),l.clearTwinDirty(this.db),this.db.exec("COMMIT")}catch(V){let q=null;try{this.db.exec("ROLLBACK")}catch(B){q=B}if(j||!this.writer.acceptsAppends||q!==null){this.writeRecoveryRequired=!0;let B={code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:`internal event append failed after physical segment truth may have changed; a durable physical batch may exist without synchronized twin accounting (${String(V)}${q===null?"":`; twin rollback also failed: ${String(q)}`}). Same-handle retry is forbidden; close and reopen for segment-authoritative recovery before retry`};throw Object.assign(Error(B.message),{code:B.code,structuredError:B})}throw V}return X.map((V)=>V.id)}emitSpan($,Z,Q,X,z,Y=!1,j=!1){let W={traceId:this.ulid(),spanId:this.ulid(),name:$,attrs:X,status:z===void 0?"ok":"error",startTs:Z,durationMs:Math.max(0,Math.round(Q*1000)/1000)};if(z!==void 0)W.error=z;let V=j&&!this.writeRecoveryRequired&&this.writer.acceptsAppends?l.validateTwinWriteState(this.db,"trace span append"):this.twinWriteError("trace span append");if(Y&&V===null)this.appendInternalUnlessClosed([{kind:"trace.span",payload:W,nk:{source:"zortex",stream:"trace",sourceId:W.spanId,rev:"0"}}],!0);return this.opts.onSpan?.(W),W}watermark(){let $=l.validateTwinWatermark(this.db,"event-log watermark");if(!K($))throw new l$($.err);return $.ok}async readGeneration(){let $=this.now(),Z=performance.now(),Q=this.closed?n("failed_precondition","event log closed"):await FH(_$(this.logDir,"log.db")),X=K(Q)?void 0:Q.err;return this.emitSpan("log.read-generation",$,performance.now()-Z,K(Q)?{untilSeq:Q.ok.untilSeq,projectionEpoch:Q.ok.projectionEpoch}:{},X,!1),Q}async evidenceMetadata($){let Z=this.now(),Q=performance.now(),X=null,z;if(this.closed)z=n("failed_precondition","event log closed");else if(!Array.isArray($)||$.length>Dz||$.some((j)=>!q$(j)))z=n("invalid_argument",`evidenceMetadata requires at most ${Dz} canonical event ULIDs`);else{let j=[...new Set($)];if(j.length===0)z=H({found:[],missing:[]});else{let W=await MQ.open({type:"open",operation:"evidence-metadata",dbPath:_$(this.logDir,"log.db"),ids:j},this.readSessionIdleMs,(V,q)=>{this.emitSpan("log.read-lease-expired",this.now(),0,{operation:"evidence-metadata",untilSeq:q.untilSeq,projectionEpoch:q.projectionEpoch},V,!1)});if(!K(W))z=W;else{let V=W.ok;X=V.generation;let q=new Map;try{for(;;){let G=await V.nextBatch();if(!K(G))throw new l$(G.err);for(let J of G.ok.rows){let U=J,L={id:U.id,source:U.source,stream:U.stream,sourceId:U.source_id,rev:U.rev,kind:U.kind,nk:{source:U.source,stream:U.stream,sourceId:U.source_id,rev:U.rev},ts:U.ts,contentHash:U.content_hash,segment:U.segment,line:U.line,origin:U.origin===null?null:JSON.parse(U.origin),erased:U.erased===1};if(U.coverage!==null)L.coverage=JSON.parse(U.coverage);if(U.incident_state!==null)L.incidentState=U.incident_state;q.set(U.id,L)}if(G.ok.done)break}z=H({found:j.flatMap((G)=>{let J=q.get(G);return J===void 0?[]:[J]}),missing:j.filter((G)=>!q.has(G))})}catch(G){z={err:G1(G,"log.evidence-metadata").structuredError}}let B=await V.close();if(!K(B)&&K(z))z=B}}}let Y=K(z)?void 0:("err"in z)?z.err:void 0;return this.emitSpan("log.evidence-metadata",Z,performance.now()-Q,{requested:Array.isArray($)?$.length:0,...X===null?{}:{untilSeq:X.untilSeq,projectionEpoch:X.projectionEpoch},...K(z)?{found:z.ok.found.length,missing:z.ok.missing.length}:{}},Y,!1),z}async*readRows($,Z,Q,X,z,Y,j){let W=this.now(),V=performance.now(),q=0,B="early-break",G=null,J=null,U=null;try{if(this.closed)throw new l$({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"event log closed"});if(Z?.afterSeq!==void 0&&!q$(Z.afterSeq))throw new l$({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"scan afterSeq must be a canonical ULID"});if(Z?.untilSeq!==void 0&&!q$(Z.untilSeq))throw new l$({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"scan untilSeq must be a canonical ULID"});if(Z?.projectionEpoch!==void 0&&(!Number.isSafeInteger(Z.projectionEpoch)||Z.projectionEpoch<0))throw new l$({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"scan projectionEpoch must be a non-negative safe integer"});if($==="source-text"&&(Z?.untilSeq===void 0||Y===void 0||Y.trim()===""||Buffer.byteLength(Y)>PH))throw new l$({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"scanSourceText requires one bounded source and one inclusive untilSeq watermark"});let L=await MQ.open({type:"open",operation:$,dbPath:_$(this.logDir,"log.db"),...Z===void 0?{}:{range:Z},...Q===void 0?{}:{filter:Q},...Y===void 0?{}:{source:Y},...j===void 0?{}:{nkBase:j}},this.readSessionIdleMs,(D,P)=>{this.emitSpan("log.read-lease-expired",this.now(),0,{operation:$,untilSeq:P.untilSeq,projectionEpoch:P.projectionEpoch},D,!1)});if(!K(L))throw new l$(L.err);G=L.ok,J=G.generation;for(;;){let D=await G.nextBatch();if(!K(D))throw new l$(D.err);for(let P of D.ok.rows){let F=G.renewIdleLease();if(!K(F))throw new l$(F.err);let A=z(P);q++,yield A}if(D.ok.done){B="completed";break}}}catch(L){throw U=G1(L,X),B="failed",U}finally{let L=null;if(G!==null){let D=await G.close();if(!K(D))L=new l$(D.err)}if(L!==null&&U===null)U=L,B="failed";if(this.emitSpan(X,W,performance.now()-V,{yielded:q,outcome:B,...J===null?{}:{untilSeq:J.untilSeq,projectionEpoch:J.projectionEpoch},...Y===void 0?{}:{source:Y}},U?.structuredError,!1),L!==null&&U===L)throw L}}async*scan($,Z){yield*this.readRows("scan",$,Z,"log.scan",(Q)=>{let X=Q;return X.erased===1?H1(X):V5(X)})}async*scanMetadata($,Z){yield*this.readRows("metadata",$,Z,"log.scan-metadata",(Q)=>{let X=Q,z={id:X.id,source:X.source,stream:X.stream,sourceId:X.source_id,rev:X.rev,kind:X.kind,nk:{source:X.source,stream:X.stream,sourceId:X.source_id,rev:X.rev},ts:X.ts,contentHash:X.content_hash,segment:X.segment,line:X.line,origin:X.origin===null?null:JSON.parse(X.origin),erased:X.erased===1};if(X.coverage!==null)z.coverage=JSON.parse(X.coverage);return z})}async*scanSourceText($,Z){yield*this.readRows("source-text",Z,void 0,"log.scan-source-text",(Q)=>{let X=Q,z={id:X.id,nk:{source:X.source,stream:X.stream,sourceId:X.source_id,rev:X.rev},contentHash:X.content_hash,canon:X.canon,ts:X.ts,observedTs:X.observed_ts,trust:JSON.parse(X.trust),origin:JSON.parse(X.origin),tier:X.tier,kind:X.kind,schemaVersion:X.schema_version,body:X.body};if(X.policy_version!==null)z.policyVersion=X.policy_version;if(X.coverage!==null)z.coverage=JSON.parse(X.coverage);if(X.lang!==null)z.lang=X.lang;return z},$)}async chainAsync($,Z){let Q=[];try{for await(let X of this.readRows("chain",Z,void 0,"log.chain-async",(z)=>z,void 0,$))Q.push(X)}catch(X){return{err:G1(X,"log.chain-async").structuredError}}return H(this.orderChain(Q,$).map((X)=>X.erased===1?H1(X):V5(X)))}async headAsync($,Z){let Q=await this.chainAsync($,Z);if(!K(Q))return Q;if(Q.ok.length===0)return G$(`no events under nk base ${$.source}/${$.stream}/${$.sourceId} (rebind-closed lookup)`);for(let X=Q.ok.length-1;X>=0;X--){let z=Q.ok[X];if(!b0(z))return H(z)}return G$(`all ${Q.ok.length} revisions erased \u2014 tombstones retained (erased \u2260 never-existed)`)}rebindClosure($){let Z=(z)=>`${z.source} ${z.stream} ${z.sourceId}`,Q=new Map([[Z($),$]]),X=[$];while(X.length>0){let z=X.pop(),Y=this.db.query("SELECT to_source AS s, to_stream AS t, to_source_id AS i FROM rebinds WHERE from_source = ? AND from_stream = ? AND from_source_id = ?").all(z.source,z.stream,z.sourceId),j=this.db.query("SELECT from_source AS s, from_stream AS t, from_source_id AS i FROM rebinds WHERE to_source = ? AND to_stream = ? AND to_source_id = ?").all(z.source,z.stream,z.sourceId);for(let W of[...Y,...j]){let V={source:W.s,stream:W.t,sourceId:W.i};if(!Q.has(Z(V)))Q.set(Z(V),V),X.push(V)}}return[...Q.values()]}chainRowsForBase($){let Z=this.rebindClosure($),Q=[];for(let X of Z){let z=this.db.query("SELECT * FROM events WHERE source = ? AND stream = ? AND source_id = ?").all(X.source,X.stream,X.sourceId);Q.push(...z)}return this.orderChain(Q,$)}orderChain($,Z){let Q=this.streams.get(Y0(Z.source,Z.stream)),X;if(Q!==void 0)X=Q.revOrder;else if($.length>0&&$.every((j)=>j.unique_nk===0))X="head-compare";else X="upstream-version";let z=(j,W)=>j.id<W.id?-1:j.id>W.id?1:0;if(X==="head-compare")return $.sort(z);let Y=X==="event-ts"?bz:Q?.comparator==="numeric"?fF:bz;return $.sort((j,W)=>{let V=PV(j.rev,W.rev,Y);return V!==0?V:z(j,W)})}chain($){return this.assertTwinReadable("event-log chain"),this.chainRowsForBase($).map((Z)=>Z.erased===1?H1(Z):V5(Z))}head($){let Z=this.twinReadError("event-log head");if(Z!==null)return{err:Z};let Q=this.rebindClosure($),X=[];for(let Y of Q){let j=this.db.query("SELECT id, rev, unique_nk, erased FROM events WHERE source = ? AND stream = ? AND source_id = ?").all(Y.source,Y.stream,Y.sourceId);X.push(...j)}if(X.length===0)return G$(`no events under nk base ${$.source}/${$.stream}/${$.sourceId} (rebind-closed lookup)`);let z=this.orderChain(X,$);for(let Y=z.length-1;Y>=0;Y--){let j=z[Y];if(j.erased===0){let W=this.db.query("SELECT * FROM events WHERE id = ?").get(j.id);if(W===null)return n("data_loss",`head row ${j.id} vanished between the chain walk and its fetch \u2014 twin corruption`,"non-retryable");return H(V5(W))}}return G$(`all ${z.length} revisions erased \u2014 tombstones retained (erased \u2260 never-existed)`)}headMany($){let Z=new Map;if($.length===0)return Z;let Q=(J)=>`${J.source}/${J.stream}/${J.sourceId}`,X=this.twinReadError("event-log headMany");if(X!==null){for(let J of $)Z.set(Q(J),{err:X});return Z}let z=new Map,Y=new Map;for(let J of $){let U=Q(J);if(Y.has(U))continue;let L=this.rebindClosure(J);Y.set(U,L);for(let D of L){let P=Q(D),F=z.get(P);if(F===void 0)z.set(P,[U]);else F.push(U)}}let j=[...z.keys()],W=new Map,V=200;for(let J=0;J<j.length;J+=V){let U=j.slice(J,J+V),L=U.map(()=>"(?,?,?)").join(","),D=[];for(let F of U){let A=F.indexOf("/"),N=F.indexOf("/",A+1);D.push(F.slice(0,A),F.slice(A+1,N),F.slice(N+1))}let P=this.db.query(`SELECT id, rev, unique_nk, erased, source, stream, source_id FROM events WHERE (source, stream, source_id) IN (VALUES ${L})`).all(...D);for(let F of P){let A=`${F.source}/${F.stream}/${F.source_id}`;for(let N of z.get(A)??[]){let S=W.get(N);if(S===void 0)W.set(N,[F]);else S.push(F)}}}let q=new Map;for(let J of $){let U=Q(J);if(Z.has(U)||q.has(U))continue;let L=W.get(U)??[];if(L.length===0){Z.set(U,G$(`no events under nk base ${J.source}/${J.stream}/${J.sourceId} (rebind-closed lookup)`));continue}let D=this.orderChain(L,J),P=!1;for(let F=D.length-1;F>=0;F--){let A=D[F];if(A.erased===0){q.set(U,A.id),P=!0;break}}if(!P)Z.set(U,G$(`all ${D.length} revisions erased \u2014 tombstones retained (erased \u2260 never-existed)`))}let B=[...new Set(q.values())],G=new Map;for(let J=0;J<B.length;J+=V){let U=B.slice(J,J+V),L=this.db.query(`SELECT * FROM events WHERE id IN (${U.map(()=>"?").join(",")})`).all(...U);for(let D of L)G.set(D.id,D)}for(let[J,U]of q){let L=G.get(U);if(L===void 0){Z.set(J,n("data_loss",`head row ${U} vanished between the chain walk and its fetch \u2014 twin corruption`,"non-retryable"));continue}try{Z.set(J,H(V5(L)))}catch(D){Z.set(J,n("data_loss",`event ${U} has a malformed stored envelope: ${D instanceof Error?D.message:String(D)}`,"non-retryable"))}}return Z}headById($){let Z=this.twinReadError("event-log headById");if(Z!==null)return{err:Z};let Q=this.db.query("SELECT * FROM events WHERE id = ?").get($);if(Q===null)return G$(`no event with id '${$}' \u2014 id-addressed twin lookup`);if(Q.erased!==0)return G$(sH($));try{return H(V5(Q))}catch(X){return n("data_loss",`event ${$} has a malformed stored envelope: ${X instanceof Error?X.message:String(X)}`,"non-retryable")}}resolveMentions($){let Z=this.opts.resolution;if(Z===void 0)return{resolved:$.map((X)=>({...X,assertedBy:[]})),resolution:{asOf:mH,stale:!0}};return{resolved:$.map((X)=>{let z={...X,assertedBy:[]};if(X.handle!==void 0){let Y=Z.lookup(X.handle);if(Y!==null)z.entity=Y.entity,z.confidence=Y.confidence,z.assertedBy=Y.assertedBy}return z}),resolution:{asOf:Z.asOf(),stale:Z.stale()}}}artifactError($){let Z=this.opts.authorization?.trailerKey??"Authorized-By",Q=this.opts.authorization?.founderIdentity;if($===void 0||$.kind!=="oq12-git-trailer"||typeof $.trailer!=="string")return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"erasure requires the user-held OQ-12 authorization artifact (L0 interim: the founder-identity git trailer) \u2014 origin alone is NOT authority (event-log \xA73.6); nothing scrubbed"};let X=new RegExp(`^${Z}:\\s*(\\S.*)$`).exec($.trailer.trim());if(X===null||Q!==void 0&&X[1].trim()!==Q)return{code:"permission_denied",layer:"storage",retryability:"non-retryable",message:`erasure authorization artifact rejected: trailer must read '${Z}: <founder identity>' (OQ-12 interim marker, event-log \xA79.9); nothing scrubbed`};return null}forgedErasure($){return this.appendInternalUnlessClosed([{kind:"security.incident",payload:{class:"erasure-forgery",detail:$}}]),n("permission_denied",$)}requestErasure($,Z){let Q=this.twinWriteError("erasure request");if(Q!==null)return{err:Q};let X=this.artifactError(Z);if(X!==null)return this.forgedErasure(X.message);let z=$.selector;if(!z||!z.ids&&!z.nkBase&&!z.source)return n("invalid_argument","erasure selector must name ids, an nkBase, or source(+tsRange)");let[Y]=this.appendInternalUnlessClosed([{kind:"erasure.requested",origin:{kind:"user"},payload:{selector:z,futureToo:$.futureToo===!0,reason:$.reason}}]);if(Y===void 0)return n("internal","erasure.requested append failed");this.journalErasure(Y,"SCOPING");let j=this.computeScope(Y,z);if(!K(j))return this.journalErasure(Y,"PARTIAL",{error:j.err}),j;let W=j.ok;return this.journalErasure(Y,"AWAITING_CONFIRM",{scope:W}),H(W)}computeScope($,Z){let Q=new Set,X=(q)=>q.startsWith("erasure.");if(Z.ids!==void 0)for(let q of Z.ids){let B=this.db.query("SELECT id, kind, erased FROM events WHERE id = ?").get(q);if(B===null)return n("not_found",`erasure selector id ${q} does not exist \u2014 never-existed \u2260 erased \u2260 empty`);if(B.erased===0&&!X(B.kind))Q.add(B.id)}if(Z.nkBase!==void 0){for(let q of this.chainRowsForBase(Z.nkBase))if(q.erased===0&&!X(q.kind))Q.add(q.id)}if(Z.source!==void 0){let q=this.db.query("SELECT id, kind, ts FROM events WHERE source = ? AND erased = 0").all(Z.source);for(let B of q){if(X(B.kind))continue;if(Z.tsRange!==void 0&&(B.ts<Z.tsRange.from||B.ts>Z.tsRange.to))continue;Q.add(B.id)}}let z=[],Y=!0;while(Y){Y=!1;let q=this.db.query(`SELECT id, payload FROM events WHERE erased = 0 AND payload LIKE '%"evidence"%'`).all();for(let B of q){if(Q.has(B.id)||B.payload===null)continue;let G=JSON.parse(B.payload);if(!Array.isArray(G.evidence)||G.evidence.length===0)continue;let J=G.evidence.filter((L)=>typeof L==="string"),U=J.filter((L)=>Q.has(L));if(U.length===0)continue;if(U.length===J.length)Q.add(B.id),Y=!0;else if(!z.includes(B.id))z.push(B.id)}}let j=[...Q].sort(),W=new Map;for(let q of j){let B=this.db.query("SELECT blobs FROM events WHERE id = ?").get(q);if(B?.blobs==null)continue;for(let G of JSON.parse(B.blobs)){if(W.has(G.sha256))continue;let U=this.db.query("SELECT id FROM events WHERE erased = 0 AND blobs LIKE ?").all(`%${G.sha256}%`).some((L)=>!Q.has(L.id));W.set(G.sha256,U)}}let V=this.db.query("SELECT ts FROM events WHERE id = ?").get($)?.ts??this.now();return H({jobId:$,ids:j,blobs:[...W.entries()].map(([q,B])=>({sha256:q,shared:B})).sort((q,B)=>bz(q.sha256,B.sha256)),reDerive:z.sort(),distillationCaveat:oH,lapseAt:new Date(Date.parse(V)+hH).toISOString()})}journalErasure($,Z,Q={},X){let z=this.now(),Y={jobId:$,state:Z};for(let[W,V]of Object.entries(Q))if(V!==void 0)Y[W]=V;let j={traceId:$,spanId:this.ulid(),name:"erasure.step",attrs:Y,status:X===void 0?"ok":"error",startTs:z,durationMs:0};if(X!==void 0)j.error=X;this.appendInternalUnlessClosed([{kind:"trace.span",payload:j,nk:{source:"zortex",stream:"trace",sourceId:j.spanId,rev:"0"}}]),this.opts.onSpan?.(j)}erasureJob($){let Z=this.db.query("SELECT job_id, state, scope, last_completed, error FROM erasure_jobs WHERE job_id = ?").get($);if(Z===null)return n("not_found",`no erasure job ${$}`);let Q={jobId:Z.job_id,state:Z.state};if(Z.scope!==null)Q.scope=JSON.parse(Z.scope);if(Z.last_completed!==null)Q.lastCompleted=Z.last_completed;if(Z.error!==null)Q.error=JSON.parse(Z.error);return Q.jobId?H(Q):n("internal","unreachable")}confirmErasure($,Z){let Q=this.twinWriteError("erasure confirmation");if(Q!==null)return{err:Q};let X=this.artifactError(Z);if(X!==null)return this.forgedErasure(X.message);let z=this.erasureJob($);if(!K(z))return z;let Y=z.ok;if(Y.state!=="AWAITING_CONFIRM")return n("failed_precondition",`erasure job ${$} is ${Y.state}, not AWAITING_CONFIRM${Y.state==="PARTIAL"?" \u2014 use resumeErasure":""}`);let j=Y.scope;if(Date.parse(this.now())>Date.parse(j.lapseAt))return this.journalErasure($,"LAPSED"),n("failed_precondition",`erasure request ${$} lapsed (no confirm within 7 days) \u2014 nothing scrubbed (\xA73.6)`);return this.runScrub($,j,0)}resumeErasure($){let Z=this.twinWriteError("erasure resume");if(Z!==null)return{err:Z};let Q=this.erasureJob($);if(!K(Q))return Q;let X=Q.ok;if(X.state!=="PARTIAL")return n("failed_precondition",`erasure job ${$} is ${X.state}, not PARTIAL`);let z=X.lastCompleted===void 0?0:A1.indexOf(X.lastCompleted)+1;return this.runScrub($,X.scope,z)}runScrub($,Z,Q){let X=this.jobRequestedFutureToo($);for(let z=Q;z<A1.length;z++){let Y=A1[z];try{if(Y==="SCRUBBING_LOG")this.stepScrubLog(Z,X);else if(Y==="SCRUBBING_BLOBS")this.stepScrubBlobs(Z);else if(Y==="SCRUBBING_DERIVED"){if(this.opts.erasureHooks?.scrubDerived)this.opts.erasureHooks.scrubDerived(Z.ids)}else if(Y==="REPROJECTING"){if(this.opts.erasureHooks?.reproject)this.opts.erasureHooks.reproject(Z.ids)}else if(Y==="VERIFYING")this.stepVerify(Z);this.journalErasure($,Y,{lastCompleted:Y})}catch(j){let W={code:j.code==="data_loss"?"data_loss":"internal",layer:"storage",retryability:"retry-at-higher-level",message:`erasure step ${Y} failed: ${j.message??String(j)}`};if(this.twinIsDirty())return n("data_loss",`${W.message}; synchronized twin is recovery-gated and must be reopened before erasure resumes`,"retry-at-higher-level");let V=z===0?void 0:A1[z-1];return this.journalErasure($,"PARTIAL",{failedStep:Y,lastCompleted:V,error:W},W),this.erasureJob($)}}return this.journalErasure($,"DONE"),this.erasureJob($)}jobRequestedFutureToo($){let Z=this.db.query("SELECT request FROM erasure_jobs WHERE job_id = ?").get($);if(Z===null)return!1;return JSON.parse(Z.request)?.futureToo===!0}rejectTombProjection($){throw l.markTwinDirty(this.db,"tomb-authority-projection-mismatch"),Object.assign(Error($),{code:"data_loss"})}validatedTombProjection($,Z,Q){if(!q$($.id)||!q$(Z))return this.rejectTombProjection(`${Q}: tombstone projection contains a non-canonical event id`);let X={id:$.id,nk:{source:$.source,stream:$.stream,sourceId:$.source_id,rev:$.rev},ts:$.ts,kind:$.kind,contentHash:$.content_hash,tomb:Z},z=l.liveDbEvent(this.db,X.tomb);if(z!==null&&!K(g5(z)))return this.rejectTombProjection(`${Q}: authorizer ${X.tomb} has an invalid stored envelope`);let Y=l.validateTombAuthorization(X,z,Q);if(!K(Y))return this.rejectTombProjection(Y.err.message);if($.erased===1&&!l.erasedRowMatchesTomb($,X))return this.rejectTombProjection(`${Q}: erased row ${$.id} retains content or differs from its tomb skeleton`);return X}validateRawAuthorizationsForTombs($,Z){let Q=new Set($.map((j)=>j.tomb)),X=new Set;for(let j of Q){let W=this.db.query("SELECT segment, erased FROM events WHERE id = ?").get(j);if(W===null||W.erased!==0)return n("data_loss",`${Z}: raw authorizer ${j} has no synchronized live location`);X.add(W.segment)}let z=new Map,Y=null;for(let j of X){let W=p5(_$(this.logDir,`seg-${j}.zev`),void 0,(V)=>{if(!Q.has(V.id))return;if(z.has(V.id))Y=V.id;else z.set(V.id,V)});if(!K(W))return W}if(Y!==null)return n("data_loss",`${Z}: duplicate raw authorizer ${Y}`);for(let j of $){let W=z.get(j.tomb)??null,V=l.validateTombAuthorization(j,W,Z);if(!K(V))return V;let q=l.liveDbEvent(this.db,j.tomb);if(W===null||q===null||!K5(W,q))return n("data_loss",`${Z}: raw authorizer ${j.tomb} differs from its synchronized envelope`)}return H(!0)}stepScrubLog($,Z){for(let Y of $.ids){let j=this.db.query("SELECT * FROM events WHERE id = ?").get(Y);if(j===null)throw Error(`scoped id ${Y} vanished`);let W=this.db.query("SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND rev = ?").get(j.source,j.stream,j.source_id,j.rev);if(W!==null){if(this.validatedTombProjection(j,W.tomb_id,`live erasure preflight for ${Y}`),j.erased===1)continue}if(W===null&&j.erased===1)this.rejectTombProjection(`live erasure preflight for ${Y}: erased row has no tombstone projection`);if(W===null){if(this.appendInternalUnlessClosed([{kind:"erasure.tombstone",payload:{erasedId:Y,nk:{source:j.source,stream:j.stream,sourceId:j.source_id,rev:j.rev},ts:j.ts,kind:j.kind,contentHash:j.content_hash,futureToo:Z}}]).length!==1)this.rejectTombProjection(`live erasure preflight for ${Y}: authorizer append did not return exactly one event id`)}}let Q=new Map,X=[];for(let Y of $.ids){let j=this.db.query("SELECT * FROM events WHERE id = ?").get(Y);if(j===null)this.rejectTombProjection(`live erasure preflight for ${Y}: scoped row vanished`);let W=this.db.query("SELECT tomb_id FROM tombstones t JOIN events e ON e.id = ? WHERE t.source = e.source AND t.stream = e.stream AND t.source_id = e.source_id AND t.rev = e.rev").get(Y);if(W===null)this.rejectTombProjection(`live erasure preflight for ${Y}: tombstone projection missing`);if(X.push(this.validatedTombProjection(j,W.tomb_id,`live erasure preflight for ${Y}`)),j.erased===1)continue;if(!Q.has(j.segment))Q.set(j.segment,new Map);Q.get(j.segment).set(Y,W.tomb_id)}if(X.length>0&&this.writer.segmentId!==null)this.sealActiveSegment();let z=this.validateRawAuthorizationsForTombs(X,"live erasure preflight");if(!K(z))this.rejectTombProjection(z.err.message);if(Q.size>0)l.markTwinDirty(this.db,"erasure-segment-surgery-in-progress");this.db.exec("BEGIN IMMEDIATE");try{for(let[Y,j]of Q){let W=_$(this.logDir,`seg-${Y}.zev`),V=a7(W,j);if(!K(V))throw Object.assign(Error(V.err.message),{code:V.err.code});let q=[...j.keys()].sort(),B=[...new Set(V.ok.applied)].sort();if(V.ok.segment!==Y||q.length!==B.length||q.some((G,J)=>G!==B[J]))throw Object.assign(Error(`segment surgery receipt mismatch for ${Y}: refusing to scrub the synchronized twin`),{code:"data_loss"});this.db.query("UPDATE segments SET rewrite_gen = ? WHERE segment = ?").run(V.ok.rewriteGen,Y),l.recordSealedFingerprint(this.db,W);for(let G of j.keys()){let J=j.get(G);Uz(this.db,G,J)}}for(let Y of $.ids){let j=this.db.query("SELECT erased, source, stream, source_id, rev FROM events WHERE id = ?").get(Y);if(j!==null&&j.erased===0){let W=this.db.query("SELECT tomb_id FROM tombstones WHERE source = ? AND stream = ? AND source_id = ? AND rev = ?").get(j.source,j.stream,j.source_id,j.rev);if(W!==null)Uz(this.db,Y,W.tomb_id)}}l.refreshProjectionEpoch(this.db),l.clearTwinDirty(this.db),this.db.exec("COMMIT")}catch(Y){throw this.db.exec("ROLLBACK"),Y}}stepScrubBlobs($){for(let Z of $.blobs){let Q=this.db.query("SELECT refcount FROM blob_refs WHERE sha256 = ?").get(Z.sha256);if(Q!==null&&Q.refcount<=0)this.blobs.unlink(Z.sha256)}}stepVerify($){let Z=new Map,Q=[];for(let z of $.ids){let Y=this.db.query("SELECT * FROM events WHERE id = ?").get(z);if(Y===null||Y.erased!==1)this.rejectTombProjection(`erased id ${z} still live in the twin`);let j=Z.get(Y.segment);if(j===void 0){let V=d0(_$(this.logDir,`seg-${Y.segment}.zev`));if(!K(V))this.rejectTombProjection(V.err.message);if(j=V.ok,Z.set(Y.segment,j),!E8(j).chainIntact)this.rejectTombProjection(`segment ${Y.segment} chain broken post-surgery`)}let W=j.entries.find((V)=>(V.kind==="tomb"?V.tomb.id:V.frame.rec.id)===z);if(W===void 0||W.kind!=="tomb")this.rejectTombProjection(`event ${z} not tombstoned in segment ${Y.segment}`);if(!l.erasedRowMatchesTomb(Y,W.tomb))this.rejectTombProjection(`event ${z} synchronized erased row differs from the raw tomb skeleton`);Q.push(W.tomb)}let X=this.validateRawAuthorizationsForTombs(Q,"erasure VERIFYING");if(!K(X))this.rejectTombProjection(X.err.message);for(let z of $.blobs){let Y=this.db.query("SELECT refcount FROM blob_refs WHERE sha256 = ?").get(z.sha256),j=Y!==null&&Y.refcount>0;if(!j&&this.blobs.has(z.sha256))throw Object.assign(Error(`zero-ref blob ${z.sha256} still on disk`),{code:"data_loss"});if(j&&!this.blobs.has(z.sha256))throw Object.assign(Error(`shared blob ${z.sha256} missing \u2014 over-scrub`),{code:"data_loss"})}}sealActiveSegment(){if(this.writer.segmentId===null)return;let $=this.writer.seal();if($===null)throw Error("active segment seal returned no descriptor proof");this.db.exec("BEGIN IMMEDIATE");try{this.db.query("UPDATE segments SET sealed = 1 WHERE segment = ?").run($.segment),l.recordSealedProof(this.db,$),this.db.exec("COMMIT")}catch(Z){throw this.db.exec("ROLLBACK"),Z}this.writer=new l3(this.logDir,J8,this.now)}inspect(){let $=(Z)=>this.db.query(Z).get().c;return{events:$("SELECT COUNT(*) AS c FROM events"),erased:$("SELECT COUNT(*) AS c FROM events WHERE erased = 1"),tombstones:$("SELECT COUNT(*) AS c FROM tombstones"),pendingRefsDepth:$("SELECT COUNT(*) AS c FROM pending_refs"),dedupIndexRows:$("SELECT COUNT(*) AS c FROM events WHERE unique_nk = 1"),unknownKinds:$("SELECT COUNT(*) AS c FROM unknown_kinds"),blobRefs:$("SELECT COUNT(*) AS c FROM blob_refs WHERE refcount > 0"),watermark:this.watermark(),segments:this.db.query("SELECT * FROM segments ORDER BY segment").all().map((Z)=>({segment:Z.segment,file:Z.file,sealed:Z.sealed===1,rewriteGen:Z.rewrite_gen,count:Z.count}))}}static validateAuthorityGenerationFiles($,Z,Q){let X=l.listSegmentFiles($);if(!K(X))return X;if(!K5(X.ok,Z)||!K5(Q.map((Y)=>Y.file),Z))return n("unavailable","segment verification candidate set changed before its success stamp","transient");for(let Y of Q){let j=W5(_$($,Y.file));if(!K(j))return j;if(j.ok.state!=="sealed"||j.ok.segmentId!==Y.segment||j.ok.count!==Y.count||j.ok.fingerprint!==Y.fingerprint)return n("unavailable",`segment verification descriptor generation changed at ${Y.file}`,"transient")}let z=l.listSegmentFiles($);if(!K(z))return z;return K5(z.ok,Z)?H(!0):n("unavailable","segment verification candidate set changed during descriptor recheck","transient")}static verifySegmentsStreamingGeneration($,Z,Q,X,z={}){let Y=l.listSegmentFiles($);if(!K(Y))return Y;let j=Y.ok,W=[],V;try{if(X!==void 0)Y$(X,"verification-catalog-create");V=Y1.create($)}catch(J){return{err:U$(J,"could not create verification authority catalog",{code:"unavailable",retryability:"transient"})}}let q=!1,B=()=>{if(q)return{ok:[]};q=!0;try{return{ok:V.remove(z)}}catch(J){let U=null;try{V.close()}catch(L){U=L}return{err:U$(U===null?J:AggregateError([J,U]),`verification authority catalog cleanup threw${U===null?"":" and descriptor close failed"}`,{code:"unavailable",retryability:"transient"})}}},G=(J)=>{if(q)return{err:J};if(X!==void 0)try{Y$(X,"verification-catalog-cleanup")}catch(D){try{V.close()}catch(P){return{err:U$(AggregateError([D,P]),"verification catalog retained after writer-lock loss and close failed",{code:"unavailable",retryability:"transient"})}}return{err:U$(D,"verification catalog retained after writer-lock loss",{code:"unavailable",retryability:"transient"})}}let U=B();if("err"in U)return n("unavailable",`${J.message}; ${U.err.message}`,"transient","storage");let L=U.ok;if(L.length===0)return{err:J};return n("unavailable",`${J.message}; verification catalog cleanup failed: ${L.join(" | ")}`,"transient","storage")};try{for(let U of j){if(X!==void 0)Y$(X,"verification-catalog-segment-stage");let L=U.slice(4,-4);V.beginSegment();let D=null,P=p5(_$($,U),(F,A)=>{try{V.stageTomb(F,L,A)}catch(N){throw D=N,N}},(F,A)=>{try{V.stageEvent(F,L,A)}catch(N){throw D=N,N}});if(D!==null)return V.rollbackSegment(),G(U$(D,`segment verification authority join rejected ${U}`,{code:"data_loss",retryability:"non-retryable"}));if(!K(P))return V.rollbackSegment(),G(P.err);if(X!==void 0)Y$(X,"verification-catalog-segment-commit");V.commitSegment(U,P.ok),W.push(P.ok)}let J=!1;try{if(X!==void 0)Y$(X,"verification-authority-transaction");Z.exec("BEGIN IMMEDIATE"),J=!0;let U=l.validateTwinAuthorityAccounting(Z,$,V);if(!K(U)){let N=U.err;throw Object.assign(Error(N.message),{structured:N})}let L=l.validateTwinTombGeneration(Z,V);if(!K(L)){let N=L.err;throw Object.assign(Error(N.message),{structured:N})}let D=[...V.segments()];if(X!==void 0)Y$(X,"verification-catalog-cleanup");let P=B();if("err"in P)throw Object.assign(Error(P.err.message),{structured:P.err});let F=P.ok;if(F.length>0){let N={code:"unavailable",layer:"storage",retryability:"transient",message:`segment verification passed but authority catalog cleanup failed: ${F.join(" | ")}`};throw Object.assign(Error(N.message),{structured:N})}let A=l.validateAuthorityGenerationFiles($,j,D);if(!K(A)){let N=A.err;throw Object.assign(Error(N.message),{structured:N})}if(X!==void 0)Y$(X,"verification-authority-stamp");return Z.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(w8,m8),Z.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('segment-verify:last-success', ?)").run(Q),Z.query("DELETE FROM meta WHERE key = 'segment-verify:last-failure'").run(),Z.exec("COMMIT"),J=!1,H(W)}catch(U){let L=null;if(J)try{Z.exec("ROLLBACK")}catch(P){L=P}let D=U.structured;if(L===null&&D!==void 0)return G(D);return G(U$(L===null?U:AggregateError([U,L]),`segment verification stamp failed${L===null?"":" and rollback failed"}`,{code:"internal",retryability:"transient"}))}}catch(J){return G(U$(J,"segment verification authority catalog failed",{code:"data_loss",retryability:"non-retryable"}))}}verifySegmentsStreaming($){let Z=this.writerLock===null?void 0:(Q)=>{let X=C1(this.writerLock,this.opts.writerLockRaceHooks??{},Q);if(!K(X))this.writeRecoveryRequired=!0;return X};return l.verifySegmentsStreamingGeneration(this.logDir,this.db,$,Z,this.opts.ownedPathRaceHooks)}recordSegmentVerificationFailure($,Z){if(this.writerLock===null)return n("unavailable",`segment verification failed (${Z.code}: ${Z.message}); its diagnostic write was refused because writer-lock ownership is missing`,"transient");let Q=C1(this.writerLock,this.opts.writerLockRaceHooks??{},"verification-failure-diagnostic");if(!K(Q)){let X="err"in Q?Q.err.message:Q.empty.how;return n("unavailable",`segment verification failed (${Z.code}: ${Z.message}); its diagnostic write was refused: ${X}`,"transient")}try{return this.db.query("INSERT OR REPLACE INTO meta (key, value) VALUES ('segment-verify:last-failure', ?)").run(JSON.stringify({ts:$,error:Z})),H(!0)}catch(X){return{err:U$(X,`segment verification failed (${Z.code}: ${Z.message}); its diagnostic write also failed`,{code:"internal",retryability:"transient"})}}}finishSegmentVerificationFailure($,Z){this.writeRecoveryRequired=!0;let Q=this.recordSegmentVerificationFailure($,Z);if(!K(Q))return Q;return{err:Z}}verifySegmentsIfDue(){let $=this.twinWriteError("scheduled segment sweep");if($!==null)return{err:$};let Z=this.now(),Q=Date.parse(Z);if(!Number.isFinite(Q))return n("invalid_argument",`event-log clock returned an invalid instant: ${Z}`);let X=this.db.query("SELECT value FROM meta WHERE key = 'segment-verify:last-success'").get()?.value,z=X===void 0?Number.NaN:Date.parse(X);if(!(!Number.isFinite(z)||z>Q||Q-z>=hH))return H({ran:!1,reports:[]});let j=this.verifySegmentsStreaming(Z);if(!K(j))return this.finishSegmentVerificationFailure(Z,j.err);return H({ran:!0,reports:j.ok})}verifySegments(){let $=this.twinWriteError("segment sweep");if($!==null)return{err:$};let Z=this.now();if(this.ownsWriterLock&&this.writer.segmentId!==null)try{this.sealActiveSegment()}catch(X){return this.finishSegmentVerificationFailure(Z,U$(X,"segment verification could not seal its active segment",{code:"internal",retryability:"transient"}))}let Q=this.verifySegmentsStreaming(Z);if(!K(Q))return this.finishSegmentVerificationFailure(Z,Q.err);return Q}twinSnapshot(){return this.assertTwinReadable("event-log twin snapshot"),DH(this.db)}close(){if(this.closed)return;this.refuseQueuedAppends();let $=null;try{if(this.ownsWriterLock&&this.writer.segmentId!==null)if(this.twinWriteError("event-log close")!==null)this.writer.closeWithoutSeal();else{let X=this.writer.seal();if(X===null)throw Error("event-log close seal returned no descriptor proof");this.db.exec("BEGIN IMMEDIATE");try{this.db.query("UPDATE segments SET sealed = 1 WHERE segment = ?").run(X.segment),l.recordSealedProof(this.db,X),this.db.exec("COMMIT")}catch(z){throw this.db.exec("ROLLBACK"),z}}}catch(Q){$=Q}this.closed=!0;try{UQ(this.db,"event-log close")}catch(Q){}this.readPermit?.release();let Z=null;if(this.writerLock!==null){let Q=this.writerLock;this.writerLock=null;let X=Iz(Q,this.opts.writerLockRaceHooks);if(!K(X))Z=Error("err"in X?X.err.message:X.empty.how)}if($!==null&&Z!==null)throw AggregateError([$,Z],"event-log close and writer-lock release failed");if($!==null)throw $;if(Z!==null)throw Z}}var b9="00000000000000000000000000",n5=500,T1,iH="no last-good log view exists yet",yF,mH="1970-01-01T00:00:00.000Z",hH=604800000,w8="tomb-authority-proof-version",m8="2",uH,EF,vF,A1,oH="Methodology already distilled into global skill transfers (D14/D17) cannot be recalled; by D17 construction it contains no raw data, quotes, names, or identifying patterns, but the erased content's influence on shipped methodology is irrecoverable.";var kz=E(()=>{f();y7();r7();$z();KH();Kz();MH();W1();NH();b7();Vz();ZQ();gH();T1=RF(_1(OF(import.meta.url)),"..","..","..","events");yF=/^seg-[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}\.zev$/,uH=/^\.(?:recovery-catalog|verify-authority)\.[0-9]+\.[0-9a-z]+\.[0-9a-z]+\.db(?:-(?:wal|shm))?$/,EF=/^\.catalog-reclaim\.[0-9]+\.[0-9a-z]+\.[0-9a-z]+\.receipt\.json$/,vF=["pending_refs","resolved_refs","claims","tombstones","rebinds","unknown_kinds","blob_refs","erasure_jobs","segments","events"],A1=["SCRUBBING_LOG","SCRUBBING_BLOBS","SCRUBBING_DERIVED","REPROJECTING","VERIFYING"]});var aH=E(()=>{f();kz()});var F0=E(()=>{kz();W1();y7();$z();r7();E7();aH()});function C($,Z,Q="non-retryable",X){return v({code:$,layer:"connector",retryability:Q,message:Z,...X!==void 0?{cause:X}:{}})}function W$($,Z){return v({code:"failed_precondition",layer:"connector",retryability:"non-retryable",message:`'${$}' is blocked by ${Z}`})}function n8($){return($.code==="unauthenticated"||$.code==="permission_denied")&&$.layer!=="storage"}var _0=E(()=>{f()});function lN($,Z,Q,X){let z=(j)=>{let W=X.justifications?.[j];return typeof W==="string"&&W.trim()!==""};if(JJ[$.taint]<JJ[Z.defaultTaint]&&!z($.name))return C("invalid_argument",`action '${$.name}': taint '${$.taint}' is weaker than the manifest defaultTaint floor '${Z.defaultTaint}' \u2014 requires explicit reviewer-approved justification (connectors \xA72.1)`);if($.effect.class!=="read"&&$.verification.method==="none"&&!z($.name))return C("invalid_argument",`action '${$.name}': verification.method 'none' on a '${$.effect.class}' effect is an FM-15 hole \u2014 declare a probe or an explicit justification (connectors \xA72.3c)`);let Y=$.effect.compensation;if(Y!==void 0){if(!Q.has(Y.action))return C("invalid_argument",`action '${$.name}': compensation.action '${Y.action}' is not a declared action (connectors \xA72.3d)`);let j=Z.actions.find((W)=>W.name===Y.action);if(!(j.idempotency.supported||j.verification.method!=="none"))return C("invalid_argument",`action '${$.name}': compensation.action '${Y.action}' is not retry-safe (needs idempotency.supported or a verification probe \u2014 connectors \xA72.3d)`)}for(let j of $.escalateWhen??[])if(GJ[j.class]<GJ[$.effect.class])return C("invalid_argument",`action '${$.name}': escalateWhen class '${j.class}' is BELOW the declared effect class '${$.effect.class}' \u2014 escalation may never downgrade (connectors \xA72.3f)`);return H(!0)}function X6($,Z={}){let Q=qK($);if(!K(Q))return Q;let X=Q.ok,z=new Set,Y=new Map;for(let W of X.streams){if(z.has(W.stream))return C("invalid_argument",`duplicate stream declaration '${W.stream}'`);if(z.add(W.stream),W.kinds.length===0)return C("invalid_argument",`stream '${W.stream}' declares no kinds \u2014 an unreachable stream is a lie`);let V=W.deleteKind!==void 0?[...W.kinds,W.deleteKind]:W.kinds;for(let q of V){let B=Y.get(q);if(B!==void 0&&B!==W.stream)return C("invalid_argument",`kind '${q}' is declared by streams '${B}' and '${W.stream}' \u2014 every emitted event belongs to EXACTLY ONE declared stream (connectors \xA72.1)`);Y.set(q,W.stream)}}let j=new Set;for(let W of X.actions){if(j.has(W.name))return C("invalid_argument",`duplicate action declaration '${W.name}'`);j.add(W.name)}for(let W of X.actions){let V=lN(W,X,j,Z);if(!K(V))return V}for(let W of Object.keys(X.actionScopes??{}))if(!j.has(W))return C("invalid_argument",`actionScopes names undeclared action '${W}' \u2014 least-grant input must reference a declared contract (connectors \xA72.1)`);if(X.retaliationRisk==="banning"&&(X.tier==="api"||X.tier==="mcp-wrapped"||X.tier==="browser-driven"))return C("invalid_argument",`retaliationRisk 'banning' forbids active tier '${X.tier}' \u2014 route to passive/local/screen tiers (connectors \xA72.1 D9 gating)`);return H(X)}function AY($,Z){let Q=$.streams.find((X)=>X.stream===Z);if(Q===void 0)return C("invalid_argument",`undeclared stream '${Z}'`);return H(Q)}function i8($,Z={}){return $.streams.map((Q)=>{let X={source:$.source,stream:Q.stream,revOrder:Q.revOrder,quality:Q.identity.quality};if(Q.identity.noneIdentity!==void 0)X.noneIdentity=Q.identity.noneIdentity;if(Q.revOrder==="upstream-version")X.comparator=Z[Q.stream]??"numeric";return X})}var JJ,GJ;var uQ=E(()=>{f();_0();JJ={"quoted-only":2,"summarized-only":1,unrestricted:0},GJ={read:0,create:1,update:2,delete:3,dispatch:4}});function cN($){if($==="")return C("invalid_argument","path synthesizer: empty input");let Z=$.normalize("NFC").replace(/\\/g,"/"),Q=Z.startsWith("/"),X=[];for(let Y of Z.split("/")){if(Y===""||Y===".")continue;if(Y===".."){if(X.length>0&&X[X.length-1]!=="..")X.pop();else if(!Q)X.push("..");continue}X.push(Y)}let z=X.join("/");return H(Q?`/${z}`:z===""?".":z)}function dN($){let Z;try{Z=new URL($.normalize("NFC"))}catch{return C("invalid_argument",`url synthesizer: unparseable URL '${$}'`)}let Q=[...Z.searchParams.entries()].sort(([z,Y],[j,W])=>z<j?-1:z>j?1:Y<W?-1:Y>W?1:0),X=Q.length>0?`?${Q.map(([z,Y])=>`${encodeURIComponent(z)}=${encodeURIComponent(Y)}`).join("&")}`:"";return H(`${Z.protocol}//${Z.host}${Z.pathname}${X}`)}function nN($){if($==="")return C("invalid_argument","hash synthesizer: empty input");return H(L$($))}function _Y($,Z){if(!U8.includes($))return C("invalid_argument",`unknown synthesizer '${String($)}'`);return UJ[$].canonicalize(Z)}function TY($,Z){if($==="")return C("invalid_argument","epoch prefix: empty epoch token");if(Z==="")return C("invalid_argument","epoch prefix: empty bare sourceId");return H(`${encodeURIComponent($)}:${Z}`)}function SY($){if(!$.includes("#")&&!$.includes("%"))return $;return $.replace(/%/g,"%25").replace(/#/g,"%23")}var UJ;var RY=E(()=>{f();_0();UJ={path:{kind:"path",version:1,canonicalize:cN},url:{kind:"url",version:1,canonicalize:dN},hash:{kind:"hash",version:1,canonicalize:nN}}});class z6{source;grantId;claimedFrom=new Set;globalsById=new Map;scoped=[];constructor($,Z){this.source=$;this.grantId=Z}recordGlobal($,Z){if($.from.source!==this.source)return;let Q=iN($);if(this.claimedFrom.has(Q))return;if(this.claimedFrom.add(Q),!Z||$.reason!=="provider-documented"||$.rebindId===void 0||$.to.source!==this.source)return;let X=$;if(this.globalsById.has(X.rebindId))this.globalsById.set(X.rebindId,null);else this.globalsById.set(X.rebindId,X)}recordScoped($){if($.source===this.source&&$.grantId===this.grantId)this.scoped.push($)}acceptedScoped(){let $=new Set,Z=[];for(let Q of this.scoped){let X=this.globalsById.get(Q.rebindId);if(X===void 0||X===null||$.has(Q.rebindId))continue;if(!sN(X,Q))continue;$.add(Q.rebindId),Z.push(Q)}return Z}}var iN=($)=>`${$.from.source}\x00${$.from.stream}\x00${$.from.sourceId}`,sN=($,Z)=>$.from.source===Z.from.source&&$.from.stream===Z.from.stream&&$.from.sourceId===Z.from.sourceId&&$.to.source===Z.to.source&&$.to.stream===Z.to.stream&&$.to.sourceId===Z.to.sourceId;import{createHash as oN}from"crypto";function pQ($,Z){return oN("sha256").update(`${$.length}:${$}:${Z}`).digest("hex")}function aN($,Z,Q,X){let z=new Map;for(let V of $?.values()??[])z.set(V,(z.get(V)??0)+1);let Y=[...z].sort(([V],[q])=>V<q?-1:1).map(([V,q])=>({cause:V,count:q})),j=Y.reduce((V,q)=>V+q.count,0);if(Z===void 0)return{containedByRail:Y,contained:0};let W=Z-Q-X;return{containedByRail:Y,contained:W>0?Math.min(j,W):0}}function rN($){let Z=$.expected===void 0?$.containedByRail.reduce((X,z)=>X+z.count,0):$.contained,Q=[];for(let{cause:X,count:z}of $.containedByRail){if(Z<=0)break;let Y=Math.min(z,Z);Z-=Y,Q.push({cause:X,count:Y})}return Q}function tN($){return rN($).map(({cause:Z,count:Q})=>({reason:`${LJ}:${Z}`,count:Q}))}class Y6{source;grantId;census=null;nks=new Map;deleteKinds;aliases=new Map;contained=new Map;constructor($,Z){this.source=$.source,this.grantId=Z,this.deleteKinds=new Map($.streams.map((Q)=>[Q.stream,Q.deleteKind]))}canonId($,Z){let Q=this.aliases.get($);if(Q===void 0)return Z;let X=Z;for(let z=0;z<100;z++){let Y=Q.get(X);if(Y===void 0)return X;X=Y}return X}recordRebind($,Z,Q){let X=this.aliases.get($);if(X===void 0)X=new Map,this.aliases.set($,X);X.set(Z,Q);let z=this.nks.get($);if(z===void 0)return;let Y=z.get(Z);if(Y===void 0)return;z.delete(Z);let j=this.canonId($,Q),W=z.get(j);if(W===void 0)z.set(j,Y);else W.deleted=W.deleted&&Y.deleted}recordContained($,Z,Q){let X=this.contained.get($);if(X===void 0)X=new Map,this.contained.set($,X);X.set(Z,Q)}settleContainment(){for(let[$,Z]of this.contained){if(Z.size===0)continue;for(let Q of this.nks.get($)?.keys()??[])Z.delete(pQ($,Q))}}record($,Z,Q,X){let z=this.nks.get($);if(z===void 0)z=new Map,this.nks.set($,z);let Y=this.canonId($,Z),j=this.contained.get($);if(j!==void 0&&j.size>0)j.delete(pQ($,Y));let W=Q===this.deleteKinds.get($)||X==="erased-suppressed",V=z.get(Y);if(V===void 0)z.set(Y,{deleted:W});else if(W)V.deleted=!0;else if(X==="appended")V.deleted=!1}observeCensus($){this.census=$}get lastCensus(){return this.census}censusStaleness($){if(this.census===null)return"never";let Z=Date.parse($)-Date.parse(this.census.asOf);if(Z>MJ)return"incident";if(Z>DJ)return"degraded";return"fresh"}rows(){let $=new Set([...this.nks.keys(),...this.contained.keys(),...Object.keys(this.census?.streams??{})]),Z=[];for(let Q of[...$].sort()){let X=this.nks.get(Q),z=0,Y=0;for(let B of X?.values()??[])if(B.deleted)Y++;else z++;let j=this.census?.streams[Q],W=j?.partialReasons??[],V=W.reduce((B,G)=>B+(G.count??0),0),q={stream:Q,attributed:V,attributedReasons:W,...aN(this.contained.get(Q),j?.total,V,z),coveredLive:z,coveredDeleted:Y};if(j!==void 0){if(q.method=j.method,j.total!==void 0)q.expected=j.total}Z.push(q)}return Z}reconcile($){if($===null||typeof $!=="object")return C("invalid_argument","reconcile: census required (FM-18 source of truth)");this.census=$;let Z=[];for(let Q of this.rows()){let X=tN(Q);if(Q.expected===void 0){let j=[...Q.attributedReasons,...X];Z.push({stream:Q.stream,kind:"no-total",enumerated:Q.coveredLive+Q.coveredDeleted,...j.length>0?{reasons:j}:{}});continue}let z=Q.expected-Q.attributed,Y=Q.coveredLive+Q.contained;if(Q.coveredLive>z)Z.push({stream:Q.stream,kind:"duplicate-object",expected:Q.expected,covered:Q.coveredLive,surplus:Q.coveredLive-z});else if(Y<z)Z.push({stream:Q.stream,kind:"unattributed-gap",expected:Q.expected,covered:Q.coveredLive,gap:z-Y});else if(Q.attributed>0||X.length>0)Z.push({stream:Q.stream,kind:"attributed",reasons:[...Q.attributedReasons,...X]});else Z.push({stream:Q.stream,kind:"clean"})}return H(Z)}snapshot(){let $={};for(let[Q,X]of[...this.nks.entries()].sort(([z],[Y])=>z<Y?-1:1)){let z=[],Y=[];for(let[j,W]of X)(W.deleted?Y:z).push(j);$[Q]={live:z.sort(),deleted:Y.sort()}}let Z={};for(let[Q,X]of[...this.contained.entries()].sort(([z],[Y])=>z<Y?-1:1)){let z={};for(let[Y,j]of X)(z[j]??=[]).push(Y);for(let Y of Object.keys(z))z[Y].sort();Z[Q]=z}return{source:this.source,grantId:this.grantId,census:this.census,streams:$,contained:Z}}}var LJ="contained-by-rail",DJ=604800000,MJ=1209600000;var lQ=E(()=>{f();F0();_0()});import{createHash as eN}from"crypto";function $A($){let Z=[...new Set($)],Q=[],X="";for(let z of Z){if(z.length===0||z.length>uZ)return C("data_loss",`I-7 detector pattern name is outside the 1..${uZ} character incident contract`);let Y=X===""?z:`${X}, ${z}`;if(Y.length<=uZ){X=Y;continue}Q.push(X),X=z}if(X!=="")Q.push(X);return H(Q)}function PJ($,Z){let Q=$.raw;if(Q===null||typeof Q!=="object"||Array.isArray(Q))return;return Q[Z]}function ZA($,Z,Q,X){let z=Z.identity.quality;if(z==="container-scoped"){let Y=Z.identity.epochField,j=PJ(Q,Y);if(j===void 0||j===null||typeof j==="object")return C("invalid_argument",`stream '${Z.stream}': container-scoped epoch field '${Y}' missing from the raw item \u2014 the framework cannot prefix the epoch (connectors \xA72.2)`);return TY(String(j),X.nk.sourceId??"")}if(z==="synthetic"){let Y=$.identityInput?.(Q)??(Z.identity.idField!==void 0?PJ(Q,Z.identity.idField):void 0);if(typeof Y!=="string"||Y==="")return C("invalid_argument",`stream '${Z.stream}': synthetic identity input missing \u2014 the connector must supply identityInput(item) (or declare idField) for the '${Z.identity.synthesizer}' synthesizer (connectors \xA72.4)`);return _Y(Z.identity.synthesizer,Y)}return H(X.nk.sourceId??"")}function QA($){return $.replace(/(data:[a-zA-Z0-9.+/-]+;base64,)([A-Za-z0-9+/=]{64,})/g,(Z,Q,X)=>`${Q}<media:${eN("sha256").update(X).digest("hex")}>`)}function j6($,Z,Q,X){let z=[],Y=[],j=[];for(let W of Q){let V=AY(Z,W.streamRef);if(!K(V))return V;let q=V.ok,B=$.detectRebind?.(W)??null;if(B!==null){let F=q.identity.rebindOn??[];if(q.identity.quality!=="durable-with-exceptions"||!F.includes(B.condition))return C("invalid_argument",`stream '${q.stream}': identity exception '${B.condition}' is not a documented rebindOn condition \u2014 undocumented provider behavior is drift (FM-19; connectors \xA72.2)`);Y.push({from:{source:Z.source,stream:q.stream,sourceId:B.from},to:{source:Z.source,stream:q.stream,sourceId:B.to},reason:"provider-documented"})}let G;try{G=$.normalize(W)}catch(F){return C("invalid_argument",`normalize threw on a '${W.streamRef}' item: ${String(F)} \u2014 normalize is PURE and total over pulled items (connectors \xA72.4)`)}if(G.nk.source!==Z.source)return C("invalid_argument",`draft nk.source '${G.nk.source}' \u2260 manifest source '${Z.source}' \u2014 identity is deterministic from upstream facts of THIS source (I-1)`);if(G.nk.stream!==W.streamRef)return C("invalid_argument",`draft nk.stream '${G.nk.stream}' \u2260 pulled streamRef '${W.streamRef}' \u2014 every event belongs to exactly one declared stream (\xA72.1)`);if(G.kind!==q.deleteKind&&!q.kinds.includes(G.kind))return C("invalid_argument",`kind '${G.kind}' is not declared by stream '${q.stream}' (kinds [${q.kinds.join(", ")}]${q.deleteKind!==void 0?` + deleteKind '${q.deleteKind}'`:""}) \u2014 undeclared emit fails lint (\xA72.1)`);if(G.coverage!==void 0)return C("invalid_argument","draft carries 'coverage' \u2014 coverage.phase has exactly ONE producer (the framework); connectors never set it (connectors \xA72.4)");if(G.nk.rev!==void 0&&G.nk.rev!=="")G={...G,nk:{...G.nk,rev:SY(G.nk.rev)}};let J=a4(G,{revOrder:q.revOrder,quality:q.identity.quality});if(!K(J))return J;let U=ZA($,q,W,G);if(!K(U))return U;let L=q.identity.quality==="none"?NZ(q.identity.noneIdentity??"occurrence",Z0({kind:G.kind,body:G.body,payload:G.payload,blobs:G.blobs}),G.ts):U.ok,D=l0(QA(JSON.stringify({body:G.body,payload:G.payload??null,refs:G.refs??null,mentions:G.mentions})));if(D.length>0){let F=$A(D.map((N)=>N.pattern));if(!K(F))return F;let A=pQ(q.stream,L);for(let N of F.ok)j.push({stream:q.stream,pattern:N,identity:A});continue}let P={...G,nk:{...G.nk,...L!==""&&q.identity.quality!=="none"?{sourceId:L}:{}},coverage:{phase:X.phase,syncRun:X.syncRun}};z.push({draft:P,stream:q.stream,sourceId:L,kind:G.kind})}return H({drafts:z,rebinds:Y,leaks:j})}var OY=E(()=>{f();_9();f();_0();RY();lQ();uQ()});function IY($,Z,Q=0.5){let z=Math.min((Z==="throttling"?300000:30000)*2**Math.max(0,$),3600000),Y=(Q*2-1)*0.2;return Math.round(z*(1+Y))}function yY($){return $==="transient"||$==="throttling"}class W6{capacity;refillPerMinute;tokens;lastRefillMs;constructor($=10,Z=1,Q=0){this.capacity=$;this.refillPerMinute=Z;this.tokens=$,this.lastRefillMs=Q}refill($){let Z=($-this.lastRefillMs)/60000;if(Z<=0)return;this.tokens=Math.min(this.capacity,this.tokens+Z*this.refillPerMinute),this.lastRefillMs=$}available($){return this.refill($),Math.floor(this.tokens)}take($){if(this.refill($),this.tokens<1)return!1;return this.tokens-=1,!0}nextTokenAtMs($){if(this.refill($),this.tokens>=1)return $;let Z=1-this.tokens;return $+Math.ceil(Z/this.refillPerMinute*60000)}}var xY=5;function l9($){return Date.parse($)}function CJ($){if($===null||typeof $!=="object")return null;let Z=$;if(typeof Z.code!=="string"||typeof Z.message!=="string")return null;let Q=typeof Z.layer==="string"?Z.layer:"connector",X=typeof Z.retryability==="string"?Z.retryability:"non-retryable";return{code:Z.code,layer:Q,retryability:X,message:Z.message}}class cQ{source;grantId;stateValue="IDLE";runIdValue=null;attemptValue=0;healAttemptValue=0;backoffDueAtValue=null;stateEnteredAtValue;lastProgressAtValue=null;lastSyncedValue=null;lastReprobeAtValue=null;lastErrorValue=null;pendingBackfillValue=!1;openIncidents=new Map;openRepairs=new Map;emit;now;jitter;quota;ulid=V$();replaying=!1;constructor($){this.source=$.source,this.grantId=$.grantId,this.emit=$.emit,this.now=$.now,this.jitter=$.jitter??Math.random,this.quota=$.retryQuota??new W6,this.stateEnteredAtValue=this.now()}get state(){return this.stateValue}get runId(){return this.runIdValue}get attempt(){return this.attemptValue}get healAttempt(){return this.healAttemptValue}get backoffDueAt(){return this.backoffDueAtValue}get lastSynced(){return this.lastSyncedValue}get pendingBackfill(){return this.pendingBackfillValue}get stateEnteredAt(){return this.stateEnteredAtValue}get lastError(){return this.lastErrorValue}hasOpenIncident($){return this.openIncidents.has($)}hasOpenRepair($){return this.openRepairs.has($)}refuse($){return C("failed_precondition",`sync machine (${this.source}, ${this.grantId}): transition '${$}' is not declared from state '${this.stateValue}' (FM-22: every transition is declared; \xA73.5)`)}transition($,Z,Q={}){let X=this.stateValue;if(this.stateValue=$,this.stateEnteredAtValue=this.now(),$==="PULLING")this.lastProgressAtValue=this.stateEnteredAtValue;return this.lastErrorValue=CJ(Q.error)??($==="IDLE"||$==="DISCOVERING"||$==="PULLING"?null:this.lastErrorValue),this.emit("sync.run.transition",{source:this.source,grantId:this.grantId,runId:this.runIdValue,from:X,to:$,cause:Z,attempt:this.attemptValue,healAttempt:this.healAttemptValue,pendingBackfill:this.pendingBackfillValue,backoffDueAt:this.backoffDueAtValue,lastSynced:this.lastSyncedValue,at:this.stateEnteredAtValue,...Q}),$}fileIncident($){if(this.openIncidents.has($.cause))return;this.openIncidents.set($.cause,!0),this.emit("sync.incident.filed",{source:this.source,grantId:this.grantId,runId:this.runIdValue,cause:$.cause,class:$.class,detail:$.detail??null,at:this.now()})}fileRepair($){if(this.openRepairs.has($))return;this.openRepairs.set($,!0),this.emit("sync.repair.filed",{source:this.source,grantId:this.grantId,runId:this.runIdValue,cause:$,at:this.now()})}freshRun(){this.runIdValue=this.ulid(),this.attemptValue=0,this.healAttemptValue=0,this.backoffDueAtValue=null}schedule($="schedule"){if(this.stateValue!=="IDLE")return this.refuse("schedule");return this.freshRun(),H(this.transition("DISCOVERING",$))}censusOk(){if(this.stateValue!=="DISCOVERING")return this.refuse("censusOk");return H(this.transition("PULLING","census-ok"))}grantAuthError($){if(this.stateValue!=="DISCOVERING"&&this.stateValue!=="PULLING"&&this.stateValue!=="RECONCILING")return this.refuse("grantAuthError");return H(this.transition("AUTH_BLOCKED","auth-error",{error:$}))}batchProgress(){if(this.stateValue!=="PULLING")return this.refuse("batchProgress");return this.lastProgressAtValue=this.now(),H(!0)}routePageError($){if(this.stateValue!=="PULLING")return this.refuse("routePageError");if(($.code==="unauthenticated"||$.code==="permission_denied")&&$.layer!=="storage")return this.transition("AUTH_BLOCKED","auth-error",{error:$}),H({to:"AUTH_BLOCKED"});if(yY($.retryability)){if(this.attemptValue>=xY)return this.enterErrored(`retries-exhausted:${$.code}`,$),H({to:"ERRORED"});let Z=l9(this.now()),Q=Z+IY(this.attemptValue,$.retryability,this.jitter());if($.retryability==="throttling"&&!this.quota.take(Z))Q=Math.max(Q,this.quota.nextTokenAtMs(Z));return this.attemptValue+=1,this.backoffDueAtValue=new Date(Q).toISOString(),this.transition("RETRY_WAIT",`page-error:${$.retryability}`,{error:$}),H({to:"RETRY_WAIT",backoffDueAt:this.backoffDueAtValue,attempt:this.attemptValue})}if($.retryability==="retry-at-higher-level")return this.transition("IDLE","run-failed",{error:$}),H({to:"IDLE",runFailed:!0});return this.enterErrored($.code,$),H({to:"ERRORED"})}enterErrored($,Z){this.transition("ERRORED",`non-retryable:${$}`,{error:Z}),this.fileRepair($),this.fileIncident({cause:$,class:"fm19-errored",detail:{code:Z.code,message:Z.message}})}phaseFailed($){if(this.stateValue!=="DISCOVERING"&&this.stateValue!=="RECONCILING")return this.refuse("phaseFailed");return H(this.transition("IDLE","run-failed",{error:$}))}backoffDue(){if(this.stateValue!=="RETRY_WAIT")return this.refuse("backoffDue");let $=this.backoffDueAtValue;if($!==null&&l9(this.now())<l9($))return C("failed_precondition",`sync machine (${this.source}, ${this.grantId}): backoff not due until ${$} (durable schedule \u2014 restarts never reset it)`);return this.backoffDueAtValue=null,H(this.transition("PULLING","backoff-due"))}exhausted(){if(this.stateValue!=="PULLING")return this.refuse("exhausted");return H(this.transition("RECONCILING","exhausted"))}reconcileClean(){if(this.stateValue!=="RECONCILING")return this.refuse("reconcileClean");return this.lastSyncedValue=this.now(),this.attemptValue=0,this.healAttemptValue=0,this.pendingBackfillValue=!1,H(this.transition("IDLE","reconcile-clean"))}reconcileGapAttributed($){if(this.stateValue!=="RECONCILING")return this.refuse("reconcileGapAttributed");return this.lastSyncedValue=this.now(),this.attemptValue=0,this.healAttemptValue=0,this.pendingBackfillValue=!1,H(this.transition("IDLE","gap-attributed",{reasons:$}))}reconcileGapUnattributed($){if(this.stateValue!=="RECONCILING")return this.refuse("reconcileGapUnattributed");if(this.healAttemptValue>=FJ)return this.fileIncident({cause:"fm18-unattributed-gap",class:"fm18-gap",detail:$}),H(this.transition("INCIDENT","gap-persists-at-K",{gap:$}));return this.healAttemptValue+=1,this.pendingBackfillValue=!0,H(this.transition("PULLING",`heal:${this.healAttemptValue}`,{gap:$}))}duplicateObjectSignal($){if(this.stateValue!=="RECONCILING")return this.refuse("duplicateObjectSignal");return this.fileIncident({cause:"identity-misdeclaration",class:"reclassify-rebind",detail:$}),H(this.transition("INCIDENT","duplicate-object-signal",{detail:$}))}cursorExpired(){if(this.stateValue!=="PULLING")return this.refuse("cursorExpired");return this.pendingBackfillValue=!0,this.emit("sync.cursor.expired",{source:this.source,grantId:this.grantId,runId:this.runIdValue,at:this.now()}),H(!0)}streamStalled($){if(this.stateValue!=="PULLING")return this.refuse("streamStalled");return this.fileIncident({cause:"stream-stall",class:"fm21-stream-stall",detail:$}),H(this.transition("IDLE","stream-stall",{detail:$}))}checkTimeout(){let $=l9(this.now()),Z=(Q,X)=>$-l9(X)>=Q;if(this.stateValue==="DISCOVERING"&&Z(c9.DISCOVERING,this.stateEnteredAtValue))return this.fileIncident({cause:"timeout:DISCOVERING",class:"fm22-timeout",detail:{limitMs:c9.DISCOVERING}}),H({timedOut:!0,state:this.transition("IDLE","timeout:DISCOVERING")});if(this.stateValue==="PULLING"&&Z(c9.PULLING,this.lastProgressAtValue??this.stateEnteredAtValue))return this.fileIncident({cause:"timeout:PULLING",class:"fm22-timeout",detail:{limitMs:c9.PULLING}}),H({timedOut:!0,state:this.transition("IDLE","timeout:PULLING")});if(this.stateValue==="RECONCILING"&&Z(c9.RECONCILING,this.stateEnteredAtValue))return this.fileIncident({cause:"timeout:RECONCILING",class:"fm22-timeout",detail:{limitMs:c9.RECONCILING}}),H({timedOut:!0,state:this.transition("IDLE","timeout:RECONCILING")});return H({timedOut:!1,state:this.stateValue})}authRepaired(){if(this.stateValue!=="AUTH_BLOCKED")return this.refuse("authRepaired");return this.freshRun(),H(this.transition("DISCOVERING","auth-repaired"))}repairCompleted($){if(this.stateValue!=="ERRORED")return this.refuse("repairCompleted");return this.openRepairs.delete($),this.emit("sync.repair.completed",{source:this.source,grantId:this.grantId,cause:$,at:this.now()}),this.freshRun(),H(this.transition("DISCOVERING","repair-completed"))}userRetry(){if(this.stateValue!=="ERRORED")return this.refuse("userRetry");return this.freshRun(),H(this.transition("DISCOVERING","user-retry"))}scheduledReprobe(){if(this.stateValue!=="ERRORED")return this.refuse("scheduledReprobe");let $=l9(this.now());if(this.lastReprobeAtValue!==null&&$-l9(this.lastReprobeAtValue)<NJ)return C("failed_precondition",`sync machine (${this.source}, ${this.grantId}): re-probe cooldown \u2014 at most one scheduled re-probe per 24h (\xA73.5)`);return this.lastReprobeAtValue=this.now(),this.freshRun(),H(this.transition("DISCOVERING","scheduled-reprobe"))}incidentResolved($){if(this.stateValue!=="INCIDENT")return this.refuse("incidentResolved");return this.openIncidents.delete($),this.emit("sync.incident.resolved",{source:this.source,grantId:this.grantId,cause:$,at:this.now()}),H(this.transition("IDLE","incident-resolved"))}userDisable(){if(this.stateValue==="DISABLED")return this.refuse("userDisable");if(this.stateValue!=="IDLE"&&this.runIdValue!==null)this.emit("sync.run.aborted",{source:this.source,grantId:this.grantId,runId:this.runIdValue,cause:"user-disable",at:this.now()});return H(this.transition("DISABLED","user-disable"))}userEnable(){if(this.stateValue!=="DISABLED")return this.refuse("userEnable");return this.pendingBackfillValue=!0,this.freshRun(),H(this.transition("DISCOVERING","user-enable"))}recover(){if(this.stateValue==="DISCOVERING"||this.stateValue==="PULLING"||this.stateValue==="RECONCILING")return H(this.transition("DISCOVERING","crash-recovery"));return H(this.stateValue)}applyReplay($,Z){switch($){case"sync.run.transition":{if(this.stateValue=Z.to,this.runIdValue=Z.runId??null,this.attemptValue=Z.attempt??0,this.healAttemptValue=Z.healAttempt??0,this.pendingBackfillValue=Z.pendingBackfill??!1,this.backoffDueAtValue=Z.backoffDueAt??null,this.lastSyncedValue=Z.lastSynced??null,this.lastErrorValue=CJ(Z.error),this.stateEnteredAtValue=Z.at??this.stateEnteredAtValue,this.stateValue==="PULLING")this.lastProgressAtValue=this.stateEnteredAtValue;break}case"sync.incident.filed":this.openIncidents.set(Z.cause,!0);break;case"sync.incident.resolved":this.openIncidents.delete(Z.cause);break;case"sync.repair.filed":this.openRepairs.set(Z.cause,!0);break;case"sync.repair.completed":this.openRepairs.delete(Z.cause);break;default:break}}static replay($,Z){let Q=new cQ($);Q.replaying=!0;for(let X of Z){if(!hZ.includes(X.kind))continue;if(X.payload.source!==$.source||X.payload.grantId!==$.grantId)continue;let z=w$(X.kind,X.payload);if(!K(z)){Q.replaying=!1;let Y="err"in z?z.err.message:"payload unexpectedly empty";return C("data_loss",`malformed authoritative ${X.kind} fact for (${$.source}, ${$.grantId}): ${Y}`)}if(X.kind==="sync.run.transition"&&z.ok.from!==Q.stateValue)return Q.replaying=!1,C("data_loss",`out-of-order authoritative sync.run.transition for (${$.source}, ${$.grantId}): expected from '${Q.stateValue}', observed '${String(z.ok.from)}'`);Q.applyReplay(X.kind,z.ok)}return Q.replaying=!1,H(Q)}get isReplaying(){return this.replaying}}var c9,FJ=2,NJ=86400000,EY=120000,T0,s8;var dQ=E(()=>{f();_0();c9={DISCOVERING:600000,PULLING:1800000,RECONCILING:600000},T0={source:"zortex",stream:"sync"},s8={source:T0.source,stream:T0.stream,revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"}});import{mkdirSync as XA,readFileSync as zA,rmSync as YA,writeFileSync as vY}from"fs";import{join as nQ}from"path";class V6{cursor=null;readCursor(){if(this.cursor===null)return G$("no persisted cursor for this (source, grant) \u2014 full list from null");return H(this.cursor)}writeCursor($){this.cursor=$}writeCensus($){}writeCoverage($){}destroy(){this.cursor=null}}class K6{dir;constructor($,Z,Q){this.dir=nQ($,Z,Q),XA(this.dir,{recursive:!0})}readCursor(){let $;try{$=zA(nQ(this.dir,"cursor"),"utf8")}catch{return G$("cursor file absent \u2014 full list from null (cursors are cost optimization, \xA72.2 rule 4)")}let Z=JSON.parse($);if(Z.cursor===null)return G$("cursor file records null \u2014 prior run ended exhausted");return H(Z.cursor)}writeCursor($){vY(nQ(this.dir,"cursor"),JSON.stringify({cursor:$}),"utf8")}writeCensus($){vY(nQ(this.dir,"census"),JSON.stringify($,null,2),"utf8")}writeCoverage($){vY(nQ(this.dir,"coverage"),JSON.stringify($,null,2),"utf8")}destroy(){YA(this.dir,{recursive:!0,force:!0})}}var bY=E(()=>{f()});function WA($,Z,Q){let X=$;return X.appendAsync===void 0?Promise.resolve(X.append(Z,Q)):X.appendAsync(Z,Q)}class B5{manifest;machine;ledger;store;connector;log;grant;now;onSpan;streamStallMs;ulid=V$();emittedRebinds=new Set;omissionsByRun=new Map;disableRequested=!1;constructor($,Z,Q,X,z,Y){this.connector=$.connector,this.log=$.log,this.grant=$.grant,this.manifest=Z,this.machine=Q,this.ledger=X,this.now=$.now??(()=>new Date().toISOString()),this.onSpan=$.onSpan,this.streamStallMs=$.streamStallMs??EY,this.store=$.stateRoot!==void 0?new K6($.stateRoot,Z.source,$.grant.id):new V6;for(let j of z)this.emittedRebinds.add(j);for(let j of Y){let W=this.omissionsByRun.get(j.runId);if(W===void 0)W=new Map,this.omissionsByRun.set(j.runId,W);W.set(gY(j),{stream:j.stream,reason:j.reason,parent:j.parent})}}static async create($){let Z=X6($.connector.manifest);if(!K(Z))return Z;let Q=Z.ok;if($.grant.source!==Q.source)return C("invalid_argument",`grant is for source '${$.grant.source}', manifest declares '${Q.source}' \u2014 one grant resolves to exactly ONE (source, account) (I-7)`);let X=[],z=new Y6(Q,$.grant.id),Y=[],j=new Map,W=new z6(Q.source,$.grant.id),V=null,q=await $.log.readGeneration();if(!K(q))return C("unavailable","sync replay could not capture one event-log generation; mixed-generation state is refused (FM-23/D24)");let B={...q.ok};try{for await(let D of $.log.scanMetadata(B,{sources:[Q.source]}))if(!D.erased&&D.origin?.kind==="connector"&&D.origin.source===Q.source&&D.origin.grant===$.grant.id)z.record(D.stream,D.sourceId,D.kind,"appended");for await(let D of $.log.scan(B,{sources:[T0.source],streams:["identity",T0.stream]})){if(b0(D))continue;let P=D;if(P.nk.source!==T0.source)continue;let F=P.payload??{};if(P.nk.stream==="identity"&&P.kind==="identity.rebind"){let N=P9(F);if(K(N))W.recordGlobal(N.ok,P.origin.kind==="kernel");continue}if(P.origin.kind!=="kernel")continue;if(P.nk.stream!==T0.stream)continue;if(F.source!==Q.source||F.grantId!==$.grant.id)continue;if(P.kind===TJ){let N=RZ(F);if(!K(N)){let S="err"in N?N.err.message:"payload unexpectedly empty";return C("data_loss",`malformed authoritative ${P.kind} fact: ${S}`)}W.recordScoped(N.ok);continue}if(!hZ.includes(P.kind))continue;let A=w$(P.kind,F);if(!K(A)){let N="err"in A?A.err.message:"payload unexpectedly empty";return C("data_loss",`malformed authoritative ${P.kind} fact: ${N}`)}if(P.kind==="sync.coverage.omission.observed"){let N=A.ok,S=JSON.stringify([N.runId,N.stream,N.parent.stream,N.parent.sourceId]),R=j.get(S);if(R!==void 0&&R.reason!==N.reason)return C("data_loss",`conflicting authoritative coverage omission reasons for one parent collection in run ${N.runId}`);j.set(S,N);continue}if(X.push({kind:P.kind,payload:A.ok}),P.kind==="sync.census.observed")V=A.ok.census;if(P.kind==="sync.security.token-carryover"){let N=A.ok.identity,S=A.ok.stream;if(typeof N==="string"&&typeof S==="string")z.recordContained(S,N,P.kind)}}}catch(D){let P=D.structuredError;if(P!==void 0)return C(P.code,`sync replay generation failed: ${P.message}`,P.retryability,P);return C("unavailable",`sync replay read failed: ${D instanceof Error?D.message:String(D)}`,"transient")}for(let D of W.acceptedScoped())Y.push(AJ(D)),z.recordRebind(D.from.stream,D.from.sourceId,D.to.sourceId);if(z.settleContainment(),V!==null)z.observeCensus(V);let G=$.now??(()=>new Date().toISOString()),J=null,U=(D,P)=>{B5.appendSyncEvent($.log,G,D,P)},L=cQ.replay({source:Q.source,grantId:$.grant.id,emit:U,now:G,...$.jitter!==void 0?{jitter:$.jitter}:{}},X);if(!K(L))return L;return J=L.ok,J.recover(),H(new B5($,Q,J,z,Y,J.runId===null?[]:[...j.values()].filter((D)=>D.runId===J.runId)))}static appendSyncEvent($,Z,Q,X){let z={nk:{source:T0.source,stream:T0.stream},ts:Z(),tier:"first-party",kind:Q,schemaVersion:1,mentions:[],body:"",payload:X},Y=$.append([z],{kind:"kernel"});if(!K(Y)||Y.ok.some((j)=>j.outcome==="anomaly"))throw Error(`sync event '${Q}' could not be appended: ${JSON.stringify(Y)}`)}emitSync($,Z){B5.appendSyncEvent(this.log,this.now,$,{source:this.manifest.source,grantId:this.grant.id,runId:this.machine.runId,...Z})}validatePullOmissions($,Z){let Q=$.omissions;if(Q===void 0)return H([]);if(!Array.isArray(Q)||Q.length>_J)return C("invalid_argument",`pull omissions must be an array of at most ${_J} rows`);let X=new Set(this.manifest.streams.map((j)=>j.stream)),z=new Set(Z.map((j)=>`${j.stream}\x00${j.sourceId}`)),Y=new Map;for(let j=0;j<Q.length;j++){let W=Q[j];if(!h(W)||Object.keys(W).sort().join("\x00")!=="parent\x00reason\x00stream")return C("invalid_argument",`pull omission ${j} must contain exactly stream/reason/parent`);if(typeof W.stream!=="string"||W.stream.length===0||W.stream.length>128||!X.has(W.stream))return C("invalid_argument",`pull omission ${j} names an undeclared or invalid child stream`);if(typeof W.reason!=="string"||W.reason.length>128||!jA.test(W.reason))return C("invalid_argument",`pull omission ${j} reason must be a bounded lowercase machine code`);let V=W.parent;if(!h(V)||Object.keys(V).sort().join("\x00")!=="sourceId\x00stream")return C("invalid_argument",`pull omission ${j} parent must contain exactly stream/sourceId`);if(typeof V.stream!=="string"||V.stream.length===0||V.stream.length>128||!X.has(V.stream))return C("invalid_argument",`pull omission ${j} names an undeclared or invalid parent stream`);if(typeof V.sourceId!=="string"||V.sourceId.length===0||V.sourceId.length>1024)return C("invalid_argument",`pull omission ${j} parent sourceId is invalid`);let q=w$("sync.coverage.omission.observed",{source:this.manifest.source,grantId:this.grant.id,runId:this.machine.runId,stream:W.stream,reason:W.reason,parent:{stream:V.stream,sourceId:V.sourceId}});if(!K(q))return C("invalid_argument",`pull omission ${j} does not satisfy the falcon fact contract`);if(!z.has(`${V.stream}\x00${V.sourceId}`))return C("invalid_argument",`pull omission ${j} parent was not prepared in the same page`);if(this.ledger.lastCensus?.streams[W.stream]?.method!=="pagination-exhaustion")return C("invalid_argument",`pull omission ${j} child stream is not declared pagination-exhaustion by the current census`);let B={stream:W.stream,reason:W.reason,parent:{stream:V.stream,sourceId:V.sourceId}},G=gY(B),J=Y.get(G);if(J!==void 0&&J.reason!==B.reason)return C("invalid_argument",`pull omission ${j} conflicts with another reason for the same parent collection`);Y.set(G,B)}return H([...Y.values()])}commitPullOmissions($,Z){for(let X of this.omissionsByRun.keys())if(X!==$)this.omissionsByRun.delete(X);let Q=this.omissionsByRun.get($);if(Q===void 0)Q=new Map,this.omissionsByRun.set($,Q);for(let X of Z){let z=gY(X),Y=Q.get(z);if(Y!==void 0){if(Y.reason!==X.reason)throw Error("coverage omission reason changed within one sync run");continue}this.emitSync("sync.coverage.omission.observed",X),Q.set(z,X)}}censusWithRunOmissions($,Z){for(let Y of this.omissionsByRun.keys())if(Y!==Z)this.omissionsByRun.delete(Y);let Q=this.omissionsByRun.get(Z);if(Q===void 0||Q.size===0)return $;let X={...$.streams},z=new Map;for(let Y of Q.values()){let j=z.get(Y.stream);if(j===void 0)j=new Map,z.set(Y.stream,j);j.set(Y.reason,(j.get(Y.reason)??0)+1)}for(let[Y,j]of z){let W=X[Y];if(W===void 0||W.method!=="pagination-exhaustion")throw Error(`coverage omission stream '${Y}' lost its pagination-exhaustion census declaration`);let V=new Map;for(let q of W.partialReasons??[])V.set(q.reason,q.count);for(let[q,B]of j)V.set(q,(V.get(q)??0)+B);X[Y]={...W,partialReasons:[...V].sort(([q],[B])=>q.localeCompare(B)).map(([q,B])=>({reason:q,...B!==void 0?{count:B}:{}}))}}return{...$,streams:X}}appendRebind($){let Z=AJ($);if(this.emittedRebinds.has(Z))return!1;let Q=this.ulid(),X={...$,rebindId:Q},z={source:this.manifest.source,grantId:this.grant.id,rebindId:Q,from:$.from,to:$.to},Y={ts:this.now(),tier:"first-party",schemaVersion:1,mentions:[],body:""},j=[{...Y,nk:{source:"zortex",stream:"identity"},kind:"identity.rebind",payload:X},{...Y,nk:{source:T0.source,stream:T0.stream},kind:TJ,payload:z}],W=this.log.append(j,{kind:"kernel"});if(!K(W)||W.ok.some((V)=>V.outcome==="anomaly"))throw Error(`identity rebind fact batch append failed: ${JSON.stringify(W)}`);return this.emittedRebinds.add(Z),this.ledger.recordRebind($.from.stream,$.from.sourceId,$.to.sourceId),!0}emitSpan($,Z,Q,X,z){let Y=this.machine.runId;if(Y===null)return;let j={traceId:Y,spanId:this.ulid(),name:$,attrs:X,status:z===void 0?"ok":"error",...z!==void 0?{error:z}:{},startTs:Z,durationMs:Q};this.onSpan?.(j);let W={nk:{source:"zortex",stream:"trace",sourceId:j.spanId,rev:"0"},ts:Z,tier:"first-party",kind:"trace.span",schemaVersion:1,mentions:[],body:"",payload:j},V=this.log.append([W],{kind:"kernel"});if(!K(V))throw Error(`trace.span append failed: ${JSON.stringify(V)}`)}requestDisable(){this.disableRequested=!0;let $=this.machine.state;if($==="PULLING"||$==="RECONCILING"||$==="DISCOVERING")return H($);return this.disableRequested=!1,this.machine.userDisable()}enable(){return this.disableRequested=!1,this.machine.userEnable()}authRepaired(){return this.machine.authRepaired()}report($){return{runId:this.machine.runId,state:this.machine.state,delivered:0,outcomes:{},appended:0,healAttempts:this.machine.healAttempt,rebindsEmitted:0,tokenLeaks:0,coverage:this.ledger.rows(),...$}}runOnce($="schedule"){try{return this.runOnceInner($)}catch(Z){return C("internal",`sync run aborted: ${String(Z)}`,"transient")}}runOnceInner($){let Z=this.machine,Q=()=>Z.lastError===null?{}:{error:Z.lastError};switch(Z.state){case"DISABLED":return H(this.report({ran:!1,skipped:"DISABLED \u2014 ingestion stops and NOTHING else (OQ-11/P23); exits via user re-enable only"}));case"AUTH_BLOCKED":return H(this.report({ran:!1,skipped:"AUTH_BLOCKED \u2014 exits ONLY via auth repair (uarch/auth.md)",...Q()}));case"ERRORED":return H(this.report({ran:!1,skipped:"ERRORED \u2014 exits via repair-order completion, user retry, or the 24h re-probe",...Q()}));case"INCIDENT":return H(this.report({ran:!1,skipped:"INCIDENT \u2014 exits via FM-18 work-order resolution"}));case"RETRY_WAIT":{let X=Z.backoffDue();if(!K(X))return H(this.report({ran:!1,skipped:X.err.message}));return this.drive({resumePull:!0})}case"IDLE":{let X=Z.schedule($);if(!K(X))return X;return this.drive({resumePull:!1})}case"DISCOVERING":return this.drive({resumePull:!1});default:return C("failed_precondition",`runOnce cannot start from state '${Z.state}'`)}}async runOnceAsync($="schedule"){if(this.connector.discoverAsync===void 0||this.connector.pullAsync===void 0)return C("failed_precondition","runOnceAsync requires explicit discoverAsync and pullAsync capabilities; synchronous provider fallback is forbidden (FM-23)");try{return await this.runOnceInnerAsync($)}catch(Z){return C("internal",`sync run aborted: ${String(Z)}`,"transient")}}async runOnceInnerAsync($){let Z=this.machine,Q=()=>Z.lastError===null?{}:{error:Z.lastError};switch(Z.state){case"DISABLED":return H(this.report({ran:!1,skipped:"DISABLED \u2014 ingestion stops and NOTHING else (OQ-11/P23); exits via user re-enable only"}));case"AUTH_BLOCKED":return H(this.report({ran:!1,skipped:"AUTH_BLOCKED \u2014 exits ONLY via auth repair (uarch/auth.md)",...Q()}));case"ERRORED":return H(this.report({ran:!1,skipped:"ERRORED \u2014 exits via repair-order completion, user retry, or the 24h re-probe",...Q()}));case"INCIDENT":return H(this.report({ran:!1,skipped:"INCIDENT \u2014 exits via FM-18 work-order resolution"}));case"RETRY_WAIT":{let X=Z.backoffDue();if(!K(X))return H(this.report({ran:!1,skipped:X.err.message}));return this.driveAsync({resumePull:!0})}case"IDLE":{let X=Z.schedule($);if(!K(X))return X;return this.driveAsync({resumePull:!1})}case"DISCOVERING":return this.driveAsync({resumePull:!1});default:return C("failed_precondition",`runOnce cannot start from state '${Z.state}'`)}}async stepScan($){let Z,Q=new Promise((z)=>{Z=setTimeout(()=>z({kind:"stalled"}),this.streamStallMs)}),X=$.next().then((z)=>z.done===!0?{kind:"done"}:{kind:"value",value:z.value});try{return await Promise.race([X,Q])}finally{if(Z!==void 0)clearTimeout(Z)}}async driveAsync($){let Z=this.machine,Q=Z.healAttempt>0,X=Z.healAttempt,z=0,Y=0,j=0,W=0,V={},q,B=this.store.readCursor(),G=K(B)?B.ok:null;if(!$.resumePull){let J=await this.discoverCensusAsync();if(!K(J)){let L=J.err;if(n8(L))return Z.grantAuthError(L),H(this.report({ran:!0,error:L}));return Z.phaseFailed(L),H(this.report({ran:!0,runFailed:!0,error:L}))}this.emitSync("sync.census.observed",{census:J.ok}),this.store.writeCensus(J.ok),this.ledger.observeCensus(J.ok);let U=Z.censusOk();if(!K(U))return U}for(;;){let J;if(Q)J=Z.healAttempt<=1?G:null;else{let k=this.store.readCursor();J=K(k)?k.ok:null}let U=this.connector.scan,L=U!==void 0?U(this.grant,J):null,D=!1;while(!D){if(this.disableRequested)return this.disableRequested=!1,Z.userDisable(),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q}));let k=Z.checkTimeout();if(K(k)&&k.ok.timedOut)return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q}));let d=this.now(),y=performance.now(),b;if(L!==null){let a=await this.stepScan(L);if(a.kind==="stalled")return this.emitSpan("connector.pull",d,performance.now()-y,{source:this.manifest.source,"grant.id":this.grant.id,"cursor.state":J===null?"null":"set",stalled:!0},{code:"deadline_exceeded",layer:"connector",retryability:"non-retryable",message:`streaming scan produced no batch within ${this.streamStallMs}ms (FM-21 stall watchdog)`}),Z.streamStalled({boundMs:this.streamStallMs,"cursor.state":J===null?"null":"set"}),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q}));if(a.kind==="done"){D=!0;break}b=a.value}else b=await this.connector.pullAsync(this.grant,J);if(!K(b)){let a="err"in b?b.err:{code:"internal",layer:"connector",retryability:"non-retryable",message:"pull returned empty \u2014 a page is an assertion (FM-21)"};if(this.emitSpan("connector.pull",d,performance.now()-y,{source:this.manifest.source,"grant.id":this.grant.id,"cursor.state":J===null?"null":"set"},a),a.code==="not_found"&&J!==null){Z.cursorExpired(),J=null,G=null,this.store.writeCursor(null);continue}let Q$=Z.routePageError(a);if(!K(Q$))return Q$;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:a,...Q$.ok.to==="IDLE"?{runFailed:!0}:{}}))}let g=b.ok;Z.batchProgress(),z+=g.items.length,this.emitSpan("connector.pull",d,performance.now()-y,{source:this.manifest.source,"grant.id":this.grant.id,"batch.count":g.items.length,"cursor.state":J===null?"null":"set",exhausted:g.exhausted});let w=this.phaseFor(Q);q=w;let u=Z.runId,p=j6(this.connector,this.manifest,g.items,{phase:w,syncRun:u});if(!K(p)){let a=p.err,Q$=Z.routePageError(a);if(!K(Q$))return Q$;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:a}))}let o=this.validatePullOmissions(g,p.ok.drafts);if(!K(o)){let a=o.err,Q$=Z.routePageError(a);if(!K(Q$))return Q$;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:a}))}for(let a of p.ok.leaks)W+=1,this.emitSync("sync.security.token-carryover",{stream:a.stream,pattern:a.pattern,class:"i7-raw-token",identity:a.identity}),this.ledger.recordContained(a.stream,a.identity,"sync.security.token-carryover");let Z$=this.now(),H$=performance.now(),A$=null,e=p.ok.drafts;for(let a=0;a<e.length;a+=n5){let Q$=e.slice(a,a+n5),n$=await WA(this.log,Q$.map((m$)=>m$.draft),{kind:"connector",source:this.manifest.source,grant:this.grant.id});if(!K(n$)){A$="err"in n$?n$.err:{code:"internal",layer:"storage",retryability:"transient",message:"append returned empty"};break}let R0=n$.ok;for(let m$=0;m$<R0.length;m$++){let s$=R0[m$],H8=Q$[m$];if(s$===void 0||H8===void 0)continue;if(V[s$.outcome]=(V[s$.outcome]??0)+1,s$.outcome==="appended"||s$.outcome==="anomaly")Y+=1;this.ledger.record(H8.stream,H8.sourceId,H8.kind,s$.outcome)}}if(this.emitSpan("connector.append",Z$,performance.now()-H$,{source:this.manifest.source,"grant.id":this.grant.id,"batch.count":e.length,"appended.count":Y,"deduped.count":(V.duplicate??0)+(V["head-noop"]??0),"coverage.phase":w},A$??void 0),A$!==null){let a=Z.routePageError(A$);if(!K(a))return a;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:A$}))}for(let a of p.ok.rebinds)if(this.appendRebind(a))j+=1;if(this.commitPullOmissions(u,o.ok),!Q)J=g.next,this.store.writeCursor(J),this.emitSync("sync.cursor.advanced",{cursor:J});else J=g.next;D=g.exhausted}let P=Z.exhausted();if(!K(P))return P;let F=await this.discoverCensusAsync();if(!K(F)){let k=F.err;if(n8(k))return Z.grantAuthError(k),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:k}));return Z.phaseFailed(k),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,runFailed:!0,error:k}))}let A=this.censusWithRunOmissions(F.ok,Z.runId);this.emitSync("sync.census.observed",{census:A}),this.store.writeCensus(A);let N=this.ledger.reconcile(A);if(!K(N))return N;let S=N.ok;this.emitSync("sync.coverage.reconciled",{verdicts:S}),this.store.writeCoverage(this.ledger.snapshot());let R=()=>H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,healAttempts:X,rebindsEmitted:j,tokenLeaks:W,phase:q,verdicts:S})),O=S.find((k)=>k.kind==="duplicate-object");if(O!==void 0)return Z.duplicateObjectSignal(O),R();let T=S.find((k)=>k.kind==="unattributed-gap");if(T!==void 0){let k=Z.reconcileGapUnattributed(T);if(!K(k))return k;if(k.ok==="INCIDENT")return R();Q=!0,X=Z.healAttempt;continue}let m=S.filter((k)=>k.kind==="attributed"||k.kind==="no-total"&&(k.reasons?.length??0)>0);if(m.length>0)return Z.reconcileGapAttributed({streams:m}),R();return Z.reconcileClean(),R()}}phaseFor($){if($||this.machine.pendingBackfill)return"backfill";return this.machine.lastSynced===null?"snapshot":"live"}discoverCensus(){let $=this.now(),Z=performance.now(),Q=this.connector.discover(this.grant);if(this.emitSpan("connector.discover",$,performance.now()-Z,{source:this.manifest.source,"grant.id":this.grant.id,result:K(Q)?"ok":"err"},K(Q)?void 0:Q.err),!K(Q))return Q;if("empty"in Q)return C("invalid_argument","discover returned empty \u2014 a census is an assertion, never an absence (FM-18/FM-21)");return Q}async discoverCensusAsync(){let $=this.now(),Z=performance.now(),Q=await this.connector.discoverAsync(this.grant);if(this.emitSpan("connector.discover",$,performance.now()-Z,{source:this.manifest.source,"grant.id":this.grant.id,result:K(Q)?"ok":"err"},K(Q)?void 0:Q.err),!K(Q))return Q;if("empty"in Q)return C("invalid_argument","discover returned empty \u2014 a census is an assertion, never an absence (FM-18/FM-21)");return Q}drive($){let Z=this.machine,Q=Z.healAttempt>0,X=Z.healAttempt,z=0,Y=0,j=0,W=0,V={},q,B=this.store.readCursor(),G=K(B)?B.ok:null;if(!$.resumePull){let J=this.discoverCensus();if(!K(J)){let L=J.err;if(n8(L))return Z.grantAuthError(L),H(this.report({ran:!0,error:L}));return Z.phaseFailed(L),H(this.report({ran:!0,runFailed:!0,error:L}))}this.emitSync("sync.census.observed",{census:J.ok}),this.store.writeCensus(J.ok),this.ledger.observeCensus(J.ok);let U=Z.censusOk();if(!K(U))return U}for(;;){let J;if(Q)J=Z.healAttempt<=1?G:null;else{let T=this.store.readCursor();J=K(T)?T.ok:null}let U=!1;while(!U){if(this.disableRequested)return this.disableRequested=!1,Z.userDisable(),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q}));let T=Z.checkTimeout();if(K(T)&&T.ok.timedOut)return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q}));let m=this.now(),k=performance.now(),d=this.connector.pull(this.grant,J);if(!K(d)){let e="err"in d?d.err:{code:"internal",layer:"connector",retryability:"non-retryable",message:"pull returned empty \u2014 a page is an assertion (FM-21)"};if(this.emitSpan("connector.pull",m,performance.now()-k,{source:this.manifest.source,"grant.id":this.grant.id,"cursor.state":J===null?"null":"set"},e),e.code==="not_found"&&J!==null){Z.cursorExpired(),J=null,G=null,this.store.writeCursor(null);continue}let a=Z.routePageError(e);if(!K(a))return a;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:e,...a.ok.to==="IDLE"?{runFailed:!0}:{}}))}let y=d.ok;Z.batchProgress(),z+=y.items.length,this.emitSpan("connector.pull",m,performance.now()-k,{source:this.manifest.source,"grant.id":this.grant.id,"batch.count":y.items.length,"cursor.state":J===null?"null":"set",exhausted:y.exhausted});let b=this.phaseFor(Q);q=b;let g=Z.runId,w=j6(this.connector,this.manifest,y.items,{phase:b,syncRun:g});if(!K(w)){let e=w.err,a=Z.routePageError(e);if(!K(a))return a;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:e}))}let u=this.validatePullOmissions(y,w.ok.drafts);if(!K(u)){let e=u.err,a=Z.routePageError(e);if(!K(a))return a;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:e}))}for(let e of w.ok.leaks)W+=1,this.emitSync("sync.security.token-carryover",{stream:e.stream,pattern:e.pattern,class:"i7-raw-token",identity:e.identity}),this.ledger.recordContained(e.stream,e.identity,"sync.security.token-carryover");let p=this.now(),o=performance.now(),Z$=0,H$=null,A$=w.ok.drafts;for(let e=0;e<A$.length;e+=n5){let a=A$.slice(e,e+n5),Q$=this.log.append(a.map((R0)=>R0.draft),{kind:"connector",source:this.manifest.source,grant:this.grant.id});if(!K(Q$)){H$="err"in Q$?Q$.err:{code:"internal",layer:"storage",retryability:"transient",message:"append returned empty"};break}let n$=Q$.ok;for(let R0=0;R0<n$.length;R0++){let m$=n$[R0],s$=a[R0];if(m$===void 0||s$===void 0)continue;if(V[m$.outcome]=(V[m$.outcome]??0)+1,m$.outcome==="appended"||m$.outcome==="anomaly")Y+=1;this.ledger.record(s$.stream,s$.sourceId,s$.kind,m$.outcome),Z$+=1}}if(this.emitSpan("connector.append",p,performance.now()-o,{source:this.manifest.source,"grant.id":this.grant.id,"batch.count":A$.length,"appended.count":Y,"deduped.count":(V.duplicate??0)+(V["head-noop"]??0),"coverage.phase":b},H$??void 0),H$!==null){let e=Z.routePageError(H$);if(!K(e))return e;return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:H$}))}for(let e of w.ok.rebinds)if(this.appendRebind(e))j+=1;if(this.commitPullOmissions(g,u.ok),!Q)J=y.next,this.store.writeCursor(J),this.emitSync("sync.cursor.advanced",{cursor:J});else J=y.next;U=y.exhausted}let L=Z.exhausted();if(!K(L))return L;let D=this.discoverCensus();if(!K(D)){let T=D.err;if(n8(T))return Z.grantAuthError(T),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,error:T}));return Z.phaseFailed(T),H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,rebindsEmitted:j,tokenLeaks:W,phase:q,runFailed:!0,error:T}))}let P=this.censusWithRunOmissions(D.ok,Z.runId);this.emitSync("sync.census.observed",{census:P}),this.store.writeCensus(P);let F=this.ledger.reconcile(P);if(!K(F))return F;let A=F.ok;this.emitSync("sync.coverage.reconciled",{verdicts:A}),this.store.writeCoverage(this.ledger.snapshot());let N=(T)=>{return H(this.report({ran:!0,delivered:z,outcomes:V,appended:Y,healAttempts:X,rebindsEmitted:j,tokenLeaks:W,phase:q,verdicts:A}))},S=A.find((T)=>T.kind==="duplicate-object");if(S!==void 0)return Z.duplicateObjectSignal(S),N();let R=A.find((T)=>T.kind==="unattributed-gap");if(R!==void 0){let T=Z.reconcileGapUnattributed(R);if(!K(T))return T;if(T.ok==="INCIDENT")return N();Q=!0,X=Z.healAttempt;continue}let O=A.filter((T)=>T.kind==="attributed"||T.kind==="no-total"&&(T.reasons?.length??0)>0);if(O.length>0)return Z.reconcileGapAttributed({streams:O}),N();return Z.reconcileClean(),N()}}}var AJ=($)=>`${$.from.stream}\x00${$.from.sourceId}\x00${$.to.stream}\x00${$.to.sourceId}`,gY=($)=>JSON.stringify([$.stream,$.parent.stream,$.parent.sourceId]),_J=4096,jA,TJ="sync.identity.rebound";var SJ=E(()=>{f();F0();_0();dQ();lQ();OY();bY();uQ();jA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/});var ll;var RJ=E(()=>{f();F0();uQ();dQ();ll=Date.parse("2026-07-01T00:00:00.000Z")});class OJ{connector;grant;machine;now;onRepairOrder;onSpan;ulid=V$();lastRunAt=null;openCauses=new Set;constructor($){this.connector=$.connector,this.grant=$.grant,this.machine=$.machine,this.now=$.now,this.onRepairOrder=$.onRepairOrder,this.onSpan=$.onSpan}get intervalMs(){return this.connector.manifest.healthProbe.intervalMin*60000}due(){if(this.machine.state==="DISABLED")return!1;if(this.lastRunAt===null)return!0;return Date.parse(this.now())-Date.parse(this.lastRunAt)>=this.intervalMs}runFetchOne(){if(this.machine.state==="DISABLED")return G$("source DISABLED \u2014 probes stop; a deliberate disconnect is never treated as rot (OQ-11/P23)");let $=this.now(),Z=performance.now();this.lastRunAt=$;let Q=this.connector.pull(this.grant,null),X=performance.now()-Z,z=this.intervalMs,Y=K(Q)?void 0:("err"in Q)?Q.err:void 0,j={ref:`health:fetch-one:${this.connector.manifest.source}`,result:K(Q)?"pass":"fail",latencyMs:X,budgetMs:z,budgetMet:X<=z,...Y!==void 0?{error:Y}:{}};if(this.emitProbeSpan(j,$),j.result==="fail"){let W=`health-probe:${Y?.code??"empty"}`;if(!this.openCauses.has(W))this.openCauses.add(W),this.onRepairOrder(W)}return H(j)}repairResolved($){this.openCauses.delete($)}emitProbeSpan($,Z){let Q={traceId:this.ulid(),spanId:this.ulid(),name:"probe.run",attrs:{"probe.ref":$.ref,layer:"connector",result:$.result,"latency.ms":$.latencyMs,"budget.ms":$.budgetMs,"budget.met":$.budgetMet},status:$.result==="pass"?"ok":"error",...$.error!==void 0?{error:$.error}:{},startTs:Z,durationMs:$.latencyMs};this.onSpan?.(Q)}}var xJ=E(()=>{f();_0();lQ();dQ()});var IJ=E(()=>{f();_0()});var yJ=E(()=>{f();_0()});var EJ=E(()=>{f();_0()});var j$=E(()=>{_0();uQ();RY();OY();dQ();lQ();bY();SJ();RJ();xJ();IJ();yJ();EJ()});function EG($){return W$(`posthog action '${$}'`,eY)}var g0="posthog",P5="insight",C5="dashboard",F5="annotation",N5="person",A5="cohort",_5="feature-flag",$9="event",v6,eY="connectors.md \xA72.3c classification review \u2014 posthog v0 declares zero ActionContracts (read-only ingestion)";var $j=E(()=>{j$();v6={source:g0,tier:"api",auth:{provider:"posthog",method:"api-key",scopes:["insight:read","dashboard:read","annotation:read","person:read","cohort:read","feature_flag:read","query:read","user:read"],multiAccount:!1,probe:{op:"users.@me"}},streams:[{stream:P5,kinds:["insight.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"upstream-version",revField:"last_modified_at"},{stream:C5,kinds:["dashboard.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"upstream-version",revField:"last_modified_at"},{stream:F5,kinds:["annotation.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"upstream-version",revField:"updated_at"},{stream:N5,kinds:["person.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"head-compare"},{stream:A5,kinds:["cohort.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"head-compare"},{stream:_5,kinds:["feature_flag.changed"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"head-compare"},{stream:$9,kinds:["event.recorded"],identity:{quality:"container-scoped",epochField:"project"},revOrder:"event-ts"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:60},retaliationRisk:"tolerant"}});function W4($){let Z;try{Z=new URL($)}catch{return C("invalid_argument",`posthog base URL '${$}' is not a parseable URL`)}if(Z.protocol!=="https:")return C("invalid_argument",`posthog base URL '${$}' must be https \u2014 PostHog cloud (us/eu) and any sane self-hosted deployment serve the API over TLS`);return H(`${Z.protocol}//${Z.host}`)}class g6{base;transport;authHeader;cap;projectId;constructor($,Z,Q,X,z){this.base=$,this.transport=Z,this.authHeader=Q,this.cap=X,this.projectId=z}static create($){let Z=W4($.baseUrl??j4);if(!K(Z))return Z;let Q=$.projectId===void 0?null:String($.projectId);return H(new g6(Z.ok,$.transport??zj,$.authHeader,$.cap??Yj,Q))}get baseUrl(){return this.base}httpStatusError($,Z){if($===401)return C("unauthenticated",`posthog ${Z} \u2192 HTTP 401 \u2014 the personal API key is invalid/expired (grant-level; auth repair, never a retry)`);if($===403)return C("permission_denied",`posthog ${Z} \u2192 HTTP 403 \u2014 the key lacks the scope/project grant (grant-level; auth repair, never a retry)`);if($===429)return C("resource_exhausted",`posthog ${Z} \u2192 HTTP 429 \u2014 rate limited; long backoff + retry-quota token bucket (I-6)`,"throttling");if($>=500)return C("unavailable",`posthog ${Z} \u2192 HTTP ${$} \u2014 transient server condition`,"transient");return C("internal",`posthog ${Z} \u2192 HTTP ${$} \u2014 REST-surface drift (FM-19)`)}getJson($,Z){return this.getJsonUrl(`${this.base}${$}`,Z)}getJsonUrl($,Z){let Q=this.authHeader();if(!K(Q))return Q;let X=this.transport({url:$,headers:{Authorization:Q.ok,Accept:"application/json"}});if(!X.ok)return{err:X.error};if(X.status!==200)return this.httpStatusError(X.status,Z);let z;try{z=JSON.parse(X.body)}catch{return C("internal",`posthog ${Z} response is not JSON \u2014 REST-surface drift (FM-19)`)}return H(z)}resolveProject(){if(this.projectId!==null)return H(this.projectId);let $=this.getJson("/api/projects/@current/","GET /api/projects/@current/");if(!K($))return $;let Z=$.ok,Q=Z!==null&&typeof Z==="object"&&!Array.isArray(Z)?Z.id:void 0;if(typeof Q!=="number"&&typeof Q!=="string")return C("internal","posthog /api/projects/@current/ has no numeric id \u2014 REST-surface drift (FM-19)");return this.projectId=String(Q),H(this.projectId)}whoami(){return this.getJson("/api/users/@me/","GET /api/users/@me/")}parseListPage($,Z){if($===null||typeof $!=="object"||Array.isArray($))return C("internal",`posthog ${Z} is not a paginated object \u2014 REST-surface drift (FM-19)`);let Q=$;if(!Array.isArray(Q.results))return C("internal",`posthog ${Z} missing 'results' \u2014 REST-surface drift (FM-19)`);let X=Q.next;if(X!==null&&typeof X!=="string")return C("internal",`posthog ${Z} 'next' is neither a URL nor null \u2014 REST-surface drift (FM-19)`);let z=Q.count;if(z!==void 0&&typeof z!=="number")return C("internal",`posthog ${Z} 'count' is not a number \u2014 REST-surface drift (FM-19)`);if(z===void 0&&X!==null)return C("internal",`posthog ${Z} omits 'count' on a paginated response \u2014 cannot reconcile FM-18 coverage`);for(let Y of Q.results)if(Y===null||typeof Y!=="object"||Array.isArray(Y))return C("internal",`posthog ${Z} results carry a non-object row \u2014 REST-surface drift (FM-19)`);return H({count:z??null,next:X,results:Q.results})}census(){let $=this.resolveProject();if(!K($))return $;let Z=$.ok,Q=(q)=>{let B=`GET /api/projects/${Z}/${q}/?limit=1`,G=this.getJson(`/api/projects/${Z}/${q}/?limit=1`,B);if(!K(G))return G;let J=this.parseListPage(G.ok,B);if(!K(J))return J;return H(J.ok.count??J.ok.results.length)},X=Q("insights");if(!K(X))return X;let z=Q("dashboards");if(!K(z))return z;let Y=Q("annotations");if(!K(Y))return Y;let j=Q("persons");if(!K(j))return j;let W=Q("cohorts");if(!K(W))return W;let V=Q("feature_flags");if(!K(V))return V;return H({insight:{total:X.ok},dashboard:{total:z.ok},annotation:{total:Y.ok},person:{total:j.ok},cohort:{total:W.ok},featureFlag:{total:V.ok}})}pullAll($,Z,Q){let X=[],z=0;for(;;){let Y=`GET /api/projects/${$}/${Z}/?limit=${t9}&offset=${z}`,j=this.getJson(`/api/projects/${$}/${Z}/?limit=${t9}&offset=${z}`,Y);if(!K(j))return j;let W=this.parseListPage(j.ok,Y);if(!K(W))return W;let V=W.ok;for(let q of V.results)if(X.push(q),X.length>Q())return C("resource_exhausted",`posthog pull exceeded the ${this.cap}-object cap (authored objects are bounded; the EVENT firehose is deliberately not a stream) \u2014 refused LOUD, never a silent truncation that would misreconcile FM-18 coverage`);if(V.next===null||V.results.length===0)break;z+=t9}return H(X)}starterSnapshot($){if(!Number.isSafeInteger($)||$<1||$>t9)return C("invalid_argument",`posthog starter limit must be 1..${t9}`);let Z=this.resolveProject();if(!K(Z))return Z;let Q=`GET /api/projects/${Z.ok}/insights/?limit=${$}&offset=0`,X=this.getJson(`/api/projects/${Z.ok}/insights/?limit=${$}&offset=0`,Q);if(!K(X))return X;let z=this.parseListPage(X.ok,Q);if(!K(z))return z;let Y=[];for(let j of z.ok.results.slice(0,$)){let W=this.buildInsight(Z.ok,j);if(!K(W))return W;Y.push(W.ok)}return H({insights:Y,dashboards:[],annotations:[],persons:[],cohorts:[],featureFlags:[]})}list(){let $=this.resolveProject();if(!K($))return $;let Z=$.ok,Q=0,X=()=>this.cap-Q,z=this.pullAll(Z,"insights",X);if(!K(z))return z;Q+=z.ok.length;let Y=this.pullAll(Z,"dashboards",X);if(!K(Y))return Y;Q+=Y.ok.length;let j=this.pullAll(Z,"annotations",X);if(!K(j))return j;Q+=j.ok.length;let W=this.pullAll(Z,"persons",X);if(!K(W))return W;Q+=W.ok.length;let V=this.pullAll(Z,"cohorts",X);if(!K(V))return V;Q+=V.ok.length;let q=this.pullAll(Z,"feature_flags",X);if(!K(q))return q;let B=[];for(let P of z.ok){let F=this.buildInsight(Z,P);if(!K(F))return F;B.push(F.ok)}let G=[];for(let P of Y.ok){let F=this.buildDashboard(Z,P);if(!K(F))return F;G.push(F.ok)}let J=[];for(let P of j.ok){let F=this.buildAnnotation(Z,P);if(!K(F))return F;J.push(F.ok)}let U=[];for(let P of W.ok){let F=this.buildPerson(Z,P);if(!K(F))return F;U.push(F.ok)}let L=[];for(let P of V.ok){let F=this.buildCohort(Z,P);if(!K(F))return F;L.push(F.ok)}let D=[];for(let P of q.ok){let F=this.buildFeatureFlag(Z,P);if(!K(F))return F;D.push(F.ok)}return H({insights:B,dashboards:G,annotations:J,persons:U,cohorts:L,featureFlags:D})}listEvents($){let Z=this.resolveProject();if(!K(Z))return Z;let Q=Z.ok,X,z;if($.next!==null)X=$.next,z=`GET ${$.next}`;else{let B=`/api/projects/${Q}/events/?limit=${$Z}`+($.after!==null?`&after=${encodeURIComponent($.after)}`:"");X=`${this.base}${B}`,z=`GET /api/projects/${Q}/events/?limit=${$Z}${$.after!==null?"&after=\u2026":""}`}let Y=this.getJsonUrl(X,z);if(!K(Y))return Y;let j=Y.ok;if(j===null||typeof j!=="object"||Array.isArray(j))return C("internal",`posthog ${z} is not a paginated object \u2014 REST-surface drift (FM-19)`);let W=j;if(!Array.isArray(W.results))return C("internal",`posthog ${z} missing 'results' \u2014 REST-surface drift (FM-19)`);let V=W.next;if(V!==null&&V!==void 0&&typeof V!=="string")return C("internal",`posthog ${z} 'next' is neither a URL nor null \u2014 REST-surface drift (FM-19)`);let q=[];for(let B of W.results){if(B===null||typeof B!=="object"||Array.isArray(B))return C("internal",`posthog ${z} results carry a non-object row \u2014 REST-surface drift (FM-19)`);let G=this.buildEvent(Q,B);if(!K(G))return G;q.push(G.ok)}return H({events:q,next:typeof V==="string"?V:null})}buildInsight($,Z){let{id:Q,last_modified_at:X}=Z;if(typeof Q!=="number")return this.driftRow("insight","id");if(typeof X!=="string"||X==="")return this.driftRow("insight","last_modified_at");return H({project:$,id:Q,short_id:typeof Z.short_id==="string"?Z.short_id:"",name:typeof Z.name==="string"?Z.name:null,derived_name:typeof Z.derived_name==="string"?Z.derived_name:null,last_modified_at:X,created_by:Y4(Z.created_by),verbatim:Qj(Z,Zj)})}buildDashboard($,Z){let Q=Z.id,X=Z.last_modified_at??Z.created_at;if(typeof Q!=="number")return this.driftRow("dashboard","id");if(typeof X!=="string"||X==="")return this.driftRow("dashboard","last_modified_at|created_at");return H({project:$,id:Q,name:typeof Z.name==="string"?Z.name:null,last_modified_at:X,created_by:Y4(Z.created_by),verbatim:Qj(Z,Zj)})}buildAnnotation($,Z){let{id:Q,updated_at:X}=Z;if(typeof Q!=="number")return this.driftRow("annotation","id");if(typeof X!=="string"||X==="")return this.driftRow("annotation","updated_at");return H({project:$,id:Q,content:typeof Z.content==="string"?Z.content:null,updated_at:X,created_by:Y4(Z.created_by),verbatim:Qj(Z,Zj)})}buildPerson($,Z){let Q=Z.id;if(typeof Q!=="number")return this.driftRow("person","id");let X=[];if(Array.isArray(Z.distinct_ids)){for(let z of Z.distinct_ids)if(typeof z==="string")X.push(z)}return H({project:$,id:Q,uuid:typeof Z.uuid==="string"?Z.uuid:null,name:typeof Z.name==="string"?Z.name:null,distinct_ids:X,created_at:typeof Z.created_at==="string"?Z.created_at:"",verbatim:{...Z}})}buildCohort($,Z){let Q=Z.id;if(typeof Q!=="number")return this.driftRow("cohort","id");return H({project:$,id:Q,name:typeof Z.name==="string"?Z.name:null,created_at:typeof Z.created_at==="string"?Z.created_at:"",created_by:Y4(Z.created_by),verbatim:{...Z}})}buildFeatureFlag($,Z){let Q=Z.id;if(typeof Q!=="number")return this.driftRow("feature-flag","id");return H({project:$,id:Q,key:typeof Z.key==="string"?Z.key:null,name:typeof Z.name==="string"?Z.name:null,created_at:typeof Z.created_at==="string"?Z.created_at:"",created_by:Y4(Z.created_by),verbatim:{...Z}})}buildEvent($,Z){let{id:Q,timestamp:X}=Z;if(typeof Q!=="string"||Q==="")return this.driftRow("event","id");if(typeof X!=="string"||X==="")return this.driftRow("event","timestamp");return H({project:$,id:Q,event:typeof Z.event==="string"?Z.event:"",timestamp:X,distinct_id:typeof Z.distinct_id==="string"?Z.distinct_id:null,verbatim:{...Z}})}driftRow($,Z){return C("internal",`posthog ${$} row is missing/mistyped '${Z}' \u2014 REST-surface drift (FM-19; a versioned object with no version token cannot ride the upstream-version chain)`)}}function Y4($){if($===null||$===void 0||typeof $!=="object"||Array.isArray($))return null;let Z=$;if(typeof Z.id!=="number")return null;let Q={id:Z.id};if(typeof Z.distinct_id==="string")Q.distinct_id=Z.distinct_id;if(typeof Z.first_name==="string")Q.first_name=Z.first_name;if(typeof Z.last_name==="string")Q.last_name=Z.last_name;if(typeof Z.email==="string")Q.email=Z.email;return Q}function Qj($,Z){let Q={};for(let[X,z]of Object.entries($))if(!Z.has(X))Q[X]=z;return Q}var Xj="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real credentials at C-P6-2 (G2)",zj=()=>({ok:!1,error:W$("posthog live WAN transport",Xj).err}),j4="https://us.posthog.com",vG="https://eu.posthog.com",Yj=25000,t9=100,$Z=100,b6=5000000,Zj;var f6=E(()=>{f();j$();Zj=new Set(["result","last_refresh","is_cached","cache_target_age","next_allowed_client_refresh","hasMore","columns","timezone"])});function $0($){return $.replace(/phx_[A-Za-z0-9_\-]{32,}/g,"[REDACTED:posthog-credential]")}function rA($){return aA.has($.toLowerCase().replace(/[^a-z0-9]/g,""))}function a0($){if(typeof $==="string")return $0($);if(Array.isArray($))return $.map(a0);if($===null||typeof $!=="object")return $;let Z={};for(let[Q,X]of Object.entries($))Z[Q]=rA(Q)?"[REDACTED:credential-property]":a0(X);return Z}var aA;var bG=E(()=>{aA=new Set(["token","accesstoken","refreshtoken","apikey","personalapikey","authorization","secret","clientsecret"])});function e9($){if($===null)return[];let Z=$0(($.email??"").trim()),Q=$0([$.first_name??"",$.last_name??""].join(" ").trim()),X=Q!==""?Q:Z!==""?Z:$0($.distinct_id??String($.id));if(X==="")return[];let z={role:"actor",kind:"person",raw:X};if(Z!=="")z.handle={ns:"email",value:Z};return[z]}function tA($){return $0($.name??$.derived_name??`insight ${$.id}`)}function eA($){if($===null)return{p:"objects",eventsAfter:null};try{let Z=JSON.parse($);if(Z.p==="objects"||Z.p==="events")return Z}catch{}return{p:"objects",eventsAfter:null}}function $_($,Z){if($===null)return Z;let Q=Date.parse($),X=Date.parse(Z);if(!Number.isFinite(X))return $;if(!Number.isFinite(Q))return Z;return X>Q?Z:$}function Z_($){let Z=$.distinct_ids.find((j)=>j.trim()!=="")??"",Q=($.name??"").trim(),X=Z!==""?Z:Q;if(X==="")return[];let Y={role:"subject",kind:"person",raw:$0(X)};if(Z!=="")Y.handle={ns:"posthog-distinct-id",value:$0(Z)};return[Y]}function Q_($){let Z=($.distinct_id??"").trim();if(Z==="")return[];let Q=$0(Z);return[{role:"actor",kind:"person",raw:Q,handle:{ns:"posthog-distinct-id",value:Q}}]}function gG($,Z={}){let Q=Z.now??(()=>new Date().toISOString()),X=Z.eventRunCap??b6;return{manifest:v6,discover(z){let Y=$.census();if(!K(Y))return Y;let j={[P5]:{total:Y.ok.insight.total,method:"count-api"},[C5]:{total:Y.ok.dashboard.total,method:"count-api"},[F5]:{total:Y.ok.annotation.total,method:"count-api"},[N5]:{total:Y.ok.person.total,method:"count-api"},[A5]:{total:Y.ok.cohort.total,method:"count-api"},[_5]:{total:Y.ok.featureFlag.total,method:"count-api"},[$9]:{method:"pagination-exhaustion"}},W=[[P5,Y.ok.insight],[C5,Y.ok.dashboard],[F5,Y.ok.annotation],[N5,Y.ok.person],[A5,Y.ok.cohort],[_5,Y.ok.featureFlag]];for(let[V,q]of W)if(q.partialReasons!==void 0)j[V].partialReasons=q.partialReasons;return H({asOf:Q(),streams:j})},pull(z,Y){let j=eA(Y);if(j.p==="objects"){let U=$.list();if(!K(U))return U;let L=[];for(let D of U.ok.insights)L.push({streamRef:P5,raw:D});for(let D of U.ok.dashboards)L.push({streamRef:C5,raw:D});for(let D of U.ok.annotations)L.push({streamRef:F5,raw:D});for(let D of U.ok.persons)L.push({streamRef:N5,raw:D});for(let D of U.ok.cohorts)L.push({streamRef:A5,raw:D});for(let D of U.ok.featureFlags)L.push({streamRef:_5,raw:D});return H({items:L,next:jj({p:"events",after:j.eventsAfter,next:null,maxTs:null,drained:0}),exhausted:!1})}let W=$.listEvents({after:j.after,next:j.next});if(!K(W))return W;let V=W.ok,q=V.events.map((U)=>({streamRef:$9,raw:U})),B=j.maxTs;for(let U of V.events)B=$_(B,U.timestamp);let G=j.drained+V.events.length;if(G>X)return C("resource_exhausted",`posthog event firehose drain exceeded the ${X}-event single-run cap \u2014 refused LOUD (never a silent slice; the next run resumes from the time-window high-water mark)`);if(V.next!==null)return H({items:q,next:jj({p:"events",after:j.after,next:V.next,maxTs:B,drained:G}),exhausted:!1});let J=B??j.after;return H({items:q,next:jj({p:"objects",eventsAfter:J}),exhausted:!0})},normalize(z){switch(z.streamRef){case P5:{let Y=z.raw;return{nk:{source:g0,stream:P5,sourceId:String(Y.id),rev:Y.last_modified_at},ts:Y.last_modified_at,tier:"api",kind:"insight.changed",schemaVersion:1,mentions:e9(Y.created_by),body:tA(Y),payload:a0(Y.verbatim)}}case C5:{let Y=z.raw;return{nk:{source:g0,stream:C5,sourceId:String(Y.id),rev:Y.last_modified_at},ts:Y.last_modified_at,tier:"api",kind:"dashboard.changed",schemaVersion:1,mentions:e9(Y.created_by),body:$0(Y.name??`dashboard ${Y.id}`),payload:a0(Y.verbatim)}}case F5:{let Y=z.raw;return{nk:{source:g0,stream:F5,sourceId:String(Y.id),rev:Y.updated_at},ts:Y.updated_at,tier:"api",kind:"annotation.changed",schemaVersion:1,mentions:e9(Y.created_by),body:$0(Y.content??`annotation ${Y.id}`),payload:a0(Y.verbatim)}}case N5:{let Y=z.raw;return{nk:{source:g0,stream:N5,sourceId:String(Y.id)},ts:Y.created_at!==""?Y.created_at:Q(),tier:"api",kind:"person.changed",schemaVersion:1,mentions:Z_(Y),body:$0(Y.name??(Y.distinct_ids[0]??`person ${Y.id}`)),payload:a0(Y.verbatim)}}case A5:{let Y=z.raw;return{nk:{source:g0,stream:A5,sourceId:String(Y.id)},ts:Y.created_at!==""?Y.created_at:Q(),tier:"api",kind:"cohort.changed",schemaVersion:1,mentions:e9(Y.created_by),body:$0(Y.name??`cohort ${Y.id}`),payload:a0(Y.verbatim)}}case _5:{let Y=z.raw;return{nk:{source:g0,stream:_5,sourceId:String(Y.id)},ts:Y.created_at!==""?Y.created_at:Q(),tier:"api",kind:"feature_flag.changed",schemaVersion:1,mentions:e9(Y.created_by),body:$0(Y.key??Y.name??`feature flag ${Y.id}`),payload:a0(Y.verbatim)}}case $9:{let Y=z.raw;return{nk:{source:g0,stream:$9,sourceId:Y.id,rev:Y.timestamp},ts:Y.timestamp,tier:"api",kind:"event.recorded",schemaVersion:1,mentions:Q_(Y),body:$0(Y.event!==""?Y.event:`event ${Y.id}`),payload:a0(Y.verbatim)}}default:throw Error(`posthog normalize: undeclared streamRef '${z.streamRef}'`)}}}}var jj=($)=>JSON.stringify($);var fG=E(()=>{f();j$();$j();f6();bG()});class Wj{projectName;tMs=X_;nextInsightId=1;nextDashboardId=1;nextAnnotationId=1;nextPersonId=1;nextCohortId=1;nextFeatureFlagId=1;nextEventSeq=1;eventPageSize=$Z;insights=new Map;dashboards=new Map;annotations=new Map;persons=new Map;cohorts=new Map;featureFlags=new Map;events=[];attributed={insight:{phantoms:0,reasons:[]},dashboard:{phantoms:0,reasons:[]},annotation:{phantoms:0,reasons:[]},person:{phantoms:0,reasons:[]},cohort:{phantoms:0,reasons:[]},featureFlag:{phantoms:0,reasons:[]}};failure=null;constructor($="1"){this.projectName=$}setProject($){this.projectName=$}get project(){return this.projectName}setEventPageSize($){if($<1)throw Error("event page size must be \u2265 1");this.eventPageSize=$}tick(){return this.tMs+=1000,new Date(this.tMs).toISOString()}user(){return{id:7,distinct_id:"u7",first_name:"Kwun",last_name:"West",email:"kwun@example.test"}}plantInsight($={}){let Z=$.id??this.nextInsightId++;if(Z>=this.nextInsightId)this.nextInsightId=Z+1;let Q=$.lastModifiedAt??this.tick(),X=$.name===void 0?`Insight ${Z}`:$.name,z=$.createdBy===void 0?this.user():$.createdBy,Y={id:Z,short_id:`sh${Z}`,name:X,last_modified_at:Q,created_at:"2026-07-01T00:00:00.000Z",query:{kind:"TrendsQuery",series:[{event:"$pageview"}]},...$.extra??{}},j={project:this.projectName,id:Z,short_id:`sh${Z}`,name:X,derived_name:X===null?`Insight ${Z} (derived)`:null,last_modified_at:Q,created_by:z,verbatim:Y};return this.insights.set(Z,j),j}plantDashboard($={}){let Z=$.id??this.nextDashboardId++;if(Z>=this.nextDashboardId)this.nextDashboardId=Z+1;let Q=$.lastModifiedAt??this.tick(),X=$.name===void 0?`Dashboard ${Z}`:$.name,z=$.createdBy===void 0?this.user():$.createdBy,Y={project:this.projectName,id:Z,name:X,last_modified_at:Q,created_by:z,verbatim:{id:Z,name:X,last_modified_at:Q,created_at:"2026-07-01T00:00:00.000Z",pinned:!1}};return this.dashboards.set(Z,Y),Y}plantAnnotation($={}){let Z=$.id??this.nextAnnotationId++;if(Z>=this.nextAnnotationId)this.nextAnnotationId=Z+1;let Q=$.updatedAt??this.tick(),X=$.content===void 0?`Annotation ${Z}`:$.content,z=$.createdBy===void 0?this.user():$.createdBy,Y={project:this.projectName,id:Z,content:X,updated_at:Q,created_by:z,verbatim:{id:Z,content:X,updated_at:Q,created_at:"2026-07-01T00:00:00.000Z",scope:"project",date_marker:Q}};return this.annotations.set(Z,Y),Y}plantPerson($={}){let Z=$.id??this.nextPersonId++;if(Z>=this.nextPersonId)this.nextPersonId=Z+1;let Q=$.distinctIds??[`person-${Z}@example.test`],X=$.name===void 0?`Person ${Z}`:$.name,z=$.uuid===void 0?`00000000-0000-4000-8000-${String(Z).padStart(12,"0")}`:$.uuid,Y=$.properties??{email:Q[0]??null,plan:"free"},j={project:this.projectName,id:Z,uuid:z,name:X,distinct_ids:Q,created_at:"2026-07-01T00:00:00.000Z",verbatim:{id:Z,uuid:z,name:X,distinct_ids:Q,properties:Y,created_at:"2026-07-01T00:00:00.000Z"}};return this.persons.set(Z,j),j}plantCohort($={}){let Z=$.id??this.nextCohortId++;if(Z>=this.nextCohortId)this.nextCohortId=Z+1;let Q=$.name===void 0?`Cohort ${Z}`:$.name,X=$.createdBy===void 0?this.user():$.createdBy,z=$.properties??{properties:{type:"AND",values:[]}},Y={project:this.projectName,id:Z,name:Q,created_at:"2026-07-01T00:00:00.000Z",created_by:X,verbatim:{id:Z,name:Q,filters:z,created_at:"2026-07-01T00:00:00.000Z",created_by:X===null?null:{id:X.id},is_static:!1,last_calculation:"2026-07-01T00:00:00.000Z"}};return this.cohorts.set(Z,Y),Y}plantFeatureFlag($={}){let Z=$.id??this.nextFeatureFlagId++;if(Z>=this.nextFeatureFlagId)this.nextFeatureFlagId=Z+1;let Q=$.key===void 0?`flag-${Z}`:$.key,X=$.name===void 0?`Feature Flag ${Z}`:$.name,z=$.createdBy===void 0?this.user():$.createdBy,Y=$.active??!0,j={project:this.projectName,id:Z,key:Q,name:X,created_at:"2026-07-01T00:00:00.000Z",created_by:z,verbatim:{id:Z,key:Q,name:X,active:Y,filters:{groups:[]},created_at:"2026-07-01T00:00:00.000Z",created_by:z===null?null:{id:z.id}}};return this.featureFlags.set(Z,j),j}plantEvent($={}){let Z=this.nextEventSeq++,Q=$.id??`evt-${String(Z).padStart(8,"0")}`,X=$.timestamp??this.tick(),z=$.event??"$pageview",Y=$.distinctId===void 0?`person-${Z}@example.test`:$.distinctId,j=$.properties??{$current_url:"https://app.example.test/",$browser:"Chrome"},W={project:this.projectName,id:Q,event:z,timestamp:X,distinct_id:Y,verbatim:{id:Q,event:z,timestamp:X,distinct_id:Y,properties:j,elements_chain:""}};return this.events.push(W),W}planPhantoms($,Z){this.attributed[$].phantoms+=Z}planAttributed($,Z,Q){this.attributed[$].phantoms+=Q,this.attributed[$].reasons.push({reason:Z,count:Q})}setFailure($){this.failure=$}streamCensus($,Z){let Q=this.attributed[$],X={total:Z+Q.phantoms};if(Q.reasons.length>0)X.partialReasons=Q.reasons.map((z)=>({...z}));return X}census(){if(this.failure!==null)return{err:this.failure};return H({insight:this.streamCensus("insight",this.insights.size),dashboard:this.streamCensus("dashboard",this.dashboards.size),annotation:this.streamCensus("annotation",this.annotations.size),person:this.streamCensus("person",this.persons.size),cohort:this.streamCensus("cohort",this.cohorts.size),featureFlag:this.streamCensus("featureFlag",this.featureFlags.size)})}list(){if(this.failure!==null)return{err:this.failure};let $=(Z)=>[...Z.values()].map((Q)=>({...Q})).sort((Q,X)=>Q.id-X.id);return H({insights:$(this.insights),dashboards:$(this.dashboards),annotations:$(this.annotations),persons:$(this.persons),cohorts:$(this.cohorts),featureFlags:$(this.featureFlags)})}listEvents($){if(this.failure!==null)return{err:this.failure};let Z=$.after!==null?Date.parse($.after):null,Q=this.events.filter((W)=>Z===null||Date.parse(W.timestamp)>Z).map((W)=>({...W})).sort((W,V)=>W.timestamp<V.timestamp?-1:W.timestamp>V.timestamp?1:W.id<V.id?-1:W.id>V.id?1:0),X=$.next!==null?Number.parseInt($.next.replace(/^off:/,""),10):0;if(!Number.isFinite(X)||X<0)return{err:{code:"internal",layer:"connector",retryability:"non-retryable",message:`fixture: corrupt event offset cursor '${$.next}'`}};let z=Q.slice(X,X+this.eventPageSize),Y=X+z.length,j=Y<Q.length?`off:${Y}`:null;return H({events:z,next:j})}}var X_;var kG=E(()=>{f();f6();X_=Date.parse("2026-07-01T00:00:00.000Z")});class Kj{inner;snapshot;constructor($){this.inner=$}selected(){if(this.snapshot!==void 0)return H(this.snapshot);let $=this.inner.starterSnapshot(Vj);if(!K($))return $;return this.snapshot=$.ok,H(this.snapshot)}census(){let $=this.selected();if(!K($))return $;return H({insight:{total:$.ok.insights.length},dashboard:{total:0},annotation:{total:0},person:{total:0},cohort:{total:0},featureFlag:{total:0}})}list(){return this.selected()}listEvents($){return H({events:[],next:null})}}var Vj=10;var wG=E(()=>{f()});var mG;var hG=E(()=>{mG={research:{candidates:[{repo:"PostHog/posthog-node",recency:0.9,commits:0.9,comprehensiveness:0.4,maintenance:0.9},{repo:"PostHog/posthog-js",recency:0.9,commits:0.9,comprehensiveness:0.3,maintenance:0.9},{repo:"PostHog/mcp (posthog MCP server)",recency:0.8,commits:0.7,comprehensiveness:0.6,maintenance:0.7}],chosen:"from-scratch",rationale:"The two PostHog SDKs (posthog-node, posthog-js) target event CAPTURE \u2014 posthog.capture()/feature flags \u2014 not the private READ API this connector ingests; wrapping them buys nothing and pulls in the write path v0 explicitly avoids. The PostHog MCP server is the only real read wrapper, but adopting it forces tier 'mcp-wrapped', a vendored server + SDK pinned against quarterly churn (\xA78.5), and the annotation/classification gates \u2014 a large supply-chain and maintenance surface for what is SEVEN documented read surfaces: the insights, dashboards, annotations, persons, cohorts and feature_flags list endpoints PLUS the analytics EVENT firehose (GET /api/projects/{id}/events/, paged by a documented time-window cursor), plus /api/users/@me/. EVERY data (P29) is ingested \u2014 the events the thin v0 excluded are now paged honestly, incremental not sliced. The leaf import law (REPO-STRUCTURE \xA72.3) forbids the dependency regardless. So the honest choice is a from-scratch thin read client over the injected transport seam: zero third-party code (wrapsThirdParty:false), G1-gated wire, and the documented API shape as the only knowledge needed.",refs:["PostHog private API reference (insights/dashboards/annotations/persons/cohorts/feature_flags list, users/@me, pagination {count,next,previous,results}): https://posthog.com/docs/api","PostHog events API (GET /api/projects/{id}/events/, {next,results} with no count, `after`/`before` time window): https://posthog.com/docs/api/events","PostHog persons API (GET /api/projects/{id}/persons/, distinct_ids + merged properties): https://posthog.com/docs/api/persons","PostHog personal API keys + scopes (Bearer auth, scoped read keys): https://posthog.com/docs/api#authentication","PostHog cloud regions (US https://us.posthog.com / EU https://eu.posthog.com / self-hosted base URL): https://posthog.com/docs/api","PostHog/posthog-node \u2014 event CAPTURE SDK, not the read API: https://github.com/PostHog/posthog-node","PostHog/mcp \u2014 the read wrapper ruled out on tier + leaf law: https://github.com/PostHog/mcp","connectors \xA72.2 \u2014 container-scoped default (undocumented cross-account/project id uniqueness); \xA72.4 pagination-exhaustion for the count-less firehose; \xA78.5 MCP churn row"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"posthog-api@2026-07-06",schemas:[{name:"posthog-read-rest",kind:"openapi"}],identityFacts:[{stream:"insight",fact:"numeric project-scoped id (per-project primary key; recurs across projects) \u2192 container-scoped with the project epoch; upstream-version on last_modified_at; soft-delete only (no observable tombstone \u2192 no deleteKind)",citation:"posthog.com/docs/api (insights list: id, short_id, name, last_modified_at, created_by) + connectors \xA72.2 container-scoped default"},{stream:"dashboard",fact:"numeric project-scoped id \u2192 container-scoped (project epoch); upstream-version on last_modified_at; soft-delete only",citation:"posthog.com/docs/api (dashboards list: id, name, last_modified_at, created_by) + connectors \xA72.2"},{stream:"annotation",fact:"numeric project-scoped id \u2192 container-scoped (project epoch); upstream-version on updated_at (not last_modified_at); content-bodied",citation:"posthog.com/docs/api (annotations list: id, content, updated_at, created_by) + connectors \xA72.2"},{stream:"person",fact:"numeric project-scoped id \u2192 container-scoped (project epoch); the person `uuid` is durable-but-EDITORIAL (payload, not identity); MUTABLE (distinct_ids merge, properties accrue) but the list carries NO modification instant (only created_at) \u2192 revOrder head-compare (appender contentHash orders the chain); soft-delete only",citation:"posthog.com/docs/api (persons list: id, uuid, distinct_ids, properties, created_at \u2014 no updated_at) + connectors \xA72.2 container-scoped default + \xA72.4 head-compare"},{stream:"cohort",fact:"numeric project-scoped id \u2192 container-scoped (project epoch); MUTABLE grouping with no documented edit instant (last_calculation is a background recompute, NOT authorship \u2014 excluded as rev to avoid forking on recalc) \u2192 revOrder head-compare; soft-delete only",citation:"posthog.com/docs/api (cohorts list: id, name, filters, created_at, created_by, last_calculation \u2014 no updated_at) + connectors \xA72.2 + \xA72.4 head-compare"},{stream:"feature-flag",fact:"numeric project-scoped id \u2192 container-scoped (project epoch); MUTABLE rollout rule with no documented modification instant \u2192 revOrder head-compare (a toggled/edited flag re-hashes to a new revision); the human `key` rides payload; soft-delete only",citation:"posthog.com/docs/api (feature_flags list: id, key, name, filters, active, created_at, created_by \u2014 no updated_at) + connectors \xA72.2 + \xA72.4 head-compare"},{stream:"event",fact:"UUID id \u2192 container-scoped (project epoch; cross-project uuid uniqueness UNdocumented so 'durable' would be a misdeclaration, \xA77.5); IMMUTABLE observation \u2192 revOrder event-ts (rev := timestamp as RFC3339 UTC millis, one revision each); NO provider count \u2192 coverage 'pagination-exhaustion'; NO deletion (a firehose only appends); paged by a documented time-window cursor (after high-water mark + opaque next)",citation:"posthog.com/docs/api events (id uuid, event, timestamp, distinct_id, properties; {next,results} with no count; `after`/`before` window) + connectors \xA72.2 container-scoped default + \xA72.4 event-ts / pagination-exhaustion"}]},identity:{perStream:[{stream:"insight",citation:"connectors \xA72.2 container-scoped default (numeric project-scoped id; cross-project uniqueness undocumented) + upstream-version last_modified_at"},{stream:"dashboard",citation:"connectors \xA72.2 container-scoped default + upstream-version last_modified_at"},{stream:"annotation",citation:"connectors \xA72.2 container-scoped default + upstream-version updated_at"},{stream:"person",citation:"connectors \xA72.2 container-scoped default (numeric project-scoped id; uuid editorial) + \xA72.4 head-compare (no upstream modification instant)"},{stream:"cohort",citation:"connectors \xA72.2 container-scoped default + \xA72.4 head-compare (last_calculation is a background recompute, not authorship)"},{stream:"feature-flag",citation:"connectors \xA72.2 container-scoped default + \xA72.4 head-compare (no upstream modification instant)"},{stream:"event",citation:"connectors \xA72.2 container-scoped default (UUID; cross-project uniqueness undocumented) + \xA72.4 event-ts (immutable observation) + pagination-exhaustion coverage (no provider count)"}]},classification:{rows:[]}}});var uG={};h0(uG,{refusePosthogAction:()=>EG,normalizeBaseUrl:()=>W4,gatedWanTransport:()=>zj,creatorMentions:()=>e9,createPosthogConnector:()=>gG,StarterPosthogSource:()=>Kj,POSTHOG_WAN_GATE:()=>Xj,POSTHOG_V0_READ_ONLY_GATE:()=>eY,POSTHOG_US_BASE:()=>j4,POSTHOG_STARTER_INSIGHT_LIMIT:()=>Vj,POSTHOG_SOURCE:()=>g0,POSTHOG_PULL_CAP:()=>Yj,POSTHOG_PERSON_STREAM:()=>N5,POSTHOG_PAGE_LIMIT:()=>t9,POSTHOG_MANIFEST:()=>v6,POSTHOG_INSIGHT_STREAM:()=>P5,POSTHOG_FEATURE_FLAG_STREAM:()=>_5,POSTHOG_EVENT_STREAM:()=>$9,POSTHOG_EVENT_RUN_CAP:()=>b6,POSTHOG_EVENT_PAGE_LIMIT:()=>$Z,POSTHOG_EU_BASE:()=>vG,POSTHOG_DASHBOARD_STREAM:()=>C5,POSTHOG_COHORT_STREAM:()=>A5,POSTHOG_ARTIFACTS:()=>mG,POSTHOG_ANNOTATION_STREAM:()=>F5,HttpPosthogSource:()=>g6,FixturePosthogSource:()=>Wj});var qj=E(()=>{$j();fG();f6();kG();wG();hG()});function ZU($){return W$(`activitywatch action '${$}'`,Jj)}var q4="activitywatch",Z9="sample",k6,Jj="connectors.md \xA72.3c classification review \u2014 activitywatch v0 declares zero ActionContracts (read-only ingestion)";var Gj=E(()=>{j$();k6={source:q4,tier:"local-app",auth:{provider:"local",method:"none",scopes:[],multiAccount:!1,probe:{op:"api-info"}},streams:[{stream:Z9,kinds:["signal.sampled"],identity:{quality:"container-scoped",epochField:"bucket"},revOrder:"event-ts"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"}});function XU($){return L_.has($.toLowerCase().replace(/[^a-z0-9]/g,""))}function M_($){if($==="")return $;let Z=$;for(let Q of D_)Q.lastIndex=0,Z=Z.replace(Q,"REDACTED-credential-shape");return Z}function QU($){if($==="")return $;return $.split("&").map((Z)=>{let Q=Z.indexOf("=");if(Q===-1)return Z;let X=Z.slice(0,Q);return XU(X)?`${X}=REDACTED-credential-param`:Z}).join("&")}function P_($){if($==="")return $;let Z=$.indexOf("#"),Q=Z===-1?$:$.slice(0,Z),X=Z===-1?"":$.slice(Z+1),z=Q.indexOf("?"),Y=z===-1?Q:Q.slice(0,z),j=z===-1?"":Q.slice(z+1),W=Y+(z===-1?"":`?${QU(j)}`)+(Z===-1?"":`#${QU(X)}`);return M_(W)}function Uj($){let Z={};for(let[Q,X]of Object.entries($))Z[Q]=XU(Q)?"REDACTED-credential-param":zU(X);return Z}function zU($){if(typeof $==="string")return P_($);if(Array.isArray($))return $.map(zU);if($!==null&&typeof $==="object")return Uj($);return $}var L_,D_;var YU=E(()=>{L_=new Set(["token","apikey","accesstoken","key","authorization","secret","refreshtoken","clientsecret","idtoken","sessiontoken"]);D_=[/ya29\.[A-Za-z0-9_-]{8,}/g,/\b1\/\/[A-Za-z0-9_-]{8,}/g,/\bgh[opusr]_[A-Za-z0-9]{8,}/g,/\bgithub_pat_[A-Za-z0-9_]{16,}/g,/\bxox[bpae][-.][A-Za-z0-9-]{8,}/g,/\bsecret_[A-Za-z0-9]{16,}/g,/\bntn_[A-Za-z0-9]{16,}/g,/\bphx_[A-Za-z0-9_-]{32,}/g,/\bsk-[A-Za-z0-9_-]{16,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g]});function w6($){if($===void 0||$===null)return"";if(typeof $==="string")return $;return JSON.stringify($)}function Lj($,Z){if($==="afkstatus")return`afk: ${w6(Z.status)}`;if($==="currentwindow")return`window: ${w6(Z.app)} \u2014 ${w6(Z.title)}`;let Q=Object.keys(Z).sort().map((X)=>`${X}=${w6(Z[X])}`);return`${$}: ${Q.join(", ")}`}function jU($){return{manifest:k6,discover(Z){let Q=$.census();if(!K(Q))return Q;return H({asOf:new Date().toISOString(),streams:{[Z9]:{total:Q.ok.samples,method:"count-api"}}})},pull(Z,Q){let X=$.list();if(!K(X))return X;let z=X.ok.map((Y)=>({streamRef:Z9,raw:Y}));return H({items:z,next:null,exhausted:!0})},normalize(Z){if(Z.streamRef!==Z9)throw Error(`activitywatch normalize: undeclared streamRef '${Z.streamRef}'`);let Q=Z.raw,X=Uj(Q.data);return{nk:{source:q4,stream:Z9,sourceId:String(Q.id),rev:Q.timestamp},ts:Q.timestamp,tier:"local-app",kind:"signal.sampled",schemaVersion:1,mentions:[],body:Lj(Q.bucketType,X),payload:{bucket:Q.bucket,duration:Q.duration,data:X}}}}}var WU=E(()=>{f();Gj();YU()});function Mj($){let Z;try{Z=new URL($)}catch{return C("invalid_argument",`aw base URL '${$}' is not a parseable URL`)}if(Z.protocol!=="http:"&&Z.protocol!=="https:")return C("invalid_argument",`aw base URL '${$}' must be http(s) \u2014 got protocol '${Z.protocol}'`);if(!C_.has(Z.hostname))return C("invalid_argument",`aw base URL host '${Z.hostname}' is not loopback \u2014 aw-server is a LOCAL app (D9 local-app tier), never an outbound transport; only 127.0.0.1 / localhost / ::1 are permitted (keeps G1 honest)`);return H(`${Z.protocol}//${Z.host}`)}class m6{base;get;constructor($,Z){this.base=$,this.get=Z}static create($={}){let Z=Mj($.baseUrl??Dj);if(!K(Z))return Z;return H(new m6(Z.ok,$.get??Pj))}get baseUrl(){return this.base}unavailable($){return C("unavailable",`aw-server unreachable at ${this.base} \u2014 is ActivityWatch running? (${$}) \u2014 NEVER an empty success (FM-21)`,"transient")}httpStatusError($,Z){return $>=500?C("unavailable",`aw ${Z} returned HTTP ${$}`,"transient"):C("internal",`aw ${Z} returned HTTP ${$} \u2014 REST-surface drift (FM-19)`,"non-retryable")}fetchBuckets(){let $=this.get(`${this.base}/api/0/buckets/`);if(!$.ok)return this.unavailable($.error);if($.status!==200)return this.httpStatusError($.status,"GET /api/0/buckets/");let Z;try{Z=JSON.parse($.body)}catch{return C("internal","aw buckets response is not JSON \u2014 REST-surface drift (FM-19)")}if(Z===null||typeof Z!=="object"||Array.isArray(Z))return C("internal","aw buckets response is not an id\u2192meta object \u2014 REST-surface drift (FM-19)");let Q=[];for(let[X,z]of Object.entries(Z)){let Y=z?.type;Q.push({id:X,type:typeof Y==="string"?Y:""})}return Q.sort((X,z)=>X.id<z.id?-1:X.id>z.id?1:0),H(Q)}census(){let $=this.fetchBuckets();if(!K($))return $;let Z=0;for(let Q of $.ok){let X=this.get(`${this.base}/api/0/buckets/${encodeURIComponent(Q.id)}/events/count`);if(!X.ok)return this.unavailable(X.error);if(X.status!==200)return this.httpStatusError(X.status,`GET events/count for '${Q.id}'`);let z=Number.parseInt(X.body.trim(),10);if(Number.isNaN(z))return C("internal",`aw events/count for '${Q.id}' returned non-numeric '${X.body.trim()}' \u2014 REST-surface drift (FM-19)`);Z+=z}return H({samples:Z})}list(){let $=this.fetchBuckets();if(!K($))return $;let Z=[];for(let Q of $.ok){let X=H4-Z.length+1,z=this.get(`${this.base}/api/0/buckets/${encodeURIComponent(Q.id)}/events?limit=${X}`);if(!z.ok)return this.unavailable(z.error);if(z.status!==200)return this.httpStatusError(z.status,`GET events for '${Q.id}'`);let Y;try{Y=JSON.parse(z.body)}catch{return C("internal",`aw events for '${Q.id}' response is not JSON \u2014 REST-surface drift (FM-19)`)}if(!Array.isArray(Y))return C("internal",`aw events for '${Q.id}' response is not an array \u2014 REST-surface drift (FM-19)`);for(let j of Y){let W=j;if(W===null||typeof W.id!=="number"||typeof W.timestamp!=="string"||typeof W.duration!=="number"||W.data===null||typeof W.data!=="object"||Array.isArray(W.data))return C("internal",`aw event row in '${Q.id}' has an unexpected shape \u2014 REST-surface drift (FM-19)`);Z.push({bucket:Q.id,bucketType:Q.type,id:W.id,timestamp:W.timestamp,duration:W.duration,data:W.data})}if(Z.length>H4)return C("resource_exhausted",`aw pull exceeded the ${H4}-event cap \u2014 refusing a partial snapshot (loud, never a silent truncation that would misreconcile FM-18 coverage); narrow the pull window`,"non-retryable")}return H(Z)}}var H4=20000,Dj="http://127.0.0.1:5600",C_,Pj=($)=>{let Z=Bun.spawnSync(["curl","-sS","--max-time","10","-w",`
372
+ %{http_code}`,$],{stdout:"pipe",stderr:"pipe"});if((Z.exitCode??1)!==0){let j=Z.stderr.toString().trim();return{ok:!1,error:j!==""?j:`curl exit ${Z.exitCode??"?"}`}}let Q=Z.stdout.toString(),X=Q.lastIndexOf(`
373
+ `),z=X>=0?Q.slice(0,X):Q,Y=X>=0?Number.parseInt(Q.slice(X+1),10):Number.NaN;return{ok:!0,status:Number.isNaN(Y)?0:Y,body:z}};var VU=E(()=>{f();j$();C_=new Set(["127.0.0.1","localhost","::1","[::1]"])});class Cj{buckets=new Map;tMs=F_;unreachable=!1;addBucket($,Z){if(!this.buckets.has($))this.buckets.set($,{type:Z,events:[]})}plant($,Z){let Q=this.buckets.get($);if(Q===void 0)throw Error(`fixture: unknown bucket '${$}' \u2014 addBucket first`);this.tMs+=1000;let z={id:Z.id??Q.events.length+1,timestamp:Z.timestamp??new Date(this.tMs).toISOString(),duration:Z.duration??1,data:Z.data};return Q.events.push(z),{bucket:$,bucketType:Q.type,id:z.id,timestamp:z.timestamp,duration:z.duration,data:z.data}}setUnreachable($=!0){this.unreachable=$}serverAbsent(){return C("unavailable","fixture: aw-server unreachable (server-absent drill) \u2014 NEVER an empty success (FM-21)","transient")}census(){if(this.unreachable)return this.serverAbsent();let $=0;for(let Z of this.buckets.values())$+=Z.events.length;return H({samples:$})}list(){if(this.unreachable)return this.serverAbsent();let $=[],Z=[...this.buckets.entries()].sort(([Q],[X])=>Q<X?-1:Q>X?1:0);for(let[Q,X]of Z)for(let z of X.events)$.push({bucket:Q,bucketType:X.type,id:z.id,timestamp:z.timestamp,duration:z.duration,data:z.data});return H($)}}var F_;var KU=E(()=>{f();j$();F_=Date.parse("2026-07-01T00:00:00.000Z")});var qU;var HU=E(()=>{qU={research:{candidates:[{repo:"8bitgentleman/activitywatch-mcp-server",recency:2,commits:2,comprehensiveness:4,maintenance:2},{repo:"Auriora/activitywatch-mcp",recency:2,commits:2,comprehensiveness:3,maintenance:2},{repo:"galacoder/mcp-activitywatch",recency:1,commits:1,comprehensiveness:2,maintenance:1},{repo:"doozMen/activitywatch-mcp",recency:2,commits:2,comprehensiveness:3,maintenance:2},{repo:"ActivityWatch/aw-client",recency:4,commits:4,comprehensiveness:4,maintenance:4}],chosen:"from-scratch",rationale:"Leaf import law (REPO-STRUCTURE \xA72.3) forbids importing or vendoring ANY third-party package, so no MCP server and no aw-client library can be wrapped. INDRA needs only READ ingestion (GET buckets + events + events/count) \u2014 a tiny stable slice of the documented aw-server REST v0 surface, not the AQL engine or the write/heartbeat path the MCP servers wrap. A from-scratch thin loopback client is the lowest supply-chain-risk option (wrapsThirdParty:false) and the only one compatible with the D9 local-app tier and the loopback law.",refs:["https://docs.activitywatch.net/en/latest/api/rest.html","https://github.com/8bitgentleman/activitywatch-mcp-server","https://github.com/ActivityWatch/aw-client","https://github.com/ActivityWatch/awesome-activitywatch"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"aw-server-rest@0",schemas:[{name:"bucket-events",kind:"openapi"}],identityFacts:[{stream:"sample",fact:"AW event ids are small per-bucket integers that RESET per bucket (live 2026-07-06: window 1438/1439, afk 3, input 15) \u2014 durable only within the bucket epoch; events are immutable once assigned a distinct id (heartbeat only extends the current open event); no read-path deletion exists",citation:"https://docs.activitywatch.net/en/latest/api/rest.html + live observation 2026-07-06 (index.ts receipt)"}]},identity:{perStream:[{stream:"sample",citation:"container-scoped, epochField 'bucket' (framework prefixes '<bucket>:<id>' \u2014 identity.ts prefixEpoch, epoch-proof test); revOrder event-ts per I-1 rev authorship (appender toRfc3339UtcMillis); no deleteKind \u2014 an unobservable tombstone would be a lie (connectors \xA72.2)"}]},classification:{rows:[]}}});var BU={};h0(BU,{renderSampleBody:()=>Lj,refuseActivityWatchAction:()=>ZU,createActivityWatchConnector:()=>jU,bunCurlGet:()=>Pj,assertLoopbackBase:()=>Mj,HttpAwSource:()=>m6,FixtureAwSource:()=>Cj,AW_PULL_CAP:()=>H4,AW_DEFAULT_BASE:()=>Dj,ACTIVITYWATCH_V0_READ_ONLY_GATE:()=>Jj,ACTIVITYWATCH_SOURCE:()=>q4,ACTIVITYWATCH_SAMPLE_STREAM:()=>Z9,ACTIVITYWATCH_PIPELINE_ARTIFACTS:()=>qU,ACTIVITYWATCH_MANIFEST:()=>k6,ACTIVITYWATCH_ARTIFACTS:()=>N_});var N_;var JU=E(()=>{Gj();WU();VU();KU();HU();N_={auth:{provider:"local",method:"none",scopes:[],multiAccount:!1,probe:{op:"api-info",endpoint:"GET /api/0/info"},machineSetup:{installed:!0,running:!0,installMethod:"pre-existing (aw-qt already running; brew unavailable, not in /Applications \u2014 standalone aw-server)",infoPayload:{hostname:"Kaynes-MacBook-Pro.local",version:"v0.14.0b1",testing:!1},liveArm:"available"}},research:{chosen:"from-scratch",rationale:"Leaf import law (REPO-STRUCTURE \xA72.3) forbids importing or vendoring ANY third-party package \u2014 a connector leaf may import only @indra/contracts + @indra/connector-framework + builtins \u2014 so no MCP server and no aw-client library can be wrapped. INDRA needs only READ ingestion (GET buckets + events + events/count), a tiny stable slice of the documented aw-server REST v0 surface, not the AQL query engine or the write/heartbeat path the MCP servers wrap. A from-scratch thin loopback client is therefore the lowest supply-chain-risk option (wrapsThirdParty:false) and the only one compatible with the D9 local-app tier and the loopback law.",refs:["https://docs.activitywatch.net/en/latest/api/rest.html","https://github.com/8bitgentleman/activitywatch-mcp-server","https://github.com/ActivityWatch/aw-client","https://github.com/ActivityWatch/awesome-activitywatch"],candidates:[{name:"8bitgentleman/activitywatch-mcp-server",ref:"https://github.com/8bitgentleman/activitywatch-mcp-server",kind:"mcp-server",language:"TypeScript",signals:{stars:69,forks:20,commits:30,tools:["list-buckets","run-query (AQL)","get-events","get-settings"]},scores:{recency:2,commits:2,comprehensiveness:4,maintenance:2},overall:2.5,note:"Most popular + comprehensive AW MCP; TS. Wraps the AQL query engine + settings (write-adjacent, heavier than read ingest). Cannot be imported (leaf law); no recent-release signal."},{name:"Auriora/activitywatch-mcp",ref:"https://github.com/Auriora/activitywatch-mcp",kind:"mcp-server",language:"unknown",signals:{note:"LLM query/analyze of AW data"},scores:{recency:2,commits:2,comprehensiveness:3,maintenance:2},overall:2.25,note:"Alternate AW MCP. Same leaf-law block; fewer maintenance signals than 8bitgentleman."},{name:"galacoder/mcp-activitywatch",ref:"https://github.com/galacoder/mcp-activitywatch",kind:"mcp-server",language:"unknown",signals:{},scores:{recency:1,commits:1,comprehensiveness:2,maintenance:1},overall:1.25,note:"Sparse AW MCP; little signal. Not a viable base even if leaf law allowed wrapping."},{name:"doozMen/activitywatch-mcp",ref:"https://github.com/doozMen/activitywatch-mcp",kind:"mcp-server",language:"Swift",signals:{},scores:{recency:2,commits:2,comprehensiveness:3,maintenance:2},overall:1.5,note:"Swift runtime \u2014 incompatible with INDRA's Bun/TS runtime (would need a subprocess bridge); ruled out on runtime alone."},{name:"ActivityWatch/aw-client (+ aw-client-js)",ref:"https://github.com/ActivityWatch/aw-client",kind:"official-client-library",language:"Python / TypeScript",signals:{note:"official REST wrapper: get_events(limit,start,end), insert_event(s), delete_event"},scores:{recency:4,commits:4,comprehensiveness:4,maintenance:4},overall:4,note:"The authoritative, well-maintained client. STILL cannot be a leaf dependency (leaf law) and it carries the write path INDRA does not want. Used as the API-shape reference, not vendored."},{name:"aw-server REST API (documented spec)",ref:"https://docs.activitywatch.net/en/latest/api/rest.html",kind:"spec",language:"n/a",signals:{note:"the source of truth; interactive OpenAPI playground at http://localhost:5600/api/"},scores:{recency:4,commits:4,comprehensiveness:3,maintenance:4},overall:3.75,note:"The surface this connector was built AGAINST directly (not a wrapper to adopt). Docs self-describe as 'highly incomplete' \u2192 live playground + live probing filled the gaps."}]},supplyChain:{wrapsThirdParty:!1,vendored:null,note:"No vendored code. The connector talks to a local aw-server the USER installed; INDRA ships no aw-server binary and imports no aw client. manifest.vendored is therefore absent (only required when wrapping third-party MCP/connector code)."},discovered:{pin:"aw-server-rest@0",schemas:[{name:"bucket-events",kind:"openapi",ref:"http://localhost:5600/api/ (flask-restx OpenAPI) + https://docs.activitywatch.net/en/latest/api/rest.html",endpoints:["GET /api/0/info","GET /api/0/buckets/","GET /api/0/buckets/{id}/events?limit=&start=&end=","GET /api/0/buckets/{id}/events/count"],observedLive:{date:"2026-07-06",buckets:[{id:"aw-watcher-window_<host>",type:"currentwindow",eventDataKeys:["app","title"],sampleEventId:1439},{id:"aw-watcher-afk_<host>",type:"afkstatus",eventDataKeys:["status"],sampleEventId:3},{id:"aw-watcher-input_<host>",type:"os.hid.input",eventDataKeys:["presses","clicks","deltaX","deltaY","scrollX","scrollY"],sampleEventId:15}],eventShape:{id:"integer (per-bucket)",timestamp:"RFC3339 +00:00 (microsecond precision)",duration:"seconds (float)",data:"object"},countEndpointReturns:1425}}],identityFacts:{sample:{quality:"container-scoped",epoch:"the bucket id",epochField:"bucket",idField:"event id (per-bucket integer)",revOrder:"event-ts",deleteKind:null,citations:["REST docs: buckets group events; events carry id/timestamp/duration/data \u2014 https://docs.activitywatch.net/en/latest/api/rest.html","Live 2026-07-06: event ids are small per-bucket integers (window 1438/1439, afk 3, input 15) that RESET per bucket \u2192 durable only within the bucket epoch (I-1 container-scoped).","aw-server event model: distinct ids are written once and immutable; heartbeat only extends the CURRENT open event's duration \u2192 event-ts is the ordering authority; no read-path deletion \u2192 no deleteKind."]}}},identity:{perStream:{sample:{quality:"container-scoped",epochField:"bucket",revOrder:"event-ts",deleteKind:null,citations:["container-scoped: AW event ids are per-bucket integers (collide across buckets) \u2014 the framework prefixes the bucket epoch so '<bucketA>:1' \u2260 '<bucketB>:1' (identity.ts prefixEpoch; epoch-proof test).","event-ts: samples are immutable point-in-time observations; rev := ts, canonicalized by the appender via toRfc3339UtcMillis (I-1 rev authorship, event-log \xA72.3 step 3). AW always emits UTC (+00:00) so the rev never forks.","no deleteKind: aw-server never deletes on the read path (append-only bucket streams) \u2014 declaring an unobservable tombstone would be a lie (connectors \xA72.2)."]}}},classification:{rows:[],note:"v0 is read-only ingestion \u2014 zero ActionContracts. aw-server CAN write (POST events / heartbeat) but no contract enters the callable set before the \xA72.3c reviewer re-derivation; any invocation is a typed failed_precondition refusal (refuseActivityWatchAction)."}}});function GU($){return W$(`apple-notes action '${$}'`,Fj)}var ZZ="apple-notes",h6,Fj="connectors.md \xA72.3c classification review \u2014 apple-notes v0 declares zero ActionContracts (read-only)";var Nj=E(()=>{j$();h6={source:ZZ,tier:"local-app",auth:{provider:"apple",method:"local-permission",scopes:[],multiAccount:!1,probe:{op:"osascript.notes.count"}},tccPermissions:["automation"],streams:[{stream:"note",kinds:["note.changed"],deleteKind:"note.deleted",identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:"folder",kinds:["folder.changed"],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:60},retaliationRisk:"tolerant"}});function __($){return $.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g,(Z,Q)=>{if(Q.startsWith("#x")||Q.startsWith("#X")){let X=Number.parseInt(Q.slice(2),16);return Number.isNaN(X)?Z:String.fromCodePoint(X)}if(Q.startsWith("#")){let X=Number.parseInt(Q.slice(1),10);return Number.isNaN(X)?Z:String.fromCodePoint(X)}return A_[Q.toLowerCase()]??Z})}function u6($){let Z=$;return Z=Z.replace(/<br\s*\/?>/gi,`
374
+ `),Z=Z.replace(/<\/(?:div|p|h[1-6]|li|ul|ol|blockquote|tr|table|pre)>/gi,`
375
+ `),Z=Z.replace(/<li(?:\s[^>]*)?>/gi,"- "),Z=Z.replace(/<[^>]*>/g,""),Z=__(Z),Z=Z.split(`
376
+ `).map((Q)=>Q.replace(/[ \t]+$/g,"")).join(`
377
+ `),Z=Z.replace(/\n{3,}/g,`
378
+
379
+ `),Z.replace(/^\n+/,"").replace(/\n+$/,"")}var A_;var Aj=E(()=>{A_={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "}});function UU($){return{manifest:h6,discover(Z){let Q=$.counts();if(!("ok"in Q))return Q;return H({asOf:Q.ok.asOf,streams:{note:{total:Q.ok.liveNotes,method:"count-api"},folder:{total:Q.ok.folders,method:"count-api"}}})},pull(Z,Q){let X=$.list();if(!("ok"in X))return X;let z=[...X.ok.folders.map((Y)=>({streamRef:"folder",raw:Y})),...X.ok.notes.map((Y)=>({streamRef:"note",raw:Y}))];return H({items:z,next:null,exhausted:!0})},normalize(Z){if(Z.streamRef==="folder"){let Q=Z.raw;return{nk:{source:ZZ,stream:"folder",sourceId:Q.id},ts:_j,tier:"local-app",kind:"folder.changed",schemaVersion:1,mentions:[],body:Q.name,payload:Z.raw}}if(Z.streamRef==="note"){let Q=Z.raw;return{nk:{source:ZZ,stream:"note",sourceId:Q.id},ts:Q.modificationDate,tier:"local-app",kind:Q.deleted?"note.deleted":"note.changed",schemaVersion:1,mentions:[],body:u6(Q.body),payload:Z.raw}}throw Error(`apple-notes normalize: undeclared streamRef '${Z.streamRef}'`)}}}var _j="1970-01-01T00:00:00.000Z";var LU=E(()=>{f();Nj();Aj()});class Sj{defaultFolderId;trashFolderId;tMs=T_;pk=0;denied=!1;phantoms=0;folders=new Map;notes=new Map;constructor(){this.defaultFolderId=this.addFolder("Notes"),this.trashFolderId=this.addFolder("Recently Deleted")}tick(){return this.tMs+=1000,new Date(this.tMs).toISOString()}mintId($){return this.pk+=1,`${Tj}${$}/p${this.pk}`}addFolder($){let Z=this.mintId("ICFolder");return this.folders.set(Z,{id:Z,name:$}),Z}plant($={}){let Z=this.mintId("ICNote"),Q=this.tick(),X=$.folderId??this.defaultFolderId;if(!this.folders.has(X))throw Error(`fixture: unknown folder '${X}'`);return this.notes.set(Z,{id:Z,name:$.name??`Note ${this.pk}`,body:$.body??`<div>Note ${this.pk}</div><div>body</div>`,folderId:X,creationDate:Q,modificationDate:Q}),Z}modify($,Z){let Q=this.mustGet($);if(Z.name!==void 0)Q.name=Z.name;if(Z.body!==void 0)Q.body=Z.body;Q.modificationDate=this.tick()}deleteNote($){let Z=this.mustGet($);Z.folderId=this.trashFolderId,Z.modificationDate=this.tick()}restore($,Z){let Q=this.mustGet($);Q.folderId=Z??this.defaultFolderId,Q.modificationDate=this.tick()}purge($){this.mustGet($),this.notes.delete($)}planPhantoms($){this.phantoms=$}denyAuth($=!0){this.denied=$}mustGet($){let Z=this.notes.get($);if(Z===void 0)throw Error(`fixture: unknown note '${$}'`);return Z}tccDenied(){return v({code:"permission_denied",layer:"upstream",retryability:"non-retryable",message:"fixture TCC denial: Not authorized to send Apple events to Notes (-1743) \u2014 automation permission missing (auth.md local-permission flow repairs)"})}counts(){if(this.denied)return this.tccDenied();let $=0,Z=0;for(let Q of this.notes.values())if(Q.folderId===this.trashFolderId)Z+=1;else $+=1;return H({asOf:new Date(this.tMs).toISOString(),liveNotes:$+this.phantoms,deletedNotes:Z,folders:this.folders.size})}list(){if(this.denied)return this.tccDenied();let $=[...this.folders.values()].map((Q)=>({...Q})).sort((Q,X)=>Q.id<X.id?-1:1),Z=[...this.notes.values()].map((Q)=>{let X=this.folders.get(Q.folderId);return{id:Q.id,name:Q.name,body:Q.body,folder:X?.name??null,folderId:X?.id??null,creationDate:Q.creationDate,modificationDate:Q.modificationDate,deleted:Q.folderId===this.trashFolderId}}).sort((Q,X)=>Q.id<X.id?-1:1);return H({folders:$,notes:Z})}}var Tj="x-coredata://FIXTURE-STORE-0000/",T_;var DU=E(()=>{f();T_=Date.parse("2026-07-01T00:00:00.000Z")});function yj($,Z){if(/-1743|not authorized to send apple events|erraeeventnotpermitted/i.test(Z))return{code:"permission_denied",layer:"upstream",retryability:"non-retryable",message:"macOS TCC automation denial: osascript is not authorized to send Apple events to Notes (-1743) \u2014 acquire the 'automation' TCC grant via auth.md's local-permission flow"};if(/-1712|timed out/i.test(Z))return{code:"deadline_exceeded",layer:"upstream",retryability:"transient",message:`Apple event timed out talking to Notes (-1712): ${Rj(Z)}`};if(/-600|isn['\u2019]t running|not running/i.test(Z))return{code:"unavailable",layer:"upstream",retryability:"transient",message:`Notes.app not reachable (-600): ${Rj(Z)}`};return{code:"internal",layer:"upstream",retryability:"non-retryable",message:`osascript failed (exit ${$}): ${Rj(Z)} \u2014 scripting-interface drift is rot (FM-19); repair order due`}}function Rj($){return $.split(`
380
+ `,1)[0]?.trim()??""}function B4($){return v({code:"internal",layer:"upstream",retryability:"non-retryable",message:`unparseable osascript output (${$}) \u2014 scripting-interface drift is rot (FM-19)`})}class Ej{exec;constructor($=Oj){this.exec=$}run($){let Z=this.exec(["osascript","-l","JavaScript","-e",$]);if(Z.exitCode!==0)return v(yj(Z.exitCode,Z.stderr));try{return H(JSON.parse(Z.stdout))}catch(Q){return B4("not JSON")}}counts(){let $=this.run(xj);if(!("ok"in $))return $;let Z=$.ok;if(Z===null||typeof Z!=="object"||typeof Z.asOf!=="string"||typeof Z.liveNotes!=="number"||typeof Z.deletedNotes!=="number"||typeof Z.folders!=="number")return B4("counts shape");return H({asOf:Z.asOf,liveNotes:Z.liveNotes,deletedNotes:Z.deletedNotes,folders:Z.folders})}list(){let $=this.run(Ij);if(!("ok"in $))return $;let Z=$.ok;if(Z===null||typeof Z!=="object"||!Array.isArray(Z.folders)||!Array.isArray(Z.notes))return B4("listing shape");let Q=[];for(let z of Z.folders){if(typeof z?.id!=="string"||typeof z.name!=="string")return B4("folder row");Q.push({id:z.id,name:z.name})}let X=[];for(let z of Z.notes){if(typeof z?.id!=="string"||typeof z.name!=="string"||typeof z.body!=="string"||typeof z.creationDate!=="string"||typeof z.modificationDate!=="string"||typeof z.deleted!=="boolean")return B4("note row");X.push({id:z.id,name:z.name,body:z.body,...z.bodyUnreadable===!0?{bodyUnreadable:!0}:{},folder:typeof z.folder==="string"?z.folder:null,folderId:typeof z.folderId==="string"?z.folderId:null,creationDate:z.creationDate,modificationDate:z.modificationDate,deleted:z.deleted})}return Q.sort((z,Y)=>z.id<Y.id?-1:1),X.sort((z,Y)=>z.id<Y.id?-1:1),H({folders:Q,notes:X})}}var Oj=($)=>{let Z=Bun.spawnSync([...$],{stdout:"pipe",stderr:"pipe"});return{exitCode:Z.exitCode??1,stdout:Z.stdout.toString(),stderr:Z.stderr.toString()}},xj,Ij;var MU=E(()=>{f();xj=["(() => {"," const app = Application('Notes');"," const walk = (fs, out, seen) => {"," for (let i = 0; i < fs.length; i++) {"," let fid = null;"," try { fid = fs[i].id(); } catch (e) { continue; }"," if (seen[fid]) continue;"," seen[fid] = true;"," out.push(fs[i]);"," let subs = [];"," try { subs = fs[i].folders(); } catch (e) { subs = []; }"," walk(subs, out, seen);"," }"," return out;"," };"," const folders = walk(app.folders(), [], {});"," let deleted = 0;"," for (let i = 0; i < folders.length; i++) {"," if (folders[i].name() === 'Recently Deleted') deleted += folders[i].notes.id().length;"," }"," const total = app.notes.id().length;"," return JSON.stringify({ asOf: new Date().toISOString(), folders: folders.length, liveNotes: total - deleted, deletedNotes: deleted });","})()"].join(`
381
+ `),Ij=["(() => {"," const app = Application('Notes');"," const walk = (fs, out, seen) => {"," for (let i = 0; i < fs.length; i++) {"," let fid = null;"," try { fid = fs[i].id(); } catch (e) { continue; }"," if (seen[fid]) continue;"," seen[fid] = true;"," out.push(fs[i]);"," let subs = [];"," try { subs = fs[i].folders(); } catch (e) { subs = []; }"," walk(subs, out, seen);"," }"," return out;"," };"," const folders = walk(app.folders(), [], {});"," const foldersOut = [];"," const notesOut = [];"," for (let i = 0; i < folders.length; i++) {"," const fid = folders[i].id();"," const fname = folders[i].name();"," foldersOut.push({ id: fid, name: fname });"," const isDeleted = fname === 'Recently Deleted';"," const fnotes = folders[i].notes;"," const ids = fnotes.id();"," if (ids.length === 0) continue;"," const names = fnotes.name();"," const created = fnotes.creationDate();"," const modified = fnotes.modificationDate();"," let bodies = null;"," try { bodies = fnotes.body(); } catch (e) { bodies = null; }"," for (let j = 0; j < ids.length; j++) {"," let body = bodies !== null ? bodies[j] : null;"," let unreadable = false;"," if (body === null || body === undefined) {"," try { body = fnotes[j].body(); } catch (e) { body = ''; unreadable = true; }"," }"," notesOut.push({"," id: ids[j],"," name: names[j],"," body: body === null || body === undefined ? '' : body,"," bodyUnreadable: unreadable,"," folder: fname,"," folderId: fid,"," creationDate: created[j] ? created[j].toISOString() : new Date(0).toISOString(),"," modificationDate: modified[j] ? modified[j].toISOString() : new Date(0).toISOString(),"," deleted: isDeleted"," });"," }"," }"," return JSON.stringify({ folders: foldersOut, notes: notesOut });","})()"].join(`
382
+ `)});var PU={};h0(PU,{refuseAppleNotesAction:()=>GU,mapOsascriptFailure:()=>yj,htmlToText:()=>u6,createAppleNotesConnector:()=>UU,bunOsascriptExec:()=>Oj,OsascriptNotesSource:()=>Ej,FixtureNotesSource:()=>Sj,FOLDER_TS_UNKNOWN:()=>_j,FIXTURE_STORE_URI:()=>Tj,APPLE_NOTES_V0_READ_ONLY_GATE:()=>Fj,APPLE_NOTES_SOURCE:()=>ZZ,APPLE_NOTES_MANIFEST:()=>h6,APPLE_NOTES_LIST_SCRIPT:()=>Ij,APPLE_NOTES_COUNT_SCRIPT:()=>xj});var CU=E(()=>{Nj();LU();DU();MU();Aj()});function FU($){return W$(`chrome-history action '${$}'`,kj)}var T5="chrome-history",S0="visit",f0="download",k0="search-term",r0="bookmark",vj="visit.deleted",bj="download.deleted",gj="search-term.deleted",fj="bookmark.deleted",p6,kj="connectors.md \xA72.3c classification review \u2014 chrome-history v0 declares zero ActionContracts (read-only)";var wj=E(()=>{j$();p6={source:T5,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:[],multiAccount:!1,probe:{op:"stat-history-db"}},tccPermissions:["full-disk"],streams:[{stream:S0,kinds:["page.visited"],identity:{quality:"container-scoped",epochField:"profile"},revOrder:"event-ts",deleteKind:vj},{stream:f0,kinds:["file.downloaded"],identity:{quality:"container-scoped",epochField:"profile"},revOrder:"head-compare",deleteKind:bj},{stream:k0,kinds:["search.performed"],identity:{quality:"container-scoped",epochField:"profile"},revOrder:"event-ts",deleteKind:gj},{stream:r0,kinds:["bookmark.saved"],identity:{quality:"container-scoped",epochField:"profile"},revOrder:"head-compare",deleteKind:fj}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:60},retaliationRisk:"tolerant"}});function R_($){return S_.has($.toLowerCase().replace(/[^a-z0-9]/g,""))}function AU($){if($==="")return $;let Z=$;for(let Q of O_)Q.lastIndex=0,Z=Z.replace(Q,"REDACTED-credential-shape");return Z}function NU($){if($==="")return $;return $.split("&").map((Z)=>{let Q=Z.indexOf("=");if(Q===-1)return Z;let X=Z.slice(0,Q);return R_(X)?`${X}=REDACTED-credential-param`:Z}).join("&")}function Q9($){if($==="")return $;let Z=$.indexOf("#"),Q=Z===-1?$:$.slice(0,Z),X=Z===-1?"":$.slice(Z+1),z=Q.indexOf("?"),Y=z===-1?Q:Q.slice(0,z),j=z===-1?"":Q.slice(z+1),W=Y+(z===-1?"":`?${NU(j)}`)+(Z===-1?"":`#${NU(X)}`);return AU(W)}function X9($){return AU($)}function _U($){return $.map(Q9)}var S_,O_;var TU=E(()=>{S_=new Set(["token","apikey","accesstoken","key","authorization","secret","refreshtoken","clientsecret","idtoken","sessiontoken"]);O_=[/ya29\.[A-Za-z0-9_-]{8,}/g,/\b1\/\/[A-Za-z0-9_-]{8,}/g,/\bgh[opusr]_[A-Za-z0-9]{8,}/g,/\bgithub_pat_[A-Za-z0-9_]{16,}/g,/\bxox[bpae][-.][A-Za-z0-9-]{8,}/g,/\bsecret_[A-Za-z0-9]{16,}/g,/\bntn_[A-Za-z0-9]{16,}/g,/\bphx_[A-Za-z0-9_-]{32,}/g,/\bsk-[A-Za-z0-9_-]{16,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g]});function n6(){return{visit:[],download:[],"search-term":[],bookmark:[]}}function SU($){let Z=[...$].sort((X,z)=>X-z),Q=[];for(let X of Z){let z=Q[Q.length-1];if(z!==void 0&&X<=z[1]+1)z[1]=Math.max(z[1],X);else Q.push([X,X])}return Q}function RU($){let Z=new Set;for(let[Q,X]of $)for(let z=Q;z<=X;z++)Z.add(z);return Z}function OU($){if(!Array.isArray($))return[];let Z=[];for(let Q of $){if(!Array.isArray(Q)||Q.length!==2)continue;let[X,z]=Q;if(typeof X!=="number"||typeof z!=="number")continue;if(!Number.isSafeInteger(X)||!Number.isSafeInteger(z)||X<1||z<X)continue;Z.push([X,z])}return Z}function x_($){let Z={baseline:{},retired:{}};if($===null)return Z;let Q;try{Q=JSON.parse($)}catch{return Z}let X={baseline:{},retired:{}},z=Q.baseline??Q.profiles;if(z!==null&&typeof z==="object")for(let[Y,j]of Object.entries(z)){let W=n6();if(j!==null&&typeof j==="object")for(let V of xU){let q=j[V];if(Array.isArray(q))W[V]=q.filter((B)=>typeof B==="string")}X.baseline[Y]=W}if(Q.retired!==null&&typeof Q.retired==="object")for(let[Y,j]of Object.entries(Q.retired)){let W={};if(j!==null&&typeof j==="object")for(let V of i6){let q=j[V];if(q===null||typeof q!=="object")continue;let B=q.seq;if(typeof B!=="number"||!Number.isSafeInteger(B)||B<0)continue;W[V]={seq:B,ranges:OU(q.ranges),live:OU(q.live)}}X.retired[Y]=W}return X}function I_($,Z){return JSON.stringify({baseline:$,retired:Z})}function l6($){return $!==null&&typeof $==="object"&&$.__chromeDeleted===!0}function c6($,Z,Q,X){return{streamRef:$,raw:{__chromeDeleted:!0,id:Z,profile:Q,observedAtIso:X}}}function d6($,Z){let Q,X;if($===S0)Q=vj,X=!0;else if($===k0)Q=gj,X=!0;else if($===f0)Q=bj,X=!1;else Q=fj,X=!1;return{nk:{source:T5,stream:$,sourceId:Z.id,...X?{rev:Z.observedAtIso}:{}},ts:Z.observedAtIso,tier:"local-app",kind:Q,schemaVersion:1,mentions:[],body:`${Z.id} \u2014 deleted`,payload:{id:Z.id,profile:Z.profile,deleted:!0,observedAtIso:Z.observedAtIso}}}function y_($,Z){$.visit+=Z.visit,$.download+=Z.download,$["search-term"]+=Z["search-term"],$.bookmark+=Z.bookmark}function IU($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:p6,discover(X){let z=$.profiles();if(!K(z))return z;let Y={visit:0,download:0,"search-term":0,bookmark:0};for(let j of z.ok){let W=j.census();if(!K(W))return W;y_(Y,W.ok)}return H({asOf:Q(),streams:{[S0]:{total:Y.visit,method:"count-api"},[f0]:{total:Y.download,method:"count-api"},[k0]:{total:Y["search-term"],method:"count-api"},[r0]:{total:Y.bookmark,method:"census"}}})},pull(X,z){let Y=x_(z),j=$.profiles();if(!K(j))return j;let W=[],V={},q={},B=new Set,G=Q();for(let J of j.ok){let U=J.profile;B.add(U);let L=E_(J);if(!K(L))return L;W.push(...L.ok.items);let D=n6();for(let N of mj)D[N]=L.ok.ids[N];V[U]=D;let P=Y.baseline[U]??n6();for(let N of mj){let S=new Set(L.ok.ids[N]);for(let R of P[N])if(!S.has(R))W.push(c6(N,R,U,G))}let F=J.retired();if(!K(F))return F;let A={};for(let N of i6){let S=F.ok[N];if(S.highWater===null)continue;let R=Y.retired[U]?.[N],O=R!==void 0&&R.seq<=S.highWater?RU(R.ranges):new Set,T=new Set(L.ok.ids[N]),m=[];for(let d of S.ids){if(T.has(d))continue;let y=Number(d);if(!Number.isSafeInteger(y))continue;if(!O.has(y))W.push(c6(N,d,U,G));m.push(y)}let k=[];for(let d of L.ok.ids[N]){let y=Number(d);if(Number.isSafeInteger(y))k.push(y)}A[N]={seq:S.highWater,ranges:SU(m),live:SU(k)}}if(Object.keys(A).length>0)q[U]=A}for(let J of new Set([...Object.keys(Y.baseline),...Object.keys(Y.retired)])){if(B.has(J))continue;let U=Y.baseline[J]??n6();for(let D of mj)for(let P of U[D])W.push(c6(D,P,J,G));let L=Y.retired[J]??{};for(let D of i6){let P=L[D];if(P===void 0)continue;for(let F of RU(P.live))W.push(c6(D,String(F),J,G))}}return H({items:W,next:I_(V,q),exhausted:!0})},normalize(X){switch(X.streamRef){case S0:return l6(X.raw)?d6(S0,X.raw):v_(X.raw);case f0:return l6(X.raw)?d6(f0,X.raw):b_(X.raw);case k0:return l6(X.raw)?d6(k0,X.raw):g_(X.raw);case r0:return l6(X.raw)?d6(r0,X.raw):f_(X.raw);default:throw Error(`chrome-history normalize: undeclared streamRef '${X.streamRef}'`)}}}}function E_($){let Z=$.visits();if(!K(Z))return Z;let Q=$.downloads();if(!K(Q))return Q;let X=$.searchTerms();if(!K(X))return X;let z=$.bookmarks();if(!K(z))return z;let Y=[];for(let W of Z.ok)Y.push({streamRef:S0,raw:W});for(let W of Q.ok)Y.push({streamRef:f0,raw:W});for(let W of X.ok)Y.push({streamRef:k0,raw:W});for(let W of z.ok)Y.push({streamRef:r0,raw:W});let j={visit:Z.ok.map((W)=>W.id),download:Q.ok.map((W)=>W.id),"search-term":X.ok.map((W)=>W.urlId),bookmark:z.ok.map((W)=>W.guid)};return H({items:Y,ids:j})}function v_($){let Z=Q9($.url),Q=X9($.title);return{nk:{source:T5,stream:S0,sourceId:$.id,rev:$.visitTimeIso},ts:$.visitTimeIso,tier:"local-app",kind:"page.visited",schemaVersion:1,mentions:[],body:`${Q} \u2014 ${Z}`,payload:{url:Z,title:Q,visitTimeIso:$.visitTimeIso,profile:$.profile}}}function b_($){let Z=Q9($.url),Q=_U($.urlChain),X=X9($.targetPath),z=X9($.currentPath),Y=Q9($.referrer),j=Q9($.tabUrl),W=k_(X)||Z;return{nk:{source:T5,stream:f0,sourceId:$.id},ts:$.startTimeIso,tier:"local-app",kind:"file.downloaded",schemaVersion:1,mentions:[],body:`${W} \u2014 ${Z}`,payload:{url:Z,urlChain:Q,guid:$.guid,targetPath:X,currentPath:z,mimeType:$.mimeType,startTimeIso:$.startTimeIso,endTimeIso:$.endTimeIso,receivedBytes:$.receivedBytes,totalBytes:$.totalBytes,state:$.state,stateLabel:$.stateLabel,dangerType:$.dangerType,interruptReason:$.interruptReason,opened:$.opened,referrer:Y,tabUrl:j,profile:$.profile}}}function g_($){let Z=X9($.term),Q=Q9($.url),X=X9($.title);return{nk:{source:T5,stream:k0,sourceId:$.urlId,rev:$.lastVisitIso},ts:$.lastVisitIso,tier:"local-app",kind:"search.performed",schemaVersion:1,mentions:[],body:Z,payload:{term:Z,url:Q,title:X,urlId:$.urlId,lastVisitIso:$.lastVisitIso,profile:$.profile}}}function f_($){let Z=X9($.name),Q=Q9($.url),X=X9($.path),z=Q!==""?`${Z} \u2014 ${Q}`:Z;return{nk:{source:T5,stream:r0,sourceId:$.guid},ts:$.dateAddedIso,tier:"local-app",kind:"bookmark.saved",schemaVersion:1,mentions:[],body:z,payload:{name:Z,url:Q,nodeType:$.nodeType,guid:$.guid,id:$.id,parentGuid:$.parentGuid,path:X,dateAddedIso:$.dateAddedIso,dateModifiedIso:$.dateModifiedIso,profile:$.profile}}}function k_($){let Z=$.split(/[\\/]/);return Z[Z.length-1]??""}var xU,i6,mj;var yU=E(()=>{f();wj();TU();xU=[S0,f0,k0,r0],i6=[S0],mj=xU.filter(($)=>!i6.includes($))});function s6(){return{visit:{highWater:null,ids:[]},download:{highWater:null,ids:[]},"search-term":{highWater:null,ids:[]},bookmark:{highWater:null,ids:[]}}}class uj{profileName;tMs=w_;nextId={visit:1,download:1,"search-term":1,bookmark:1};phantoms={visit:0,download:0,"search-term":0,bookmark:0};visitRows=[];downloadRows=[];searchRows=[];bookmarkRows=[];visitIdSpace=new Set;visitIdSpaceProvable=!0;constructor($="Default"){this.profileName=$}setProfile($){this.profileName=$}get profile(){return this.profileName}tick(){return this.tMs+=1000,new Date(this.tMs).toISOString()}plant($={}){let Z=$.id??String(this.nextId.visit++);if(/^\d+$/.test(Z))this.visitIdSpace.add(Z);else this.visitIdSpaceProvable=!1;return this.visitRows.push({id:Z,url:$.url??`https://example.test/page-${Z}`,title:$.title??`Page ${Z}`,visitTimeIso:$.visitTimeIso??this.tick(),profile:this.profileName}),Z}plantDownload($={}){let Z=$.id??String(this.nextId.download++);return this.downloadRows.push({id:Z,guid:$.guid??`guid-${Z}`,url:$.url??`https://dl.test/file-${Z}.bin`,urlChain:$.urlChain??[$.url??`https://dl.test/file-${Z}.bin`],targetPath:$.targetPath??`/Users/me/Downloads/file-${Z}.bin`,currentPath:$.currentPath??`/Users/me/Downloads/file-${Z}.bin`,mimeType:$.mimeType??"application/octet-stream",startTimeIso:$.startTimeIso??this.tick(),endTimeIso:$.endTimeIso??"",receivedBytes:$.receivedBytes??1024,totalBytes:$.totalBytes??1024,state:$.state??1,stateLabel:$.stateLabel??"complete",dangerType:$.dangerType??0,interruptReason:$.interruptReason??0,opened:$.opened??0,referrer:$.referrer??"",tabUrl:$.tabUrl??"",profile:this.profileName}),Z}mutateDownload($,Z){let Q=this.downloadRows.find((X)=>X.id===$&&X.profile===this.profileName);if(Q!==void 0)Object.assign(Q,Z)}removeVisit($){let Z=this.visitRows.findIndex((Q)=>Q.id===$&&Q.profile===this.profileName);if(Z<0)throw Error(`fixture: unknown visit '${$}' in profile '${this.profileName}'`);this.visitRows.splice(Z,1)}plantSearchTerm($={}){let Z=$.urlId??String(this.nextId["search-term"]++);return this.searchRows.push({urlId:Z,term:$.term??`query ${Z}`,url:$.url??`https://www.google.com/search?q=query+${Z}`,title:$.title??`query ${Z} - Google Search`,lastVisitIso:$.lastVisitIso??this.tick(),profile:this.profileName}),Z}plantBookmark($={}){let Z=this.nextId.bookmark++,Q=$.guid??`bm-guid-${Z}`;return this.bookmarkRows.push({guid:Q,id:$.id??String(Z),name:$.name??`Bookmark ${Z}`,nodeType:$.nodeType??"url",url:$.url??($.nodeType==="folder"?"":`https://bm.test/${Z}`),parentGuid:$.parentGuid??"",path:$.path??"Bookmarks bar",dateAddedIso:$.dateAddedIso??this.tick(),dateModifiedIso:$.dateModifiedIso??"",profile:this.profileName}),Q}planPhantoms($,Z="visit"){this.phantoms[Z]=$}removeDownload($){let Z=this.downloadRows.findIndex((Q)=>Q.id===$&&Q.profile===this.profileName);if(Z<0)throw Error(`fixture: unknown download '${$}' in profile '${this.profileName}'`);this.downloadRows.splice(Z,1)}removeSearchTerm($){let Z=this.searchRows.findIndex((Q)=>Q.urlId===$&&Q.profile===this.profileName);if(Z<0)throw Error(`fixture: unknown search term '${$}' in profile '${this.profileName}'`);this.searchRows.splice(Z,1)}removeBookmark($){let Z=this.bookmarkRows.findIndex((Q)=>Q.guid===$&&Q.profile===this.profileName);if(Z<0)throw Error(`fixture: unknown bookmark '${$}' in profile '${this.profileName}'`);this.bookmarkRows.splice(Z,1)}withoutVisitIdSpace(){this.visitIdSpaceProvable=!1}retired(){let $=s6();if(!this.visitIdSpaceProvable)return H($);let Z=new Set(this.visitRows.filter((z)=>z.profile===this.profileName).map((z)=>z.id)),Q=[...this.visitIdSpace].filter((z)=>!Z.has(z)).sort((z,Y)=>Number(z)-Number(Y)),X=[...this.visitIdSpace].reduce((z,Y)=>Math.max(z,Number(Y)),0);return $.visit={highWater:X,ids:Q},H($)}census(){return H({visit:this.visitRows.length+this.phantoms.visit,download:this.downloadRows.length+this.phantoms.download,"search-term":this.searchRows.length+this.phantoms["search-term"],bookmark:this.bookmarkRows.length+this.phantoms.bookmark})}visits(){return H([...this.visitRows].map(($)=>({...$})).sort(($,Z)=>hj($.id,Z.id)))}downloads(){return H([...this.downloadRows].map(($)=>({...$,urlChain:[...$.urlChain]})).sort(($,Z)=>hj($.id,Z.id)))}searchTerms(){return H([...this.searchRows].map(($)=>({...$})).sort(($,Z)=>hj($.urlId,Z.urlId)))}bookmarks(){return H([...this.bookmarkRows].map(($)=>({...$})).sort(($,Z)=>$.guid<Z.guid?-1:$.guid>Z.guid?1:0))}profiles(){return H([this])}}function hj($,Z){if(/^\d+$/.test($)&&/^\d+$/.test(Z)){let Q=BigInt($)-BigInt(Z);return Q<0n?-1:Q>0n?1:0}return $<Z?-1:$>Z?1:0}class pj{profileSources;constructor($){this.profileSources=$}profiles(){return H([...this.profileSources])}removeProfile($){let Z=this.profileSources.findIndex((Q)=>Q.profile===$);if(Z<0)throw Error(`fixture: unknown profile '${$}'`);this.profileSources.splice(Z,1)}}var w_;var EU=E(()=>{f();w_=Date.parse("2026-07-01T00:00:00.000Z")});function m_($,Z){let Q=$/Z,X=$%Z;return X!==0n&&X<0n!==Z<0n?Q-1n:Q}function t0($){let Z=$-o6,Q=Number(m_(Z,1000n)),X=new Date(Q);if(Number.isNaN(X.getTime()))throw Error(`webkit-epoch: unrepresentable timestamp from ${$.toString()} \xB5s`);return X.toISOString()}function bU($){let Z=Date.parse($);if(Number.isNaN(Z))throw Error(`webkit-epoch: unparseable ISO '${$}'`);return BigInt(Z)*1000n+o6}var vU=11644473600,o6;var a6=E(()=>{o6=BigInt(11644473600)*1000000n});function gU($){if(typeof $!=="string"||!/^\d+$/.test($))return"";return t0(BigInt($))}function r6($){return $!==null&&$!==void 0&&typeof $==="object"&&!Array.isArray($)?$:null}function t6($,Z){let Q=r6($);if(Q===null)return v({code:"data_loss",layer:"upstream",retryability:"non-retryable",message:`chrome-history: Bookmarks for profile '${Z}' is not a JSON object \u2014 corrupt file (broken is loud, never an empty success \u2014 FM-21)`});let X=r6(Q.roots);if(X===null)return v({code:"data_loss",layer:"upstream",retryability:"non-retryable",message:`chrome-history: Bookmarks for profile '${Z}' has no 'roots' object \u2014 corrupt/unrecognized schema (FM-21)`});let z=[],Y=new Set,j=(W,V,q)=>{let B=r6(W);if(B===null)return;let G=typeof B.guid==="string"?B.guid:"",U=(typeof B.type==="string"?B.type:"")==="folder"?"folder":"url",L=typeof B.name==="string"?B.name:"";if(G!==""&&!Y.has(G))Y.add(G),z.push({guid:G,id:typeof B.id==="string"?B.id:String(B.id??""),name:L,nodeType:U,url:U==="url"&&typeof B.url==="string"?B.url:"",parentGuid:V,path:q,dateAddedIso:gU(B.date_added)||t0(0n),dateModifiedIso:gU(B.date_modified),profile:Z});let D=B.children;if(Array.isArray(D)){let P=q===""?L:`${q}/${L}`;for(let F of D)j(F,G,P)}};for(let W of Object.keys(X).sort())if(r6(X[W])!==null)j(X[W],"","");return H(z)}var lj=E(()=>{f();a6()});import{Database as fU}from"bun:sqlite";import{copyFileSync as kU,existsSync as cj,mkdtempSync as h_,readFileSync as u_,rmSync as p_}from"fs";import{tmpdir as l_}from"os";import{join as J4}from"path";function QZ($=process.env.HOME??""){return J4($,"Library","Application Support","Google","Chrome")}function c_($){switch($){case 0:return"in_progress";case 1:return"complete";case 2:return"cancelled";case 3:case 4:return"interrupted";default:return"unknown"}}function d_($){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,$)}class L0{opts;constructor($){this.opts=$}get profile(){return this.opts.profile}dbPath(){if(this.opts.historyDbPath!==void 0)return this.opts.historyDbPath;let $=this.opts.userDataDir??QZ();return J4($,this.opts.profile,"History")}bookmarksFilePath(){if(this.opts.bookmarksPath!==void 0)return this.opts.bookmarksPath;let $=this.opts.userDataDir??QZ();return J4($,this.opts.profile,"Bookmarks")}get cap(){return this.opts.cap??dj}profiles(){return H([this])}read($){let Z=this.dbPath();if(!cj(Z))return v({code:"not_found",layer:"upstream",retryability:"non-retryable",message:`chrome-history: no History db at '${Z}' \u2014 Chrome absent for profile '${this.opts.profile}', or Full-Disk-Access missing (empty is an assertion, never a default \u2014 FM-21)`});let Q=h_(J4(l_(),"chrome-history-"));try{let X="no attempt made";for(let z=0;z<wU;z++){if(z>0)d_(200);let Y=J4(Q,`History-${z}`);try{kU(Z,Y);for(let V of["-wal","-shm"]){let q=`${Z}${V}`;if(cj(q))kU(q,`${Y}${V}`)}let j=new fU(Y,{readwrite:!0});try{j.exec("PRAGMA wal_checkpoint(TRUNCATE)");let V=j.query("PRAGMA quick_check").get()?.quick_check;if(V!=="ok"){X=`staged copy failed quick_check ('${V??"no result"}') \u2014 torn WAL hot-copy`;continue}}finally{j.close()}let W=new fU(Y,{readonly:!0});try{return $(W)}finally{W.close()}}catch(j){X=j instanceof Error?j.message:String(j)}}return v({code:"data_loss",layer:"upstream",retryability:"transient",message:`chrome-history: could not obtain a consistent History snapshot for profile '${this.opts.profile}' after ${wU} attempts (last: ${X}) \u2014 a torn WAL hot-copy is refused, never a silent partial (FM-21)`})}finally{p_(Q,{recursive:!0,force:!0})}}static tableExists($,Z){return($.query("SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name=?").get(Z)?.n??0)>0}static autoincrementHighWater($,Z){let Q=$.query("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(Z)?.sql;if(typeof Q!=="string"||!/AUTOINCREMENT/i.test(Q))return null;if(!L0.tableExists($,"sqlite_sequence"))return null;let X=$.query("SELECT seq FROM sqlite_sequence WHERE name=?").get(Z)?.seq;return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0?X:null}static columns($,Z){let Q=$.query(`PRAGMA table_info(${Z})`).all();return new Set(Q.map((X)=>X.name))}census(){let $=this.read((Q)=>{let X=Q.query("SELECT COUNT(*) AS n FROM visits v JOIN urls u ON u.id = v.url").get()?.n??0,z=L0.tableExists(Q,"downloads")?Q.query("SELECT COUNT(*) AS n FROM downloads").get()?.n??0:0,Y=L0.tableExists(Q,"keyword_search_terms")?Q.query("SELECT COUNT(DISTINCT url_id) AS n FROM keyword_search_terms").get()?.n??0:0;return H({visit:X,download:z,search:Y})});if(!("ok"in $))return $;let Z=this.bookmarks();if(!("ok"in Z))return Z;return H({visit:$.ok.visit,download:$.ok.download,"search-term":$.ok.search,bookmark:Z.ok.length})}retired(){return this.read(($)=>{let Z=s6(),Q=L0.autoincrementHighWater($,"visits");if(Q===null)return H(Z);if(Q>this.cap)return v({code:"resource_exhausted",layer:"upstream",retryability:"non-retryable",message:`chrome-history: 'visits' identity high-water ${Q} exceeds the ${this.cap} cap for profile '${this.opts.profile}' \u2014 refused loud, never a truncated sweep`});let X=new Set($.query("SELECT v.id AS id FROM visits v JOIN urls u ON u.id = v.url").all().map((Y)=>Y.id)),z=[];for(let Y=1;Y<=Q;Y++)if(!X.has(Y))z.push(String(Y));return Z.visit={highWater:Q,ids:z},H(Z)})}visits(){return this.read(($)=>{let Z=$.query("SELECT COUNT(*) AS n FROM visits").get()?.n??0;if(Z>this.cap)return v({code:"resource_exhausted",layer:"upstream",retryability:"non-retryable",message:`chrome-history: ${Z} visits exceeds the ${this.cap} cap for profile '${this.opts.profile}' \u2014 refused loud (resource_exhausted), never a truncated silent success`});let Q=$.query("SELECT CAST(v.id AS TEXT) AS id, u.url AS url, u.title AS title, CAST(v.visit_time AS TEXT) AS visit_time FROM visits v JOIN urls u ON u.id = v.url ORDER BY v.id").all();return H(Q.map((X)=>({id:X.id,url:X.url,title:X.title??"",visitTimeIso:t0(BigInt(X.visit_time)),profile:this.opts.profile})))})}downloads(){return this.read(($)=>{if(!L0.tableExists($,"downloads"))return H([]);let Z=L0.columns($,"downloads");if(!Z.has("id")||!Z.has("start_time"))return v({code:"data_loss",layer:"upstream",retryability:"non-retryable",message:`chrome-history: 'downloads' table for profile '${this.opts.profile}' lacks id/start_time \u2014 unrecognized schema (broken is loud \u2014 FM-21)`});let Q=["id","guid","current_path","target_path","start_time","end_time","received_bytes","total_bytes","state","danger_type","interrupt_reason","opened","referrer","tab_url","mime_type"],X=new Set(["id","start_time","end_time"]),z=Q.filter((W)=>Z.has(W)).map((W)=>X.has(W)?`CAST(d.${W} AS TEXT) AS ${W}`:`d.${W} AS ${W}`).join(", "),Y=$.query(`SELECT ${z} FROM downloads d ORDER BY d.id`).all(),j=new Map;if(L0.tableExists($,"downloads_url_chains")){let W=$.query("SELECT CAST(id AS TEXT) AS id, chain_index AS chain_index, url AS url FROM downloads_url_chains ORDER BY id, chain_index").all();for(let V of W){let q=j.get(V.id)??[];q.push(V.url),j.set(V.id,q)}}return H(Y.map((W)=>{let V=j.get(W.id)??[],q=W.state??0;return{id:W.id,guid:W.guid??"",url:V.length>0?V[V.length-1]:"",urlChain:V,targetPath:W.target_path??"",currentPath:W.current_path??"",mimeType:W.mime_type??"",startTimeIso:t0(BigInt(W.start_time)),endTimeIso:W.end_time!==null&&W.end_time!==void 0&&W.end_time!=="0"?t0(BigInt(W.end_time)):"",receivedBytes:W.received_bytes??0,totalBytes:W.total_bytes??0,state:q,stateLabel:c_(q),dangerType:W.danger_type??0,interruptReason:W.interrupt_reason??0,opened:W.opened??0,referrer:W.referrer??"",tabUrl:W.tab_url??"",profile:this.opts.profile}}))})}searchTerms(){return this.read(($)=>{if(!L0.tableExists($,"keyword_search_terms"))return H([]);let Z=$.query("SELECT CAST(k.url_id AS TEXT) AS url_id, k.term AS term, u.url AS url, u.title AS title, CAST(u.last_visit_time AS TEXT) AS last_visit_time FROM keyword_search_terms k JOIN urls u ON u.id = k.url_id GROUP BY k.url_id ORDER BY k.url_id").all();return H(Z.map((Q)=>({urlId:Q.url_id,term:Q.term,url:Q.url,title:Q.title??"",lastVisitIso:t0(BigInt(Q.last_visit_time)),profile:this.opts.profile})))})}bookmarks(){let $=this.bookmarksFilePath();if(!cj($))return H([]);let Z;try{Z=u_($,"utf8")}catch(X){return v({code:"data_loss",layer:"upstream",retryability:"non-retryable",message:`chrome-history: reading Bookmarks for profile '${this.opts.profile}' failed: ${X instanceof Error?X.message:String(X)}`})}let Q;try{Q=JSON.parse(Z)}catch(X){return v({code:"data_loss",layer:"upstream",retryability:"non-retryable",message:`chrome-history: Bookmarks for profile '${this.opts.profile}' is not valid JSON: ${X instanceof Error?X.message:String(X)} (corrupt file is loud \u2014 FM-21)`})}return t6(Q,this.opts.profile)}}var dj=50000,wU=4;var nj=E(()=>{f();lj();a6()});import{existsSync as ij,readFileSync as n_,readdirSync as i_}from"fs";import{join as s_}from"path";function mU($){if($==="Default")return[0,0,$];let Z=/^Profile (\d+)$/.exec($);if(Z)return[1,Number(Z[1]),$];return[2,0,$]}function o_($){return[...$].sort((Z,Q)=>{let X=mU(Z),z=mU(Q);return X[0]-z[0]||X[1]-z[1]||(X[2]<z[2]?-1:X[2]>z[2]?1:0)})}class sj{opts;constructor($={}){this.opts=$}get userDataDir(){return this.opts.userDataDir??QZ()}fromLocalState($){let Z=s_($,"Local State");if(!ij(Z))return[];try{let Q=JSON.parse(n_(Z,"utf8")),X=Q!==null&&typeof Q==="object"?Q.profile?.info_cache??null:null;if(X!==null&&typeof X==="object"&&!Array.isArray(X))return Object.keys(X)}catch{}return[]}fromDirScan($){let Z;try{Z=i_($,{withFileTypes:!0})}catch{return[]}return Z.filter((Q)=>Q.isDirectory()&&(Q.name==="Default"||/^Profile \d+$/.test(Q.name))).map((Q)=>Q.name)}profiles(){let $=this.userDataDir;if(!ij($))return v({code:"not_found",layer:"upstream",retryability:"non-retryable",message:`chrome-history: no Chrome user-data dir at '${$}' \u2014 Chrome absent, or Full-Disk-Access missing (empty is an assertion \u2014 FM-21)`});let Z=o_([...new Set([...this.fromLocalState($),...this.fromDirScan($)])]),Q=[];for(let X of Z){let z=new L0({profile:X,userDataDir:$,...this.opts.cap!==void 0?{cap:this.opts.cap}:{}});if(ij(z.dbPath()))Q.push(z)}if(Q.length===0)return v({code:"not_found",layer:"upstream",retryability:"non-retryable",message:`chrome-history: Chrome user-data dir '${$}' holds no profile with a readable History db \u2014 Full-Disk-Access missing, or no profile initialized (never an empty success \u2014 FM-21)`});return H(Q)}}var hU=E(()=>{f();nj()});var uU;var pU=E(()=>{uU={research:{candidates:[{repo:"pesos/browser-history",recency:0.4,commits:0.5,comprehensiveness:0.7,maintenance:0.4},{repo:"community browser-history MCP servers (modelcontextprotocol ecosystem)",recency:0.6,commits:0.3,comprehensiveness:0.4,maintenance:0.3},{repo:"chrome.history extension + native-messaging bridge",recency:0.7,commits:0.5,comprehensiveness:0.5,maintenance:0.5}],chosen:"from-scratch",rationale:"Chrome's browsing data is a set of passive LOCAL files \u2014 the History SQLite db (page visits + downloads + keyword search terms) and a Bookmarks JSON tree, one of each PER PROFILE. Reading them directly with the runtime's own bun:sqlite + JSON.parse is strictly simpler and safer than wrapping an extension or MCP server: zero third-party code, zero vendored supply-chain surface (FM-25), no running-browser dependency, and it reaches EVERY class + EVERY profile (the founder's 'every data' bar), which a chrome.history extension cannot (it omits the microsecond visit_time, downloads metadata, and cross-profile scope). The knowledge needed is stable and documented \u2014 the Chromium visits/urls/downloads/keyword_search_terms schema, the Bookmarks codec, the profile roster in Local State, and the WebKit microseconds-since-1601 epoch. The one non-obvious mechanic (the live db is WAL-locked) is handled by the copy-then-open discipline every local-history reader uses.",refs:["Chromium visits table: components/history/core/browser/visit_database.cc (visits.id, visits.url\u2192urls.id, visits.visit_time)","Chromium urls table: components/history/core/browser/url_database.cc (urls.url, urls.title, urls.last_visit_time)","Chromium downloads + downloads_url_chains: components/history/core/browser/download_database.cc (downloads.id/guid/state/target_path, chain url by chain_index)","Chromium keyword_search_terms: components/history/core/browser/keyword_search_term_util.cc (keyword_id, url_id\u2192urls.id, term)","Chromium bookmarks on-disk JSON: components/bookmarks/browser/bookmark_codec.cc (roots{bookmark_bar,other,synced}, node guid/type/url/date_added)","Chromium profile roster: Local State 'profile.info_cache' keys (Default, Profile 1, \u2026); base/time/time.h WebKit epoch (Unix delta 11,644,473,600 s)","Chromium history expiration ~90 days: components/history/core/browser/expire_history_backend.cc"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"chromium-history-schema@m120",schemas:[],identityFacts:[{stream:"visit",fact:"visits.id is a per-profile autoincrement rowid; cross-profile uniqueness undocumented \u2192 container-scoped with profile epoch; immutable \u21D2 event-ts; ~90d pruning bounds backfill",citation:"event-log \xA78c (EI-F16) + chromium visit_database.cc"},{stream:"download",fact:"downloads.id is a per-profile rowid \u2192 container-scoped with profile epoch; a download MUTATES (in_progress\u2192complete) \u21D2 head-compare (no upstream version token)",citation:"connectors \xA72.2 container-scoped + head-compare; chromium download_database.cc"},{stream:"search-term",fact:"keyword_search_terms has no durable pk; url_id (the results page, per-profile) is the stable anchor \u2192 container-scoped; results-page last_visit_time re-stamps on re-search \u21D2 event-ts",citation:"connectors \xA72.2 container-scoped; chromium keyword_search_terms schema"},{stream:"bookmark",fact:"bookmark node guids are stable but permanent-folder guids are FIXED across profiles \u2192 container-scoped with profile epoch; name/url editable \u21D2 head-compare",citation:"connectors \xA72.2 container-scoped + head-compare; chromium bookmark_codec.cc"}]},identity:{perStream:[{stream:"visit",citation:"connectors \xA72.2 container-scoped default (per-profile rowid); event-ts (immutable)"},{stream:"download",citation:"connectors \xA72.2 container-scoped (per-profile rowid); head-compare (mutable download)"},{stream:"search-term",citation:"connectors \xA72.2 container-scoped (per-profile url_id); event-ts (re-search re-stamp)"},{stream:"bookmark",citation:"connectors \xA72.2 container-scoped (fixed permanent-folder guids); head-compare (editable)"}]},classification:{rows:[]}}});var lU={};h0(lU,{webkitMicrosToIso:()=>t0,refuseChromeHistoryAction:()=>FU,parseBookmarksTree:()=>t6,isoToWebkitMicros:()=>bU,defaultChromeUserDataDir:()=>QZ,createChromeHistoryConnector:()=>IU,WEBKIT_UNIX_EPOCH_DELTA_SECONDS:()=>vU,WEBKIT_UNIX_EPOCH_DELTA_MICROS:()=>o6,SqliteHistorySource:()=>L0,MAX_VISITS:()=>dj,FixtureHistorySource:()=>uj,FixtureChromeInstall:()=>pj,ChromeInstallSource:()=>sj,CHROME_HISTORY_VISIT_STREAM:()=>S0,CHROME_HISTORY_V0_READ_ONLY_GATE:()=>kj,CHROME_HISTORY_SOURCE:()=>T5,CHROME_HISTORY_SEARCH_TERM_STREAM:()=>k0,CHROME_HISTORY_MANIFEST:()=>p6,CHROME_HISTORY_DOWNLOAD_STREAM:()=>f0,CHROME_HISTORY_BOOKMARK_STREAM:()=>r0,CHROME_HISTORY_ARTIFACTS:()=>uU});var cU=E(()=>{wj();yU();EU();nj();hU();lj();a6();pU()});function dU($){return W$(`computer-files action '${$}'`,oj)}var G4="computer-files",e6,oj="connectors.md \xA72.3c classification review \u2014 computer-files v0 declares zero ActionContracts (read-only)";var aj=E(()=>{j$();e6={source:G4,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:[],multiAccount:!1,probe:{op:"stat-roots"}},tccPermissions:["full-disk"],streams:[{stream:"file",kinds:["localfile.observed"],deleteKind:"localfile.missing",identity:{quality:"synthetic",synthesizer:"path"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:60},retaliationRisk:"tolerant"}});import{createHash as a_}from"crypto";import{extname as r_}from"path";function $2($){return r_($).toLowerCase()}function Z8($,Z=$.length){let Q=Math.min(Z,rj);for(let X=0;X<Q;X++)if($[X]===0)return!0;return!1}function Z2($){return a_("sha256").update($).digest("hex")}function Q2($,Z,Q){return`[file ${$} \xB7 ${Z} bytes \xB7 ${Q==="binary"?"binary content":Q==="over-cap"?"over the content cap":"unreadable (permission denied)"} \u2014 content by reference]`}var XZ=500,zZ=1048576,YZ=8388608,rj=8192;var U4=()=>{};function e_($){return t_.has($.toLowerCase().replace(/[^a-z0-9]/g,""))}function iU($){if($==="")return $;let Z=$;for(let Q of $T)Q.lastIndex=0,Z=Z.replace(Q,"REDACTED-credential-shape");return Z}function ZT($){let Z=$.indexOf("="),Q=$.indexOf(":"),X=Z===-1?Q:Q===-1?Z:Math.min(Z,Q);if(X<=0)return $;let z=$.slice(0,X),Y=z.replace(/^\s*(export\s+)?/i,"").trim().replace(/^["'[]|["'\]]$/g,"");if(!e_(Y))return $;let j=$.slice(X+1);if(j.trim()==="")return $;let W=/(\r?\n)$/.exec(j)?.[1]??"";return`${z}${$[X]}REDACTED-credential-assignment${W}`}function sU($){if($===null||$==="")return $;nU.lastIndex=0;let Q=$.replace(nU,"REDACTED-credential-block").split(/(\r?\n)/);for(let X=0;X<Q.length;X+=2)Q[X]=ZT(Q[X]);return iU(Q.join(""))}function tj($){return iU($)}var t_,$T,nU;var oU=E(()=>{t_=new Set(["password","passwd","pwd","secret","token","apikey","apisecret","accesstoken","refreshtoken","idtoken","sessiontoken","authorization","auth","credentials","privatekey","clientsecret","clientid","awssecretaccesskey","awsaccesskeyid","awssessiontoken","githubtoken","ghtoken","npmtoken","authtoken","oauthtoken","dbpassword","databasepassword","databaseurl","connectionstring","encryptionkey","signingkey","secretkey","sharedsecret","passphrase"]);$T=[/ya29\.[A-Za-z0-9_-]{8,}/g,/\b1\/\/[A-Za-z0-9_-]{8,}/g,/\bgh[opusr]_[A-Za-z0-9]{8,}/g,/\bgithub_pat_[A-Za-z0-9_]{16,}/g,/\bxox[bpae][-.][A-Za-z0-9-]{8,}/g,/\bsecret_[A-Za-z0-9]{16,}/g,/\bntn_[A-Za-z0-9]{16,}/g,/\bphx_[A-Za-z0-9_-]{32,}/g,/\bsk-[A-Za-z0-9_-]{16,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g],nU=/-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----[\s\S]{0,200000}?-----END [A-Z0-9 ]{0,40}PRIVATE KEY-----/g});function aU($,Z=()=>new Date().toISOString(),Q={}){let X={manifest:e6,discover(Y){let j=$.census();if(!("ok"in j))return j;return H({asOf:Z(),streams:{file:{total:j.ok.files,method:"census"}}})},async discoverAsync(Y){let j=await $.censusAsync();if(!("ok"in j))return j;return H({asOf:Z(),streams:{file:{total:j.ok.files,method:"census"}}})},pull(Y,j){let W=$.list();if(!("ok"in W))return W;let V=W.ok.map((q)=>({streamRef:"file",raw:q}));return H({items:V,next:null,exhausted:!0})},async pullAsync(Y,j){let W=await $.listAsync();if(!("ok"in W))return W;let V=W.ok.map((q)=>({streamRef:"file",raw:q}));return H({items:V,next:null,exhausted:!0})},normalize(Y){let j=Y.raw,W=tj(j.path),V=sU(j.content),q=$2(W);return{nk:{source:G4,stream:"file"},ts:new Date(j.mtimeMs).toISOString(),tier:"local-app",kind:"localfile.observed",schemaVersion:1,mentions:[],body:V??Q2(W,j.size,j.contentOmitted??"unreadable"),payload:{path:W,size:j.size,ext:q,sha256:j.sha256,...j.contentOmitted!==void 0?{contentOmitted:j.contentOmitted}:{}}}},identityInput(Y){return tj(Y.raw.path)}},z=$.scan;if(z!==void 0){let Y=z.bind($);X.scan=async function*(j,W){for await(let V of Y(W,Q.scanBatchSize)){if(!K(V)){yield V;return}let{entries:q,next:B,exhausted:G}=V.ok,J=q.map((U)=>({streamRef:"file",raw:U}));yield H({items:J,next:B,exhausted:G})}}}return X}var rU=E(()=>{f();aj();U4();oU()});import{createHash as tU}from"crypto";import{closeSync as QT,openSync as XT,readdirSync as zT,readSync as YT,statSync as jT}from"fs";import{open as WT,opendir as VT,stat as KT}from"fs/promises";import{homedir as eU}from"os";import{join as B0}from"path";function ej(){return[eU()]}function QW($=eU()){return[B0($,"Library","Caches"),B0($,".zortex","git-cache"),B0($,".cache"),B0($,".rustup","toolchains"),B0($,".cargo","registry"),B0($,".bun","install","cache"),B0($,".npm","_cacache"),B0($,"go","pkg","mod"),B0($,".cargo","git"),B0($,"Library","Developer","Xcode","DerivedData"),B0($,".gradle","caches"),B0($,".m2","repository")]}class XW{roots;cap;maxContentBytes;maxHashBytes;skipDirNames;skipAbsDirs;scanBatchSize;constructor($={}){this.roots=$.roots??ej(),this.cap=$.cap??$W,this.maxContentBytes=$.maxContentBytes??zZ,this.maxHashBytes=$.maxHashBytes??YZ,this.skipDirNames=new Set(($.skipDirNames??ZW).map((Z)=>Z.toLowerCase())),this.skipAbsDirs=new Set($.skipAbsDirs??QW()),this.scanBatchSize=$.scanBatchSize??XZ}skipDir($,Z){return this.skipDirNames.has(Z.toLowerCase())||this.skipAbsDirs.has($)}collectPaths(){let $=[],Z=[...this.roots];while(Z.length>0){let Q=Z.pop(),X;try{X=zT(Q,{withFileTypes:!0})}catch{continue}for(let z of X){let Y=z.name,j=B0(Q,Y);if(z.isSymbolicLink())continue;if(z.isDirectory()){if(!this.skipDir(j,Y))Z.push(j);continue}if(!z.isFile())continue;if(Y.endsWith(".sock"))continue;let W;try{W=jT(j)}catch{continue}$.push({path:j,mtimeMs:W.mtimeMs,size:W.size})}}return $}async collectPathsAsync(){let $=[],Z=[...this.roots];while(Z.length>0){let Q=Z.pop();try{let X=await VT(Q);for await(let z of X){let Y=z.name,j=B0(Q,Y);if(z.isSymbolicLink())continue;if(z.isDirectory()){if(!this.skipDir(j,Y))Z.push(j);continue}if(!z.isFile()||Y.endsWith(".sock"))continue;try{let W=await KT(j);$.push({path:j,mtimeMs:W.mtimeMs,size:W.size})}catch(W){}}}catch(X){}}return $}overCap($){return v({code:"resource_exhausted",layer:"connector",retryability:"non-retryable",message:`computer-files walk found ${$} files under the declared roots, over the ${this.cap} cap \u2014 narrow the roots or raise the cap (never a silent truncation)`})}readContent($,Z){if(Z>this.maxHashBytes)return{sha256:"",content:null,contentOmitted:"over-cap"};let Q;try{Q=XT($,"r")}catch{return{sha256:"",content:null,contentOmitted:"unreadable"}}try{let X=tU("sha256"),z=Buffer.allocUnsafe(X2),Y=Z<=this.maxContentBytes,j=[],W=!1,V=!1;for(;;){let B;try{B=YT(Q,z,0,X2,null)}catch{return{sha256:"",content:null,contentOmitted:"unreadable"}}if(B<=0)break;if(X.update(z.subarray(0,B)),!V)W=Z8(z,B),V=!0;if(Y&&!W)j.push(Buffer.from(z.subarray(0,B)))}let q=X.digest("hex");if(Z>this.maxContentBytes)return{sha256:q,content:null,contentOmitted:"over-cap"};if(W)return{sha256:q,content:null,contentOmitted:"binary"};return{sha256:q,content:Buffer.concat(j).toString("utf8")}}finally{QT(Q)}}async readContentAsync($,Z){let Q=()=>({sha256:"",content:null,contentOmitted:"unreadable"});if(Z>this.maxHashBytes)return{sha256:"",content:null,contentOmitted:"over-cap"};let X;try{X=await WT($,"r")}catch(j){return Q()}let z,Y=!1;try{let j=tU("sha256"),W=Buffer.allocUnsafe(X2),V=Z<=this.maxContentBytes,q=[],B=!1,G=!1;for(;;){let{bytesRead:U}=await X.read(W,0,X2,null);if(U<=0)break;if(j.update(W.subarray(0,U)),!G)B=Z8(W,U),G=!0;if(V&&!B)q.push(Buffer.from(W.subarray(0,U)))}let J=j.digest("hex");z=Z>this.maxContentBytes?{sha256:J,content:null,contentOmitted:"over-cap"}:B?{sha256:J,content:null,contentOmitted:"binary"}:{sha256:J,content:Buffer.concat(q).toString("utf8")}}catch(j){Y=!0}try{await X.close()}catch(j){Y=!0}return Y||z===void 0?Q():z}census(){let $=this.collectPaths();if($.length>this.cap)return this.overCap($.length);return H({files:$.length})}list(){let $=this.collectPaths();if($.length>this.cap)return this.overCap($.length);let Z=$.map((Q)=>{let X=this.readContent(Q.path,Q.size),z={path:Q.path,mtimeMs:Q.mtimeMs,size:Q.size,sha256:X.sha256,content:X.content};if(X.contentOmitted!==void 0)z.contentOmitted=X.contentOmitted;return z});return Z.sort((Q,X)=>Q.path<X.path?-1:Q.path>X.path?1:0),H(Z)}async censusAsync(){let $=await this.collectPathsAsync();if($.length>this.cap)return this.overCap($.length);return H({files:$.length})}async listAsync(){let $=await this.collectPathsAsync();if($.length>this.cap)return this.overCap($.length);let Z=[];for(let Q of $){let X=await this.readContentAsync(Q.path,Q.size),z={path:Q.path,mtimeMs:Q.mtimeMs,size:Q.size,sha256:X.sha256,content:X.content};if(X.contentOmitted!==void 0)z.contentOmitted=X.contentOmitted;Z.push(z)}return Z.sort((Q,X)=>Q.path<X.path?-1:Q.path>X.path?1:0),H(Z)}async*scan($=null,Z){let Q=Z??this.scanBatchSize,X=await this.collectPathsAsync();if(X.length>this.cap){yield this.overCap(X.length);return}X.sort((Y,j)=>Y.path<j.path?-1:Y.path>j.path?1:0);let z=$===null?X:X.filter((Y)=>Y.path>$);if(z.length===0){yield H({entries:[],next:null,exhausted:!0});return}for(let Y=0;Y<z.length;Y+=Q){let j=z.slice(Y,Y+Q),W=[];for(let B of j){let G=await this.readContentAsync(B.path,B.size),J={path:B.path,mtimeMs:B.mtimeMs,size:B.size,sha256:G.sha256,content:G.content};if(G.contentOmitted!==void 0)J.contentOmitted=G.contentOmitted;W.push(J)}let V=Y+Q>=z.length,q=j[j.length-1].path;yield H({entries:W,next:V?null:q,exhausted:V})}}}var $W=1e6,ZW,X2=65536;var $L=E(()=>{f();U4();ZW=["node_modules",".git",".trash",".zortex"]});class zW{tMs=qT;files=new Map;tick(){return this.tMs+=1000,this.tMs}plant($,Z="",Q={}){if(this.files.has($))throw Error(`fixture: '${$}' already planted`);let X=Q.size??Buffer.byteLength(Z,"utf8");return this.files.set($,{path:$,mtimeMs:this.tick(),size:X,text:Z}),$}update($,Z,Q={}){let X=this.mustGet($);X.text=Z,X.size=Q.size??Buffer.byteLength(Z,"utf8"),X.mtimeMs=this.tick()}remove($){this.mustGet($),this.files.delete($)}mustGet($){let Z=this.files.get($);if(Z===void 0)throw Error(`fixture: unknown file '${$}'`);return Z}classify($){let Z=Buffer.from($.text,"utf8"),Q="",X=null,z;if($.size>YZ)z="over-cap";else if(Q=Z2(Z),$.size>zZ)z="over-cap";else if(Z8(Z))z="binary";else X=$.text;let Y={path:$.path,mtimeMs:$.mtimeMs,size:$.size,sha256:Q,content:X};if(z!==void 0)Y.contentOmitted=z;return Y}sortedFiles(){return[...this.files.values()].sort(($,Z)=>$.path<Z.path?-1:$.path>Z.path?1:0)}census(){return H({files:this.files.size})}list(){return H(this.sortedFiles().map(($)=>this.classify($)))}async censusAsync(){return H({files:this.files.size})}async listAsync(){return H(this.sortedFiles().map(($)=>this.classify($)))}async*scan($=null,Z=XZ){let Q=this.sortedFiles(),X=$===null?Q:Q.filter((z)=>z.path>$);if(X.length===0){yield H({entries:[],next:null,exhausted:!0});return}for(let z=0;z<X.length;z+=Z){let Y=X.slice(z,z+Z),j=Y.map((V)=>this.classify(V)),W=z+Z>=X.length;yield H({entries:j,next:W?null:Y[Y.length-1].path,exhausted:W})}}}var qT;var ZL=E(()=>{f();U4();qT=Date.parse("2026-07-01T00:00:00.000Z")});var QL;var XL=E(()=>{QL={research:{candidates:[{repo:"paulmillr/chokidar",recency:0.9,commits:0.8,comprehensiveness:0.5,maintenance:0.9},{repo:"modelcontextprotocol/servers (filesystem)",recency:0.9,commits:0.9,comprehensiveness:0.7,maintenance:0.8},{repo:"mrmlnc/fast-glob",recency:0.7,commits:0.6,comprehensiveness:0.5,maintenance:0.7}],chosen:"from-scratch",rationale:"A local filesystem census needs only the Node/Bun stdlib (node:fs readdir/stat/readFile + node:path/os). Every surveyed third party is either the wrong shape (chokidar watches deltas; fast-glob matches, neither enumerates a complete covered snapshot) or a net loss (the MCP filesystem server forces tier 'mcp-wrapped', a vendored server, and an SDK to pin against \xA78.5 churn) \u2014 all for a declared-roots walk that is a dozen stdlib calls. Wrapping any of them adds an FM-25 supply-chain surface and a vendoring gate for zero capability gain, so the honest choice is from-scratch over the stdlib.",refs:["node:fs \u2014 Node.js stdlib filesystem API (readdirSync/statSync/readFileSync): https://nodejs.org/api/fs.html","connectors \xA72.2 \u2014 synthetic identity via the framework 'path' synthesizer (I-1: connectors never hand-roll identity)","event-log \xA78c \u2014 APFS/HFS+ NFC filename-normalization pin (the 'path' synthesizer's canonicalization profile)","connectors \xA78.5 \u2014 MCP SDK/spec churn: vendored servers pin repo@commit; the surface a from-scratch stdlib walk avoids"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"node-fs@stdlib",schemas:[],identityFacts:[{stream:"file",fact:"path is the natural identity; content hash orders revisions (head-compare); no upstream revision token",citation:"connectors \xA72.2 synthetic/path row"}]},identity:{perStream:[{stream:"file",citation:"connectors \xA72.2 synthetic via 'path'; APFS NFC pin event-log \xA78c"}]},classification:{rows:[]}}});var zL={};h0(zL,{sha256Hex:()=>Z2,refuseComputerFilesAction:()=>dU,looksBinary:()=>Z8,extOf:()=>$2,defaultWalkRoots:()=>ej,defaultSkipAbsDirs:()=>QW,createComputerFilesConnector:()=>aU,byRefBody:()=>Q2,WalkFilesSource:()=>XW,WALK_FILE_CAP:()=>$W,SNIFF_BYTES:()=>rj,MAX_HASH_BYTES:()=>YZ,MAX_CONTENT_BYTES:()=>zZ,FixtureFilesSource:()=>zW,DEFAULT_SKIP_DIR_NAMES:()=>ZW,DEFAULT_SCAN_BATCH_SIZE:()=>XZ,COMPUTER_FILES_V0_READ_ONLY_GATE:()=>oj,COMPUTER_FILES_SOURCE:()=>G4,COMPUTER_FILES_MANIFEST:()=>e6,COMPUTER_FILES_ARTIFACTS:()=>QL});var YL=E(()=>{aj();rU();U4();$L();ZL();XL()});function jL($){return W$(`github action '${$}'`,YW)}var z9="github",Y9="repo",j9="issue",W9="file",V9="commit",z2,YW="connectors.md \xA72.3c classification review \u2014 github v0 declares zero ActionContracts (read-only ingestion); create-issue/comment are obvious but UNCLASSIFIED, so uncallable";var jW=E(()=>{j$();z2={source:z9,tier:"api",auth:{provider:"github",method:"device-flow",scopes:["repo","read:user"],multiAccount:!0,probe:{op:"user.get"}},streams:[{stream:Y9,kinds:["repo.changed"],identity:{quality:"durable",idField:"id"},revOrder:"upstream-version",revField:"updated_at"},{stream:j9,kinds:["issue.changed"],identity:{quality:"durable",idField:"id"},revOrder:"upstream-version",revField:"updated_at"},{stream:W9,kinds:["codefile.observed"],identity:{quality:"durable",idField:"path"},revOrder:"head-compare"},{stream:V9,kinds:["commit.recorded"],identity:{quality:"durable",idField:"sha"},revOrder:"upstream-version",revField:"sha"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:30},retaliationRisk:"tolerant"}});import{existsSync as WW,mkdirSync as WL,readFileSync as HT,statSync as BT}from"fs";import{join as L4}from"path";function VW($){let Z=new Date($);return Number.isNaN(Z.getTime())?"1970-01-01T00:00:00.000Z":Z.toISOString()}function LT($){let Z=Math.min($.length,8192);for(let Q=0;Q<Z;Q++)if($[Q]===0)return!0;return!1}class j2{cacheDir;exec;contentCap;constructor($,Z,Q){this.cacheDir=$,this.exec=Z,this.contentCap=Q}static create($){let Z=$.exec??qW,Q=Z(["git","--version"]);if(!Q.ok)return C("failed_precondition",`git is not available: ${Q.stderr.trim()||`exit ${Q.exitCode}`}`,"non-retryable");return WL($.cacheDir,{recursive:!0}),H(new j2($.cacheDir,Z,$.contentCap??KW))}repoDir($){return L4(this.cacheDir,$)}cloneUrl($){return`https://github.com/${$}.git`}ensure($){let Z=this.repoDir($);if(WW(L4(Z,".git"))){let X=this.exec(["git","fetch","--all","--prune","--quiet"],Z);if(!X.ok)return C("unavailable",`git fetch ${$} failed: ${X.stderr.trim()}`,"transient");return H(void 0)}WL(Z,{recursive:!0});let Q=this.exec(["git","clone","--quiet",this.cloneUrl($),Z]);if(!Q.ok){let X=Q.stderr.trim();if(/authentication|permission|denied|not found|could not read/i.test(X))return C("permission_denied",`git clone ${$} refused: ${X}`,"non-retryable");return C("unavailable",`git clone ${$} failed: ${X}`,"transient")}return H(void 0)}files($){let Z=this.repoDir($);if(!WW(L4(Z,".git")))return C("failed_precondition",`files(${$}) before ensure() \u2014 no local clone`,"non-retryable");let Q=this.exec(["git","ls-files","-s","-z"],Z);if(!Q.ok)return C("internal",`git ls-files ${$}: ${Q.stderr.trim()}`,"non-retryable");let X=Q.stdout.split(JT).filter((W)=>W.length>0);if(X.length>Y2)return C("resource_exhausted",`${$} has ${X.length} files, over the ${Y2} cap \u2014 refusing a partial tree (FM-18)`,"non-retryable");let z=this.exec(["git","log","-1","--format=%cI"],Z),Y=VW(z.ok&&z.stdout.trim()!==""?z.stdout.trim():"1970-01-01T00:00:00.000Z"),j=[];for(let W of X){let V=W.indexOf("\t");if(V<0)continue;let q=W.slice(0,V).split(/\s+/),B=q[0]??"",G=q[1]??"",J=W.slice(V+1);if(B==="160000"){j.push({repo:$,path:J,size:0,mode:B,blobSha:G,content:null,contentOmitted:"binary"});continue}let U=L4(Z,J),L=0;try{L=BT(U).size}catch{j.push({repo:$,path:J,size:0,mode:B,blobSha:G,content:null,contentOmitted:"binary"});continue}if(L>this.contentCap){j.push({repo:$,path:J,size:L,mode:B,blobSha:G,content:null,contentOmitted:"over-cap"});continue}let D;try{D=HT(U)}catch{j.push({repo:$,path:J,size:L,mode:B,blobSha:G,content:null,contentOmitted:"binary"});continue}if(LT(D)){j.push({repo:$,path:J,size:L,mode:B,blobSha:G,content:null,contentOmitted:"binary"});continue}j.push({repo:$,path:J,size:L,mode:B,blobSha:G,content:D.toString("utf8")})}return H(j.map((W)=>({...W,ts:Y})))}commits($){let Z=this.repoDir($);if(!WW(L4(Z,".git")))return C("failed_precondition",`commits(${$}) before ensure() \u2014 no local clone`,"non-retryable");let Q=["%H","%P","%an","%ae","%aI","%cn","%ce","%cI","%s","%b"].join("%x1f")+"%x1e",X=this.exec(["git","log","--all","--no-color",`--pretty=format:${Q}`],Z);if(!X.ok)return C("internal",`git log ${$}: ${X.stderr.trim()}`,"non-retryable");let z=[];for(let Y of X.stdout.split(GT)){let j=Y.replace(/^\s+/,"");if(j==="")continue;let W=j.split(UT);if(W.length<9||W[0]===void 0||W[0]==="")continue;z.push({repo:$,sha:W[0],parents:(W[1]??"").split(" ").filter((V)=>V.length>0),authorName:W[2]??"",authorEmail:W[3]??"",authorDate:VW(W[4]??""),committerName:W[5]??"",committerEmail:W[6]??"",committerDate:VW(W[7]??""),subject:W[8]??"",body:W[9]??""})}return H(z)}}class HW{repos;constructor(){this.repos=new Map}plant($,Z){this.repos.set($,{files:Z.files??[],commits:Z.commits??[],fail:Z.fail})}ensure($){let Z=this.repos.get($);if(Z?.fail!==void 0)return{err:Z.fail};return H(void 0)}files($){let Z=this.repos.get($);if(Z===void 0)return C("failed_precondition",`no planted repo '${$}'`,"non-retryable");if(Z.fail!==void 0)return{err:Z.fail};return H(Z.files)}commits($){let Z=this.repos.get($);if(Z===void 0)return C("failed_precondition",`no planted repo '${$}'`,"non-retryable");if(Z.fail!==void 0)return{err:Z.fail};return H(Z.commits)}}var KW=524288,Y2=200000,qW=($,Z)=>{let Q=Bun.spawnSync($,{cwd:Z,stdout:"pipe",stderr:"pipe"});return{ok:(Q.exitCode??1)===0,stdout:Q.stdout.toString(),stderr:Q.stderr.toString(),exitCode:Q.exitCode??1}},JT,GT,UT;var VL=E(()=>{f();j$();JT=String.fromCharCode(0),GT=String.fromCharCode(30),UT=String.fromCharCode(31)});function DT($){if($===null)return{p:"repos",url:null,seen:[]};try{return JSON.parse($)}catch{return{p:"repos",url:null,seen:[]}}}function MT($){if($==="Organization")return"org";if($==="User")return"person";return"unknown"}function BW($,Z){return{role:$,kind:MT(Z.type),raw:Z.login,handle:{ns:"github-login",value:Z.login}}}function KL($,Z,Q){if(Q===""&&Z==="")return null;return{role:$,kind:"person",raw:Z!==""?Z:Q,handle:{ns:"email",value:Q}}}function PT($){return $.description!==null&&$.description!==""?`${$.full_name} \u2014 ${$.description}`:$.full_name}function qL($,Z={}){let Q=Z.now??(()=>new Date().toISOString()),X=Z.cloneSource,z=(Y,j=[])=>{if(X!==void 0&&Y.length>0)return H({items:j,next:w0({p:"files",repos:Y,idx:0}),exhausted:!1});return H({items:j,next:null,exhausted:!0})};return{manifest:z2,discover(Y){let j=$.getUser();if(!K(j))return j;let W=$.censusCounts();if(!K(W))return W;let V={[Y9]:{total:W.ok.repos,method:"census"},[j9]:{total:W.ok.issues,method:"census",...W.ok.issueAttributed.length>0?{partialReasons:W.ok.issueAttributed}:{}}};if(X!==void 0)V[W9]={method:"pagination-exhaustion"},V[V9]={method:"pagination-exhaustion"};return H({asOf:Q(),streams:V})},pull(Y,j){let W=DT(j);if(W.p==="repos"){let J=$.listRepos(W.url);if(!K(J))return J;let U=J.ok.repos.map((D)=>({streamRef:Y9,raw:D})),L=[...W.seen,...J.ok.repos.map((D)=>D.full_name)];if(J.ok.next!==null)return H({items:U,next:w0({p:"repos",url:J.ok.next,seen:L}),exhausted:!1});if(L.length===0)return H({items:U,next:null,exhausted:!0});return H({items:U,next:w0({p:"issues",repos:L,queue:L,url:null}),exhausted:!1})}if(W.p==="issues"){let J=W.repos??W.queue,U=W.queue[0];if(U===void 0)return z(J);let L=$.listIssues(U,W.url);if(!K(L)){if("err"in L&&L.err.code==="permission_denied"){let F=W.queue.slice(1);if(F.length>0)return H({items:[],next:w0({p:"issues",repos:J,queue:F,url:null}),exhausted:!1});return z(J)}return L}let D=L.ok.issues.map((F)=>({streamRef:j9,raw:F}));if(L.ok.next!==null)return H({items:D,next:w0({p:"issues",repos:J,queue:W.queue,url:L.ok.next}),exhausted:!1});let P=W.queue.slice(1);if(P.length>0)return H({items:D,next:w0({p:"issues",repos:J,queue:P,url:null}),exhausted:!1});return z(J,D)}if(W.p==="files"){if(X===void 0)return H({items:[],next:null,exhausted:!0});let J=W.repos[W.idx];if(J===void 0){if(W.repos.length===0)return H({items:[],next:null,exhausted:!0});return H({items:[],next:w0({p:"commits",repos:W.repos,idx:0}),exhausted:!1})}let U=X.ensure(J);if(!K(U)){if("err"in U&&U.err.code==="permission_denied")return H({items:[],next:w0({p:"files",repos:W.repos,idx:W.idx+1}),exhausted:!1});return U}let L=X.files(J);if(!K(L))return L;let D=L.ok.map((P)=>({streamRef:W9,raw:P}));return H({items:D,next:w0({p:"files",repos:W.repos,idx:W.idx+1}),exhausted:!1})}if(X===void 0)return H({items:[],next:null,exhausted:!0});let V=W.repos[W.idx];if(V===void 0)return H({items:[],next:null,exhausted:!0});let q=X.commits(V);if(!K(q)){if("err"in q&&(q.err.code==="permission_denied"||q.err.code==="failed_precondition")){let J=W.idx+1;return H({items:[],next:J<W.repos.length?w0({p:"commits",repos:W.repos,idx:J}):null,exhausted:J>=W.repos.length})}return q}let B=q.ok.map((J)=>({streamRef:V9,raw:J})),G=W.idx+1;return H({items:B,next:G<W.repos.length?w0({p:"commits",repos:W.repos,idx:G}):null,exhausted:G>=W.repos.length})},normalize(Y){if(Y.streamRef===Y9){let j=Y.raw;return{nk:{source:z9,stream:Y9,sourceId:String(j.id),rev:j.updated_at},ts:j.updated_at,tier:"api",kind:"repo.changed",schemaVersion:1,mentions:[BW("actor",j.owner)],body:PT(j),payload:Y.raw}}if(Y.streamRef===j9){let j=Y.raw,W=[];if(j.user!==null)W.push(BW("actor",j.user));for(let V of j.assignees)W.push(BW("participant",V));return{nk:{source:z9,stream:j9,sourceId:String(j.id),rev:j.updated_at},ts:j.updated_at,tier:"api",kind:"issue.changed",schemaVersion:1,mentions:W,body:`#${j.number}: ${j.title}`,payload:Y.raw}}if(Y.streamRef===W9){let j=Y.raw;return{nk:{source:z9,stream:W9,sourceId:`${j.repo}:${j.path}`},ts:j.ts,tier:"api",kind:"codefile.observed",schemaVersion:1,mentions:[],body:j.content!==null?`${j.repo}/${j.path}`:`${j.repo}/${j.path} (content ${j.contentOmitted??"omitted"})`,payload:Y.raw}}if(Y.streamRef===V9){let j=Y.raw,W=[],V=KL("actor",j.authorName,j.authorEmail);if(V!==null)W.push(V);if(j.committerEmail!==j.authorEmail||j.committerName!==j.authorName){let q=KL("participant",j.committerName,j.committerEmail);if(q!==null)W.push(q)}return{nk:{source:z9,stream:V9,sourceId:j.sha,rev:j.sha},ts:j.committerDate,tier:"api",kind:"commit.recorded",schemaVersion:1,mentions:W,body:`${j.sha.slice(0,7)} ${j.subject}`,payload:Y.raw}}throw Error(`github normalize: undeclared streamRef '${Y.streamRef}'`)}}}var w0=($)=>JSON.stringify($);var HL=E(()=>{f();jW()});function K2($){if($===void 0||$==="")return null;for(let Z of $.split(",")){let Q=Z.match(/<([^>]+)>\s*;\s*rel="([^"]+)"/);if(Q!==null&&Q[2]==="next"&&Q[1]!==void 0)return Q[1]}return null}function W2($,Z){let Q=Z.toLowerCase();for(let[X,z]of Object.entries($))if(X.toLowerCase()===Q)return z;return}function DW($){let Z=$;return Z!==null&&typeof Z==="object"&&typeof Z.login==="string"&&typeof Z.id==="number"&&typeof Z.node_id==="string"&&typeof Z.type==="string"}function CT($){let Z=$;if(!DW(Z))return null;if(Z.name!==null&&typeof Z.name!=="string")return null;return Z}function FT($){let Z=$;if(Z===null||typeof Z!=="object")return null;if(typeof Z.id!=="number"||typeof Z.node_id!=="string"||typeof Z.name!=="string"||typeof Z.full_name!=="string"||typeof Z.private!=="boolean"||!DW(Z.owner)||typeof Z.updated_at!=="string"||typeof Z.open_issues_count!=="number"||typeof Z.has_issues!=="boolean")return null;return Z}function NT($){let Z=$;if(Z===null||typeof Z!=="object")return null;if(typeof Z.id!=="number"||typeof Z.node_id!=="string"||typeof Z.number!=="number"||typeof Z.title!=="string"||typeof Z.state!=="string"||typeof Z.updated_at!=="string"||!Array.isArray(Z.assignees))return null;if(Z.user!==null&&!DW(Z.user))return null;return Z}class q2{transport;authHeaders;cap;constructor($,Z,Q){this.transport=$,this.authHeaders=Z,this.cap=Q}static create($={}){if($.transport===void 0||$.transport===LW||$.authHeaders===void 0)return W$("github live wire (transport + grant-scoped auth headers)",WZ);return H(new q2($.transport,$.authHeaders,$.cap??UW))}requestHeaders(){return{Accept:JW,"X-GitHub-Api-Version":GW,...this.authHeaders()}}request($){let Z=this.transport($,this.requestHeaders());if(!Z.ok){if(Z.structuredError!==void 0)return{err:Z.structuredError};if(Z.error===WZ)return W$("github live wire",WZ);return C("unavailable",`github request to ${$} failed at the transport: ${Z.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return H({status:Z.status,body:Z.body,headers:Z.headers})}httpError($,Z,Q){if($===401)return C("unauthenticated",`github ${Q}: HTTP 401 \u2014 the grant is unauthenticated (expired/revoked token)`,"non-retryable");if($===403){let X=W2(Z,"x-ratelimit-remaining"),z=W2(Z,"retry-after");if(X==="0"||z!==void 0)return C("resource_exhausted",`github ${Q}: HTTP 403 rate-limited (X-RateLimit-Remaining: ${X??"?"}${z!==void 0?`, Retry-After: ${z}`:""}) \u2014 throttling`,"throttling");return C("permission_denied",`github ${Q}: HTTP 403 \u2014 the grant lacks permission for this resource`,"non-retryable")}if($===404)return C("permission_denied",`github ${Q}: HTTP 404 \u2014 not found or not accessible (GitHub 404-hides private resources)`,"non-retryable");if($>=500)return C("unavailable",`github ${Q}: HTTP ${$} \u2014 upstream server error`,"transient");return C("internal",`github ${Q}: unexpected HTTP ${$} \u2014 REST-surface drift (FM-19)`,"non-retryable")}parseArray($,Z){let Q;try{Q=JSON.parse($)}catch{return C("internal",`github ${Z}: response is not JSON \u2014 REST-surface drift (FM-19)`,"non-retryable")}if(!Array.isArray(Q))return C("internal",`github ${Z}: response is not a JSON array \u2014 REST-surface drift (FM-19)`,"non-retryable");return H(Q)}getUser(){let $=this.request(`${D4}/user`);if(!K($))return $;if($.ok.status!==200)return this.httpError($.ok.status,$.ok.headers,"GET /user");let Z;try{Z=JSON.parse($.ok.body)}catch{return C("internal","github GET /user: response is not JSON \u2014 REST-surface drift (FM-19)","non-retryable")}let Q=CT(Z);if(Q===null)return C("internal","github GET /user: unexpected user shape \u2014 REST-surface drift (FM-19)","non-retryable");return H(Q)}listRepos($){let Z=$??`${D4}/user/repos?per_page=${V2}`,Q=this.request(Z);if(!K(Q))return Q;if(Q.ok.status!==200)return this.httpError(Q.ok.status,Q.ok.headers,"GET /user/repos");let X=this.parseArray(Q.ok.body,"GET /user/repos");if(!K(X))return X;let z=[];for(let Y of X.ok){let j=FT(Y);if(j===null)return C("internal","github GET /user/repos: a repo row has an unexpected shape \u2014 REST-surface drift (FM-19)","non-retryable");z.push(j)}return H({repos:z,next:K2(W2(Q.ok.headers,"link"))})}listIssues($,Z){let Q=Z??`${D4}/repos/${$}/issues?state=all&per_page=${V2}`,X=this.request(Q);if(!K(X))return X;if(X.ok.status!==200)return this.httpError(X.ok.status,X.ok.headers,`GET /repos/${$}/issues`);let z=this.parseArray(X.ok.body,`GET /repos/${$}/issues`);if(!K(z))return z;let Y=[];for(let j of z.ok){let W=NT(j);if(W===null)return C("internal",`github GET /repos/${$}/issues: an issue row has an unexpected shape \u2014 REST-surface drift (FM-19)`,"non-retryable");Y.push(W)}return H({issues:Y,next:K2(W2(X.ok.headers,"link"))})}censusCounts(){let $=[],Z=null,Q=0;do{let Y=this.listRepos(Z);if(!K(Y))return Y;if($.push(...Y.ok.repos),$.length>this.cap)return C("resource_exhausted",`github census exceeded the ${this.cap}-repo cap \u2014 refusing a partial census (loud, FM-18)`,"non-retryable");if(++Q>jZ)return C("resource_exhausted",`github repo pagination exceeded ${jZ} pages \u2014 Link-cycle drift (FM-19)`,"non-retryable");Z=Y.ok.next}while(Z!==null);let X=0,z=[];for(let Y of $){let j=null,W=0;for(;;){let V=this.listIssues(Y.full_name,j);if(!K(V)){if(V.err.code==="permission_denied"){z.push({reason:`repo-issues-permission-scoped: ${Y.full_name}`,count:Y.open_issues_count}),X+=Y.open_issues_count;break}return V}if(X+=V.ok.issues.length,X>this.cap)return C("resource_exhausted",`github census exceeded the ${this.cap}-issue cap \u2014 refusing a partial census (loud, FM-18)`,"non-retryable");if(++W>jZ)return C("resource_exhausted",`github issue pagination for ${Y.full_name} exceeded ${jZ} pages \u2014 Link-cycle drift (FM-19)`,"non-retryable");if(j=V.ok.next,j===null)break}}return H({repos:$.length,issues:X,issueAttributed:z})}}var D4="https://api.github.com",JW="application/vnd.github+json",GW="2022-11-28",V2=100,UW=50000,jZ=5000,WZ="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider auth walks at C-P6-2 (G2)",LW=()=>({ok:!1,error:WZ});var BL=E(()=>{f();j$()});function JL($){if($===null)return 0;let Z=Number.parseInt($.replace(/^off:/,""),10);return Number.isNaN(Z)?0:Z}class MW{user={login:"octocat",id:1,node_id:"MDQ6VXNlcjE=",type:"User",name:"The Octocat"};repos=[];issuesByRepo=new Map;denied=new Map;pageSize=2;tMs=AT;nextRepoId=1000;nextIssueId=5000;tokenExpired=!1;armedPageError=null;setUser($){this.user=$}tick(){return this.tMs+=1000,new Date(this.tMs).toISOString().replace(/\.\d{3}Z$/,"Z")}plantRepo($={}){let Z=$.owner??this.user,Q=$.id??this.nextRepoId++,X=$.name??`repo-${Q}`,z=$.updated_at??this.tick(),Y={id:Q,node_id:`R_${Q}`,name:X,full_name:`${Z.login}/${X}`,private:!1,owner:{login:Z.login,id:Z.id,node_id:Z.node_id,type:Z.type},html_url:`https://github.com/${Z.login}/${X}`,description:$.description??null,fork:!1,created_at:z,updated_at:z,pushed_at:z,language:null,archived:!1,open_issues_count:$.open_issues_count??0,has_issues:!0};if(this.repos.push(Y),!this.issuesByRepo.has(Y.full_name))this.issuesByRepo.set(Y.full_name,[]);return Y}plantIssue($,Z={}){let Q=this.issuesByRepo.get($);if(Q===void 0)throw Error(`fixture: unknown repo '${$}' \u2014 plantRepo first`);let X=Z.id??this.nextIssueId++,z=Z.number??Q.length+1,Y=Z.updated_at??this.tick(),j=Z.pullRequest===!0?{url:`https://api.github.com/repos/${$}/pulls/${z}`,html_url:`https://github.com/${$}/pull/${z}`,diff_url:`https://github.com/${$}/pull/${z}.diff`,patch_url:`https://github.com/${$}/pull/${z}.patch`}:void 0,W={id:X,node_id:`I_${X}`,number:z,title:Z.title??`Issue ${z}`,state:Z.state??"open",user:Z.user===void 0?this.user:Z.user,assignees:Z.assignees??[],labels:Z.labels??[],created_at:Y,updated_at:Y,closed_at:(Z.state??"open")==="closed"?Y:null,body:Z.body===void 0?null:Z.body,html_url:`https://github.com/${$}/issues/${z}`,repository_url:`https://api.github.com/repos/${$}`,...j!==void 0?{pull_request:j}:{}};return Q.push(W),W}buildIssue($,Z={}){let Q=this.issuesByRepo.get($);if(Q===void 0)throw Error(`fixture: unknown repo '${$}' \u2014 plantRepo first`);let X=[...Q],z=this.plantIssue($,Z);return this.issuesByRepo.set($,X),z}denyIssues($,Z){if(!this.issuesByRepo.has($))throw Error(`fixture: unknown repo '${$}'`);this.denied.set($,Z);let Q=this.repos.find((X)=>X.full_name===$);if(Q!==void 0)Q.open_issues_count=Z}mutateIssueId($,Z){for(let Q of this.issuesByRepo.values())for(let X of Q)if(X.id===$)X.id=Z,X.node_id=`I_${Z}`}editIssue($,Z,Q){let X=this.issuesByRepo.get($);if(X===void 0)throw Error(`fixture: unknown repo '${$}'`);let z=X.find((Y)=>Y.id===Z);if(z===void 0)throw Error(`fixture: unknown issue id ${Z} in '${$}'`);if(Q.title!==void 0)z.title=Q.title;if(Q.state!==void 0)z.state=Q.state;if(Q.body!==void 0)z.body=Q.body;z.updated_at=Q.updated_at??this.tick()}setTokenExpired($=!0){this.tokenExpired=$}armPageError($){this.armedPageError=$}setPageSize($){this.pageSize=Math.max(1,$)}unauthenticated(){return C("unauthenticated","fixture: the grant is unauthenticated (expired-token drill) \u2014 NEVER an empty success (FM-21)","non-retryable")}consumeArmed(){if(this.armedPageError===null)return null;let $=this.armedPageError;return this.armedPageError=null,{err:$}}getUser(){if(this.tokenExpired)return this.unauthenticated();return H({...this.user})}censusCounts(){if(this.tokenExpired)return this.unauthenticated();let $=0,Z=[];for(let Q of this.repos){let X=this.denied.get(Q.full_name);if(X!==void 0){Z.push({reason:`repo-issues-permission-scoped: ${Q.full_name}`,count:X}),$+=X;continue}$+=(this.issuesByRepo.get(Q.full_name)??[]).length}return H({repos:this.repos.length,issues:$,issueAttributed:Z})}listRepos($){if(this.tokenExpired)return this.unauthenticated();let Z=this.consumeArmed();if(Z!==null)return Z;let Q=JL($),X=this.repos.slice(Q,Q+this.pageSize).map((Y)=>({...Y,owner:{...Y.owner}})),z=Q+this.pageSize;return H({repos:X,next:z<this.repos.length?`off:${z}`:null})}listIssues($,Z){if(this.tokenExpired)return this.unauthenticated();let Q=this.consumeArmed();if(Q!==null)return Q;if(this.denied.has($))return C("permission_denied",`fixture: issues for '${$}' are permission-scoped (403) \u2014 item-level attributed skip`,"non-retryable");let X=this.issuesByRepo.get($)??[],z=JL(Z),Y=X.slice(z,z+this.pageSize).map((W)=>({...W})),j=z+this.pageSize;return H({issues:Y,next:j<X.length?`off:${j}`:null})}}var AT;var GL=E(()=>{f();j$();AT=Date.parse("2026-07-01T00:00:00.000Z")});var UL;var LL=E(()=>{UL={research:{candidates:[{repo:"octokit/rest.js (@octokit/rest)",recency:0.95,commits:0.95,comprehensiveness:0.95,maintenance:0.95},{repo:"github/github-mcp-server",recency:0.9,commits:0.9,comprehensiveness:0.85,maintenance:0.9},{repo:"cli/cli (gh)",recency:0.9,commits:0.9,comprehensiveness:0.8,maintenance:0.9}],chosen:"from-scratch",rationale:"v0 needs exactly THREE documented REST GET routes \u2014 GET /user, GET /user/repos (Link-paginated), GET /repos/{owner}/{repo}/issues?state=all \u2014 over an INJECTED transport so the G1 outbound chokepoint stays the only wire. A from-scratch thin client over that seam is strictly simpler and lower-blast-radius than every survey candidate: @octokit/rest and the gh CLI both bring their OWN transport (defeating the gate) and cannot be leaf dependencies (\xA72.3, which permits only @indra/contracts + the framework); github/github-mcp-server adds a vendored binary, an MCP transport, and a quarterly-churn SDK pin (\xA78.5) for zero capability gain. Wrapping any of them is an FM-25 supply-chain surface for what is ~200 lines of typed REST parsing (wrapsThirdParty:false). DELIBERATELY UNCOVERED in v0 (named as honest gaps, future streams, not silent omissions): pull requests as a FIRST-CLASS stream with review/merge state (they ride the 'issue' stream via the raw pull_request marker for now); commits; stars/watchers; notifications; releases; the write/action surface (create-issue/comment \u2014 gated behind \xA72.3c + G3).",refs:["GitHub REST API, api-version 2022-11-28 (pinned): https://docs.github.com/en/rest?apiVersion=2022-11-28","GET /user/repos + Link-header pagination: https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user + https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api","GET /repos/{owner}/{repo}/issues \u2014 'every pull request is an issue' (the pull_request marker): https://docs.github.com/en/rest/issues/issues#list-repository-issues","Global id uniqueness (durable identity, \xA72.2 exemption): https://docs.github.com/en/rest/using-the-rest-api/getting-started-with-the-rest-api + GraphQL global node IDs https://docs.github.com/en/graphql/reference/interfaces#node","OAuth 2.0 Device Authorization Grant (auth.method device-flow): https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow (RFC 8628)"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"github-rest@2022-11-28",schemas:[{name:"github/rest-api-description (OpenAPI 3, api.github.com)",kind:"openapi"}],identityFacts:[{stream:"repo",fact:"the numeric database `id` is globally unique per resource type across github.com (durable); `updated_at` (RFC3339, second granularity) is the upstream version token; deletion leaves no observable tombstone on the list path (no deleteKind)",citation:"REST getting-started (resources/ids) + GraphQL global node IDs; \xA72.2 durable-id exemption to the \xA78.5 multi-account default"},{stream:"issue",fact:"durable numeric `id` (unique across all issues+PRs on github.com); `updated_at` orders revisions; PRs are issues, marked verbatim by the `pull_request` field; closed is a revision, not a deletion; second-granularity updated_at ties tolerated by I-1 (loud #c<n> on same-second content divergence)",citation:"REST 'List repository issues' ('every pull request is an issue') + I-1 rev authorship / \xA72.2 rule 7"},{stream:"file",fact:"a code file's durable identity is (repo, path); its content is addressed by the git blob sha, so head-compare (appender contentHash) records a changed file as a new revision and re-observes an unchanged file as a no-op (content-addressed idempotency); a removed path leaves no read-path tombstone (coverage shrink, no deleteKind)",citation:"git object model (ls-files -s blob shas) + connectors \xA72.2 head-compare / I-1 rev authorship (appender-assigned contentHash)"},{stream:"commit",fact:"a commit is immutable and its sha is a content-addressed durable id (globally unique); exactly one revision ever, so rev = the sha itself (a re-sync yields the same (sourceId, rev) \u2192 duplicate \u2192 zero appended)",citation:"git object model (git log --all, commit sha) + connectors \xA72.2 durable / I-1 (single-revision immutable object)"}]},identity:{perStream:[{stream:"repo",citation:"connectors \xA72.2 durable (idField 'id'); global-uniqueness exemption to the multi-account container-scoped default"},{stream:"issue",citation:"connectors \xA72.2 durable (idField 'id'); revOrder upstream-version via updated_at (I-1 rev authorship)"},{stream:"file",citation:"connectors \xA72.2 durable (idField 'path', sourceId = repo:path); revOrder head-compare \u2014 appender contentHash is the rev (content-addressed, idempotent)"},{stream:"commit",citation:"connectors \xA72.2 durable (idField 'sha'); revOrder upstream-version revField 'sha' \u2014 an immutable commit has exactly one revision"}]},classification:{rows:[]}}});var DL={};h0(DL,{refuseGithubAction:()=>jL,parseLinkNext:()=>K2,githubGatedTransport:()=>LW,createGithubConnector:()=>qL,bunGitExec:()=>qW,HttpGithubSource:()=>q2,GitCliCloneSource:()=>j2,GITHUB_WIRE_GATE:()=>WZ,GITHUB_V0_READ_ONLY_GATE:()=>YW,GITHUB_SOURCE:()=>z9,GITHUB_REPO_STREAM:()=>Y9,GITHUB_PULL_CAP:()=>UW,GITHUB_PER_PAGE:()=>V2,GITHUB_MAX_PAGES:()=>jZ,GITHUB_MANIFEST:()=>z2,GITHUB_ISSUE_STREAM:()=>j9,GITHUB_FILE_STREAM:()=>W9,GITHUB_FILE_CONTENT_CAP:()=>KW,GITHUB_FILES_PER_REPO_CAP:()=>Y2,GITHUB_COMMIT_STREAM:()=>V9,GITHUB_ARTIFACTS:()=>UL,GITHUB_API_VERSION:()=>GW,GITHUB_API_BASE:()=>D4,GITHUB_ACCEPT:()=>JW,FixtureGithubSource:()=>MW,FixtureCloneSource:()=>HW});var ML=E(()=>{jW();VL();HL();BL();GL();LL()});function PL($){return W$(`imessage action '${$}'`,PW)}var S5="imessage",R5="message",O5="chat",x5="handle",I5="attachment",M4="message.deleted",P4="im.chat.deleted",C4="im.handle.deleted",F4="im.attachment.deleted",H2,PW="connectors.md \xA72.3c classification review \u2014 imessage v0 declares zero ActionContracts (read-only local chat.db ingestion)";var CW=E(()=>{j$();H2={source:S5,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:[],multiAccount:!1,probe:{op:"stat-messages-chatdb"}},tccPermissions:["full-disk"],streams:[{stream:R5,kinds:["message.received","message.sent"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"event-ts",deleteKind:M4},{stream:O5,kinds:["im.chat"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:P4},{stream:x5,kinds:["im.handle"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:C4},{stream:I5,kinds:["im.attachment"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:F4}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"}});function e0(){return{message:[],chat:[],handle:[],attachment:[]}}function ST($,Z){let Q=e0();if($===null)return{tombstoned:Q};try{let X=JSON.parse($);if(X.store!==Z)return{tombstoned:Q};let z=X.tombstoned;if(z!==null&&typeof z==="object")for(let Y of FW){let j=z[Y];if(Array.isArray(j))Q[Y]=j.filter((W)=>typeof W==="string")}return{tombstoned:Q}}catch{return{tombstoned:e0()}}}function RT($,Z){return JSON.stringify({store:$,tombstoned:Z})}function OT($){return $!==null&&typeof $==="object"&&$.__imessageRetired===!0}function xT($,Z,Q,X){return{streamRef:$,raw:{__imessageRetired:!0,store:Z,rowid:Q,observedAtIso:X}}}function IT($,Z){return{nk:{source:S5,stream:$,sourceId:Z.rowid,...TT[$]?{rev:Z.observedAtIso}:{}},ts:Z.observedAtIso,tier:"local-app",kind:_T[$],schemaVersion:1,mentions:[],body:`${$} ${Z.rowid} \u2014 deleted from the Messages store`,payload:{store:Z.store,rowid:Z.rowid,deleted:!0,observedAtIso:Z.observedAtIso}}}function B2($,Z,Q){return Z!==""?[{role:Q,raw:Z,handle:{ns:$,value:Z}}]:[]}function yT($,Z){$.message+=Z.message,$.chat+=Z.chat,$.handle+=Z.handle,$.attachment+=Z.attachment}function CL($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:H2,discover(X){let z=$.census();if(!K(z))return z;let Y={message:0,chat:0,handle:0,attachment:0};return yT(Y,z.ok),H({asOf:Q(),streams:{[R5]:{total:Y.message,method:"count-api"},[O5]:{total:Y.chat,method:"count-api"},[x5]:{total:Y.handle,method:"count-api"},[I5]:{total:Y.attachment,method:"count-api"}}})},pull(X,z){let Y=$.messages();if(!K(Y))return Y;let j=$.chats();if(!K(j))return j;let W=$.handles();if(!K(W))return W;let V=$.attachments();if(!K(V))return V;let q=$.retired();if(!K(q))return q;let B=[];for(let D of Y.ok)B.push({streamRef:R5,raw:D});for(let D of j.ok)B.push({streamRef:O5,raw:D});for(let D of W.ok)B.push({streamRef:x5,raw:D});for(let D of V.ok)B.push({streamRef:I5,raw:D});let G={message:new Set(Y.ok.map((D)=>D.rowid)),chat:new Set(j.ok.map((D)=>D.rowid)),handle:new Set(W.ok.map((D)=>D.rowid)),attachment:new Set(V.ok.map((D)=>D.rowid))},J=ST(z,q.ok.store).tombstoned,U=e0(),L=Q();for(let D of FW){let P=new Set(J[D]);for(let F of q.ok.ids[D]){if(G[D].has(F))continue;if(!P.has(F))B.push(xT(D,q.ok.store,F,L));P.add(F)}U[D]=[...P].sort()}return H({items:B,next:RT(q.ok.store,U),exhausted:!0})},normalize(X){if(OT(X.raw)){if(!FW.includes(X.streamRef))throw Error(`imessage normalize: undeclared streamRef '${X.streamRef}'`);return IT(X.streamRef,X.raw)}switch(X.streamRef){case R5:return ET(X.raw);case O5:return vT(X.raw);case x5:return bT(X.raw);case I5:return gT(X.raw);default:throw Error(`imessage normalize: undeclared streamRef '${X.streamRef}'`)}}}}function ET($){let Z=$.isFromMe?"sent":"received",Q=$.handle!==""?`iMessage ${Z} with ${$.handle}`:`iMessage ${Z}`;return{nk:{source:S5,stream:R5,sourceId:$.rowid,rev:$.dateIso},ts:$.dateIso,tier:"local-app",kind:$.isFromMe?"message.sent":"message.received",schemaVersion:1,mentions:[...B2("imessage-handle",$.handle,$.isFromMe?"participant":"actor"),...$.chatIds.flatMap((X)=>B2("imessage-chat",X,"participant"))],body:$.text!==""?$.text:Q,payload:$}}function vT($){let Z=$.displayName||$.chatIdentifier||$.guid||$.rowid;return{nk:{source:S5,stream:O5,sourceId:$.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.chat",schemaVersion:1,mentions:B2("imessage-chat",$.chatIdentifier,"participant"),body:Z,payload:$}}function bT($){return{nk:{source:S5,stream:x5,sourceId:$.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.handle",schemaVersion:1,mentions:B2("imessage-handle",$.id,"participant"),body:$.id||$.uncanonicalizedId||$.rowid,payload:$}}function gT($){let Z=$.transferName||$.filename||$.guid||$.rowid;return{nk:{source:S5,stream:I5,sourceId:$.rowid},ts:$.createdIso||$.startDateIso||"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.attachment",schemaVersion:1,mentions:[],body:Z,payload:$}}var FW,_T,TT;var FL=E(()=>{f();CW();FW=[R5,O5,x5,I5],_T={message:M4,chat:P4,handle:C4,attachment:F4},TT={message:!0,chat:!1,handle:!1,attachment:!1}});class NW{store;t=fT;messageRows=[];chatRows=[];handleRows=[];attachmentRows=[];retiredIds=e0();constructor($="fixture"){this.store=$}retire($,Z){let Q=$==="message"?this.messageRows:$==="chat"?this.chatRows:$==="handle"?this.handleRows:this.attachmentRows,X=Q.findIndex((z)=>z.rowid===Z);if(X!==-1)Q.splice(X,1);if(!this.retiredIds[$].includes(Z))this.retiredIds[$].push(Z)}tick(){return this.t+=1000,new Date(this.t).toISOString()}plantHandle($={}){let Z=$.rowid??String(this.handleRows.length+1);return this.handleRows.push({store:this.store,rowid:Z,id:$.id??`+1555000${Z}`,service:$.service??"iMessage",country:$.country??"US",uncanonicalizedId:$.uncanonicalizedId??""}),Z}plantChat($={}){let Z=$.rowid??String(this.chatRows.length+1);return this.chatRows.push({store:this.store,rowid:Z,guid:$.guid??`iMessage;-;chat-${Z}`,chatIdentifier:$.chatIdentifier??`chat-${Z}`,serviceName:$.serviceName??"iMessage",displayName:$.displayName??"",roomName:$.roomName??"",lastAddressedHandle:$.lastAddressedHandle??""}),Z}plantAttachment($={}){let Z=$.rowid??String(this.attachmentRows.length+1);return this.attachmentRows.push({store:this.store,rowid:Z,guid:$.guid??`att-${Z}`,filename:$.filename??`/Users/me/Library/Messages/Attachments/${Z}/photo.jpg`,mimeType:$.mimeType??"image/jpeg",transferName:$.transferName??`photo-${Z}.jpg`,totalBytes:$.totalBytes??1234,createdIso:$.createdIso??this.tick(),startDateIso:$.startDateIso??"",userInfo:$.userInfo??""}),Z}plantMessage($={}){let Z=$.rowid??String(this.messageRows.length+1),Q=$.handleId??(this.handleRows[0]?.rowid??this.plantHandle()),X=this.chatRows[0]?.rowid??this.plantChat();return this.messageRows.push({store:this.store,rowid:Z,guid:$.guid??`msg-${Z}`,text:$.text??`fixture message ${Z}`,service:$.service??"iMessage",account:$.account??"E:user@example.test",handleId:Q,handle:$.handle??this.handleRows.find((z)=>z.rowid===Q)?.id??"",handleService:$.handleService??"iMessage",chatIds:$.chatIds??[X],attachmentIds:$.attachmentIds??[],isFromMe:$.isFromMe??!1,dateIso:$.dateIso??this.tick(),dateReadIso:$.dateReadIso??"",dateDeliveredIso:$.dateDeliveredIso??"",cacheRoomnames:$.cacheRoomnames??"",associatedMessageGuid:$.associatedMessageGuid??"",associatedMessageType:$.associatedMessageType??0}),Z}census(){return H({message:this.messageRows.length,chat:this.chatRows.length,handle:this.handleRows.length,attachment:this.attachmentRows.length})}messages(){return H(this.messageRows.map(($)=>({...$,chatIds:[...$.chatIds],attachmentIds:[...$.attachmentIds]})))}chats(){return H(this.chatRows.map(($)=>({...$})))}handles(){return H(this.handleRows.map(($)=>({...$})))}attachments(){return H(this.attachmentRows.map(($)=>({...$})))}retired(){return H({store:this.store,ids:{message:[...this.retiredIds.message],chat:[...this.retiredIds.chat],handle:[...this.retiredIds.handle],attachment:[...this.retiredIds.attachment]}})}}var fT;var NL=E(()=>{f();fT=Date.parse("2026-07-01T00:00:00.000Z")});import{Database as AL}from"bun:sqlite";import{copyFileSync as _L,existsSync as TL,mkdtempSync as kT,rmSync as wT}from"fs";import{homedir as mT,tmpdir as hT}from"os";import{join as AW}from"path";function TW($=mT()){return AW($,"Library","Messages","chat.db")}function pT($){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,$)}function J2($,Z,Q="non-retryable"){return v({code:$,layer:"upstream",retryability:Q,message:Z})}function N4($){if($===null||$===""||$==="0")return"";let Z=BigInt($),Q=Z>10000000000000n?Number(Z/1000000n):Number(Z*1000n);return X5(uT+Q)}function Q8($,Z){return($.query("SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name=?").get(Z)?.n??0)>0}function lT($,Z){let Q=$.query("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(Z)?.sql;if(typeof Q!=="string"||!/AUTOINCREMENT/i.test(Q))return null;if(!Q8($,"sqlite_sequence"))return null;let z=$.query("SELECT seq FROM sqlite_sequence WHERE name=?").get(Z)?.seq;return typeof z==="number"&&Number.isSafeInteger(z)&&z>=0?z:null}function RL($,Z,Q,X){let z=new Map;if(!Q8($,Z))return z;let Y=$.query(`SELECT CAST(${Q} AS TEXT) AS l, CAST(${X} AS TEXT) AS r FROM ${Z} ORDER BY ${Q}, ${X}`).all();for(let j of Y){let W=z.get(j.l)??[];W.push(j.r),z.set(j.l,W)}return z}class SW{opts;constructor($={}){this.opts=$}chatDbPath(){return this.opts.chatDbPath??TW()}get cap(){return this.opts.cap??_W}get store(){return this.opts.store??this.chatDbPath()}read($){let Z=this.chatDbPath();if(!TL(Z))return J2("not_found",`imessage: no Messages chat.db at '${Z}' \u2014 Messages absent or Full-Disk-Access missing (empty is never a default)`);let Q=kT(AW(hT(),"imessage-chatdb-"));try{let X="no attempt made";for(let z=0;z<SL;z++){if(z>0)pT(200);let Y=AW(Q,`chat-${z}.db`);try{_L(Z,Y);for(let V of["-wal","-shm"]){let q=`${Z}${V}`;if(TL(q))_L(q,`${Y}${V}`)}let j=new AL(Y,{readwrite:!0});try{j.exec("PRAGMA wal_checkpoint(TRUNCATE)");let V=j.query("PRAGMA quick_check").get()?.quick_check;if(V!=="ok"){X=`quick_check='${V??"missing"}'`;continue}}finally{j.close()}let W=new AL(Y,{readonly:!0});try{return $(W)}finally{W.close()}}catch(j){if(X=j instanceof Error?j.message:String(j),/\bEPERM\b|operation not permitted/i.test(X))return J2("permission_denied",`imessage: macOS denied reading '${Z}' (Full-Disk-Access/TCC) \u2014 grant the host process access, then re-run sync; denied reads are AUTH_BLOCKED, never empty syncs`)}}return v({code:"data_loss",layer:"upstream",retryability:"transient",message:`imessage: could not obtain a consistent chat.db snapshot after ${SL} attempts (last: ${X})`})}finally{wT(Q,{recursive:!0,force:!0})}}census(){return this.read(($)=>{let Z=(Q)=>Q8($,Q)?$.query(`SELECT COUNT(*) AS n FROM ${Q}`).get()?.n??0:0;return H({message:Z("message"),chat:Z("chat"),handle:Z("handle"),attachment:Z("attachment")})})}retired(){return this.read(($)=>{let Z=e0();for(let Q of Object.keys(Z)){let X=Q;if(!Q8($,X))continue;let z=lT($,X);if(z===null)continue;if(z>this.cap)return J2("resource_exhausted",`imessage: '${X}' identity high-water ${z} exceeds cap ${this.cap} \u2014 refused loud, never truncated`);let Y=new Set($.query(`SELECT ROWID AS r FROM ${X}`).all().map((W)=>W.r)),j=[];for(let W=1;W<=z;W++)if(!Y.has(W))j.push(String(W));Z[Q]=j}return H({store:this.store,ids:Z})})}messages(){return this.read(($)=>{let Z=$.query("SELECT COUNT(*) AS n FROM message").get()?.n??0;if(Z>this.cap)return J2("resource_exhausted",`imessage: ${Z} messages exceeds cap ${this.cap} \u2014 refused loud, never truncated`);let Q=RL($,"chat_message_join","message_id","chat_id"),X=RL($,"message_attachment_join","message_id","attachment_id"),z=$.query("SELECT CAST(m.ROWID AS TEXT) AS rowid, m.guid AS guid, m.text AS text, m.service AS service, m.account AS account, CAST(m.handle_id AS TEXT) AS handle_id, h.id AS handle, h.service AS handle_service, CAST(m.date AS TEXT) AS date, CAST(m.date_read AS TEXT) AS date_read, CAST(m.date_delivered AS TEXT) AS date_delivered, m.is_from_me AS is_from_me, m.cache_roomnames AS cache_roomnames, m.associated_message_guid AS associated_message_guid, m.associated_message_type AS associated_message_type FROM message m LEFT JOIN handle h ON h.ROWID = m.handle_id ORDER BY m.ROWID").all();return H(z.map((Y)=>({store:this.store,rowid:Y.rowid,guid:Y.guid??"",text:Y.text??"",service:Y.service??"",account:Y.account??"",handleId:Y.handle_id??"",handle:Y.handle??"",handleService:Y.handle_service??"",chatIds:Q.get(Y.rowid)??[],attachmentIds:X.get(Y.rowid)??[],isFromMe:(Y.is_from_me??0)===1,dateIso:N4(Y.date),dateReadIso:N4(Y.date_read),dateDeliveredIso:N4(Y.date_delivered),cacheRoomnames:Y.cache_roomnames??"",associatedMessageGuid:Y.associated_message_guid??"",associatedMessageType:Y.associated_message_type??0})))})}chats(){return this.read(($)=>{if(!Q8($,"chat"))return H([]);let Z=$.query("SELECT CAST(ROWID AS TEXT) AS rowid, guid, chat_identifier, service_name, display_name, room_name, last_addressed_handle FROM chat ORDER BY ROWID").all();return H(Z.map((Q)=>({store:this.store,rowid:Q.rowid,guid:Q.guid??"",chatIdentifier:Q.chat_identifier??"",serviceName:Q.service_name??"",displayName:Q.display_name??"",roomName:Q.room_name??"",lastAddressedHandle:Q.last_addressed_handle??""})))})}handles(){return this.read(($)=>{if(!Q8($,"handle"))return H([]);let Z=$.query("SELECT CAST(ROWID AS TEXT) AS rowid, id, service, country, uncanonicalized_id FROM handle ORDER BY ROWID").all();return H(Z.map((Q)=>({store:this.store,rowid:Q.rowid,id:Q.id??"",service:Q.service??"",country:Q.country??"",uncanonicalizedId:Q.uncanonicalized_id??""})))})}attachments(){return this.read(($)=>{if(!Q8($,"attachment"))return H([]);let Z=$.query("SELECT CAST(ROWID AS TEXT) AS rowid, guid, filename, mime_type, transfer_name, total_bytes, CAST(created_date AS TEXT) AS created_date, CAST(start_date AS TEXT) AS start_date, CAST(user_info AS TEXT) AS user_info FROM attachment ORDER BY ROWID").all();return H(Z.map((Q)=>({store:this.store,rowid:Q.rowid,guid:Q.guid??"",filename:Q.filename??"",mimeType:Q.mime_type??"",transferName:Q.transfer_name??"",totalBytes:Q.total_bytes??0,createdIso:N4(Q.created_date),startDateIso:N4(Q.start_date),userInfo:Q.user_info??""})))})}}var _W=250000,SL=4,uT;var OL=E(()=>{f();uT=Date.parse("2001-01-01T00:00:00.000Z")});var xL;var IL=E(()=>{xL={research:{candidates:[{repo:"local-chat.db",recency:5,commits:0,comprehensiveness:5,maintenance:5},{repo:"github.com/jesec/imessage-rs",recency:3,commits:3,comprehensiveness:4,maintenance:3},{repo:"BlueBubbles private-api",recency:4,commits:4,comprehensiveness:4,maintenance:4}],chosen:"from-scratch",rationale:"The requested deliverable is read ingestion, not sending. The lawful high-fidelity route is the local macOS Messages SQLite store: no Apple protocol automation, no private API injection, no SIP-off helper, and no third-party parser. The connector stages a read-only chat.db snapshot and maps source rows onto the framework rails.",refs:["docs/uarch/channels.md \xA73.4 inbound messages via local DB watcher","docs/research/channel-reality.md CR-F1 iMessage chat.db read path","docs/research/channel-reality.md CR-F2 private API/SIP-off rejected for ingestion","docs/uarch/connectors.md \xA72.1 local-app tier + TCC permissions"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"macos-messages-chatdb@sqlite-master",schemas:[{name:"chat.db sqlite_master tables: message, chat, handle, attachment, join tables",kind:"sqlite-schema"}],identityFacts:[{stream:"message",fact:"message.ROWID is a local-store row id; message.guid is retained as payload evidence, but not relied on as globally durable identity. The stream is container-scoped by the local chat.db store and ordered by message date.",citation:"docs/uarch/INTERFACES.md I-1 container-scoped identity + chatdb-source.ts SELECT over message.ROWID/date"},{stream:"chat",fact:"chat.ROWID identifies a local chat row; chat metadata is mutable and has no upstream version token.",citation:"chatdb-source.ts SELECT over chat.ROWID + docs/uarch/connectors.md \xA72.2 head-compare"},{stream:"handle",fact:"handle.ROWID identifies a local handle row; handle metadata has no upstream version token.",citation:"chatdb-source.ts SELECT over handle.ROWID + docs/uarch/connectors.md \xA72.2 head-compare"},{stream:"attachment",fact:"attachment.ROWID identifies a local attachment row; attachment metadata has no upstream version token.",citation:"chatdb-source.ts SELECT over attachment.ROWID + docs/uarch/connectors.md \xA72.2 head-compare"}]},identity:{perStream:[{stream:"message",citation:"container-scoped, epochField 'store', revOrder event-ts; framework prefixes <store>:<ROWID>."},{stream:"chat",citation:"container-scoped, epochField 'store', revOrder head-compare for mutable metadata snapshots."},{stream:"handle",citation:"container-scoped, epochField 'store', revOrder head-compare for mutable metadata snapshots."},{stream:"attachment",citation:"container-scoped, epochField 'store', revOrder head-compare for mutable metadata snapshots."}]},classification:{rows:[]}}});var yL={};h0(yL,{refuseImessageAction:()=>PL,emptyRetiredIds:()=>e0,defaultMessagesChatDbPath:()=>TW,createImessageConnector:()=>CL,MAX_MESSAGES:()=>_W,IMESSAGE_V0_READ_ONLY_GATE:()=>PW,IMESSAGE_SOURCE:()=>S5,IMESSAGE_MESSAGE_STREAM:()=>R5,IMESSAGE_MESSAGE_DELETED_KIND:()=>M4,IMESSAGE_MANIFEST:()=>H2,IMESSAGE_HANDLE_STREAM:()=>x5,IMESSAGE_HANDLE_DELETED_KIND:()=>C4,IMESSAGE_CHAT_STREAM:()=>O5,IMESSAGE_CHAT_DELETED_KIND:()=>P4,IMESSAGE_ATTACHMENT_STREAM:()=>I5,IMESSAGE_ATTACHMENT_DELETED_KIND:()=>F4,IMESSAGE_ARTIFACTS:()=>xL,FixtureImessageSource:()=>NW,ChatDbMessagesSource:()=>SW});var EL=E(()=>{CW();FL();NL();OL();IL()});function vL($){return W$(`notion action '${$}'`,RW)}var y5="notion",VZ="page",KZ="database",X8="block",z8="dbrow",Y8="comment",j8="user",A4="doc.changed",_4="collection.changed",T4="block.observed",S4="row.changed",R4="comment.created",O4="user.observed",G2,RW="connectors.md \xA72.3c classification review \u2014 notion v0 declares zero ActionContracts (read-only ingestion)";var OW=E(()=>{j$();G2={source:y5,tier:"api",auth:{provider:"notion",method:"api-key",scopes:[],multiAccount:!1,probe:{op:"users.me"}},streams:[{stream:VZ,kinds:[A4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:KZ,kinds:[_4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:X8,kinds:[T4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:z8,kinds:[S4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:Y8,kinds:[R4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"},{stream:j8,kinds:[O4],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:30},retaliationRisk:"tolerant"}});function U2($){if(!Array.isArray($))return"";return $.map((Z)=>Z!==null&&typeof Z==="object"&&typeof Z.plain_text==="string"?Z.plain_text:"").join("")}function L2($,Z){if($===KZ)return U2(Z.title);let Q=Z.properties;if(Q!==void 0&&Q!==null&&typeof Q==="object")for(let X of Object.keys(Q).sort()){let z=Q[X];if(z!==void 0&&z!==null&&typeof z==="object"&&z.type==="title")return U2(z.title)}return""}function I4($){let Z=[],Q=$.last_edited_by;if(Q!==void 0&&Q!==null&&typeof Q.id==="string"&&Q.id!=="")Z.push({role:"actor",kind:"person",raw:Q.id,handle:{ns:"notion-user",value:Q.id}});let X=$.created_by;if(X!==void 0&&X!==null&&typeof X.id==="string"&&X.id!=="")Z.push({role:"participant",kind:"person",raw:X.id,handle:{ns:"notion-user",value:X.id}});return Z}function yW($){let Z=$.type;if(typeof Z!=="string")return"";let Q=$[Z];if(Q!==null&&typeof Q==="object"&&"rich_text"in Q)return U2(Q.rich_text);return""}function cT($){let Z=$.created_by;if(Z!==void 0&&Z!==null&&typeof Z.id==="string"&&Z.id!=="")return[{role:"actor",kind:"person",raw:Z.id,handle:{ns:"notion-user",value:Z.id}}];return[]}function dT($){let Z;try{Z=JSON.parse($)}catch{return IW}if(Z!==null&&typeof Z==="object"){let Q=Z.p;if(Q==="search"||Q==="users"||Q==="rows"||Q==="blocks"||Q==="comments")return Z}return IW}function xW($){return"err"in $&&$.err.layer==="connector"&&$.err.code==="permission_denied"}function bL($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:G2,discover(X){let z=$.census(X);if(!K(z))return z;let Y={};for(let j of["page","database"]){let W=z.ok.streams[j];Y[j]={total:W.total,method:"census",...W.partialReasons!==void 0&&W.partialReasons.length>0?{partialReasons:W.partialReasons}:{}}}return Y[X8]={method:"pagination-exhaustion"},Y[z8]={method:"pagination-exhaustion"},Y[Y8]={method:"pagination-exhaustion"},Y[j8]={method:"pagination-exhaustion"},H({asOf:Q(),streams:Y})},pull(X,z){let Y=z!==null?dT(z):IW;if(Y.p==="search"){let B=$.search(X,Y.o,Y.a);if(!K(B))return B;let G=B.ok,J=G.items.map((P)=>({streamRef:Y.o,raw:P})),U=G.items.map((P)=>P.id),L=Y.o==="page"?[...Y.pages,...U]:Y.pages,D=Y.o==="database"?[...Y.dbs,...U]:Y.dbs;if(G.hasMore)return H({items:J,next:J0({p:"search",o:Y.o,a:G.nextCursor,pages:L,dbs:D}),exhausted:!1});if(Y.o==="page")return H({items:J,next:J0({p:"search",o:"database",a:null,pages:L,dbs:D}),exhausted:!1});return H({items:J,next:J0({p:"users",a:null,pages:L,dbs:D}),exhausted:!1})}if(Y.p==="users"){let B=$.users(X,Y.a);if(!K(B))return B;let G=B.ok.items.map((J)=>({streamRef:j8,raw:J}));if(B.ok.hasMore)return H({items:G,next:J0({p:"users",a:B.ok.nextCursor,pages:Y.pages,dbs:Y.dbs}),exhausted:!1});return H({items:G,next:J0({p:"rows",i:0,a:null,pages:Y.pages,dbs:Y.dbs,rows:[]}),exhausted:!1})}if(Y.p==="rows"){let B=Y.dbs[Y.i];if(B===void 0){let L=[...Y.pages,...Y.rows];if(L.length===0)return H({items:[],next:null,exhausted:!0});return H({items:[],next:J0({p:"blocks",i:0,ids:L}),exhausted:!1})}let G=$.databaseRows(X,B,Y.a);if(!K(G)){if(xW(G))return H({items:[],next:J0({p:"rows",i:Y.i+1,a:null,pages:Y.pages,dbs:Y.dbs,rows:Y.rows}),exhausted:!1});return G}let J=G.ok.items.map((L)=>({streamRef:z8,raw:L})),U=[...Y.rows,...G.ok.items.map((L)=>L.id)];if(G.ok.hasMore)return H({items:J,next:J0({p:"rows",i:Y.i,a:G.ok.nextCursor,pages:Y.pages,dbs:Y.dbs,rows:U}),exhausted:!1});return H({items:J,next:J0({p:"rows",i:Y.i+1,a:null,pages:Y.pages,dbs:Y.dbs,rows:U}),exhausted:!1})}if(Y.p==="blocks"){let B=Y.ids[Y.i];if(B===void 0){if(Y.ids.length===0)return H({items:[],next:null,exhausted:!0});return H({items:[],next:J0({p:"comments",i:0,a:null,ids:Y.ids}),exhausted:!1})}let G=$.blockTree(X,B);if(!K(G)){if(xW(G))return H({items:[],next:J0({p:"blocks",i:Y.i+1,ids:Y.ids}),exhausted:!1});return G}let J=G.ok.map((U)=>({streamRef:X8,raw:U}));return H({items:J,next:J0({p:"blocks",i:Y.i+1,ids:Y.ids}),exhausted:!1})}let j=Y.ids[Y.i];if(j===void 0)return H({items:[],next:null,exhausted:!0});let W=$.comments(X,j,Y.a);if(!K(W)){if(xW(W))return C("permission_denied",`notion comment class is unreadable for this grant (403 restricted_resource on GET /v1/comments) \u2014 the integration lacks the "Read comments" capability; grant-level \u2192 AUTH_BLOCKED, never a zero-comment success (FM-21). Underlying: ${W.err.message}`,"non-retryable");return W}let V=W.ok.items.map((B)=>({streamRef:Y8,raw:B}));if(W.ok.hasMore)return H({items:V,next:J0({p:"comments",i:Y.i,a:W.ok.nextCursor,ids:Y.ids}),exhausted:!1});let q=Y.i+1;if(q>=Y.ids.length)return H({items:V,next:null,exhausted:!0});return H({items:V,next:J0({p:"comments",i:q,a:null,ids:Y.ids}),exhausted:!1})},normalize(X){let z=X.streamRef;if(z===VZ||z===z8){let Y=X.raw,j=x4(Y.last_edited_time??Y.created_time,z,Y.id);return{nk:{source:y5,stream:z,sourceId:Y.id},ts:j,tier:"api",kind:z===VZ?A4:S4,schemaVersion:1,mentions:I4(Y),body:L2(z,Y),payload:X.raw}}if(z===KZ){let Y=X.raw,j=x4(Y.last_edited_time??Y.created_time,z,Y.id);return{nk:{source:y5,stream:z,sourceId:Y.id},ts:j,tier:"api",kind:_4,schemaVersion:1,mentions:I4(Y),body:L2(z,Y),payload:X.raw}}if(z===X8){let Y=X.raw,j=x4(Y.last_edited_time??Y.created_time,z,Y.id);return{nk:{source:y5,stream:z,sourceId:Y.id},ts:j,tier:"api",kind:T4,schemaVersion:1,mentions:I4(Y),body:yW(Y),payload:X.raw}}if(z===Y8){let Y=X.raw,j=x4(Y.last_edited_time??Y.created_time,z,Y.id);return{nk:{source:y5,stream:z,sourceId:Y.id},ts:j,tier:"api",kind:R4,schemaVersion:1,mentions:cT(Y),body:U2(Y.rich_text),payload:X.raw}}if(z===j8){let Y=X.raw,j=Y.user,W=x4(Y.observedAt,z,j.id);return{nk:{source:y5,stream:z,sourceId:j.id},ts:W,tier:"api",kind:O4,schemaVersion:1,mentions:[],body:typeof j.name==="string"?j.name:"",payload:j}}throw Error(`notion normalize: undeclared streamRef '${z}'`)}}}function x4($,Z,Q){if(typeof $!=="string"||$==="")throw Error(`notion normalize: '${Z}' object '${Q}' has no timestamp`);return $}var IW,J0=($)=>JSON.stringify($);var gL=E(()=>{f();j$();OW();IW={p:"search",o:"page",a:null,pages:[],dbs:[]}});function y4($,Z,Q={maxDepth:BZ,maxNodes:JZ}){let X=[],z=[{id:Z,depth:0}],Y=0;while(Y<z.length){let j=z[Y];if(Y+=1,j===void 0)break;if(j.depth>Q.maxDepth)return C("resource_exhausted",`notion block tree under '${Z}' exceeded depth ${Q.maxDepth} \u2014 refusing a runaway/cyclic recursion LOUD (drift, FM-19), never a silent truncation`,"non-retryable");let W=null,V=0;for(;;){let q=$(j.id,W);if(!K(q))return q;let B=q.ok;for(let G of B.items){if(X.push(G),X.length>Q.maxNodes)return C("resource_exhausted",`notion block tree under '${Z}' exceeded ${Q.maxNodes} nodes \u2014 refusing a partial tree LOUD (FM-18/FM-19)`,"non-retryable");if(G.has_children===!0)z.push({id:G.id,depth:j.depth+1})}if(V+=1,V>HZ)return C("internal",`notion /v1/blocks/${j.id}/children paginated past ${HZ} pages (has_more never cleared) \u2014 REST-surface drift (FM-19)`,"non-retryable");if(!B.hasMore)break;W=B.nextCursor}}return H(X)}function K9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function nT($){if(!K9($)||$.object!=="block"||typeof $.id!=="string")return null;if(typeof $.last_edited_time!=="string")return null;return $}function iT($){if(!K9($)||$.object!=="page"||typeof $.id!=="string")return null;if(typeof $.last_edited_time!=="string")return null;return $}function sT($){if(!K9($)||$.object!=="comment"||typeof $.id!=="string")return null;if(typeof $.created_time!=="string")return null;return $}function oT($){if(!K9($)||$.object!=="user"||typeof $.id!=="string")return null;return $}class P2{transport;authHeaders;cap;blockDepthCap;blockNodeCap;pageSize;constructor($,Z,Q,X,z,Y){this.transport=$;this.authHeaders=Z;this.cap=Q;this.blockDepthCap=X;this.blockNodeCap=z;this.pageSize=Y}static create($={}){return new P2($.transport??fW,$.authHeaders??kW,$.cap??bW,$.blockDepthCap??BZ,$.blockNodeCap??JZ,$.pageSize??vW)}unavailable($){return C("unavailable",`notion transport failure (${$}) \u2014 api.notion.com unreachable; NEVER an empty success (FM-21)`,"transient")}drift($){return C("internal",`notion REST-surface drift (${$}) \u2014 the pinned ${D2} surface changed shape; non-retryable rot, repair order due (FM-19)`,"non-retryable")}mapStatus($,Z,Q){if($===200)try{return H(JSON.parse(Z))}catch{return this.drift(`non-JSON 200 body from ${Q}`)}if($===401)return C("unauthenticated",`notion ${Q}: HTTP 401 unauthorized \u2014 invalid/expired integration secret (grant-level \u2192 AUTH_BLOCKED, never a zero-item success; FM-21)`,"non-retryable");if($===403)return C("permission_denied",`notion ${Q}: HTTP 403 restricted_resource \u2014 the integration lacks access (grant-level \u2192 AUTH_BLOCKED)`,"non-retryable");if($===429)return C("resource_exhausted",`notion ${Q}: HTTP 429 rate_limited \u2014 throttling (long backoff + the I-6 retry-quota token bucket; \xA73.5 anti-storm)`,"throttling");if($>=500)return C("unavailable",`notion ${Q}: HTTP ${$} \u2014 transient server condition`,"transient");return this.drift(`HTTP ${$} from ${Q}`)}request($,Z,Q,X){let z=this.authHeaders($);if(!K(z))return z;let Y={...z.ok,"Notion-Version":D2,"Content-Type":"application/json"},j=this.transport(`${EW}${Q}`,{method:Z,headers:Y,...X!==void 0?{body:X}:{}});if(!j.ok){if(j.structuredError!==void 0)return{err:j.structuredError};return j.gated===!0?W$("notion live WAN transport",M2):this.unavailable(j.error)}return this.mapStatus(j.status,j.body,`${Z} ${Q}`)}probe($){let Z=this.request($,"GET","/v1/users/me");if(!K(Z))return Z;let Q=Z.ok;if(!K9(Q)||typeof Q.id!=="string")return this.drift("/v1/users/me response missing a string id");return H({botId:Q.id})}parseSearchPage($,Z){if(!K9($))return this.drift("/v1/search response is not an object");let Q=$.results;if(!Array.isArray(Q))return this.drift("/v1/search 'results' is not an array");let X=[];for(let W of Q){if(!K9(W)||typeof W.id!=="string"||W.object!==Z||typeof W.last_edited_time!=="string")return this.drift(`/v1/search returned an object missing id / '${Z}' object type / last_edited_time`);X.push(W)}let z=$.has_more===!0,Y=$.next_cursor,j=typeof Y==="string"?Y:null;if(z&&j===null)return this.drift("/v1/search has_more:true but next_cursor is null");return H({items:X,nextCursor:j,hasMore:z})}search($,Z,Q){let X=JSON.stringify({filter:{property:"object",value:Z},page_size:this.pageSize,...Q!==null?{start_cursor:Q}:{}}),z=this.request($,"POST","/v1/search",X);if(!K(z))return z;return this.parseSearchPage(z.ok,Z)}census($){let Z={},Q=0;for(let X of gW){let z=null,Y=0,j=0;for(;;){let W=this.search($,X,z);if(!K(W))return W;if(Y+=W.ok.items.length,Q+=W.ok.items.length,Q>this.cap)return C("resource_exhausted",`notion census exceeded the ${this.cap}-object cap \u2014 refusing a partial census (loud; a silent truncation would misreconcile FM-18 coverage); narrow the workspace`,"non-retryable");if(j+=1,j>HZ)return this.drift(`/v1/search paginated past ${HZ} pages for '${X}' (has_more never cleared)`);if(!W.ok.hasMore)break;z=W.ok.nextCursor}Z[X]={total:Y}}return H({streams:Z})}parseCursorList($,Z,Q){if(!K9($))return this.drift(`${Q} response is not an object`);let X=$.results;if(!Array.isArray(X))return this.drift(`${Q} 'results' is not an array`);let z=[];for(let V of X){let q=Z(V);if(q===null)return this.drift(`${Q} returned an item of unexpected shape`);z.push(q)}let Y=$.has_more===!0,j=$.next_cursor,W=typeof j==="string"?j:null;if(Y&&W===null)return this.drift(`${Q} has_more:true but next_cursor is null`);return H({items:z,nextCursor:W,hasMore:Y})}blockChildren($,Z,Q){let X=new URLSearchParams({page_size:String(qZ)});if(Q!==null)X.set("start_cursor",Q);let z=this.request($,"GET",`/v1/blocks/${encodeURIComponent(Z)}/children?${X.toString()}`);if(!K(z))return z;return this.parseCursorList(z.ok,nT,`GET /v1/blocks/${Z}/children`)}blockTree($,Z){return y4((Q,X)=>this.blockChildren($,Q,X),Z,{maxDepth:this.blockDepthCap,maxNodes:this.blockNodeCap})}databaseRows($,Z,Q){let X=JSON.stringify({page_size:qZ,...Q!==null?{start_cursor:Q}:{}}),z=this.request($,"POST",`/v1/databases/${encodeURIComponent(Z)}/query`,X);if(!K(z))return z;return this.parseCursorList(z.ok,iT,`POST /v1/databases/${Z}/query`)}comments($,Z,Q){let X=new URLSearchParams({block_id:Z,page_size:String(qZ)});if(Q!==null)X.set("start_cursor",Q);let z=this.request($,"GET",`/v1/comments?${X.toString()}`);if(!K(z))return z;return this.parseCursorList(z.ok,sT,`GET /v1/comments?block_id=${Z}`)}users($,Z){let Q=new URLSearchParams({page_size:String(qZ)});if(Z!==null)Q.set("start_cursor",Z);let X=this.request($,"GET",`/v1/users?${Q.toString()}`);if(!K(X))return X;let z=this.parseCursorList(X.ok,oT,"GET /v1/users");if(!K(z))return z;let Y=new Date().toISOString();return H({items:z.ok.items.map((j)=>({user:j,observedAt:Y})),nextCursor:z.ok.nextCursor,hasMore:z.ok.hasMore})}}var D2="2022-06-28",EW="https://api.notion.com",vW=100,bW=20000,HZ=5000,gW,qZ=100,BZ=30,JZ=50000,M2="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real credentials at C-P6-2 (G2)",fW=()=>({ok:!1,gated:!0,error:M2}),kW=()=>W$("notion live credential headers","C-P6-2 (G2 \u2014 real-provider credentials); the broker injects the Authorization header only after G2 opens");var wW=E(()=>{f();j$();gW=["page","database"]});function C2($){return new Date(Math.floor($/60000)*60000).toISOString()}class mW{pages=new Map;databases=new Map;blocksById=new Map;blockKids=new Map;rowsByDb=new Map;commentsByBlock=new Map;userList=[];tMs=aT;pageSize=100;blockDepthCap=BZ;blockNodeCap=JZ;failMode=null;failPhase="both";restricted={page:{count:0,reason:""},database:{count:0,reason:""}};setPageSize($){if($<1)throw Error(`fixture: page_size must be \u2265 1 (got ${$})`);this.pageSize=$}setBlockCaps($){if($.depth!==void 0)this.blockDepthCap=$.depth;if($.nodes!==void 0)this.blockNodeCap=$.nodes}tick(){return this.tMs+=60000,this.tMs}makeObject($,Z,Q,X){let z=C2(X.ms),Y={object:"user",id:X.createdBy??"user-creator-uuid"},j={object:"user",id:X.lastEditedBy??"user-editor-uuid"},W={object:$,id:Z,created_time:z,last_edited_time:z,created_by:Y,last_edited_by:j,archived:!1,url:`https://www.notion.so/${Z.replace(/-/g,"")}`,parent:{type:"workspace",workspace:!0}};if($==="page")W.properties={Name:{id:"title",type:"title",title:[{plain_text:Q}]}};else W.title=[{plain_text:Q}];return W}plantPage($={}){let Z=$.id??`page-${this.pages.size+1}-uuid`;if(this.pages.has(Z))throw Error(`fixture: page '${Z}' already planted`);let Q=this.makeObject("page",Z,$.title??"",{ms:this.tick(),...$});return this.pages.set(Z,Q),Q}plantDatabase($={}){let Z=$.id??`db-${this.databases.size+1}-uuid`;if(this.databases.has(Z))throw Error(`fixture: database '${Z}' already planted`);let Q=this.makeObject("database",Z,$.title??"",{ms:this.tick(),...$});return this.databases.set(Z,Q),Q}makeBlock($,Z,Q,X,z,Y){let j=C2(z),W={object:"block",id:$,type:Q,created_time:j,last_edited_time:j,created_by:{object:"user",id:"user-creator-uuid"},last_edited_by:{object:"user",id:Y??"user-editor-uuid"},has_children:!1,archived:!1,parent:{type:"page_id",page_id:Z}};return W[Q]={rich_text:[{plain_text:X}]},W}plantBlock($){let Z=$.id??`block-${this.blocksById.size+1}-uuid`;if(this.blocksById.has(Z))throw Error(`fixture: block '${Z}' already planted`);let Q=this.makeBlock(Z,$.parentId,$.type??"paragraph",$.text??"",this.tick(),$.lastEditedBy);this.blocksById.set(Z,Q);let X=this.blockKids.get($.parentId)??[];return X.push(Z),this.blockKids.set($.parentId,X),Q}mutateBlock($,Z,Q={}){let X=this.blocksById.get($);if(X===void 0)throw Error(`fixture: unknown block '${$}'`);let z=Q.sameMinute===!0?this.tMs:this.tick(),Y=this.parentOfBlock($);this.blocksById.set($,this.makeBlock($,Y,X.type??"paragraph",Z,z,Q.lastEditedBy??X.last_edited_by?.id))}parentOfBlock($){for(let[Z,Q]of this.blockKids)if(Q.includes($))return Z;return"unknown-parent"}plantRow($){let Z=this.rowsByDb.get($.databaseId)??[],Q=$.id??`row-${$.databaseId}-${Z.length+1}-uuid`,X=this.makeObject("page",Q,$.title??"",{ms:this.tick(),...$.lastEditedBy!==void 0?{lastEditedBy:$.lastEditedBy}:{},...$.createdBy!==void 0?{createdBy:$.createdBy}:{}});return X.parent={type:"database_id",database_id:$.databaseId},Z.push(X),this.rowsByDb.set($.databaseId,Z),X}plantComment($){let Z=this.commentsByBlock.get($.blockId)??[],Q=$.id??`comment-${this.commentCount()+1}-uuid`,X=C2(this.tick()),z={object:"comment",id:Q,parent:{type:"page_id",page_id:$.blockId},discussion_id:`disc-${Q}`,created_time:X,last_edited_time:X,created_by:{object:"user",id:$.author??"user-commenter-uuid"},rich_text:[{plain_text:$.text??""}]};return Z.push(z),this.commentsByBlock.set($.blockId,Z),z}commentCount(){let $=0;for(let Z of this.commentsByBlock.values())$+=Z.length;return $}plantUser($={}){let Z=$.id??`user-${this.userList.length+1}-uuid`;if(this.userList.some((z)=>z.user.id===Z))throw Error(`fixture: user '${Z}' already planted`);let Q=$.type??"person",X={object:"user",id:Z,type:Q,name:$.name??"",avatar_url:null};if(Q==="person")X.person={email:`${Z}@example.test`};else X.bot={};return this.userList.push({user:X,observedAt:C2(this.tick())}),X}mutatePage($,Z,Q={}){let X=this.mustPage($),z=Q.sameMinute===!0?this.tMs:this.tick();this.pages.set($,this.makeObject("page",$,Z,{ms:z,createdBy:X.created_by?.id,lastEditedBy:Q.lastEditedBy??X.last_edited_by?.id}))}remapPageId($,Z){let Q=this.mustPage($);if(this.pages.has(Z))throw Error(`fixture: page '${Z}' already exists`);this.pages.delete($),this.pages.set(Z,{...Q,id:Z})}removePage($){this.mustPage($),this.pages.delete($)}plantRestricted($,Z,Q="restricted_resource (integration not shared with the object)"){if(Z<0)throw Error("fixture: restricted count must be \u2265 0");this.restricted[$]={count:Z,reason:Q}}injectFailure($,Z={}){this.failMode=$,this.failPhase=Z.phase??"both"}clearFailure(){this.failMode=null,this.failPhase="both"}mustPage($){let Z=this.pages.get($);if(Z===void 0)throw Error(`fixture: unknown page '${$}'`);return Z}maybeFail($){if(this.failMode===null)return null;if(this.failPhase!=="both"&&this.failPhase!==$)return null;switch(this.failMode){case"invalid-key":return C("unauthenticated","fixture notion: HTTP 401 unauthorized \u2014 invalid integration secret (grant-level \u2192 AUTH_BLOCKED, never a zero-item success; FM-21)","non-retryable");case"restricted-grant":return C("permission_denied","fixture notion: HTTP 403 restricted_resource \u2014 grant lacks access (grant-level \u2192 AUTH_BLOCKED)","non-retryable");case"server-5xx":return C("unavailable","fixture notion: HTTP 503 \u2014 transient server condition","transient");case"rate-limited":return C("resource_exhausted","fixture notion: HTTP 429 rate_limited \u2014 throttling (long backoff + retry-quota token bucket; \xA73.5)","throttling");case"drift":return C("internal","fixture notion: /v1/search returned an unexpected shape \u2014 REST-surface drift (FM-19), non-retryable rot","non-retryable");default:return null}}sorted($){return[...($==="page"?this.pages:this.databases).values()].sort((Q,X)=>Q.id<X.id?-1:Q.id>X.id?1:0)}probe($){let Z=this.maybeFail("census");if(Z!==null)return Z;return H({botId:"fixture-bot-user-uuid"})}census($){let Z=this.maybeFail("census");if(Z!==null)return Z;let Q=(X)=>{let z=X==="page"?this.pages.size:this.databases.size,Y=this.restricted[X],j=z+Y.count;return Y.count>0?{total:j,partialReasons:[{reason:Y.reason,count:Y.count}]}:{total:j}};return H({streams:{page:Q("page"),database:Q("database")}})}search($,Z,Q){let X=this.maybeFail("search");if(X!==null)return X;let z=this.sorted(Z),Y=Q===null?0:Number.parseInt(Q,10);if(Number.isNaN(Y)||Y<0)return C("invalid_argument",`fixture notion: unparseable cursor '${Q}'`);let j=z.slice(Y,Y+this.pageSize),W=Y+j.length,V=W<z.length;return H({items:j,nextCursor:V?String(W):null,hasMore:V})}paginate($,Z){let Q=Z===null?0:Number.parseInt(Z,10);if(Number.isNaN(Q)||Q<0)return C("invalid_argument",`fixture notion: unparseable cursor '${Z}'`);let X=$.slice(Q,Q+this.pageSize),z=Q+X.length,Y=z<$.length;return H({items:X,nextCursor:Y?String(z):null,hasMore:Y})}blockChildren($,Z,Q){let X=this.maybeFail("blocks");if(X!==null)return X;let z=(this.blockKids.get(Z)??[]).map((Y)=>{return{...this.blocksById.get(Y),has_children:(this.blockKids.get(Y)??[]).length>0}});return this.paginate(z,Q)}blockTree($,Z){return y4((Q,X)=>this.blockChildren($,Q,X),Z,{maxDepth:this.blockDepthCap,maxNodes:this.blockNodeCap})}databaseRows($,Z,Q){let X=this.maybeFail("rows");if(X!==null)return X;return this.paginate(this.rowsByDb.get(Z)??[],Q)}comments($,Z,Q){let X=this.maybeFail("comments");if(X!==null)return X;return this.paginate(this.commentsByBlock.get(Z)??[],Q)}users($,Z){let Q=this.maybeFail("users");if(Q!==null)return Q;let X=[...this.userList].sort((z,Y)=>z.user.id<Y.user.id?-1:z.user.id>Y.user.id?1:0);return this.paginate(X,Z)}}var aT;var fL=E(()=>{f();j$();wW();aT=Date.parse("2026-07-01T00:00:00.000Z")});class uW{inner;grantId;pages;constructor($){this.inner=$}bind($){if(this.grantId===void 0)return this.grantId=$.id,H(void 0);return this.grantId===$.id?H(void 0):C("permission_denied","notion starter source cannot mix credential grants","non-retryable")}selected($){let Z=this.bind($);if(!K(Z))return Z;if(this.pages!==void 0)return H(this.pages);let Q=this.inner.search($,"page",null);if(!K(Q))return Q;return this.pages={items:Q.ok.items.slice(0,hW),nextCursor:null,hasMore:!1},H(this.pages)}probe($){let Z=this.bind($);return K(Z)?this.inner.probe($):Z}census($){let Z=this.selected($);return K(Z)?H({streams:{page:{total:Z.ok.items.length},database:{total:0}}}):Z}search($,Z,Q){let X=this.bind($);if(!K(X))return X;if(Q!==null)return C("invalid_argument","notion starter source has one bounded page","non-retryable");if(Z==="page")return this.selected($);return H({items:[],nextCursor:null,hasMore:!1})}blockChildren($,Z,Q){let X=this.bind($);if(!K(X))return X;if(Q!==null)return C("invalid_argument","notion starter source has no block page token","non-retryable");return H({items:[],nextCursor:null,hasMore:!1})}blockTree($,Z){let Q=this.bind($);return K(Q)?H([]):Q}databaseRows($,Z,Q){let X=this.bind($);if(!K(X))return X;if(Q!==null)return C("invalid_argument","notion starter source has no database row page token","non-retryable");return H({items:[],nextCursor:null,hasMore:!1})}comments($,Z,Q){let X=this.bind($);if(!K(X))return X;if(Q!==null)return C("invalid_argument","notion starter source has no comment page token","non-retryable");return H({items:[],nextCursor:null,hasMore:!1})}users($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","notion starter source has no user page token","non-retryable");return H({items:[],nextCursor:null,hasMore:!1})}}var hW=10;var kL=E(()=>{f();j$()});var wL;var mL=E(()=>{wL={research:{candidates:[{repo:"makenotion/notion-sdk-js (@notionhq/client)",recency:0.95,commits:0.85,comprehensiveness:0.95,maintenance:0.95},{repo:"makenotion/notion-mcp-server",recency:0.9,commits:0.85,comprehensiveness:0.85,maintenance:0.85},{repo:"suekou/mcp-notion-server",recency:0.6,commits:0.5,comprehensiveness:0.6,maintenance:0.5}],chosen:"from-scratch",rationale:"Leaf import law (REPO-STRUCTURE \xA72.3) forbids importing or vendoring ANY third-party package \u2014 a connector leaf may import only @indra/contracts + @indra/connector-framework + builtins \u2014 so neither the official @notionhq/client SDK nor any notion MCP server can be wrapped. INDRA v0 needs READ ingestion of EVERY data class the fetch-all doctrine (connectors \xA72.4) requires: POST /v1/search (page/database metadata) + GET /v1/users/me (the probe), AND the actual CONTENT \u2014 GET /v1/blocks/{id}/children descended RECURSIVELY (the full block tree IS a page's body), POST /v1/databases/{id}/query (every row), GET /v1/comments?block_id= (comments), GET /v1/users (the directory). This is the documented READ surface, never the write path (POST/PATCH pages, POST comments \u2014 those are the \xA72.3c action review, out of v0). An SDK adds a supply-chain surface for a REST client the leaf law forbids anyway, and the from-scratch client is a few dozen lines per endpoint behind ONE injected transport (which is ALSO what makes the wire gate testable without a socket \u2014 the same transport carries the content endpoints). So from-scratch over the stdlib fetch shape is the lowest-risk option (wrapsThirdParty:false) and the only one compatible with tier 'api' + the G1 wire gate. Content magnitude with no count endpoint (blocks/rows/comments/users) reconciles by pagination-exhaustion (\xA72.4 'enumerated N'), never a faked census total.",refs:["https://developers.notion.com/reference/intro \u2014 Notion REST API reference (the surface built against)","https://developers.notion.com/reference/post-search \u2014 POST /v1/search: object filter + start_cursor/next_cursor/has_more pagination","https://developers.notion.com/reference/get-self \u2014 GET /v1/users/me (the probe.op 'users.me')","https://developers.notion.com/reference/get-block-children \u2014 GET /v1/blocks/{id}/children: the block tree, has_children RECURSION","https://developers.notion.com/reference/post-database-query \u2014 POST /v1/databases/{id}/query: every row (a page object)","https://developers.notion.com/reference/retrieve-a-comment \u2014 GET /v1/comments?block_id=: page/block comments","https://developers.notion.com/reference/get-users \u2014 GET /v1/users: the workspace directory","https://developers.notion.com/reference/versioning \u2014 the Notion-Version header (pinned 2022-06-28)","https://github.com/makenotion/notion-sdk-js \u2014 @notionhq/client (API-shape reference, NOT vendored: leaf law)","https://github.com/makenotion/notion-mcp-server \u2014 the reference MCP server (surveyed, not wrapped: leaf law + write-path weight)","connectors \xA72.3 \u2014 leaf import law: connectors/<source> may import only contracts + framework"]},supplyChain:{wrapsThirdParty:!1},discovered:{pin:"notion-api@2022-06-28",schemas:[{name:"POST /v1/search (object filter, cursor pagination)",kind:"openapi"},{name:"GET /v1/users/me (credential probe)",kind:"openapi"},{name:"GET /v1/blocks/{id}/children (the block tree, has_children recursion)",kind:"openapi"},{name:"POST /v1/databases/{id}/query (database rows)",kind:"openapi"},{name:"GET /v1/comments?block_id= (comments)",kind:"openapi"},{name:"GET /v1/users (the workspace directory)",kind:"openapi"}],identityFacts:[{stream:"page",fact:"the page `id` is a durable UUID (idField 'id'); content orders revisions (head-compare) because last_edited_time is minute-granular; no read-path tombstone (no deleteKind)",citation:"developers.notion.com object model + reference/versioning (minute-granular timestamps); connectors \xA72.2 durable/head-compare"},{stream:"database",fact:"the database `id` is a durable UUID (idField 'id'); title is the top-level rich-text array; content orders revisions (head-compare), minute-granular last_edited_time; no read-path tombstone",citation:"developers.notion.com database object; connectors \xA72.2 durable/head-compare"},{stream:"block",fact:"the block `id` is a durable UUID (idField 'id'); fetched via GET /v1/blocks/{id}/children and descended RECURSIVELY on has_children; content orders revisions (head-compare), minute-granular last_edited_time; no read-path tombstone",citation:"developers.notion.com/reference/get-block-children + block object; connectors \xA72.2 durable/head-compare, \xA72.4 fetch-all"},{stream:"dbrow",fact:"a database row IS a page object \u2014 durable UUID (idField 'id'); fetched via POST /v1/databases/{id}/query; its properties are the cell values; head-compare on minute-granular last_edited_time; no read-path tombstone",citation:"developers.notion.com/reference/post-database-query (rows are page objects); connectors \xA72.2 durable/head-compare"},{stream:"comment",fact:"the comment `id` is a durable UUID (idField 'id'); fetched via GET /v1/comments?block_id=; body is rich_text, created_by the commenter; head-compare (content-addressed); no read-path tombstone",citation:"developers.notion.com/reference/retrieve-a-comment + comment object; connectors \xA72.2 durable/head-compare"},{stream:"user",fact:"the user `id` is a durable UUID (idField 'id'); fetched via GET /v1/users; the user object carries NO temporal field, so head-compare (content-addressed) is the ONLY honest revision authority and the event ts is the fetch-time observation instant (kept out of payload so unchanged users head-noop)",citation:"developers.notion.com/reference/get-users + user object (no last_edited_time); connectors \xA72.2 head-compare, \xA72.4 (ts requirement)"}]},identity:{perStream:[{stream:"page",citation:"durable UUID (idField 'id') \u2014 developers.notion.com object model; revOrder head-compare \u2014 last_edited_time minute granularity (connectors \xA72.2)"},{stream:"database",citation:"durable UUID (idField 'id') \u2014 developers.notion.com database object; revOrder head-compare \u2014 minute-granular last_edited_time (connectors \xA72.2)"},{stream:"block",citation:"durable UUID (idField 'id') \u2014 developers.notion.com block object; revOrder head-compare \u2014 minute-granular last_edited_time; the recursive block tree IS the page content (\xA72.4)"},{stream:"dbrow",citation:"durable UUID (idField 'id') \u2014 a database row is a page object (post-database-query); revOrder head-compare \u2014 minute-granular last_edited_time (connectors \xA72.2)"},{stream:"comment",citation:"durable UUID (idField 'id') \u2014 developers.notion.com comment object; revOrder head-compare (content-addressed, minute-granular) (connectors \xA72.2)"},{stream:"user",citation:"durable UUID (idField 'id') \u2014 developers.notion.com user object; revOrder head-compare \u2014 NO temporal field, so content is the only honest authority (connectors \xA72.2)"}]},classification:{rows:[]}}});var hL={};h0(hL,{refuseNotionAction:()=>vL,extractTitle:()=>L2,extractMentions:()=>I4,extractBlockText:()=>yW,createNotionConnector:()=>bL,collectBlockTree:()=>y4,WAN_GATE:()=>M2,StarterNotionSource:()=>uW,NOTION_VERSION:()=>D2,NOTION_V0_READ_ONLY_GATE:()=>RW,NOTION_USER_STREAM:()=>j8,NOTION_USER_KIND:()=>O4,NOTION_STARTER_PAGE_LIMIT:()=>hW,NOTION_SOURCE:()=>y5,NOTION_PULL_CAP:()=>bW,NOTION_PAGE_STREAM:()=>VZ,NOTION_PAGE_SIZE:()=>vW,NOTION_PAGE_KIND:()=>A4,NOTION_OBJECT_TYPES:()=>gW,NOTION_MAX_PAGES:()=>HZ,NOTION_MAX_BLOCK_DEPTH:()=>BZ,NOTION_MANIFEST:()=>G2,NOTION_DBROW_STREAM:()=>z8,NOTION_DBROW_KIND:()=>S4,NOTION_DATABASE_STREAM:()=>KZ,NOTION_DATABASE_KIND:()=>_4,NOTION_CONTENT_PAGE_SIZE:()=>qZ,NOTION_COMMENT_STREAM:()=>Y8,NOTION_COMMENT_KIND:()=>R4,NOTION_BLOCK_STREAM:()=>X8,NOTION_BLOCK_NODE_CAP:()=>JZ,NOTION_BLOCK_KIND:()=>T4,NOTION_ARTIFACTS:()=>wL,NOTION_API_BASE:()=>EW,HttpNotionSource:()=>P2,GATED_WAN_TRANSPORT:()=>fW,GATED_CREDENTIAL_HEADERS:()=>kW,FixtureNotionSource:()=>mW});var uL=E(()=>{OW();gL();wW();fL();kL();mL()});function pL($){return W$(`wechat action '${$}'`,pW)}var W8="wechat",q9="message",H9="contact",B9="chatroom",rT="artifact",tT="record",F2,pW="connectors.md \xA72.3c classification review \u2014 wechat v0 declares zero ActionContracts (read-only local-DB ingestion); a WeChat send would be dispatch/world/quoted-only per \xA75 and requires independent reviewer re-derivation before it is callable";var lW=E(()=>{j$();F2={source:W8,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:[],multiAccount:!1,probe:{op:"chatlog-info"}},tccPermissions:["full-disk"],vendored:{repo:"github.com/sjzar/chatlog",commit:"74e568085b8ae5aa3ec72dcd37aac6da969fa121",license:"Apache-2.0",scanReport:"src/VENDORING.md"},streams:[{stream:q9,kinds:["im.message"],identity:{quality:"container-scoped",epochField:"talker"},revOrder:"event-ts"},{stream:H9,kinds:["im.contact"],identity:{quality:"durable",idField:"userName"},revOrder:"head-compare"},{stream:B9,kinds:["im.chatroom"],identity:{quality:"durable",idField:"name"},revOrder:"head-compare"},{stream:rT,kinds:["localfile.observed"],identity:{quality:"durable",idField:"fileId"},revOrder:"upstream-version",revField:"backupGeneration"},{stream:tT,kinds:["localdata.observed"],identity:{quality:"durable",idField:"recordId"},revOrder:"upstream-version",revField:"backupGeneration"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"pagination-exhaustion",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"banning"}});function $5($){return typeof $==="string"?$.trim():""}function eT($){return $5($.content)||$5($.text)||$5($.msg)||$5($.message)}function cW($){let Z=eT($);return Z!==""?Z:`WeChat message ${String($.seq)}`}function dW($){return $5($.remark)||$5($.nickName)||$5($.alias)||$.userName}function nW($){return $5($.remark)||$5($.nickName)||$.name}function A2($,Z,Q){return Z!==""?[{role:Q,raw:Z,handle:{ns:$,value:Z}}]:[]}function $S($){return[...A2("wechat-user",$5($.sender),"actor"),...A2("wechat-chat",$.talker,"participant")]}function ZS($){return X5($)}function lL($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:F2,discover(X){let z=$.probe(X);if(!K(z))return z;return H({asOf:Q(),streams:{[q9]:{method:"pagination-exhaustion"},[H9]:{method:"pagination-exhaustion"},[B9]:{method:"pagination-exhaustion"}}})},pull(X,z){let Y=$.snapshot(X);if(!K(Y))return Y;let j=[];for(let W of Y.ok.messages)j.push({streamRef:q9,raw:W});for(let W of Y.ok.contacts)j.push({streamRef:H9,raw:W});for(let W of Y.ok.chatrooms)j.push({streamRef:B9,raw:W});return H({items:j,next:null,exhausted:!0})},normalize(X){switch(X.streamRef){case q9:{let z=X.raw,Y=ZS(z.time);return{nk:{source:W8,stream:q9,sourceId:String(z.seq),rev:Y},ts:Y,tier:"local-app",kind:"im.message",schemaVersion:1,mentions:$S(z),body:cW(z),payload:z}}case H9:{let z=X.raw;return{nk:{source:W8,stream:H9,sourceId:z.userName},ts:N2,tier:"local-app",kind:"im.contact",schemaVersion:1,mentions:A2("wechat-user",z.userName,"participant"),body:dW(z),payload:z}}case B9:{let z=X.raw;return{nk:{source:W8,stream:B9,sourceId:z.name},ts:N2,tier:"local-app",kind:"im.chatroom",schemaVersion:1,mentions:A2("wechat-chat",z.name,"participant"),body:nW(z),payload:z}}default:throw Error(`wechat normalize: undeclared streamRef '${X.streamRef}'`)}}}}var N2="1970-01-01T00:00:00.000Z";var cL=E(()=>{f();lW()});function XS($){let Z;try{Z=new URL($)}catch{return C("invalid_argument",`chatlog base URL '${$}' is not parseable`)}if(Z.protocol!=="http:"&&Z.protocol!=="https:")return C("invalid_argument",`chatlog base URL '${$}' must be http(s), got '${Z.protocol}'`);if(!QS.has(Z.hostname))return C("invalid_argument",`chatlog base URL host '${Z.hostname}' is not loopback; WeChat chatlog is a local-app source, never an outbound transport`);return Z.hash="",Z.search="",H(Z.toString().replace(/\/$/,""))}function zS($,Z){try{return H(JSON.parse($))}catch{return C("internal",`chatlog ${Z}: response is not JSON -- REST-surface drift (FM-19)`)}}function YS($,Z,Q){if($===200)return zS(Z,Q);if($===401||$===403)return C("permission_denied",`chatlog ${Q} returned HTTP ${$} -- local permission/key not available`);if($===404)return C("not_found",`chatlog ${Q} returned HTTP 404 -- endpoint or local DB missing`);if($===423)return C("failed_precondition",`chatlog ${Q} returned HTTP 423 -- WeChat database is locked/not decrypted`);if($>=500)return C("unavailable",`chatlog ${Q} returned HTTP ${$}`,"transient");return C("internal",`chatlog ${Q} returned HTTP ${$} -- REST-surface drift (FM-19)`)}function dL($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function jS($,Z){if(dL($)&&Array.isArray($.items))return H($.items);return C("internal",`chatlog ${Z}: response is not {items:[...]} -- REST-surface drift (FM-19)`)}function WS($,Z){if(Array.isArray($))return H($);if(dL($)&&Array.isArray($.items))return H($.items);return C("internal",`chatlog ${Z}: response is not a message array -- REST-surface drift (FM-19)`)}function VS(...$){for(let Z of $)if(typeof Z==="string"&&Z.trim()!=="")return Z.trim();return""}function KS($){return VS($.talker,$.userName,$.name)}function qS($){return typeof $.userName==="string"&&$.userName!==""}function HS($){return typeof $.name==="string"&&$.name!==""}function BS($){return $.talker!==""&&(typeof $.seq==="string"||typeof $.seq==="number")&&typeof $.time==="string"&&$.time!==""}class T2{base;get;constructor($,Z){this.base=$;this.get=Z}static create($={}){let Z=XS($.baseUrl??iW);if(!K(Z))return Z;return H(new T2(Z.ok,$.transport??sW))}request($,Z){let Q=this.get(`${this.base}${$}`);if(!Q.ok){let X=Q.code??"unavailable",z=Q.retryability??(X==="unavailable"?"transient":"non-retryable"),Y=X==="unavailable"?" -- ensure the repo-vendored chatlog service can start from packages/connectors/wechat/vendor/github.com/sjzar/chatlog@v0.0.26 (data-key/SIP failures must stay loud; see packages/connectors/wechat/src/VENDORING.md). NEVER an empty success (FM-21)":" -- typed startup failure; auth failures route to AUTH_BLOCKED, never an empty sync (FM-21)";return C(X,`chatlog ${Z} is unreachable at ${this.base}: ${Q.error}${Y}`,z)}return YS(Q.status,Q.body,Z)}probe($){let Z=this.request("/api/v1/session","probe sessions");if(!K(Z))return Z;return H({ready:!0})}listItems($,Z){let Q=this.request($,Z);if(!K(Q))return Q;return jS(Q.ok,Z)}messagesForTalker($){let Z=[],Q=0;for(;;){let X=`/api/v1/chatlog?talker=${encodeURIComponent($)}&time=all&format=json&limit=${E4}&offset=${Q}`,z=this.request(X,`messages for '${$}'`);if(!K(z))return z;let Y=WS(z.ok,`messages for '${$}'`);if(!K(Y))return Y;for(let j of Y.ok)Z.push({...j,talker:j.talker??$});if(Z.length>_2)return C("resource_exhausted",`chatlog pull exceeded ${_2} messages -- refusing a partial snapshot (FM-18)`);if(Y.ok.length<E4)break;Q+=E4}return H(Z)}snapshot($){let Z=this.listItems("/api/v1/contact","contacts");if(!K(Z))return Z;if(!Z.ok.every(qS))return C("internal","chatlog contacts contain a row without userName -- REST-surface drift (FM-19)");let Q=this.listItems("/api/v1/chatroom","chatrooms");if(!K(Q))return Q;if(!Q.ok.every(HS))return C("internal","chatlog chatrooms contain a row without name -- REST-surface drift (FM-19)");let X=this.listItems("/api/v1/session","sessions");if(!K(X))return X;let z=[];for(let Y of X.ok){let j=KS(Y);if(j==="")return C("internal","chatlog sessions contain a row without talker/userName/name -- REST-surface drift (FM-19)");let W=this.messagesForTalker(j);if(!K(W))return W;z.push(...W.ok)}if(!z.every(BS))return C("internal","chatlog messages contain a row without talker/seq/time -- REST-surface drift (FM-19)");return H({messages:z,contacts:Z.ok,chatrooms:Q.ok})}}var iW="http://127.0.0.1:5030",E4=2000,_2=500000,QS,sW=($)=>{let Z=Bun.spawnSync(["curl","-sS","--max-time","20",$],{stdout:"pipe",stderr:"pipe"});if((Z.exitCode??1)!==0){let Q=Z.stderr.toString().trim();return{ok:!1,error:Q!==""?Q:`curl exit ${Z.exitCode??"?"}`}}return{ok:!0,status:200,body:Z.stdout.toString()}};var nL=E(()=>{f();j$();QS=new Set(["127.0.0.1","localhost","::1","[::1]"])});class oW{messages=[];contacts=[];chatrooms=[];failure=null;failureAt="all";tMs=iL;seq=1000000000000;fail($,Z="all"){this.failure=$,this.failureAt=Z}plantMessage($={}){this.tMs+=1000,this.seq+=1;let Z={talker:$.talker??"wxid_alice",seq:$.seq??String(this.seq),time:$.time??new Date(this.tMs).toISOString(),sender:$.sender??"wxid_bob",type:$.type??1,content:$.content??"hello from WeChat",...$};return this.messages.push(Z),Z}plantContact($={}){let Q={userName:$.userName??`wxid_contact_${this.contacts.length+1}`,nickName:$.nickName??`Contact ${this.contacts.length+1}`,...$};return this.contacts.push(Q),Q}plantChatroom($={}){let Q={name:$.name??`${this.chatrooms.length+1}@chatroom`,nickName:$.nickName??`Room ${this.chatrooms.length+1}`,...$};return this.chatrooms.push(Q),Q}failed(){switch(this.failure){case"permission_denied":return C("permission_denied","fixture chatlog: local permission/key denied -- never empty");case"internal":return C("internal","fixture chatlog: REST-surface drift");case"unavailable":default:return C("unavailable","fixture chatlog: server unavailable -- NEVER an empty success","transient")}}probe($){if(this.failure!==null&&(this.failureAt==="all"||this.failureAt==="probe"))return this.failed();return H({ready:!0})}snapshot($){if(this.failure!==null&&(this.failureAt==="all"||this.failureAt==="snapshot"))return this.failed();return H({messages:this.messages.map((Z)=>({...Z})),contacts:this.contacts.map((Z)=>({...Z})),chatrooms:this.chatrooms.map((Z)=>({...Z}))})}}function sL($){return new Date(iL+$).toISOString()}var iL;var oL=E(()=>{f();j$();iL=Date.parse("2026-07-01T00:00:00.000Z")});import{existsSync as rL,readdirSync as JS}from"fs";import{homedir as GS}from"os";import{join as GZ,parse as US,resolve as tL}from"path";function eL($){return rL(GZ($,"db_storage","message","message_0.db"))}function aL($,Z){let Q=new Set,X=[];for(let z of $){let Y=tL(z),j=Z==="win32"?Y.toLowerCase():Y;if(Q.has(j))continue;Q.add(j),X.push(Y)}return X}function LS($){let Z=[$,GZ($,"Documents")],Q=US($).root;if(Q!=="")Z.push(Q);for(let X=65;X<=90;X+=1)Z.push(`${String.fromCharCode(X)}:\\`);return Z}function DS($){if(!rL($))return H([]);try{return H(JS($,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&Z.name.startsWith("wxid_")).map((Z)=>GZ($,Z.name)).filter(eL))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);return C("unavailable",`wechat data directory '${$}' could not be enumerated: ${Q}`,"transient")}}function $D($){let Z=$.override?.trim()??process.env.ZORTEX_WECHAT_CHATLOG_BIN?.trim();if(Z!==void 0&&Z!=="")return Z;let Q=$.platform??process.platform,X=GZ($.appRoot,"packages","connectors","wechat",".bin","chatlog");if(Q==="win32")return`${X}.exe`;return X}function ZD($={}){let Z=$.platform??process.platform,Q=$.explicitDataDir?.trim()??process.env.ZORTEX_WECHAT_DATA_DIR?.trim();if(Q!==void 0&&Q!==""){let W=tL(Q);return H(eL(W)?{state:"ready",path:W,source:"explicit"}:{state:"missing",checked:1})}if(Z!=="darwin"&&Z!=="win32")return H({state:"unsupported",platform:Z});let X=$.homeDir??GS(),z=Z==="darwin"?[GZ(X,"Library","Containers","com.tencent.xinWeChat","Data","Documents","xwechat_files")]:($.searchRoots??LS(X)).map((W)=>GZ(W,"xwechat_files")),Y=[];for(let W of z){let V=DS(W);if(!K(V))return V;Y.push(...V.ok)}let j=aL(Y,Z);if(j.length===0)return H({state:"missing",checked:aL(z,Z).length});if(j.length>1)return H({state:"ambiguous",candidates:j.length});return H({state:"ready",path:j[0],source:"discovered"})}function QD($=process.platform){if($==="darwin")return"darwin";if($==="win32")return"windows";return null}var XD=E(()=>{f();j$()});var zD;var YD=E(()=>{zD={research:{candidates:[{repo:"sjzar/chatlog",recency:0.95,commits:0.9,comprehensiveness:0.9,maintenance:0.9},{repo:"xaoyaoo/PyWxDump",recency:0.7,commits:0.7,comprehensiveness:0.85,maintenance:0.6},{repo:"LC044/WeChatMsg",recency:0.7,commits:0.6,comprehensiveness:0.8,maintenance:0.6},{repo:"raw macOS WeChat SQLCipher store (from-scratch)",recency:0.5,commits:0,comprehensiveness:0.5,maintenance:0.2}],chosen:"sjzar/chatlog",rationale:"chatlog is the best base on every \xA76 step-2 axis AND is the right SHAPE for this framework. It (1) does the hard part \u2014 extracts the SQLCipher key from the running WeChat and decrypts the v3/v4 DBs on macOS+Windows \u2014 which is precisely the 'find the existing repo that actually extracts the data' the RESEARCH stage demands and the screenshot attempt skipped; and (2) exposes the result as a LOOPBACK HTTP REST API (127.0.0.1:5030), which is STRUCTURALLY IDENTICAL to activitywatch's aw-server already in this repo: a local HTTP client behind an injected sync transport, loopback-law bounded, tier 'local-app'. Reading the local decrypted DB is NOT protocol automation and NOT injection into WeChat's servers, so \u2014 unlike wechaty/wcferry protocol puppets \u2014 it cannot get the account banned (why 'banning' + 'local-app' is the lawful set, \xA72.1). PyWxDump and WeChatMsg decrypt the same store but are Python (a heavier external runtime), Windows-first, and the wrong shape (a web UI / a batch GUI exporter, not a time-range query API); re-reading the SQLCipher store from scratch would re-implement chatlog's rotating-key cat-and-mouse for zero gain and a fresh FM-25 surface. chatlog is a single Go binary shelled to as an external PROCESS (never an npm dep), Apache-2.0, actively maintained, and ships REST + MCP \u2014 INDRA rides the REST surface. Live-verified this fabrication: chatlog installs, auto-detects WeChat v4 + the real data_dir, and binds the loopback API; see the tierDecision pins + VENDORING.md for the v4/SIP key-extraction blocker and the human step.",refs:["https://github.com/sjzar/chatlog \u2014 Go: key extraction + SQLCipher decrypt (WeChat v3/v4, macOS+Windows) + loopback HTTP REST API + MCP; the chosen base (Apache-2.0)","https://github.com/sjzar/chatlog/blob/main/internal/chatlog/http/route.go \u2014 the REAL routes: GET /api/v1/{chatlog,contact,chatroom,session} (pinned @v0.0.26)","https://github.com/sjzar/chatlog/blob/main/internal/model/message.go \u2014 the REAL message JSON: seq/time/talker/sender/isSelf/type/content (identity source: Seq = per-talker '10\u4F4D\u65F6\u95F4\u6233 + 3\u4F4D\u5E8F\u53F7')","https://github.com/xaoyaoo/PyWxDump \u2014 Python: DB decrypt + key extraction + web viewer (surveyed; heavier runtime, Windows-first, viewer-not-API)","https://github.com/LC044/WeChatMsg \u2014 Python: decrypt + export chat history to HTML/CSV with a GUI (surveyed; batch exporter, not a query service)","connectors \xA75 \u2014 the General Connector (D9 rungs 5\u20136): promote a working extraction into a named connector with full manifest v2","connectors \xA78.5 \u2014 WeChat posture pin: protocol automation \u2192 bans \u2192 the LOCAL decrypted-DB read is the lawful high-fidelity path (tier 'local-app', not the banned protocol tiers)"]},supplyChain:{wrapsThirdParty:!0,license:"Apache-2.0",scanReport:"src/VENDORING.md"},discovered:{pin:"github.com/sjzar/chatlog@74e568085b8ae5aa3ec72dcd37aac6da969fa121",schemas:[],identityFacts:[{stream:"message",fact:"the message JSON carries `seq` (int64), `time` (RFC3339), `talker` (chat/room id), `sender` (wxid), `isSelf`, `type`, `subType`, `content`. `seq` is the identity token, documented '\u6D88\u606F\u5E8F\u53F7\uFF0C10\u4F4D\u65F6\u95F4\u6233 + 3\u4F4D\u5E8F\u53F7' (a per-message sequence = 10-digit timestamp + 3-digit counter): it orders + is unique WITHIN one talker, but is NOT documented globally unique across talkers \u2192 container-scoped, epoch = `talker` (framework prefixes \u2192 `<talker>:<seq>`). A message is immutable once delivered (a recall is a NEW system message, not an edit) \u2192 revOrder 'event-ts', rev := the message time (UTC 'Z'). No deleteKind (no observable tombstone). Honest bound: a chat-clear/migration can re-mint seq \u2192 FM-18 duplicate-object signal.",citation:"chatlog@v0.0.26 internal/model/message.go (Message.Seq/.Time/.Talker/.Sender) + internal/chatlog/http/route.go (GET /api/v1/chatlog); connectors \xA72.2 container-scoped default"},{stream:"contact",fact:"the contact JSON carries `userName` (the wxid, the Contact table PRIMARY KEY), `alias`, `remark`, `nickName`, `isFriend`. `userName` is a STABLE durable id (idField), but the record MUTATES (remark/nickname) with no version token \u2192 revOrder 'head-compare' (the appender records a new revision only on a real content change). No deleteKind \u2014 the contact list is a current-state snapshot.",citation:"chatlog@v0.0.26 internal/model/contact.go (Contact.UserName PRIMARY KEY) + route.go (GET /api/v1/contact \u2192 {items:[\u2026]}); connectors \xA72.2 durable + \xA78 drill 4 head-compare"},{stream:"chatroom",fact:"the chatroom JSON carries `name` (the '\u2026@chatroom' id, the ChatRoom table PRIMARY KEY), `owner`, `users:[{userName,displayName}]`, `remark`, `nickName`. `name` is a STABLE durable id (idField); the record MUTATES (member list / display name) with no version token \u2192 revOrder 'head-compare'. The `users` list is a source-native participant list \u2192 mechanical participant mentions (I-2). No deleteKind.",citation:"chatlog@v0.0.26 internal/model/chatroom.go (ChatRoom.Name PRIMARY KEY, ChatRoomUser) + route.go (GET /api/v1/chatroom \u2192 {items:[\u2026]}); connectors \xA72.2 durable"},{stream:"artifact",fact:"Apple Manifest.db fileID is durable within a backup generation; backupGeneration is the immutable upstream revision.",citation:"discovered/ios-backup-schema-2026-07-30.json manifest.table, manifest.columns, and identityFacts"},{stream:"record",fact:"A generic row ID is backup-generation scoped source fileID + table + declared primary key or stable row ordinal; backupGeneration is the immutable upstream revision.",citation:"discovered/ios-backup-schema-2026-07-30.json identityFacts record and complete prepared-row reconciliation"}]},identity:{perStream:[{stream:"message",citation:"container-scoped, epoch 'talker' \u2014 chatlog Message.Seq is a per-talker sequence ('10\u4F4D\u65F6\u95F4\u6233 + 3\u4F4D\u5E8F\u53F7', message.go), unique within a chat but not across chats (connectors \xA72.2 container-scoped default); event-ts ordering (a delivered message is immutable; a recall is a fresh system message, never an edit; no upstream version token)"},{stream:"contact",citation:"durable, idField 'userName' \u2014 the wxid is the Contact PRIMARY KEY (contact.go); head-compare because the record mutates (remark/nickname) with no version token (connectors \xA72.2 durable + \xA78 drill 4)"},{stream:"chatroom",citation:"durable, idField 'name' \u2014 the '\u2026@chatroom' id is the ChatRoom PRIMARY KEY (chatroom.go); head-compare because the member list / display name mutate with no version token"},{stream:"artifact",citation:"discovered/ios-backup-schema-2026-07-30.json: all 22,912 selected Apple manifest rows retain fileID and one backup-generation revision"},{stream:"record",citation:"discovered/ios-backup-schema-2026-07-30.json: generic SQLite rows retain backup generation, Apple fileID, source table, and primary-key/row-ordinal identity"}]},classification:{rows:[]}}});var jD={};h0(jD,{wechatChatlogPlatform:()=>QD,resolveChatlogBinaryPath:()=>$D,renderMessageBody:()=>cW,renderContactBody:()=>dW,renderChatroomBody:()=>nW,refuseWechatAction:()=>pL,fixtureInstant:()=>sL,discoverWechatDataDir:()=>ZD,createWechatConnector:()=>lL,bunCurlGet:()=>sW,WECHAT_V0_READ_ONLY_GATE:()=>pW,WECHAT_SOURCE:()=>W8,WECHAT_METADATA_TS_UNKNOWN:()=>N2,WECHAT_MESSAGE_STREAM:()=>q9,WECHAT_MANIFEST:()=>F2,WECHAT_CONTACT_STREAM:()=>H9,WECHAT_CHATROOM_STREAM:()=>B9,WECHAT_CHATLOG_DEFAULT_BASE:()=>iW,WECHAT_ARTIFACTS:()=>zD,HttpChatlogSource:()=>T2,FixtureChatlogSource:()=>oW,CHATLOG_PULL_CAP:()=>_2,CHATLOG_MESSAGE_PAGE:()=>E4});var WD=E(()=>{lW();cL();nL();oL();XD();YD()});function VD($){return W$(`whatsapp export action '${$}'`,aW)}var v4="whatsapp",J9="message",S2=1048576,b4=10,R2,aW="connectors.md \xA72.3c classification review \u2014 WhatsApp export import declares zero actions";var O2=E(()=>{j$();R2={source:v4,tier:"local-app",auth:{provider:"local",method:"none",scopes:[],multiAccount:!1,probe:{op:"stat-export-file"}},streams:[{stream:J9,kinds:["message.imported"],identity:{quality:"synthetic",synthesizer:"hash"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:60},retaliationRisk:"banning"}});function KD($){let Z=$.replace(PS,"$1$2 REDACTED-credential-assignment");for(let Q of MS)Q.lastIndex=0,Z=Z.replace(Q,"REDACTED-credential-shape");return Z}function qD($){return{manifest:R2,discover(Z){let Q=$.census();if(!K(Q))return Q;return H({asOf:new Date().toISOString(),streams:{[J9]:{total:Q.ok.messages,method:"census"}}})},pull(Z,Q){let X=$.list();if(!K(X))return X;return H({items:X.ok.map((z)=>({streamRef:J9,raw:z})),next:null,exhausted:!0})},normalize(Z){if(Z.streamRef!==J9)throw Error(`whatsapp export normalize: undeclared streamRef '${Z.streamRef}'`);let Q=Z.raw,X=Q.sender===void 0?void 0:KD(Q.sender),z=KD(Q.body);return{nk:{source:v4,stream:J9},ts:Q.observedAt,tier:"local-app",kind:"message.imported",schemaVersion:1,mentions:[],body:X===void 0?z:`${X}: ${z}`,payload:{tailSha256:Q.tailSha256,offset:Q.offset}}},identityInput(Z){return Z.raw.identity}}}var MS,PS;var HD=E(()=>{f();O2();MS=[/\b(?:gh[opusr]_[A-Za-z0-9]{8,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|ya29\.[A-Za-z0-9_-]{8,}|1\/\/[A-Za-z0-9_-]{8,})\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g],PS=/(^|\n)(\s*(?:password|passwd|pwd|secret|token|authorization|api[ _-]?key|client[ _-]?secret|access[ _-]?token|refresh[ _-]?token)\s*[:=])\s*[^\r\n]+/gi});import{createHash as CS}from"crypto";import{closeSync as FS,openSync as NS,readSync as AS,statSync as _S}from"fs";import{extname as TS,resolve as SS}from"path";function xS($){let Z=RS.exec($)??OS.exec($);if(Z===null)return;let Q=Z.groups?.sender?.trim(),X=Z.groups?.body??"";return Q===void 0||Q===""?{body:X}:{body:X,sender:Q}}function rW($,Z,Q=b4){let X=[],z,Y=Z;for(let j of $.matchAll(/([^\r\n]*)(\r\n|\n|\r|$)/g)){let W=j[1]??"",V=j[2]??"";if(W!==""||V!==""){let q=xS(W);if(q!==void 0)z={...q,offset:Y},X.push(z);else if(z!==void 0)z.body+=`${z.body===""?"":`
383
+ `}${W}`}Y+=Buffer.byteLength(W+V)}return X.slice(-Q)}function m0($,Z){return C($,Z,"non-retryable")}class tW{file;maxBytes;maxMessages;loaded;constructor($){this.file=SS($.file),this.maxBytes=$.maxBytes??S2,this.maxMessages=$.maxMessages??b4}census(){let $=this.load();return"ok"in $?H({messages:$.ok.length}):$}list(){return this.load()}load(){if(this.loaded!==void 0)return this.loaded;if(TS(this.file).toLowerCase()!==".txt")return this.loaded=m0("invalid_argument","WhatsApp import requires one user-exported .txt chat file");let $;try{$=_S(this.file)}catch(G){let J=G.code;return this.loaded=J==="ENOENT"?m0("not_found","selected WhatsApp export file was not found"):J==="EACCES"||J==="EPERM"?m0("permission_denied","selected WhatsApp export file is not readable"):m0("internal","could not stat selected WhatsApp export file")}if(!$.isFile())return this.loaded=m0("invalid_argument","selected WhatsApp export must be a regular .txt file");if($.size===0)return this.loaded=m0("invalid_argument","selected WhatsApp export is empty");if(!Number.isSafeInteger($.size)||$.size<0)return this.loaded=m0("internal","selected WhatsApp export has an invalid size");let Z=Math.min($.size,this.maxBytes),Q=$.size-Z,X=Buffer.allocUnsafe(Z),z;try{if(z=NS(this.file,"r"),AS(z,X,0,Z,Q)!==Z)return this.loaded=m0("internal","selected WhatsApp export changed during bounded read")}catch(G){let J=G.code;return this.loaded=J==="EACCES"||J==="EPERM"?m0("permission_denied","selected WhatsApp export file is not readable"):m0("internal","could not read selected WhatsApp export file")}finally{if(z!==void 0)FS(z)}let Y=X.toString("utf8"),j=Y.search(/\r\n|\n|\r/),W=Q===0||j<0?"":Y.slice(0,j+(Y[j]==="\r"&&Y[j+1]===`
384
+ `?2:1)),V=rW(Q===0?Y:Y.slice(W.length),Q+Buffer.byteLength(W),this.maxMessages);if(V.length===0)return this.loaded=m0("invalid_argument","selected file contains no recognized WhatsApp chat records");let q=CS("sha256").update(X).digest("hex"),B=new Date($.mtimeMs).toISOString();return this.loaded=H(V.map((G)=>({...G,identity:`${this.file}\x00${G.offset}`,observedAt:B,tailSha256:q})))}}var RS,OS;var BD=E(()=>{f();j$();O2();RS=/^(?:\u200e|\u200f)?\s*(?:\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4},?\s+\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AaPp][Mm])?)\s+-\s+(?:(?<sender>[^:\r\n]{1,160}):\s*)?(?<body>[\s\S]*)$/,OS=/^\[(?:\d{4}[/.\-]\d{1,2}[/.\-]\d{1,2},?\s+\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AaPp][Mm])?)\]\s*(?:(?<sender>[^:\r\n]{1,160}):\s*)?(?<body>[\s\S]*)$/});var JD={};h0(JD,{refuseWhatsappExportAction:()=>VD,parseWhatsappExport:()=>rW,createWhatsappExportConnector:()=>qD,WHATSAPP_EXPORT_SOURCE:()=>v4,WHATSAPP_EXPORT_READ_ONLY_GATE:()=>aW,WHATSAPP_EXPORT_MESSAGE_STREAM:()=>J9,WHATSAPP_EXPORT_MAX_MESSAGES:()=>b4,WHATSAPP_EXPORT_MAX_BYTES:()=>S2,WHATSAPP_EXPORT_MANIFEST:()=>R2,FileWhatsappExportSource:()=>tW});var GD=E(()=>{O2();HD();BD()});_9();import{createHash as WV}from"crypto";import{join as PZ}from"path";f();import{closeSync as NN,mkdirSync as AN,openSync as _N,readFileSync as TN,unlinkSync as CY,writeSync as SN}from"fs";import{join as e1}from"path";f();f();f();f();function WP($){return $.effect.class==="dispatch"&&$.fuse!=="none"}function VP($,Z){let Q=new Set,X=$.params.properties;if(X!==null&&typeof X==="object"&&!Array.isArray(X))for(let z of Object.keys(X))Q.add(z);for(let z of $.taintFlow??[])Q.add(z.param);for(let z of Object.keys(Z))Q.add(z);return[...Q].sort()}function F7($,Z){let Q=[],X=[],z=WP($);for(let Y of VP($,Z)){let j=$.taintFlow?.find((B)=>B.param===Y),W=wV($,Y);if(W===void 0){X.push(`${Y}: no taintFlow declaration and not a fused dispatch \u2014 falcon policy governs (I-3)`);continue}if(W==="any"){X.push(`${Y}: accepts 'any' under policyRef ${j?.policyRef??"(declared)"} \u2014 the explicit flow permit (I-3)`);continue}let V=j!==void 0?"declared":"fused-dispatch-default",q=Z[Y];if(q===void 0){Q.push({param:Y,rule:V,found:"no provenance recorded \u2014 unknown is not clean (default-deny)"});continue}if(q.level==="untrusted"){Q.push({param:Y,rule:V,found:`untrusted provenance via [${q.sources.join(", ")}]`});continue}X.push(`${Y}: '${q.level}' provenance satisfies untainted-only (${V})`)}if(Q.length>0)return{verdict:"refused",reason:"tainted_param_flow",failures:Q,checked:X};return z?{verdict:"pass",failures:Q,checked:[...X,"parameter-provenance firewall clear (fused dispatch, FM-25)"]}:{verdict:"pass",failures:Q,checked:X}}f();function N7($,Z){return v({code:$,layer:"kernel",retryability:"non-retryable",message:Z})}function A7($,Z){if(!$.actionClasses.includes(Z.actionClass))return N7("permission_denied",`capability firewall (security \xA74.2): worker manifest [${$.actionClasses.join(", ")}] does not declare '${Z.actionClass}'${Z.action!==void 0?` for ${Z.action}`:""} \u2014 capability is fixed at spawn and `+"unreachable from skill text (\xA73.3); undeclared call refused");return H({allowed:!0,actionClass:Z.actionClass})}function _7($){switch($.class){case"read":return H("read");case"create":case"update":case"delete":return H("vault_write");case"dispatch":switch($.category){case"pay":return H("pay");case"post":return H("post");case"send":return H("send");case"delete-at-source":return H("delete_at_source");default:return N7("failed_precondition",`dispatch category '${$.category??"(none)"}' has no frozen worker-class mapping (\xA73.3) \u2014 `+"the worker-type registry must declare the class; capability is never guessed from a name")}default:return N7("failed_precondition",`unknown effect class '${String($.class)}'`)}}var Qq=[{rule:"aws-access-key-id",re:/\bAKIA[0-9A-Z]{16}\b/},{rule:"private-key-block",re:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"github-token",re:/\bgh[pousr]_[A-Za-z0-9]{36}\b/},{rule:"slack-token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/},{rule:"openai-key",re:/\bsk-[A-Za-z0-9_-]{20,}\b/},{rule:"google-api-key",re:/\bAIza[0-9A-Za-z_-]{35}\b/},{rule:"jwt",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/},{rule:"provider secret key (sk-\u2026)",re:/\bsk-[A-Za-z0-9_-]{16,}/},{rule:"google-access (ya29.)",re:/ya29\.[A-Za-z0-9_.\-]{8,}/},{rule:"google-refresh (1//)",re:/\b1\/\/[A-Za-z0-9_\-]{8,}/},{rule:"github classic token (ghp/ghs)",re:/\bgh[ps]_[A-Za-z0-9]{20,}/},{rule:"github (gho_/ghu_/ghr_)",re:/\bgh[our]_[A-Za-z0-9]{8,}/},{rule:"github fine-grained PAT",re:/\bgithub_pat_[A-Za-z0-9_]{20,}/},{rule:"slack legacy (xoxr/xoxs)",re:/\bxox[rs]-[A-Za-z0-9\-]{8,}/},{rule:"slack-rotating (xoxe)",re:/\bxoxe[.\-][A-Za-z0-9\-]{8,}/},{rule:"notion (secret_)",re:/\bsecret_[A-Za-z0-9]{16,}/},{rule:"notion (ntn_)",re:/\bntn_[A-Za-z0-9]{16,}/},{rule:"posthog-personal (phx_)",re:/phx_[A-Za-z0-9_\-]{32,}/},{rule:"google-drive-resource-key",re:/(?:"(?:resourceKey|targetResourceKey)"\s*:\s*"[^"\r\n]{8,}"|[?&]resourcekey=[^&"'\s\\]{8,})/iu},{rule:"bearer credential",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/},{rule:"slack (xox[bpae]-)",re:/\bxox[bpae]-[A-Za-z0-9\-]{8,}/},{rule:"jwt (eyJ)",re:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{4,}/}],KP=Qq.map(($)=>$.rule);function Xq($){if($.length===0)return 0;let Z=new Map;for(let X of $)Z.set(X,(Z.get(X)??0)+1);let Q=0;for(let X of Z.values()){let z=X/$.length;Q-=z*Math.log2(z)}return Q}var T7=/[A-Za-z0-9+/=_-]{32,}/g,qP=4.5;function S7($){return`${$.slice(0,4)}\u2026(${$.length} chars)`}function tZ($,Z=[],Q=256){let X=[],z=!1,Y=(j)=>{if(X.length>=Q)return z=!0,!1;return X.push(j),!0};$:for(let j of Z){if(j.length===0)continue;let W=0;for(;;){let V=$.indexOf(j,W);if(V===-1)break;if(!Y({kind:"canary",class:"named",rule:"planted-canary",excerpt:S7(j),index:V,length:j.length}))break $;W=V+j.length}}if(!z)for(let{rule:j,re:W}of Qq){let V=W.exec($);if(V===null)continue;if(!Y({kind:"secret",class:"named",rule:j,excerpt:S7(V[0]),index:V.index,length:V[0].length}))break}if(!z){T7.lastIndex=0;let j;while((j=T7.exec($))!==null){let W=j[0];if(Xq(W)<=qP)continue;if(!Y({kind:"secret",class:"generic",rule:"high-entropy-token",excerpt:S7(W),index:j.index,length:W.length}))break}T7.lastIndex=0}return{hits:X,capped:z}}var x7="egress.verdict",zq="security.incident";var R7=30000;function Yq($){return $===x7||$.startsWith("grant.")||$.startsWith("trust.")||$.startsWith("anomaly.")}function I7($,Z){if(!Yq($))return H({kind:$});if(Z.kind==="kernel")return H({kind:$});return{err:{code:"permission_denied",layer:"kernel",retryability:"non-retryable",message:`authority-kind writer isolation (security \xA72.2): '${$}' is appendable ONLY by the falcon identity \u2014 `+`an append by origin '${Z.kind}' is an automatic incident (the projections the chokepoint treats as authority must not be writable by the workers the threat model assumes compromised)`}}}function O7($){switch($){case"grant_pending":case"grant_suspended":return"retry-at-higher-level";case"anomaly_block":return"transient";default:return"non-retryable"}}var HP=["pay","post","send","delete-at-source"];class S3{policy;resolve;baselines;canaries;sink;now;fusePolicy;incidentList=[];verdictList=[];alive=!0;anomalyDownIncidentFiled=!1;constructor($){this.policy=$.policy,this.resolve=$.resolve,this.baselines=$.baselines,this.canaries=$.canaries,this.sink=$.sink,this.now=$.now??(()=>new Date().toISOString()),this.fusePolicy=$.fusePolicy??P8}kill($){this.alive=!1}revive(){this.alive=!0}isAlive(){return this.alive}incidents(){return this.incidentList}verdicts(){return this.verdictList}submit($){return H(this.evaluate($,!1).verdict)}submitContained($){return H(this.evaluate($,!0))}expire($){let Z=this.refused("queue_expired","deadline_exceeded",`queued egress for ${$.channel} exceeded its max age \u2014 a stale intent NEVER fires late (security \xA74.4; FM-21 distinct state)`,["queued-egress max age reached; refused rather than fired stale"]);return this.record($,Z)}evaluate($,Z){if(!V3.includes($.channel))return this.atomic(this.record($,this.refused("undeclared_capability","invalid_argument",`unknown egress channel '${String($.channel)}' \u2014 the exits are enumerated (\xA72.1); anything else fails the invariant`,[`channel '${String($.channel)}' is not an enumerated egress channel`])));if($.channel==="diag_donation")return this.atomic(this.record($,this.refused("content_class_fail","failed_precondition","blocked by OQ-23/FM-28: diag_donation is a RESERVED channel \u2014 every request verdicts refused until the T3 per-donation grant flow ships (default-deny holds; the channel exists so the refusal is typed)",["diag_donation reserved until the T3 flow ships"])));let Q=iV($);if(!K(Q)){let V="err"in Q?Q.err.message:"malformed";return this.atomic(this.record($,this.refused("undeclared_capability","invalid_argument",`malformed EgressRequest: ${V}`,[V])))}let X=this.resolve($);if(!K(X)){let V="empty"in X?X.empty.how:("err"in X)?X.err.message:"unresolvable";return this.atomic(this.record($,this.refused("content_class_fail","failed_precondition",`the chokepoint reads bytes, not claims \u2014 payload unresolvable: ${V}`,[V])))}let z=X.ok,Y=tZ(z.bytes,this.canaries),j=null;if(Y.hits.length>0){let V=this.containOrRefuse($,z,Y.hits,Y.capped,Z);if("refusal"in V)return this.atomic(this.record($,V.refusal));j=V.contained}let W=this.route($,z);if(j===null)return this.atomic(this.record($,W));if(W.decision==="refused")return this.atomic(this.record($,W));for(let V of j.ids)this.fileIncident("secret-egress-contained",`high-entropy (generic-class) hit in part '${V}' on ${$.channel} \u2014 part WITHHELD, residue re-scanned and served (\xA74.3a)`);return W.reasons=[...W.reasons,j.reason],{verdict:this.record($,W,{withheld:j.ids.length}),bytes:j.residue,withheld:{count:j.ids.length,ids:j.ids}}}route($,Z){switch($.channel){case"connector_action":return this.connectorAction($,Z);case"gateway_slice":return this.gatewaySlice($,Z);case"fetch_url":return this.fetchUrl(Z);case"channel_notice":return this.channelNotice(Z);case"marketplace_publish":return this.pass(["user-authority pack share; leak scan clear (\xA74.3 marketplace split)"]);case"llm_inference":case"telemetry_aggregate":case"cloud_sync":case"distill_transfer":return this.tierGoverned($.channel,Z);default:return this.refused("undeclared_capability","failed_precondition",`channel '${$.channel}' has no verdict route`,[])}}containOrRefuse($,Z,Q,X,z){let Y=(D,P)=>{let F=`${D.rule} (${D.excerpt})`;return this.fileIncident(D.kind==="canary"?"canary-egress":"secret-egress",`${F} on ${$.channel} \u2014 ${P}`),{refusal:this.refused(D.kind==="canary"?"canary_match":"secret_match","failed_precondition",`egress-side ${D.kind} scan hit: ${F} \u2014 dropped pre-transmit (a worker can COMPUTE a secret into an output, \xA74.3); ${P}`,[F,P])}},j=Q.find((D)=>D.kind==="canary");if(j!==void 0)return Y(j,"a canary hit is never contained (\xA74.3a condition 1)");let W=Q.find((D)=>D.class==="named");if(W!==void 0)return Y(W,"a named (pinned-shape) hit refuses the whole payload (\xA74.3a condition 2)");let V=Q[0];if(!z)return Y(V,"this caller cannot receive a contained residue \u2014 payload treated as atomic (\xA74.3a condition 3)");if(Z.parts===void 0||Z.reserialize===void 0)return Y(V,"payload declares no severable partition \u2014 atomic payloads refuse whole (\xA74.3a condition 3)");if(X)return Y(V,`hit enumeration capped at ${Q.length} \u2014 could not enumerate, so nothing is contained (\xA74.3a condition 4)`);let q=new Set;for(let D of Z.parts)if(tZ(D.bytes,this.canaries,1).hits.length>0)q.add(D.id);if(q.size===0)return Y(V,"the hit belongs to no declared part \u2014 it lives in a seam no item-drop can contain (\xA74.3a condition 5)");let B=Z.parts.filter((D)=>!q.has(D.id)).map((D)=>D.id);if(B.length===0)return Y(V,"every declared part is dirty \u2014 an empty residue is a refusal, never an empty pass (\xA74.3a condition 6)");let G=Z.reserialize(B);if(!K(G)){let D="empty"in G?G.empty.how:("err"in G)?G.err.message:"reserialize failed";return Y(V,`residue could not be re-serialized (${D}) \u2014 refusing whole rather than serving unscanned bytes`)}let J=G.ok,U=tZ(J,this.canaries,1);if(U.hits.length>0)return Y(U.hits[0],"the residue STILL scans dirty after containment \u2014 refusing whole (\xA74.3a condition 7, the residue re-scan)");let L=[...q];return{contained:{residue:J,ids:L,reason:`\xA74.3a containment: ${L.length} generic-class part(s) withheld, residue re-scanned clean and returned verbatim `+"(detector unchanged \u2014 the withheld bytes still never leave)"}}}atomic($){return{verdict:$,bytes:null,withheld:{count:0,ids:[]}}}connectorAction($,Z){let Q=$.contract;if(Q===void 0)return this.refused("undeclared_capability","failed_precondition","connector_action requires the I-3 contract reference (the chokepoint reads the contract's frozen axes)",[]);let X=_7({class:Q.class,...Q.category!==void 0?{category:Q.category}:{}});if(!K(X))return this.refused("undeclared_capability","failed_precondition","err"in X?X.err.message:"no class mapping",[]);if(Z.workerManifest===void 0)return this.refused("undeclared_capability","failed_precondition","no worker manifest resolvable \u2014 capability is falcon-owned and per-call (\xA73.3)",[]);let z=A7(Z.workerManifest,{actionClass:X.ok,action:Q.action});if(!K(z))return this.fileIncident("undeclared-capability","err"in z?z.err.message:"undeclared capability"),this.refused("undeclared_capability","permission_denied","err"in z?z.err.message:"undeclared capability",[`worker manifest does not declare '${X.ok}' for ${Q.action}`]);let Y=Q.class==="dispatch";if(Z.actionContract===void 0||Z.paramProvenance===void 0){if(Y)return this.refused("tainted_param_flow","permission_denied","fused dispatch with no resolvable provenance map \u2014 DEFAULT-DENY: every param of a fused dispatch is untainted-only (\xA73.4), and unknown is not clean",["no AssemblyTrace provenance map for a fused dispatch action"])}else{let B=F7(Z.actionContract,Z.paramProvenance);if(B.verdict==="refused")return this.refused("tainted_param_flow","permission_denied",`parameter-provenance firewall (FM-25/CaMeL): ${B.failures.map((G)=>`${G.param} (${G.found})`).join("; ")} \u2014 checked mechanically, independent of model behavior`,B.failures.map((G)=>`${G.param}: ${G.found}`))}let j=this.fuseKeyFor(Q.category),W=this.fusePolicy.rows[j],V=W.baseMs,q=[`${Q.action}: base fuse ${W.baseMs}ms (fuse-policy@v1 ${j})`];if(this.baselines===null){if(!this.anomalyDownIncidentFiled)this.anomalyDownIncidentFiled=!0;this.fileIncident("anomaly-detector-down","anomaly detector unavailable \u2014 fuses revert to pre-decay defaults; trust degrades toward caution (\xA76)"),q.push("anomaly detector down: default (undecayed) fuse length")}else{let B=this.baselines.scoreEgress({channel:$.channel,...Z.recipient!==void 0?{recipient:Z.recipient}:{},bytes:Z.bytes.length,fuseKey:j});V+=B.fuseExtensionMs;for(let G of B.notes)q.push(G)}if(Q.category==="send"){let B=this.foreignSources(Z);if(B.length>0)V=Math.max(V,R7),q.push(`send context-novelty: payload origins [${B.join(", ")}] are foreign to the thread context \u2014 \u2265${R7}ms by rule (\xA74.3, OQ-19 interim)`)}if(HP.includes(j))V=Math.max(V,W.floorMs);if(V<=0)return this.pass(q);return this.fused(V,q)}fuseKeyFor($){switch($){case"pay":return"pay";case"post":return"post";case"send":return"send";case"delete-at-source":return"delete-at-source";default:return"dispatch-other"}}foreignSources($){if($.taint.level!=="untrusted")return[];let Z=new Set($.contextOrigins??[]);return $.taint.sources.filter((Q)=>!Z.has(Q))}gatewaySlice($,Z){if($.grantId===void 0)return this.refused("scope_violation","failed_precondition","gateway_slice requires a grant reference (\xA73.5) \u2014 scope is the line",[]);if(Z.scope===void 0)return this.refused("scope_violation","failed_precondition","no scope evidence resolvable for the slice",[]);let Q={grantee:Z.scope.grantee,form:Z.scope.form,...Z.scope.kinds!==void 0?{kinds:Z.scope.kinds}:{},...Z.scope.paths!==void 0?{paths:Z.scope.paths}:{}};return this.consultPolicy((X)=>X.scopeVerdict(Q))}tierGoverned($,Z){if(Z.dataTier===void 0)return this.refused("content_class_fail","failed_precondition",`${$} payload carries no data-tier classification \u2014 default-deny (D26 law 2); classify before egress`,[]);let Q={egressChannel:$,dataTier:Z.dataTier,policyVersionOfData:Z.policyVersionOfData??(this.policy?.version()??1),...Z.workload!==void 0?{workload:Z.workload}:{},...Z.payloadKind!==void 0?{payloadKind:Z.payloadKind}:{}};return this.consultPolicy((X)=>X.tierAllow(Q))}fetchUrl($){let Z=$.fetchUrl;if(Z===void 0)return this.refused("source_novelty_block","failed_precondition","fetch_url with no URL evidence \u2014 refused",[]);if(!(Z.verbatimInLevel==="system"||Z.verbatimInLevel==="user"||Z.allowlisted===!0))return this.fileIncident("fetch-url-provenance",`constructed URL '${Z.url}' is not provenance-derived`),this.refused("source_novelty_block","permission_denied",`fetch_url must be provenance-derived (\xA74.3): '${Z.url}' appears in no system/user-taint source and no per-worker-type allowlist \u2014 never constructed from untrusted content`,[`URL '${Z.url}' not provenance-derived`]);return this.pass([`fetch_url '${Z.url}' is provenance-derived (${Z.allowlisted===!0?"allowlisted domain":`verbatim in ${Z.verbatimInLevel}-taint source`})`])}channelNotice($){if($.channelNotice===void 0)return this.pass(["channel_notice: content-free default (D8) \u2014 no content leaves"]);return this.consultPolicyResult((Z)=>Z.channelClass($.channelNotice.channel,$.channelNotice.sendPath),(Z)=>this.pass([`channel_notice ${$.channelNotice.channel}: contentPolicy '${Z.contentPolicy}', e2ee '${Z.e2ee}' (D8/OQ-4)`]))}consultPolicy($){if(this.policy===null)return this.strictest("no policy engine wired");try{return $(this.policy)}catch(Z){return this.strictest(Z instanceof Error?Z.message:String(Z))}}consultPolicyResult($,Z){if(this.policy===null)return this.strictest("no policy engine wired");try{let Q=$(this.policy);if(!K(Q)){let X="err"in Q?Q.err.message:("empty"in Q)?Q.empty.how:"policy refusal";return this.refused("content_class_fail","failed_precondition",X,[X])}return Z(Q.ok)}catch(Q){return this.strictest(Q instanceof Error?Q.message:String(Q))}}strictest($){return this.refused("anomaly_block","unavailable",`policy consult failed (${$}) \u2014 strictest posture: deny (FM-8/21); a policy failure never fails open`,["policy engine unavailable/failed \u2014 strictest posture applied"])}pass($){return{decision:"pass",reasons:$}}fused($,Z){return{decision:"pass_with_fuse",fuseMs:$,reasons:Z}}refused($,Z,Q,X){return{decision:"refused",reason:$,error:{code:Z,layer:"kernel",retryability:O7($),message:Q},reasons:X}}record($,Z,Q){if(Z.decision==="refused"&&Z.reason!==void 0&&Z.error!==void 0)Z.error={...Z.error,retryability:O7(Z.reason)};return this.verdictList.push({request:$,verdict:Z}),this.sink.append({kind:x7,payload:{requestId:$.id,channel:$.channel,decision:Z.decision,...Z.reason!==void 0?{reason:Z.reason}:{},...Z.fuseMs!==void 0?{fuseMs:Z.fuseMs}:{},...Q!==void 0?{containment:{unit:"part",withheld:Q.withheld}}:{},reasons:Z.reasons}},{kind:"kernel"}),Z}fileIncident($,Z){this.incidentList.push({at:this.now(),class:$,detail:Z}),this.sink.append({kind:zq,payload:{class:$,detail:Z}},{kind:"kernel"})}}f();f();F0();var rH={effect:"deny",operations:["network*"],filters:[],because:"security \xA72.1 claim 1 \u2014 workers, plugins and vendored/pack code execute socket-less; "+"the falcon-owned chokepoint is the only network broker, reachable over local IPC"},kF=[{id:"connector-pull",clause:"\xA72.1 exemption (1): connector pull() ingestion traffic on the framework's fast path \u2014 "+"manifest-pinned domains, inside the sandbox, batched (a 10k-item sync cannot pay 50ms \xD7 10k of verdicts)",rules:[{effect:"allow",operations:["network-outbound"],filters:[{kind:"remote-ip",value:"*:443"}],because:"pinned-domain ingestion is HTTPS; the OS rule narrows the exemption to TCP/443 and nothing else"}],notEnforcedByOS:["the manifest-pinned DOMAIN set: Seatbelt filters by address and port, never by hostname. "+"The domain half is proxy/framework-enforced (WR F6 \u2014 allowedDomains rides an external proxy with no TLS inspection), "+"so the compiled profile carries the allowlist as data the chokepoint honours, not as an OS guarantee","residual covert egress via pull query parameters to the LEGITIMATE source domain \u2014 \xA72.1 accepts and names this","`*:443` is open to EVERY host for the life of the spawn, and no OS rule can tell a pull() request from any other TCP/443 connection the process opens. The selection marker narrows WHICH SPAWNS receive this exit (a connector "+"sync run); nothing narrows what code inside such a spawn \u2014 a vendored library, gauntleted pack content \u2014 does "+"with it once open"],compensatingControls:["manifest-pinned domain set (attacker-influenced pull parameters are bounded by it)","the fast path runs inside the sandbox \u2014 batching exempts it from per-request verdicts, not from containment","selection requires the framework-authored `sync` order kind, so no plugin manifest can elect itself into this exit "+"(\xA72.1 claim 1 requires plugins socket-less)"]},{id:"auth-driver-browser",clause:"\xA72.1 exemption (2): auth-driver browser sessions (auth.md \xA75) \u2014 a driven browser is an unverdicted byte channel by nature",rules:[{effect:"allow",operations:["network-outbound"],filters:[{kind:"remote-ip",value:"localhost:*"}],because:"the driver reaches the browser it drives over a loopback automation port; the OS rule narrows this exit to "+"LOOPBACK ADDRESSES \u2014 that, and nothing else, is what it narrows"}],notEnforcedByOS:["the driven browser is a SEPARATE process outside this profile \u2014 its own egress is not contained by this rule at all; "+"\xA72.1 names it an unverdicted byte channel and this transcription does not pretend otherwise","`localhost:*` is EVERY loopback listener on the host, on every port \u2014 not only the browser's automation port. "+"Any local INDRA listener in reach is inside this rule (the indrad IPC socket, the D25 gateway, a local model server): Seatbelt filters an address and a port, so it can name neither the port the driver actually dials nor the process answering it","a local FORWARDING PROXY is a route OFF-HOST reached through a loopback address, so this rule does not mean "+"'nothing routed is opened' \u2014 it means nothing routed is opened DIRECTLY. The address is narrowed; the "+"destination behind it is not"],compensatingControls:["the pinned-domain abort rule (auth.md)","heaviest-tier flight recording of every driver run","the watchdog","zero-ICE-recall isolation","the exit is granted only to a spawn HOLDING the auth-driver/browser-profile runtime lease (falcon \xA74.3 "+"all-or-nothing acquisition) \u2014 never to a worker by default"]},{id:"loopback-listener",clause:"\xA72.1 exemption (3): the RFC 8252 loopback listener (receives redirects; sends nothing)",rules:[{effect:"allow",operations:["network-bind"],filters:[{kind:"local-ip",value:"localhost:*"}],because:"RFC 8252 requires a loopback bind to receive the authorization redirect"},{effect:"allow",operations:["network-inbound"],filters:[{kind:"local-ip",value:"localhost:*"}],because:"the redirect arrives as an inbound loopback connection; off-host reachability stays denied"}],notEnforcedByOS:["'sends nothing' is a property of the listener's protocol, not of any OS rule: network-inbound permits writing on an ACCEPTED connection (the HTTP response back to the browser), and no Seatbelt filter can express send-nothing"],compensatingControls:["the local filter is loopback-only \u2014 the listener cannot be reached off-host","the listener is short-lived and scoped to one RFC 8252 flow"]}];f();f();f();var tH=["pay","post","send","delete-at-source"];function g9($){return tH.includes($)}var eH={artifact:"fuse-policy",version:1,policy:KX},AQ=eH;function wz($){return`fuse-policy@v${$.version}`}if(wz(AQ)!==qX)throw Error(`fuse-policy artifact drift: ${wz(AQ)} != contracts ${qX}`);function S1($){let Z=new Set($.contextSources);return $.payloadSources.filter((Q)=>Q===ZX||!Z.has(Q))}f();import{Database as mF}from"bun:sqlite";f();var N0={intent:"action.intent",recall:"action.recall",executing:"action.executing",effect:"action.effect",failed:"action.failed",unknown:"action.unknown",fuseArmed:"fuse.armed",fuseElapsed:"fuse.elapsed",fuseResumed:"action.fuse_resumed",watchdogChecked:"watchdog.checked",watchdogLate:"watchdog.late"},ZB=Object.values(N0),_Q={source:"zortex",stream:"action",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},QB={[N0.recall]:["user","kernel"],[N0.watchdogChecked]:["kernel"],[N0.watchdogLate]:["kernel"]};function $B($,Z,Q="non-retryable"){return{err:{code:$,layer:"kernel",retryability:Q,message:Z}}}function R1($){return typeof $==="string"&&f5.includes($)}function XB($,Z,Q){return{nk:{source:_Q.source,stream:_Q.stream},ts:Q,tier:"first-party",kind:$,schemaVersion:1,mentions:[],body:"",payload:Z}}function f9($,Z,Q,X,z){let Y=QB[Z];if(Y!==void 0&&!Y.includes(X.kind))return $B("permission_denied",`kind '${Z}' allows origins [${Y.join(", ")}]; origin '${X.kind}' denied (undo-layer \xA73.3 ACL, enforced at the undo writer seam)`);let j=$.append([XB(Z,Q,z)],X);if(!K(j))return j;let W=j.ok[0];if(W===void 0)return $B("internal",`append of '${Z}' returned no result row`,"transient");return H(W.id)}function TQ($){let Z={intentId:$.intent_id,key:$.fuse_key,fuseMs:$.fuse_ms,armedAtAwakeMs:$.armed_awake_ms,executeAfterAwakeMs:$.execute_after_awake_ms,state:$.state,resurfaced:$.resurfaced===1,lateRecall:$.late_recall===1};if($.hold_reason!==null)Z.holdReason=$.hold_reason;return Z}function O$($,Z,Q="non-retryable"){return{err:{code:$,layer:"kernel",retryability:Q,message:Z}}}class SQ{db;closed=!1;constructor($){this.db=$}static open($,Z){let Q=new mF($,{create:!0});Q.exec("PRAGMA journal_mode = WAL"),Q.exec("PRAGMA synchronous = FULL"),Q.exec(`CREATE TABLE IF NOT EXISTS fuse_deadlines (
385
+ intent_id TEXT PRIMARY KEY,
386
+ fuse_key TEXT NOT NULL,
387
+ fuse_ms INTEGER NOT NULL,
388
+ armed_awake_ms INTEGER NOT NULL,
389
+ execute_after_awake_ms INTEGER NOT NULL,
390
+ state TEXT NOT NULL,
391
+ resurfaced INTEGER NOT NULL DEFAULT 1,
392
+ late_recall INTEGER NOT NULL DEFAULT 0,
393
+ hold_reason TEXT
394
+ )`),Q.exec("CREATE TABLE IF NOT EXISTS fuse_clock (k TEXT PRIMARY KEY, v TEXT NOT NULL)");let X=new SQ(Q),z=X.metaGet("phase"),Y,j=0;if(z===null)X.metaSet("awake_ms","0"),X.metaSet("last_wall_ms",String(Z)),X.metaSet("phase","awake"),Y="awake";else j=Math.max(0,Z-Number(X.metaGet("last_wall_ms")??Z)),X.metaSet("phase","recovering"),Y="recovering";return{store:X,phase:Y,gapMs:j}}close(){if(!this.closed)this.db.close(),this.closed=!0}metaGet($){return this.db.query("SELECT v FROM fuse_clock WHERE k = ?").get($)?.v??null}metaSet($,Z){this.db.query("INSERT OR REPLACE INTO fuse_clock (k, v) VALUES (?, ?)").run($,Z)}phase(){return this.metaGet("phase")??"awake"}awakeNowMs(){return Number(this.metaGet("awake_ms")??"0")}tick($){let Z=this.phase();if(Z!=="awake")return O$("failed_precondition",`tick refused in phase '${Z}' \u2014 awake time cannot pass inside a gap (I-3 step 5)`);let Q=Number(this.metaGet("last_wall_ms")??String($)),X=Math.max(0,$-Q),z=this.awakeNowMs()+X;return this.metaSet("awake_ms",String(z)),this.metaSet("last_wall_ms",String($)),H(z)}sleepBegan($){let Z=this.tick($);if(!("ok"in Z))return Z;return this.metaSet("phase","asleep"),H(Z.ok)}reconcile($){if(this.phase()==="awake")return H({gapMs:0,resurface:[]});let Q=Number(this.metaGet("last_wall_ms")??String($)),X=Math.max(0,$-Q);return this.metaSet("last_wall_ms",String($)),this.db.query("UPDATE fuse_deadlines SET resurfaced = 0 WHERE state = 'ARMED'").run(),this.metaSet("phase","awake"),H({gapMs:X,resurface:this.armed()})}markResurfaced($){if(this.db.query("UPDATE fuse_deadlines SET resurfaced = 1 WHERE intent_id = ? AND state = 'ARMED'").run($).changes===0)return O$("not_found",`no ARMED deadline for intent ${$}`);return H(!0)}arm($,Z,Q){if(!q$($))return O$("invalid_argument",`arm: intentId must be a ULID (got '${String($)}')`);if(!R1(Z))return O$("invalid_argument",`arm: unknown fuse key '${String(Z)}'`);if(!Number.isInteger(Q)||Q<0)return O$("invalid_argument","arm: fuseMs must be a non-negative integer");if(this.phase()!=="awake")return O$("failed_precondition",`arm refused in phase '${this.phase()}' \u2014 reconcile the gap first (falcon \xA74.1 order)`);if(this.rawGet($)!==null)return O$("already_exists",`deadline for intent ${$} already armed`);let z=this.awakeNowMs();return this.db.query(`INSERT INTO fuse_deadlines (intent_id, fuse_key, fuse_ms, armed_awake_ms, execute_after_awake_ms, state, resurfaced, late_recall)
395
+ VALUES (?, ?, ?, ?, ?, 'ARMED', 1, 0)`).run($,Z,Q,z,z+Q),this.mustGet($)}scanDue(){let $=this.phase();if($!=="awake")return O$("failed_precondition",`elapse scan refused in phase '${$}' \u2014 sleep/crash gap reconciliation precedes the scan (I-3 step 5)`);let Z=this.db.query("SELECT COUNT(*) AS c FROM fuse_deadlines WHERE state = 'ARMED' AND resurfaced = 0").get();if(Z.c>0)return O$("failed_precondition",`elapse scan refused: ${Z.c} armed fuse(s) not yet re-surfaced \u2014 visible-first re-surface before any elapse scan (D4/I-3)`);let Q=this.db.query("SELECT * FROM fuse_deadlines WHERE state = 'ARMED' AND execute_after_awake_ms <= ? ORDER BY intent_id").all(this.awakeNowMs());return H(Q.map(TQ))}recall($){let Z=this.rawGet($);if(Z===null)return O$("not_found",`no deadline row for intent ${$} \u2014 re-derive from action.intent events (the log is the truth, undo-layer \xA76)`);let Q=Z.state;if(Q==="ARMED"||Q==="HELD"){this.db.query("UPDATE fuse_deadlines SET state = 'RECALLED', hold_reason = NULL WHERE intent_id = ?").run($);let z=this.mustGet($);return"ok"in z?H({disposition:"recalled",row:z.ok}):z}if(Q==="RECALLED"){let z=this.mustGet($);return"ok"in z?H({disposition:"recalled",row:z.ok}):z}this.db.query("UPDATE fuse_deadlines SET late_recall = 1 WHERE intent_id = ?").run($);let X=this.mustGet($);return"ok"in X?H({disposition:"late-recall",row:X.ok}):X}markElapsed($){let Z=this.rawGet($);if(Z===null)return O$("not_found",`no deadline row for intent ${$}`);if(this.phase()!=="awake")return O$("failed_precondition",`elapse refused in phase '${this.phase()}' \u2014 a fuse may never elapse inside a gap (I-3 step 5)`);if(Z.state!=="ARMED")return O$("failed_precondition",`intent ${$} is ${Z.state}, not ARMED`);if(Z.resurfaced!==1)return O$("failed_precondition",`intent ${$} not re-surfaced after a gap \u2014 visible-first before elapse (D4)`);if(Z.execute_after_awake_ms>this.awakeNowMs())return O$("failed_precondition",`intent ${$} not due: executeAfter ${Z.execute_after_awake_ms} > awake now ${this.awakeNowMs()}`);return this.db.query("UPDATE fuse_deadlines SET state = 'ELAPSED' WHERE intent_id = ?").run($),this.mustGet($)}hold($,Z){let Q=this.rawGet($);if(Q===null)return O$("not_found",`no deadline row for intent ${$}`);if(Q.state!=="ARMED")return O$("failed_precondition",`intent ${$} is ${Q.state}, not ARMED`);return this.db.query("UPDATE fuse_deadlines SET state = 'HELD', hold_reason = ? WHERE intent_id = ?").run(Z,$),this.mustGet($)}releaseHold($){let Z=this.rawGet($);if(Z===null)return O$("not_found",`no deadline row for intent ${$}`);if(Z.state!=="HELD")return O$("failed_precondition",`intent ${$} is ${Z.state}, not HELD`);return this.db.query("UPDATE fuse_deadlines SET state = 'ARMED', hold_reason = NULL WHERE intent_id = ?").run($),this.mustGet($)}noticeUndeliverable($){let Z=this.rawGet($);if(Z===null)return O$("not_found",`no deadline row for intent ${$}`);if(Z.state!=="ARMED")return O$("failed_precondition",`intent ${$} is ${Z.state}, not ARMED`);if(g9(Z.fuse_key)){let X=this.hold($,"notice-undeliverable");return"ok"in X?H({held:!0,row:X.ok}):X}let Q=this.mustGet($);return"ok"in Q?H({held:!1,row:Q.ok}):Q}get($){let Z=this.rawGet($);if(Z===null)return G$(`no fuse_deadlines row for intent ${$} (durable table consulted)`);return H(TQ(Z))}armed(){return this.db.query("SELECT * FROM fuse_deadlines WHERE state = 'ARMED' ORDER BY armed_awake_ms, intent_id").all().map(TQ)}all(){return this.db.query("SELECT * FROM fuse_deadlines ORDER BY armed_awake_ms, intent_id").all().map(TQ)}rawGet($){return this.db.query("SELECT * FROM fuse_deadlines WHERE intent_id = ?").get($)}mustGet($){let Z=this.rawGet($);if(Z===null)return O$("internal",`deadline row for ${$} vanished mid-transition`,"transient");return H(TQ(Z))}}f();f();var zB=30000;function mz($){let Z=[...$].sort((z,Y)=>z.armedAtAwakeMs-Y.armedAtAwakeMs||(z.intentId<Y.intentId?-1:1)),Q=[],X=null;for(let z of Z)if(X!==null&&z.armedAtAwakeMs-X.lastArm<=zB)X.intentIds.push(z.intentId),X.lastArm=z.armedAtAwakeMs;else{if(X!==null)Q.push({intentIds:X.intentIds,firstArmAtAwakeMs:X.firstArmAtAwakeMs});X={intentIds:[z.intentId],firstArmAtAwakeMs:z.armedAtAwakeMs,lastArm:z.armedAtAwakeMs}}if(X!==null)Q.push({intentIds:X.intentIds,firstArmAtAwakeMs:X.firstArmAtAwakeMs});return Q}var YB={version:"sig-corpus@v0",patterns:[/ignore\s+(?:all\s+|any\s+)?(?:previous|prior|above|earlier)\s+(?:instructions?|directives?|rules?)/i,/disregard\s+(?:the\s+)?(?:previous|prior|above|earlier|system)\s+(?:instructions?|prompt|messages?)/i,/you\s+(?:are|must|should)\s+now\s+(?:act|behave|respond)\s+as/i,/(?:as|to)\s+the\s+(?:ai|agent|assistant)\s*[:,]/i,/system\s+prompt/i,/\b(?:urgent(?:ly)?|immediately)\b[^.]{0,80}\b(?:send|forward|transfer|pay|wire)\b/i,/\b(?:send|forward|transfer|wire|pay)\b[^.]{0,120}\b(?:do\s+not|don'?t)\s+(?:tell|notify|inform|mention)/i,/\bexfiltrat/i,/\bthis\s+is\s+(?:your|the)\s+(?:owner|operator|developer|admin)\b/i]};function k9($){return{signature:$,verdict:"clear"}}function h8($,Z){return{signature:$,verdict:"fired",evidence:Z}}function jB($,Z){let Q=[];for(let X of $.sourceContent){let z=YB.patterns.some((j)=>j.test(X.text)),Y=Z!==void 0&&Z(X.text).injection;if(z||Y)Q.push(X.eventId)}return Q.length>0?h8("injection-signature",Q):k9("injection-signature")}function WB($){if($.contract.effect.class!=="dispatch")return k9("source-novelty-echo");let Z={payloadSources:$.payloadSources,contextSources:$.contextSources};if(S1(Z).length===0)return k9("source-novelty-echo");let X=$.sourceContent.map((z)=>z.eventId);return h8("source-novelty-echo",X.length>0?X:[$.intentId])}function VB($){let Z=[];if($.recipient!==void 0)Z.push(!$.baselines.knownRecipients.includes($.recipient));if($.amount!==void 0&&$.baselines.maxAmountObserved!==void 0)Z.push($.amount>$.baselines.maxAmountObserved);if($.volumeToday!==void 0&&$.baselines.maxDailyVolumeObserved!==void 0)Z.push($.volumeToday>$.baselines.maxDailyVolumeObserved);return Z.some(Boolean)?h8("recipient-baseline",[$.intentId]):k9("recipient-baseline")}function KB($){if($.contract.effect.reversibility!=="compensatable")return k9("undo-path-present");return $.contract.effect.compensation!==void 0&&$.compensation!==void 0&&$.compensation.pathDeclared&&$.compensation.lastTestGreen?k9("undo-path-present"):h8("undo-path-present",[$.intentId])}function qB($,Z){let Q=Z.policy.rows[$.fuseKey];if($.armedFuseMs<Q.floorMs)return h8("floor-integrity",[$.intentId]);if($.fuseKey==="send"&&S1({payloadSources:$.payloadSources,contextSources:$.contextSources}).length>0&&$.armedFuseMs<30000)return h8("floor-integrity",[$.intentId]);return k9("floor-integrity")}function HB($){return $.some((Z)=>Z.verdict==="fired"&&Z.evidence!==void 0&&Z.evidence.length>0)?"recall":"allow"}function hF($,Z){return{err:{code:$,layer:"kernel",retryability:"non-retryable",message:Z}}}class O1{opts;now;ulid;constructor($){this.opts=$,this.now=$.now??(()=>new Date().toISOString()),this.ulid=$.ulid??HV}run($){if($.length===0)return hF("invalid_argument","watchdog run over an empty batch");let Z=this.ulid(),Q=[];for(let X of $){let z=[jB(X,this.opts.classifier),WB(X),VB(X),KB(X),qB(X,this.opts.policy)],Y=HB(z),j=Math.max(0,this.opts.awakeNowMs()-X.armedAtAwakeMs),W={intentId:X.intentId,runId:Z,checklist:z,verdict:Y,completedAtMs:j},V=f9(this.opts.log,N0.watchdogChecked,W,{kind:"kernel"},this.now());if(!K(V))return V;let q=V.ok,B=j>X.armedFuseMs/2,G=B&&g9(X.fuseKey);if(B){let U={runId:Z,intentId:X.intentId,fuseMs:X.armedFuseMs,completedAtMs:j,holdRequired:G},L=f9(this.opts.log,N0.watchdogLate,U,{kind:"kernel"},this.now());if(!K(L))return L}let J={intentId:X.intentId,check:W,checkedEventId:q,late:B,holdRequired:G};if(Y==="recall"){let U=this.opts.recall.requestRecall({intentId:X.intentId,by:"watchdog",via:"watchdog",watchdogRunId:Z,checkRef:q},{kind:"kernel"});if(!K(U))return U;J.recallEventId=U.ok.recallEventId}Q.push(J)}return H({runId:Z,results:Q})}}f();F0();f();f();var u8={kind:"kernel"},RQ="order.created",i5="order.planned",x1="order.leased",OQ="order.started",I1="order.blocked",w9="order.evidence_complete",xQ="order.closed",IQ="order.failed";var y1="incident.filed";var BB="inbox.escalated",JB="gauntlet.verdict",GB="gauntlet.run.opened",UB="worker.exited",LB="spend.metered";var yQ=[{source:"zortex",stream:"workorder",revOrder:"upstream-version",comparator:"numeric",quality:"durable"},{source:"zortex",stream:"incident",revOrder:"upstream-version",comparator:"numeric",quality:"durable"},{source:"zortex",stream:"lesson",revOrder:"upstream-version",comparator:"numeric",quality:"durable"},{source:"zortex",stream:"check",revOrder:"upstream-version",quality:"none",noneIdentity:"state"},{source:"zortex",stream:"probe-run",revOrder:"upstream-version",quality:"none",noneIdentity:"state"},{source:"zortex",stream:"loop",revOrder:"upstream-version",quality:"none",noneIdentity:"state"},{source:"zortex",stream:"inbox",revOrder:"upstream-version",quality:"none",noneIdentity:"state"},{source:"zortex",stream:"kpi",revOrder:"upstream-version",quality:"durable"}];function DB($,Z,Q){return{ts:Q,tier:"first-party",kind:$,schemaVersion:1,mentions:[],body:"",payload:Z}}function E1($,Z,Q,X,z,Y){return{nk:{source:"zortex",stream:$,sourceId:Z,rev:String(Q)},...DB(X,z,Y)}}function MB($,Z,Q,X){return{nk:{source:"zortex",stream:$},...DB(Z,Q,X)}}function m9($){let Z=L$(`block0:${$}`),Q="";for(let X=0;X<26;X++){let z=parseInt(Z.slice(X*2,X*2+2),16),Y=X===0?z%8:z%32;Q+=m2.charAt(Y)}return Q}f();F0();f();var PB=["harness:loop-repair","harness:refactor","harness:decompose","distill:mutation"],lF=[...C8,...PB];function cF($){let Z=$.split(":",1)[0];return C8.includes(Z)?Z:null}function dF($){return lF.includes($)}var hz={build:["lint","eval","test"],fix:["replay","lint","eval"],sync:["probe","artifact"],derive:["probe","artifact"],distill:["probe","artifact"],research:["artifact"],repair:["probe","replay"],review:["artifact"],harness:["test","lint"]},v1=3600000,nF={CREATED:168*v1,PLANNED:12*v1,LEASED:300000,BLOCKED:72*v1,EVIDENCE_COMPLETE:1*v1,GAUNTLET:1800000},iF={};function CB($){return{...nF,...iF[$]??{}}}var FB=600000,NB=3600000,uz=2,AB=2;function i$($){return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:$})}function _B($,Z,Q){let X=$3($);if(!K(X))return X;if(!dF(Z))return i$(`template '${Z}' is not registered \u2014 TemplateId grammar '<kind>' | '<kind>:<variant>', variants ${PB.join(", ")} (iteration-loop \xA73.1)`);let z=cF(Z);if(z!==$.kind)return i$(`template '${Z}' does not match order kind '${$.kind}'`);if(z==="fix"&&Q?.incidentRef===void 0&&Q?.targetOrderId===void 0)return i$("fix template requires templateData.incidentRef (\xA74.2; D12 fix-loop orders join via templateData.targetOrderId)");if(z==="repair"&&(Q?.probeRef===void 0||Q.probeRef===""))return i$("repair template requires templateData.probeRef = the failing probe (FM-19 class, \xA74.2)");if(z==="review"&&Q?.targetOrderId===void 0)return i$("review template requires templateData.targetOrderId (\xA74.2)");if(z==="harness"&&Q?.incidentRef===void 0)return i$("harness template requires the citing threshold/incident event ref (\xA74.10) in templateData.incidentRef");for(let Y of hz[z])if(!$.acceptance.some((j)=>j.check.kind===Y))return i$(`template '${Z}' adds a '${Y}' check \u2014 acceptance carries no criterion of that kind (\xA74.2)`);return H($)}function TB($,Z){let Q=new Set;for(let X of Z.plan.steps)for(let z of X.criteria)Q.add(z);for(let X of $.acceptance)if(!Q.has(X.n))return i$(`FM-1: criterion ${X.n} is not mapped to any plan step`);if($.kind==="build"||$.kind==="fix"){if(Z.registryQueries.length===0)return i$("FM-3: order.planned is invalid unless registryQueries records \u22651 query (iteration-loop \xA74.4)");let X=new Set;for(let q=0;q<Z.registryQueries.length;q++){let B=Z.registryQueries[q];if(B===void 0||typeof B.query!=="string"||B.query.trim()==="")return i$(`FM-3: registryQueries[${q}].query must be a non-empty registry query (iteration-loop \xA74.4)`);if(!Array.isArray(B.resultIds)||B.resultIds.length===0)return i$(`FM-3 fail closed: registryQueries[${q}].resultIds is empty, so registry coverage is unknown (FM-21; iteration-loop \xA74.4)`);for(let G=0;G<B.resultIds.length;G++){let J=B.resultIds[G];if(typeof J!=="string"||J.trim()==="")return i$(`FM-3 fail closed: registryQueries[${q}].resultIds[${G}] must be a non-empty returned registry ID (iteration-loop \xA74.4)`);X.add(J.trim())}}let z=$.shapeAnalysis?.existing;if(z===void 0||z.length===0)return i$("FM-3: shapeAnalysis.existing must cite every returned registry result ID (iteration-loop \xA74.4)");let Y=z.map((q)=>q.trim()),j=(q,B)=>q===B||q.startsWith(`${B} `),W=[...X].filter((q)=>!Y.some((B)=>j(B,q)));if(W.length>0)return i$(`FM-3: shapeAnalysis.existing does not cite returned registry result ID(s): ${W.join(", ")} (iteration-loop \xA74.4)`);let V=Y.filter((q)=>q===""||![...X].some((B)=>j(q,B)));if(V.length>0)return i$(`FM-3: shapeAnalysis.existing contains item(s) absent from registry query results: ${V.map((q)=>q||"<empty>").join(", ")} (iteration-loop \xA74.4)`);if(Z.researchRefs.length===0)return i$("FM-10: researchRefs must be non-empty for build/fix orders (\xA73.1)")}return H(Z)}function SB($){let{failedOrder:Z,violations:Q,attempt:X}=$,z=Q.map((V)=>`${V.law}: ${V.detail}`).join("; ")||"gauntlet verdict fail",Y=Z.acceptance.map((V)=>({n:V.n,statement:V.statement,check:{...V.check}})),j=Y.length;for(let V of hz.fix)if(!Y.some((q)=>q.check.kind===V))j+=1,Y.push({n:j,statement:`template-added ${V} check (fix template, \xA74.2)`,check:{kind:V,ref:`template:fix:${V}:${$.failedOrder.id}`}});return{order:{id:$.id,kind:"fix",requirement:`D12 fix attempt ${X}: ${z}`,shapeAnalysis:{touchedBlocks:Z.shapeAnalysis?.touchedBlocks??[],existing:Z.shapeAnalysis?.existing??[],delta:`repair order ${Z.id} to verdict-pass: ${z}`},acceptance:Y,leases:[...Z.leases],budget:{...Z.budget},provenance:{spawnedBy:$.spawnedBy,parent:Z.id}},templateData:{targetOrderId:Z.id}}}function EQ($,Z,Q){return E1("incident",$,0,y1,Z,Q)}function RB($,Z){return MB("inbox",BB,$,Z)}f();F0();var sF={[RQ]:"CREATED",[i5]:"PLANNED",[x1]:"LEASED",[OQ]:"IN_PROGRESS",[I1]:"BLOCKED",[w9]:"EVIDENCE_COMPLETE",[xQ]:"CLOSED",[IQ]:"FAILED"};class vQ{rows=new Map;static async build($){let Z=new vQ;for await(let Q of $.scan()){if(b0(Q))continue;Z.apply(Q)}return Z}apply($){if($.nk.source==="zortex"&&$.nk.stream==="workorder"){if($.nk.rev.includes("#"))return;this.applyOrderEvent($);return}let Z=$.payload;if($.kind===GB&&typeof Z?.orderId==="string"){let Q=this.rows.get(Z.orderId);if(Q&&Q.state==="EVIDENCE_COMPLETE")Q.state="GAUNTLET",Q.stateEnteredTs=$.ts,Q.gauntletPickups+=1;return}if($.kind===JB&&typeof Z?.orderId==="string"){let Q=this.rows.get(Z.orderId);if(Q){if(Q.verdicts.push({eventId:$.id,payload:$.payload}),Q.firstVerdictTs===void 0)Q.firstVerdictTs=$.ts}return}if($.kind===LB&&typeof Z?.orderId==="string"&&typeof Z?.usd==="number"){let Q=this.rows.get(Z.orderId);if(Q)Q.spendUsd+=Z.usd;return}if($.kind===y1&&typeof Z?.orderRef==="string"&&typeof Z?.state==="string"){let Q=this.rows.get(Z.orderRef);if(Q)Q.incidentStates.add(Z.state)}}applyOrderEvent($){let Z=$.nk.sourceId,Q=Number($.nk.rev);if($.kind===RQ){let Y=$.payload,j={id:Z,order:Y.order,template:Y.template,state:"CREATED",stateEnteredTs:$.ts,headRev:Q,runs:0,leaseReleases:0,verdicts:[],gauntletPickups:0,spendUsd:0,createdTs:$.ts,incidentStates:new Set};if(Y.templateData!==void 0)j.templateData=Y.templateData;this.rows.set(Z,j);return}let X=this.rows.get(Z);if(X===void 0)return;if(Q<=X.headRev)return;X.headRev=Q;let z=sF[$.kind];if(z===void 0)return;if($.kind===i5){let Y=$.payload;if(X.state==="LEASED")X.leaseReleases+=1;X.lastPlan=Y,X.retry=Y.retry}if($.kind===OQ)X.runs+=1,X.runId=$.payload.runId;if($.kind===w9)X.lastEvidence=$.payload;if($.kind===xQ)X.verdictRef=$.payload.verdictRef;if($.kind===IQ)X.failure=$.payload;X.state=z,X.stateEnteredTs=$.ts}show($){let Z=this.rows.get($);if(Z===void 0)return G$(`no order '${$}' in the book (full-scan projection)`);return H(Z)}list($){let Z=[];for(let Q of this.rows.values()){if($?.state!==void 0&&Q.state!==$.state)continue;if($?.kind!==void 0&&Q.order.kind!==$.kind)continue;Z.push(Q)}return Z}queue(){return this.list().filter(($)=>$.state==="CREATED"||$.state==="PLANNED").sort(($,Z)=>{let Q=$.order.kind==="harness"?0:1,X=Z.order.kind==="harness"?0:1;if(Q!==X)return Q-X;return $.createdTs<Z.createdTs?-1:$.createdTs>Z.createdTs?1:0})}attemptOf($){let Z=0,Q=this.rows.get($),X=new Set([$]);while(Q?.templateData?.targetOrderId!==void 0&&!X.has(Q.templateData.targetOrderId))Z+=1,X.add(Q.templateData.targetOrderId),Q=this.rows.get(Q.templateData.targetOrderId);return Z}}f();function A0($,Z,Q="non-retryable"){return v({code:$,layer:"kernel",retryability:Q,message:Z})}function H5($,Z){return new Date(Date.parse($)+Z).toISOString()}class b1{log;now;ulid;constructor($){this.log=$.log,this.now=$.now??(()=>new Date().toISOString()),this.ulid=$.ulid??V$()}async book(){return vQ.build(this.log)}headRev($){let Z=-1;try{for(let Q of this.log.chain({source:"zortex",stream:"workorder",sourceId:$})){if("erasedKind"in Q)continue;if(Q.nk.rev.includes("#"))continue;let X=Number(Q.nk.rev);if(Number.isFinite(X)&&X>Z)Z=X}}catch(Q){return A0("unavailable",`order chain unreadable (event log unavailable): ${String(Q)}`,"transient")}return H(Z)}compareAndAppendRefusal($,Z,Q){return A0("aborted",`compare-and-append refused: order ${$} chain head is rev ${Z}, caller expected ${Q} \u2014 the chain advanced (recovery-vs-live race, iteration-loop \xA74.1)`)}staleExpectedRev($,Z){if(Z===void 0||$.headRev===Z)return;return this.compareAndAppendRefusal($.id,$.headRev,Z)}appendOrderEvent($,Z,Q,X={}){let z=this.headRev($);if(!K(z))return z;let Y=z.ok;if(X.expectedRev!==void 0&&Y!==X.expectedRev)return this.compareAndAppendRefusal($,Y,X.expectedRev);return this.appendOrderEventAtRev($,Z,Q,Y+1,X.ts??this.now())}appendOrderEventAtRev($,Z,Q,X,z){let Y=E1("workorder",$,X,Z,Q,z??this.now()),j=this.log.append([Y],u8);if(!K(j))return j;let W=j.ok[0];if(W===void 0)return A0("internal","append returned no outcome");if(W.outcome==="anomaly"){let V=this.fileReviewOrder($,`nk-conflict on order ${$} rev ${X} (kind ${Z}) \u2014 ingest.anomaly ${W.anomalyId}`),q={eventId:W.id,rev:X};if(K(V))q.reviewOrderId=V.ok;return H(q)}return H({eventId:W.id,rev:X})}fileReviewOrder($,Z){let X={id:this.ulid(),kind:"review",requirement:`review anomalous append: ${Z}`,acceptance:[{n:1,statement:"independent review report of the conflicting appends (FM-1/D12)",check:{kind:"artifact",ref:`review:${$}`}}],leases:[],budget:{tokens:50000,usd:5,wallClockMin:60},provenance:{spawnedBy:"kernel",parent:$}};return this.create(X,"review",{targetOrderId:$})}fileAutoIncident($,Z,Q){let X=m9($),z=this.log.append([EQ(X,Z,Q)],u8);if(!K(z))return z;return H(X)}escalate($,Z){this.log.append([RB($,Z)],u8)}async row($){let Q=(await this.book()).show($);if(!K(Q)){if("empty"in Q)return A0("not_found",`order '${$}' not found in the order book`);return Q}return Q}refuseState($,Z,Q){return A0("failed_precondition",`cannot ${Q} order ${$.id}: state is ${$.state}, transition requires ${Z.join("|")} (iteration-loop \xA74.1 state machine)`)}create($,Z,Q){let X=_B($,Z,Q);if(!K(X))return X;let z=this.headRev($.id);if(!K(z))return A0("failed_precondition",`order.created append refused: ${z.err.message}`);if(z.ok!==-1)return A0("already_exists",`order ${$.id} already has a lifecycle chain`);let Y={order:$,template:Z};if(Q!==void 0)Y.templateData=Q;let j=this.appendOrderEventAtRev($.id,RQ,Y,0);if(!K(j))return j;return H($.id)}async plan($,Z,Q={}){let X=await this.row($);if(!K(X))return X;let z=X.ok,Y=this.staleExpectedRev(z,Q.expectedRev);if(Y!==void 0)return Y;if(z.state!=="CREATED")return this.refuseState(z,["CREATED"],"plan");let j=TB(z.order,Z);if(!K(j))return j;return this.appendOrderEvent($,i5,Z,Q)}async answerBlocked($){let Z=await this.row($);if(!K(Z))return Z;let Q=Z.ok;if(Q.state!=="BLOCKED")return this.refuseState(Q,["BLOCKED"],"answer");if(Q.lastPlan===void 0)return A0("failed_precondition",`order ${$} has no recorded plan to re-enter with`);let X={...Q.lastPlan};return delete X.retry,delete X.recoveredBy,this.appendOrderEvent($,i5,X)}async lease($,Z,Q,X={}){let z=await this.row($);if(!K(z))return z;let Y=z.ok,j=this.staleExpectedRev(Y,X.expectedRev);if(j!==void 0)return j;if(Y.state!=="PLANNED")return this.refuseState(Y,["PLANNED"],"lease");if(Y.retry!==void 0&&this.now()<Y.retry.notBefore)return A0("failed_precondition",`order ${$} is in retry backoff until ${Y.retry.notBefore} (run-level ${Y.retry.cause}, \xA74.1) \u2014 leases are never held through a backoff`,"throttling");return this.appendOrderEvent($,x1,{leases:Z,grantedBy:Q},X)}async start($,Z,Q={}){let X=await this.row($);if(!K(X))return X;let z=X.ok,Y=this.staleExpectedRev(z,Q.expectedRev);if(Y!==void 0)return Y;if(z.state!=="LEASED")return this.refuseState(z,["LEASED"],"start");return this.appendOrderEvent($,OQ,{runId:Z},Q)}async block($,Z,Q,X){let z=await this.row($);if(!K(z))return z;let Y=z.ok;if(Y.state!=="IN_PROGRESS")return this.refuseState(Y,["IN_PROGRESS"],"block");if(X!==void 0){for(let W of["missingRuling","ownerDoc","requiredAction","gateId"])if(typeof X[W]!=="string"||X[W].length===0)return{err:{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`order.blocked authority.${W} is required and non-empty (RA-7 structured blocked state)`}};if(X.affectedRung!=="gate"&&typeof X.affectedRung!=="number")return{err:{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"order.blocked authority.affectedRung must be a rung number or 'gate'"}}}let j=X===void 0?{question:Z,inboxRef:Q}:{question:Z,inboxRef:Q,authority:X};return this.appendOrderEvent($,I1,j)}async completeEvidence($,Z){let Q=await this.row($);if(!K(Q))return Q;let X=Q.ok;if(X.state!=="IN_PROGRESS")return this.refuseState(X,["IN_PROGRESS"],"complete evidence for");let z=new Set(X.order.acceptance.map((Y)=>Y.n));for(let Y of Z)if(!z.has(Y.n))return A0("invalid_argument",`evidence pairs criterion ${Y.n} which does not exist on the order (\xA73.1: pairing is EXPLICIT)`);return this.appendOrderEvent($,w9,{evidence:Z})}async fail($,Z,Q,X={}){let z={reason:Z,attempts:Q};if(X.incidentRef!==void 0)z.incidentRef=X.incidentRef;if(X.recoveredBy!==void 0)z.recoveredBy=X.recoveredBy;let Y=this.appendOrderEvent($.id,IQ,z,{ts:X.ts??this.now()});if(!K(Y))return Y;if($.order.kind==="fix"||$.order.kind==="build")this.fileAutoIncident(`${$.id}:failed`,{symptom:`order ${$.id} (${$.order.kind}) terminated FAILED(${Z})`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:$.id,state:"FAILED"},X.ts??this.now());return Y}async onVerdict($,Z){let Q=await this.book(),X=Q.show(Z.orderId);if(!K(X))return A0("not_found",`verdict names unknown order ${Z.orderId}`);let z=X.ok;if(z.state!=="GAUNTLET"&&z.state!=="EVIDENCE_COMPLETE")return this.refuseState(z,["GAUNTLET","EVIDENCE_COMPLETE"],"apply a verdict to");if(Z.disposition==="pass"){let B=this.appendOrderEvent(z.id,xQ,{verdictRef:$});if(!K(B))return B;return H({closed:z.id})}if(Z.disposition==="errored"){let B=z.lastEvidence??{evidence:[]},G=this.appendOrderEvent(z.id,w9,B);if(!K(G))return G;return H({})}let Y=Q.attemptOf(z.id),j=await this.fail(z,"attempts_exhausted",Y,{});if(!K(j))return j;if(Y>=AB)return this.escalate({reason:`D12 fix loop exhausted at attempt ${Y}`,orderRef:z.id,state:"FAILED",trail:{verdicts:z.verdicts.map((B)=>B.eventId),violations:Z.violations}},this.now()),H({escalated:!0});let{order:W,templateData:V}=SB({failedOrder:z.order,violations:Z.violations,attempt:Y+1,spawnedBy:"gauntlet",id:this.ulid()}),q=this.create(W,"fix",V);if(!K(q))return q;return H({fixOrderId:q.ok})}async applyRunFailure($,Z,Q={}){let X=await this.row($);if(!K(X))return X;let z=X.ok;if(z.state!=="IN_PROGRESS")return this.refuseState(z,["IN_PROGRESS"],"apply a run failure to");let Y=Q.ts??this.now();if(Z.status==="reaped")this.fileAutoIncident(`${$}:reaped:${z.runs}`,{symptom:`worker run ${z.runId??"?"} for order ${$} reaped (heartbeat/budget)`,layer:"kernel",severity:"sev2",detectedBy:"reap",orderRef:$,state:"IN_PROGRESS"},Y);if(z.spendUsd>z.order.budget.usd){let G=await this.fail(z,"budget_exceeded",z.runs,{ts:Y,...Q.recoveredBy!==void 0?{recoveredBy:Q.recoveredBy}:{}});if(!K(G))return G;return H({action:"failed"})}let j=Z.status==="reaped"?"transient":Z.error?.retryability??"non-retryable";if(j==="non-retryable"){let G=this.fileAutoIncident(`${$}:non-retryable:${z.runs}`,{symptom:`order ${$} run failed non-retryable: ${Z.error?.message??"no structured error attached"}`,layer:Z.error?.layer??"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:$,state:"IN_PROGRESS",...Z.error===void 0?{}:{failure:{stage:Z.stage,code:Z.error.code,layer:Z.error.layer,retryability:Z.error.retryability}}},Y),J=await this.fail(z,"attempts_exhausted",z.runs,{ts:Y,...K(G)?{incidentRef:G.ok}:{}});if(!K(J))return J;return H({action:"failed"})}if(z.runs>=uz){let G=this.fileAutoIncident(`${$}:attempts-exhausted`,{symptom:`order ${$} exhausted its ${uz} runs (\xA74.1)`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:$,state:"IN_PROGRESS"},Y),J=await this.fail(z,"attempts_exhausted",z.runs,{ts:Y,...K(G)?{incidentRef:G.ok}:{}});if(!K(J))return J;return this.escalate({reason:"attempts exhausted",orderRef:$,state:"FAILED"},Y),H({action:"failed"})}let V=H5(Y,j==="throttling"?NB:FB);if(z.lastPlan===void 0)return A0("internal",`order ${$} reached IN_PROGRESS without a plan`);let q={plan:z.lastPlan.plan,registryQueries:z.lastPlan.registryQueries,researchRefs:z.lastPlan.researchRefs,retry:{run:z.runs,notBefore:V,cause:Z.status}};if(Q.recoveredBy!==void 0)q.recoveredBy=Q.recoveredBy;let B=this.appendOrderEvent($,i5,q,{ts:Y});if(!K(B))return B;return H({action:"retry",notBefore:V})}async sweep($){let Z=await this.book(),Q={expired:[],escalated:[],leaseReleased:[],reaped:[],blockedExpired:[],gateIncidents:[],gauntletIncidents:[],gauntletRequeued:[],retried:[],failed:[]};for(let X of Z.list()){if(X.state==="CLOSED"||X.state==="FAILED")continue;let z=CB(X.template),Y=X.stateEnteredTs;if(X.state==="CREATED"){let j=H5(Y,z.CREATED);if($>j){let W=await this.fail(X,"expired",0,{ts:j,recoveredBy:"timeout-sweep"});if(K(W))Q.expired.push(X.id)}}else if(X.state==="PLANNED"){let j=H5(Y,z.PLANNED);if($>j)this.escalate({reason:"PLANNED re-prioritize",orderRef:X.id,state:"PLANNED",deadline:j},j),Q.escalated.push(X.id)}else if(X.state==="LEASED"){let j=H5(Y,z.LEASED);if($>j&&X.lastPlan!==void 0){let W={...X.lastPlan,recoveredBy:"timeout-sweep"};delete W.retry;let V=this.appendOrderEvent(X.id,i5,W,{ts:j});if(K(V)){if(Q.leaseReleased.push(X.id),X.leaseReleases+1>=3)this.fileAutoIncident(`${X.id}:lease-thrash`,{symptom:`order ${X.id} lease released 3\xD7 without starting (\xA74.1)`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:X.id,state:"LEASED"},j)}}}else if(X.state==="IN_PROGRESS"){let j=H5(Y,X.order.budget.wallClockMin*60000);if($>j){let W=X.runId??m9(`${X.id}:run`);this.log.append([{nk:{source:"zortex",stream:"workorder-runs",sourceId:W,rev:String(X.runs)},ts:j,tier:"first-party",kind:UB,schemaVersion:1,mentions:[],body:"",payload:{runId:W,status:"reaped",evidence:[],spend:{tokens:0,usd:0},traceId:W}}],u8);let V=await this.applyRunFailure(X.id,{status:"reaped"},{ts:j,recoveredBy:"timeout-sweep"});if(K(V))Q.reaped.push(X.id),(V.ok.action==="retry"?Q.retried:Q.failed).push(X.id)}}else if(X.state==="BLOCKED"){let j=H5(Y,z.BLOCKED);if($>j){let W=await this.fail(X,"blocked_timeout",X.runs,{ts:j,recoveredBy:"timeout-sweep"});if(K(W))Q.blockedExpired.push(X.id),this.escalate({reason:"blocked question expired unanswered (72h)",orderRef:X.id,state:"BLOCKED",deadline:j},j)}}else if(X.state==="EVIDENCE_COMPLETE"){let j=H5(Y,z.EVIDENCE_COMPLETE);if($>j&&!X.incidentStates.has("EVIDENCE_COMPLETE")){let W=this.fileAutoIncident(`${X.id}:EVIDENCE_COMPLETE`,{symptom:`order ${X.id} sat in EVIDENCE_COMPLETE past 1h \u2014 the verdict identity is not picking up (gate broken)`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:X.id,state:"EVIDENCE_COMPLETE"},j);if(K(W))Q.gateIncidents.push(X.id)}}else if(X.state==="GAUNTLET"){let j=z.GAUNTLET,W=H5(Y,j),V=H5(Y,2*j);if($>V&&X.incidentStates.has("GAUNTLET")){this.fileAutoIncident(`${X.id}:GAUNTLET-2`,{symptom:`order ${X.id} gauntlet verdict cap exceeded twice \u2014 treated as errored, re-queued`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:X.id,state:"GAUNTLET-2"},V);let B={...X.lastEvidence??{evidence:[]},recoveredBy:"timeout-sweep"},G=this.appendOrderEvent(X.id,w9,B,{ts:V});if(K(G))Q.gauntletRequeued.push(X.id)}else if($>W&&!X.incidentStates.has("GAUNTLET")){let q=this.fileAutoIncident(`${X.id}:GAUNTLET`,{symptom:`order ${X.id} exceeded the 30m gauntlet verdict cap \u2014 one gauntlet-run retry`,layer:"kernel",severity:"sev2",detectedBy:"watchdog",orderRef:X.id,state:"GAUNTLET"},W);if(K(q))Q.gauntletIncidents.push(X.id)}}}return H(Q)}}f();f();function x($,Z,Q="non-retryable",X){let z={code:$,layer:"kernel",retryability:Q,message:Z};if(X!==void 0)z.cause=X;return{err:z}}function U0($){return X5($)}var pz={read:0,create:1,update:2,delete:3,dispatch:4};function lz($,Z){return(pz[Z]??0)>(pz[$]??0)?Z:$}var OB=14400000,xB=86400000;function g1($){if($.fuse==="floor")return OB;if($.effect.class==="dispatch"&&$.effect.reversibility==="irreversible")return xB;return null}function bQ($,Z,Q="params"){let X=Z.type;if(X==="object"){if($===null||typeof $!=="object"||Array.isArray($))return x("invalid_argument",`${Q}: expected object`);let Y=Z.properties,j=Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{},W=Array.isArray(Z.required)?Z.required:[];for(let V of W)if(typeof V==="string"&&$[V]===void 0)return x("invalid_argument",`${Q}.${V}: required param missing`);if(Z.additionalProperties===!1){for(let V of Object.keys($))if(j[V]===void 0)return x("invalid_argument",`${Q}.${V}: unknown param (additionalProperties: false)`)}for(let[V,q]of Object.entries(j)){let B=$[V];if(B===void 0)continue;if(q===null||typeof q!=="object"||Array.isArray(q))continue;let G=bQ(B,q,`${Q}.${V}`);if(!("ok"in G))return G}return{ok:!0}}if(X==="string"){if(typeof $!=="string")return x("invalid_argument",`${Q}: expected string`)}else if(X==="number"||X==="integer"){if(typeof $!=="number")return x("invalid_argument",`${Q}: expected number`);if(X==="integer"&&!Number.isInteger($))return x("invalid_argument",`${Q}: expected integer`);let Y=Z.minimum;if(typeof Y==="number"&&$<Y)return x("invalid_argument",`${Q}: ${$} < minimum ${Y}`);let j=Z.maximum;if(typeof j==="number"&&$>j)return x("invalid_argument",`${Q}: ${$} > maximum ${j}`)}else if(X==="boolean"){if(typeof $!=="boolean")return x("invalid_argument",`${Q}: expected boolean`)}else if(X==="array"){if(!Array.isArray($))return x("invalid_argument",`${Q}: expected array`);let Y=Z.items;if(Y!==null&&typeof Y==="object"&&!Array.isArray(Y))for(let j=0;j<$.length;j++){let W=bQ($[j],Y,`${Q}[${j}]`);if(!("ok"in W))return W}}else if(X!==void 0)return x("failed_precondition",`${Q}: schema type '${String(X)}' outside the pinned subset \u2014 fail closed`);let z=Z.enum;if(Array.isArray(z)){if(!z.some((j)=>JSON.stringify(j)===JSON.stringify($)))return x("invalid_argument",`${Q}: value not in enum`)}return{ok:!0}}var s5={enqueued:"job.enqueued",started:"job.started",succeeded:"job.succeeded",failed:"job.failed",abandoned:"job.abandoned"},h9={queued:"worker.queued",leased:"worker.leased",spawned:"worker.spawned",exited:"worker.exited",runSummary:"worker.run.summary"},p8={opened:"breaker.opened",halfOpen:"breaker.half_open",closed:"breaker.closed",tripped:"breaker.tripped"},l8={sleepBegan:"sleep.began",safeMode:"falcon.safe_mode",haltLoud:"falcon.halt_loud",spendReconciled:"spend.reconciled"},IB=["worker.exited","gauntlet.verdict"];function c8($){return IB.includes($)}var cz=[{kind:"action.*",source:"zortex",stream:"action",sourceId:"occurrence",rev:"occurrence"},{kind:"fuse.*",source:"zortex",stream:"action",sourceId:"occurrence",rev:"occurrence"},{kind:"worker.*",source:"zortex",stream:"worker",sourceId:"occurrence",rev:"occurrence"},{kind:"gauntlet.verdict",source:"zortex",stream:"worker",sourceId:"occurrence",rev:"occurrence"},{kind:"job.*",source:"zortex",stream:"job",sourceId:"occurrence",rev:"occurrence"},{kind:"breaker.*",source:"zortex",stream:"breaker",sourceId:"occurrence",rev:"occurrence"},{kind:"sleep.began",source:"zortex",stream:"kernel",sourceId:"occurrence",rev:"occurrence"},{kind:"falcon.*",source:"zortex",stream:"kernel",sourceId:"occurrence",rev:"occurrence"},{kind:"spend.reconciled",source:"zortex",stream:"kernel",sourceId:"occurrence",rev:"occurrence"},{kind:"trace.span",source:"zortex",stream:"trace",sourceId:"spanId",rev:"0"}];function dz($){let Z=cz.find((X)=>X.kind===$);if(Z!==void 0)return Z.stream;return cz.find((X)=>X.kind.endsWith(".*")&&$.startsWith(X.kind.slice(0,-1)))?.stream}var gQ=[{source:"zortex",stream:"job",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"worker",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"breaker",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"},{source:"zortex",stream:"kernel",revOrder:"upstream-version",quality:"none",noneIdentity:"occurrence"}];var oF={"ice.assemble":["requester.workerType"],"llm.call":["request.temperature"]};function nz($,Z){let Q=DX[$];if(Q===void 0)return x("invalid_argument",`span name '${$}' is not in the I-6 attr registry \u2014 adding a span name is an edit to falcon \xA73.4's table, not ad-hoc emission`);let X=oF[$]??[];for(let z of Q){if(X.includes(z))continue;if(Z[z]===void 0)return x("invalid_argument",`span '${$}' missing required attr '${z}' (falcon \xA73.4 registry)`)}return{ok:!0}}var yB={kind:"kernel"},EB=Symbol("falcon-verdict-seal");class iz{constructor($){if($!==EB)throw Error("VerdictAuthority is falcon-minted only (I-5 verdict-writer isolation)")}}class f1{log;authority;claimed=!1;halted=null;onHalt;ulid=V$();constructor($,Z={}){this.log=$,this.authority=new iz(EB),this.onHalt=Z.onHalt}claimVerdictAuthority(){if(this.claimed)return x("failed_precondition","verdict authority already claimed \u2014 exactly one holder per falcon (I-5)");return this.claimed=!0,{ok:this.authority}}healthy(){return this.halted===null}haltError(){return this.halted}clearHalt(){this.halted=null}noteExternalStorageFailure($){if(this.halted===null)this.halted=$,this.onHalt?.($)}append($,Z,Q,X={}){if(this.halted!==null)return x("unavailable",`HALT_LOUD: event log unwritable \u2014 an action that can't be evented may not fire (D24); cause: ${this.halted.message}`,"retry-at-higher-level",this.halted);if(c8($)&&X.authority!==this.authority)return x("permission_denied",`kind '${$}' is verdict-class: appendable only with the falcon VerdictAuthority (I-5 verdict-writer isolation) \u2014 workers lack the capability architecturally`);let z=X.origin??yB,Y=I7($,z);if(!K(Y))return Y;let j=dz($),W=U0(Q),V=$==="trace.span"?this.traceProto(Z,W):{nk:{source:"zortex",stream:j??"kernel"},ts:W,tier:"first-party",kind:$,schemaVersion:1,mentions:[],body:"",payload:Z},q=this.log.append([V],z);if(!K(q)){let J=("err"in q?q.err:void 0)??{code:"internal",layer:"storage",retryability:"non-retryable",message:"append returned empty"};if(J.layer==="storage"||J.code==="data_loss"||J.code==="unavailable")this.halted=J,this.onHalt?.(J);return x("unavailable",`event append failed for '${$}': ${J.message}`,"retry-at-higher-level",J)}let B=q.ok[0];if(B===void 0)return x("internal",`append of '${$}' returned no result row`,"transient");return{ok:B.id}}traceProto($,Z){return{nk:{source:"zortex",stream:"trace",sourceId:$!==null&&typeof $==="object"&&!Array.isArray($)?String($.spanId??""):"",rev:"0"},ts:Z,tier:"first-party",kind:"trace.span",schemaVersion:1,mentions:[],body:"",payload:$}}emitSpan($,Z){let Q=z3($);if(!K(Q))return Q;let X=nz($.name,$.attrs);if(!("ok"in X))return X;return this.append("trace.span",$,Z)}fileIncident($,Z,Q,X,z={}){if(this.halted!==null)return x("unavailable",`HALT_LOUD: incident '${$}' not appendable \u2014 stderr-tier log is the fallback (\xA74.7)`,"retry-at-higher-level",this.halted);let Y={symptom:$,layer:"kernel",severity:Z,detectedBy:Q,...z},j=EQ(this.ulid(),Y,U0(X)),W=this.log.append([j],yB);if(!K(W)){let q="err"in W?W.err:void 0;return x("unavailable",`incident append failed: ${q?.message??"empty"}`,"retry-at-higher-level",q)}let V=W.ok[0];if(V===void 0)return x("internal","incident append returned no row","transient");return{ok:V.id}}}f();var oz="pricing@v1";var az=0.1,d$="2026-06-12T00:00:00.000Z",rz=[{provider:"anthropic",model:"claude-opus-4-8",unit:"tokens",inPerMTok:5,outPerMTok:25,asOf:d$},{provider:"anthropic",model:"claude-opus-4-7",unit:"tokens",inPerMTok:5,outPerMTok:25,asOf:d$},{provider:"anthropic",model:"claude-opus-4-6",unit:"tokens",inPerMTok:5,outPerMTok:25,asOf:d$},{provider:"anthropic",model:"claude-sonnet-5",unit:"tokens",inPerMTok:2,outPerMTok:10,asOf:d$},{provider:"anthropic",model:"claude-sonnet-4-6",unit:"tokens",inPerMTok:3,outPerMTok:15,asOf:d$},{provider:"anthropic",model:"claude-haiku-4-5",unit:"tokens",inPerMTok:1,outPerMTok:5,asOf:d$},{provider:"anthropic",model:"web-search",unit:"request",perRequest:0.01,asOf:d$},{provider:"openai",model:"gpt-5.1",unit:"tokens",inPerMTok:1.25,outPerMTok:10,asOf:d$},{provider:"openai",model:"gpt-5-mini",unit:"tokens",inPerMTok:0.25,outPerMTok:2,asOf:d$},{provider:"openai",model:"gpt-5-nano",unit:"tokens",inPerMTok:0.05,outPerMTok:0.4,asOf:d$},{provider:"openai",model:"text-embedding-3-small",unit:"tokens",inPerMTok:0.02,outPerMTok:0,asOf:d$},{provider:"openai",model:"text-embedding-3-large",unit:"tokens",inPerMTok:0.13,outPerMTok:0,asOf:d$},{provider:"openrouter",model:"deepseek/deepseek-chat-v3.1",unit:"tokens",inPerMTok:0.25,outPerMTok:1,asOf:d$},{provider:"openrouter",model:"meta-llama/llama-3.3-70b-instruct",unit:"tokens",inPerMTok:0.1,outPerMTok:0.25,asOf:d$},{provider:"openrouter",model:"qwen/qwen3-235b-a22b",unit:"tokens",inPerMTok:0.2,outPerMTok:0.6,asOf:d$},{provider:"openrouter",model:"anthropic/claude-sonnet-4-6",unit:"tokens",inPerMTok:3,outPerMTok:15,asOf:d$},{provider:"openrouter",model:"openai/gpt-5-mini",unit:"tokens",inPerMTok:0.25,outPerMTok:2,asOf:d$}];function aF($,Z){return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`no pricing entry for provider='${$}' model='${Z??""}' \u2014 paid call FAILS CLOSED: `+"a missing price is a hard error at the meter, never a silent $0 (FM-24; V1 \xA72 5x-burn misreport). "+`File a repricing order against ${oz}.`})}function vB($,Z,Q=rz){for(let X of Q)if(X.provider===$&&(X.model??"")===(Z??""))return H(X);return aF($,Z)}function tz($=rz,Z=oz){return{version:Z,priceFor:(Q,X)=>vB(Q,X,$)}}function fQ($,Z){if($.unit==="tokens"){let Q=Z.tokensIn??0,X=Z.tokensOut??0;if(Q>0&&$.inPerMTok===void 0)return sz($,"inPerMTok");if(X>0&&$.outPerMTok===void 0)return sz($,"outPerMTok");return H(Q/1e6*($.inPerMTok??0)+X/1e6*($.outPerMTok??0))}if($.perRequest===void 0)return sz($,"perRequest");return H($.perRequest*(Z.requests??1))}function sz($,Z){return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`pricing row for provider='${$.provider}' model='${$.model??""}' lacks ${Z} \u2014 `+"the charge FAILS CLOSED (FM-24: never silent $0)"})}var ez="spend.metered";var u9=["sync","derivation","flywheel","feed","fabrication","subscriptions"];function bB($,Z,Q,X){return{nk:{source:"zortex",stream:$},ts:Q,tier:"first-party",kind:Z,schemaVersion:1,mentions:[],body:"",payload:X}}function gB($){let Z={};for(let[Q,X]of Object.entries($))if(X!==void 0)Z[Q]=X;return Z}function $Y($,Z){return bB("spend","spend.metered",Z,gB($))}function ZY($,Z){return bB("envelope","envelope.transition",Z,gB($))}f();function rF($){return"erasedKind"in $}class kQ{records=[];chargeIds=new Set;healthState="healthy";health(){return this.healthState}markCorrupt(){this.healthState="corrupt"}record($){if(this.healthState!=="healthy")return v({code:"failed_precondition",layer:"kernel",retryability:"transient",message:`spend ledger is ${this.healthState} \u2014 refusing writes until rebuilt from ledger events (FM-21: never spend blind)`});if(this.chargeIds.has($.chargeId))return H(!0);return this.chargeIds.add($.chargeId),this.records.push($),H(!0)}all(){return this.records}size(){return this.records.length}periodSpend($){let Z=0;for(let Q of this.records)if(Q.periodKey===$)Z+=Q.usd;return Z}orderSpend($){let Z=0;for(let Q of this.records)if(Q.orderId===$)Z+=Q.usd;return Z}totalsByOrder($){return this.groupSum((Z)=>Z.orderId,$)}totalsByProvider($){return this.groupSum((Z)=>Z.provider,$)}totalsByDay($){return this.groupSum((Z)=>Z.ts.slice(0,10),$)}totalsByCategory($){return this.groupSum((Z)=>Z.category,$)}totalsByProviderDay($){return this.groupSum((Z)=>`${Z.provider} ${Z.ts.slice(0,10)}`,$)}groupSum($,Z){let Q=new Map;for(let X of this.records){if(Z!==void 0&&X.periodKey!==Z)continue;let z=$(X);if(z===void 0)continue;Q.set(z,(Q.get(z)??0)+X.usd)}return Q}chargesBetween($,Z){return this.records.filter((Q)=>{let X=Date.parse(Q.ts);return X>$&&X<=Z})}lastUseByProvider($){let Z;for(let Q of this.records){if(Q.provider!==$)continue;if(Z===void 0||Q.ts>Z)Z=Q.ts}return Z}recomputeUsd($,Z=0.000000001){let Q=0,X=[];for(let z of this.records){let Y=$.priceFor(z.provider,z.model);if(!K(Y))return Y;let j=fQ(Y.ok,{tokensIn:z.tokensIn,tokensOut:z.tokensOut,requests:z.requests});if(!K(j))return j;let W=Math.abs(j.ok-z.usd);if(W>Q)Q=W;if(W>Z)X.push(z)}return H({maxDeltaUsd:Q,mismatched:X})}async rebuildFromLog($){this.healthState="rebuilding",this.records=[],this.chargeIds=new Set;try{for await(let Z of $.scan(void 0,{kinds:[ez],sources:["zortex"],streams:["spend"]})){if(rF(Z))continue;let Q=tF(Z);if(!K(Q))return this.healthState="corrupt",Q;if(!this.chargeIds.has(Q.ok.chargeId))this.chargeIds.add(Q.ok.chargeId),this.records.push(Q.ok)}}catch(Z){return this.healthState="corrupt",v({code:"data_loss",layer:"storage",retryability:"transient",message:`ledger rebuild scan failed \u2014 meter stays closed: ${String(Z)}`})}return this.healthState="healthy",H(this.records.length)}}function tF($){let Z=$.payload;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return v({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`spend.metered event ${$.id} carries a non-object payload \u2014 ledger rebuild fails closed`});let Q=Z,X=(S)=>typeof Q[S]==="string"?Q[S]:void 0,z=(S)=>typeof Q[S]==="number"?Q[S]:void 0,Y=X("chargeId"),j=X("provider"),W=X("traceId"),V=X("unit"),q=z("usd"),B=X("category"),G=X("periodKey"),J=X("priceVersion"),U=z("tokensIn"),L=z("tokensOut"),D=z("requests"),P=X("model"),F=X("orderId"),A=X("runId");if(!q$(Y)||j===void 0||j.trim()!==j||j===""||!q$(W)||q===void 0||!Number.isFinite(q)||q<0||B===void 0||!u9.includes(B)||G===void 0||!/^\d{4}-\d{2}$/.test(G)||J===void 0||J.trim()!==J||J===""||U===void 0||!Number.isSafeInteger(U)||U<0||L===void 0||!Number.isSafeInteger(L)||L<0||D===void 0||!Number.isSafeInteger(D)||D<0||P!==void 0&&(P.trim()!==P||P==="")||F!==void 0&&!q$(F)||A!==void 0&&!q$(A)||V!=="tokens"&&V!=="request"&&V!=="subscription")return v({code:"data_loss",layer:"storage",retryability:"non-retryable",message:`spend.metered event ${$.id} payload is malformed \u2014 ledger rebuild fails closed`});let N={chargeId:Y,eventId:$.id,traceId:W,ts:$.ts,periodKey:G,provider:j,unit:V,tokensIn:U,tokensOut:L,requests:D,usd:q,priceVersion:J,category:B};if(P!==void 0)N.model=P;if(F!==void 0)N.orderId=F;if(A!==void 0)N.runId=A;if(X("reserve")==="sacred-review")N.reserve="sacred-review";return H(N)}function QY($){return $.slice(0,7)}class k1{active;pending;activePeriodKey;deps;constructor($,Z){this.active=$,this.deps=Z,this.activePeriodKey=QY(Z.now())}roll(){let $=QY(this.deps.now());if($!==this.activePeriodKey){if(this.activePeriodKey=$,this.pending!==void 0)this.active=this.pending,this.pending=void 0}}periodKey(){return this.roll(),this.activePeriodKey}config(){return this.roll(),this.active}configure($){this.roll(),this.pending=$}pendingConfig(){return this.roll(),this.pending}reserveTotal(){let $=this.config();if($.monthlyUsd<=0)return 0;let Z=$.reserves,Q=Z===void 0?5:Z.reduce((X,z)=>X+z.usd,0);return Math.min(Q,$.monthlyUsd)}remaining(){return this.config().monthlyUsd-this.deps.periodSpend(this.activePeriodKey)}state(){return this.roll(),this.stateForSpend(this.deps.periodSpend(this.activePeriodKey))}stateForSpend($){let Z=this.config();if(Z.monthlyUsd<=0)return"zero-envelope";let Q=Z.monthlyUsd-$,X=0.000000001;if(Q<=X)return"exhausted";if($>=0.9*Z.monthlyUsd-X)return"reserve-only";if(Q<this.reserveTotal()-X)return"reserve-only";return"open"}}f();var $N=0.000000001;class fB{events=[];ulid=V$();append($){let Z=[];for(let Q of $)this.events.push(Q),Z.push({id:this.ulid(),outcome:"appended"});return H(Z)}ofKind($){return this.events.filter((Z)=>Z.kind===$)}}class XY{ledger;accountant;sink;pricing;now;ulid=V$();lastState;constructor($){this.sink=$.sink,this.pricing=$.pricing??tz(),this.ledger=$.ledger??new kQ,this.now=$.now??(()=>new Date().toISOString()),this.accountant=new k1($.envelope,{periodSpend:(Z)=>this.ledger.periodSpend(Z),now:this.now}),this.lastState=this.accountant.state()}configureEnvelope($){this.accountant.configure($)}charge($){let Z=QN($);if(!K(Z))return Z;let Q=this.ledger.health();if(Q!=="healthy")return v({code:"unavailable",layer:"kernel",retryability:"transient",message:`spend ledger projection is ${Q} \u2014 meter FAILS CLOSED until rebuilt from ledger events (FM-21)`});let X=this.accountant.state();if(X==="zero-envelope")return G$("zero-envelope: monthlyUsd=0 \u2014 paid capabilities are dormant-by-declaration; "+"pay-class actions are uncallable as a distinct state, not a failing one (D7 wave-3, credits \xA73.2, FM-21)");let z;try{let A=this.pricing.priceFor($.provider,$.model);if(!K(A))return A;if(A.ok.unit!==$.unit)return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`pricing unit mismatch for provider='${$.provider}' model='${$.model??""}': MeteredCall.unit='${$.unit}', ${this.pricing.version} row.unit='${A.ok.unit}' \u2014 `+"paid call FAILS CLOSED instead of landing an unpriced charge"});let N=fQ(A.ok,{tokensIn:$.tokensIn??0,tokensOut:$.tokensOut??0,requests:$.requests??0});if(!K(N))return N;z=N.ok}catch(A){return v({code:"internal",layer:"kernel",retryability:"non-retryable",message:`pricing module unloadable \u2014 every paid call HARD-ERRORS, never free-rides (doc \xA76.6a): ${String(A)}`})}let Y=this.accountant.config(),j=this.accountant.periodKey(),W=this.ledger.periodSpend(j),V=$.reserve==="sacred-review";if(X==="exhausted")return this.refuse("ceiling hit \u2014 'exhausted': ALL paid calls refuse; local-only routing posture engages (credits \xA73.2)");if(X==="reserve-only"&&!V)return this.refuse("'reserve-only': only sacred-review reserve-tagged charges pass (credits \xA73.2)");let q=V?Y.monthlyUsd:Y.monthlyUsd-this.accountant.reserveTotal();if(W+z>q+$N)return this.refuse(`charge of $${z.toFixed(6)} would cross the ${V?"envelope ceiling":"ordinary ceiling (monthlyUsd \u2212 sacred reserve)"} ($${W.toFixed(6)} spent of $${q.toFixed(6)}) \u2014 the ceiling is a wall, not a scheduler (credits \xA73.1)`);let B=$.ts??this.now(),G=this.ulid(),J={chargeId:G,provider:$.provider,traceId:$.traceId,unit:$.unit,tokensIn:$.tokensIn??0,tokensOut:$.tokensOut??0,requests:$.requests??0,usd:z,priceVersion:this.pricing.version,category:$.category,periodKey:j};if($.model!==void 0)J.model=$.model;if($.orderId!==void 0)J.orderId=$.orderId;if($.runId!==void 0)J.runId=$.runId;if(V)J.reserve="sacred-review";let U=[$Y(J,B)],L=this.accountant.stateForSpend(W+z);if(L!==X)U.push(ZY({from:X,to:L,periodKey:j,monthlyUsd:Y.monthlyUsd,remainingUsd:Y.monthlyUsd-(W+z),feedNotice:L==="reserve-only"||L==="exhausted"},B));let D=this.sink.append(U);if(!K(D))return D;let P=D.ok[0];if(P===void 0)return v({code:"internal",layer:"storage",retryability:"transient",message:"sink returned no append result for the spend.metered event"});let F=this.ledger.record({chargeId:G,eventId:P.id,ts:B,periodKey:j,provider:$.provider,traceId:$.traceId,...$.model!==void 0?{model:$.model}:{},unit:$.unit,tokensIn:$.tokensIn??0,tokensOut:$.tokensOut??0,requests:$.requests??0,usd:z,priceVersion:this.pricing.version,category:$.category,...$.orderId!==void 0?{orderId:$.orderId}:{},...$.runId!==void 0?{runId:$.runId}:{},...V?{reserve:"sacred-review"}:{}});if(!K(F))return F;return this.lastState=L,H({chargeId:G,eventId:P.id,traceId:$.traceId,usd:z,tokens:{in:$.tokensIn??0,out:$.tokensOut??0},requests:$.requests??0,priceVersion:this.pricing.version,periodKey:j,state:L,remaining:Y.monthlyUsd-(W+z)})}observedState(){return this.lastState}refuse($){return v({code:"resource_exhausted",layer:"kernel",retryability:"throttling",message:`meter.charge refused: ${$}`})}}var ZN=new Set(["provider","model","unit","tokensIn","tokensOut","requests","traceId","orderId","runId","category","reserve","ts","usd"]);function QN($){if(typeof $!=="object"||$===null||Array.isArray($))return e$("MeteredCall must be an object");let Z=$;if(typeof Z.provider!=="string"||Z.provider.trim()===""||Z.provider!==Z.provider.trim())return e$("MeteredCall.provider must be a non-empty trimmed provider id");if(Z.model!==void 0&&(typeof Z.model!=="string"||Z.model.trim()===""||Z.model!==Z.model.trim()))return e$("MeteredCall.model, when present, must be a non-empty trimmed model id");if(Z.unit!=="tokens"&&Z.unit!=="request"&&Z.unit!=="subscription")return e$("MeteredCall.unit must be 'tokens', 'request', or 'subscription'");if(typeof Z.category!=="string"||!u9.includes(Z.category))return e$(`MeteredCall.category must be one of ${u9.join("|")}`);if(!q$($.traceId))return e$("MeteredCall.traceId is required and must be a canonical ULID \u2014 every spend.metered receipt must join its I-6 trace");let Q=$;for(let X of Object.keys(Q))if(!ZN.has(X))return e$(`unsupported caller-supplied MeteredCall field '${X}' \u2014 pricing inputs come only from the versioned pricing table`);if(Q.orderId!==void 0&&!q$(Q.orderId))return e$("MeteredCall.orderId, when present, must be a canonical ULID");if(Q.runId!==void 0&&!q$(Q.runId))return e$("MeteredCall.runId, when present, must be a canonical ULID");for(let X of["tokensIn","tokensOut","requests"]){if(!Object.prototype.hasOwnProperty.call(Q,X))continue;let z=Q[X];if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)return e$(`MeteredCall.${X} must be a finite non-negative safe integer from provider usage`)}if($.unit==="tokens"){if(!Object.prototype.hasOwnProperty.call(Q,"tokensIn")||!Object.prototype.hasOwnProperty.call(Q,"tokensOut"))return e$("exact token usage is unknown: both MeteredCall.tokensIn and tokensOut are required");if(Object.prototype.hasOwnProperty.call(Q,"requests"))return e$("MeteredCall.requests is not valid for unit='tokens'")}else{if(!Object.prototype.hasOwnProperty.call(Q,"requests"))return e$(`${$.unit} usage is unknown: MeteredCall.requests is required`);if(Object.prototype.hasOwnProperty.call(Q,"tokensIn")||Object.prototype.hasOwnProperty.call(Q,"tokensOut"))return e$(`token counts are not valid for unit='${$.unit}'`)}if(($.unit==="tokens"||$.unit==="request")&&Object.prototype.hasOwnProperty.call(Q,"usd"))return e$(`caller-supplied usd is rejected for unit='${$.unit}' \u2014 the meter computes usd from the versioned pricing table`);return H(!0)}function e$($){return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:$})}f();F0();var YN=new Set(["provider","model","unit","tokensIn","tokensOut","requests"]);function zY($,Z){return(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"paid-call usage must be an object"});let X=Object.keys(Q).find((z)=>!YN.has(z));if(X!==void 0)return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`paid-call usage field '${X}' is not provider usage; workers cannot author USD or attribution`});return $.charge({...Q,traceId:Z.traceId,category:Z.category,...Z.orderId!==void 0?{orderId:Z.orderId}:{},...Z.runId!==void 0?{runId:Z.runId}:{},...Z.reserve!==void 0?{reserve:Z.reserve}:{}})}}function YY($,Z,Q){let{periodKey:X}=Q;if(Z.status==="unreachable")return{status:"billing-unknown",periodKey:X,reason:Z.reason};let z=Q.deltaThreshold??az,Y=new Map;for(let G of Z.lines){if(!G.day.startsWith(X))continue;Y.set(G.provider,(Y.get(G.provider)??0)+G.usd)}let j=$.totalsByProvider(X),W=new Set([...Y.keys(),...j.keys()]),V=[],q=[],B=[];for(let G of[...W].sort()){let J=j.get(G)??0,U=Y.get(G)??0,L=J>0?Math.abs(U-J)/J:U>0?Number.POSITIVE_INFINITY:0;if(V.push({provider:G,ledgerUsd:J,billedUsd:U,deltaFraction:L}),L>z)q.push({kind:"billing-delta",provider:G,deltaFraction:L,detail:`provider '${G}' billed $${U.toFixed(6)} vs computed $${J.toFixed(6)} (${Number.isFinite(L)?(L*100).toFixed(1)+"%":"unmetered spend"}) \u2014 `+">10% delta is an incident (I-5); the ledger keeps token-truth, usd stays recomputable (FM-8)"}),B.push({kind:"harness:repricing",provider:G,reason:`reconciliation delta ${Number.isFinite(L)?(L*100).toFixed(1)+"%":"\u221E"} for '${G}' in ${X} \u2014 review the pricing table entry`})}if(q.length>0)return{status:"delta-incident",periodKey:X,perProvider:V,incidents:q,repricingOrders:B};return{status:"reconciled",periodKey:X,perProvider:V}}f();f();var jY=60000,kB=5,wB=3,WY=30000,mB=3600000,hB=300000,uB=1,pB=10,jN=7,VY=3600000,lB=3,WN=5,VN=5,cB=0.05;class w1{db;clock;appender;wallNow;probe;paidPaused=!1;constructor($){this.db=$.db,this.clock=$.clock,this.appender=$.appender,this.wallNow=$.wallNow,this.probe=$.probe}stateFor($){let Z=this.raw($);if(Z===null)return"CLOSED";if(Z.state==="OPEN"){let Q=this.clock.awakeNowMs();if(Z.opened_awake_ms!==null&&Q-Z.opened_awake_ms>=Z.cooldown_ms)return"HALF_OPEN"}return Z.state}recordSuccess($){this.ensure($),this.db.query("UPDATE breakers SET consecutive_unavailable = 0 WHERE name = ?").run($)}recordFailure($,Z){this.ensure($);let Q=this.clock.awakeNowMs();if(this.db.query("INSERT INTO breaker_failures (name, at_awake_ms) VALUES (?, ?)").run($,Q),this.db.query("DELETE FROM breaker_failures WHERE name = ? AND at_awake_ms < ?").run($,Q-jY),Z.code==="unavailable")this.db.query("UPDATE breakers SET consecutive_unavailable = consecutive_unavailable + 1 WHERE name = ?").run($);else this.db.query("UPDATE breakers SET consecutive_unavailable = 0 WHERE name = ?").run($);let X=this.raw($);if(X===null)return x("internal",`breaker '${$}' vanished`);if(X.state==="OPEN")return{ok:{state:"OPEN"}};if(X.state==="HALF_OPEN")return this.open($,X.open_count);if(this.db.query("SELECT COUNT(*) AS c FROM breaker_failures WHERE name = ? AND at_awake_ms >= ?").get($,Q-jY).c>=kB||X.consecutive_unavailable>=wB)return this.open($,X.open_count);return{ok:{state:X.state}}}probeHalfOpen(){let $=[],Z=[],Q=this.db.query("SELECT * FROM breakers WHERE state IN ('OPEN', 'HALF_OPEN')").all(),X=this.clock.awakeNowMs();for(let z of Q){if(z.state==="OPEN"){if(z.opened_awake_ms===null||X-z.opened_awake_ms<z.cooldown_ms)continue;let j=this.appender.append(p8.halfOpen,{name:z.name},this.wallNow());if(!("ok"in j))return j;this.db.query("UPDATE breakers SET state = 'HALF_OPEN' WHERE name = ?").run(z.name)}if(this.probe===void 0)continue;let Y=this.probe(z.name);if("ok"in Y&&Y.ok.healthy){this.db.query("UPDATE breakers SET state = 'CLOSED', consecutive_unavailable = 0, opened_awake_ms = NULL WHERE name = ?").run(z.name);let j=this.appender.append(p8.closed,{name:z.name},this.wallNow());if(!("ok"in j))return j;$.push(z.name)}else{let j=this.open(z.name,z.open_count);if(!("ok"in j))return j;Z.push(z.name)}}return{ok:{closed:$,reopened:Z}}}open($,Z){let Q=Math.min(WY*2**Z,mB);this.db.query("UPDATE breakers SET state = 'OPEN', opened_awake_ms = ?, open_count = ?, cooldown_ms = ? WHERE name = ?").run(this.clock.awakeNowMs(),Z+1,Q,$);let X=this.appender.append(p8.opened,{name:$,cooldownMs:Q,openCount:Z+1},this.wallNow());if(!("ok"in X))return X;return{ok:{state:"OPEN"}}}ensure($){this.db.query("INSERT OR IGNORE INTO breakers (name, state, cooldown_ms) VALUES (?, 'CLOSED', ?)").run($,WY)}breakers(){return this.db.query("SELECT * FROM breakers").all().map((Z)=>({name:Z.name,state:this.stateFor(Z.name),openCount:Z.open_count,cooldownMs:Z.cooldown_ms}))}takeRateToken($){let Z=$.constraints?.ratePerHour;if(Z===void 0)return!0;return this.takeFromBucket(`rate:${$.name}`,Z,Z)}takeRetryQuota($){return this.takeFromBucket(`retry:${$}`,WN,VN)}takeFromBucket($,Z,Q){let X=this.clock.awakeNowMs(),z=this.db.query("SELECT * FROM buckets WHERE key = ?").get($),Y;if(z===null)Y=Z;else{let j=z.tokens+(X-z.updated_awake_ms)/3600000*z.refill_per_hour;Y=Math.min(Z,j)}if(Y<1)return this.db.query("INSERT OR REPLACE INTO buckets (key, tokens, capacity, refill_per_hour, updated_awake_ms) VALUES (?, ?, ?, ?, ?)").run($,Y,Z,Q,X),!1;return this.db.query("INSERT OR REPLACE INTO buckets (key, tokens, capacity, refill_per_hour, updated_awake_ms) VALUES (?, ?, ?, ?, ?)").run($,Y-1,Z,Q,X),!0}paidWorkPaused(){return this.paidPaused}resumePaidWork(){this.paidPaused=!1}noteSpend($,Z,Q,X={}){let z=`${$}:${Z}`,Y=this.clock.awakeNowMs(),j=Y-Y%hB,W=X.learn??!0;if(this.db.query(`INSERT INTO spend_windows (scope, window_start_awake_ms, usd, learn) VALUES (?, ?, ?, ?)
396
+ ON CONFLICT(scope, window_start_awake_ms) DO UPDATE SET usd = usd + excluded.usd`).run(z,j,Q,W?1:0),!W)return{ok:{tripped:!1}};let V=this.db.query("SELECT usd FROM spend_windows WHERE scope = ? AND window_start_awake_ms = ?").get(z,j),q=this.db.query(`SELECT AVG(usd) AS mean, COUNT(*) AS n FROM spend_windows
397
+ WHERE scope = ? AND learn = 1 AND window_start_awake_ms < ? AND window_start_awake_ms >= ?`).get(z,j,j-jN*86400000),B=q.n>0&&q.mean!==null?q.mean:cB,G=Math.max(uB,pB*B);if((V?.usd??0)>G)return this.tripSpend(`spend:${z}`,{rule:"rate",scope:z,observedUsd:V?.usd??0,thresholdUsd:G,windowStartAwakeMs:j});return{ok:{tripped:!1}}}noteIntentFingerprint($,Z,Q){let X=this.clock.awakeNowMs();this.db.query("INSERT INTO fingerprints (contract, fp, at_awake_ms) VALUES (?, ?, ?)").run($,Z,X),this.db.query("DELETE FROM fingerprints WHERE at_awake_ms < ?").run(X-VY);let z=this.db.query("SELECT COUNT(*) AS c FROM fingerprints WHERE contract = ? AND fp = ? AND at_awake_ms >= ?").get($,Z,X-VY).c;if(z>lB)return this.tripSpend(`spend:fingerprint:${$}`,{rule:"repeat-fingerprint",contract:$,fingerprint:Z,count:z});return{ok:{tripped:!1}}}tripSpend($,Z){this.paidPaused=!0;let Q=this.appender.append(p8.tripped,{name:$,...Z},this.wallNow());if(!("ok"in Q))return Q;return this.appender.fileIncident(`spend breaker '${$}' tripped (${String(Z.rule)}) \u2014 paid work paused; inbox notice (D7: the ceiling is the only hard stop)`,"sev2","guard",this.wallNow()),{ok:{tripped:!0}}}nightlyReconciliation($,Z,Q){let X=YY($,Z,{periodKey:Q}),z=X.status==="billing-unknown"?null:X.perProvider.map((j)=>({provider:j.provider,ledgerUsd:j.ledgerUsd,billedUsd:j.billedUsd,deltaFraction:Number.isFinite(j.deltaFraction)?j.deltaFraction:"non-finite"})),Y=this.appender.append(l8.spendReconciled,{status:X.status,periodKey:Q,perProvider:z,reason:X.status==="billing-unknown"?X.reason:null},this.wallNow());if(!("ok"in Y))return Y;if(X.status==="delta-incident")for(let j of X.incidents)this.appender.fileIncident(`spend reconciliation delta >10% for provider '${j.provider}': ${j.detail}`,"sev2","guard",this.wallNow());return{ok:X}}raw($){return this.db.query("SELECT * FROM breakers WHERE name = ?").get($)??null}}class m1{db;constructor($){this.db=$,$.exec("CREATE TABLE IF NOT EXISTS falcon_clock (k TEXT PRIMARY KEY, v TEXT NOT NULL)")}open($){if(this.get("phase")===null)return this.set("awake_ms","0"),this.set("last_wall_ms",String($)),this.set("phase","awake"),{phase:"awake",gapMs:0};let Q=Math.max(0,$-Number(this.get("last_wall_ms")??$));return this.set("phase","recovering"),{phase:"recovering",gapMs:Q}}get($){return this.db.query("SELECT v FROM falcon_clock WHERE k = ?").get($)?.v??null}set($,Z){this.db.query("INSERT OR REPLACE INTO falcon_clock (k, v) VALUES (?, ?)").run($,Z)}phase(){return this.get("phase")??"awake"}awakeNowMs(){return Number(this.get("awake_ms")??"0")}tick($){let Z=this.phase();if(Z!=="awake")return x("failed_precondition",`tick refused in phase '${Z}' \u2014 reconcile the gap first (falcon \xA74.1)`);let Q=Number(this.get("last_wall_ms")??String($)),X=this.awakeNowMs()+Math.max(0,$-Q);return this.set("awake_ms",String(X)),this.set("last_wall_ms",String($)),{ok:X}}sleepBegan($){let Z=this.tick($);if(!("ok"in Z))return Z;return this.set("phase","asleep"),Z}reconcile($){if(this.phase()==="awake")return{gapMs:0};let Z=Number(this.get("last_wall_ms")??String($)),Q=Math.max(0,$-Z);return this.set("last_wall_ms",String($)),this.set("phase","awake"),{gapMs:Q}}}class h1{falcon;fuses;constructor($,Z){this.falcon=$,this.fuses=Z}awakeNowMs(){return this.falcon.awakeNowMs()}phase(){return this.falcon.phase()}tick($){let Z=this.falcon.tick($);if(!("ok"in Z))return Z;let Q=this.fuses.tick($);if(!("ok"in Q))return Q;return Z}sleepBegan($){let Z=this.falcon.sleepBegan($);if(!("ok"in Z))return Z;let Q=this.fuses.sleepBegan($);if(!("ok"in Q))return Q;return Z}reconcile($){let Z=this.falcon.reconcile($),Q=this.fuses.reconcile($);if(!("ok"in Q))return Q;return{ok:{gapMs:Math.max(Z.gapMs,Q.ok.gapMs),resurface:Q.ok.resurface}}}}import{Database as KN}from"bun:sqlite";function KY($){let Z=new KN($,{create:!0});Z.exec("PRAGMA journal_mode = WAL"),Z.exec("PRAGMA busy_timeout = 5000"),Z.exec("PRAGMA synchronous = FULL"),Z.exec(`CREATE TABLE IF NOT EXISTS jobs (
398
+ id TEXT PRIMARY KEY,
399
+ class TEXT NOT NULL,
400
+ order_id TEXT,
401
+ due_at_awake_ms INTEGER NOT NULL,
402
+ priority INTEGER NOT NULL,
403
+ state TEXT NOT NULL,
404
+ attempt INTEGER NOT NULL DEFAULT 0,
405
+ visible_at_awake_ms INTEGER NOT NULL DEFAULT 0,
406
+ backoff_ms INTEGER NOT NULL DEFAULT 0,
407
+ enqueued_awake_ms INTEGER NOT NULL DEFAULT 0
408
+ )`),Z.exec("CREATE INDEX IF NOT EXISTS jobs_claim ON jobs (state, due_at_awake_ms, priority)"),Z.exec(`CREATE TABLE IF NOT EXISTS leases (
409
+ pattern TEXT PRIMARY KEY,
410
+ holder_run_id TEXT NOT NULL,
411
+ expires_at_awake_ms INTEGER NOT NULL
412
+ )`),Z.exec(`CREATE TABLE IF NOT EXISTS runs (
413
+ run_id TEXT PRIMARY KEY,
414
+ order_id TEXT NOT NULL,
415
+ worker_type TEXT NOT NULL,
416
+ state TEXT NOT NULL,
417
+ queued_awake_ms INTEGER NOT NULL,
418
+ leased_awake_ms INTEGER,
419
+ spawned_awake_ms INTEGER,
420
+ heartbeat_awake_ms INTEGER,
421
+ heartbeat_every_sec INTEGER NOT NULL DEFAULT 20,
422
+ wall_deadline_awake_ms INTEGER,
423
+ budget_tokens REAL NOT NULL,
424
+ budget_usd REAL NOT NULL,
425
+ budget_wallclock_min REAL NOT NULL,
426
+ spent_tokens REAL NOT NULL DEFAULT 0,
427
+ spent_usd REAL NOT NULL DEFAULT 0,
428
+ respawn_of TEXT,
429
+ reap_count INTEGER NOT NULL DEFAULT 0,
430
+ model_pin TEXT,
431
+ model_seen TEXT,
432
+ trace_id TEXT NOT NULL,
433
+ exit_status TEXT,
434
+ order_json TEXT NOT NULL,
435
+ slice_demand_id TEXT,
436
+ worker_type_json TEXT,
437
+ terminal_payload_json TEXT,
438
+ terminal_summary_json TEXT,
439
+ terminal_event_id TEXT,
440
+ terminal_summary_event_id TEXT,
441
+ terminal_order_failure_reason TEXT,
442
+ terminal_postlude_done INTEGER NOT NULL DEFAULT 0
443
+ )`);let Q=Z.query("PRAGMA table_info(runs)").all(),X={worker_type_json:"TEXT",terminal_payload_json:"TEXT",terminal_summary_json:"TEXT",terminal_event_id:"TEXT",terminal_summary_event_id:"TEXT",terminal_order_failure_reason:"TEXT",terminal_postlude_done:"INTEGER NOT NULL DEFAULT 0"};for(let[z,Y]of Object.entries(X))if(!Q.some((j)=>j.name===z))Z.exec(`ALTER TABLE runs ADD COLUMN ${z} ${Y}`);return Z.exec("CREATE INDEX IF NOT EXISTS runs_state ON runs (state, heartbeat_awake_ms)"),Z.exec(`CREATE TABLE IF NOT EXISTS intents (
444
+ intent_id TEXT PRIMARY KEY,
445
+ contract TEXT NOT NULL,
446
+ params_json TEXT NOT NULL,
447
+ idempotency_key TEXT NOT NULL,
448
+ execute_after_awake_ms INTEGER NOT NULL,
449
+ minted_wall_ms INTEGER NOT NULL,
450
+ fuse_ms INTEGER NOT NULL DEFAULT 0,
451
+ effective_class TEXT NOT NULL,
452
+ category TEXT,
453
+ reversibility TEXT NOT NULL,
454
+ fuse_level TEXT NOT NULL,
455
+ state TEXT NOT NULL,
456
+ attempt INTEGER NOT NULL DEFAULT 0,
457
+ verify_attempts INTEGER NOT NULL DEFAULT 0,
458
+ first_verify_awake_ms INTEGER,
459
+ next_attempt_awake_ms INTEGER NOT NULL DEFAULT 0,
460
+ paused_ms_total INTEGER NOT NULL DEFAULT 0,
461
+ deferred_since_awake_ms INTEGER,
462
+ requested_by_run TEXT,
463
+ requested_by_order TEXT,
464
+ requester_worker_type TEXT,
465
+ grant_id TEXT,
466
+ recovery_reentry INTEGER NOT NULL DEFAULT 0,
467
+ provenance_json TEXT,
468
+ last_error TEXT
469
+ )`),Z.exec("CREATE INDEX IF NOT EXISTS intents_scan ON intents (state, execute_after_awake_ms)"),Z.exec(`CREATE TABLE IF NOT EXISTS buckets (
470
+ key TEXT PRIMARY KEY,
471
+ tokens REAL NOT NULL,
472
+ capacity REAL NOT NULL,
473
+ refill_per_hour REAL NOT NULL,
474
+ updated_awake_ms INTEGER NOT NULL
475
+ )`),Z.exec(`CREATE TABLE IF NOT EXISTS breakers (
476
+ name TEXT PRIMARY KEY,
477
+ state TEXT NOT NULL,
478
+ consecutive_unavailable INTEGER NOT NULL DEFAULT 0,
479
+ opened_awake_ms INTEGER,
480
+ open_count INTEGER NOT NULL DEFAULT 0,
481
+ cooldown_ms INTEGER NOT NULL DEFAULT 0
482
+ )`),Z.exec(`CREATE TABLE IF NOT EXISTS breaker_failures (
483
+ name TEXT NOT NULL,
484
+ at_awake_ms INTEGER NOT NULL
485
+ )`),Z.exec("CREATE INDEX IF NOT EXISTS breaker_failures_at ON breaker_failures (name, at_awake_ms)"),Z.exec(`CREATE TABLE IF NOT EXISTS spend_windows (
486
+ scope TEXT NOT NULL,
487
+ window_start_awake_ms INTEGER NOT NULL,
488
+ usd REAL NOT NULL DEFAULT 0,
489
+ learn INTEGER NOT NULL DEFAULT 1,
490
+ PRIMARY KEY (scope, window_start_awake_ms)
491
+ )`),Z.exec(`CREATE TABLE IF NOT EXISTS fingerprints (
492
+ contract TEXT NOT NULL,
493
+ fp TEXT NOT NULL,
494
+ at_awake_ms INTEGER NOT NULL
495
+ )`),Z.exec("CREATE INDEX IF NOT EXISTS fingerprints_scan ON fingerprints (contract, fp, at_awake_ms)"),Z.exec("CREATE TABLE IF NOT EXISTS boots (at_wall_ms INTEGER NOT NULL)"),Z.exec(`CREATE TABLE IF NOT EXISTS daily_calls (
496
+ name TEXT NOT NULL,
497
+ day TEXT NOT NULL,
498
+ used INTEGER NOT NULL DEFAULT 0,
499
+ PRIMARY KEY (name, day)
500
+ )`),Z}f();var qY=4,qN=8,HY=3,nB=3,HN=2000,dB=60000,BN=86400000;var iB=["EFFECTED","FAILED","UNKNOWN","RECALLED","EXPIRED"];function BY($){return`act_${$}`}function sB($){switch($){case"pay":case"post":case"send":case"delete-at-source":return $;default:return"dispatch-other"}}var JN=["pay","post","send","delete-at-source"];class u1{map=new Map;register($,Z){this.map.set($,Z)}forIntent($){return this.map.get($)}resolve=($)=>{let Z=this.map.get($.id);if(Z===void 0)return x("not_found",`no evidence registered for egress request '${$.id}'`);return{ok:Z}}}class p1{db;clock;fuses;appender;breakers;chokepoint;evidence;upstream;wallNow;contracts=new Map;confidentAfter;volatileParams;envelope;watcher;ulid=V$();constructor($){this.db=$.db,this.clock=$.clock,this.fuses=$.fuses,this.appender=$.appender,this.breakers=$.breakers,this.chokepoint=$.chokepoint,this.evidence=$.evidence,this.upstream=$.upstream,this.wallNow=$.wallNow,this.confidentAfter=$.confidentAfterMs??{},this.volatileParams=$.volatileParams??{},this.envelope=$.envelope,this.watcher=$.watchdog??null;for(let Z of $.contracts){let Q=t4(Z);if(!K(Q))throw Error(`invalid ActionContract '${Z.name}': ${"err"in Q?Q.err.message:"empty"}`);this.contracts.set(Z.name,Z)}}attachWatchdog($){this.watcher=$}paramFingerprint($,Z){let Q=this.volatileParams[$]??[],X=Z;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let z={};for(let[Y,j]of Object.entries(Z))if(!Q.includes(Y))z[Y]=j;X=z}return L$(C$(X))}requestAction($){if(!this.appender.healthy())return x("unavailable","HALT_LOUD: an action that can't be evented may not fire (D24/N1)","retry-at-higher-level");if(this.clock.phase()!=="awake")return x("failed_precondition",`requestAction refused in phase '${this.clock.phase()}' \u2014 reconcile first (\xA74.1)`);if($.params!==null&&typeof $.params==="object"&&!Array.isArray($.params)&&$.params.requestedBy!==void 0)return x("invalid_argument","params.requestedBy rejected \u2014 requester provenance is falcon-stamped from the IPC session, never caller-supplied (I-3, B3-P2-2)");let Z=this.contracts.get($.contract);if(Z===void 0)return x("not_found",`no ActionContract named '${$.contract}' \u2014 declaration is the connector's job (I-3)`);let Q=bQ($.params,Z.params);if(!("ok"in Q))return Q;let X={params:$.params,envelope:{remaining:this.envelope?.remaining()??Number.MAX_SAFE_INTEGER}};for(let[R,O]of Object.entries(Z.constraints?.paramBounds??{})){let T=$.params!==null&&typeof $.params==="object"&&!Array.isArray($.params)?$.params[R]:void 0;if(typeof T!=="number")return x("invalid_argument",`constraint bound on '${R}' requires a numeric param`);let m=_V(T,O,X);if(!K(m))return m;if(!m.ok)return x("failed_precondition",`param '${R}'=${T} violates its declared Bound (I-3 constraints)`)}let z=Z.effect.class;for(let R of Z.escalateWhen??[]){let O=AV(R.predicate,X);if(!K(O))return O;if(O.ok)z=lz(z,R.class)}let Y=Z.effect.category;if(z==="dispatch"&&Y==="pay"&&this.envelope!==void 0&&this.envelope.remaining()<=0)return x("resource_exhausted","envelope exhausted \u2014 pay-class intents refuse at INTENT (D7)","throttling");let j=this.ulid(),W=C$($.params),V=this.paramFingerprint(Z.name,$.params),q=this.breakers.noteIntentFingerprint(Z.name,V,this.wallNow());if(!("ok"in q))return q;if(q.ok.tripped)return x("resource_exhausted",`repeat-fingerprint breaker tripped for '${Z.name}' \u2014 >3 identical intents in 1h (falcon \xA74.5); incident filed`,"throttling");if(z==="dispatch"&&this.watcher===null)return x("failed_precondition",`refusing to arm a fuse on '${Z.name}': this falcon hosts no watchdog, so nothing could recall inside the window `+"(undo-layer \xA74.1a \u2014 a fuse may only arm where a recall can land). Compose the watchdog pass, or route an action the chokepoint does not fuse.");let B=this.overallTaint($.provenance);this.evidence.register(j,{bytes:W,taint:B,...$.contextOrigins!==void 0?{contextOrigins:$.contextOrigins}:{},workerManifest:$.session?.capabilities??{actionClasses:[],taintExposure:"mediated"},actionContract:Z,...$.provenance!==void 0?{paramProvenance:$.provenance}:{},...$.recipient!==void 0?{recipient:$.recipient}:{},...this.usdOf($.params)!==void 0?{usd:this.usdOf($.params)}:{}});let G={id:j,channel:"connector_action",payloadRef:{sha256:L$(W),bytes:Buffer.byteLength(W,"utf8")},actor:{workerId:$.session?.runId??"kernel",workerType:$.session?.workerType??"kernel"},...$.grantId!==void 0?{grantId:$.grantId}:{},contract:{action:Z.name,class:z,...Y!==void 0?{category:Y}:{},reversibility:Z.effect.reversibility}},J=this.chokepoint.submit(G);if(!K(J))return J;let U=J.ok;if(U.decision==="refused"){let R=U.error;return x(R?.code==="permission_denied"?"permission_denied":"failed_precondition",`chokepoint refused '${Z.name}': ${U.reason??"unspecified"} \u2014 ${U.reasons.join("; ")}`,"non-retryable",R)}let L=U.decision==="pass_with_fuse"?U.fuseMs??0:0,D=sB(Y);if(z==="dispatch"&&Y!==void 0&&JN.includes(Y))L=Math.max(L,P8.rows[D].floorMs);if(L>0&&this.watcher===null)return x("failed_precondition",`refusing to arm a ${L}ms fuse on '${Z.name}' (effect class '${z}'): this falcon hosts no watchdog, `+"so nothing could recall inside the window (undo-layer \xA74.1a). A non-dispatch class reached the fuse table \u2014 the class-level "+"refusal above no longer covers the space, so the fuse policy and this guard have drifted apart.");let P=this.clock.awakeNowMs(),F=this.wallNow(),A=$.session!==void 0?{runId:$.session.runId,...$.session.orderId!==void 0?{orderId:$.session.orderId}:{}}:void 0,N={contract:Z.name,params:$.params,idempotencyKey:BY(j),executeAfter:U0(F+L),...A!==void 0?{requestedBy:A}:{}},S=this.appender.append("action.intent",N,F);if(!("ok"in S))return S;if(this.db.query(`INSERT INTO intents (intent_id, contract, params_json, idempotency_key, execute_after_awake_ms,
501
+ minted_wall_ms, fuse_ms, effective_class, category, reversibility, fuse_level, state,
502
+ requested_by_run, requested_by_order, requester_worker_type, grant_id, provenance_json)
503
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INTENT', ?, ?, ?, ?, ?)`).run(j,Z.name,JSON.stringify($.params),BY(j),P+L,F,L,z,Y??null,Z.effect.reversibility,Z.fuse,A?.runId??null,A?.orderId??null,$.session?.workerType??null,$.grantId??null,$.provenance!==void 0?JSON.stringify($.provenance):null),L>0){let R=this.fuses.arm(j,D,L);if(!("ok"in R))return R;let O=this.appender.append("fuse.armed",{intentId:j,key:D,fuseMs:L},F);if(!("ok"in O))return O}return{ok:{intentId:j,fuseMs:L}}}recall($,Z,Q,X){if(Z==="watchdog"&&X===void 0)return x("invalid_argument","action.recall by 'watchdog' must carry watchdogRunId (undo-layer \xA73.3 \u2014 its runId rides the payload)");let z=this.raw($);if(z===null)return x("not_found",`no intent '${$}'`);if(iB.includes(z.state))return x("failed_precondition",`intent '${$}' is terminal (${z.state}) \u2014 recall refused`);if(z.state!=="INTENT")return x("failed_precondition",`intent '${$}' already ${z.state} \u2014 the fuse elapsed; physics won (late recall is the undo layer's honest-notice path)`);if(z.fuse_ms>0){let W=this.fuses.recall($);if(!("ok"in W))return W;if(W.ok.disposition==="late-recall")return x("failed_precondition",`fuse for '${$}' already elapsed \u2014 late recall logged by the undo layer`)}let Y={intentId:$,by:Z,via:Q};if(X!==void 0){if(Y.watchdogRunId=X.runId,X.checkRef!==void 0)Y.checkRef=X.checkRef}let j=this.appender.append("action.recall",Y,this.wallNow());if(!("ok"in j))return j;return this.setState($,"RECALLED"),{ok:{state:"RECALLED",recallEventId:j.ok}}}armedForWatch(){let $=[],Z=[];for(let Q of this.fuses.armed()){let X=this.raw(Q.intentId);if(X===null||X.state!=="INTENT")continue;let z=this.contracts.get(X.contract),Y=this.evidence.forIntent(Q.intentId);if(z===void 0||Y===void 0){Z.push(Q);continue}let j={intentId:Q.intentId,contract:z,params:JSON.parse(X.params_json),fuseKey:Q.key,armedFuseMs:Q.fuseMs,armedAtAwakeMs:Q.armedAtAwakeMs,payloadSources:Y.taint.sources,contextSources:Y.contextOrigins??[],sourceContent:[{eventId:Q.intentId,text:Y.bytes}],baselines:{knownRecipients:[]}};if(z.effect.reversibility==="compensatable")j.compensation={pathDeclared:z.effect.compensation!==void 0,lastTestGreen:!1};$.push(j)}return{contexts:$,unwatchable:Z}}holdFuse($,Z){return this.fuses.hold($,Z)}tick(){if(!this.appender.healthy())return x("unavailable","HALT_LOUD: no EXECUTE while the event log is unwritable (N1)","retry-at-higher-level");let $=this.fuses.scanDue();if(!("ok"in $))return $;let Z=this.clock.awakeNowMs();for(let q of $.ok){let B=this.fuses.markElapsed(q.intentId);if(!("ok"in B))return B;let G=this.appender.append("fuse.elapsed",{intentId:q.intentId},this.wallNow());if(!("ok"in G))return G}let Q=[],X=[],z=[],Y=(q)=>{if(q.fuse_ms<=0||q.state!=="INTENT")return!1;let B=this.fuses.get(q.intent_id);return K(B)&&B.ok.state==="HELD"},j=this.db.query(`SELECT * FROM intents
504
+ WHERE state IN ('INTENT', 'VERIFYING') AND execute_after_awake_ms <= ? AND next_attempt_awake_ms <= ?
505
+ ORDER BY execute_after_awake_ms ASC
506
+ LIMIT ?`).all(Z,Z,qY*qN),W=j.filter(Y),V=[...j.filter((q)=>!Y(q)).slice(0,qY),...W];for(let q of V){if(q.fuse_ms>0&&q.state==="INTENT"){let L=this.fuses.get(q.intent_id);if(K(L)&&L.ok.state==="RECALLED"){this.setState(q.intent_id,"RECALLED");continue}}let B=this.contracts.get(q.contract);if(B===void 0){this.fail(q,x("failed_precondition",`contract '${q.contract}' no longer registered`).err);continue}let G=g1(B);if(q.state==="INTENT"&&G!==null&&q.paused_ms_total>G){this.expire(q,G),z.push(q.intent_id);continue}if(q.fuse_ms>0&&q.state==="INTENT"){let L=this.fuses.get(q.intent_id);if(K(L)&&L.ok.state==="HELD"){if(Z>q.execute_after_awake_ms+q.fuse_ms){this.expire(q,q.fuse_ms),z.push(q.intent_id);continue}X.push(q.intent_id);continue}}if(q.state==="INTENT"&&q.paused_ms_total>0&&G!==null){let L=this.reVerdict(q,B);if(!("ok"in L))return L;if(!L.ok)continue}let J=this.upstreamOf(B.name);if(this.breakers.stateFor(J)!=="CLOSED"){let L=q.deferred_since_awake_ms??Z;if(q.deferred_since_awake_ms===null)this.db.query("UPDATE intents SET deferred_since_awake_ms = ? WHERE intent_id = ?").run(Z,q.intent_id);let D=G??BN;if(Z-L>D)this.fail(q,x("unavailable",`breaker '${J}' OPEN past max-defer \u2014 intent failed, notice`,"retry-at-higher-level").err);else X.push(q.intent_id);continue}if(q.category==="pay"&&this.breakers.paidWorkPaused()){X.push(q.intent_id);continue}if(!this.breakers.takeRateToken(B)){X.push(q.intent_id);continue}let U=q.state==="VERIFYING"?this.verifyStep(q,B):this.executeStep(q,B);if(!("ok"in U))return U;Q.push(q.intent_id)}return{ok:{executed:Q,deferred:X,expired:z}}}rebuildFromEvents($){this.db.query("DELETE FROM intents").run();let Z=this.clock.awakeNowMs(),Q=this.wallNow(),X=0;for(let z of $){let Y=z.payload;if(Y===null||typeof Y!=="object"||Array.isArray(Y))continue;if(z.kind==="action.intent"){let j=Y,W=(j.idempotencyKey??"").replace(/^act_/,""),V=this.contracts.get(j.contract),q=Date.parse(j.executeAfter),B=q<=Q?Z:Z+(q-Q);this.db.query(`INSERT OR REPLACE INTO intents (intent_id, contract, params_json, idempotency_key,
507
+ execute_after_awake_ms, minted_wall_ms, fuse_ms, effective_class, category, reversibility,
508
+ fuse_level, state, requested_by_run, requested_by_order)
509
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INTENT', ?, ?)`).run(W,j.contract,JSON.stringify(j.params),j.idempotencyKey,B,q,V!==void 0&&V.effect.class==="dispatch"?1:0,V?.effect.class??"dispatch",V?.effect.category??null,V?.effect.reversibility??"irreversible",V?.fuse??"standard",j.requestedBy?.runId??null,j.requestedBy?.orderId??null),X++}else if(z.kind==="action.executing"){let j=String(Y.intentId??"");this.db.query("UPDATE intents SET state = 'INTENT', attempt = ?, recovery_reentry = 1, execute_after_awake_ms = ?, next_attempt_awake_ms = 0 WHERE intent_id = ?").run(Number(Y.attempt??1),Z,j)}else if(z.kind==="action.recall")this.setState(String(Y.intentId??""),"RECALLED");else if(z.kind==="action.effect")this.setState(String(Y.intentId??""),"EFFECTED");else if(z.kind==="action.failed")this.setState(String(Y.intentId??""),"FAILED");else if(z.kind==="action.unknown")this.setState(String(Y.intentId??""),"UNKNOWN")}return{ok:{rebuilt:X}}}notePausedGap($){this.db.query("UPDATE intents SET paused_ms_total = paused_ms_total + ? WHERE state IN ('INTENT','VERIFYING','EXECUTING')").run($)}expireStalePaused(){let $=this.db.query("SELECT * FROM intents WHERE state = 'INTENT' AND paused_ms_total > 0").all(),Z=[];for(let Q of $){let X=this.contracts.get(Q.contract);if(X===void 0)continue;let z=g1(X);if(z===null||Q.paused_ms_total<=z)continue;this.expire(Q,z);let Y=this.fuses.get(Q.intent_id);if("ok"in Y&&Y.ok.state==="ARMED")this.fuses.hold(Q.intent_id,`expired past staleness cap ${z}ms`);Z.push(Q.intent_id)}return{ok:Z}}intent($){let Z=this.raw($);if(Z===null)return x("not_found",`no intent '${$}'`);let Q={intentId:Z.intent_id,contract:Z.contract,state:Z.state,idempotencyKey:Z.idempotency_key,attempt:Z.attempt,verifyAttempts:Z.verify_attempts,fuseMs:Z.fuse_ms,effectiveClass:Z.effective_class};if(Z.requested_by_run!==null)Q.requestedBy={runId:Z.requested_by_run,...Z.requested_by_order!==null?{orderId:Z.requested_by_order}:{}};if(Z.last_error!==null)Q.lastError=Z.last_error;return{ok:Q}}intents($){return this.db.query("SELECT * FROM intents ORDER BY minted_wall_ms ASC").all().filter((Q)=>$===void 0||Q.state===$).map((Q)=>{let X=this.intent(Q.intent_id);return"ok"in X?X.ok:void 0})}executeStep($,Z){let Q=JSON.parse($.params_json),X=$.attempt+1,z=this.clock.awakeNowMs();if($.attempt>=1||$.recovery_reentry===1){let q=(this.wallNow()-$.minted_wall_ms)/86400000,B=Z.idempotency.supported?Z.idempotency.windowDays:void 0;if(!(B!==void 0&&q<=B)){let J=this.upstream.probe({contract:Z,params:Q,idempotencyKey:$.idempotency_key});if(!K(J))return this.verifyExhaustedOrRetry($,Z,"query-before-retry probe failed");if(J.ok.reading==="effected")return this.effect($,Z,J.ok.evidenceRef??"query-before-retry:prior-effect",X,"effected");if(J.ok.reading==="unknown")return this.verifyExhaustedOrRetry($,Z,"query-before-retry inconclusive")}}this.db.query("UPDATE intents SET state = 'EXECUTING', attempt = ?, recovery_reentry = 0 WHERE intent_id = ?").run(X,$.intent_id);let j=this.appender.append("action.executing",{intentId:$.intent_id,attempt:X},this.wallNow());if(!("ok"in j))return j;let W=this.upstreamOf(Z.name),V=this.upstream.execute({contract:Z,params:Q,idempotencyKey:$.idempotency_key,attempt:X,...$.grant_id!==null?{grantId:$.grant_id}:{}});if(!K(V)){let q="err"in V?V.err:x("internal","upstream returned empty").err;if(this.breakers.recordFailure(W,q),q.code==="deadline_exceeded")return this.toVerifying($,Z,X);if(q.retryability==="transient"&&X<HY)return this.retryLater($,X,HN,q),{ok:!0};if(q.retryability==="throttling"&&X<HY){let B=this.breakers.takeRetryQuota(W);return this.retryLater($,X,B?dB:dB*4,q),{ok:!0}}return this.fail({...$,attempt:X},q),this.emitActionSpan($,Z,X,"error","unknown",z,q),{ok:!0}}return this.breakers.recordSuccess(W),this.verifyAfterExecute($,Z,X,V.ok.evidenceHint)}verifyAfterExecute($,Z,Q,X){if(Z.verification.method==="none")return this.effect($,Z,void 0,Q,"none-declared",X);return this.toVerifying($,Z,Q)}toVerifying($,Z,Q){let X=this.clock.awakeNowMs(),z=this.confidentAfter[Z.name]??0;if(this.db.query("UPDATE intents SET state = 'VERIFYING', attempt = ?, first_verify_awake_ms = COALESCE(first_verify_awake_ms, ?), next_attempt_awake_ms = ? WHERE intent_id = ?").run(Q,X,X+z,$.intent_id),z===0){let Y=this.raw($.intent_id);if(Y!==null)return this.verifyStep(Y,Z)}return{ok:!0}}verifyStep($,Z){let Q=JSON.parse($.params_json),X=this.upstream.probe({contract:Z,params:Q,idempotencyKey:$.idempotency_key}),z=K(X)?X.ok:{reading:"unknown"};if(z.reading==="effected")return this.effect($,Z,z.evidenceRef??`probe:${Z.verification.probeRef??Z.verification.method}`,$.attempt,"effected");if(z.reading==="absent")return this.db.query("UPDATE intents SET state = 'INTENT', next_attempt_awake_ms = ?, execute_after_awake_ms = ? WHERE intent_id = ?").run(this.clock.awakeNowMs(),this.clock.awakeNowMs(),$.intent_id),{ok:!0};return this.verifyExhaustedOrRetry($,Z,"verify probe inconclusive")}verifyExhaustedOrRetry($,Z,Q){let X=this.clock.awakeNowMs(),z=this.confidentAfter[Z.name]??0,Y=$.verify_attempts+1,j=$.first_verify_awake_ms??X,W=X-j;if(Y>=nB&&W>=4*z){let q=this.appender.append("action.unknown",{intentId:$.intent_id,verifyAttempts:Y},this.wallNow());if(!("ok"in q))return q;return this.db.query("UPDATE intents SET state = 'UNKNOWN', verify_attempts = ?, last_error = ? WHERE intent_id = ?").run(Y,Q,$.intent_id),this.appender.fileIncident(`action.unknown for intent ${$.intent_id} (${$.contract}) \u2014 verification exhausted, possibly effected; NEVER retry-eligible`,"sev2","probe",this.wallNow()),this.emitActionSpan($,Z,$.attempt,"error","unknown",X),{ok:!0}}let V=Math.max(z,1000);return this.db.query("UPDATE intents SET state = 'VERIFYING', verify_attempts = ?, first_verify_awake_ms = COALESCE(first_verify_awake_ms, ?), next_attempt_awake_ms = ? WHERE intent_id = ?").run(Y,j,X+V,$.intent_id),{ok:!0}}effect($,Z,Q,X,z,Y){let j=z==="none-declared"?{intentId:$.intent_id,evidence:"none-declared",...Y!==void 0?{evidenceRef:Y}:{}}:{intentId:$.intent_id,evidenceRef:Q??""},W=this.appender.append("action.effect",j,this.wallNow());if(!("ok"in W))return W;return this.db.query("UPDATE intents SET state = 'EFFECTED', attempt = ? WHERE intent_id = ?").run(X,$.intent_id),this.emitActionSpan($,Z,X,"ok","effected",this.clock.awakeNowMs()),{ok:!0}}fail($,Z){if(!("ok"in this.appender.append("action.failed",{intentId:$.intent_id,error:Z},this.wallNow())))return;this.db.query("UPDATE intents SET state = 'FAILED', last_error = ? WHERE intent_id = ?").run(Z.message,$.intent_id)}expire($,Z){let Q=x("failed_precondition",`intent '${$.intent_id}' paused ${$.paused_ms_total}ms > class cap ${Z}ms \u2014 EXPIRED, never a late fire (\xA74.1)`).err;if(!("ok"in this.appender.append("action.failed",{intentId:$.intent_id,error:Q},this.wallNow())))return;this.db.query("UPDATE intents SET state = 'EXPIRED', last_error = ? WHERE intent_id = ?").run(Q.message,$.intent_id),this.appender.fileIncident(`intent ${$.intent_id} (${$.contract}) EXPIRED past its staleness cap \u2014 inbox notice`,"sev3","watchdog",this.wallNow())}reVerdict($,Z){let Q=JSON.parse($.params_json),X=C$(Q),z=this.ulid(),Y=$.provenance_json!==null?JSON.parse($.provenance_json):{};this.evidence.register(z,{bytes:X,taint:this.overallTaint(Y),workerManifest:{actionClasses:["read","vault_write","fetch","send","pay","post","delete_at_source"],taintExposure:"mediated"},actionContract:Z,paramProvenance:Y});let j=this.chokepoint.submit({id:z,channel:"connector_action",payloadRef:{sha256:L$(X),bytes:Buffer.byteLength(X,"utf8")},actor:{workerId:$.requested_by_run??"kernel",workerType:$.requester_worker_type??"kernel"},contract:{action:Z.name,class:$.effective_class,...Z.effect.category!==void 0?{category:Z.effect.category}:{},reversibility:Z.effect.reversibility}});if(!K(j))return this.fail($,"err"in j?j.err:x("internal","re-verdict empty").err),{ok:!1};if(j.ok.decision==="refused")return this.fail($,x("failed_precondition",`wake re-verdict refused: ${j.ok.reason??""}`).err),{ok:!1};return this.db.query("UPDATE intents SET paused_ms_total = 0 WHERE intent_id = ?").run($.intent_id),{ok:!0}}retryLater($,Z,Q,X){this.db.query("UPDATE intents SET state = 'INTENT', attempt = ?, next_attempt_awake_ms = ?, last_error = ? WHERE intent_id = ?").run(Z,this.clock.awakeNowMs()+Q,X.message,$.intent_id)}setState($,Z){this.db.query("UPDATE intents SET state = ? WHERE intent_id = ?").run(Z,$)}raw($){return this.db.query("SELECT * FROM intents WHERE intent_id = ?").get($)??null}upstreamOf($){let Z=$.indexOf(".");return Z<0?$:$.slice(0,Z)}usdOf($){if($!==null&&typeof $==="object"&&!Array.isArray($)){let Z=$.amount;if(typeof Z==="number")return Z}return}overallTaint($){if($===void 0||Object.keys($).length===0)return{level:"system",sources:[]};let Z=Object.values($),Q=QX(Z[0].level,...Z.slice(1).map((z)=>z.level)),X=[...new Set(Z.filter((z)=>z.level==="untrusted").flatMap((z)=>z.sources))].sort();return{level:Q==="user-direct"?"user":Q,sources:X}}emitActionSpan($,Z,Q,X,z,Y,j){let W=this.upstreamOf(Z.name),V={traceId:$.requested_by_run??$.intent_id,spanId:this.ulid(),name:"action.execute",attrs:{"intent.id":$.intent_id,contract:Z.name,"effect.class":$.effective_class,reversibility:Z.effect.reversibility,"fuse.ms":$.fuse_ms,"idempotency.key":$.idempotency_key,attempt:Q,"verify.method":Z.verification.method,"verify.result":z,"breaker.name":W,"breaker.state":this.breakers.stateFor(W)},status:X,...j!==void 0?{error:j}:{},startTs:U0(this.wallNow()),durationMs:Math.max(0,this.clock.awakeNowMs()-Y)};this.appender.emitSpan(V,this.wallNow())}}f();var oB=["sync-due","derivation-due","probe","repair","trainer","compaction","backfill","watchdog-check","gauntlet-merge","projection","kpi","layout"];var wQ={"watchdog-check":1,"sync-due":2,repair:2,probe:3,"gauntlet-merge":3,kpi:3,"derivation-due":4,projection:4,trainer:5,compaction:5,backfill:5,layout:5},aB={"watchdog-check":30000,"sync-due":120000,repair:300000,probe:60000,"gauntlet-merge":600000,kpi:60000,"derivation-due":300000,projection:120000,trainer:900000,compaction:300000,backfill:300000,layout:600000},rB={"watchdog-check":1000,"sync-due":5000,repair:1e4,probe:5000,"gauntlet-merge":1e4,kpi:5000,"derivation-due":30000,projection:1e4,trainer:60000,compaction:60000,backfill:60000,layout:60000},l1=3600000,GY=8,tB=86400000;function JY($){let Z={id:$.id,class:$.class,dueAtAwakeMs:$.due_at_awake_ms,priority:$.priority,state:$.state,attempt:$.attempt,visibleAtAwakeMs:$.visible_at_awake_ms,backoffMs:$.backoff_ms};if($.order_id!==null)Z.orderId=$.order_id;return Z}class c1{db;clock;appender;wallNow;ring;jitter;ulid=V$();constructor($){this.db=$.db,this.clock=$.clock,this.appender=$.appender,this.wallNow=$.wallNow,this.ring=$.ring,this.jitter=$.jitter??((Z)=>Z)}enqueue($){if(!oB.includes($.class))return x("invalid_argument",`unknown job class '${String($.class)}'`);let Z=this.clock.awakeNowMs(),Q=this.ulid(),X=wQ[$.class],z=$.dueAtAwakeMs??Z;this.db.query(`INSERT INTO jobs (id, class, order_id, due_at_awake_ms, priority, state, attempt, visible_at_awake_ms, backoff_ms, enqueued_awake_ms)
510
+ VALUES (?, ?, ?, ?, ?, 'PENDING', 0, 0, ?, ?)`).run(Q,$.class,$.orderId??null,z,X,rB[$.class],Z);let Y=this.appender.append(s5.enqueued,{jobId:Q,class:$.class,orderId:$.orderId??null,priority:X,dueAtAwakeMs:z},this.wallNow());if(!("ok"in Y))return Y;return{ok:this.mustGet(Q)}}claimDue($){if(this.clock.phase()!=="awake")return x("failed_precondition",`claim refused in phase '${this.clock.phase()}' \u2014 reconcile first (\xA74.1)`);let Z=this.clock.awakeNowMs();if(this.ring?.log(JSON.stringify({t:"claim-scan",awakeMs:Z})),$.maxJobs<=0)return{ok:[]};let Q=this.db.query(`SELECT * FROM jobs
511
+ WHERE (state = 'PENDING' AND due_at_awake_ms <= ?)
512
+ OR (state = 'CLAIMED' AND visible_at_awake_ms <= ?)
513
+ ORDER BY priority ASC, due_at_awake_ms ASC
514
+ LIMIT ?`).all(Z,Z,$.maxJobs*4),X=[];for(let z of Q){if(X.length>=$.maxJobs)break;if(!$.allowedPriorities.includes(z.priority))continue;let Y=z.attempt+1;if(Y>GY){this.terminal(z.id,"FAILED",{reason:"max-attempts"});continue}let j=Z+2*aB[z.class];this.db.query("UPDATE jobs SET state = 'CLAIMED', attempt = ?, visible_at_awake_ms = ? WHERE id = ?").run(Y,j,z.id);let W=this.appender.append(s5.started,{jobId:z.id,class:z.class,attempt:Y,redelivery:z.state==="CLAIMED"},this.wallNow());if(!("ok"in W))return W;X.push(this.mustGet(z.id))}return{ok:X}}succeed($){return this.terminal($,"DONE",{})}fail($,Z){let Q=this.rawGet($);if(Q===null)return x("not_found",`no job '${$}'`);if(!Z.retryable||Q.attempt>=GY)return this.terminal($,"FAILED",{reason:Z.reason??"non-retryable"});let X=Math.min(this.jitter(Q.backoff_ms*2),l1),z=this.clock.awakeNowMs();this.db.query("UPDATE jobs SET state = 'PENDING', due_at_awake_ms = ?, backoff_ms = ? WHERE id = ?").run(z+X,X,$);let Y=this.appender.append(s5.failed,{jobId:$,class:Q.class,attempt:Q.attempt,retryAtAwakeMs:z+X,reason:Z.reason??""},this.wallNow());if(!("ok"in Y))return Y;return{ok:this.mustGet($)}}requeue($,Z){let Q=this.rawGet($);if(Q===null)return x("not_found",`no job '${$}'`);let X=Math.min(this.jitter(Math.max(Q.backoff_ms,1)*2),l1),z=this.clock.awakeNowMs();return this.db.query("UPDATE jobs SET state = 'PENDING', due_at_awake_ms = ?, backoff_ms = ?, attempt = attempt WHERE id = ?").run(z+X,X,$),this.ring?.log(JSON.stringify({t:"requeue",jobId:$,reason:Z,backoff:X})),{ok:this.mustGet($)}}requeueWithheld($,Z){let Q=this.rawGet($);if(Q===null)return x("not_found",`no job '${$}'`);let X=Math.min(this.jitter(Math.max(Q.backoff_ms,1)*2),l1),z=this.clock.awakeNowMs();return this.db.query("UPDATE jobs SET state = 'PENDING', due_at_awake_ms = ?, backoff_ms = ?, attempt = MAX(0, attempt - 1) WHERE id = ?").run(z+X,X,$),this.ring?.log(JSON.stringify({t:"requeue-withheld",jobId:$,reason:Z,backoff:X})),{ok:this.mustGet($)}}abandon($,Z){return this.terminal($,"ABANDONED",{reason:Z})}sweepAbandoned(){let $=this.clock.awakeNowMs(),Z=this.db.query("SELECT * FROM jobs WHERE state = 'PENDING' AND enqueued_awake_ms <= ?").all($-tB),Q=[];for(let X of Z){let z=this.terminal(X.id,"ABANDONED",{reason:"age"});if(!("ok"in z))return z;Q.push(z.ok)}return{ok:Q}}nextDueAwakeMs(){return this.db.query("SELECT MIN(due_at_awake_ms) AS m FROM jobs WHERE state = 'PENDING'").get().m}get($){let Z=this.rawGet($);if(Z===null)return x("not_found",`no job '${$}'`);return{ok:JY(Z)}}jobs($={}){return this.db.query("SELECT * FROM jobs ORDER BY priority ASC, due_at_awake_ms ASC").all().map(JY).filter((Q)=>($.state===void 0||Q.state===$.state)&&($.class===void 0||Q.class===$.class))}terminal($,Z,Q){let X=this.rawGet($);if(X===null)return x("not_found",`no job '${$}'`);this.db.query("UPDATE jobs SET state = ? WHERE id = ?").run(Z,$);let z=Z==="DONE"?s5.succeeded:Z==="FAILED"?s5.failed:s5.abandoned,Y=this.appender.append(z,{jobId:$,class:X.class,attempt:X.attempt,terminal:Z,...Q},this.wallNow());if(!("ok"in Y))return Y;return{ok:this.mustGet($)}}rawGet($){return this.db.query("SELECT * FROM jobs WHERE id = ?").get($)??null}mustGet($){let Z=this.rawGet($);if(Z===null)throw Error(`job '${$}' vanished mid-transaction`);return JY(Z)}}var eB=[{name:"ac-nominal",concurrentWorkers:4,allowedPriorities:[1,2,3,4,5],pausedClasses:[],reapBackground:!1,backfillPaused:!1,syncHotOnly:!1},{name:"battery-high",concurrentWorkers:2,allowedPriorities:[1,2,3,4],pausedClasses:["backfill","projection"],reapBackground:!1,backfillPaused:!0,syncHotOnly:!1},{name:"battery-low",concurrentWorkers:1,allowedPriorities:[1,2],pausedClasses:["backfill","trainer","compaction","derivation-due","projection","probe","gauntlet-merge","kpi"],reapBackground:!1,backfillPaused:!0,syncHotOnly:!0},{name:"low-power-mode",concurrentWorkers:0,allowedPriorities:[1],pausedClasses:["backfill","trainer","compaction","derivation-due","projection","probe","gauntlet-merge","kpi","sync-due","repair"],reapBackground:!1,backfillPaused:!0,syncHotOnly:!0},{name:"thermal-serious",concurrentWorkers:0,allowedPriorities:[1],pausedClasses:[],reapBackground:!1,backfillPaused:!0,syncHotOnly:!0},{name:"thermal-critical",concurrentWorkers:0,allowedPriorities:[1],pausedClasses:[],reapBackground:!0,backfillPaused:!0,syncHotOnly:!0}],$J=Object.keys(wQ).filter(($)=>wQ[$]>=5);function GN($){let Z=[...$.pausedClasses];for(let Q of $J)if(!Z.includes(Q))Z.push(Q);return{...$,name:`${$.name}+user-active`,pausedClasses:Z,backfillPaused:!0}}function d1($){let Z=(z)=>{let Y=eB.find((j)=>j.name===z);if(Y===void 0)throw Error(`governor table row '${z}' missing`);return Y},X=(()=>{if($.thermal==="critical")return Z("thermal-critical");if($.thermal==="serious")return Z("thermal-serious");if($.lowPowerMode)return Z("low-power-mode");if($.power==="battery")return $.batteryPct<=30?Z("battery-low"):Z("battery-high");return Z("ac-nominal")})();return $.userActive?GN(X):X}class n1{runtime;ipc;constructor($,Z){this.runtime=$,this.ipc=Z}run($,Z,Q,X){let z=this.runtime.spawn($,Z,Q);if(!("ok"in z))return z;if(z.ok.disposition==="queued")return{ok:{disposition:"queued",runId:z.ok.runId}};let Y=z.ok.run,j=this.ipc.session(Y.id);if(!("ok"in j))return j;let W={...j.ok,exit:()=>x("failed_precondition","WorkerHost owns terminalization; return the exit submission after all provider usage is reported")},V,q,B={run:Y,ipc:W,reportFirstModel:(L)=>this.runtime.reportFirstModel(Y.id,L),reportModelRefused:(L)=>this.runtime.reportModelRefused(Y.id,L),meter:(L)=>{let D=this.runtime.noteUsage(Y.id,L);if(!("ok"in D)&&V===void 0){V="err"in D?D.err:x("resource_exhausted",D.empty.how,"throttling").err;let P=this.runtime.run(Y.id);if("ok"in P&&P.ok.state==="RUNNING")q=j.ok.exit({status:"failed",evidence:[],error:V})}return D}},G;try{G=X(B)}catch(L){G=x("internal",`worker threw: ${L instanceof Error?L.message:String(L)}`)}let J=this.runtime.run(Y.id);if(!("ok"in J))return J;if(J.ok.state!=="RUNNING"){if(V!==void 0&&J.ok.state==="REAPED"){if(V.code!=="resource_exhausted")return{err:V};return{ok:{disposition:"terminated-by-falcon",runId:Y.id,status:"reaped"}}}if(V!==void 0&&J.ok.exitStatus==="failed"){if(q!==void 0&&!("ok"in q))return q;return{ok:{disposition:"exited",runId:Y.id,status:"failed"}}}return{ok:{disposition:"terminated-by-falcon",runId:Y.id,status:J.ok.exitStatus??J.ok.state}}}if(V!==void 0){let L=j.ok.exit({status:"failed",evidence:[],error:V});if(!("ok"in L))return L;return{ok:{disposition:"exited",runId:Y.id,status:"failed"}}}if("ok"in G){let L=j.ok.exit(G.ok);if(!("ok"in L))return L;let D=this.runtime.run(Y.id);if(!("ok"in D))return D;return{ok:{disposition:"exited",runId:Y.id,status:D.ok.exitStatus??G.ok.status}}}let U=j.ok.exit({status:"failed",evidence:[],error:"err"in G?G.err:void 0});if(!("ok"in U))return U;return{ok:{disposition:"exited",runId:Y.id,status:"failed"}}}}f();var UN=["action.","fuse.","job.","breaker.","worker.","falcon.","gauntlet.","sleep.","grant.","trust.","egress.","anomaly.","spend.","erasure."];function LN($){return UN.some((Z)=>$.startsWith(Z))||c8($)}class i1{log;appender;runtime;talon;wallNow;capabilitiesFor;provenanceFor;credentialTalon;constructor($){this.log=$.log,this.appender=$.appender,this.runtime=$.runtime,this.talon=$.talon,this.wallNow=$.wallNow,this.capabilitiesFor=$.capabilitiesFor,this.provenanceFor=$.provenanceFor}attachCredentialTalon($){if(this.credentialTalon!==void 0)return x("already_exists","falcon credential talon is already attached");let Z=$.attachToRuntime();if(!("ok"in Z))return Z;return this.credentialTalon=$,{ok:void 0}}session($){let Z=this.runtime.run($);if(!("ok"in Z))return Z;return{ok:this.bound($)}}bound($){return{runId:$,appendEvents:(Z)=>this.appendEvents($,Z),requestAction:(Z,Q,X)=>this.requestAction($,Z,Q,X),heartbeat:(Z)=>this.runtime.heartbeat($,Z),query:(Z)=>this.query($,Z),executeCredential:(Z,Q)=>this.executeCredential($,Z,Q),revokeCredential:(Z)=>this.revokeCredential($,Z),exit:(Z)=>this.runtime.exit($,Z)}}executeCredential($,Z,Q){if(this.credentialTalon===void 0)return x("failed_precondition","indrad credential talon is not attached (I-7 fail closed)");return this.credentialTalon.execute($,Z,Q)}revokeCredential($,Z){if(this.credentialTalon===void 0)return x("failed_precondition","indrad credential talon is not attached (I-7 fail closed)");return this.credentialTalon.revoke($,Z)}appendEvents($,Z){if(!this.appender.healthy())return x("unavailable","HALT_LOUD: IPC append unavailable while the event log is unwritable (N1)","retry-at-higher-level");let Q=this.runtime.run($);if(!("ok"in Q))return Q;for(let V of Z)if(LN(V.kind)){if(c8(V.kind))this.appender.fileIncident(`worker ${$} attempted a verdict-class append ('${V.kind}') over IPC \u2014 refused architecturally (I-5 verdict-writer isolation)`,"sev2","guard",this.wallNow(),{traceId:Q.ok.traceId});return x("permission_denied",`kind '${V.kind}' is falcon-owned \u2014 workers cannot append it over IPC (I-5/\xA73.1; verdict-writer isolation for worker.exited/gauntlet.verdict)`)}let X=U0(this.wallNow()),z=Z.map((V)=>({nk:{source:"zortex",stream:"trace",sourceId:`${$}:${V.kind}:${X}`,rev:"0"},ts:X,tier:"first-party",kind:V.kind,schemaVersion:1,mentions:[],body:V.body??"",payload:V.payload})),Y=this.log.append(z,{kind:"kernel"});if(!K(Y))return Y;let j=Y.ok.map((V)=>V.id),W=Y.ok.filter((V)=>V.outcome==="duplicate"||V.outcome==="head-noop").length;return{ok:{ids:j,deduped:W}}}requestAction($,Z,Q,X){let z=this.runtime.run($);if(!("ok"in z))return z;if(z.ok.state!=="RUNNING")return x("failed_precondition",`run '${$}' is ${z.ok.state} \u2014 only RUNNING workers request actions`);let Y={runId:$,orderId:z.ok.orderId,workerType:z.ok.workerType,capabilities:this.capabilitiesFor(z.ok.workerType)},j=this.provenanceFor?.($,Z,Q)??{};return this.talon.requestAction({contract:Z,params:Q,session:Y,...X!==void 0?{grantId:X}:{},...j.provenance!==void 0?{provenance:j.provenance}:{},...j.contextOrigins!==void 0?{contextOrigins:j.contextOrigins}:{},...j.recipient!==void 0?{recipient:j.recipient}:{}})}async query($,Z){let Q=this.runtime.run($);if(!("ok"in Q))return Q;if(Z.q!=="log-range")return x("invalid_argument",`unknown query '${String(Z.q)}'`);let X=Math.min(Z.limit??100,1000),z=[],Y=Z.fromSeq!==void 0?{afterSeq:Z.fromSeq}:void 0,j=Z.kinds!==void 0?{kinds:Z.kinds}:void 0;for await(let W of this.log.scan(Y,j)){if("erasedKind"in W)continue;if(z.push(W),z.length>=X)break}return{ok:z}}}var QJ=600000;function UY($){return $.startsWith("res:")}function LY($){let Z="^";for(let Q=0;Q<$.length;Q++){let X=$.charAt(Q);if(X==="*")if($.charAt(Q+1)==="*")Z+=".*",Q++;else Z+="[^/]*";else if("\\^$.|?+()[]{}".includes(X))Z+=`\\${X}`;else Z+=X}return new RegExp(`${Z}$`)}function ZJ($){let Z=$.indexOf("*");return Z<0?$:$.slice(0,Z)}function XJ($,Z){if(UY($)||UY(Z))return $===Z;if($===Z)return!0;if(LY($).test(Z)||LY(Z).test($))return!0;let Q=ZJ($),X=ZJ(Z);if(!($.includes("*")||Z.includes("*")))return!1;return Q.startsWith(X)||X.startsWith(Q)}class s1{db;clock;constructor($,Z){this.db=$,this.clock=Z}acquire($,Z,Q){if(Z.length===0)return{ok:{disposition:"granted",leases:[]}};let X=this.clock.awakeNowMs(),z=[...new Set(Z)].sort(),Y=Math.max(0,Q)*60000+QJ,j=this.db.transaction(()=>{this.db.query("DELETE FROM leases WHERE expires_at_awake_ms <= ?").run(X);let W=this.db.query("SELECT * FROM leases").all(),V=[];for(let B of z)for(let G of W){if(G.holder_run_id===$)continue;if(XJ(B,G.pattern))V.push({requested:B,heldBy:G.holder_run_id,pattern:G.pattern})}if(V.length>0)return{disposition:"queued",conflicts:V};let q=[];for(let B of z)this.db.query("INSERT OR REPLACE INTO leases (pattern, holder_run_id, expires_at_awake_ms) VALUES (?, ?, ?)").run(B,$,X+Y),q.push({pattern:B,holderRunId:$,expiresAtAwakeMs:X+Y});return{disposition:"granted",leases:q}});try{return{ok:j()}}catch(W){return x("internal",`lease transaction failed: ${W instanceof Error?W.message:String(W)}`,"transient")}}release($){return{ok:this.db.query("DELETE FROM leases WHERE holder_run_id = ?").run($).changes}}held($){return($===void 0?this.db.query("SELECT * FROM leases").all():this.db.query("SELECT * FROM leases WHERE holder_run_id = ?").all($)).map((Q)=>({pattern:Q.pattern,holderRunId:Q.holder_run_id,expiresAtAwakeMs:Q.expires_at_awake_ms}))}covers($,Z){return this.held($).some((Q)=>!UY(Q.pattern)&&LY(Q.pattern).test(Z))}}import{closeSync as DN,existsSync as MN,openSync as PN,readSync as zJ,writeSync as DY}from"fs";var jJ=16777216,p9=16,YJ=1515342158,CN=new RegExp(String.fromCharCode(0),"g");class o1{fd;size;writeOffset;wrapped;constructor($,Z=jJ){this.size=Z;let Q=!MN($);if(this.fd=PN($,Q?"w+":"r+"),Q)this.writeOffset=0,this.wrapped=!1,this.flushHeader();else{let X=Buffer.alloc(p9);if(zJ(this.fd,X,0,p9,0),X.readUInt32BE(0)===YJ&&X.readUInt32BE(4)===Z)this.writeOffset=X.readUInt32BE(8),this.wrapped=X.readUInt32BE(12)===1;else this.writeOffset=0,this.wrapped=!1,this.flushHeader()}}flushHeader(){let $=Buffer.alloc(p9);$.writeUInt32BE(YJ,0),$.writeUInt32BE(this.size,4),$.writeUInt32BE(this.writeOffset,8),$.writeUInt32BE(this.wrapped?1:0,12),DY(this.fd,$,0,p9,0)}log($){let Z=Buffer.from(`${$}
515
+ `,"utf8");if(Z.length>=this.size)return;if(this.writeOffset+Z.length>this.size){let Q=this.size-this.writeOffset;if(Q>0)DY(this.fd,Buffer.alloc(Q),0,Q,p9+this.writeOffset);this.writeOffset=0,this.wrapped=!0}DY(this.fd,Z,0,Z.length,p9+this.writeOffset),this.writeOffset+=Z.length,this.flushHeader()}snapshot(){let $=Buffer.alloc(this.size);zJ(this.fd,$,0,this.size,p9);let Z=$.subarray(0,this.writeOffset).toString("utf8");if(!this.wrapped)return Z;let Q=$.subarray(this.writeOffset).toString("utf8").replace(CN,""),X=Q.indexOf(`
516
+ `);return(X>=0?Q.slice(X+1):"")+Z}close(){this.flushHeader(),DN(this.fd)}}f();class a1{talon;constructor($){this.talon=$}requestRecall($,Z){if($.by==="watchdog"&&Z.kind!=="kernel")return x("permission_denied",`action.recall by 'watchdog' submits through the falcon API (security \xA74.2 \u2014 a watchdog that can act would be a target); got origin '${Z.kind}'`);if($.by==="watchdog"&&$.watchdogRunId===void 0)return x("invalid_argument","action.recall by 'watchdog' must carry watchdogRunId (undo-layer \xA73.3)");let Q=this.talon.recall($.intentId,$.by,$.via,$.watchdogRunId!==void 0?{runId:$.watchdogRunId,...$.checkRef!==void 0?{checkRef:$.checkRef}:{}}:void 0);if(!K(Q))return Q;return{ok:{recallEventId:Q.ok.recallEventId,disposition:"recalled",deadlineUpdated:!0}}}}class r1{opts;policy;watchdog;checkedOnce=new Set;unwatchedNoticed=new Set;constructor($){this.opts=$,$.talon.attachWatchdog(new a1($.talon)),this.policy=$.policy??AQ,this.watchdog=new O1({log:$.log,recall:new a1($.talon),policy:this.policy,awakeNowMs:$.awakeNowMs,now:$.now,...$.classifier!==void 0?{classifier:$.classifier}:{}})}run(){let $={checked:[],recalled:[],unwatched:[],held:[]},Z=this.opts.talon.armedForWatch();for(let Y of Z.unwatchable){if(this.unwatchedNoticed.has(Y.intentId))continue;this.unwatchedNoticed.add(Y.intentId),$.unwatched.push(Y.intentId);let j=g9(Y.key),W={runId:Y.intentId,intentId:Y.intentId,fuseMs:Y.fuseMs,completedAtMs:Math.max(0,this.opts.awakeNowMs()-Y.armedAtAwakeMs),holdRequired:j},V=f9(this.opts.log,N0.watchdogLate,W,{kind:"kernel"},this.opts.now());if(!K(V))return V;if(j){let q=this.opts.talon.holdFuse(Y.intentId,"unwatched fuse: this falcon did not arm it and cannot check it (undo-layer \xA74.2/\xA76)");if(!K(q))return q;$.held.push(Y.intentId)}}let Q=Z.contexts.filter((Y)=>!this.checkedOnce.has(Y.intentId));if(Q.length===0)return{ok:$};let X=new Map(Q.map((Y)=>[Y.intentId,Y])),z=mz(Q.map((Y)=>({intentId:Y.intentId,armedAtAwakeMs:Y.armedAtAwakeMs})));for(let Y of z){let j=Y.intentIds.map((V)=>X.get(V)).filter((V)=>V!==void 0);if(j.length===0)continue;let W=this.watchdog.run(j);if(!K(W))return W;for(let V of W.ok.results){if(this.checkedOnce.add(V.intentId),$.checked.push(V.intentId),V.recallEventId!==void 0){$.recalled.push(V.intentId);continue}if(V.holdRequired){let q=this.opts.talon.holdFuse(V.intentId,"watchdog check completed past fuse/2 on a floor-category intent (undo-layer \xA74.2)");if(!K(q))return q;$.held.push(V.intentId)}}}return{ok:$}}}var MY=[...gQ,_Q];f();var PY=20,mQ=3,WJ=60000,VJ=86400000;var FN=["build","fix"];class t1{db;clock;appender;authority;leases;wallNow;envelope;meter;broker;worktreeFor;onOrderFailed;ulid=V$();credentialsByRun=new Map;credentialTerminalCleanup;constructor($){this.db=$.db,this.clock=$.clock,this.appender=$.appender,this.authority=$.authority,this.leases=$.leases,this.wallNow=$.wallNow,this.envelope=$.envelope,this.meter=$.meter,this.broker=$.broker,this.worktreeFor=$.worktreeFor,this.onOrderFailed=$.onOrderFailed}attachCredentialTerminalCleanup($,Z){if(this.credentialTerminalCleanup!==void 0)return x("already_exists","credential terminal-cleanup hook is already attached");if(this.broker===void 0||this.broker!==Z)return x("failed_precondition","credential talon broker is not the exact broker that owns runtime mint/revoke authority (I-7)");return this.credentialTerminalCleanup=$,{ok:void 0}}runRegistry(){return{isLive:($)=>{let Z=this.raw($);if(Z===null||Z.state!=="LEASED"&&Z.state!=="RUNNING")return!1;if(this.remainingWallClockFor(Z)<=0)return!1;if(Z.state==="LEASED")return!0;let X=Z.heartbeat_awake_ms??Z.spawned_awake_ms;return X!==null&&this.clock.awakeNowMs()-X<=mQ*Z.heartbeat_every_sec*1000},orderIdFor:($)=>{let Z=this.raw($);if(Z===null)return null;let Q=this.validatedOrder(Z);return K(Q)&&Q.ok.id===Z.order_id?Q.ok.id:null},remainingWallClockMs:($)=>{let Z=this.raw($);if(Z===null||Z.state!=="LEASED"&&Z.state!=="RUNNING")return null;return this.remainingWallClockFor(Z)}}}spawn($,Z,Q){if(!this.appender.healthy())return x("unavailable","HALT_LOUD: no spawns while the event log is unwritable (falcon \xA76 N1)","retry-at-higher-level");return this.spawnInternal($,Z,Q,{budgets:null,respawnOf:null,reapCount:0})}spawnInternal($,Z,Q,X){let z=this.ulid(),Y=this.ulid(),j=this.clock.awakeNowMs(),W=X.budgets??(()=>{let F=this.envelope!==void 0?Math.max(0,this.envelope.remaining()):$.budget.usd;return{tokens:$.budget.tokens,usd:Math.min($.budget.usd,F),wallClockMin:$.budget.wallClockMin}})();this.db.query(`INSERT INTO runs (run_id, order_id, worker_type, state, queued_awake_ms, heartbeat_every_sec,
517
+ budget_tokens, budget_usd, budget_wallclock_min, respawn_of, reap_count, model_pin, trace_id,
518
+ order_json, slice_demand_id, worker_type_json)
519
+ VALUES (?, ?, ?, 'QUEUED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(z,$.id,Q.workerType,j,PY,W.tokens,W.usd,W.wallClockMin,X.respawnOf,X.reapCount,Q.modelPin,Y,JSON.stringify($),Z.demandId??null,JSON.stringify(Q));let V=this.appender.append(h9.queued,{runId:z,orderId:$.id,workerType:Q.workerType,respawnOf:X.respawnOf},this.wallNow());if(!("ok"in V))return V;let q=this.leases.acquire(z,$.leases,W.wallClockMin);if(!("ok"in q))return q;if(q.ok.disposition==="queued")return{ok:{disposition:"queued",runId:z,conflicts:q.ok.conflicts.map((F)=>({requested:F.requested,heldBy:F.heldBy}))}};this.db.query("UPDATE runs SET state = 'LEASED', leased_awake_ms = ? WHERE run_id = ?").run(j,z);let B=this.appender.append(h9.leased,{runId:z,orderId:$.id,leases:[...$.leases].sort()},this.wallNow());if(!("ok"in B))return B;let G=[];for(let F of Q.actionScopes??[]){if(this.broker===void 0)return this.leases.release(z),this.db.query("UPDATE runs SET state = 'FAILED', exit_status = 'failed' WHERE run_id = ?").run(z),x("failed_precondition",`worker type '${Q.workerType}' declares actionScopes but no auth broker is wired \u2014 order blocked, never a mid-run hang (\xA74.1)`);let A=Math.ceil((W.wallClockMin*60000+60000)/1000),N=this.broker.mint($.id,z,F.source,F.account,F.scopes,A);if(!K(N)){let S=r(N)?N.err:{code:"internal",layer:"kernel",retryability:"non-retryable",message:"broker mint returned empty during credentialed spawn"};return this.failCredentialedSpawn(z,G,S)}G.push(N.ok)}let J=FN.includes($.kind)?this.worktreeFor?.($):void 0,U={id:z,orderId:$.id,workerType:Q.workerType,skillVersions:Q.skillVersions??[],sandbox:{...J!==void 0?{worktree:J}:{},leases:[...$.leases].sort(),credentials:G,budgets:W},heartbeatEverySec:PY},L=pV(U);if(!K(L)){let F=r(L)?L.err:{code:"internal",layer:"kernel",retryability:"non-retryable",message:"WorkerRun validation returned empty"};return this.failCredentialedSpawn(z,G,F)}this.credentialsByRun.set(z,G.map((F)=>({...F,scopes:[...F.scopes]})));let D=j+W.wallClockMin*60000;this.db.query("UPDATE runs SET state = 'RUNNING', spawned_awake_ms = ?, heartbeat_awake_ms = ?, wall_deadline_awake_ms = ? WHERE run_id = ?").run(j,j,D,z);let P=this.appender.append(h9.spawned,{runId:z,orderId:$.id,workerType:Q.workerType,harness:Q.harness,modelPin:Q.modelPin},this.wallNow());if(!("ok"in P)){let F=r(P)?P.err:{code:"internal",layer:"kernel",retryability:"non-retryable",message:"worker.spawned append returned empty"};return this.failCredentialedSpawn(z,G,F)}return{ok:{disposition:"spawned",run:U}}}heartbeat($,Z){let Q=this.raw($);if(Q===null)return x("not_found",`no run '${$}'`);if(Q.state!=="RUNNING")return x("failed_precondition",`heartbeat on run '${$}' in state ${Q.state} \u2014 only RUNNING heartbeats`);let X=this.clock.awakeNowMs();this.db.query("UPDATE runs SET heartbeat_awake_ms = ? WHERE run_id = ?").run(X,$);let z=Q.wall_deadline_awake_ms??X;return{ok:{budgetRemaining:{tokens:Math.max(0,Q.budget_tokens-Q.spent_tokens),usd:Math.max(0,Q.budget_usd-Q.spent_usd),wallClockMin:Math.max(0,(z-X)/60000)}}}}noteUsage($,Z){let Q=this.raw($);if(Q===null)return x("not_found",`no run '${$}'`);if(Q.state!=="RUNNING")return x("failed_precondition",`usage on run '${$}' in state ${Q.state}`);if(this.meter===void 0)return x("failed_precondition","authoritative worker Meter is not composed; paid fabrication usage fails closed");if(typeof Z!=="object"||Z===null||Array.isArray(Z))return x("invalid_argument","worker usage must be an object");let X=Z.model;if(X!==Q.model_pin)return x("failed_precondition",`worker usage model '${typeof X==="string"?X:""}' does not match pinned model '${Q.model_pin??""}'`);let z=zY(this.meter,{traceId:Q.trace_id,category:"fabrication",orderId:Q.order_id,runId:$})(Z);if(!K(z))return z;let Y=this.syncAuthoritativeSpend($);if(!K(Y))return Y;let j=Y.ok.tokens>Q.budget_tokens,W=Y.ok.usd>Q.budget_usd;if(j||W){let V=`${j?"token":"usd"} budget exceeded: ${Y.ok.tokens}/${Q.budget_tokens} tokens, $${Y.ok.usd}/$${Q.budget_usd}`,q=this.reap($,"budget",V);if(!K(q))return q;return x("resource_exhausted",`run '${$}' authoritative spend exceeds its budget and was reaped: ${V}`,"throttling")}return Y}reportFirstModel($,Z){let Q=this.raw($);if(Q===null)return x("not_found",`no run '${$}'`);if(Q.state!=="RUNNING")return x("failed_precondition",`run '${$}' is ${Q.state}`);if(this.db.query("UPDATE runs SET model_seen = ? WHERE run_id = ?").run(Z,$),Q.model_pin!==null&&Z!==Q.model_pin){let X=this.terminalExit($,"model-substituted",[],`pinned '${Q.model_pin}', response attributed '${Z}'`);if(!("ok"in X))return X;return{ok:{continue:!1}}}return{ok:{continue:!0}}}reportModelRefused($,Z){if(this.raw($)===null)return x("not_found",`no run '${$}'`);let X=this.terminalExit($,"model-refused",[],Z);if(!("ok"in X))return X;return{ok:{continue:!1}}}exit($,Z){let Q=this.raw($);if(Q===null)return x("not_found",`no run '${$}'`);if(Z.status==="reaped"||Z.status==="model-refused"||Z.status==="model-substituted")return x("permission_denied",`status '${Z.status}' is falcon-assigned \u2014 a worker cannot self-report it (I-5)`);if(Z.status==="blocked"&&(Z.blockedQuestion===void 0||Z.blockedQuestion.trim()===""))return x("invalid_argument","a 'blocked' exit carries a precise question for the inbox (constitution 17)");if(Q.state!=="RUNNING"&&Q.terminal_payload_json===null)return x("failed_precondition",`exit on run '${$}' in state ${Q.state}`);if(Z.status==="done"&&Q.state==="RUNNING"){let X=this.typeRowFor(Q);if(!K(X))return X;if(X.ok.harness==="sdk"){let z=this.meter?.ledger.all().some((Y)=>Y.runId===$)===!0;if(Q.model_seen===null||!z){let Y=[...Q.model_seen===null?["first provider model assertion"]:[],...!z?["authoritative spend.metered receipt"]:[]].join(" and ");return this.terminalExit($,"failed",Z.evidence,`SDK worker cannot complete done without ${Y}`)}}}return this.terminalExit($,Z.status,Z.evidence,Z.error?.message,Z.blockedQuestion)}sweep(){let $=this.clock.awakeNowMs(),Z=[],Q=[],X=[],z=this.db.query("SELECT * FROM runs WHERE state = 'RUNNING'").all();for(let W of z){let V=$-(W.heartbeat_awake_ms??W.spawned_awake_ms??$),q=V>mQ*W.heartbeat_every_sec*1000,B=W.wall_deadline_awake_ms!==null&&$>W.wall_deadline_awake_ms,G=W.spent_tokens>W.budget_tokens,J=W.spent_usd>W.budget_usd;if(q){let U=this.reap(W.run_id,"heartbeat",`heartbeat age ${V}ms > ${mQ*W.heartbeat_every_sec*1000}ms`);if(!("ok"in U))return U;Z.push(W.run_id)}else if(B||G||J){let U=B?"wallClock budget":G?"token budget":"usd budget",L=this.reap(W.run_id,"budget",`${U} exceeded`);if(!("ok"in L))return L;Z.push(W.run_id)}}let Y=this.db.query("SELECT * FROM runs WHERE state = 'QUEUED' AND queued_awake_ms <= ?").all($-VJ);for(let W of Y)this.db.query("UPDATE runs SET state = 'ABANDONED' WHERE run_id = ?").run(W.run_id),this.appender.fileIncident(`worker run ${W.run_id} QUEUED past 24h class-cap \u2014 abandoned`,"sev3","reap",this.wallNow(),{orderRef:W.order_id}),Q.push(W.run_id);let j=this.db.query("SELECT * FROM runs WHERE state = 'LEASED' AND leased_awake_ms <= ?").all($-WJ);for(let W of j)this.leases.release(W.run_id),this.db.query("UPDATE runs SET state = 'FAILED', exit_status = 'failed' WHERE run_id = ?").run(W.run_id),X.push(W.run_id);return{ok:{reaped:Z,abandoned:Q,releasedLeased:X}}}reap($,Z,Q){let X=this.raw($);if(X===null)return x("not_found",`no run '${$}'`);let z=JSON.parse(X.order_json),Y=null,j;if(Z==="budget")j=`budget reap (${Q}) \u2014 respawn with zero remainder is a guaranteed second reap`;else if(X.reap_count>=1)j=`second reap (${Z}) \u2014 a truthful failure beats a flailing loop`;else if(Y=this.typeRowFor(X),!K(Y))j=`respawn authority unavailable: ${r(Y)?Y.err.message:"worker type projection was empty"}`;let W=this.terminalExit($,"reaped",[],`${Z} reap: ${Q}`,void 0,j);if(!("ok"in W))return W;if(j!==void 0){if(Y!==null&&!K(Y))return Y;return{ok:{}}}let V=this.db.query("SELECT COALESCE(SUM(spent_tokens),0) AS t, COALESCE(SUM(spent_usd),0) AS u FROM runs WHERE order_id = ?").get(z.id),q={tokens:Math.max(0,z.budget.tokens-V.t),usd:Math.max(0,z.budget.usd-V.u),wallClockMin:z.budget.wallClockMin};if(Y===null||!K(Y))return x("data_loss",`run '${$}' has no validated respawn authority after terminalization`);let B=X.slice_demand_id!==null?{demandId:X.slice_demand_id}:{},G=this.spawnInternal(z,B,Y.ok,{budgets:q,respawnOf:$,reapCount:X.reap_count+1});if(!("ok"in G))return G;return{ok:{respawned:G.ok}}}recoverCrashed(){let $=[],Z=[],Q=this.db.query(`SELECT run_id FROM runs
520
+ WHERE terminal_payload_json IS NOT NULL
521
+ AND (terminal_event_id IS NULL OR terminal_summary_event_id IS NULL OR terminal_postlude_done = 0)
522
+ ORDER BY queued_awake_ms ASC`).all();for(let Y of Q){let j=this.finishTerminalExit(Y.run_id);if(!K(j))return j}let X=this.db.query("SELECT * FROM runs WHERE state = 'RUNNING'").all();for(let Y of X){let j=this.reap(Y.run_id,"crash","falcon restart found RUNNING row with no live process");if(!("ok"in j))return j;$.push(Y.run_id)}let z=this.db.query("SELECT * FROM runs WHERE state = 'LEASED'").all();for(let Y of z)this.leases.release(Y.run_id),this.db.query("UPDATE runs SET state = 'FAILED', exit_status = 'failed' WHERE run_id = ?").run(Y.run_id),Z.push(Y.run_id);return{ok:{reaped:$,releasedLeased:Z}}}run($){let Z=this.raw($);if(Z===null)return x("not_found",`no run '${$}'`);return{ok:this.view(Z)}}authorizeCredential($,Z){if(!this.appender.healthy())return x("unavailable","HALT_LOUD: credential authorization is disabled while the event log is unwritable (I-7/D24)","retry-at-higher-level",this.appender.haltError()??void 0);let Q=this.raw($);if(Q===null)return x("not_found",`no run '${$}'`);let X=this.validatedOrder(Q);if(!K(X))return r(X)?X:x("data_loss",`run '${$}' persisted WorkOrder validation returned empty`);if(X.ok.id!==Q.order_id)return x("data_loss",`run '${$}' persisted WorkOrder id does not match its run authority`);if(Q.state!=="RUNNING")return x("failed_precondition",`run '${$}' is ${Q.state} \u2014 credential execution requires RUNNING`);let z=Q.heartbeat_awake_ms??Q.spawned_awake_ms;if((z===null?Number.POSITIVE_INFINITY:this.clock.awakeNowMs()-z)>mQ*Q.heartbeat_every_sec*1000)return x("failed_precondition",`run '${$}' heartbeat is stale \u2014 credential execution refused (I-7)`);if(this.remainingWallClockFor(Q)<=0)return x("failed_precondition",`run '${$}' wall-clock budget is exhausted \u2014 credential execution refused (I-7)`);let j=this.credentialsByRun.get($)?.find((V)=>V.id===Z.id);if(j===void 0)return x("permission_denied",`credential handle is not assigned to run '${$}' (I-7)`);if(!(j.source===Z.source&&j.account===Z.account&&j.expiresAt===Z.expiresAt&&j.scopes.length===Z.scopes.length&&j.scopes.every((V,q)=>Z.scopes[q]===V)))return x("permission_denied",`credential handle metadata does not match run '${$}' assignment (I-7)`);return{ok:{orderId:X.ok.id,grant:{...j,scopes:[...j.scopes]}}}}markCredentialRevoked($,Z){let Q=(this.credentialsByRun.get($)??[]).filter((X)=>X.id!==Z);if(Q.length===0)this.credentialsByRun.delete($);else this.credentialsByRun.set($,Q)}retryCredentialCleanup($){let Z=this.raw($);if(Z===null)return x("not_found",`no run '${$}'`);if(Z.state==="QUEUED"||Z.state==="LEASED"||Z.state==="RUNNING")return x("failed_precondition",`run '${$}' is ${Z.state}; credential cleanup retry requires a terminal run`);if(Z.terminal_payload_json!==null&&Z.terminal_summary_json!==null){let Q=this.finishTerminalExit($);return K(Q)?{ok:void 0}:Q}return this.finalizeCredentialCleanup($)}retryTerminalExit($){let Z=this.raw($);if(Z===null)return x("not_found",`no run '${$}'`);if(Z.terminal_payload_json===null||Z.terminal_summary_json===null)return x("failed_precondition",`run '${$}' has no persisted terminal phase to retry`);return this.finishTerminalExit($)}runs($={}){return this.db.query("SELECT * FROM runs ORDER BY queued_awake_ms ASC").all().map((Q)=>this.view(Q)).filter((Q)=>($.state===void 0||Q.state===$.state)&&($.orderId===void 0||Q.orderId===$.orderId))}failCredentialedSpawn($,Z,Q){if(this.db.query("UPDATE runs SET state = 'FAILED', exit_status = 'failed' WHERE run_id = ?").run($),this.leases.release($),Z.length===0)return{err:Q};this.credentialsByRun.set($,Z.map((Y)=>({...Y,scopes:[...Y.scopes]})));let X=this.finalizeCredentialCleanup($);if(K(X))return{err:Q};let z=r(X)?X.err:{code:"internal",layer:"kernel",retryability:"non-retryable",message:"credential cleanup returned empty after spawn validation failure"};return this.aggregateFailures(`credentialed spawn '${$}' failed validation/mint and cleanup`,[Q,z])}aggregateFailures($,Z){if(Z.length===1)return{err:Z[0]};let Q;for(let X=Z.length-1;X>=0;X--)Q=this.appendFailureTail(Z[X],Q);return x("unavailable",$,"retry-at-higher-level",Q)}appendFailureTail($,Z){return{code:$.code,layer:$.layer,retryability:$.retryability,message:$.message,...$.cause!==void 0?{cause:this.appendFailureTail($.cause,Z)}:Z!==void 0?{cause:Z}:{}}}typeRowFor($){if($.worker_type_json===null)return x("data_loss",`run '${$.run_id}' is missing persisted worker-type authority; refusing lossy respawn`);let Z;try{Z=JSON.parse($.worker_type_json)}catch{return x("data_loss",`run '${$.run_id}' has malformed persisted worker-type authority`)}if(Z===null||typeof Z!=="object"||Array.isArray(Z))return x("data_loss",`run '${$.run_id}' worker-type authority is not an object`);let Q=Z,X=(J)=>Array.isArray(J)&&J.every((U)=>typeof U==="string"),z=Q.defaultBudgets,Y=z!==null&&typeof z==="object"&&!Array.isArray(z)&&["tokens","usd","wallClockMin"].every((J)=>{let U=z[J];return typeof U==="number"&&Number.isFinite(U)&&U>=0}),j=(J)=>typeof J==="string"&&J.trim().length>0,W=(J)=>j(J)&&J===J.trim()&&!J.includes(":"),V=Q.actionScopes===void 0||Array.isArray(Q.actionScopes)&&Q.actionScopes.every((J)=>J!==null&&typeof J==="object"&&!Array.isArray(J)&&W(J.source)&&j(J.account)&&X(J.scopes)&&J.scopes.every((U)=>U.trim().length>0)),q=Q.skillVersions===void 0||Array.isArray(Q.skillVersions)&&Q.skillVersions.every((J)=>J!==null&&typeof J==="object"&&!Array.isArray(J)&&typeof J.skill==="string"&&J.skill.length>0&&typeof J.version==="string"&&J.version.length>0),B=NX(Q.capabilities);if(!(Q.workerType===$.worker_type&&(Q.harness==="sdk"||Q.harness==="local-loop")&&(Q.qosClass==="utility"||Q.qosClass==="background")&&typeof Q.modelPin==="string"&&(Q.localVariant===void 0||typeof Q.localVariant==="string")&&X(Q.allowedDomains)&&Y&&V&&q&&K(B)))return x("data_loss",`run '${$.run_id}' persisted worker-type authority failed validation`);return{ok:Z}}syncAuthoritativeSpend($){let Z=this.raw($);if(Z===null)return x("not_found",`no run '${$}'`);if(this.meter===void 0)return{ok:{tokens:Z.spent_tokens,usd:Z.spent_usd}};if(this.meter.ledger.health()!=="healthy")return x("unavailable","authoritative SpendLedger is not healthy; worker exit fails closed","transient");let Q=0,X=0;for(let z of this.meter.ledger.all()){if(z.runId!==$)continue;Q+=z.tokensIn+z.tokensOut,X+=z.usd}if(!Number.isSafeInteger(Q)||Q<0||!Number.isFinite(X)||X<0)return x("data_loss",`authoritative spend totals are invalid for run '${$}'`);try{this.db.query("UPDATE runs SET spent_tokens = ?, spent_usd = ? WHERE run_id = ?").run(Q,X,$)}catch(z){return x("unavailable",`could not reconcile authoritative spend for run '${$}': ${String(z)}`,"transient")}return{ok:{tokens:Q,usd:X}}}failOrder($,Z){let Q=this.appender.fileIncident(`order ${$} failed: ${Z}`,"sev2","reap",this.wallNow(),{orderRef:$});if(!K(Q))return Q;return this.onOrderFailed?.($,Z),{ok:void 0}}terminalExit($,Z,Q,X,z,Y){let j=this.syncAuthoritativeSpend($);if(!K(j))return j;let W=this.raw($);if(W===null)return x("not_found",`no run '${$}'`);let V={runId:$,status:Z,evidence:Q,spend:{tokens:W.spent_tokens,usd:W.spent_usd},traceId:W.trace_id},q=gZ(V);if(!K(q))return q;let B=this.wallNow();if(W.terminal_summary_json!==null)try{let D=JSON.parse(W.terminal_summary_json);if(typeof D.terminalWallMs!=="number"||!Number.isSafeInteger(D.terminalWallMs)||D.terminalWallMs<0)return x("data_loss",`run '${$}' persisted terminal authority has no valid terminalWallMs`);B=D.terminalWallMs}catch{return x("data_loss",`run '${$}' has malformed persisted terminal summary`)}let G={runId:$,orderId:W.order_id,workerType:W.worker_type,demandId:W.slice_demand_id,tokens:W.spent_tokens,usd:W.spent_usd,outcome:Z,errorDetail:X??null,blockedQuestion:z??null,modelPin:W.model_pin,modelSeen:W.model_seen,heartbeatsMissed:0,terminalWallMs:B},J=JSON.stringify(V),U=JSON.stringify(G),L=Z==="done"?"DONE":Z==="blocked"?"BLOCKED":Z==="reaped"?"REAPED":"FAILED";if(W.terminal_payload_json===null||W.terminal_summary_json===null){if(W.terminal_payload_json!==null||W.terminal_summary_json!==null)return x("data_loss",`run '${$}' has an incomplete persisted terminal phase`);if(W.state!=="RUNNING")return x("failed_precondition",`terminal exit on run '${$}' in state ${W.state}`);this.db.query(`UPDATE runs
523
+ SET state = ?, exit_status = ?, terminal_payload_json = ?, terminal_summary_json = ?,
524
+ terminal_order_failure_reason = ?
525
+ WHERE run_id = ?`).run(L,Z,J,U,Y??null,$)}else if(W.terminal_payload_json!==J||W.terminal_summary_json!==U||W.terminal_order_failure_reason!==(Y??null))return x("failed_precondition",`terminal retry payload differs from persisted terminal authority for run '${$}'`);return this.finishTerminalExit($)}finishTerminalExit($){let Z=this.raw($);if(Z===null)return x("not_found",`no run '${$}'`);let Q=[],X=[],z=null,Y=null,j=null;try{let V=JSON.parse(Z.terminal_payload_json??"null"),q=gZ(V);if(K(q))z=q.ok;else Q.push(r(q)?q.err:x("data_loss","terminal payload validation returned empty").err),X.push("terminal payload")}catch{Q.push(x("data_loss",`run '${$}' has malformed persisted terminal payload`).err),X.push("terminal payload")}try{let V=JSON.parse(Z.terminal_summary_json??"null");if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let q=V.terminalWallMs;if(typeof q==="number"&&Number.isSafeInteger(q)&&q>=0)j=q,Y=V;else Q.push(x("data_loss",`run '${$}' persisted terminal summary has invalid terminalWallMs`).err),X.push("worker.run.summary payload")}else Q.push(x("data_loss",`run '${$}' persisted terminal summary is not an object`).err),X.push("worker.run.summary payload")}catch{Q.push(x("data_loss",`run '${$}' has malformed persisted terminal summary`).err),X.push("worker.run.summary payload")}if(z!==null&&j!==null&&Z.terminal_event_id===null){let V=this.appender.append(h9.exited,z,j,{authority:this.authority});if(K(V))try{this.db.query("UPDATE runs SET terminal_event_id = ? WHERE run_id = ?").run(V.ok,$)}catch(q){Q.push(x("unavailable",`worker.exited checkpoint failed after durable append for run '${$}': ${String(q)}`,"retry-at-higher-level").err),X.push("worker.exited checkpoint")}else Q.push(r(V)?V.err:x("internal","worker.exited append returned empty").err),X.push("worker.exited");Z=this.raw($)??Z}if(Y!==null&&j!==null&&Z.terminal_event_id!==null&&Z.terminal_summary_event_id===null){let V=this.appender.append(h9.runSummary,Y,j);if(K(V))try{this.db.query("UPDATE runs SET terminal_summary_event_id = ? WHERE run_id = ?").run(V.ok,$)}catch(q){Q.push(x("unavailable",`worker.run.summary checkpoint failed after durable append for run '${$}': ${String(q)}`,"retry-at-higher-level").err),X.push("worker.run.summary checkpoint")}else Q.push(r(V)?V.err:x("internal","worker.run.summary append returned empty").err),X.push("worker.run.summary");Z=this.raw($)??Z}let W=this.finalizeCredentialCleanup($);if(!K(W))Q.push(r(W)?W.err:x("internal",`credential cleanup returned empty for terminal run '${$}'`).err),X.push("credential cleanup");if(this.leases.release($),Q.length===0&&Z.terminal_event_id!==null&&Z.terminal_summary_event_id!==null&&Z.terminal_postlude_done===0&&z!==null){let V=Y,q=typeof V?.errorDetail==="string"?V.errorDetail:void 0,B={ok:void 0};if(Z.terminal_order_failure_reason!==null)B=this.failOrder(Z.order_id,Z.terminal_order_failure_reason);else if(z.status==="reaped"){let G=this.appender.fileIncident(`worker ${$} exited '${z.status}'${q!==void 0?`: ${q}`:""}`,"sev2","reap",this.wallNow(),{traceId:Z.trace_id,orderRef:Z.order_id});B=K(G)?{ok:void 0}:G}else if(z.status==="model-refused"||z.status==="model-substituted")B=this.failOrder(Z.order_id,`cognition supply chain failed (${z.status})${q!==void 0?`: ${q}`:""}`);if(K(B))this.db.query("UPDATE runs SET terminal_postlude_done = 1 WHERE run_id = ?").run($);else Q.push(r(B)?B.err:x("internal",`terminal postlude returned empty for run '${$}'`).err),X.push("terminal postlude")}if(Q.length>0)return this.aggregateFailures(`terminal exit '${$}' incomplete at ${[...new Set(X)].join(", ")}`,Q);if(Z.terminal_event_id===null)return x("data_loss",`terminal run '${$}' has no worker.exited checkpoint`);return{ok:{eventId:Z.terminal_event_id}}}cleanupCredentials($){let Z=this.credentialsByRun.get($)??[];if(Z.length===0)return this.credentialsByRun.delete($),{ok:void 0};if(this.broker===void 0)return x("internal",`run '${$}' has credential assignments without a broker cleanup authority`);let Q=[],X=[];for(let Y of Z){let j=this.broker.revoke(Y.id);if(K(j))continue;let W=r(j)?j.err:{code:"internal",layer:"kernel",retryability:"non-retryable",message:`broker revoke returned empty for handle '${Y.id}'`};Q.push({handleId:Y.id,error:W}),X.push(Y)}if(X.length===0)this.credentialsByRun.delete($);else this.credentialsByRun.set($,X);if(Q.length===0)return{ok:void 0};let z;for(let Y=Q.length-1;Y>=0;Y--){let j=Q[Y];z=this.appendFailureTail({code:j.error.code,layer:j.error.layer,retryability:j.error.retryability,message:`handle '${j.handleId}': ${j.error.message}`,...j.error.cause!==void 0?{cause:j.error.cause}:{}},z)}return x("unavailable",`${Q.length} credential handle revocations failed after run '${$}' became terminal; failed assignments remain retained for retry`,"retry-at-higher-level",z)}finalizeCredentialCleanup($){let Z=this.cleanupCredentials($);if(!K(Z))return Z;return this.credentialTerminalCleanup?.releaseRun($)??{ok:void 0}}view($){let Z=this.clock.awakeNowMs(),Q={runId:$.run_id,orderId:$.order_id,workerType:$.worker_type,state:$.state,heartbeatAgeMs:$.heartbeat_awake_ms===null?null:Z-$.heartbeat_awake_ms,budgets:{tokens:$.budget_tokens,usd:$.budget_usd,wallClockMin:$.budget_wallclock_min},spent:{tokens:$.spent_tokens,usd:$.spent_usd},reapCount:$.reap_count,traceId:$.trace_id};if($.respawn_of!==null)Q.respawnOf=$.respawn_of;if($.exit_status!==null)Q.exitStatus=$.exit_status;return Q}raw($){return this.db.query("SELECT * FROM runs WHERE run_id = ?").get($)??null}remainingWallClockFor($){let Z=$.wall_deadline_awake_ms??$.queued_awake_ms+$.budget_wallclock_min*60000;return Math.max(0,Z-this.clock.awakeNowMs())}validatedOrder($){let Z;try{Z=JSON.parse($.order_json)}catch{return x("data_loss",`run '${$.run_id}' has malformed persisted WorkOrder JSON`)}let Q=$3(Z);if(K(Q))return Q;if(r(Q))return x("data_loss",`run '${$.run_id}' has invalid persisted WorkOrder authority: ${Q.err.message}`,"non-retryable",Q.err);return x("data_loss",`run '${$.run_id}' persisted WorkOrder validation returned empty`)}}function RN($){return $.length===0?"no typed failure was reported":$.map((Z)=>`${Z.code}: ${Z.message}`).join(" | ")}var KJ=3,$6=300000,FY=3;class qJ{log;appender;wallNow;constructor($,Z,Q){this.log=$;this.appender=Z;this.wallNow=Q}append($,Z){if($.kind==="security.incident"){let z=$.payload,Y=z!==null&&typeof z==="object"&&!Array.isArray(z)?`${String(z.class??"incident")}: ${String(z.detail??JSON.stringify(z))}`:JSON.stringify($.payload);this.appender.fileIncident(`chokepoint: ${Y}`,"sev2","guard",this.wallNow());return}let Q={nk:{source:"zortex",stream:"security"},ts:U0(this.wallNow()),tier:"first-party",kind:$.kind,schemaVersion:1,mentions:[],body:"",payload:$.payload},X=this.log.append([Q],Z);if(!("ok"in X)){let z="err"in X?X.err:void 0;this.appender.noteExternalStorageFailure(z??{code:"unavailable",layer:"storage",retryability:"retry-at-higher-level",message:"egress sink append failed"})}}}class d8{clockSet;appender;scheduler;leases;breakers;runtime;talon;evidence;ipc;host;ring;watchdog;authority;db;wallNow;lockPath;safeMode;closed=!1;constructor($,Z){this.wallNow=$.wallNow,this.clockSet=Z.clockSet,this.appender=Z.appender,this.authority=Z.authority,this.leases=Z.leases,this.scheduler=Z.scheduler,this.breakers=Z.breakers,this.runtime=Z.runtime,this.talon=Z.talon,this.evidence=Z.evidence,this.ipc=Z.ipc,this.ring=Z.ring,this.db=Z.db,this.lockPath=Z.lockPath,this.safeMode=Z.safeMode,this.watchdog=Z.watchdog,this.host=new n1(this.runtime,this.ipc)}static boot($){AN($.dir,{recursive:!0});let Z=e1($.dir,"falcon.lock"),Q=d8.acquireLock(Z);if(!("ok"in Q))return Q;let X=KY(e1($.dir,"falcon.db")),z=$.wallNow,Y=z();X.query("INSERT INTO boots (at_wall_ms) VALUES (?)").run(Y),X.query("DELETE FROM boots WHERE at_wall_ms < ?").run(Y-$6);let j=X.query("SELECT COUNT(*) AS c FROM boots WHERE at_wall_ms >= ?").get(Y-$6).c,W=j>=KJ,V=new m1(X);V.open(Y);let q=SQ.open(e1($.dir,"fuses.db"),Y),B=new h1(V,q.store),G=new f1($.log,$.onHalt!==void 0?{onHalt:$.onHalt}:{}),J=G.claimVerdictAuthority();if(!("ok"in J))return J;let U=new o1(e1($.dir,"ring.mmap"),$.ringBytes??1048576),L=new s1(X,V),D=new c1({db:X,clock:V,appender:G,wallNow:z,ring:U}),P=new w1({db:X,clock:V,appender:G,wallNow:z,...$.breakerProbe!==void 0?{probe:$.breakerProbe}:{}}),F=$.meter?.accountant??$.envelope,A=new t1({db:X,clock:V,appender:G,authority:J.ok,leases:L,wallNow:z,...F!==void 0?{envelope:F}:{},...$.meter!==void 0?{meter:$.meter}:{},...$.broker!==void 0?{broker:$.broker}:{}}),N=new u1,S=$.chokepoint??new S3({policy:null,resolve:N.resolve,baselines:null,canaries:[],sink:new qJ($.log,G,z),now:()=>U0(z()),fusePolicy:P8}),R=new p1({db:X,clock:V,fuses:q.store,appender:G,breakers:P,chokepoint:S,evidence:N,upstream:$.upstream,wallNow:z,contracts:$.contracts,...F!==void 0?{envelope:F}:{},...$.confidentAfterMs!==void 0?{confidentAfterMs:$.confidentAfterMs}:{},...$.volatileParams!==void 0?{volatileParams:$.volatileParams}:{}}),O=new r1({talon:R,log:$.log,now:()=>U0(z()),awakeNowMs:()=>V.awakeNowMs(),...$.injectionClassifier!==void 0?{classifier:$.injectionClassifier}:{}}),T=new i1({log:$.log,appender:G,runtime:A,talon:R,wallNow:z,capabilitiesFor:$.capabilitiesFor??(()=>({actionClasses:[],taintExposure:"mediated"})),...$.provenanceFor!==void 0?{provenanceFor:$.provenanceFor}:{}}),m=new d8($,{clockSet:B,appender:G,authority:J.ok,leases:L,scheduler:D,breakers:P,runtime:A,talon:R,evidence:N,ipc:T,ring:U,db:X,lockPath:Z,safeMode:W,watchdog:O});if(W)G.append(l8.safeMode,{bootCount:j,windowMs:$6},Y);return{ok:m}}mode(){if(!this.appender.healthy())return"HALT_LOUD";if(this.safeMode)return"SAFE_MODE";return"RUNNING"}exitSafeMode(){this.safeMode=!1}verdictAuthority(){return this.authority}sleep($){let Z=this.clockSet.sleepBegan($);if(!("ok"in Z))return Z;let Q=this.appender.append(l8.sleepBegan,{awakeMs:Z.ok},$);if(!("ok"in Q))return Q;return{ok:{awakeMs:Z.ok}}}wake($){let Z=this.clockSet.reconcile($);if(!("ok"in Z))return Z;let Q=[];for(let z of Z.ok.resurface){let Y=this.appender.append("action.fuse_resumed",{intentId:z.intentId,key:z.key,fuseMs:z.fuseMs,gapMs:Z.ok.gapMs},$);if(!("ok"in Y))return Y;let j=this.clockSet.fuses.markResurfaced(z.intentId);if(!("ok"in j))return j;Q.push(z.intentId)}if(Z.ok.gapMs>0)this.talon.notePausedGap(Z.ok.gapMs);let X=this.talon.expireStalePaused();if(!("ok"in X))return X;return{ok:{gapMs:Z.ok.gapMs,resurfaced:Q}}}recoverCrashedRuns(){let $=[],Z=[],Q=[],X=this.runtime.runs({state:"RUNNING"}).length;for(let z=1;z<=FY;z++){if(X===0)return{ok:{reaped:$,releasedLeased:Z,respawnFailures:Q,passes:z-1}};let Y=this.runtime.recoverCrashed();if("ok"in Y)$.push(...Y.ok.reaped),Z.push(...Y.ok.releasedLeased);else{let W=Y.err;Q.push(W);let V=this.appender.fileIncident(`falcon boot crash recovery could not carry out a \xA74.3 escalation: ${W.message}`,"sev3","reap",this.wallNow());if(!("ok"in V))return V}let j=this.runtime.runs({state:"RUNNING"}).length;if(j>=X&&!("ok"in Y))return x("data_loss",`crash recovery made no progress on ${j} RUNNING row(s) at boot \u2014 their leases would starve every later run (\xA74.3): ${RN(Q)}`);if(X=j,X===0)return{ok:{reaped:$,releasedLeased:Z,respawnFailures:Q,passes:z}}}return x("data_loss",`crash recovery did not reach a fixpoint in ${FY} passes \u2014 ${X} RUNNING row(s) survive boot and their leases would starve every later run (\xA74.3)`)}tick($,Z){let Q=this.clockSet.tick($);if(!("ok"in Q))return Q;let X=d1(Z??{power:"ac",batteryPct:100,lowPowerMode:!1,thermal:"nominal",userActive:!1});if(this.ring.log(JSON.stringify({t:"tick",awakeMs:Q.ok,governor:X.name})),this.mode()!=="RUNNING")return{ok:{claimed:0,executed:0,deferred:0,reaped:0,governor:X,watchdog:{checked:[],recalled:[],unwatched:[],held:[]}}};let z=this.scheduler.claimDue({maxJobs:Math.max(X.concurrentWorkers,1),allowedPriorities:X.allowedPriorities});if(!("ok"in z))return z;let Y=this.watchdog.run();if(!("ok"in Y))this.appender.fileIncident(`watchdog pass failed: ${"err"in Y?Y.err.message:"checked-empty"} \u2014 the due-scan and lease sweep continue (undo-layer \xA74.1a); `+"no fuse can elapse unwatched, so degrading here is safer than stopping the falcon's own clock","sev2","watchdog",this.wallNow());let j="ok"in Y?Y.ok:{checked:[],recalled:[],unwatched:[],held:[]},W=this.talon.tick();if(!("ok"in W))return W;let V=this.runtime.sweep();if(!("ok"in V))return V;let q=this.breakers.probeHalfOpen();if(!("ok"in q))return q;return{ok:{claimed:z.ok.length,executed:W.ok.executed.length,deferred:W.ok.deferred.length,reaped:V.ok.reaped.length,governor:X,watchdog:j}}}close(){if(this.closed)return;let $=[],Z=(Q,X)=>{try{X()}catch(z){let Y=z instanceof Error?z.message:String(z);$.push(Error(`${Q} failed: ${Y}`,{cause:z}))}};if(Z("Bun.gc",()=>Bun.gc(!0)),Z("falcon database close",()=>this.db.close(!0)),Z("ring close",()=>this.ring.close()),Z("fuse store close",()=>this.clockSet.fuses.close()),Z("falcon lock release",()=>{try{CY(this.lockPath)}catch(Q){if(typeof Q==="object"&&Q!==null&&"code"in Q&&Q.code==="ENOENT")return;throw Q}}),this.closed=!0,$.length>0)throw AggregateError($,`Falcon close failed in ${$.length} cleanup operation(s)`)}static acquireLock($){for(let Z=0;Z<2;Z++)try{let Q=_N($,"wx");return SN(Q,JSON.stringify({pid:process.pid,at:new Date().toISOString()})),NN(Q),{ok:!0}}catch(Q){try{let X=JSON.parse(TN($,"utf8"));if(typeof X.pid==="number"&&X.pid!==process.pid)try{return process.kill(X.pid,0),x("failed_precondition",`another indrad (pid ${X.pid}) holds ${$} \u2014 single-instance law (\xA74.1.1); manual second copies die`)}catch(z){if(z.code==="EPERM")return x("failed_precondition",`another indrad (pid ${X.pid}) holds ${$} \u2014 single-instance law (\xA74.1.1)`);CY($);continue}if(X.pid===process.pid)return{ok:!0};CY($)}catch(X){return x("failed_precondition",`falcon lock ${$} exists and is unreadable \u2014 refusing to race (\xA74.1.1)`)}}return x("failed_precondition",`could not acquire ${$}`)}}f();var gh=String.fromCharCode(34),fh=String.fromCharCode(92),kh=String.fromCharCode(10);f();f();function NY($){return`${$.replace(/\/+$/,"")}/.zortex/falcon.sock`}function IN($){let{body:Z,...Q}=$;return Z!==void 0?{...Q,body:Buffer.from(Z).toString("base64")}:{...Q}}function yN($){return{...$,body:new Uint8Array(Buffer.from($.body,"base64"))}}class hQ{socket;buffer="";nextId=1;pending=new Map;helloWaiters=[];runId;boundSurface;constructor(){}static async connect($){let Z=new hQ;try{Z.socket=await Bun.connect({unix:$,data:{client:Z},socket:{data:(Q,X)=>Q.data.client.onData(X),close:(Q)=>Q.data.client.onClosed(),error:(Q,X)=>Q.data.client.onClosed(X)}})}catch(Q){return x("unavailable",`no indrad resident at '${$}': ${Q instanceof Error?Q.message:String(Q)}`,"retry-at-higher-level")}return H(Z)}onClosed($){let Z=x("unavailable",`falcon socket connection closed${$!==void 0?`: ${$.message}`:""}`,"retry-at-higher-level");for(let[,Q]of this.pending)Q(Z);this.pending.clear();while(this.helloWaiters.length>0)this.helloWaiters.shift()?.({t:"error",error:Z.err})}onData($){this.buffer+=$.toString("utf8");let Z=this.buffer.indexOf(`
526
+ `);while(Z>=0){let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Z=this.buffer.indexOf(`
527
+ `),Q!=="")this.onLine(Q)}}onLine($){let Z;try{Z=JSON.parse($)}catch{let Q=x("internal",`falcon socket framing fault: unparseable server frame (${$.length} bytes)`);for(let[,X]of this.pending)X(Q);this.pending.clear();while(this.helloWaiters.length>0)this.helloWaiters.shift()?.({t:"error",error:Q.err});this.socket?.end();return}if(Z.t==="result"){let Q=this.pending.get(Z.id);if(Q!==void 0)this.pending.delete(Z.id),Q(Z.result);return}this.helloWaiters.shift()?.(Z)}awaitHandshake(){return new Promise(($)=>this.helloWaiters.push($))}write($){this.socket?.write(`${JSON.stringify($)}
528
+ `)}async submit($,Z,Q){let X=this.awaitHandshake();this.write({t:"submit",order:$,slice:Z,workerType:Q});let z=await X;if(z.t==="submitted")return this.runId=z.runId,H({runId:z.runId,nonce:z.nonce});if(z.t==="error")return v(z.error);return x("internal",`unexpected handshake reply '${z.t}' to submit`)}async surface($){let Z=this.awaitHandshake();this.write({t:"surface",surface:$});let Q=await Z;if(Q.t==="surface-bound")return this.boundSurface=Q.surface,H({surface:Q.surface});if(Q.t==="error")return v(Q.error);return x("internal",`unexpected handshake reply '${Q.t}' to surface`)}async hello($,Z){let Q=this.awaitHandshake();this.write({t:"hello",runId:$,nonce:Z});let X=await Q;if(X.t==="attached")return this.runId=X.runId,H({runId:X.runId});if(X.t==="error")return v(X.error);return x("internal",`unexpected handshake reply '${X.t}' to hello`)}call($,Z){let Q=this.nextId++,X=new Promise((z)=>{this.pending.set(Q,z)});return this.write({t:"call",id:Q,method:$,args:Z}),X}appendEvents($){return this.call("appendEvents",[$])}requestAction($,Z,Q){return this.call("requestAction",[$,Z,Q])}heartbeat($){return this.call("heartbeat",[$])}query($){return this.call("query",[$])}async executeCredential($,Z){let Q=await this.call("executeCredential",[$,IN(Z)]);if(!K(Q))return Q;return H(yN(Q.ok))}revokeCredential($){return this.call("revokeCredential",[$])}exit($){return this.call("exit",[$])}disconnect(){this.socket?.end()}}_9();f();var Z6=T3;class Q6{broker;runtime;revoked=new Set;revokedByRun=new Map;bindings=new Map;attached=!1;constructor($){this.broker=$.broker,this.runtime=$.runtime}attachToRuntime(){if(this.attached)return v({code:"already_exists",layer:"kernel",retryability:"non-retryable",message:"credential talon is already attached to its runtime"});let $=this.runtime.attachCredentialTerminalCleanup(this,this.broker);if("ok"in $)this.attached=!0;return $}bind($,Z,Q){let X=this.requireAttached();if(!("ok"in X))return X;let z=this.bindings.get($)??new Map;if(z.has(Z.id))return v({code:"already_exists",layer:"kernel",retryability:"non-retryable",message:`public credential '${Z.id}' is already bound for run '${$}'`});if([...z.values()].some((W)=>W.brokerHandle.id===Q.id))return v({code:"already_exists",layer:"kernel",retryability:"non-retryable",message:`broker handle '${Q.id}' already has a public alias for run '${$}'`});let Y=this.runtime.authorizeCredential($,Q);if(!("ok"in Y))return Y;if(!(Z.source===Q.source&&Z.account===Q.account&&Z.expiresAt===Q.expiresAt&&Z.scopes.length===Q.scopes.length&&Z.scopes.every((W,V)=>Q.scopes[V]===W)))return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`public credential alias is incompatible with run '${$}' broker handle (I-7)`});return z.set(Z.id,{publicGrant:{...Z,scopes:[...Z.scopes]},brokerHandle:{...Q,scopes:[...Q.scopes]}}),this.bindings.set($,z),H(void 0)}execute($,Z,Q){let X=this.prepareExecution($,Z,Q);if(!("ok"in X))return X;return this.broker.execute(X.ok,Q)}async executeAsync($,Z,Q){let X=this.prepareExecution($,Z,Q);if(!("ok"in X))return X;if(this.broker.executeAsync===void 0)return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"credential broker has no asynchronous provider execution capability (FM-23)"});try{return await this.broker.executeAsync(X.ok,Q)}catch{return v({code:"internal",layer:"kernel",retryability:"non-retryable",message:"credential broker async execution rejected before returning a checked result"})}}prepareExecution($,Z,Q){let X=this.requireAttached();if(!("ok"in X))return X;let z=this.bindingFor($,Z);if(!("ok"in z))return z;if(this.revoked.has(z.ok.brokerHandle.id))return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"credential talon session is closed"});let Y=this.runtime.authorizeCredential($,z.ok.brokerHandle);if(!("ok"in Y))return Y;let j=Object.keys(Q.headers).find((W)=>Z6.has(W.toLowerCase()));if(j!==void 0)return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`caller-supplied credential header '${j}' is forbidden by I-7; broker injection is mandatory`});if(Q.capabilityRefs!==void 0){let W=F8(Q.capabilityRefs);if(!("ok"in W))return W}return H(Y.ok.grant.id)}revoke($,Z){let Q=this.requireAttached();if(!("ok"in Q))return Q;let X=this.bindingFor($,Z);if(!("ok"in X))return X;if(this.revoked.has(X.ok.brokerHandle.id))return H(void 0);let z=this.runtime.authorizeCredential($,X.ok.brokerHandle);if(!("ok"in z))return z;let Y=this.broker.revoke(z.ok.grant.id);if("ok"in Y){this.revoked.add(z.ok.grant.id);let j=this.revokedByRun.get($)??new Set;j.add(z.ok.grant.id),this.revokedByRun.set($,j),this.runtime.markCredentialRevoked($,z.ok.grant.id)}return Y}releaseRun($){let Z=this.requireAttached();if(!("ok"in Z))return Z;this.bindings.delete($);for(let Q of this.revokedByRun.get($)??[])this.revoked.delete(Q);return this.revokedByRun.delete($),H(void 0)}residentCounts(){let $=new Set([...this.bindings.keys(),...this.revokedByRun.keys()]),Z=0;for(let Q of this.bindings.values())Z+=Q.size;return{runs:$.size,bindings:Z,revoked:this.revoked.size}}requireAttached(){return this.attached?H(void 0):v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"credential talon is not attached to the runtime's exact minting broker (I-7)"})}bindingFor($,Z){let Q=this.bindings.get($)?.get(Z.id);if(Q===void 0)return{ok:{brokerHandle:Z}};let X=Q.publicGrant;if(!(X.id===Z.id&&X.source===Z.source&&X.account===Z.account&&X.expiresAt===Z.expiresAt&&X.scopes.length===Z.scopes.length&&X.scopes.every((Y,j)=>Z.scopes[j]===Y)))return v({code:"permission_denied",layer:"kernel",retryability:"non-retryable",message:`connector grant does not match run '${$}' credential binding (I-7)`});return{ok:{brokerHandle:Q.brokerHandle}}}}_9();f();var HJ=65536,EN=512,vN=4.5;function bN($,Z,Q){let X=0;for(let z of Z){let j=($[z]??0)/Q;X-=j*Math.log2(j)}return X}function gN($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===43||$===45||$===47||$===61||$===95}function fN($){return $>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102}function kN($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===43||$===47||$===61||$===92}function wN($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===43||$===45||$===46||$===47}function mN($){let Z;for(let Q of l0($))if(Z===void 0||Q.index<Z.index)Z={detector:Q.pattern,index:Q.index};return Z?.detector}class BJ{namedHit;genericHit;segmentLine=0;inMediaPayload=!1;mediaState=0;mimeLength=0;safeChunk=Buffer.allocUnsafe(HJ);safeLength=0;namedCarry="";genericLength=0;genericCounts=new Uint32Array(128);genericSeen=[];genericHasDigit=!1;genericHasLower=!1;genericHasUpper=!1;genericAllHex=!0;push($){for(let Z=0;Z<$.length&&this.namedHit===void 0;Z++){let Q=$[Z];if(Q===void 0)continue;if(this.pushRaw(Q),Q===10)this.flushNamed(),this.namedCarry="",this.segmentLine++}return this.namedHit}finish(){return this.finishGeneric(),this.flushNamed(),this.namedHit??this.genericHit}pushRaw($){if(this.inMediaPayload){if(kN($))return;this.inMediaPayload=!1,this.namedCarry="",this.mediaState=0}if(this.pushDetectable($),this.advanceMediaPrefix($))this.flushNamed(),this.namedCarry="",this.inMediaPayload=!0}pushDetectable($){if(this.safeChunk[this.safeLength++]=$,this.safeLength>=HJ)this.flushNamed();if(!gN($)){this.finishGeneric();return}if(this.genericLength++,this.genericCounts[$]===0)this.genericSeen.push($);this.genericCounts[$]=(this.genericCounts[$]??0)+1,this.genericHasDigit||=$>=48&&$<=57,this.genericHasUpper||=$>=65&&$<=90,this.genericHasLower||=$>=97&&$<=122,this.genericAllHex&&=fN($)}finishGeneric(){if(this.genericHit===void 0&&this.genericLength>=40&&!this.genericAllHex&&this.genericHasDigit&&this.genericHasLower&&this.genericHasUpper&&bN(this.genericCounts,this.genericSeen,this.genericLength)>=vN)this.genericHit={detector:"high-entropy literal (\u226540 chars, mixed charset)",detectorClass:"generic",segmentLine:this.segmentLine};this.genericLength=0;for(let $ of this.genericSeen)this.genericCounts[$]=0;this.genericSeen=[],this.genericHasDigit=!1,this.genericHasLower=!1,this.genericHasUpper=!1,this.genericAllHex=!0}advanceMediaPrefix($){let Z=[100,97,116,97,58];if(this.mediaState<Z.length){if($===Z[this.mediaState]){if(this.mediaState++,this.mediaState===Z.length)this.mimeLength=0}else this.mediaState=$===Z[0]?1:0;return!1}if(this.mediaState===5){if(wN($))this.mimeLength++;else if($===59&&this.mimeLength>0)this.mediaState=6;else this.mediaState=$===Z[0]?1:0,this.mimeLength=0;return!1}let X=[98,97,115,101,54,52,44][this.mediaState-6];if($===X){if(this.mediaState++,this.mediaState===13)return this.mediaState=0,this.mimeLength=0,!0}else this.mediaState=$===Z[0]?1:0,this.mimeLength=0;return!1}flushNamed(){if(this.safeLength===0||this.namedHit!==void 0)return;let $=`${this.namedCarry}${this.safeChunk.subarray(0,this.safeLength).toString("latin1")}`,Z=mN($);if(Z!==void 0)this.namedHit={detector:Z,detectorClass:"named",segmentLine:this.segmentLine};this.namedCarry=$.slice(-EN),this.safeLength=0}}f();f();f();F0();j$();function qA($){return $.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("\t","\\t").replaceAll("\r","\\r").replaceAll(`
529
+ `,"\\n")}function s0($,Z){return`${$} = "${qA(Z)}"`}var vJ=0;function HA($=process.env){let Z=$.ZORTEX_WAN_TRANSPORT?.trim();if(Z==="curl"||Z==="pooled")return Z;return($.ZORTEX_CURL_BIN?.trim()??"")!==""?"curl":"pooled"}async function BA($,Z,Q={},X=(z,Y)=>fetch(z,Y)){let z=Q.maxTimeSec??45,Y=new AbortController,j=setTimeout(()=>Y.abort(),Math.max(1,Math.ceil(z*1000)));try{let W=await X($,{method:Q.method??"GET",headers:Z,...Q.body!==void 0?{body:Q.body}:{},redirect:"manual",signal:Y.signal}),V=await W.text(),q={};return W.headers.forEach((B,G)=>{q[G.toLowerCase()]=B}),{ok:!0,status:W.status,body:V,headers:q}}catch(W){if(Y.signal.aborted)return{ok:!1,error:`wan transport exceeded ${z}s and was aborted`};return{ok:!1,error:W instanceof Error?W.message:String(W)}}finally{clearTimeout(j)}}function q6($,Z,Q={}){let X=process.env.ZORTEX_CURL_BIN?.trim()||"curl",z=["silent","show-error","include",s0("max-time",String(Q.maxTimeSec??45)),...Q.method!==void 0&&Q.method!=="GET"?[s0("request",Q.method)]:[],...Object.entries(Z).map(([j,W])=>s0("header",`${j}: ${W}`)),...Q.body!==void 0?[s0("data-binary",Q.body)]:[],s0("url",$),""].join(`
530
+ `);vJ++;let Y=Bun.spawnSync([X,"--config","-"],{stdin:Buffer.from(z,"utf8"),stdout:"pipe",stderr:"pipe"});if((Y.exitCode??1)!==0){let j=Y.stderr.toString().trim();return{ok:!1,error:j!==""?j:`curl exit ${Y.exitCode??"?"}`}}return bJ(Y.stdout.toString())}async function iQ($,Z,Q={}){if(HA()==="pooled")return BA($,Z,Q);let X=process.env.ZORTEX_CURL_BIN?.trim()||"curl",z=Q.maxTimeSec??45,Y=["silent","show-error","include",s0("max-time",String(z)),...Q.method!==void 0&&Q.method!=="GET"?[s0("request",Q.method)]:[],...Object.entries(Z).map(([F,A])=>s0("header",`${F}: ${A}`)),...Q.body!==void 0?[s0("data-binary",Q.body)]:[],s0("url",$),""].join(`
531
+ `),j;try{vJ++,j=Bun.spawn([X,"--config","-"],{stdin:Buffer.from(Y,"utf8"),stdout:"pipe",stderr:"pipe"})}catch(F){return{ok:!1,error:`curl spawn failed: ${F instanceof Error?F.message:String(F)}`}}let W=new Response(j.stdout).arrayBuffer(),V=new Response(j.stderr).arrayBuffer(),q=!1,B=!1,G=!1,J,U=setTimeout(()=>{q=!0;try{j.kill("SIGTERM")}catch{B=!0}finally{J=setTimeout(()=>{try{j.kill("SIGKILL")}catch{G=!0}},250)}},Math.max(1,Math.ceil(z*1000)+250)),[L,D,P]=await Promise.all([j.exited,W,V]);if(clearTimeout(U),J!==void 0)clearTimeout(J);if(q)return{ok:!1,error:B||G?`curl transport exceeded ${z}s; termination signaling raced with child reap`:`curl transport exceeded ${z}s and was terminated`};if(L!==0){let F=new TextDecoder().decode(P).trim();return{ok:!1,error:F!==""?F:`curl exit ${L}`}}return bJ(new TextDecoder().decode(D))}function bJ($){let Z=JA($);if(Z<0)return{ok:!1,error:`unparseable status line '${$.split(/\r?\n/,1)[0]?.slice(0,60)??""}'`};let Q=GA($,Z),X=Q===null?$.slice(Z):$.slice(Z,Q.index),z=Q===null?"":$.slice(Q.index+Q.sep.length),Y=X.split(/\r?\n/),j=Y[0]??"",W=j.match(/^HTTP\/[\d.]+\s+(\d{3})/);if(W===null)return{ok:!1,error:`unparseable status line '${j.slice(0,60)}'`};let V=Number.parseInt(W[1],10),q={};for(let B of Y.slice(1)){let G=B.indexOf(":");if(G>0)q[B.slice(0,G).trim().toLowerCase()]=B.slice(G+1).trim()}return{ok:!0,status:V,body:z,headers:q}}function JA($){let Z=/(^|\r?\n\r?\n)(HTTP\/[\d.]+\s+\d{3}[^\r\n]*)/g,Q=-1,X;while((X=Z.exec($))!==null){let z=X[1]??"";Q=X.index+z.length}return Q}function GA($,Z){let Q=$.indexOf(`\r
532
+ \r
533
+ `,Z),X=$.indexOf(`
534
+
535
+ `,Z);if(Q<0&&X<0)return null;if(Q>=0&&(X<0||Q<=X))return{index:Q,sep:`\r
536
+ \r
537
+ `};return{index:X,sep:`
538
+
539
+ `}}F0();j$();j$();var J5="gmail",G5="message",d9="label",n9="thread",i9="draft",s9="attachment",H6="message.received",B6="label.changed",J6="thread.changed",G6="draft.changed",U6="attachment.observed",fY="message.deleted",o8="account",gJ="https://www.googleapis.com/auth/gmail.readonly",V0={source:J5,tier:"api",auth:{provider:"google",method:"oauth-pkce",scopes:[gJ],multiAccount:!0,probe:{op:"users.getProfile"}},streams:[{stream:G5,kinds:[H6],identity:{quality:"container-scoped",epochField:o8},revOrder:"upstream-version",revField:"historyId",deleteKind:fY},{stream:d9,kinds:[B6],identity:{quality:"container-scoped",epochField:o8},revOrder:"head-compare"},{stream:n9,kinds:[J6],identity:{quality:"container-scoped",epochField:o8},revOrder:"upstream-version",revField:"historyId"},{stream:i9,kinds:[G6],identity:{quality:"container-scoped",epochField:o8},revOrder:"upstream-version",revField:"historyId"},{stream:s9,kinds:[U6],identity:{quality:"container-scoped",epochField:o8},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"};f();function UA($){return $!==null&&typeof $==="object"&&$.__gmailDeletion===!0}var a8="1970-01-01T00:00:00.000Z";function LA($){if($===null)return{phase:"messages",pageToken:null,labelsDone:!1,sinceHistoryId:null};try{let Z=JSON.parse($),Q=typeof Z.sh==="string"?Z.sh:null;if(Z.done===!0)return{phase:"messages",pageToken:null,labelsDone:!1,sinceHistoryId:Q};return{phase:Z.ph==="threads"||Z.ph==="drafts"?Z.ph:"messages",pageToken:typeof Z.p==="string"?Z.p:null,labelsDone:Z.l===!0,sinceHistoryId:Q}}catch{return{phase:"messages",pageToken:null,labelsDone:!1,sinceHistoryId:null}}}function sQ($,Z,Q,X){return JSON.stringify({ph:$,p:Z,l:Q,sh:X})}function DA($){return JSON.stringify({done:!0,sh:$})}function o9($,Z){let Q=Z.toLowerCase();for(let X of $)if(X.name.toLowerCase()===Q)return X.value;return}function MA($){let Z=$.trim(),Q=/<([^>]+)>/.exec(Z);if(Q){let X=Q[1].trim();return X!==""?{raw:Z,email:X}:{raw:Z}}if(/^[^\s@,]+@[^\s@,]+$/.test(Z))return{raw:Z,email:Z};return{raw:Z}}function kY($){return $.split(",").map((Z)=>Z.trim()).filter((Z)=>Z!=="").map(MA)}function wY($,Z){return{role:$,raw:Z.raw,...Z.email!==void 0?{handle:{ns:"email",value:Z.email}}:{}}}function fJ($){let Z=[],Q=o9($,"From");if(Q!==void 0)for(let Y of kY(Q))Z.push(wY("actor",Y));let X=o9($,"To");if(X!==void 0)for(let Y of kY(X))Z.push(wY("participant",Y));let z=o9($,"Cc");if(z!==void 0)for(let Y of kY(z))Z.push(wY("participant",Y));return Z}function kJ($){let Z=[],Q=o9($,"Message-ID");if(Q!==void 0&&Q.trim()!=="")Z.push({rel:"rfc822-message-id",to:{ns:"rfc822-msgid",value:Q.trim()}});let X=o9($,"In-Reply-To");if(X!==void 0&&X.trim()!=="")Z.push({rel:"reply-to",to:{ns:"rfc822-msgid",value:X.trim()}});let z=o9($,"References");if(z!==void 0)for(let Y of z.split(/\s+/).map((j)=>j.trim()).filter((j)=>j!==""))Z.push({rel:"references",to:{ns:"rfc822-msgid",value:Y}});return Z}function PA($){return Buffer.from($,"base64url").toString("utf8")}function CA($){if($===void 0)return"";let Z=[],Q=(X)=>{let z=(X.mimeType??"").toLowerCase();if(!((X.filename??"")!==""||(X.body?.attachmentId??"")!=="")&&z.startsWith("text/plain")&&typeof X.body?.data==="string"&&X.body.data!==""){let j=PA(X.body.data);if(j!=="")Z.push(j)}for(let j of X.parts??[])Q(j)};return Q($),Z.join(`
540
+ `).trim()}function wJ($,Z,Q){let X=(o9($,"Subject")??"").trim(),z=CA(Q),Y=z!==""?z:Z.trim();return[X,Y].filter((j)=>j!=="").join(" \u2014 ")}function mY($){if($===void 0)return a8;let Z=Number($);if(!Number.isFinite(Z))return a8;return new Date(Z).toISOString()}function FA($){let Z=$.filename!==""?$.filename:"(unnamed attachment)",Q=`${$.mimeType}, ${$.size} bytes`;return $.contentOmitted==="over-cap"?`${Z} \u2014 ${Q} (content by-reference, over-cap)`:`${Z} \u2014 ${Q}`}function NA($){if($.sha256===void 0)return;let Z={sha256:$.sha256,bytes:$.size};if($.mimeType!=="")Z.mime=$.mimeType;if($.filename!=="")Z.name=$.filename;return[Z]}function hY($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:V0,discover(X){let z=$.census(X);if(!K(z))return z;let Y={total:z.ok.messages.total,method:"census"};if(z.ok.messages.partialReasons!==void 0)Y.partialReasons=z.ok.messages.partialReasons;return H({asOf:Q(),streams:{[G5]:Y,[d9]:{total:z.ok.labels.total,method:"census"},[n9]:{total:z.ok.threads.total,method:"census"},[i9]:{total:z.ok.drafts.total,method:"census"},[s9]:{method:"pagination-exhaustion"}}})},pull(X,z){let Y=LA(z),j=[];if(Y.phase==="messages"){if(!Y.labelsDone){let U=$.labels(X);if(!K(U))return U;for(let L of U.ok)j.push({streamRef:d9,raw:L});if(Y.sinceHistoryId!==null){let L=$.messageDeletions(X,Y.sinceHistoryId);if(!K(L)){if(L.err.code!=="not_found")return L}else for(let D of L.ok){let P={__gmailDeletion:!0,account:D.account,id:D.id,atHistoryId:D.atHistoryId};j.push({streamRef:G5,raw:P})}}}let G=$.messagesPage(X,Y.pageToken);if(!K(G))return G;for(let U of G.ok.messages)j.push({streamRef:G5,raw:U});for(let U of G.ok.attachments)j.push({streamRef:s9,raw:U});let J=G.ok.nextPageToken;if(J===null)return H({items:j,next:sQ("threads",null,!0,Y.sinceHistoryId),exhausted:!1});return H({items:j,next:sQ("messages",J,!0,Y.sinceHistoryId),exhausted:!1})}if(Y.phase==="threads"){let G=$.threadsPage(X,Y.pageToken);if(!K(G))return G;for(let U of G.ok.threads)j.push({streamRef:n9,raw:U});let J=G.ok.nextPageToken;if(J===null)return H({items:j,next:sQ("drafts",null,!0,Y.sinceHistoryId),exhausted:!1});return H({items:j,next:sQ("threads",J,!0,Y.sinceHistoryId),exhausted:!1})}let W=$.draftsPage(X,Y.pageToken);if(!K(W))return W;for(let G of W.ok.drafts)j.push({streamRef:i9,raw:G});let V=W.ok.nextPageToken;if(V!==null)return H({items:j,next:sQ("drafts",V,!0,Y.sinceHistoryId),exhausted:!1});let q=$.getProfile(X),B=K(q)&&q.ok.historyId!==void 0?q.ok.historyId:null;return H({items:j,next:DA(B),exhausted:!0})},normalize(X){if(X.streamRef===G5){if(UA(X.raw)){let V=X.raw;return{nk:{source:J5,stream:G5,sourceId:V.id,rev:V.atHistoryId},ts:a8,tier:"api",kind:fY,schemaVersion:1,mentions:[],body:`${V.id} \u2014 deleted`,payload:{id:V.id,deleted:!0,atHistoryId:V.atHistoryId}}}let z=X.raw,Y=z.payload?.headers??[],j=kJ(Y),W={nk:{source:J5,stream:G5,sourceId:z.id,rev:z.historyId},ts:mY(z.internalDate),tier:"api",kind:H6,schemaVersion:1,mentions:fJ(Y),body:wJ(Y,z.snippet??"",z.payload),payload:X.raw};if(j.length>0)W.refs=j;return W}if(X.streamRef===n9){let z=X.raw;return{nk:{source:J5,stream:n9,sourceId:z.id,rev:z.historyId},ts:a8,tier:"api",kind:J6,schemaVersion:1,mentions:[],body:`thread ${z.id}`,payload:X.raw}}if(X.streamRef===i9){let z=X.raw,Y=z.message.payload?.headers??[],j=kJ(Y),W={nk:{source:J5,stream:i9,sourceId:z.id,rev:z.message.historyId},ts:mY(z.message.internalDate),tier:"api",kind:G6,schemaVersion:1,mentions:fJ(Y),body:wJ(Y,z.message.snippet??"",z.message.payload),payload:X.raw};if(j.length>0)W.refs=j;return W}if(X.streamRef===s9){let z=X.raw,Y=NA(z),j={nk:{source:J5,stream:s9,sourceId:`${encodeURIComponent(z.messageId)}:${z.partId}`},ts:mY(z.internalDate),tier:"api",kind:U6,schemaVersion:1,mentions:[],body:FA(z),payload:X.raw};if(Y!==void 0)j.blobs=Y;return j}if(X.streamRef===d9){let z=X.raw;return{nk:{source:J5,stream:d9,sourceId:z.id},ts:a8,tier:"api",kind:B6,schemaVersion:1,mentions:[],body:z.name,payload:X.raw}}throw Error(`gmail normalize: undeclared streamRef '${X.streamRef}'`)}}}f();j$();var uJ=50000,mJ=50000,hJ=5000,uY=1048576,pJ="https://gmail.googleapis.com/gmail/v1",L6="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)",lJ=()=>({ok:!1,error:L6});function pY($,Z,Q){if(Z.length>Q)return{contentOmitted:"over-cap"};let X=$!==""?$:"application/octet-stream",z=Buffer.from(Z).toString("base64");return{sha256:L$(Z),contentDataUri:`data:${X};base64,${z}`}}class r8{transport;authHeaders;cap;pageSize;attachmentCap;includeAttachments;query;resolvedAccount=null;constructor($,Z,Q,X,z,Y,j){this.transport=$,this.authHeaders=Z,this.cap=Q,this.pageSize=X,this.attachmentCap=z,this.includeAttachments=Y,this.query=j}static create($){return new r8($.transport??lJ,$.authHeaders,$.cap??uJ,$.pageSize??100,$.attachmentCap??uY,$.includeAttachments??!0,$.query!==void 0&&$.query.trim()!==""?$.query.trim():void 0)}get($,Z,Q){let X=this.authHeaders($);if(!K(X))return X;let z=this.transport(`${pJ}${Z}`,X.ok);if(!z.ok){if(z.structuredError!==void 0)return{err:z.structuredError};if(z.error===L6)return W$("gmail live WAN transport",L6);return C("unavailable",`gmail ${Q} transport failure: ${z.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return this.routeStatus(z.status,z.body,Q)}routeStatus($,Z,Q){if($===200)try{return H(JSON.parse(Z))}catch{return C("internal",`gmail ${Q}: 200 body is not JSON \u2014 REST-surface drift (FM-19)`)}if($===401)return C("unauthenticated",`gmail ${Q} returned HTTP 401 \u2014 grant credential invalid/expired (auth.md repairs)`);if($===403)return C("permission_denied",`gmail ${Q} returned HTTP 403 \u2014 grant lacks the readonly scope (auth.md repairs)`);if($===404)return C("not_found",`gmail ${Q} returned HTTP 404 \u2014 checkpoint expired; documented full re-list (\xA72.2 rule 4)`);if($===429)return C("resource_exhausted",`gmail ${Q} returned HTTP 429 \u2014 quota exceeded`,"throttling");if($>=500)return C("unavailable",`gmail ${Q} returned HTTP ${$}`,"transient");return C("internal",`gmail ${Q} returned HTTP ${$} \u2014 REST-surface drift (FM-19)`)}account($){if(this.resolvedAccount!==null)return H(this.resolvedAccount);let Z=this.getProfile($);if(!K(Z))return Z;return this.resolvedAccount=Z.ok.emailAddress,H(this.resolvedAccount)}getProfile($){let Z=this.get($,"/users/me/profile","getProfile");if(!K(Z))return Z;let Q=Z.ok;if(Q===null||typeof Q!=="object"||Array.isArray(Q))return C("internal","gmail getProfile: response is not an object \u2014 REST-surface drift (FM-19)");let X=Q.emailAddress;if(typeof X!=="string"||X==="")return C("internal","gmail getProfile: emailAddress missing \u2014 cannot source the account epoch (REST-surface drift, FM-19)");return H(Q)}enumerateAll($,Z,Q,X){let z=[],Y=null;for(;;){let j=Z.includes("?")?"&":"?",W=Z.includes("/messages")||Z.includes("/threads"),V=`${j}maxResults=500${W&&this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${Y!==null?`&pageToken=${encodeURIComponent(Y)}`:""}`,q=this.get($,`${Z}${V}`,X);if(!K(q))return q;let B=this.parseListIds(q.ok,Q,X);if(!K(B))return B;for(let G of B.ok.ids)z.push(G);if(z.length>this.cap)return C("resource_exhausted",`gmail ${X} enumeration exceeded the ${this.cap} cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18); narrow the sync window`,"non-retryable");if(B.ok.nextPageToken===null)return H(z);Y=B.ok.nextPageToken}}parseListIds($,Z,Q){if($===null||typeof $!=="object"||Array.isArray($))return C("internal",`gmail ${Q}: response is not an object \u2014 REST-surface drift (FM-19)`);let X=$[Z],z=[];if(X!==void 0){if(!Array.isArray(X))return C("internal",`gmail ${Q}: \`${Z}\` is not an array \u2014 REST-surface drift (FM-19)`);for(let j of X){let W=j?.id;if(typeof W!=="string"||W==="")return C("internal",`gmail ${Q}: a row is missing a string \`id\` \u2014 REST-surface drift (FM-19)`);z.push(W)}}let Y=$.nextPageToken;if(Y!==void 0&&typeof Y!=="string")return C("internal",`gmail ${Q}: nextPageToken is not a string \u2014 REST-surface drift (FM-19)`);return H({ids:z,nextPageToken:typeof Y==="string"&&Y!==""?Y:null})}parseIdList($){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail messages.list: response is not an object \u2014 REST-surface drift (FM-19)");let Z=$,Q=Z.messages,X=[];if(Q!==void 0){if(!Array.isArray(Q))return C("internal","gmail messages.list: `messages` is not an array \u2014 REST-surface drift (FM-19)");for(let Y of Q){let j=Y?.id;if(typeof j!=="string"||j==="")return C("internal","gmail messages.list: a row is missing a string `id` \u2014 REST-surface drift (FM-19)");let W=Y.threadId;X.push({id:j,...typeof W==="string"?{threadId:W}:{}})}}let z=Z.nextPageToken;if(z!==void 0&&typeof z!=="string")return C("internal","gmail messages.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");return H({ids:X,nextPageToken:typeof z==="string"&&z!==""?z:null})}census($){let Z=this.enumerateAll($,"/users/me/messages?includeSpamTrash=true","messages","messages.list");if(!K(Z))return Z;let Q=this.labels($);if(!K(Q))return Q;let X=this.enumerateAll($,"/users/me/threads?includeSpamTrash=true","threads","threads.list");if(!K(X))return X;let z=this.enumerateAll($,"/users/me/drafts","drafts","drafts.list");if(!K(z))return z;return H({messages:{total:Z.ok.length},labels:{total:Q.ok.length},threads:{total:X.ok.length},drafts:{total:z.ok.length}})}messagesPage($,Z){let Q=this.account($);if(!K(Q))return Q;let X=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${Z!==null?`&pageToken=${encodeURIComponent(Z)}`:""}`,z=this.get($,`/users/me/messages?${X}`,"messages.list");if(!K(z))return z;let Y=this.parseIdList(z.ok);if(!K(Y))return Y;let j=[],W=[];for(let{id:V}of Y.ok.ids){let q=this.get($,`/users/me/messages/${encodeURIComponent(V)}?format=full`,"messages.get");if(!K(q))return q;let B=this.parseMessage(q.ok,Q.ok);if(!K(B))return B;if(j.push(B.ok),this.includeAttachments){let G=this.attachmentsFor($,B.ok);if(!K(G))return G;for(let J of G.ok)W.push(J)}}return H({messages:j,attachments:W,nextPageToken:Y.ok.nextPageToken})}attachmentsFor($,Z){let Q=this.collectAttachments(Z.payload),X=[];for(let z of Q){let Y={account:Z.account,messageId:Z.id,...Z.threadId!==void 0?{threadId:Z.threadId}:{},partId:z.partId,attachmentId:z.attachmentId,filename:z.filename,mimeType:z.mimeType,size:z.size,...Z.internalDate!==void 0?{internalDate:Z.internalDate}:{}};if(z.size>this.attachmentCap){X.push({...Y,contentOmitted:"over-cap"});continue}let j=this.get($,`/users/me/messages/${encodeURIComponent(Z.id)}/attachments/${encodeURIComponent(z.attachmentId)}`,"messages.attachments.get");if(!K(j))return j;let W=this.parseAttachmentBody(j.ok);if(!K(W))return W;let V=Buffer.from(W.ok.data,"base64url"),q=pY(z.mimeType,V,this.attachmentCap);X.push({...Y,size:V.length,...q})}return H(X)}collectAttachments($){let Z=[],Q=(X,z)=>{let Y=X.body?.attachmentId;if(typeof Y==="string"&&Y!==""){let W=typeof X.partId==="string"&&X.partId!==""?X.partId:z;Z.push({partId:W,attachmentId:Y,filename:typeof X.filename==="string"?X.filename:"",mimeType:typeof X.mimeType==="string"?X.mimeType:"application/octet-stream",size:typeof X.body?.size==="number"?X.body.size:0})}let j=X.parts??[];for(let W=0;W<j.length;W++)Q(j[W],z===""?String(W):`${z}.${W}`)};if($!==void 0)Q($,"");return Z}parseAttachmentBody($){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail attachments.get: response is not an object \u2014 REST-surface drift (FM-19)");let Z=$.data;if(typeof Z!=="string")return C("internal","gmail attachments.get: missing string `data` (the attachment bytes) \u2014 REST-surface drift (FM-19)");let Q=$.size;return H({size:typeof Q==="number"?Q:0,data:Z})}parseMessage($,Z){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail messages.get: response is not an object \u2014 REST-surface drift (FM-19)");let Q=$,X=Q.id;if(typeof X!=="string"||X==="")return C("internal","gmail messages.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)");let z=Q.historyId;if(typeof z!=="string"||z==="")return C("internal",`gmail messages.get '${X}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`);return H({...Q,account:Z})}threadsPage($,Z){let Q=this.account($);if(!K(Q))return Q;let X=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${Z!==null?`&pageToken=${encodeURIComponent(Z)}`:""}`,z=this.get($,`/users/me/threads?${X}`,"threads.list");if(!K(z))return z;let Y=this.parseListIds(z.ok,"threads","threads.list");if(!K(Y))return Y;let j=[];for(let W of Y.ok.ids){let V=this.get($,`/users/me/threads/${encodeURIComponent(W)}?format=minimal&fields=id,historyId`,"threads.get");if(!K(V))return V;let q=this.parseThread(V.ok,Q.ok);if(!K(q))return q;j.push(q.ok)}return H({threads:j,nextPageToken:Y.ok.nextPageToken})}parseThread($,Z){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail threads.get: response is not an object \u2014 REST-surface drift (FM-19)");let Q=$,X=Q.id;if(typeof X!=="string"||X==="")return C("internal","gmail threads.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)");let z=Q.historyId;if(typeof z!=="string"||z==="")return C("internal",`gmail threads.get '${X}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`);return H({account:Z,id:X,historyId:z})}draftsPage($,Z){let Q=this.account($);if(!K(Q))return Q;let X=`maxResults=${this.pageSize}${Z!==null?`&pageToken=${encodeURIComponent(Z)}`:""}`,z=this.get($,`/users/me/drafts?${X}`,"drafts.list");if(!K(z))return z;let Y=this.parseListIds(z.ok,"drafts","drafts.list");if(!K(Y))return Y;let j=[];for(let W of Y.ok.ids){let V=this.get($,`/users/me/drafts/${encodeURIComponent(W)}?format=full`,"drafts.get");if(!K(V))return V;let q=this.parseDraft(V.ok,Q.ok);if(!K(q))return q;j.push(q.ok)}return H({drafts:j,nextPageToken:Y.ok.nextPageToken})}parseDraft($,Z){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail drafts.get: response is not an object \u2014 REST-surface drift (FM-19)");let Q=$,X=Q.id;if(typeof X!=="string"||X==="")return C("internal","gmail drafts.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)");let z=this.parseMessage(Q.message,Z);if(!K(z))return z;return H({...Q,account:Z,id:X,message:z.ok})}labels($){let Z=this.account($);if(!K(Z))return Z;let Q=this.get($,"/users/me/labels","labels.list");if(!K(Q))return Q;let X=Q.ok;if(X===null||typeof X!=="object"||Array.isArray(X))return C("internal","gmail labels.list: response is not an object \u2014 REST-surface drift (FM-19)");let z=X.labels;if(z===void 0)return H([]);if(!Array.isArray(z))return C("internal","gmail labels.list: `labels` is not an array \u2014 REST-surface drift (FM-19)");let Y=[];for(let j of z){let W=j?.id,V=j.name;if(typeof W!=="string"||W==="")return C("internal","gmail labels.list: a label is missing a string `id` \u2014 REST-surface drift (FM-19)");if(typeof V!=="string")return C("internal",`gmail labels.list: label '${W}' is missing a string \`name\` \u2014 REST-surface drift (FM-19)`);Y.push({...j,account:Z.ok})}return H(Y)}parseHistoryDeletions($){if($===null||typeof $!=="object"||Array.isArray($))return C("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)");let Z=$,Q=[];if(Z.history!==void 0){if(!Array.isArray(Z.history))return C("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)");for(let z of Z.history){let Y=z?.id;if(typeof Y!=="string"||Y==="")return C("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)");let j=z?.messagesDeleted;if(j===void 0)continue;if(!Array.isArray(j))return C("internal","gmail history.list: `messagesDeleted` is not an array \u2014 REST-surface drift (FM-19)");for(let W of j){let V=W?.message?.id;if(typeof V!=="string"||V==="")return C("internal","gmail history.list: a messagesDeleted row is missing message.id \u2014 REST-surface drift (FM-19)");Q.push({id:V,atHistoryId:Y})}}}let X=Z.nextPageToken;if(X!==void 0&&typeof X!=="string")return C("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");return H({rows:Q,nextPageToken:typeof X==="string"&&X!==""?X:null})}messageDeletions($,Z){let Q=this.account($);if(!K(Q))return Q;let X=[],z=null,Y=0;for(;;){let j=`startHistoryId=${encodeURIComponent(Z)}&historyTypes=messageDeleted${z!==null?`&pageToken=${encodeURIComponent(z)}`:""}`,W=this.get($,`/users/me/history?${j}`,"history.list");if(!K(W))return W;let V=this.parseHistoryDeletions(W.ok);if(!K(V))return V;for(let q of V.ok.rows)X.push({account:Q.ok,id:q.id,atHistoryId:q.atHistoryId});if(X.length>mJ)return C("resource_exhausted",`gmail history.list deletions exceeded the ${mJ} cap \u2014 refusing a partial sweep (loud, never a silent truncation)`,"non-retryable");if(++Y>hJ)return C("resource_exhausted",`gmail history.list pagination exceeded ${hJ} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable");if(V.ok.nextPageToken===null)return H(X);z=V.ok.nextPageToken}}}f();j$();var Vd=Date.parse("2026-07-01T00:00:00.000Z");f();j$();var D6=10,cJ=1048576;function dJ($){if($===void 0)return 0;return(typeof $.body?.data==="string"?Buffer.from($.body.data,"base64url").byteLength:0)+($.parts??[]).reduce((Q,X)=>Q+dJ(X),0)}function nJ($){if($===void 0)return;let Z=$.body===void 0?void 0:{...$.body.attachmentId===void 0?{}:{attachmentId:$.body.attachmentId},...$.body.size===void 0?{}:{size:$.body.size}};return{...$.partId===void 0?{}:{partId:$.partId},...$.mimeType===void 0?{}:{mimeType:$.mimeType},...$.filename===void 0?{}:{filename:$.filename},...$.headers===void 0?{}:{headers:$.headers.map((Q)=>({...Q}))},...Z===void 0?{}:{body:Z},...$.parts===void 0?{}:{parts:$.parts.map(nJ)}}}function AA($){let Z=0;return $.map((Q)=>{let X=dJ(Q.payload);if(Z+X<=cJ)return Z+=X,Q;return{...Q,...Q.payload===void 0?{}:{payload:nJ(Q.payload)},starterContentOmitted:"starter-cap"}})}class M6{inner;grantId;page;constructor($){this.inner=$}bind($){if(this.grantId===void 0)return this.grantId=$.id,H(void 0);return this.grantId===$.id?H(void 0):C("permission_denied","gmail starter source cannot mix credential grants","non-retryable")}selected($){let Z=this.bind($);if(!K(Z))return Z;if(this.page!==void 0)return H(this.page);let Q=this.inner.messagesPage($,null);if(!K(Q))return Q;return this.page={messages:AA(Q.ok.messages.slice(0,D6)),attachments:[],nextPageToken:null},H(this.page)}getProfile($){let Z=this.bind($);return K(Z)?this.inner.getProfile($):Z}census($){let Z=this.selected($);if(!K(Z))return Z;return H({messages:{total:Z.ok.messages.length},labels:{total:0},threads:{total:0},drafts:{total:0}})}messagesPage($,Z){if(Z!==null)return C("invalid_argument","gmail starter source has one bounded page","non-retryable");return this.selected($)}threadsPage($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","gmail starter source has no thread page token","non-retryable");return H({threads:[],nextPageToken:null})}draftsPage($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","gmail starter source has no draft page token","non-retryable");return H({drafts:[],nextPageToken:null})}labels($){let Z=this.bind($);return K(Z)?H([]):Z}messageDeletions($,Z){let Q=this.bind($);return K(Q)?H([]):Q}}j$();var o0="google-drive",K0="file",a9="starter-file",P6="cloudfile.starter",U5="revision",L5="comment",D5="permission",C6="cloudfile.removed",q0={source:o0,tier:"api",auth:{provider:"google",method:"oauth-pkce",scopes:["https://www.googleapis.com/auth/drive.readonly"],multiAccount:!0,probe:{op:"about.get"}},streams:[{stream:K0,kinds:["cloudfile.changed"],identity:{quality:"durable-with-exceptions",idField:"id",rebindOn:["shared-drive-move","replace-upload"]},revOrder:"upstream-version",revField:"version",deleteKind:C6},{stream:a9,kinds:[P6],identity:{quality:"durable",idField:"id"},revOrder:"upstream-version",revField:"version"},{stream:U5,kinds:["cloudfile.revision"],identity:{quality:"durable",idField:"id"},revOrder:"upstream-version",revField:"id"},{stream:L5,kinds:["cloudfile.comment"],identity:{quality:"durable",idField:"id"},revOrder:"upstream-version",revField:"modifiedTime"},{stream:D5,kinds:["cloudfile.permission"],identity:{quality:"durable",idField:"id"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"census",healthProbe:{kind:"fetch-one",intervalMin:30},retaliationRisk:"tolerant"};f();j$();f();j$();function lY(){return{itemMediaQuota:{owner:"google-drive",scope:"item-media",reason:"downloadQuotaExceeded"}}}function aQ($){if($===null||typeof $!=="object"||!("itemMediaQuota"in $))return!1;if(Object.keys($).length!==1)return!1;let Z=$.itemMediaQuota;return Z!==null&&typeof Z==="object"&&Z.owner==="google-drive"&&Z.scope==="item-media"&&Z.reason==="downloadQuotaExceeded"&&Object.keys(Z).length===3}var sJ=500000,oJ=1000,A6=25,aJ=10,F6=A6,rQ=65536,N6="https://www.googleapis.com/drive/v3",rJ="nextPageToken,files(id,name,mimeType,version,createdTime,modifiedTime,owners(displayName,emailAddress,permissionId,me),lastModifyingUser(displayName,emailAddress,permissionId,me),parents,driveId,trashed,webViewLink,resourceKey,shortcutDetails(targetId,targetMimeType,targetResourceKey),size,md5Checksum,fileExtension,headRevisionId)",tJ="nextPageToken,files(id,name,mimeType,version,createdTime,modifiedTime,size,md5Checksum,fileExtension,headRevisionId)",eJ="nextPageToken,files(id)",$G="nextPageToken,revisions(id,mimeType,modifiedTime,keepForever,published,size,md5Checksum,originalFilename,lastModifyingUser(displayName,emailAddress,permissionId,me))",ZG="nextPageToken,comments(id,createdTime,modifiedTime,author(displayName,emailAddress,me),content,htmlContent,resolved,anchor,quotedFileContent,deleted,replies(id,createdTime,modifiedTime,author(displayName,emailAddress,me),content,htmlContent,action,deleted))",QG="nextPageToken,permissions(id,type,emailAddress,domain,role,displayName,deleted,pendingOwner,allowFileDiscovery)",XG="nextPageToken,newStartPageToken,changes(changeType,time,removed,fileId,driveId,file(id,name,mimeType,version,createdTime,modifiedTime,owners(displayName,emailAddress,permissionId,me),lastModifyingUser(displayName,emailAddress,permissionId,me),parents,driveId,trashed,webViewLink,resourceKey,shortcutDetails(targetId,targetMimeType,targetResourceKey),size,md5Checksum,fileExtension,headRevisionId))",tQ="drive.resource-key",oQ="supportsAllDrives=true&includeItemsFromAllDrives=true&corpora=allDrives",zG={"application/vnd.google-apps.document":"text/plain","application/vnd.google-apps.spreadsheet":"text/csv","application/vnd.google-apps.presentation":"text/plain","application/vnd.google-apps.drawing":"image/svg+xml","application/vnd.google-apps.script":"application/vnd.google-apps.script+json"},_A="application/vnd.google-apps.",TA=new Set(["application/json","application/xml","application/xhtml+xml","application/javascript","application/x-javascript","application/x-ndjson","application/csv","application/vnd.google-apps.script+json","image/svg+xml"]);function _6($){if($==="")return!1;let Z=$.split(";",1)[0]?.trim().toLowerCase()??"";return Z.startsWith("text/")||TA.has(Z)}function eQ($,Z=rQ){let Q=$.mimeType??"";if(Q.startsWith(_A)){let z=zG[Q];if(z===void 0)return{kind:"skip",reason:"no-export"};return{kind:"export",mime:z}}let X=$.size!==void 0?Number($.size):void 0;if(X!==void 0&&Number.isFinite(X)&&X>Z)return{kind:"skip",reason:"over-cap",...$.md5Checksum!==void 0?{md5Checksum:$.md5Checksum}:{},bytes:X};if(!_6(Q))return{kind:"skip",reason:"binary",...$.md5Checksum!==void 0?{md5Checksum:$.md5Checksum}:{},...X!==void 0&&Number.isFinite(X)?{bytes:X}:{}};return{kind:"download"}}var T6="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";function YG(){return W$("google-drive live WAN transport",T6)}var jG=()=>({ok:!1,error:T6}),SA=new Set(["rateLimitExceeded","userRateLimitExceeded","dailyLimitExceeded","sharingRateLimitExceeded"]);function iJ($){return Buffer.byteLength($,"utf8")}class $4{transport;authHeader;contentCap;pullCap;query;orderBy;starter;constructor($,Z,Q,X,z,Y,j){this.transport=$,this.authHeader=Z,this.contentCap=Q,this.pullCap=X,this.query=z,this.orderBy=Y,this.starter=j}static create($){return H(new $4($.transport??jG,$.authHeader,$.contentCap??rQ,$.pullCap??sJ,$.query!==void 0&&$.query.trim()!==""?$.query.trim():void 0,$.orderBy!==void 0&&$.orderBy.trim()!==""?$.orderBy.trim():void 0,$.starter===!0))}unavailable($){return C("unavailable",`drive request failed: ${$} \u2014 NEVER an empty success (FM-21)`,"transient")}statusError($,Z,Q){if($===401)return C("unauthenticated",`drive ${Q} returned HTTP 401 \u2014 the grant is not accepted (auth repair, not retry)`,"non-retryable");if($===403){let X=this.errorReason(Z);if(X!==void 0&&SA.has(X))return C("resource_exhausted",`drive ${Q} returned HTTP 403 (${X}) \u2014 quota throttle`,"throttling");return C("permission_denied",`drive ${Q} returned HTTP 403${X!==void 0?` (${X})`:""} \u2014 permission`,"non-retryable")}if($===404)return C("not_found",`drive ${Q} returned HTTP 404 \u2014 not found, inaccessible, or rejected cursor`,"non-retryable");if($===429){let X=this.errorReason(Z);return C("resource_exhausted",`drive ${Q} returned HTTP 429${X!==void 0?` (${X})`:""} \u2014 quota throttle`,"throttling")}if($>=500)return C("unavailable",`drive ${Q} returned HTTP ${$}`,"transient");return C("internal",`drive ${Q} returned HTTP ${$} \u2014 Drive v3 REST-surface drift (FM-19)`,"non-retryable")}errorReason($){try{let Z=JSON.parse($),Q=Z.error?.errors?.[0]?.reason;return typeof Q==="string"?Q:Z.error?.status}catch{return}}fetch($,Z,Q,X,z=!1){let Y=this.authHeader($);if(!K(Y))return Y;let j=this.transport({url:Z,headers:{Authorization:Y.ok,Accept:"application/json"},...X!==void 0?{capabilityRefs:[{kind:tQ,id:X}]}:{}});if(!j.ok){if(j.error===T6)return YG();if(j.structuredError!==void 0)return{err:j.structuredError};return this.unavailable(j.error)}if(j.status!==200){if(z&&(j.status===403||j.status===429)&&this.errorReason(j.body)==="downloadQuotaExceeded")return lY();return this.statusError(j.status,j.body,Q)}return H(j.body)}get($,Z,Q,X,z){let Y=this.fetch($,`${N6}${Z}?${Q}`,X,z);if(!K(Y))return Y;let j;try{j=JSON.parse(Y.ok)}catch{return C("internal",`drive ${X} response is not JSON \u2014 Drive v3 REST-surface drift (FM-19)`)}if(j===null||typeof j!=="object"||Array.isArray(j))return C("internal",`drive ${X} response is not a JSON object \u2014 Drive v3 REST-surface drift (FM-19)`);return H(j)}about($){let Z=this.get($,"/about","fields=user,storageQuota","GET /about");if(!K(Z))return Z;return H(Z.ok)}census($,Z={}){let Q=Z.resume?.countSoFar??0,X=Z.resume?.pageToken??null;for(;;){let z=`fields=${encodeURIComponent(eJ)}&pageSize=${F6}&${oQ}${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${X!==null?`&pageToken=${encodeURIComponent(X)}`:""}`,Y=this.get($,"/files",z,"GET /files (census)");if(!K(Y))return Y;let j=this.parseFiles(Y.ok,"census");if(!K(j))return j;if(j.ok.length>F6)return C("internal",`drive census returned ${j.ok.length} > pageSize ${F6} \u2014 Drive v3 REST-surface drift (FM-19)`);if(Q+=j.ok.length,Q>this.pullCap)return C("resource_exhausted",`drive census exceeded the ${this.pullCap}-file cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18 coverage); narrow the corpus`,"non-retryable");let W=Y.ok.nextPageToken;if(typeof W!=="string"||W==="")return H({files:Q});X=W,Z.onPage?.({pageToken:X,countSoFar:Q})}}list($,Z){let Q=this.starter?tJ:rJ,X=this.starter?aJ:A6,z=`fields=${encodeURIComponent(Q)}&pageSize=${X}&${oQ}${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${this.orderBy!==void 0?`&orderBy=${encodeURIComponent(this.orderBy)}`:""}${Z!==null?`&pageToken=${encodeURIComponent(Z)}`:""}`,Y=this.get($,"/files",z,"GET /files");if(!K(Y))return Y;let j=this.parseFiles(Y.ok,"list");if(!K(j))return j;if(j.ok.length>X)return C("internal",`drive files.list returned ${j.ok.length} > pageSize ${X} \u2014 Drive v3 REST-surface drift (FM-19)`);let W=Y.ok.nextPageToken;return H({files:j.ok,nextPageToken:typeof W==="string"&&W!==""?W:null})}exportFile($,Z,Q){let X=`${N6}/files/${encodeURIComponent(Z)}/export?mimeType=${encodeURIComponent(Q)}&supportsAllDrives=true`,z=this.fetch($,X,`GET /files/${Z}/export`,this.starter?void 0:Z,!0);if(aQ(z))return z;if(!K(z))return z;let Y=iJ(z.ok),j=L$(z.ok);if(Y>this.contentCap)return H({content:null,bytes:Y,mime:Q,sha256:j,omitted:"over-cap"});return H({content:z.ok,bytes:Y,mime:Q,sha256:j})}downloadFile($,Z,Q){let X=`${N6}/files/${encodeURIComponent(Z)}?alt=media&supportsAllDrives=true`,z=this.fetch($,X,`GET /files/${Z}?alt=media`,this.starter?void 0:Z,!0);if(aQ(z))return z;if(!K(z))return z;let Y=iJ(z.ok),j=L$(z.ok);if(Y>this.contentCap)return H({content:null,bytes:Y,mime:Q,sha256:j,omitted:"over-cap"});if(!_6(Q))return H({content:null,bytes:Y,mime:Q,sha256:j,omitted:"binary"});return H({content:z.ok,bytes:Y,mime:Q,sha256:j})}revisions($,Z,Q){let X=`fields=${encodeURIComponent($G)}&pageSize=${oJ}${Q!==null?`&pageToken=${encodeURIComponent(Q)}`:""}`,z=this.get($,`/files/${encodeURIComponent(Z)}/revisions`,X,`GET /files/${Z}/revisions`,Z);if(!K(z))return z;let Y=this.parseRows(z.ok,"revisions","revisions");if(!K(Y))return Y;let j=z.ok.nextPageToken;return H({revisions:Y.ok,nextPageToken:typeof j==="string"&&j!==""?j:null})}comments($,Z,Q){let X=`fields=${encodeURIComponent(ZG)}&pageSize=100&includeDeleted=true${Q!==null?`&pageToken=${encodeURIComponent(Q)}`:""}`,z=this.get($,`/files/${encodeURIComponent(Z)}/comments`,X,`GET /files/${Z}/comments`,Z);if(!K(z))return z;let Y=this.parseRows(z.ok,"comments","comments");if(!K(Y))return Y;let j=z.ok.nextPageToken;return H({comments:Y.ok,nextPageToken:typeof j==="string"&&j!==""?j:null})}permissions($,Z,Q){let X=`fields=${encodeURIComponent(QG)}&pageSize=100&supportsAllDrives=true${Q!==null?`&pageToken=${encodeURIComponent(Q)}`:""}`,z=this.get($,`/files/${encodeURIComponent(Z)}/permissions`,X,`GET /files/${Z}/permissions`,Z);if(!K(z))return z;let Y=this.parseRows(z.ok,"permissions","permissions");if(!K(Y))return Y;let j=z.ok.nextPageToken;return H({permissions:Y.ok,nextPageToken:typeof j==="string"&&j!==""?j:null})}startPageToken($){let Z=this.get($,"/changes/startPageToken",`${oQ}`,"GET /changes/startPageToken");if(!K(Z))return Z;let Q=Z.ok.startPageToken;if(typeof Q!=="string"||Q==="")return C("internal","drive changes.getStartPageToken has no startPageToken \u2014 Drive v3 REST-surface drift (FM-19)");return H(Q)}changes($,Z){let Q=`pageToken=${encodeURIComponent(Z)}&fields=${encodeURIComponent(XG)}&pageSize=${A6}&includeRemoved=true&${oQ}`,X=this.get($,"/changes",Q,"GET /changes");if(!K(X))return X;let z=this.parseRows(X.ok,"changes","changes");if(!K(z))return z;for(let W of z.ok){if(W.file===void 0)continue;let V=this.assertSanitizedFile(W.file);if(!K(V))return V}let Y=X.ok.nextPageToken,j=X.ok.newStartPageToken;return H({changes:z.ok,nextPageToken:typeof Y==="string"&&Y!==""?Y:null,newStartPageToken:typeof j==="string"&&j!==""?j:null})}parseFiles($,Z){let Q=this.parseRows($,"files",Z);if(!K(Q))return Q;for(let X of Q.ok){let z=this.assertSanitizedFile(X);if(!K(z))return z}return Q}assertSanitizedFile($){let Z=$,Q=Z.shortcutDetails,X=Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&Object.prototype.hasOwnProperty.call(Q,"targetResourceKey"),z=!1;if(typeof $.webViewLink==="string")try{let Y=new URL($.webViewLink);z=(Y.search.startsWith("?")?Y.search.slice(1):Y.search).split("&").some((W)=>{let V=W.indexOf("="),q=V<0?W:W.slice(0,V),B=z5(q);return B.kind!=="ok"||B.malformed||B.values.some((G)=>G.toLowerCase()==="resourcekey")})}catch{z=/[?&]resourcekey=/iu.test($.webViewLink)}if(Object.prototype.hasOwnProperty.call(Z,"resourceKey")||X||z)return C("permission_denied","drive response contained resource-key capability material outside broker custody (I-7 incident; value suppressed)","non-retryable");return H(!0)}parseRows($,Z,Q){let X=$[Z];if(X===void 0)return H([]);if(!Array.isArray(X))return C("internal",`drive ${Q} '${Z}' is not an array \u2014 Drive v3 REST-surface drift (FM-19)`);let z=[];for(let Y of X){if(Y===null||typeof Y!=="object"||Array.isArray(Y)||typeof Y.id!=="string"){if(Z==="changes"&&Y!==null&&typeof Y==="object"&&!Array.isArray(Y)){z.push(Y);continue}return C("internal",`drive ${Q} '${Z}' row has no string 'id' \u2014 Drive v3 REST-surface drift (FM-19)`)}z.push(Y)}return H(z)}}function cY($,Z={pageToken:null,restarted:!1}){let Q=$(Z.pageToken);if(!K(Q)){if("err"in Q&&Q.err.layer==="connector"&&Q.err.code==="permission_denied")return H({rows:[],next:null,omission:"permission-scoped"});if("err"in Q&&Q.err.layer==="connector"&&Q.err.code==="not_found"){if(Z.pageToken!==null&&!Z.restarted)return H({rows:[],next:{pageToken:null,restarted:!0},restartedFromStart:!0});return H({rows:[],next:null,omission:"not-found-or-inaccessible"})}return Q}return H({rows:Q.ok.rows,next:Q.ok.next===null?null:{pageToken:Q.ok.next,restarted:Z.restarted}})}function t8($){return $??""}function S6($,Z){if($===void 0)return null;let Q=$.displayName??$.emailAddress;if(Q===void 0||Q==="")return null;let X={role:Z,kind:"person",raw:Q};if(typeof $.emailAddress==="string"&&$.emailAddress!=="")X.handle={ns:"email",value:$.emailAddress};return X}function RA($){let Z=$.displayName??$.emailAddress??$.domain??$.type;if(Z===void 0||Z==="")return null;let X={role:"participant",kind:$.type==="group"||$.type==="domain"?"org":$.type==="user"?"person":"unknown",raw:Z};if(typeof $.emailAddress==="string"&&$.emailAddress!=="")X.handle={ns:"email",value:$.emailAddress};return X}function WG($,Z){return S6($,Z)}function R6($,Z){return{rel:$,to:{source:o0,stream:K0,sourceId:Z}}}var qG="c",Q4=($,Z,Q=0)=>({v:1,phase:"outer",mode:$,outerPageToken:Z,itemIndex:Q}),Z4=($)=>JSON.stringify($),VG=($)=>JSON.stringify({[qG]:$});function HG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function OA($,Z){return $==="files"?Z===null||typeof Z==="string":typeof Z==="string"&&Z.length>0}function xA($){return Number.isSafeInteger($)&&$>=0}var IA=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|\+00:00)$/;function KG($){if(typeof $!=="string"||!IA.test($))return!1;let Z=Date.parse($);return!Number.isNaN(Z)&&new Date(Z).toISOString().slice(0,19)===$.slice(0,19)}function yA($){let Z=$.mode;if($.v!==1||Z!=="files"&&Z!=="changes")return C("invalid_argument","google-drive pull cursor has an unsupported version or mode");let{outerPageToken:Q,itemIndex:X}=$;if(!OA(Z,Q)||!xA(X))return C("invalid_argument","google-drive pull cursor has an invalid outer-page token or file index");if($.phase==="outer")return H({v:1,phase:"outer",mode:Z,outerPageToken:Q,itemIndex:X});if($.phase==="file"){let z=$.work;if(!HG(z))return C("invalid_argument","google-drive file cursor has no work item");if(z.kind==="file"&&typeof z.fileId==="string"&&z.fileId.length>0)return H({v:1,phase:"file",mode:Z,outerPageToken:Q,itemIndex:X,work:{kind:"file",fileId:z.fileId}});return C("invalid_argument","google-drive file cursor contains malformed work")}if($.phase==="deletion"){let z=["v","phase","mode","outerPageToken","itemIndex","fileId"];if(Z!=="changes"||typeof Q!=="string"||typeof $.fileId!=="string"||$.fileId.length===0||Object.keys($).some((Y)=>!z.includes(Y)))return C("invalid_argument","google-drive deletion cursor contains provider evidence or malformed routing state");return H({v:1,phase:"deletion",mode:Z,outerPageToken:Q,itemIndex:X,fileId:$.fileId})}if($.phase==="nested"){let{subresource:z,nestedPageToken:Y}=$;if(typeof $.fileId!=="string"||$.fileId.length===0||z!=="revisions"&&z!=="comments"&&z!=="permissions"||Y!==null&&typeof Y!=="string"||typeof $.nestedRestarted!=="boolean")return C("invalid_argument","google-drive nested cursor is malformed");return H({v:1,phase:"nested",mode:Z,outerPageToken:Q,itemIndex:X,fileId:$.fileId,subresource:z,nestedPageToken:Y,nestedRestarted:$.nestedRestarted})}return C("invalid_argument","google-drive pull cursor has an unknown phase")}function EA($){if($===null)return H(Q4("files",null));try{let Z=JSON.parse($);if(HG(Z)){let Q=Z[qG];if(Z.v===void 0&&typeof Q==="string"&&Q.length>0)return H(Q4("changes",Q));if(Z.v!==void 0||Z.phase!==void 0)return yA(Z)}}catch{}return H(Q4("files",$))}function dY($,Z={}){let Q=Z.now??(()=>new Date().toISOString()),X={censusWatermark:null},z=Z.runtimeState??{read:()=>({censusWatermark:X.censusWatermark===null?null:{...X.censusWatermark}}),replace:(J)=>{X={censusWatermark:J.censusWatermark===null?null:{...J.censusWatermark}}}},Y=(J,U)=>{let L=eQ(U,rQ);if(L.kind==="skip")return H({...U,content:null,contentOmitted:L.reason,contentMime:U.mimeType,...L.bytes!==void 0?{contentBytes:L.bytes}:{}});let D=L.kind==="export"?$.exportFile(J,U.id,L.mime):$.downloadFile(J,U.id,U.mimeType??"");if(aQ(D))return H({...U,content:null,contentOmitted:"quota",contentMime:U.mimeType});if(!K(D)){if("err"in D&&D.err.layer==="connector"&&(D.err.code==="permission_denied"||D.err.code==="not_found"))return H({...U,content:null,contentOmitted:"unreadable",contentMime:U.mimeType});return D}let P=D.ok;return H({...U,content:P.content,contentBytes:P.bytes,contentMime:P.mime,...P.sha256!==void 0?{contentSha256:P.sha256}:{},...P.md5Checksum!==void 0?{md5Checksum:P.md5Checksum}:{},...P.omitted!==void 0?{contentOmitted:P.omitted}:{}})},j=(J)=>({streamRef:Z.starter===!0?a9:K0,raw:J}),W=(J,U,L,D,P)=>{if(U==="files"){let S=$.list(J,L);if(!K(S))return S;let R=S.ok.files[D];if(R?.id===P)return H(R);let O=S.ok.files.find((T)=>T.id===P);return O===void 0?C("not_found","google-drive outer page no longer contains the cursored file"):H(O)}if(L===null)return C("invalid_argument","google-drive changes file cursor has no page token");let F=$.changes(J,L);if(!K(F))return F;let A=F.ok.changes[D]?.file;if(A?.id===P)return H(A);let N=F.ok.changes.find((S)=>S.file?.id===P)?.file;return N===void 0?C("not_found","google-drive changes page no longer contains the cursored file"):H(N)},V=(J,U,L,D)=>{if(U===null)return C("invalid_argument","google-drive deletion cursor has no cited changes page");let P=$.changes(J,U);if(!K(P))return"empty"in P?C("failed_precondition","google-drive deletion rehydration returned checked-empty for an in-flight cursor"):P;let F=P.ok.changes.filter((R)=>R.fileId===D);if(F.length===0)return C("failed_precondition","google-drive deletion evidence is missing or mismatched on the cited changes page");if(F.length>1)return C("failed_precondition","google-drive deletion evidence is ambiguous on the cited changes page");let A=P.ok.changes[L],N=A?.fileId===D?A:F[0],S=N.fileId;if(S!==D)return C("failed_precondition","google-drive deletion evidence identity changed during provider-page selection");if(N.removed!==!0)return C("failed_precondition","google-drive deletion evidence does not assert removed on the cited changes page");if(!KG(N.time))return C("internal","google-drive deletion evidence has an invalid RFC3339 UTC provider time \u2014 Drive v3 REST-surface drift (FM-19)");return H({fileId:S,time:N.time})},q=(J,U,L)=>Z4(Q4(J,U,L)),B=(J)=>{if(J.subresource==="revisions")return{...J,subresource:"comments",nestedPageToken:null,nestedRestarted:!1};if(J.subresource==="comments")return{...J,subresource:"permissions",nestedPageToken:null,nestedRestarted:!1};return Q4(J.mode,J.outerPageToken,J.itemIndex+1)},G=(J,U,L,D,P)=>{let F=[];if(D.omission!==void 0){let N=Y(J,L);if(!K(N))return N;P.unshift(j(N.ok)),F.push({stream:U.subresource==="revisions"?U5:U.subresource==="comments"?L5:D5,reason:D.omission,parent:{stream:K0,sourceId:L.id}})}let A=D.next===null?B(U):{...U,nestedPageToken:D.next.pageToken,nestedRestarted:D.next.restarted};return H({items:P,...F.length>0?{omissions:F}:{},next:Z4(A),exhausted:!1})};return{manifest:q0,discover(J){let U=z.read().censusWatermark,L=$.census(J,{...U!==null?{resume:U}:{},onPage:(D)=>{z.replace({censusWatermark:D})}});if(!K(L))return L;if(z.replace({censusWatermark:null}),Z.starter===!0)return H({asOf:Q(),streams:{[K0]:{total:0,method:"census"},[a9]:{total:L.ok.files,method:"census",...L.ok.partialReasons!==void 0?{partialReasons:L.ok.partialReasons}:{}},[U5]:{method:"pagination-exhaustion"},[L5]:{method:"pagination-exhaustion"},[D5]:{method:"pagination-exhaustion"}}});return H({asOf:Q(),streams:{[K0]:{total:L.ok.files,method:"census",...L.ok.partialReasons!==void 0?{partialReasons:L.ok.partialReasons}:{}},[U5]:{method:"pagination-exhaustion"},[L5]:{method:"pagination-exhaustion"},[D5]:{method:"pagination-exhaustion"}}})},pull(J,U){let L=EA(U);if(!K(L))return L;let D=L.ok;if(D.phase==="outer"){if(D.mode==="files"){let d=$.list(J,D.outerPageToken);if(!K(d))return d;let y=d.ok.files[D.itemIndex];if(y!==void 0){let g={v:1,phase:"file",mode:D.mode,outerPageToken:D.outerPageToken,itemIndex:D.itemIndex,work:{kind:"file",fileId:y.id}};return H({items:[],next:Z4(g),exhausted:!1})}if(d.ok.nextPageToken!==null)return H({items:[],next:q("files",d.ok.nextPageToken,0),exhausted:!1});if(Z.starter===!0)return H({items:[],next:null,exhausted:!0});let b=$.startPageToken(J);if(!K(b))return b;return H({items:[],next:VG(b.ok),exhausted:!0})}let O=D.outerPageToken;if(O===null)return C("invalid_argument","google-drive changes cursor has no page token");let T=$.changes(J,O);if(!K(T))return T;let m=T.ok.changes[D.itemIndex];if(m!==void 0){let d=null;if(m.removed===!0){if(typeof m.fileId!=="string"||m.fileId.length===0||!KG(m.time))return C("internal","google-drive changes page contains malformed deletion evidence \u2014 Drive v3 REST-surface drift (FM-19)");d={v:1,phase:"deletion",mode:"changes",outerPageToken:O,itemIndex:D.itemIndex,fileId:m.fileId}}else if(m.file!==void 0)d={v:1,phase:"file",mode:D.mode,outerPageToken:O,itemIndex:D.itemIndex,work:{kind:"file",fileId:m.file.id}};if(d!==null)return H({items:[],next:Z4(d),exhausted:!1});return H({items:[],next:q("changes",O,D.itemIndex+1),exhausted:!1})}if(T.ok.nextPageToken!==null)return H({items:[],next:q("changes",T.ok.nextPageToken,0),exhausted:!1});let k=T.ok.newStartPageToken??O;return H({items:[],next:VG(k),exhausted:!0})}if(D.phase==="deletion"){let O=V(J,D.outerPageToken,D.itemIndex,D.fileId);if(!K(O))return O;return H({items:[{streamRef:K0,raw:{id:O.ok.fileId,removedAt:O.ok.time}}],next:q(D.mode,D.outerPageToken,D.itemIndex+1),exhausted:!1})}if(D.phase==="file"){let O=W(J,D.mode,D.outerPageToken,D.itemIndex,D.work.fileId);if(!K(O))return O;let T=Y(J,O.ok);if(!K(T))return T;let m={v:1,phase:"nested",mode:D.mode,outerPageToken:D.outerPageToken,itemIndex:D.itemIndex,fileId:T.ok.id,subresource:"revisions",nestedPageToken:null,nestedRestarted:!1};return H({items:[j(T.ok)],next:Z4(m),exhausted:!1})}let P={pageToken:D.nestedPageToken,restarted:D.nestedRestarted},F=W(J,D.mode,D.outerPageToken,D.itemIndex,D.fileId);if(!K(F))return F;let A=F.ok;if(D.subresource==="revisions"){let O=cY((m)=>{let k=$.revisions(J,A.id,m);return K(k)?H({rows:k.ok.revisions,next:k.ok.nextPageToken}):k},P);if(!K(O))return O;let T=O.ok.rows.map((m)=>({streamRef:U5,raw:{...m,fileId:A.id}}));return G(J,D,A,O.ok,T)}if(D.subresource==="comments"){let O=cY((m)=>{let k=$.comments(J,A.id,m);return K(k)?H({rows:k.ok.comments,next:k.ok.nextPageToken}):k},P);if(!K(O))return O;let T=O.ok.rows.map((m)=>({streamRef:L5,raw:{...m,fileId:A.id}}));return G(J,D,A,O.ok,T)}let N=cY((O)=>{let T=$.permissions(J,A.id,O);return K(T)?H({rows:T.ok.permissions,next:T.ok.nextPageToken}):T},P);if(!K(N))return N;let S=A.modifiedTime??A.createdTime,R=N.ok.rows.map((O)=>({streamRef:D5,raw:{...O,fileId:A.id,...S!==void 0?{fileModifiedTime:S}:{}}}));return G(J,D,A,N.ok,R)},normalize(J){switch(J.streamRef){case K0:return bA(J);case a9:return vA(J);case U5:return gA(J);case L5:return fA(J);case D5:return kA(J);default:throw Error(`google-drive normalize: undeclared streamRef '${J.streamRef}'`)}},detectRebind(J){if(J.streamRef!==K0)return null;let U=J.raw,L=U.rebindObservation;if(L===void 0)return null;return{stream:K0,from:L.from,to:U.id,condition:L.condition}}}}function vA($){let Z=$.raw,Q=Z.version;if(Q===void 0||Q==="")throw Error(`google-drive normalize: starter file '${Z.id}' has no 'version' \u2014 Drive v3 REST-surface drift (FM-19)`);let X=Z.modifiedTime??Z.createdTime;if(X===void 0||X==="")throw Error(`google-drive normalize: starter file '${Z.id}' has no modified/created time \u2014 Drive v3 REST-surface drift (FM-19)`);let{rebindObservation:z,removedAt:Y,...j}=Z,W=Z.contentOmitted!==void 0?` (content ${Z.contentOmitted})`:"";return{nk:{source:o0,stream:a9,sourceId:Z.id,rev:String(Q)},ts:X,tier:"api",kind:P6,schemaVersion:1,mentions:[],body:`${t8(Z.name)} \u2014 ${t8(Z.mimeType)}`.trim()+W,payload:j}}function bA($){let Z=$.raw;if(Z.removedAt!==void 0){let G=Z.removedAt,J=Date.parse(G);if(Number.isNaN(J))throw Error(`google-drive normalize: file '${Z.id}' removedAt '${G}' is not RFC3339 \u2014 drift (FM-19)`);return{nk:{source:o0,stream:K0,sourceId:Z.id,rev:String(J)},ts:G,tier:"api",kind:C6,schemaVersion:1,mentions:[],body:`${Z.id} \u2014 removed`,payload:{id:Z.id,removed:!0,removedAt:G}}}let Q=Z.version;if(Q===void 0||Q==="")throw Error(`google-drive normalize: file '${Z.id}' has no 'version' \u2014 Drive v3 REST-surface drift (FM-19)`);let X=Z.modifiedTime??Z.createdTime;if(X===void 0||X==="")throw Error(`google-drive normalize: file '${Z.id}' has no modified/created time \u2014 Drive v3 REST-surface drift (FM-19)`);let z=[],Y=S6(Z.lastModifyingUser,"actor");if(Y!==null)z.push(Y);for(let G of Z.owners??[]){let J=S6(G,"participant");if(J!==null)z.push(J)}let j=[];for(let G of Z.parents??[])j.push(R6("child-of",G));let{rebindObservation:W,removedAt:V,...q}=Z,B=Z.contentOmitted!==void 0?` (content ${Z.contentOmitted})`:"";return{nk:{source:o0,stream:K0,sourceId:Z.id,rev:String(Q)},ts:X,tier:"api",kind:"cloudfile.changed",schemaVersion:1,mentions:z,body:`${t8(Z.name)} \u2014 ${t8(Z.mimeType)}`.trim()+B,payload:q,...j.length>0?{refs:j}:{}}}function gA($){let Z=$.raw,Q=Z.fileId;if(Q===void 0||Q==="")throw Error(`google-drive normalize: revision '${Z.id}' has no parent fileId \u2014 connector plumbing drift`);let X=Z.modifiedTime;if(X===void 0||X==="")throw Error(`google-drive normalize: revision '${Q}:${Z.id}' has no modifiedTime \u2014 Drive v3 REST-surface drift (FM-19)`);let z=[],Y=S6(Z.lastModifyingUser,"actor");if(Y!==null)z.push(Y);return{nk:{source:o0,stream:U5,sourceId:`${Q}:${Z.id}`,rev:Z.id},ts:X,tier:"api",kind:"cloudfile.revision",schemaVersion:1,mentions:z,body:`revision ${Z.id} of ${Q}`,payload:$.raw,refs:[R6("revision-of",Q)]}}function fA($){let Z=$.raw,Q=Z.fileId;if(Q===void 0||Q==="")throw Error(`google-drive normalize: comment '${Z.id}' has no parent fileId \u2014 connector plumbing drift`);let X=Z.modifiedTime??Z.createdTime;if(X===void 0||X==="")throw Error(`google-drive normalize: comment '${Q}:${Z.id}' has no created/modified time \u2014 Drive v3 REST-surface drift (FM-19)`);let z=[],Y=WG(Z.author,"actor");if(Y!==null)z.push(Y);for(let W of Z.replies??[]){let V=WG(W.author,"participant");if(V!==null)z.push(V)}let j=Z.content??"";return{nk:{source:o0,stream:L5,sourceId:`${Q}:${Z.id}`,rev:X},ts:X,tier:"api",kind:"cloudfile.comment",schemaVersion:1,mentions:z,body:j!==""?j:`comment ${Z.id} on ${Q}`,payload:$.raw,refs:[R6("comment-on",Q)]}}function kA($){let Z=$.raw,Q=Z.fileId;if(Q===void 0||Q==="")throw Error(`google-drive normalize: permission '${Z.id}' has no parent fileId \u2014 connector plumbing drift`);let X=Z.fileModifiedTime;if(X===void 0||X==="")throw Error(`google-drive normalize: permission '${Q}:${Z.id}' has no observation time \u2014 connector plumbing drift`);let z=[],Y=RA(Z);if(Y!==null)z.push(Y);let{fileModifiedTime:j,...W}=Z;return{nk:{source:o0,stream:D5,sourceId:`${Q}:${Z.id}`},ts:X,tier:"api",kind:"cloudfile.permission",schemaVersion:1,mentions:z,body:`${t8(Z.role)} \u2014 ${t8(Z.type)}${Z.emailAddress!==void 0?` ${Z.emailAddress}`:Z.domain!==void 0?` ${Z.domain}`:""}`.trim(),payload:W,refs:[R6("permission-on",Q)]}}f();j$();var hd=Date.parse("2026-07-01T00:00:00.000Z");f();j$();var nY=20,BG=10;function wA($,Z){let Q=$.modifiedTime??$.createdTime??"";return(Z.modifiedTime??Z.createdTime??"").localeCompare(Q)||$.id.localeCompare(Z.id)}class O6{inner;grantId;selectedFiles;selectedIds=new Set;connected=!1;constructor($){this.inner=$}bind($){if(this.grantId===void 0)return this.grantId=$.id,H(void 0);return this.grantId===$.id?H(void 0):C("permission_denied","google-drive starter source cannot mix credential grants","non-retryable")}selected($){let Z=this.bind($);if(!K(Z))return Z;if(!this.connected){let z=this.inner.about($);if(!K(z))return z;this.connected=!0}if(this.selectedFiles!==void 0)return H(this.selectedFiles.map((z)=>({...z})));let Q=[],X=null;do{let z=this.inner.list($,X);if(!K(z))return z;Q.push(...z.ok.files),X=z.ok.nextPageToken}while(Q.length<nY&&X!==null);return this.selectedFiles=Q.slice(0,nY).filter((z)=>eQ(z).kind!=="skip").sort(wA).slice(0,BG).map((z)=>({...z})),this.selectedIds=new Set(this.selectedFiles.map((z)=>z.id)),H(this.selectedFiles.map((z)=>({...z})))}requireSelected($,Z){let Q=this.selected($);if(!K(Q))return Q;return this.selectedIds.has(Z)?H(void 0):C("not_found","google-drive starter scope does not contain this file","non-retryable")}about($){let Z=this.bind($);if(!K(Z))return Z;let Q=this.inner.about($);if(K(Q))this.connected=!0;return Q}census($,Z){let Q=this.selected($);return K(Q)?H({files:Q.ok.length}):Q}list($,Z){if(Z!==null)return C("invalid_argument","google-drive starter source has one bounded page","non-retryable");let Q=this.selected($);return K(Q)?H({files:Q.ok,nextPageToken:null}):Q}exportFile($,Z,Q){let X=this.requireSelected($,Z);return K(X)?H({content:null,bytes:0,mime:Q,omitted:"starter-deferred"}):X}downloadFile($,Z,Q){let X=this.requireSelected($,Z);return K(X)?H({content:null,bytes:0,mime:Q,omitted:"starter-deferred"}):X}revisions($,Z,Q){let X=this.requireSelected($,Z);if(!K(X))return X;if(Q!==null)return C("invalid_argument","google-drive starter source has no revision page token","non-retryable");return H({revisions:[],nextPageToken:null})}comments($,Z,Q){let X=this.requireSelected($,Z);if(!K(X))return X;if(Q!==null)return C("invalid_argument","google-drive starter source has no comment page token","non-retryable");return H({comments:[],nextPageToken:null})}permissions($,Z,Q){let X=this.requireSelected($,Z);if(!K(X))return X;if(Q!==null)return C("invalid_argument","google-drive starter source has no permission page token","non-retryable");return H({permissions:[],nextPageToken:null})}startPageToken($){let Z=this.bind($);return K(Z)?C("failed_precondition","google-drive starter scope does not adopt the historical changes feed","non-retryable"):Z}changes($,Z){let Q=this.bind($);return K(Q)?C("failed_precondition","google-drive starter scope does not adopt the historical changes feed","non-retryable"):Q}}j$();var o5="outlook",a5="message",M5="mail-folder",e8="attachment",r5="event",t5="contact",H0={source:o5,tier:"api",auth:{provider:"microsoft",method:"oauth-pkce",scopes:["User.Read","Mail.Read","Calendars.Read","Contacts.Read"],multiAccount:!0,probe:{op:"me.get"}},streams:[{stream:a5,kinds:["message.received"],identity:{quality:"container-scoped",epochField:"account"},revOrder:"head-compare"},{stream:M5,kinds:["folder.changed"],identity:{quality:"container-scoped",epochField:"account"},revOrder:"head-compare"},{stream:e8,kinds:["attachment.observed"],identity:{quality:"container-scoped",epochField:"account"},revOrder:"head-compare"},{stream:r5,kinds:["event.observed"],identity:{quality:"container-scoped",epochField:"account"},revOrder:"head-compare"},{stream:t5,kinds:["contact.observed"],identity:{quality:"container-scoped",epochField:"account"},revOrder:"head-compare"}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"};f();j$();var JG="1970-01-01T00:00:00.000Z",sY=1e5,GG=9000000,UG="1970-01-01T00:00:00.000Z";function LG($){let{contentBytes:Z,...Q}=$,X=typeof $["@odata.type"]==="string"?$["@odata.type"]:"";if(typeof Z==="string"&&Z!==""){if(Z.length>GG)return{attachment:Q,blob:null,contentOmitted:"over-cap"};let z=Buffer.from(Z,"base64"),Y={sha256:L$(z),bytes:z.length,...typeof $.contentType==="string"&&$.contentType!==""?{mime:$.contentType}:{},...typeof $.name==="string"&&$.name!==""?{name:$.name}:{}};return{attachment:Q,blob:Y}}if(X.includes("itemAttachment"))return{attachment:Q,blob:null,contentOmitted:"item"};if(X.includes("referenceAttachment"))return{attachment:Q,blob:null,contentOmitted:"reference"};return{attachment:Q,blob:null,contentOmitted:"no-content"}}var mA=["folders","messages","attachments","events","contacts"];function hA($){return JSON.stringify($)}function uA($){try{let Z=JSON.parse($);if(Z===null||typeof Z!=="object")return null;let Q=Z;if(!mA.includes(Q.stage)||typeof Q.account!=="string"||typeof Q.page!=="number")return null;if(Q.link!==null&&typeof Q.link!=="string")return null;let X=Q.attach,z=Array.isArray(X)&&X.every((Y)=>typeof Y==="string")?X:[];return{stage:Q.stage,link:Q.link,account:Q.account,page:Q.page,attach:z}}catch{return null}}function DG($,Z){let Q=typeof $==="string"?$.trim():"";if(Q!=="")return Q;let X=typeof Z==="string"?Z.trim():"";if(X!=="")return X.split(/\r?\n/)[0]??"";return""}function X4($,Z){let Q=Z?.emailAddress,X=typeof Q?.address==="string"?Q.address:"",z=typeof Q?.name==="string"?Q.name:"",Y=z!==""?z:X;if(Y==="")return null;let j={role:$,raw:Y};if(X!=="")j.handle={ns:"email",value:X};return j}function MG($){let Z=[],Q=X4("actor",$.from??void 0);if(Q!==null)Z.push(Q);for(let X of $.toRecipients??[]){let z=X4("participant",X);if(z!==null)Z.push(z)}for(let X of $.ccRecipients??[]){let z=X4("participant",X);if(z!==null)Z.push(z)}return Z}function pA($){let Z={...$};return delete Z.totalItemCount,delete Z.unreadItemCount,Z}function PG($){let Z=[];if(typeof $.internetMessageId==="string"&&$.internetMessageId!=="")Z.push({rel:"rfc5322-message-id",to:{ns:"rfc5322-message-id",value:$.internetMessageId}});if(typeof $.conversationId==="string"&&$.conversationId!=="")Z.push({rel:"conversation",to:{ns:"graph-conversation-id",value:$.conversationId}});return Z}function iY(...$){for(let Z of $)if(typeof Z==="string"&&Z!=="")return Z;return UG}function CG($){let Z=[],Q=X4("actor",$.organizer??void 0);if(Q!==null)Z.push(Q);for(let X of $.attendees??[]){let z=X4("participant",X?.emailAddress!==void 0?{emailAddress:X.emailAddress}:void 0);if(z!==null)Z.push(z)}return Z}function FG($){let Z=[];if(typeof $.iCalUId==="string"&&$.iCalUId!=="")Z.push({rel:"ical-uid",to:{ns:"ical-uid",value:$.iCalUId}});return Z}function oY($){let Z=typeof $.displayName==="string"?$.displayName.trim():"";if(Z!=="")return Z;let Q=typeof $.givenName==="string"?$.givenName.trim():"",X=typeof $.surname==="string"?$.surname.trim():"",z=`${Q} ${X}`.trim();if(z!=="")return z;let Y=($.emailAddresses??[]).find((j)=>typeof j?.address==="string"&&j.address!=="");return typeof Y?.address==="string"?Y.address:""}function NG($){let Z=[],Q=oY($),X=Array.isArray($.emailAddresses)?$.emailAddresses:[];if(X.length===0){if(Q!=="")Z.push({role:"subject",raw:Q});return Z}for(let z of X){let Y=typeof z?.address==="string"?z.address:"",j=typeof z?.name==="string"?z.name:"",W=Q!==""?Q:j!==""?j:Y;if(W===""&&Y==="")continue;let V={role:"subject",raw:W!==""?W:Y};if(Y!=="")V.handle={ns:"email",value:Y};Z.push(V)}return Z}function aY($,Z={}){let Q=Z.now??(()=>new Date().toISOString());return{manifest:H0,discover(X){let z=$.census(X);if(!K(z))return z;let Y=z.ok.partialReasons??{},j=(W)=>{let V=Y[W];return V!==void 0&&V.length>0?{partialReasons:V}:{}};return H({asOf:Q(),streams:{[a5]:{total:z.ok.messages,method:"count-api",...j(a5)},[M5]:{total:z.ok.folders,method:"census",...j(M5)},[r5]:{total:z.ok.events,method:"census",...j(r5)},[t5]:{total:z.ok.contacts,method:"census",...j(t5)}}})},pull(X,z){let Y=(J,U,L)=>U===null?H({items:L,next:null,exhausted:!0}):H({items:L,next:hA({...U,page:J}),exhausted:!1});if(z===null){let J=$.me(X);if(!K(J))return J;let U=$.listFolders(X,null);if(!K(U))return U;let L=J.ok.id,D=U.ok.value.map((F)=>({streamRef:M5,raw:{account:L,folder:F}})),P=U.ok.nextLink!==null?{stage:"folders",link:U.ok.nextLink,account:L,page:1,attach:[]}:{stage:"messages",link:null,account:L,page:1,attach:[]};return Y(1,P,D)}let j=uA(z);if(j===null)return C("invalid_argument","outlook pull: unparseable cursor \u2014 a corrupt cursor is drift, never silently ignored (FM-19)");if(j.page>sY)return C("resource_exhausted",`outlook pull exceeded the ${sY}-page bound \u2014 refusing an unbounded nextLink walk (loud, never a silent runaway)`);let W=j.account,V=j.page+1;if(j.stage==="folders"){let J=$.listFolders(X,j.link);if(!K(J))return J;let U=J.ok.value.map((D)=>({streamRef:M5,raw:{account:W,folder:D}})),L=J.ok.nextLink!==null?{stage:"folders",link:J.ok.nextLink,account:W,page:V,attach:[]}:{stage:"messages",link:null,account:W,page:V,attach:[]};return Y(V,L,U)}if(j.stage==="messages"){let J=$.listMessages(X,j.link);if(!K(J))return J;let U=J.ok.value.map((P)=>({streamRef:a5,raw:{account:W,message:P}})),L=[...j.attach,...J.ok.value.filter((P)=>P.hasAttachments===!0).map((P)=>P.id)],D=J.ok.nextLink!==null?{stage:"messages",link:J.ok.nextLink,account:W,page:V,attach:L}:L.length>0?{stage:"attachments",link:null,account:W,page:V,attach:L}:{stage:"events",link:null,account:W,page:V,attach:[]};return Y(V,D,U)}if(j.stage==="attachments"){let J=j.attach[0];if(J===void 0)return Y(V,{stage:"events",link:null,account:W,page:V,attach:[]},[]);let U=$.listAttachments(X,J,j.link);if(!K(U))return U;let L=U.ok.value.map((F)=>{let A=LG(F),N={account:W,messageId:J,attachment:A.attachment,...A.contentOmitted!==void 0?{contentOmitted:A.contentOmitted}:{}};return{streamRef:e8,raw:N,...A.blob!==null?{blobs:[A.blob]}:{}}});if(U.ok.nextLink!==null)return Y(V,{stage:"attachments",link:U.ok.nextLink,account:W,page:V,attach:j.attach},L);let D=j.attach.slice(1),P=D.length>0?{stage:"attachments",link:null,account:W,page:V,attach:D}:{stage:"events",link:null,account:W,page:V,attach:[]};return Y(V,P,L)}if(j.stage==="events"){let J=$.listEvents(X,j.link);if(!K(J))return J;let U=J.ok.value.map((D)=>({streamRef:r5,raw:{account:W,event:D}})),L=J.ok.nextLink!==null?{stage:"events",link:J.ok.nextLink,account:W,page:V,attach:[]}:{stage:"contacts",link:null,account:W,page:V,attach:[]};return Y(V,L,U)}let q=$.listContacts(X,j.link);if(!K(q))return q;let B=q.ok.value.map((J)=>({streamRef:t5,raw:{account:W,contact:J}})),G=q.ok.nextLink!==null?{stage:"contacts",link:q.ok.nextLink,account:W,page:V,attach:[]}:null;return Y(V,G,B)},normalize(X){if(X.streamRef===M5){let Y=X.raw.folder;return{nk:{source:o5,stream:M5,sourceId:Y.id},ts:JG,tier:"api",kind:"folder.changed",schemaVersion:1,mentions:[],body:typeof Y.displayName==="string"?Y.displayName:"",payload:pA(Y)}}if(X.streamRef===a5){let Y=X.raw.message,j=typeof Y.receivedDateTime==="string"&&Y.receivedDateTime!==""?Y.receivedDateTime:typeof Y.sentDateTime==="string"?Y.sentDateTime:"",W=PG(Y);return{nk:{source:o5,stream:a5,sourceId:Y.id},ts:j,tier:"api",kind:"message.received",schemaVersion:1,mentions:MG(Y),body:DG(Y.subject,Y.bodyPreview),payload:Y,...W.length>0?{refs:W}:{}}}if(X.streamRef===e8){let z=X.raw,Y=z.attachment;return{nk:{source:o5,stream:e8,sourceId:`${z.messageId}:${Y.id}`},ts:iY(Y.lastModifiedDateTime),tier:"api",kind:"attachment.observed",schemaVersion:1,mentions:[],body:typeof Y.name==="string"?Y.name:"",payload:z,...X.blobs!==void 0&&X.blobs.length>0?{blobs:X.blobs}:{},refs:[{rel:"attachment-of",to:{ns:"graph-message-id",value:z.messageId}}]}}if(X.streamRef===r5){let Y=X.raw.event,j=FG(Y);return{nk:{source:o5,stream:r5,sourceId:Y.id},ts:iY(Y.lastModifiedDateTime,Y.createdDateTime),tier:"api",kind:"event.observed",schemaVersion:1,mentions:CG(Y),body:typeof Y.subject==="string"?Y.subject:"",payload:Y,...j.length>0?{refs:j}:{}}}if(X.streamRef===t5){let Y=X.raw.contact;return{nk:{source:o5,stream:t5,sourceId:Y.id},ts:iY(Y.lastModifiedDateTime,Y.createdDateTime),tier:"api",kind:"contact.observed",schemaVersion:1,mentions:NG(Y),body:oY(Y),payload:Y}}throw Error(`outlook normalize: undeclared streamRef '${X.streamRef}'`)}}}f();j$();var x6="graph.microsoft.com",e5=`https://${x6}`,AG='IdType="ImmutableId"',_G=50,TG=1000,SG="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";var RG="msgraph-grant-ref:",OG=($)=>W$("outlook live Microsoft Graph WAN transport",SG),xG=($)=>H(`Bearer ${RG}${$.id}`);function r9($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:null}class z4{transport;auth;maxPageItems;pageSize;maxCensusPages;constructor($){this.transport=$.transport??OG,this.auth=$.auth??xG,this.maxPageItems=$.maxPageItems??TG,this.pageSize=$.pageSize??_G,this.maxCensusPages=$.maxCensusPages??1e4}static create($={}){return new z4($)}assertGraphHost($){let Z;try{Z=new URL($)}catch{return C("internal",`graph URL '${$}' is unparseable \u2014 REST-surface drift (FM-19)`)}if(Z.protocol!=="https:")return C("internal",`graph URL '${$}' is not https \u2014 refused (G1 SSRF discipline)`);if(Z.hostname!==x6)return C("internal",`graph URL host '${Z.hostname}' is not '${x6}' \u2014 a nextLink off the Graph host is drift/off-host, never followed (FM-19; G1 discipline)`);return H($)}routeStatus($,Z,Q){if($===401)return C("unauthenticated",`graph ${Q} \u2192 HTTP 401 InvalidAuthenticationToken \u2014 the grant is invalid/expired (grant-level; \u2192 AUTH_BLOCKED, never an empty success \u2014 FM-21)`,"non-retryable");if($===403)return C("permission_denied",`graph ${Q} \u2192 HTTP 403 \u2014 access denied / insufficient scope for the grant (grant-level; \u2192 AUTH_BLOCKED)`,"non-retryable");if($===429){let X=Z["retry-after"];return C("resource_exhausted",`graph ${Q} \u2192 HTTP 429 throttling${X!==void 0?` (Retry-After: ${X}s)`:""} \u2014 RETRY_WAIT long backoff + token bucket (\xA73.5)`,"throttling")}if($>=500)return C("unavailable",`graph ${Q} \u2192 HTTP ${$} \u2014 transient server condition (RETRY_WAIT short backoff)`,"transient");return C("internal",`graph ${Q} \u2192 HTTP ${$} \u2014 REST-surface drift / rejected request (FM-19, non-retryable \u2192 ERRORED)`)}fetchJson($,Z,Q){let X=this.assertGraphHost(Z);if(!K(X))return X;let z=this.auth($);if(!K(z))return z;let Y={method:"GET",url:Z,headers:{Authorization:z.ok,Prefer:AG,Accept:"application/json"}},j=this.transport(Y);if(!K(j))return j;let W=j.ok;if(W.status!==200)return this.routeStatus(W.status,W.headers,Q);let V;try{V=JSON.parse(W.body)}catch{return C("internal",`graph ${Q} response is not JSON \u2014 REST-surface drift (FM-19)`)}let q=r9(V);if(q===null)return C("internal",`graph ${Q} response is not an object \u2014 REST-surface drift (FM-19)`);return H(q)}readPage($,Z){let Q=$.value;if(!Array.isArray(Q))return C("internal",`graph ${Z} has no 'value' array \u2014 REST-surface drift (FM-19)`);if(Q.length>this.maxPageItems)return C("resource_exhausted",`graph ${Z} returned ${Q.length} items in one page, over the ${this.maxPageItems} cap \u2014 refusing a partial snapshot (loud, never a silent truncation that misreconciles FM-18)`);let X=$["@odata.nextLink"];return H({value:Q,nextLink:typeof X==="string"&&X!==""?X:null})}me($){let Z=this.fetchJson($,`${e5}/v1.0/me?$select=id,userPrincipalName,mail`,"GET /me");if(!K(Z))return Z;let Q=Z.ok.id;if(typeof Q!=="string"||Q==="")return C("internal","graph GET /me returned no string 'id' \u2014 cannot key the account epoch (FM-19)");return H(Z.ok)}listFolders($,Z){let Q=Z??`${e5}/v1.0/me/mailFolders?$top=${this.pageSize}&$select=id,displayName,parentFolderId,childFolderCount,unreadItemCount,totalItemCount`,X=this.fetchJson($,Q,"GET /me/mailFolders");if(!K(X))return X;let z=this.readPage(X.ok,"GET /me/mailFolders");if(!K(z))return z;for(let Y of z.ok.value)if(r9(Y)===null||typeof Y.id!=="string")return C("internal","graph mailFolder row has no string 'id' \u2014 REST-surface drift (FM-19)");return z}listMessages($,Z){let Q=Z??`${e5}/v1.0/me/messages?$top=${this.pageSize}`,X=this.fetchJson($,Q,"GET /me/messages");if(!K(X))return X;let z=this.readPage(X.ok,"GET /me/messages");if(!K(z))return z;for(let Y of z.ok.value){let j=r9(Y),W=typeof Y.receivedDateTime==="string"||typeof Y.sentDateTime==="string";if(j===null||typeof Y.id!=="string"||Y.id===""||!W)return C("internal","graph message row lacks a string 'id' or any date (received/sent) \u2014 REST-surface drift (FM-19)")}return z}listAttachments($,Z,Q){let X=Q??`${e5}/v1.0/me/messages/${encodeURIComponent(Z)}/attachments?$top=${this.pageSize}`,z=this.fetchJson($,X,"GET /me/messages/{id}/attachments");if(!K(z))return z;let Y=this.readPage(z.ok,"GET /me/messages/{id}/attachments");if(!K(Y))return Y;for(let j of Y.ok.value)if(r9(j)===null||typeof j.id!=="string"||j.id==="")return C("internal","graph attachment row has no string 'id' \u2014 REST-surface drift (FM-19)");return Y}listEvents($,Z){let Q=Z??`${e5}/v1.0/me/events?$top=${this.pageSize}`,X=this.fetchJson($,Q,"GET /me/events");if(!K(X))return X;let z=this.readPage(X.ok,"GET /me/events");if(!K(z))return z;for(let Y of z.ok.value){let j=Y,W=typeof j.lastModifiedDateTime==="string"||typeof j.createdDateTime==="string"||r9(j.start)!==null;if(r9(j)===null||typeof j.id!=="string"||j.id===""||!W)return C("internal","graph event row lacks a string 'id' or any date \u2014 REST-surface drift (FM-19)")}return z}listContacts($,Z){let Q=Z??`${e5}/v1.0/me/contacts?$top=${this.pageSize}`,X=this.fetchJson($,Q,"GET /me/contacts");if(!K(X))return X;let z=this.readPage(X.ok,"GET /me/contacts");if(!K(z))return z;for(let Y of z.ok.value)if(r9(Y)===null||typeof Y.id!=="string"||Y.id==="")return C("internal","graph contact row has no string 'id' \u2014 REST-surface drift (FM-19)");return z}countCollection($,Z,Q){let X=null,z=0;for(let Y=0;Y<this.maxCensusPages;Y++){let j=Z($,X);if(!K(j))return j;if(z+=j.ok.value.length,j.ok.nextLink===null)return H(z);X=j.ok.nextLink}return C("resource_exhausted",`graph ${Q} census exceeded the ${this.maxCensusPages}-page bound \u2014 refusing an unbounded walk (loud)`)}census($){let Z=null,Q=0,X=0,z=!1;for(let W=0;W<this.maxCensusPages&&!z;W++){let V=this.listFolders($,Z);if(!K(V))return V;for(let q of V.ok.value){X+=1;let B=q.totalItemCount;if(typeof B==="number"&&Number.isFinite(B)&&B>0)Q+=B}if(V.ok.nextLink===null)z=!0;else Z=V.ok.nextLink}if(!z)return C("resource_exhausted",`graph mailFolders census exceeded the ${this.maxCensusPages}-page bound \u2014 refusing an unbounded folder walk (loud)`);let Y=this.countCollection($,(W,V)=>this.listEvents(W,V),"GET /me/events");if(!K(Y))return Y;let j=this.countCollection($,(W,V)=>this.listContacts(W,V),"GET /me/contacts");if(!K(j))return j;return H({messages:Q,folders:X,events:Y.ok,contacts:j.ok})}}f();j$();var Dn=Date.parse("2026-07-01T00:00:00.000Z");f();j$();var I6=10;class y6{inner;grantId;messages;constructor($){this.inner=$}bind($){if(this.grantId===void 0)return this.grantId=$.id,H(void 0);return this.grantId===$.id?H(void 0):C("permission_denied","outlook starter source cannot mix credential grants","non-retryable")}selected($){let Z=this.bind($);if(!K(Z))return Z;if(this.messages!==void 0)return H(this.messages);let Q=this.inner.listMessages($,null);if(!K(Q))return Q;return this.messages={value:Q.ok.value.slice(0,I6),nextLink:null},H(this.messages)}me($){let Z=this.bind($);return K(Z)?this.inner.me($):Z}census($){let Z=this.selected($);return K(Z)?H({messages:Z.ok.value.length,folders:0,events:0,contacts:0}):Z}listFolders($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","outlook starter source has no folder page token","non-retryable");return H({value:[],nextLink:null})}listMessages($,Z){if(Z!==null)return C("invalid_argument","outlook starter source has one bounded message page","non-retryable");return this.selected($)}listAttachments($,Z,Q){let X=this.bind($);if(!K(X))return X;if(Q!==null)return C("invalid_argument","outlook starter source has no attachment page token","non-retryable");return H({value:[],nextLink:null})}listEvents($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","outlook starter source has no event page token","non-retryable");return H({value:[],nextLink:null})}listContacts($,Z){let Q=this.bind($);if(!K(Q))return Q;if(Z!==null)return C("invalid_argument","outlook starter source has no contact page token","non-retryable");return H({value:[],nextLink:null})}}F0();_9();f();import{existsSync as lA}from"fs";import{createHash as cA}from"crypto";import{join as rY}from"path";var tY="indrad credential RPC is not fabricated for synchronous CLI callers: the resident unix-socket transport (FalconSocketServer/FalconSocketClient, @indra/falcon) is fabricated and tested, but production sync execution is still synchronous end-to-end and has not moved behind it \u2014 a sync CLI call cannot safely bridge the async socket round-trip without risking a second event-log writer or a broken blocking call; CLI-local vault/broker fallback is forbidden until that migration lands (WO-SEC-I7-FALCON-EXEC-002)";function IG($){return rY($,".zortex","grants")}function dA($){return rY(IG($),"grants.db")}function nA($){return`zortex-${cA("sha256").update($).digest("hex").slice(0,16)}`}function iA(){return{...process.env,ZORTEX_KEYSTORE:process.env.ZORTEX_KEYSTORE??(process.platform==="darwin"?"macos-keychain":process.platform==="win32"?"windows-dpapi":"file-double")}}function sA($,Z){if(!Z.create&&!lA(dA($)))return H(null);let Q=pZ({env:iA(),dir:rY($,".zortex","auth-keystore"),account:nA($),production:!0});if(!K(Q))return Q;let X=k5.open({dir:IG($),keyStore:Q.ok,now:()=>new Date().toISOString()});if(!K(X))return X;return H(X.ok)}function oA($,Z,Q){return[...$.listGrants({source:Q}).filter((X)=>X.provider===Z||X.source===Z),...$.listGrants({source:Z})].filter((X)=>X.state!=="AUTH_BLOCKED"&&X.state!=="DISABLED")}function E6($,Z,Q){let X=sA($,{create:!1});if(!K(X))return X;let z=X.ok;if(z===null)return H(null);try{let Y=oA(z,Z,Q)[0];if(Y===void 0)return H(null);let j=z.listSecretCells(Y.grantId);if(!K(j))return j;return H({grantId:Y.grantId,source:Y.source,provider:Y.provider,method:Y.method,accountId:Y.account.id,accountLabel:Y.account.label,scopes:[...Y.scopes],secretCells:j.ok,...Y.clientId!==void 0?{clientId:Y.clientId}:{},...Y.atExpiresAt!==void 0?{atExpiresAt:Y.atExpiresAt}:{}})}finally{z.close()}}function yG($){return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:tY})}qj();f();var pG="posthog:",z_="@current";function Y_($={}){let Z=W4($.baseUrl??j4);if(!K(Z))return Z;let Q=$.projectId?.trim();if(Q==="")return v({code:"invalid_argument",layer:"auth",retryability:"non-retryable",message:"posthog --project-id must not be empty"});return H({baseUrl:Z.ok,...Q!==void 0?{projectId:Q}:{}})}function lG($){if(!$.startsWith(pG))return null;let Z=$.slice(pG.length),[Q,X,...z]=Z.split(":");if(Q===void 0||X===void 0||z.length>0)return null;try{let Y=decodeURIComponent(Q),j=decodeURIComponent(X),W=Y_({baseUrl:Y,...j!==z_?{projectId:j}:{}});if(!K(W))return null;return W.ok}catch{return null}}function j_($){return{url:"https://oauth2.googleapis.com/token",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:$.toString()}}function cG($){let Z=$.clientId??"497132544057-i7l3ii6t2t28b34fbq8l3c18sg1cagc5.apps.googleusercontent.com";if($.clientSecret!==void 0)return j_(new URLSearchParams({client_id:Z,client_secret:$.clientSecret,refresh_token:$.refreshToken,grant_type:"refresh_token"}));if(Z!=="497132544057-i7l3ii6t2t28b34fbq8l3c18sg1cagc5.apps.googleusercontent.com")throw Error("secretless Google OAuth refresh requires the compiled public client ID");return{url:"https://zortex-google-oauth.google-oauth-broker.workers.dev/google/refresh",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:Z,refreshToken:$.refreshToken})}}f();var E$=($,Z)=>v({code:$,layer:"kernel",retryability:"non-retryable",message:Z}),$8=($)=>({code:"data_loss",layer:"kernel",retryability:"non-retryable",message:$}),V4=($)=>({code:"resource_exhausted",layer:"kernel",retryability:"non-retryable",message:`engine provider read exhausted its ${$} replay envelope`}),W_=($)=>({code:"internal",layer:"kernel",retryability:"non-retryable",message:$});function K4($,Z){try{return H($(Z))}catch{return E$("internal","transactional read state clone failed")}}function dG($,Z){try{return $(Z)}catch{return E$("internal","transactional read target construction failed")}}function nG($){let Z=K4($.cloneState,$.initialState);if(!K(Z))return Z;let Q=Z.ok,X=0,z=!1,Y={read:()=>$.cloneState(Q),replace:(q)=>{let B=$.cloneState(q);$.clearState(Q),Q=B,X+=1}},j=dG($.build,Y);if(!K(j))return $.clearState(Q),j;let W=j.ok;return H({canonical:W,open:()=>{if(z)return E$("failed_precondition","transactional read owner is closed");let q=K4($.cloneState,Q);if(!K(q))return q;let B=q.ok,G=X,J=new Set,U=!1,L=!1;return H({attempt:()=>{if(U||L)return E$("failed_precondition","transactional read transaction is no longer active");let P=K4($.cloneState,B);if(!K(P))return P;let F=P.ok,A,N=!1,S=!1,R={read:()=>$.cloneState(F),replace:(k)=>{if(N)throw Error("transactional read attempt state is sealed");let d=$.cloneState(k);$.clearState(F),F=d}},O=dG($.build,R);if(!K(O))return $.clearState(F),O;let T=O.ok,m={target:T,seal:()=>{if(S||U||L||z)return E$("failed_precondition","transactional read attempt cannot seal after closure");if(N)return H(void 0);let k=K4($.cloneState,F);if(!K(k))return k;return A=k.ok,N=!0,H(void 0)},commit:()=>{if(S||U||L||z)return E$("failed_precondition","transactional read attempt cannot commit after closure");if(X!==G)return L=!0,E$("aborted","transactional read state changed before terminal CAS");let k=K4($.cloneState,N?A:F);if(!K(k))return L=!0,k;return $.clearState(Q),Q=k.ok,X+=1,L=!0,H(void 0)},close:()=>{if(S)return;if(S=!0,J.delete(m),$.disposeTarget?.(T),$.clearState(F),N)$.clearState(A)}};return J.add(m),H(m)},close:()=>{if(U)return;U=!0;for(let P of[...J])P.close();$.clearState(B)}})},close:()=>{if(z)return;z=!0,$.disposeTarget?.(W),$.clearState(Q)}})}function Hj($){let Z={maxProviderCalls:$.maxProviderCalls,maxRetainedBytes:$.maxRetainedBytes,maxReplaySteps:$.maxReplaySteps,maxReplayBytes:$.maxReplayBytes},Q=["maxProviderCalls","maxRetainedBytes","maxReplaySteps","maxReplayBytes"];for(let X of Q){let z=Z[X];if(!Number.isSafeInteger(z)||z<=0)return E$("invalid_argument",`engine provider replay bound '${X}' must be a positive safe integer`)}return H(Object.freeze(Z))}function V_($){try{let Z=JSON.stringify($);if(Z===void 0)return E$("data_loss","engine provider result was not snapshot-serializable");let Q=new TextEncoder().encode(Z);return H({byteLength:Q.byteLength,materialize:()=>{try{return H(JSON.parse(new TextDecoder().decode(Q)))}catch{return E$("data_loss","engine provider replay snapshot could not be materialized")}},clear:()=>Q.fill(0)})}catch{return E$("data_loss","engine provider result was not snapshot-serializable")}}class Bj{state;bounds;capture;clearRequest;constructor($,Z={}){this.bounds=Object.freeze({maxProviderCalls:$.maxProviderCalls,maxRetainedBytes:$.maxRetainedBytes,maxReplaySteps:$.maxReplaySteps,maxReplayBytes:$.maxReplayBytes}),this.capture=Z.capture??V_,this.clearRequest=Z.clearRequest??(()=>{return})}pending($){return $.pending}terminal($){return $.inlineTerminal}inlineTerminal($,Z,Q,X){this.clearRequest(Q);let z=$.sealCurrentAttempt;if(z===void 0||!K(z()))return $.divergence=$8("engine provider replay could not seal its completed-prefix checkpoint"),v($.divergence);return $.inlineTerminal={index:Z,error:{...X}},v({...X})}intercept($,Z){let Q=this.state;if(Q===void 0)return;let X=Q.index++;if(Q.replaySteps+=1,Q.replaySteps>this.bounds.maxReplaySteps)return Q.divergence=$8("engine provider replay exceeded a previously reserved step bound"),this.clearRequest(Z),v(Q.divergence);let z=Q.entries[X];if(z!==void 0){if(z.fingerprint!==$)return Q.divergence=$8(`engine provider replay request sequence diverged at position ${X}`),this.clearRequest(Z),v(Q.divergence);if(Q.replayBytes+z.snapshot.byteLength>this.bounds.maxReplayBytes)return Q.divergence=$8("engine provider replay exceeded a previously reserved byte bound"),this.clearRequest(Z),v(Q.divergence);Q.replayBytes+=z.snapshot.byteLength,this.clearRequest(Z);let W=z.snapshot.materialize();if(!K(W))return Q.divergence=$8("engine provider replay snapshot could not be materialized"),v(Q.divergence);return W.ok}if(X!==Q.entries.length||Q.pending!==void 0||Q.inlineTerminal!==void 0)return Q.divergence=$8(`engine provider replay produced an ambiguous request at position ${X}`),this.clearRequest(Z),v(Q.divergence);let Y=Q.forcedTerminal;if(Y!==void 0){if(Q.forcedTerminal=void 0,Y.fingerprint!==$)return Q.divergence=$8(`engine provider replay request sequence diverged at position ${X}`),this.clearRequest(Z),v(Q.divergence);return this.inlineTerminal(Q,X,Z,Y.error)}if(Q.providerCalls>=this.bounds.maxProviderCalls)return this.inlineTerminal(Q,X,Z,V4("provider-call"));let j=Q.entries.length+1;if(Q.replaySteps+j>this.bounds.maxReplaySteps)return this.inlineTerminal(Q,X,Z,V4("replay-step"));if(Q.replayBytes+Q.retainedBytes>this.bounds.maxReplayBytes)return this.inlineTerminal(Q,X,Z,V4("cumulative replay-byte"));return Q.pending={fingerprint:$,request:Z,index:X},E$("unavailable","engine provider request is pending asynchronous execution")}async run($,Z,Q){if(this.state!==void 0)return E$("failed_precondition","engine provider replay is non-reentrant");let X=Hj(this.bounds);if(!K(X))return X;let z={entries:[],index:0,providerCalls:0,retainedBytes:0,replaySteps:0,replayBytes:0};this.state=z;let Y;try{let j;try{j=$()}catch{return E$("internal","transactional read open failed")}if(!K(j))return j;Y=j.ok;for(;;){z.index=0,z.pending=void 0,z.inlineTerminal=void 0,z.sealCurrentAttempt=void 0,z.divergence=void 0;let W=Y.attempt();if(!K(W))return W;let V=W.ok;z.sealCurrentAttempt=()=>V.seal();let q;try{q=Z(V.target)}catch{z.sealCurrentAttempt=void 0;let P=this.terminal(z);if(P!==void 0)q=v({...P.error});else if(z.forcedTerminal!==void 0)return V.close(),E$("data_loss","engine provider replay did not consume its reserved forced terminal");else return V.close(),E$("internal","engine provider read threw during bounded replay")}finally{z.sealCurrentAttempt=void 0}if(z.divergence!==void 0)return V.close(),v(z.divergence);let B=this.pending(z);if(B===void 0){if(z.forcedTerminal!==void 0)return V.close(),E$("data_loss","engine provider replay did not consume its reserved forced terminal");let P=this.terminal(z),F=P===void 0?z.entries.length:z.entries.length+1;if(z.index!==F)return V.close(),E$("data_loss","engine provider replay consumed a different request count");let A=V.commit();if(V.close(),!K(A))return A;return P===void 0?q:v({...P.error})}if(B.index!==z.entries.length)return V.close(),E$("data_loss","engine provider replay pending index lost sequence authority");V.close(),z.providerCalls+=1;let G;try{G=await Q(B.request)}catch{G=v(W_("engine provider talon rejected before returning a checked result"))}finally{this.clearRequest(B.request),z.pending=void 0}let J;try{J=this.capture(G)}catch{return E$("data_loss","engine provider result snapshot capture failed")}if(!K(J))return J;let U=J.ok;if(!Number.isSafeInteger(U.byteLength)||U.byteLength<0)return U.clear(),E$("data_loss","engine provider replay snapshot reported an invalid byte length");let L=z.retainedBytes+U.byteLength,D=z.replayBytes+z.retainedBytes+U.byteLength;if(L>this.bounds.maxRetainedBytes||D>this.bounds.maxReplayBytes)U.clear(),z.forcedTerminal={fingerprint:B.fingerprint,error:L>this.bounds.maxRetainedBytes?V4("retained-byte"):V4("cumulative replay-byte")};else z.entries.push({fingerprint:B.fingerprint,snapshot:U}),z.retainedBytes=L;await Bun.sleep(0)}}finally{if(z.pending!==void 0)this.clearRequest(z.pending.request);z.pending=void 0,z.sealCurrentAttempt=void 0;for(let j of z.entries)j.snapshot.clear();z.entries.length=0,z.forcedTerminal=void 0,Y?.close(),this.state=void 0}}}f();_9();import{createHash as I2}from"crypto";import{fileURLToPath as IS}from"url";import{homedir as yS}from"os";import{dirname as ES,join as $V,resolve as UD}from"path";import{existsSync as ZV,readdirSync as vS}from"fs";var iG=new Map;function sG($){if(iG.has($.name))throw Error(`registerCommand: '${$.name}' is already registered \u2014 a second registration would silently shadow the first; route inside the owning command instead`);iG.set($.name,$)}function P$($,Z){if($.json)$.io.out(JSON.stringify({err:Z},null,2));else $.io.errOut(`zortex: ${Z.code} [${Z.layer}/${Z.retryability}] \u2014 ${Z.message}`);return 1}function oG($,Z,Q){if($.json)$.io.out(JSON.stringify(Q,null,2));else for(let X of Z)$.io.out(X);return 0}function aG($,Z){let Q=$.indexOf(Z);if(Q<0)return;let X=$[Q+1];return $.splice(Q,X===void 0?1:2),X}import{access as K_,readFile as q_}from"fs/promises";import{join as H_}from"path";var B_=1000;async function J_($){try{return await K_($),!0}catch(Z){let Q=Z.code;if(Q==="ENOENT"||Q==="ENOTDIR")return!1;throw Z}}async function G_($){let Z=H_($,".zortex","kernel","falcon.lock"),Q;try{Q=await q_(Z,"utf8")}catch(X){return{unreadable:`${Z}: ${X instanceof Error?X.message:String(X)}`}}try{let X=JSON.parse(Q);return typeof X.pid==="number"?{pid:X.pid}:{unreadable:`${Z} carries no numeric 'pid' field`}}catch(X){return{unreadable:`${Z} is not JSON: ${X instanceof Error?X.message:String(X)}`}}}async function rG($){let Z=await G_($);return"pid"in Z?Z.pid:void 0}async function tG($,Z={}){let Q=NY($);if(!await J_(Q))return{kind:"absent",socketPath:Q,why:`no falcon socket at '${Q}' \u2014 no engine is resident on this vault`};let X=Z.budgetMs??B_,z=Symbol("residency-probe-timeout"),Y=(Z.connect??hQ.connect)(Q),j=await Promise.race([Y,new Promise((V)=>{setTimeout(()=>V(z),X).unref?.()})]);if(j===z){Y.then((q)=>{if("ok"in q)q.ok.disconnect()}).catch(()=>{return});let V=await rG($);return{kind:"resident",socketPath:Q,...V===void 0?{}:{falconLockPid:V},why:`the falcon socket at '${Q}' did not answer within ${X}ms \u2014 something holds it, and this composition does not guess otherwise (falcon.md \xA73.6b, "The probe's budget")`}}if(!("ok"in j))return{kind:"stale-socket",socketPath:Q,why:`the falcon socket file at '${Q}' exists but nothing answered (a stale file from an unclean exit) \u2014 no engine is resident`};j.ok.disconnect();let W=await rG($);return{kind:"resident",socketPath:Q,...W!==void 0?{falconLockPid:W}:{},why:`an engine is resident on this vault \u2014 '${Q}' answered`}}var U_="an engine is resident on this vault";function eG($){let Z=$.posture.falconLockPid===void 0?"and .zortex/kernel/falcon.lock is held by it":`and .zortex/kernel/falcon.lock is held by pid ${$.posture.falconLockPid}`;return{code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`${U_} \u2014 '${$.posture.socketPath}' answered, ${Z}. `+"A CLI composition does not acquire falcon + log while an engine is resident (falcon.md \xA73.6b, ask 15), "+`so '${$.verb}' did not run: ${$.didNotHappen}. ${$.whyNoRoute} `+"To run it now, un-swap the engine to the one-shot install shape \u2014 'zortex daemon rollback' prints the exact bootout/bootstrap pair."}}var $U="There is no delegated route for a sync: falcon.md \xA73.5's CLI surface is read-only inspection with no enqueue or expedite method, and under residency this source is the engine's own 'sync-due' schedule (indrad.md 'Two engine modes').";var G9=!0,YV=Object.freeze({candidateLimit:20,contentLimit:10,contentBytesLimit:1048576}),y2=Symbol("registry-validated-provider-read");function UZ($,Z){let Q=$[y2];if(Q?.mode!=="transactional-replay")throw Error(`${Z}: transactional replay bounds did not pass through registry validation`);return Q.bounds}var f2="v3",CD=new RegExp(`^${f2}:[0-9A-HJKMNP-TV-Z]{26}$`);function E2($){if($.mode==="native-async")return Object.freeze({mode:"native-async"});return Object.freeze({mode:"transactional-replay",bounds:Object.freeze({maxProviderCalls:$.bounds.maxProviderCalls,maxRetainedBytes:$.bounds.maxRetainedBytes,maxReplaySteps:$.bounds.maxReplaySteps,maxReplayBytes:$.bounds.maxReplayBytes})})}var LZ=Object.freeze({maxProviderCalls:4096,maxRetainedBytes:67108864,maxReplaySteps:8500000,maxReplayBytes:536870912});function FD($){if(typeof $!=="object"||$===null||!("mode"in $))return C("failed_precondition","engine provider-read capability declaration is missing","non-retryable");let Z=$;if(Z.mode==="native-async")return H(E2({mode:"native-async"}));if(Z.mode!=="transactional-replay"||typeof Z.bounds!=="object"||Z.bounds===null)return C("failed_precondition","engine provider-read capability declaration is partial or unsupported","non-retryable");let Q=Hj(Z.bounds);if(!K(Q))return Q;return H(E2({mode:"transactional-replay",bounds:Q.ok}))}var q8=new Map,t;async function bS(){if(t!==void 0)return;t={activitywatch:await Promise.resolve().then(() => (JU(),BU)),appleNotes:await Promise.resolve().then(() => (CU(),PU)),chromeHistory:await Promise.resolve().then(() => (cU(),lU)),computerFiles:await Promise.resolve().then(() => (YL(),zL)),github:await Promise.resolve().then(() => (ML(),DL)),imessage:await Promise.resolve().then(() => (EL(),yL)),notion:await Promise.resolve().then(() => (uL(),hL)),posthog:await Promise.resolve().then(() => (qj(),uG)),wechat:await Promise.resolve().then(() => (WD(),jD)),whatsapp:await Promise.resolve().then(() => (GD(),JD))},wS(),cS(),nS(),iS()}function D0($){if($.credentialMode==="fixture")throw Error(`production sync source '${$.name}' cannot select fixture credential mode (I-7)`);q8.set($.name,$)}function LD(){return[...q8.keys()].sort()}function gS($){return $.autopilot??{mode:"blocked",reason:"no Autopilot profile declared for this registered connector"}}function fS($){let Z=q8.get($);return Z===void 0?void 0:gS(Z)}function ND($){return fS($)?.mode==="starter"}function jV($,Z,Q){let X=q8.get($);if(X===void 0)return C("not_found",`no registered sync source '${$}'`,"non-retryable");if(X.credentialMode!=="talon"||X.engine===void 0)return C("failed_precondition",`${$}: registered source has no resident-engine composition`,"non-retryable");let z=X.engine,Y={};if(Z!==void 0){if(Z.kind==="starter"&&Z.value!==f2&&!CD.test(Z.value))return C("invalid_argument",`${$}: unsupported starter selector version '${Z.value}'`,"non-retryable");let B=z.selectors?.[Z.kind];if(B===void 0)return C("invalid_argument",`${$}: unsupported engine selector '${Z.kind}'`,"non-retryable");Y={...B(Z.value),...Z.kind==="starter"?{starterSelector:Z.value}:{}}}let j=FD(z.providerRead);if(!K(j))return j;let W=E2(j.ok),V=E2(j.ok);Y=Object.freeze({...Y,[y2]:W});let q=z.policy(Q,Y);if(!K(q))return q;return H({manifest:z.manifest,scopes:[...X.scopes],policy:q.ok,allowedDomains:[...q.ok.hosts],refreshAsync:z.refreshAsync,probeAsync:z.probeAsync,providerRead:V,buildOptions:Y,requirement:z.requirement})}function u4($,Z){let Q=q8.get($);if(Q===void 0)return C("invalid_argument",`no registered sync source '${$}'`,"non-retryable");if(Q.credentialMode==="talon"&&Z.credentialTalon===void 0)return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`${$}: ${tY}`});let X=Z[y2],z=Z;if(Q.engine!==void 0){let Y=FD(X??Q.engine.providerRead);if(!K(Y))return Y;X=Y.ok,z={...Z,[y2]:X}}try{let Y=Q.build(z),j="connector"in Y?Y:{connector:Y};if(Q.engine!==void 0){let W=j.connector;if(X?.mode==="transactional-replay"){if(j.runEngineRead===void 0)return C("failed_precondition",`${$}: resident-engine connector has no asynchronous provider-read capability (FM-23)`,"non-retryable");let V=j.runEngineRead;j.connector={...W,discoverAsync:(q)=>V((B)=>B.discover(q)),pullAsync:(q,B)=>V((G)=>G.pull(q,B))}}else if(W.discoverAsync===void 0||W.pullAsync===void 0)return C("failed_precondition",`${$}: native-async engine registration has no native asynchronous provider-read capability (FM-23)`,"non-retryable")}return H(j)}catch(Y){return C("failed_precondition",`${$}: sync-source builder failed: ${Y instanceof Error?Y.message:String(Y)}`,"non-retryable")}}var eW="zortex-broker-inject-v1",AD="github code-content cloning is blocked until git fetch/clone runs through a falcon-owned, host-pinned talon without machine credential-helper access (WO-SEC-I7-SYNC-001)";class V8{source;talon;replay;constructor($,Z,Q){this.source=$;this.talon=Q,this.replay=new Bj(Z,{clearRequest:(X)=>X.body?.fill(0)})}bind($){if($.grant.source!==this.source)return C("permission_denied",`${this.source}: credential talon is bound to '${$.grant.source}' (I-7 source mismatch)`,"non-retryable");return this.talon=$,H(void 0)}authHeaders($){if(this.talon?.unavailable!==void 0)return v(this.talon.unavailable);let Z=this.checkGrant($);if(!K(Z))return Z;return H({})}authHeader($){if(this.talon?.unavailable!==void 0)return v(this.talon.unavailable);if($!==void 0){let Z=this.checkGrant($);if(!K(Z))return Z}return H(eW)}execute($){let Z=this.prepare($);if(!K(Z))return Z;let Q=this.replay.intercept(this.fingerprint(Z.ok),Z.ok);if(Q!==void 0)return Q;let X=this.talon;if(X===void 0)return this.missingTalon();return this.toBridgeResponse(X.execute(X.grant,Z.ok))}runEngineRead($,Z){return this.replay.run(()=>$.open(),Z,(Q)=>this.executePreparedAsync(Q))}prepare($){let Z=this.talon;if(Z===void 0)return this.missingTalon();if(Z.unavailable!==void 0)return v(Z.unavailable);let Q={};for(let[X,z]of Object.entries($.headers)){if(Z6.has(X.toLowerCase())){if(z!==eW)return C("invalid_argument",`${this.source}: connector supplied credential header '${X}' instead of the broker marker (I-7 incident)`,"non-retryable");continue}if(z.includes(eW))return C("invalid_argument",`${this.source}: broker marker appeared outside the compatibility auth field (I-7)`,"non-retryable");Q[X]=z}return H({method:$.method,url:$.url,headers:Q,...$.capabilityRefs!==void 0?{capabilityRefs:$.capabilityRefs}:{},...$.body!==void 0?{body:new TextEncoder().encode($.body)}:{}})}async executePreparedAsync($){let Z=this.talon;if(Z===void 0)return this.missingTalon();if(Z.unavailable!==void 0)return v(Z.unavailable);if(Z.executeAsync===void 0)return C("failed_precondition",`${this.source}: resident-engine credential talon has no asynchronous execution capability (FM-23)`,"non-retryable");return this.toBridgeResponse(await Z.executeAsync(Z.grant,$))}toBridgeResponse($){if(!K($))return $;return H({status:$.ok.status,headers:$.ok.headers,body:new TextDecoder().decode($.ok.body)})}fingerprint($){let Z=Object.entries($.headers).sort(([z],[Y])=>z.localeCompare(Y)),Q=($.capabilityRefs??[]).map((z)=>({kind:z.kind,id:z.id})),X=$.body===void 0?"":I2("sha256").update($.body).digest("hex");return I2("sha256").update(JSON.stringify({method:$.method,url:$.url,headers:Z,capabilityRefs:Q,bodyHash:X,timeoutMs:$.timeoutMs??null})).digest("hex")}missingTalon(){return C("unauthenticated",`${this.source}: no credential talon session is bound \u2014 ${mS(this.source)}; auth failure is AUTH_BLOCKED, never empty`,"non-retryable")}checkGrant($){if($.source!==this.source)return C("permission_denied",`${this.source}: connector presented a grant for '${$.source}' (I-7 source mismatch)`,"non-retryable");if(this.talon!==void 0&&$.id!==this.talon.grant.id)return C("permission_denied",`${this.source}: connector presented a grant outside the bound credential session (I-7; presented=${$.id.slice(-6)}, bound=${this.talon.grant.id.slice(-6)})`,"non-retryable");return H(void 0)}}function k4($){if(K($))return{ok:!0,...$.ok};if(r($))return{ok:!1,error:$.err.message,structuredError:$.err};return{ok:!1,error:`credential talon returned empty (${$.empty.how})`}}function kS($){let Z=()=>C("failed_precondition",AD,"non-retryable");return{...$,discover:()=>Z(),pull:()=>Z()}}function _D($,Z,Q,X,z){let Y=nG({initialState:Z,cloneState:Q,clearState:X,build:z});if(!K(Y))throw Error(`${$}: transactional connector owner failed: ${h4(Y)}`);return Y.ok}function w4($,Z){return _D($,null,()=>null,()=>{return},Z)}function DZ($,Z){return{connector:Z.canonical,bindCredentialTalon:(Q)=>$.bind(Q),runEngineRead:(Q)=>$.runEngineRead(Z,Q),cleanup:()=>Z.close()}}function wS(){D0({name:t.appleNotes.APPLE_NOTES_MANIFEST.source,scopes:["notes.read"],credentialMode:"local",build:()=>t.appleNotes.createAppleNotesConnector(new t.appleNotes.OsascriptNotesSource)}),D0({name:"computer-files",scopes:["files.read"],credentialMode:"local",autopilot:{mode:"needs-user-selection",reason:"computer-files requires explicit user-selected roots"},build:($)=>t.computerFiles.createComputerFilesConnector(new t.computerFiles.WalkFilesSource({...$.roots!==void 0?{roots:$.roots}:{}}))}),D0({name:"chrome-history",scopes:["history.read"],credentialMode:"local",autopilot:{mode:"needs-user-selection",reason:"chrome-history needs a bounded Windows selection profile before Autopilot may read it"},build:()=>t.chromeHistory.createChromeHistoryConnector(new t.chromeHistory.ChromeInstallSource({}))}),D0({name:"activitywatch",scopes:["samples.read"],credentialMode:"local",build:()=>{let $=t.activitywatch.HttpAwSource.create({});if(!K($))throw Error(`activitywatch source: ${JSON.stringify($)}`);return t.activitywatch.createActivityWatchConnector($.ok)}}),D0({name:t.imessage.IMESSAGE_MANIFEST.source,scopes:["messages.read"],credentialMode:"local",build:()=>t.imessage.createImessageConnector(new t.imessage.ChatDbMessagesSource)}),D0({name:t.github.GITHUB_MANIFEST.source,scopes:t.github.GITHUB_MANIFEST.auth.scopes,credentialMode:"talon",autopilot:{mode:"blocked",reason:AD},engine:{manifest:t.github.GITHUB_MANIFEST,policy:()=>K8(t.github.GITHUB_MANIFEST),refreshAsync:v2,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered remote corpus through indrad custody"},build:($)=>{let Z=new V8(t.github.GITHUB_MANIFEST.source,UZ($,t.github.GITHUB_MANIFEST.source),$.credentialTalon),Q=w4(t.github.GITHUB_MANIFEST.source,()=>{let X=t.github.HttpGithubSource.create({transport:(z,Y)=>k4(Z.execute({method:"GET",url:z,headers:Y})),authHeaders:()=>({})});if(!K(X))return X;return H(kS(t.github.createGithubConnector(X.ok)))});return DZ(Z,Q)}})}function m4($,Z){let Q=E6($??process.cwd(),"local",Z);if(!K(Q))return Q;return H(Q.ok?.secretCells.includes("apiKey")===!0)}function h4($){if("err"in $)return $.err.message;if("empty"in $)return`unexpected empty (${$.empty.how})`;return"unexpected ok result"}function mS($){if($==="microsoft"||$==="google")return"Autopilot must open its browser enrollment itself, never ask the user to run a command";return`${$} has no released automatic authorization route and must enter D29 fabrication`}function QV($){let Z=$??process.cwd(),Q=E6(Z,t.posthog.POSTHOG_MANIFEST.auth.provider,t.posthog.POSTHOG_MANIFEST.source);if(!K(Q))throw Error(`posthog auth metadata: ${h4(Q)}`);if(Q.ok===null)return{};return lG(Q.ok.accountId)??{}}function hS($,Z){return{code:"unavailable",layer:"connector",retryability:"transient",message:`${$}: WAN transport failed (${Z}) \u2014 NEVER an empty success (FM-21)`}}function XV($){let Z=Bun.spawnSync($,{stdout:"pipe",stderr:"pipe"});return`${Z.stdout.toString()}
541
+ ${Z.stderr.toString()}`.trim()}function uS($){let Z=[],Q=$??process.cwd(),X=$V(Q,"packages","connectors","wechat",".bin","chatlog");Z.push(ZV(X)?"repo-vendored chatlog binary is built":"repo-vendored chatlog binary is not built");let z=m4($,"wechat-data-key"),Y=m4($,"wechat-img-key");Z.push(!K(z)?`WeChat data key custody unreadable: ${h4(z)}`:!z.ok?"no WeChat data key in auth custody":"WeChat data key is present in auth custody"),Z.push(!K(Y)?`WeChat image key custody unreadable: ${h4(Y)}`:!Y.ok?"no WeChat image key in auth custody":"WeChat image key is present in auth custody");let j=XV(["csrutil","status"]);if(/enabled/i.test(j))Z.push("macOS SIP is enabled, so WeChat v4 SQLCipher key extraction is expected to fail unless SIP is disabled or a data key is supplied out-of-band");else if(/disabled/i.test(j))Z.push("macOS SIP is disabled");else if(j!=="")Z.push(`macOS SIP status unclear: ${j.replace(/\s+/g," ")}`);let W=XV(["pgrep","-fl","WeChat"]);Z.push(W===""?"WeChat process not detected":"WeChat process detected");let V=$V(yS(),"Library","Containers","com.tencent.xinWeChat","Data","Documents","xwechat_files");if(ZV(V)){let q=vS(V).filter((B)=>B.startsWith("wxid_")).length;Z.push(`${q} local WeChat account data dir(s) detected`)}else Z.push("local WeChat xwechat_files directory not found");return` -- local diagnosis: ${Z.join("; ")}`}function pS($){let Z=m4($,"wechat-data-key");if(!K(Z))return`WeChat data key custody unreadable: ${h4(Z)}`;if(Z.ok)return"AUTH_BLOCKED: a WeChat data key exists in auth custody, but falcon secret-fd injection for the chatlog subprocess is not fabricated; I-7 forbids copying it into argv or environment";let Q=XV(["csrutil","status"]);if(/enabled/i.test(Q))return"AUTH_BLOCKED: no WeChat data key in auth custody while macOS SIP is enabled; enroll the key into auth custody, then start chatlog through the not-yet-fabricated falcon secret-fd subprocess capability";return null}function lS($){let Z=!1,Q="",X,z=()=>{if(Z)return;if(Z=!0,q6(`${t.wechat.WECHAT_CHATLOG_DEFAULT_BASE}/api/v1/session`,{}).ok){Q="chatlog service was already listening";return}let j=m4($,"wechat-data-key"),W=m4($,"wechat-img-key");if(!K(j)||!K(W)){X={code:"failed_precondition",layer:"auth",retryability:"retry-at-higher-level",message:"chatlog credential metadata could not be read from auth custody"},Q=X.message;return}if(j.ok||W.ok){X={code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"stored WeChat keys require a falcon secret-fd subprocess capability; I-7 forbids argv/environment injection (WO-SEC-I7-SYNC-001)"},Q=X.message;return}X={code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"chatlog auto-decryption may acquire credential material, so the CLI cannot spawn it; a falcon-owned secret-fd subprocess capability is required (WO-SEC-I7-SYNC-001)"},Q=X.message};return{transport:(Y)=>{let j=q6(Y,{});if(j.ok)return j;if(z(),X!==void 0)return{ok:!1,error:X.message,code:X.code,retryability:X.retryability};let W=pS($);return{ok:!1,error:`${j.error}${Q!==""?` -- start gate: ${Q}`:""}${uS($)}${W!==null?` -- auth repair: ${W}`:""}`,...W!==null?{code:"unauthenticated",retryability:"non-retryable"}:{}}},cleanup:()=>{}}}function cS(){D0({name:t.wechat.WECHAT_MANIFEST.source,scopes:t.wechat.WECHAT_MANIFEST.auth.scopes,credentialMode:"local",autopilot:{mode:"blocked",reason:"WeChat is deliberately excluded from this Windows release path"},build:($)=>{let Z=lS($.appRoot),Q=t.wechat.HttpChatlogSource.create({transport:(X)=>{let z=Z.transport(X);return z.ok?{ok:!0,status:z.status,body:z.body}:{ok:!1,error:z.error,..."code"in z?{code:z.code,retryability:z.retryability}:{}}}});if(!K(Q))throw Error(`wechat source: ${JSON.stringify(Q)}`);return{connector:t.wechat.createWechatConnector(Q.ok),cleanup:Z.cleanup}}})}D0({name:V0.source,scopes:V0.auth.scopes,credentialMode:"talon",autopilot:{mode:"starter",context:"queryable",starter:YV},connection:{kind:"oauth-browser",aliases:["Gmail","Google Mail"],enrollment:["auth","enroll","google"]},engine:{manifest:V0,selectors:{"gmail-query":($)=>({gmailQuery:$}),starter:()=>({starter:!0})},policy:()=>K8(V0),refreshAsync:TD,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered remote corpus through indrad custody"},build:($)=>{let Z=new V8(V0.source,UZ($,V0.source),$.credentialTalon),Q=w4(V0.source,()=>H(hY($.starter?new M6(r8.create({transport:(X,z)=>k4(Z.execute({method:"GET",url:X,headers:z})),authHeaders:(X)=>Z.authHeaders(X),pageSize:D6,includeAttachments:!1,...$.gmailQuery!==void 0?{query:$.gmailQuery}:{}})):r8.create({transport:(X,z)=>k4(Z.execute({method:"GET",url:X,headers:z})),authHeaders:(X)=>Z.authHeaders(X),...$.gmailQuery!==void 0?{query:$.gmailQuery}:{}}))));return DZ(Z,Q)}});async function TD($){let Z;try{Z=cG($)}catch{return H({kind:"network"})}let Q=await iQ(Z.url,Z.headers,{method:"POST",body:Z.body,maxTimeSec:20});if(!Q.ok)return H({kind:"network"});let X;try{X=JSON.parse(Q.body)}catch{return H({kind:"network"})}if(Q.status===429)return H({kind:"throttled"});if(Q.status===400&&X.error==="invalid_grant")return H({kind:"invalid_grant"});let z=X.access_token;if(Q.status<200||Q.status>=300||typeof z!=="string"||z==="")return H({kind:"network"});let Y=typeof X.refresh_token==="string"?X.refresh_token:void 0,j=typeof X.expires_in==="number"?X.expires_in:void 0;return H({kind:"ok",accessToken:z,...Y!==void 0?{refreshToken:Y}:{},...j!==void 0?{expiresInSec:j}:{}})}function dS(){return H({kind:"invalid_grant"})}async function v2(){return dS()}async function MZ(){return H({kind:"network"})}D0({name:q0.source,scopes:q0.auth.scopes,credentialMode:"talon",autopilot:{mode:"starter",context:"queryable",starter:YV},connection:{kind:"oauth-browser",aliases:["Google Drive","Drive"],enrollment:["auth","enroll","google"]},engine:{manifest:q0,selectors:{"drive-query":($)=>({driveQuery:$}),starter:()=>({starter:!0})},policy:($,Z)=>{let Q=K8(q0);if(!K(Q)||Z?.starter!==!0)return Q;let{responseCapabilities:X,...z}=Q.ok;return H(z)},refreshAsync:TD,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered remote corpus through indrad custody"},build:($)=>{let Z=new V8(q0.source,UZ($,q0.source),$.credentialTalon),Q=_D(q0.source,{censusWatermark:null},(X)=>({censusWatermark:X.censusWatermark===null?null:{...X.censusWatermark}}),(X)=>{X.censusWatermark=null},(X)=>{let z=$4.create({transport:(Y)=>k4(Z.execute({method:"GET",url:Y.url,headers:Y.headers,...Y.capabilityRefs!==void 0?{capabilityRefs:Y.capabilityRefs}:{}})),authHeader:(Y)=>Z.authHeader(Y),...$.driveQuery!==void 0?{query:$.driveQuery}:{},...$.starter?{orderBy:"modifiedTime desc"}:{},...$.starter?{starter:!0}:{}});if(!K(z))return z;return H(dY($.starter?new O6(z.ok):z.ok,{runtimeState:X,...$.starter?{starter:!0}:{}}))});return DZ(Z,Q)}});function nS(){D0({name:t.posthog.POSTHOG_MANIFEST.source,scopes:t.posthog.POSTHOG_MANIFEST.auth.scopes,credentialMode:"talon",autopilot:{mode:"blocked",reason:"posthog has no released automatic authorization route; connect requests enter D29 fabrication"},engine:{manifest:t.posthog.POSTHOG_MANIFEST,selectors:{starter:()=>({starter:!0})},policy:($)=>{let Z=QV($).baseUrl;return K8(t.posthog.POSTHOG_MANIFEST,Z===void 0?void 0:new URL(Z).host)},refreshAsync:v2,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered remote corpus through indrad custody"},build:($)=>{let Z=new V8(t.posthog.POSTHOG_MANIFEST.source,UZ($,t.posthog.POSTHOG_MANIFEST.source),$.credentialTalon),Q=QV($.appRoot),X=w4(t.posthog.POSTHOG_MANIFEST.source,()=>{let z=t.posthog.HttpPosthogSource.create({...Q,transport:(Y)=>{let j=Z.execute({method:"GET",url:Y.url,headers:Y.headers});if(K(j))return{ok:!0,status:j.ok.status,body:j.ok.body};if(r(j))return{ok:!1,error:j.err};return{ok:!1,error:hS("posthog",`credential talon returned empty (${j.empty.how})`)}},authHeader:()=>Z.authHeader()});if(!K(z))return z;return H(t.posthog.createPosthogConnector($.starter?new t.posthog.StarterPosthogSource(z.ok):z.ok))});return DZ(Z,X)}}),D0({name:t.notion.NOTION_MANIFEST.source,scopes:t.notion.NOTION_MANIFEST.auth.scopes,credentialMode:"talon",autopilot:{mode:"blocked",reason:"notion has no released automatic authorization route; connect requests enter D29 fabrication"},engine:{manifest:t.notion.NOTION_MANIFEST,selectors:{starter:()=>({starter:!0})},policy:()=>K8(t.notion.NOTION_MANIFEST),refreshAsync:v2,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered remote corpus through indrad custody"},build:($)=>{let Z=new V8(t.notion.NOTION_MANIFEST.source,UZ($,t.notion.NOTION_MANIFEST.source),$.credentialTalon),Q=w4(t.notion.NOTION_MANIFEST.source,()=>{let X=t.notion.HttpNotionSource.create({transport:(z,Y)=>k4(Z.execute({method:Y.method,url:z,headers:Y.headers,...Y.body!==void 0?{body:Y.body}:{}})),authHeaders:(z)=>Z.authHeaders(z),...$.starter?{pageSize:t.notion.NOTION_STARTER_PAGE_LIMIT}:{}});return H(t.notion.createNotionConnector($.starter?new t.notion.StarterNotionSource(X):X))});return DZ(Z,Q)}})}D0({name:H0.source,scopes:H0.auth.scopes,credentialMode:"talon",autopilot:{mode:"starter",context:"queryable",starter:YV},connection:{kind:"oauth-browser",aliases:["Outlook","Microsoft Outlook","Microsoft 365 Mail"],enrollment:["auth","enroll","microsoft"]},engine:{manifest:H0,selectors:{starter:()=>({starter:!0})},policy:()=>K8(H0),refreshAsync:v2,probeAsync:MZ,providerRead:{mode:"transactional-replay",bounds:LZ},requirement:"Synchronize the registered Microsoft Graph Starter through indrad custody"},build:($)=>{let Z=new V8(H0.source,UZ($,H0.source),$.credentialTalon),Q=w4(H0.source,()=>{let X=z4.create({transport:(z)=>Z.execute({method:z.method,url:z.url,headers:z.headers}),auth:(z)=>Z.authHeader(z),...$.starter?{pageSize:I6}:{}});return H(aY($.starter?new y6(X):X))});return DZ(Z,Q)}});function iS(){D0({name:t.whatsapp.WHATSAPP_EXPORT_MANIFEST.source,scopes:t.whatsapp.WHATSAPP_EXPORT_MANIFEST.auth.scopes,credentialMode:"local",autopilot:{mode:"blocked",reason:"whatsapp is deferred from this Windows Preview pending a dedicated safe connector"},connection:{kind:"blocked",aliases:["WhatsApp","Whats App"],reason:"WhatsApp is deferred from this Windows Preview"},build:($)=>t.whatsapp.createWhatsappExportConnector(new t.whatsapp.FileWhatsappExportSource({file:$.whatsappExportFile??""}))})}var sS=3600000,DD="local";function SD($){let Z=I2("sha256").update($).digest();return V$({now:()=>0,random:(Q)=>Uint8Array.from(Z.subarray(0,Q))})()}function RD($,Z,Q,X){return{id:$,source:Z,account:Q,scopes:X,expiresAt:new Date(Date.now()+sS).toISOString()}}function zV($,Z){return RD(SD(`zortex:sync-grant:v1:${$.source}\x00${$.auth.provider}\x00${$.auth.method}\x00${DD}`),$.source,DD,Z)}function oS($,Z,Q){let X,z;if(!G9&&$.source===t.computerFiles.COMPUTER_FILES_MANIFEST.source&&(Q.roots?.length??0)>0)X="roots",z=[...new Set(Q.roots.map((j)=>UD(j)))].sort().join("\x00");else if(!G9&&$.source===t.whatsapp.WHATSAPP_EXPORT_MANIFEST.source&&Q.whatsappExportFile!==void 0)X="whatsapp-export",z=UD(Q.whatsappExportFile);else if($.source===V0.source&&Q.gmailQuery!==void 0)X="gmail-query",z=Q.gmailQuery;else if($.source===q0.source&&Q.driveQuery!==void 0)X="drive-query",z=Q.driveQuery;else if(ND($.source)&&Q.starter===!0)X="starter",z=Q.starterSelector??f2;if(X===void 0||z===void 0)return Z;let Y=I2("sha256").update(z).digest("hex");return{...Z,id:SD(`zortex:bounded-sync-grant:v1\x00${Z.id}\x00${$.source}\x00${X}\x00${Y}`)}}function aS($,Z,Q){if($.auth.method==="local-permission"||$.auth.method==="none")return H(zV($,Z));let X=E6(Q,$.auth.provider,$.source);if(!K(X))return X;if(X.ok===null)return H(zV($,Z));if(!q$(X.ok.grantId))return C("invalid_argument",`${$.source}: auth vault grant id '${X.ok.grantId}' is not a valid ULID \u2014 cannot key sync-state or connector origins to it`,"non-retryable");return H(RD(X.ok.grantId,$.source,X.ok.accountLabel,X.ok.scopes))}var rS={perform:($)=>{let Z=q6($.url,$.headers,{method:$.method,...$.body!==void 0?{body:new TextDecoder().decode($.body)}:{},maxTimeSec:Math.max(1,Math.ceil($.timeoutMs/1000))});if(!Z.ok)return v({code:"unavailable",layer:"upstream",retryability:"transient",message:`broker upstream transport failed: ${Z.error}`});return H({status:Z.status,headers:Z.headers,body:new TextEncoder().encode(Z.body)})}};function tS($,Z){let Q=zV($,Z),X={code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:$.auth.provider==="google"?`${$.source}: missing google credential in auth custody; Autopilot must start its browser enrollment itself, never ask the user to run or paste a credential; auth failure is AUTH_BLOCKED, never empty`:`${$.source}: missing ${$.auth.provider} credential in auth custody; this source has no released automatic route and must enter D29 fabrication rather than request a user credential; auth failure is AUTH_BLOCKED, never empty`};return{grant:Q,unavailable:X,execute:()=>v(X),close:()=>H(void 0)}}function K8($,Z){if($.source===V0.source)return w5({provider:$.auth.provider,hosts:["gmail.googleapis.com"],ops:[{op:"mail.read",method:"GET",pathPrefix:"/gmail/v1/users/",scopes:[...$.auth.scopes]}]});if($.source===q0.source){let Q={method:"GET",pathPrefix:"/drive/v3/files/",header:"X-Goog-Drive-Resource-Keys",format:"id/slash/secret"};return w5({provider:$.auth.provider,hosts:["www.googleapis.com"],ops:[{op:"drive.read",method:"GET",pathPrefix:"/drive/v3/",scopes:[...$.auth.scopes]}],responseCapabilities:[{kind:tQ,response:{method:"GET",pathExact:"/drive/v3/files",requiredQuery:[{name:"fields",contains:["resourceKey","shortcutDetails(targetId,targetMimeType,targetResourceKey)"]}]},captures:[{rowsPath:["files"],idField:"id",secretField:"resourceKey",urlFields:["webViewLink"],secretQueryParam:"resourcekey"},{rowsPath:["files"],objectPath:["shortcutDetails"],idField:"targetId",secretField:"targetResourceKey"}],request:Q,maxEntries:2000},{kind:tQ,response:{method:"GET",pathExact:"/drive/v3/changes",requiredQuery:[{name:"fields",contains:["resourceKey","shortcutDetails(targetId,targetMimeType,targetResourceKey)"]}]},captures:[{rowsPath:["changes"],objectPath:["file"],idField:"id",secretField:"resourceKey",urlFields:["webViewLink"],secretQueryParam:"resourcekey"},{rowsPath:["changes"],objectPath:["file","shortcutDetails"],idField:"targetId",secretField:"targetResourceKey"}],request:Q,maxEntries:2000}]})}if($.source==="github")return w5({provider:$.auth.provider,hosts:["api.github.com"],ops:[{op:"user.read",method:"GET",pathPrefix:"/user",scopes:["read:user"]},{op:"repo.read",method:"GET",pathPrefix:"/repos/",scopes:["repo"]}]});if($.source===H0.source)return w5({provider:H0.auth.provider,hosts:["graph.microsoft.com"],ops:[{op:"graph.read",method:"GET",pathPrefix:"/v1.0/me",scopes:[...H0.auth.scopes]}]});if(!G9&&$.source===t.notion.NOTION_MANIFEST.source)return w5({provider:$.auth.provider,hosts:["api.notion.com"],ops:[{op:"user.read",method:"GET",pathPrefix:"/v1/users",scopes:[]},{op:"search",method:"POST",pathPrefix:"/v1/search",scopes:[]},{op:"block.read",method:"GET",pathPrefix:"/v1/blocks/",scopes:[]},{op:"database.read",method:"POST",pathPrefix:"/v1/databases/",scopes:[]},{op:"comment.read",method:"GET",pathPrefix:"/v1/comments",scopes:[]}]});if(!G9&&$.source===t.posthog.POSTHOG_MANIFEST.source){let Q=["us.posthog.com","eu.posthog.com"];if(Z!==void 0&&!Q.includes(Z))Q.push(Z);return w5({provider:$.auth.provider,hosts:Q,ops:[{op:"user.read",method:"GET",pathPrefix:"/api/users/@me/",scopes:["user:read"]},{op:"project.read",method:"GET",pathPrefix:"/api/projects/",scopes:$.auth.scopes.filter((X)=>X!=="user:read")}],profile:{botDetection:"n/a",registrationExposure:"personal API key captured through auth custody",tokenCliffs:{rotation:"none",notes:"personal API key; provider revocation is definitive"},dcr:!1,recommendedRung:"B",probeOp:"users.@me",retaliationRisk:"low"}})}return C("failed_precondition",`${$.source}: no manifest-bound read-only talon policy is registered; fail closed`,"non-retryable")}function eS($,Z,Q,X){if($.auth.method==="local-permission"||$.auth.method==="none")return H(null);let z;if(!G9&&$.source===t.posthog.POSTHOG_MANIFEST.source){let W=QV(Q).baseUrl;if(W!==void 0)try{z=new URL(W).host}catch{return C("invalid_argument",`${$.source}: stored base URL is not parseable; auth metadata repair required`,"non-retryable")}}let Y=K8($,z);if(!K(Y))return Y;let j=yG({appRoot:Q,log:X,source:$.source,provider:$.auth.provider,declaredScopes:[...Z],upstream:rS,policyOverrides:[Y.ok]});if(!K(j))return j;return H(j.ok??tS($,Z))}function b2($){try{return $.cleanup?.(),H(void 0)}catch(Z){return C("internal",`${$.connector.manifest.source}: sync-source cleanup failed: ${Z instanceof Error?Z.message:String(Z)}`,"non-retryable")}}function $R($,Z){return{part:$,error:{code:"internal",layer:"connector",retryability:"non-retryable",message:`${$} threw during cleanup: ${Z instanceof Error?Z.message:String(Z)}`}}}function g2($,Z){try{let Q=Z();if(Q===void 0||K(Q))return;if(r(Q))return{part:$,error:Q.err};return{part:$,error:{code:"failed_precondition",layer:"connector",retryability:"non-retryable",message:`${$} returned checked-empty from a mandatory cleanup operation`}}}catch(Q){return $R($,Q)}}function OD($){let Z=$.filter((X)=>X!==void 0);if(Z.length===0)return H(void 0);if(Z.length===1)return v(Z[0].error);let Q=Z[0];return v({code:Q.error.code,layer:Q.error.layer,retryability:Q.error.retryability,message:`multiple mandatory cleanup operations failed: ${Z.map(({part:X,error:z})=>`${X} [${z.layer}/${z.code}]`).join(", ")}`,cause:Q.error})}function x2($,Z){let Q=Z===null?void 0:g2("credential talon",()=>Z.close()),X=g2("sync source",()=>b2($));return OD([Q,X])}function MD($,Z){if(r($))return $.err;return{code:"failed_precondition",layer:"connector",retryability:"non-retryable",message:Z}}function g4($,Z,Q){if(K(Z))return $;let X=MD($,`${Q} returned checked-empty`),z=MD(Z,`${Q} cleanup returned checked-empty`);return v({...X,message:`${X.message}; mandatory cleanup also failed [${z.layer}/${z.code}]`,cause:z})}function ZR($,Z){let Q=$===void 0?void 0:g2("prepared sync source",()=>$.close()),X=g2("event log",()=>Z.close());return OD([Q,X])}function k2($,Z){let Q=q8.get($);if(Q===void 0)return C("invalid_argument",`no registered sync source '${$}'`,"non-retryable");let X=Z.built===void 0?u4($,Z):H(Z.built);if(!K(X))return X;let z=X.ok,Y=Q.credentialMode==="talon"?Z.credentialTalon!==void 0?H(Z.credentialTalon):eS(z.connector.manifest,Q.scopes,Z.appRoot,Z.log):H(null);if(!K(Y)){let q=b2(z);return g4(Y,q,`${$}: credential-talon preparation`)}let j=Y.ok;if(Q.credentialMode==="talon"&&j===null){let q=b2(z),B=C("failed_precondition",`${$}: talon registry entry resolved no credential talon (I-7)`,"non-retryable");return g4(B,q,`${$}: missing credential talon`)}if(j!==null){if(z.bindCredentialTalon===void 0){let B=x2(z,j),G=C("failed_precondition",`${$}: API connector registry entry has no credential-talon binding (I-7)`,"non-retryable");return g4(G,B,`${$}: missing credential-talon binding`)}let q;try{q=z.bindCredentialTalon(j)}catch(B){q=v({code:"internal",layer:"connector",retryability:"non-retryable",message:`${$}: credential-talon bind threw: ${B instanceof Error?B.message:String(B)}`})}if(!K(q)){let B=x2(z,j);return g4(q,B,`${$}: credential-talon bind`)}}let W=j===null?aS(z.connector.manifest,Q.scopes,Z.appRoot):H(j.grant);if(!K(W)){let q=x2(z,j);return g4(W,q,`${$}: sync grant preparation`)}let V=!1;return H({connector:z.connector,grant:oS(z.connector.manifest,W.ok,Z),scopes:[...Q.scopes],close:()=>{if(V)return H(void 0);return V=!0,x2(z,j)}})}function PD($){let Z=[`sync ${$.ran?"ran":"did not run"} \u2014 state=${$.state}${$.phase!==void 0?` phase=${$.phase}`:""} appended=${$.appended}`];for(let Q of $.coverage)Z.push(` ${Q.stream}: expected=${Q.expected===void 0?"no provider total":Q.expected} coveredLive=${Q.coveredLive} coveredDeleted=${Q.coveredDeleted}`);if($.verdicts!==void 0)for(let Q of $.verdicts)Z.push(` reconcile: ${JSON.stringify(Q)}`);return Z}if(!G9)await bS();sG({name:"sync",summary:"run one connector sync onto the vault (framework rails; census honesty per FM-18)",ownerDoc:"docs/uarch/connectors.md#24",run:QR});async function QR($,Z){let Q=$[0];if(Q===void 0){let P=LD().join(", ");return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`usage: zortex sync <source> \u2014 known sources: ${P}`})}$.shift();let X=$.filter((P)=>P==="--starter").length;if(X>1)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--starter may be supplied at most once"});if(X===1)$.splice($.indexOf("--starter"),1);let z=X===1,Y=f4($,"--starter-selector"),j=f4($,"--root"),W=f4($,"--file"),V=f4($,"--gmail-query"),q=f4($,"--drive-query");if($.length>0)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`usage: zortex sync <source> [--starter] [--root <path>] [--file <export.txt>] [--gmail-query <q>] [--drive-query <q>] \u2014 unexpected arg(s): ${$.join(" ")}`});let B=q8.get(Q);if(B===void 0){let P=LD().join(", ");return P$(Z,{code:"not_found",layer:"kernel",retryability:"non-retryable",message:`no connector '${Q}' on this seat \u2014 known sources: ${P}; new connectors fabricate through the Rung-6 skill (zortex connect, C-P8)`})}if(j.length>0&&Q!=="computer-files")return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`--root is only valid for computer-files; '${Q}' has its own source location/auth probe`});if(!G9&&W.length>0&&Q!==t.whatsapp.WHATSAPP_EXPORT_MANIFEST.source)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`--file is only valid for ${t.whatsapp.WHATSAPP_EXPORT_MANIFEST.source}; '${Q}' has its own source location/auth probe`});if(!G9&&Q===t.whatsapp.WHATSAPP_EXPORT_MANIFEST.source&&W.length!==1)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"whatsapp requires exactly one explicit --file <export.txt>; Zortex never searches for a chat export"});if(V.length>0&&Q!==V0.source)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`--gmail-query is only valid for gmail; '${Q}' has its own source location/auth probe`});if(q.length>0&&Q!==q0.source)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`--drive-query is only valid for google-drive; '${Q}' has its own source location/auth probe`});if(V.length>1)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--gmail-query may be supplied at most once"});if(q.length>1)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--drive-query may be supplied at most once"});if(Y.length>1)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--starter-selector may be supplied at most once"});if(Y.length===1&&!z)return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--starter-selector requires --starter"});if(Y[0]!==void 0&&!CD.test(Y[0]))return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--starter-selector must be an Autopilot-owned v3:<ULID> selector"});if(z&&!ND(Q))return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:`--starter is only valid for a registered bounded starter source; '${Q}' has no bounded remote starter profile`});if(z&&(j.length>0||V.length>0||q.length>0))return P$(Z,{code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"--starter chooses its own bounded source selector and cannot be combined with --root, --gmail-query, or --drive-query"});{let P=await tG(Z.appRoot);if(P.kind==="resident")return P$(Z,eG({verb:`zortex sync ${Q}`,posture:P,didNotHappen:"nothing was synced, no auth custody was opened and no engine child was spawned",whyNoRoute:$U}))}if(B.engine!==void 0){let P=process.argv[1]===void 0?void 0:$V(ES(process.argv[1]),"indrad-main.js"),F=P!==void 0&&ZV(P)?P:IS(new URL("../../../indrad/src/main.ts",import.meta.url)),A=z?["--selector-kind","starter","--selector-value",Y[0]??f2]:q[0]!==void 0?["--selector-kind","drive-query","--selector-value",q[0]]:V[0]!==void 0?["--selector-kind","gmail-query","--selector-value",V[0]]:[],N=[process.execPath,F,"--app-root",Z.appRoot,"--events-dir",Z.eventsDir,"--source",Q,...Z.json?["--json"]:[],...A],S=Bun.spawn(N,{stdout:"pipe",stderr:"pipe",env:Z.env}),[R,O,T]=await Promise.all([new Response(S.stdout).text(),new Response(S.stderr).text(),S.exited]),m=R.trim(),k=O.trim();if(m!=="")Z.io.out(m);if(k!=="")Z.io.errOut(k);if(T!==0&&m==="")return P$(Z,{code:"internal",layer:"kernel",retryability:"retry-at-higher-level",message:`${Q}: indrad exited ${T??"unknown"} without structured output; ${k===""?"no child diagnostic was produced":"child diagnostic was retained locally"}`});return T}let G={...j.length>0?{roots:j}:{},...W[0]!==void 0?{whatsappExportFile:W[0]}:{},...V[0]!==void 0?{gmailQuery:V[0]}:{},...q[0]!==void 0?{driveQuery:q[0]}:{},...z?{starter:!0}:{},...Y[0]!==void 0?{starterSelector:Y[0]}:{},appRoot:Z.appRoot,env:Z.env},J=u4(Q,G);if(!K(J))return P$(Z,J.err);let U=[...i8(J.ok.connector.manifest),s8,T8,...yQ,...gQ],L=l.open({eventsDir:Z.eventsDir,streams:U});if(!K(L)){let P=b2(J.ok);return P$(Z,K(P)?L.err:P.err)}let D;try{let P=k2(Q,{...G,appRoot:Z.appRoot,log:L.ok,built:J.ok});if(!K(P))return P$(Z,P.err);D=P.ok;let F=await B5.create({connector:D.connector,log:L.ok,grant:D.grant,stateRoot:`${Z.appRoot}/.zortex/sync-state`});if(!K(F))return P$(Z,F.err);if(F.ok.machine.state==="AUTH_BLOCKED"){let S=F.ok.authRepaired();if(!K(S))return P$(Z,S.err)}if(F.ok.machine.state==="ERRORED"){let S=F.ok.machine.userRetry();if(!K(S))return P$(Z,S.err)}if(F.ok.machine.state==="INCIDENT"){let S=F.ok.machine.incidentResolved("user-triggered sync (repair signal)");if(!K(S))return P$(Z,S.err)}let A=D.connector.discoverAsync!==void 0&&D.connector.pullAsync!==void 0?await F.ok.runOnceAsync():F.ok.runOnce();if(!K(A))return P$(Z,A.err);let N=A.ok;if(N.runFailed||N.state!=="IDLE"){let S=PD(N);if(N.error!==void 0)S.push(` error: ${N.error.code} [${N.error.layer}/${N.error.retryability}] \u2014 ${N.error.message}`);else if(N.runFailed)S.push(" error: sync run failed without a typed error payload \u2014 FM-21 violation");if(Z.json)Z.io.out(JSON.stringify(N,null,2));else for(let R of S)Z.io.out(R);return 1}return oG(Z,PD(N),N)}finally{let P=ZR(D,L.ok);if(!K(P))throw Error(`sync finalization failed: ${JSON.stringify(P)}`)}}function f4($,Z){let Q=[];for(;;){let X=aG($,Z);if(X===void 0)return Q;Q.push(X)}}f();f();function xD($,Z,Q,X){let z=`auth:grant:${Z}:authority:${X}`,j={id:m9(`auth-repair:${Z}:${X}`),kind:"repair",requirement:"Repair the cited AUTH_BLOCKED grant generation through the auth driver; do not copy provider content into instructions.",acceptance:[{n:1,statement:"The cited grant generation passes its auth health probe.",check:{kind:"probe",ref:z}},{n:2,statement:"The auth lifecycle replay proves repair, retry, and authority fencing.",check:{kind:"replay",ref:"evals/replay/auth-async-lifecycle-fence.eval.ts"}}],ladder:[{rung:1,proves:"the exact grant generation is diagnosable",exitCriterion:[1]},{rung:2,proves:"repair preserves lifecycle authority and replay",exitCriterion:[2]}],leases:["res:auth-driver"],budget:{tokens:25000,usd:1,wallClockMin:30},provenance:{spawnedBy:"kernel"}},W=$.create(j,"repair",{probeRef:z});if(K(W))return H(void 0);if(r(W)&&W.err.code==="already_exists")return H(void 0);return W}function ID($,Z){if(Z.length===0)return H(void 0);let Q=Z.map(({label:z})=>z).join(", "),X=`: ${Z.map(({label:z,error:Y})=>`${z} [${Y.layer}/${Y.code}] ${Y.message}`).join("; ")}`;return v({code:"internal",layer:"kernel",retryability:"non-retryable",message:`${$} failed in ${Q}${X}`,cause:Z[0].error})}function yD($,Z){try{let Q=Z();if(Q===void 0||K(Q))return;if(r(Q))return{label:$,error:Q.err};return{label:$,error:{code:"internal",layer:"kernel",retryability:"non-retryable",message:`${$} returned checked-empty during mandatory finalization`}}}catch(Q){return{label:$,error:{code:"internal",layer:"kernel",retryability:"non-retryable",message:`${$} threw during mandatory finalization: ${Q instanceof Error?Q.message:String(Q)}`}}}}function XR($){let Z=[];if($.prepared!==void 0)Z.push({label:"prepared sync source",close:()=>$.prepared.close()});if($.session!==void 0)Z.push({label:"credential session",close:()=>$.session.close()});if($.runCleanup!==void 0)Z.push({label:"worker run cleanup",close:$.runCleanup});if($.falcon!==void 0)Z.push({label:"kernel",close:()=>$.falcon.close()});if($.vault!==void 0)Z.push({label:"auth vault",close:()=>$.vault.close()});if($.log!==void 0)Z.push({label:"event log",close:()=>$.log.close()});let Q=Z.map(({label:X,close:z})=>yD(X,z)).filter((X)=>X!==void 0);return ID("indrad finalization",Q)}function zR($){let Z=(q)=>{let B=$.indexOf(q);if(B<0)return;let G=$[B+1];return $.splice(B,G===void 0?1:2),G},Q=$.indexOf("--json"),X=Q>=0;if(X)$.splice(Q,1);let z=Z("--app-root"),Y=Z("--events-dir"),j=Z("--source"),W=Z("--selector-kind"),V=Z("--selector-value");if(z===void 0||Y===void 0||j===void 0||W===void 0!==(V===void 0)||$.length>0)return v({code:"invalid_argument",layer:"kernel",retryability:"non-retryable",message:"indrad sync requires --app-root, --events-dir, --source, and a complete optional selector pair"});return H({appRoot:z,eventsDir:Y,source:j,json:X,...W!==void 0&&V!==void 0?{selector:{kind:W,value:V}}:{}})}function N$($,Z){if(Z)console.log(JSON.stringify({err:$},null,2));else console.error(`zortex: ${$.code} [${$.layer}/${$.retryability}] \u2014 ${$.message}`);return 1}function g$($,Z){if(r($))return $.err;let Q="empty"in $?$.empty.how:"unexpected ok arm";return{code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:`${Z}: checked empty (${Q})`}}function YR($){return`zortex-${WV("sha256").update($).digest("hex").slice(0,16)}`}var jR={execute:()=>v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"connector-sync worker has no action capability"}),probe:()=>v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"connector-sync worker has no action capability"})};async function WR($){let Z=jV($.source,$.selector,$.appRoot);if(!K(Z))return N$(g$(Z,"engine sync descriptor"),$.json);let Q=Z.ok,X=Q.manifest.source,z=PZ($.appRoot,".zortex","grants");if(!await Bun.file(PZ(z,"grants.db")).exists())return N$({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:`${X}: no ${Q.manifest.auth.provider} credential exists in indrad auth custody`},$.json);let Y=[...i8(Q.manifest),s8,T8,...yQ,...MY],j=l.open({eventsDir:$.eventsDir,streams:Y});if(!K(j))return N$(g$(j,"event log open"),$.json);let W=j.ok,V,q,B=void 0,G,J,U=!1;try{let L=pZ({env:{...process.env,ZORTEX_KEYSTORE:process.env.ZORTEX_KEYSTORE??(process.platform==="darwin"?"macos-keychain":process.platform==="win32"?"windows-dpapi":"file-double")},dir:PZ($.appRoot,".zortex","auth-keystore"),account:YR($.appRoot),production:!0});if(!K(L))return N$(g$(L,"auth keystore"),$.json);let D=k5.open({dir:z,keyStore:L.ok,now:()=>new Date().toISOString()});if(!K(D))return N$(g$(D,"auth vault"),$.json);V=D.ok;let P=V.listGrants({source:X}).filter((z$)=>z$.provider===Q.manifest.auth.provider),F=P.find((z$)=>z$.state!=="AUTH_BLOCKED"&&z$.state!=="DISABLED")??P[0];if(F===void 0)return N$({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:`${X}: no active ${Q.manifest.auth.provider} grant exists in indrad auth custody`},$.json);let A=new S8(W,V.registry,()=>new Date().toISOString()),N=new dZ([Q.policy]),S=new b1({log:W}),R=new oZ({vault:V,emitter:A,matrix:N,provider:{mode:"async",transport:{refresh:Q.refreshAsync,probe:Q.probeAsync}},nowMs:Date.now,rng:()=>0,hooks:{onRepairNeeded:(z$,v$,U9)=>U9===void 0?v(T$("failed_precondition","non-retryable","AUTH_BLOCKED repair filing requires an exact authorityVersion")):xD(S,z$,v$,U9)}}),O=await R.advanceGrantOnStartAsync(F.grantId);if(!K(O))return N$(g$(O,`${X} grant-scoped lifecycle startup advance`),$.json);if(F=O.ok,F.state==="AUTH_BLOCKED"||F.state==="DISABLED")return N$({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:`${X}: grant custody is ${F.state}; repair auth custody before sync`},$.json);if(F.state==="RETRY_WAIT"&&F.atExpiresAt!==void 0&&Date.parse(F.atExpiresAt)<=Date.now())return N$({code:"unavailable",layer:"auth",retryability:"retry-at-higher-level",message:`${X}: grant refresh is in durable retry backoff and its access token is expired`},$.json);let T,m={mint:(z$,v$,U9,L9,w2)=>T===void 0?v(T$("failed_precondition","non-retryable","broker composition incomplete")):T.mint(z$,v$,U9,L9,w2,7200),revoke:(z$)=>T===void 0?v(T$("failed_precondition","non-retryable","broker composition incomplete")):T.revoke(z$),execute:(z$,v$)=>T===void 0?v(T$("failed_precondition","non-retryable","broker composition incomplete")):T.execute(z$,v$),executeAsync:async(z$,v$)=>T===void 0?v(T$("failed_precondition","non-retryable","broker composition incomplete")):T.executeAsync(z$,v$)},k=d8.boot({dir:PZ($.appRoot,".zortex","kernel"),log:W,wallNow:Date.now,contracts:[],upstream:jR,broker:m});if(!K(k))return N$(g$(k,"indrad boot"),$.json);q=k.ok;let d=q.wake(Date.now());if(!K(d))return N$(g$(d,"indrad wake"),$.json);T=new rZ({vault:V,emitter:A,matrix:N,lifecycle:R,runs:q.runtime.runRegistry(),declaredScopes:(z$)=>z$===X?[...Q.scopes]:void 0,nowMs:Date.now,upstreamAsync:{perform:async(z$)=>{let v$=await iQ(z$.url,z$.headers,{method:z$.method,...z$.body!==void 0?{body:new TextDecoder().decode(z$.body)}:{},maxTimeSec:Math.max(1,Math.ceil(z$.timeoutMs/1000))});if(!v$.ok)return v({code:"unavailable",layer:"auth",retryability:"retry-at-higher-level",message:`${X} transport unavailable: ${v$.error}`});return H({status:v$.status,headers:v$.headers,body:new TextEncoder().encode(v$.body)})}}});let y=new Q6({broker:m,runtime:q.runtime}),b=q.ipc.attachCredentialTalon(y);if(!K(b))return N$(g$(b,"credential IPC attach"),$.json);let g=q.recoverCrashedRuns();if(!K(g))return N$(g$(g,"indrad crash recovery"),$.json);let u={id:V$()(),kind:"sync",requirement:Q.requirement,acceptance:[{n:1,statement:"Source census and ingestion finish with an explicit three-state result",check:{kind:"test",ref:`zortex sync ${X}`}}],leases:["auth-vault","event-log-writer",`connector:${X}`],budget:{tokens:1e4,usd:0,wallClockMin:120},provenance:{spawnedBy:"kernel"}},p={workerType:"connector-sync",harness:"local-loop",capabilities:{actionClasses:[],taintExposure:"mediated"},qosClass:"utility",defaultBudgets:u.budget,allowedDomains:[...Q.allowedDomains],modelPin:"none",actionScopes:[{source:X,account:F.account.id,scopes:[...Q.scopes]}]},o=q.runtime.spawn(u,{},p);if(!K(o))return N$(g$(o,"credentialed sync run spawn"),$.json);if(o.ok.disposition!=="spawned")return N$({code:"unavailable",layer:"kernel",retryability:"retry-at-higher-level",message:`${X} sync is queued behind an active falcon lease`},$.json);let Z$=o.ok.run.id,H$=!1;J=()=>{if(H$)return H(void 0);let z$=q.runtime.exit(Z$,{status:U?"done":"failed",evidence:[],...!U?{error:{code:"aborted",layer:"kernel",retryability:"non-retryable",message:"indrad connector sync did not reach a clean IDLE report"}}:{}});if(K(z$))H$=!0;return z$};let A$=o.ok.run.sandbox.credentials[0];if(A$===void 0)return N$({code:"data_loss",layer:"kernel",retryability:"non-retryable",message:"credentialed sync run spawned without its declared handle"},$.json);let e=$.selector===void 0?F.grantId:V$({now:()=>0,random:(z$)=>Uint8Array.from(WV("sha256").update(`${F.grantId}\x00${X}\x00${$.selector.kind}\x00${$.selector.value}`).digest().subarray(0,z$))})(),a={...A$,id:e},Q$=y.bind(Z$,a,A$);if(!K(Q$))return N$(g$(Q$,"credential alias bind"),$.json);let n$=!1;G={grant:a,execute:(z$,v$)=>{return v({code:"failed_precondition",layer:"kernel",retryability:"non-retryable",message:"resident-engine provider reads require executeAsync (FM-23)"})},executeAsync:async(z$,v$)=>{let U9=q.runtime.heartbeat(Z$);if(!K(U9))return U9;let L9,w2=setInterval(()=>{let E5=q.runtime.heartbeat(Z$);if(!K(E5)&&L9===void 0)L9=E5},1e4);try{let E5=await y.executeAsync(Z$,z$,v$);if(L9!==void 0&&!K(L9))return L9;if(r(E5)&&E5.err.message.includes("return guard exceeded"))return v({...E5.err,message:`${E5.err.message} (content-free endpoint: upstream.read)`});return E5}finally{clearInterval(w2)}},close:()=>{if(n$)return H(void 0);let z$=yD("credential revoke",()=>y.revoke(Z$,a)),v$=ID("indrad credential session cleanup",z$===void 0?[]:[z$]);if(K(v$))n$=!0;return v$}};let R0={appRoot:$.appRoot,env:process.env,credentialTalon:G,...Q.buildOptions},m$=u4(X,R0);if(!K(m$))return N$(g$(m$,`${X} connector build`),$.json);let s$=k2(X,{appRoot:$.appRoot,env:process.env,credentialTalon:G,log:W,built:m$.ok});if(!K(s$))return N$(g$(s$,`${X} connector preparation`),$.json);B=s$.ok;let H8=$.selector===void 0?PZ($.appRoot,".zortex","sync-state"):PZ($.appRoot,".zortex","sync-state-bounded",WV("sha256").update(`${X}\x00${$.selector.kind}\x00${$.selector.value}`).digest("hex").slice(0,16)),Z5=await B5.create({connector:B.connector,log:W,grant:B.grant,stateRoot:H8});if(!K(Z5))return N$(g$(Z5,`${X} sync runner`),$.json);if(Z5.ok.machine.state==="AUTH_BLOCKED"){let z$=Z5.ok.authRepaired();if(!K(z$))return N$(g$(z$,`${X} auth repair signal`),$.json)}if(Z5.ok.machine.state==="ERRORED"){let z$=Z5.ok.machine.userRetry();if(!K(z$))return N$(g$(z$,`${X} user retry signal`),$.json)}if(Z5.ok.machine.state==="INCIDENT"){let z$=Z5.ok.machine.incidentResolved("user-triggered indrad sync repair signal");if(!K(z$))return N$(g$(z$,`${X} incident repair signal`),$.json)}let Q5=await Z5.ok.runOnceAsync();if(!K(Q5))return N$(g$(Q5,`${X} sync`),$.json);if(U=!Q5.ok.runFailed&&Q5.ok.state==="IDLE",$.json)console.log(JSON.stringify(Q5.ok,null,2));else console.log(`${X} sync ${Q5.ok.state}: appended ${Q5.ok.appended}`);return Q5.ok.runFailed||Q5.ok.state!=="IDLE"?1:0}finally{let L=XR({...B!==void 0?{prepared:B}:{},...G!==void 0?{session:G}:{},...J!==void 0?{runCleanup:J}:{},...q!==void 0?{falcon:q}:{},...V!==void 0?{vault:V}:{},log:W});if(!K(L))throw Error(`indrad sync finalization failed: ${g$(L,"indrad finalization").message}`)}}if(import.meta.main){let $=zR(process.argv.slice(2)),Z=K($)?await WR($.ok):N$(g$($,"indrad args"),process.argv.includes("--json"));process.exit(Z)}export{XR as closeIndradResources};