@rizom/ops 0.2.0-alpha.518 → 0.2.0-alpha.519

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -462,7 +462,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
462
462
  hash text NOT NULL,
463
463
  created_at numeric
464
464
  )
465
- `;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var $O;var vV=x(()=>{Ne();$O=class $O{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ix(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Pp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Qn,_V,OO,fke=()=>({union:pke,unionAll:mke,intersect:hke,except:gke}),pke,mke,hke,gke;var RO=x(()=>{Ne();vV();lo();Ga();pr();Wn();Ir();Ur();so();ku();Up();Qn=class Qn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,Ae))r={};else r=mx(e);return new OO({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};_V=class _V extends $O{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=zp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Gn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=zp(t);for(let o of Gn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,Ae)){let o=ce(t,vt)?t._.selectedFields:ce(t,Cn)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let i=typeof r==="function"?r(fke()):r;if(!Pp(this.getSelectedFields(),i.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Gn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Gn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new xt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};OO=class OO extends _V{static[J]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=$n(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};e9(OO,[Mr]);pke=Ix("union",!1),mke=Ix("union",!0),hke=Ix("intersect",!1),gke=Ix("except",!1)});var Ya;var Ax=x(()=>{Ne();Ga();Ex();Wn();RO();Ya=class Ya{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,Iu)?e:void 0,this.dialectConfig=ce(e,Iu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new $p(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Qn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Qn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Qn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Qn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new TO(this.dialectConfig);return this.dialect}}});var Tx,PO;var kV=x(()=>{Ne();lo();pr();uo();Ir();Ur();ku();Ax();Tx=class Tx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,Ae)?s:new mn(s,n[o])}return i});return new PO(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ya):e;if(!ce(t,Ae)&&!Pp(this.table[dx],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new PO(this.table,t,this.session,this.dialect,this.withList,!0)}};PO=class PO extends Mr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=$n(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,px(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Gn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Cx,EV;var IV=x(()=>{Ne();lo();Ga();uo();Wn();Ir();Ur();so();ku();Up();Cx=class Cx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new EV(this.table,px(this.table,e),this.session,this.dialect,this.withList)}};EV=class EV extends Mr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=zp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Mt)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[we.Symbol.Columns],new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=$n(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Gn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var zO=x(()=>{yV();kV();Ax();RO();IV()});var Mp;var AV=x(()=>{Ne();pr();Mp=class Mp extends Ae{constructor(e){super(Mp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Mp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var DO,$x,NO;var TV=x(()=>{Ne();lo();Dp();DO=class DO{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new NO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new NO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};$x=class $x extends Mr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>xx(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};NO=class NO extends $x{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Au;var CV=x(()=>{Ne();lo();Au=class Au extends Mr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Fp;var Ox=x(()=>{Ne();Ga();pr();zO();Wn();AV();TV();CV();Fp=class Fp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new DO(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ya(r.dialect));return new Proxy(new $p(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Mp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Qn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Qn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Cx(a,t.session,t.dialect,e)}function o(a){return new Tx(a,t.session,t.dialect,e)}function s(a){return new _x(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Qn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Qn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Cx(e,this.session,this.dialect)}$cache;insert(e){return new Tx(e,this.session,this.dialect)}delete(e){return new _x(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function LO(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var $V,Zp;var BO=x(()=>{Ne();$V=class $V{static[J]="Cache"};Zp=class Zp extends $V{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var OV=x(()=>{BO()});var RV=()=>{};var PV,jO,qO,UO;var MO=x(()=>{BO();Ne();kx();lo();Ox();PV=class PV extends Mr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};jO=class jO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Zp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await LO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await LO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new PV(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};qO=class qO{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Eu({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};UO=class UO extends Fp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new EO}}});var FO,yke,bke,Rx;var zV=x(()=>{Ne();Ga();Ur();Ax();uo();Up();FO=class FO{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};yke=class yke extends FO{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ya);let t=new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};bke=class bke extends FO{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=mx(qp(e,t))}existing(){return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Rx=class Rx extends po{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var ZO=x(()=>{RV();uV();AO();Ox();Ex();mO();mV();gV();zO();MO();uo();gO();ku();zV()});function NV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Px(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var zx,HO,DV;var KO=x(()=>{OV();Ne();hx();pr();ZO();MO();Ur();zx=class zx extends qO{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new aO,this.cache=i.cache??new Zp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new DV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new zx(this.client,this.dialect,this.schema,this.options,r),n=new HO("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};HO=class HO extends UO{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new HO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};DV=class DV extends jO{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=Rp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Rp(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>NV(r));if(this.customResultMapper)return this.customResultMapper(e,Px);return e.map((r)=>iO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Rp(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return NV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Px);return iO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap)}async values(e){let t=Rp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Tu(e,t={}){let r=new CO({casing:t.casing}),i;if(t.logger===!0)i=new sO;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=E9(t.schema,A9);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new zx(e,r,n,{logger:i,cache:t.cache},void 0),s=new LV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var LV;var BV=x(()=>{Ne();hx();Dp();Ox();Ex();KO();LV=class LV extends Fp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Nx(...e){if(typeof e[0]==="string"){let t=xu({url:e[0]});return Tu(t,e[1])}if(t9(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Tu(r,i);let n=typeof t==="string"?xu({url:t}):xu(t);return Tu(n,i)}return Tu(e[0],e[1])}var jV=x(()=>{J$();Ur();BV();((e)=>{function t(r){return Tu({},r)}e.mock=t})(Nx||(Nx={}))});var qV=x(()=>{jV();KO()});function UV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function vke(e){return e instanceof je&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Dx(e,t){let r=Date.now()+(t.budgetMs??xke),i=async(n)=>{if(t.isClosed())throw new je("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!vke(o))throw o;await t.afterRefusal?.();let s=Math.min(Ske*2**(n-1),wke),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function JO(e,t={}){let r=xu({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(d,p){return Dx(()=>typeof d==="string"?s(d,p):s(d),l)},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(d,p)=>Dx(()=>a(d,p),l),r.migrate=(d)=>Dx(()=>c(d),l),r.transaction=(d)=>Dx(()=>i(d),l)}return r}function Lx(e){let{url:t,schema:r}=e,i=UV(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?JO({url:t,authToken:i},n):JO({url:t},n);return{db:Nx(o,{schema:r}),client:o,url:t}}async function Bx(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var xke=5000,Ske=5,wke=40;var VO=x(()=>{J$();qV()});var MV=x(()=>{c$();VO()});var WO=x(()=>{VO();MV()});var oe,pt;var GO=x(()=>{ZO();ip();oe=qp("job_queue",{id:mr("id").primaryKey().$defaultFn(()=>to()),type:mr("type").notNull(),data:mr("data").notNull(),result:mr("result",{mode:"json"}),progress:mr("progress",{mode:"json"}).$type(),source:mr("source"),metadata:mr("metadata",{mode:"json"}).$type().notNull(),status:mr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:Ar("priority").notNull().default(0),retryCount:Ar("retryCount").notNull().default(0),maxRetries:Ar("maxRetries").notNull().default(3),lastError:mr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:mr("attemptId"),workerSlotId:mr("workerSlotId"),workerSessionId:mr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Qa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Qa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Qa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Qa("idx_job_queue_source").on(e.source)})),pt=qp("job_worker_sessions",{slotId:mr("slotId").primaryKey(),sessionId:mr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Qa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Qa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function FV(e){return Lx({url:e.url,schema:{jobQueue:oe,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var ZV=x(()=>{WO();GO()});class QO{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var HV=x(()=>{Sx();cx();Vn();Ne();kx();hx();lo();Dp();IO();Wn();Ir();Ur();so()});class YO{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class XO{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ke.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=_ke.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var _ke;var KV=x(()=>{Re();ys();_ke=f.looseObject({deduplicationKey:f.string().optional()})});class eR{db;transactionClient;databaseUrl;logger;deduplicator=new XO;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??kke}async insert(e){await this.write("insert",async()=>this.db.insert(oe).values(e))}async enqueueAtomic(e){return Tke.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ke.FAILED,"Replaced by newer job",p,p,d.id,Ke.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ke.PENDING,Ke.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ke.PENDING&&r!==Ke.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata:o}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,i,n){let o=Math.min(Eke*2**(i-1),Ike),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=ct(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=gs){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=gs){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(Nt(tt(pt.slotId,e),tt(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(Nt(tt(pt.slotId,e),tt(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(oe).set({status:Ke.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(oe).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(oe).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(oe).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:oe.retryCount,maxRetries:oe.maxRetries,type:oe.type,scheduledFor:oe.scheduledFor,startedAt:oe.startedAt,runtimeUpdatedAt:oe.runtimeUpdatedAt}).from(oe).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(oe).set({status:s?Ke.PENDING:Ke.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Nt(this.attemptWriteGuard(e,r),tt(oe.retryCount,o.retryCount))).returning({id:oe.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(oe).set({status:Ke.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Nt(tt(oe.id,e.jobId),tt(oe.type,e.expectedType),ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)),On(oe.attemptId),On(oe.workerSlotId),On(oe.workerSessionId),On(oe.leaseExpiresAt),On(oe.attemptHeartbeatAt),On(oe.progress),On(oe.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(oe).where(tt(oe.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(oe).where(q`json_extract(${oe.metadata}, '$.rootJobId') = ${e}`).orderBy(co(oe.createdAt),co(oe.id))}async getStatusByEntityId(e){return(await this.db.select().from(oe).where(q`json_extract(${oe.data}, '$.id') = ${e}`).orderBy(Wa(oe.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:oe.type,status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.type,oe.status),this.db.select({oldestPendingAt:q`min(case when ${oe.status} = ${Ke.PENDING} then ${oe.createdAt} end)`,duePending:q`coalesce(sum(case when ${oe.status} = ${Ke.PENDING} and ${oe.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${oe.status} = ${Ke.PENDING} and ${oe.scheduledFor} <= ${e} then ${oe.scheduledFor} end)`,latestClaimAt:q`max(${oe.startedAt})`,oldestProcessingAt:q`min(case when ${oe.status} = ${Ke.PROCESSING} then ${oe.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${oe.status} = ${Ke.PROCESSING} and ${oe.leaseExpiresAt} is not null and ${oe.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(oe),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=Ake.parse(t);if(r===0)return[];return(await this.db.select().from(oe).where(q`(${oe.runtimeUpdatedAt}, ${oe.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(oe.runtimeUpdatedAt),co(oe.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(oe).where(Nt(ao(tt(oe.status,Ke.COMPLETED),tt(oe.status,Ke.FAILED)),vu(oe.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)),r=e&&e.length>0?Nt(t,Cs(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Cs(oe.type,e):void 0;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt)).limit(t)}async getFailedJobs(e){let t=tt(oe.status,Ke.FAILED),r=e&&e.length>0?Nt(t,Cs(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:pt.slotId}).from(pt).where(Nt(tt(pt.slotId,i),tt(pt.sessionId,n),gx(pt.expiresAt,t))),c=this.db.select({slotId:pt.slotId}).from(pt).where(Nt(tt(pt.slotId,oe.workerSlotId),tt(pt.sessionId,oe.workerSessionId))),l=Nt(tt(oe.status,Ke.PROCESSING),ao(On(oe.attemptId),bx(c),vu(oe.leaseExpiresAt,t))),u=q`${oe.status} = ${Ke.PROCESSING} AND ${oe.retryCount} + 1 > ${oe.maxRetries}`,d=this.db.select({id:oe.id}).from(oe).where(Nt(Cs(oe.type,s),ao(Nt(tt(oe.status,Ke.PENDING),vu(oe.scheduledFor,t)),l))).orderBy(co(oe.priority),co(oe.createdAt)).limit(1),m=(await this.write("claim",async()=>this.db.update(oe).set({status:q`CASE WHEN ${u} THEN ${Ke.FAILED} ELSE ${Ke.PROCESSING} END`,retryCount:q`CASE WHEN ${oe.status} = ${Ke.PROCESSING} THEN ${oe.retryCount} + 1 ELSE ${oe.retryCount} END`,lastError:q`CASE WHEN ${oe.status} = ${Ke.PROCESSING} THEN 'Attempt lease expired' ELSE ${oe.lastError} END`,startedAt:q`CASE WHEN ${u} THEN ${oe.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${u} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${u} THEN ${oe.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${u} THEN ${oe.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${u} THEN ${oe.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${u} THEN ${oe.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${u} THEN ${oe.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${u} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${oe.runtimeUpdatedAt} END`}).where(Nt(Cs(oe.id,d),yx(a))).returning()))[0];if(m?.status!==Ke.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:m.id,attemptId:m.attemptId,workerSlotId:i,workerSessionId:n}),m}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${oe.runtimeUpdatedAt}) from ${oe}), 0) + 1)`}attemptWriteGuard(e,t){return t?Nt(tt(oe.id,e),tt(oe.status,Ke.PROCESSING),tt(oe.attemptId,t)):Nt(tt(oe.id,e),On(oe.attemptId),ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)))}}var kke=2000,Eke=5,Ike=40,Ake,Tke;var JV=x(()=>{HV();GO();Re();ys();sp();KV();Ake=f.number().int().min(0).max(1000),Tke=new YO});import{AsyncLocalStorage as Cke}from"async_hooks";class Hp{storage=new Cke;static createFresh(){return new Hp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Po.parse(e),n=$ke(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function $ke(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var tR=x(()=>{zo()});class Kp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Kp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=FV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Hp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new QO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new eR(i,n,o,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Bx(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ke.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:ct(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Po.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=gs){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=gs){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var VV=x(()=>{ip();c$();sp();ys();WO();ZV();JV();zo();tR()});var rR=()=>{};var WV=x(()=>{ip();ys();sp();ys();rR();tR()});var GV=x(()=>{ys();rR()});var ctt;var QV=x(()=>{zo();Re();op();ctt=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var dtt;var YV=x(()=>{Re();dtt=f.record(f.string(),f.unknown())});var XV=x(()=>{zo();ip()});var e7=x(()=>{VV();WV();GV();QV();YV();sp();ys();op();XV()});var nR={};tr(nR,{LEGACY_PROJECTION_JOB_TYPES:()=>r7,LEGACY_PROJECTION_RETIREMENT_REASON:()=>i7,legacyProjectionJobTypeSchema:()=>n7,retireLegacyProjectionJob:()=>qke});import{existsSync as Lke}from"fs";import{resolve as Bke}from"path";function t7(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function jke(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function qke(e){let t=Bke(e.databasePath);if(!Lke(t))throw Error(`Job database does not exist: ${t}`);let r=n7.parse(e.jobType),i=Kp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(jke(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:t7(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:i7,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:t7(s),retired:!0}}finally{i.close()}}var r7,n7,i7="Retired legacy projection job superseded by scheduler-owned projections";var iR=x(()=>{e7();Re();r7=["conversation-memory:project","skill:project","swot:derive","topic:project"],n7=f.enum(r7)});function er(e,t,r,i,n){return s7.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function sR(e){return Vp.parse(structuredClone(Zke[e]))}function Wp(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function qx(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),oR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return oR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:Hke(c)})}finally{clearTimeout(a)}}async function aR(e,t){let r=Vp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${jx(c)}`}if(!n)for(let c of r.phases)try{let l=a7.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=jx(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=c7.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=jx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=l7.parse(await t.stopMonitoring())}catch(c){let l=jx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=d7(a,r.maximumExternalAiCalls??0),u7.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function d7(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Hke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function jx(e){return ct(e)}var Jp,o7,s7,Vp,Uke,oR,Mke,a7,c7,Fke,l7,u7,Zke;var Ux=x(()=>{Re();Jp=f.enum(["regression","load","stress"]),o7=f.enum(["add","update","rename","delete"]),s7=f.object({id:f.string().min(1),operation:o7,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Vp=f.object({profile:Jp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(s7).min(1)}),Uke=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),oR=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),Mke=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),a7=f.object({id:f.string().min(1),operation:o7,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),c7=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),Fke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),l7=f.object({health:f.array(oR),runtime:f.array(Mke),externalAiCalls:f.number().int().nonnegative().optional(),container:Fke.optional()}),u7=f.object({profile:Jp,success:f.boolean(),baseline:Uke,phases:f.array(a7),cleanup:c7,metrics:l7,failure:f.string().optional()}),Zke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as Kke}from"child_process";async function f7(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=Kke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Gp=()=>{};class Cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new Cu(e,r,i);return await f7(e,"git",["-c","credential.helper=","-c",`credential.helper=${p7}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",p7]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Ei("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var p7='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var m7=x(()=>{Gp()});function Qp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class cR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await qx(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return Jke.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Qp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await qx(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var Jke;var h7=x(()=>{Re();Ux();Jke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Mx={};tr(Mx,{applyDirectorySyncStressPhase:()=>v7,cleanupDirectorySyncStress:()=>x7,listProbeFiles:()=>Xa,parseStressRuntimeSample:()=>_7,removeProbeFiles:()=>hR,runDeployedDirectorySyncStress:()=>y7,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>b7});import{chmod as Vke,mkdir as uR,mkdtemp as dR,readFile as Wke,readdir as Gke,rename as Qke,rm as Xp,writeFile as Yn}from"fs/promises";import{tmpdir as fR}from"os";import{join as St,resolve as pR}from"path";async function y7(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=gR(r),n=pR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await uR(n,{recursive:!0});let{pilot:o,user:s}=await mR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Jp.parse(e.profile),c=e.plan?Vp.parse(e.plan):sR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)w7(s);let l=Yke.parse(e.env??process.env),u=new S7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await aR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await nEe(p),p}async function b7(e){let r=(e.now??(()=>new Date))().toISOString(),i=gR(r),n=pR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await uR(n,{recursive:!0});let{pilot:o,user:s}=await mR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),w7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await dR(St(fR(),"brains-ops-directory-sync-access-check-"));try{let l=await Cu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Yn(St(n,"access-check.json"),`${JSON.stringify(d,null,2)}
465
+ `;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var $O;var vV=x(()=>{Ne();$O=class $O{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ix(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Pp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Qn,_V,OO,fke=()=>({union:pke,unionAll:mke,intersect:hke,except:gke}),pke,mke,hke,gke;var RO=x(()=>{Ne();vV();lo();Ga();pr();Wn();Ir();Ur();so();ku();Up();Qn=class Qn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,Ae))r={};else r=mx(e);return new OO({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};_V=class _V extends $O{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=zp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Gn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=zp(t);for(let o of Gn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,Ae)){let o=ce(t,vt)?t._.selectedFields:ce(t,Cn)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let i=typeof r==="function"?r(fke()):r;if(!Pp(this.getSelectedFields(),i.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Gn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Gn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new xt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};OO=class OO extends _V{static[J]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=$n(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};e9(OO,[Mr]);pke=Ix("union",!1),mke=Ix("union",!0),hke=Ix("intersect",!1),gke=Ix("except",!1)});var Ya;var Ax=x(()=>{Ne();Ga();Ex();Wn();RO();Ya=class Ya{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,Iu)?e:void 0,this.dialectConfig=ce(e,Iu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new $p(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Qn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Qn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Qn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Qn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new TO(this.dialectConfig);return this.dialect}}});var Tx,PO;var kV=x(()=>{Ne();lo();pr();uo();Ir();Ur();ku();Ax();Tx=class Tx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,Ae)?s:new mn(s,n[o])}return i});return new PO(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ya):e;if(!ce(t,Ae)&&!Pp(this.table[dx],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new PO(this.table,t,this.session,this.dialect,this.withList,!0)}};PO=class PO extends Mr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=$n(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,px(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Gn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Cx,EV;var IV=x(()=>{Ne();lo();Ga();uo();Wn();Ir();Ur();so();ku();Up();Cx=class Cx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new EV(this.table,px(this.table,e),this.session,this.dialect,this.withList)}};EV=class EV extends Mr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=zp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Mt)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new xt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[we.Symbol.Columns],new xt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=$n(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Gn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var zO=x(()=>{yV();kV();Ax();RO();IV()});var Mp;var AV=x(()=>{Ne();pr();Mp=class Mp extends Ae{constructor(e){super(Mp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Mp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var DO,$x,NO;var TV=x(()=>{Ne();lo();Dp();DO=class DO{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new NO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new NO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};$x=class $x extends Mr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>xx(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};NO=class NO extends $x{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Au;var CV=x(()=>{Ne();lo();Au=class Au extends Mr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Fp;var Ox=x(()=>{Ne();Ga();pr();zO();Wn();AV();TV();CV();Fp=class Fp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new DO(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ya(r.dialect));return new Proxy(new $p(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new xt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Mp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Qn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Qn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Cx(a,t.session,t.dialect,e)}function o(a){return new Tx(a,t.session,t.dialect,e)}function s(a){return new _x(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Qn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Qn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Cx(e,this.session,this.dialect)}$cache;insert(e){return new Tx(e,this.session,this.dialect)}delete(e){return new _x(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Au(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function LO(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var $V,Zp;var BO=x(()=>{Ne();$V=class $V{static[J]="Cache"};Zp=class Zp extends $V{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var OV=x(()=>{BO()});var RV=()=>{};var PV,jO,qO,UO;var MO=x(()=>{BO();Ne();kx();lo();Ox();PV=class PV extends Mr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};jO=class jO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Zp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await LO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await LO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new PV(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};qO=class qO{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Eu({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};UO=class UO extends Fp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new EO}}});var FO,yke,bke,Rx;var zV=x(()=>{Ne();Ga();Ur();Ax();uo();Up();FO=class FO{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};yke=class yke extends FO{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ya);let t=new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};bke=class bke extends FO{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=mx(qp(e,t))}existing(){return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new xt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Rx=class Rx extends po{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var ZO=x(()=>{RV();uV();AO();Ox();Ex();mO();mV();gV();zO();MO();uo();gO();ku();zV()});function NV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Px(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var zx,HO,DV;var KO=x(()=>{OV();Ne();hx();pr();ZO();MO();Ur();zx=class zx extends qO{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new aO,this.cache=i.cache??new Zp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new DV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new zx(this.client,this.dialect,this.schema,this.options,r),n=new HO("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};HO=class HO extends UO{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new HO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};DV=class DV extends jO{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=Rp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Rp(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>NV(r));if(this.customResultMapper)return this.customResultMapper(e,Px);return e.map((r)=>iO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Rp(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return NV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Px);return iO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap)}async values(e){let t=Rp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Tu(e,t={}){let r=new CO({casing:t.casing}),i;if(t.logger===!0)i=new sO;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=E9(t.schema,A9);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new zx(e,r,n,{logger:i,cache:t.cache},void 0),s=new LV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var LV;var BV=x(()=>{Ne();hx();Dp();Ox();Ex();KO();LV=class LV extends Fp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Nx(...e){if(typeof e[0]==="string"){let t=xu({url:e[0]});return Tu(t,e[1])}if(t9(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Tu(r,i);let n=typeof t==="string"?xu({url:t}):xu(t);return Tu(n,i)}return Tu(e[0],e[1])}var jV=x(()=>{J$();Ur();BV();((e)=>{function t(r){return Tu({},r)}e.mock=t})(Nx||(Nx={}))});var qV=x(()=>{jV();KO()});function UV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function vke(e){return e instanceof je&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Dx(e,t){let r=Date.now()+(t.budgetMs??xke),i=async(n)=>{if(t.isClosed())throw new je("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!vke(o))throw o;await t.afterRefusal?.();let s=Math.min(Ske*2**(n-1),wke),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function JO(e,t={}){let r=xu({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(d,p){return Dx(()=>typeof d==="string"?s(d,p):s(d),l)},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(d,p)=>Dx(()=>a(d,p),l),r.migrate=(d)=>Dx(()=>c(d),l),r.transaction=(d)=>Dx(()=>i(d),l)}return r}function Lx(e){let{url:t,schema:r}=e,i=UV(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?JO({url:t,authToken:i},n):JO({url:t},n);return{db:Nx(o,{schema:r}),client:o,url:t}}async function Bx(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var xke=5000,Ske=5,wke=40;var VO=x(()=>{J$();qV()});var MV=x(()=>{c$();VO()});var WO=x(()=>{VO();MV()});var oe,pt;var GO=x(()=>{ZO();ip();oe=qp("job_queue",{id:mr("id").primaryKey().$defaultFn(()=>to()),type:mr("type").notNull(),data:mr("data").notNull(),result:mr("result",{mode:"json"}),progress:mr("progress",{mode:"json"}).$type(),source:mr("source"),metadata:mr("metadata",{mode:"json"}).$type().notNull(),status:mr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:Ar("priority").notNull().default(0),retryCount:Ar("retryCount").notNull().default(0),maxRetries:Ar("maxRetries").notNull().default(3),lastError:mr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:mr("attemptId"),workerSlotId:mr("workerSlotId"),workerSessionId:mr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Qa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Qa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Qa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Qa("idx_job_queue_source").on(e.source)})),pt=qp("job_worker_sessions",{slotId:mr("slotId").primaryKey(),sessionId:mr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Qa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Qa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function FV(e){return Lx({url:e.url,schema:{jobQueue:oe,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var ZV=x(()=>{WO();GO()});class QO{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var HV=x(()=>{Sx();cx();Vn();Ne();kx();hx();lo();Dp();IO();Wn();Ir();Ur();so()});class YO{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class XO{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ke.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=_ke.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var _ke;var KV=x(()=>{Re();ys();_ke=f.looseObject({deduplicationKey:f.string().optional()})});class eR{db;transactionClient;databaseUrl;logger;deduplicator=new XO;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??kke}async insert(e){await this.write("insert",async()=>this.db.insert(oe).values(e))}async enqueueAtomic(e){return Tke.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ke.FAILED,"Replaced by newer job",p,p,d.id,Ke.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ke.PENDING,Ke.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ke.PENDING&&r!==Ke.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata:o}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,i,n){let o=Math.min(Eke*2**(i-1),Ike),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=ct(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=gs){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=gs){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(Nt(tt(pt.slotId,e),tt(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(Nt(tt(pt.slotId,e),tt(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(oe).set({status:Ke.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(oe).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(oe).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(oe).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:oe.retryCount,maxRetries:oe.maxRetries,type:oe.type,scheduledFor:oe.scheduledFor,startedAt:oe.startedAt,runtimeUpdatedAt:oe.runtimeUpdatedAt}).from(oe).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(oe).set({status:s?Ke.PENDING:Ke.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Nt(this.attemptWriteGuard(e,r),tt(oe.retryCount,o.retryCount))).returning({id:oe.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(oe).set({status:Ke.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Nt(tt(oe.id,e.jobId),tt(oe.type,e.expectedType),ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)),On(oe.attemptId),On(oe.workerSlotId),On(oe.workerSessionId),On(oe.leaseExpiresAt),On(oe.attemptHeartbeatAt),On(oe.progress),On(oe.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(oe).where(tt(oe.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(oe).where(q`json_extract(${oe.metadata}, '$.rootJobId') = ${e}`).orderBy(co(oe.createdAt),co(oe.id))}async getStatusByEntityId(e){return(await this.db.select().from(oe).where(q`json_extract(${oe.data}, '$.id') = ${e}`).orderBy(Wa(oe.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:oe.type,status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.type,oe.status),this.db.select({oldestPendingAt:q`min(case when ${oe.status} = ${Ke.PENDING} then ${oe.createdAt} end)`,duePending:q`coalesce(sum(case when ${oe.status} = ${Ke.PENDING} and ${oe.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${oe.status} = ${Ke.PENDING} and ${oe.scheduledFor} <= ${e} then ${oe.scheduledFor} end)`,latestClaimAt:q`max(${oe.startedAt})`,oldestProcessingAt:q`min(case when ${oe.status} = ${Ke.PROCESSING} then ${oe.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${oe.status} = ${Ke.PROCESSING} and ${oe.leaseExpiresAt} is not null and ${oe.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(oe),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=Ake.parse(t);if(r===0)return[];return(await this.db.select().from(oe).where(q`(${oe.runtimeUpdatedAt}, ${oe.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(oe.runtimeUpdatedAt),co(oe.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(oe).where(Nt(ao(tt(oe.status,Ke.COMPLETED),tt(oe.status,Ke.FAILED)),vu(oe.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)),r=e&&e.length>0?Nt(t,Cs(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Cs(oe.type,e):void 0;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt)).limit(t)}async getFailedJobs(e){let t=tt(oe.status,Ke.FAILED),r=e&&e.length>0?Nt(t,Cs(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Wa(oe.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:pt.slotId}).from(pt).where(Nt(tt(pt.slotId,i),tt(pt.sessionId,n),gx(pt.expiresAt,t))),c=this.db.select({slotId:pt.slotId}).from(pt).where(Nt(tt(pt.slotId,oe.workerSlotId),tt(pt.sessionId,oe.workerSessionId))),l=Nt(tt(oe.status,Ke.PROCESSING),ao(On(oe.attemptId),bx(c),vu(oe.leaseExpiresAt,t))),u=q`${oe.status} = ${Ke.PROCESSING} AND ${oe.retryCount} + 1 > ${oe.maxRetries}`,d=this.db.select({id:oe.id}).from(oe).where(Nt(Cs(oe.type,s),ao(Nt(tt(oe.status,Ke.PENDING),vu(oe.scheduledFor,t)),l))).orderBy(co(oe.priority),co(oe.createdAt)).limit(1),m=(await this.write("claim",async()=>this.db.update(oe).set({status:q`CASE WHEN ${u} THEN ${Ke.FAILED} ELSE ${Ke.PROCESSING} END`,retryCount:q`CASE WHEN ${oe.status} = ${Ke.PROCESSING} THEN ${oe.retryCount} + 1 ELSE ${oe.retryCount} END`,lastError:q`CASE WHEN ${oe.status} = ${Ke.PROCESSING} THEN 'Attempt lease expired' ELSE ${oe.lastError} END`,startedAt:q`CASE WHEN ${u} THEN ${oe.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${u} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${u} THEN ${oe.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${u} THEN ${oe.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${u} THEN ${oe.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${u} THEN ${oe.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${u} THEN ${oe.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${u} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${oe.runtimeUpdatedAt} END`}).where(Nt(Cs(oe.id,d),yx(a))).returning()))[0];if(m?.status!==Ke.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:m.id,attemptId:m.attemptId,workerSlotId:i,workerSessionId:n}),m}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${oe.runtimeUpdatedAt}) from ${oe}), 0) + 1)`}attemptWriteGuard(e,t){return t?Nt(tt(oe.id,e),tt(oe.status,Ke.PROCESSING),tt(oe.attemptId,t)):Nt(tt(oe.id,e),On(oe.attemptId),ao(tt(oe.status,Ke.PENDING),tt(oe.status,Ke.PROCESSING)))}}var kke=2000,Eke=5,Ike=40,Ake,Tke;var JV=x(()=>{HV();GO();Re();ys();sp();KV();Ake=f.number().int().min(0).max(1000),Tke=new YO});import{AsyncLocalStorage as Cke}from"async_hooks";class Hp{storage=new Cke;static createFresh(){return new Hp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Po.parse(e),n=$ke(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function $ke(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var tR=x(()=>{zo()});class Kp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Kp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=FV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Hp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new QO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new eR(i,n,o,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Bx(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ke.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:ct(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Po.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=gs){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=gs){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var VV=x(()=>{ip();c$();sp();ys();WO();ZV();JV();zo();tR()});var rR=()=>{};var WV=x(()=>{ip();ys();sp();ys();rR();tR()});var GV=x(()=>{ys();rR()});var ctt;var QV=x(()=>{zo();Re();op();ctt=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var dtt;var YV=x(()=>{Re();dtt=f.record(f.string(),f.unknown())});var XV=x(()=>{zo();ip()});var e7=x(()=>{VV();WV();GV();QV();YV();sp();ys();op();XV()});var nR={};tr(nR,{LEGACY_PROJECTION_JOB_TYPES:()=>r7,LEGACY_PROJECTION_RETIREMENT_REASON:()=>i7,legacyProjectionJobTypeSchema:()=>n7,retireLegacyProjectionJob:()=>qke});import{existsSync as Lke}from"fs";import{resolve as Bke}from"path";function t7(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function jke(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function qke(e){let t=Bke(e.databasePath);if(!Lke(t))throw Error(`Job database does not exist: ${t}`);let r=n7.parse(e.jobType),i=Kp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(jke(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:t7(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:i7,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:t7(s),retired:!0}}finally{i.close()}}var r7,n7,i7="Retired legacy projection job superseded by scheduler-owned projections";var iR=x(()=>{e7();Re();r7=["conversation-memory:project","skill:project","swot:derive","topic:project"],n7=f.enum(r7)});function er(e,t,r,i,n){return s7.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function sR(e){return Vp.parse(structuredClone(Zke[e]))}function Wp(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function qx(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),oR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return oR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:Hke(c)})}finally{clearTimeout(a)}}async function aR(e,t){let r=Vp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${jx(c)}`}if(!n)for(let c of r.phases)try{let l=a7.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=jx(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=c7.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=jx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=l7.parse(await t.stopMonitoring())}catch(c){let l=jx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=d7(a,r.maximumExternalAiCalls??0),u7.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function d7(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Hke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function jx(e){return ct(e)}var Jp,o7,s7,Vp,Uke,oR,Mke,a7,c7,Fke,l7,u7,Zke;var Ux=x(()=>{Re();Jp=f.enum(["regression","load","stress"]),o7=f.enum(["add","update","rename","delete"]),s7=f.object({id:f.string().min(1),operation:o7,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Vp=f.object({profile:Jp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(s7).min(1)}),Uke=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),oR=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),Mke=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),a7=f.object({id:f.string().min(1),operation:o7,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),c7=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),Fke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),l7=f.object({health:f.array(oR),runtime:f.array(Mke),externalAiCalls:f.number().int().nonnegative().optional(),container:Fke.optional()}),u7=f.object({profile:Jp,success:f.boolean(),baseline:Uke,phases:f.array(a7),cleanup:c7,metrics:l7,failure:f.string().optional()}),Zke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as Kke}from"child_process";async function f7(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=Kke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Gp=()=>{};class Cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new Cu(e,r,i);return await f7(e,"git",["-c","credential.helper=","-c",`credential.helper=${p7}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",p7]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Ei("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var p7='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var m7=x(()=>{Gp()});function Qp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class cR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await qx(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return Jke.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Qp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await qx(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var Jke;var h7=x(()=>{Re();Ux();Jke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Mx={};tr(Mx,{applyDirectorySyncStressPhase:()=>v7,cleanupDirectorySyncStress:()=>x7,listProbeFiles:()=>Xa,parseStressRuntimeSample:()=>_7,removeProbeFiles:()=>hR,runDeployedDirectorySyncStress:()=>y7,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>b7});import{chmod as Vke,mkdir as uR,mkdtemp as dR,readFile as Wke,readdir as Gke,rename as Qke,rm as Xp,writeFile as Yn}from"fs/promises";import{tmpdir as fR}from"os";import{join as St,resolve as pR}from"path";async function y7(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=gR(r),n=pR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await uR(n,{recursive:!0});let{pilot:o,user:s}=await mR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Jp.parse(e.profile),c=e.plan?Vp.parse(e.plan):sR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)w7(s);let l=Yke.parse(e.env??process.env),u=new S7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await aR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await nEe(p),p}async function b7(e){let r=(e.now??(()=>new Date))().toISOString(),i=gR(r),n=pR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await uR(n,{recursive:!0});let{pilot:o,user:s}=await mR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),w7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await dR(St(fR(),"brains-ops-directory-sync-access-check-"));try{let l=await Cu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Yn(St(n,"access-check.json"),`${JSON.stringify(d,null,2)}
466
466
  `),d}finally{await Xp(c,{recursive:!0,force:!0})}}async function x7(e){let t=e.now??(()=>new Date),r=pR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`cleanup-${gR(t().toISOString())}`));await uR(r,{recursive:!0});let{pilot:i,user:n}=await mR(e.rootDir,e.handle);Wp({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??mo,a=e.logger??console.info,c=await dR(St(fR(),"brains-ops-directory-sync-cleanup-")),l=St(c,"content");try{let u=await Cu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),d=await hR(u.dir),p;if(d>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${d} directory-sync stress probes`);let m=(await Xa(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:d,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Yn(St(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
467
467
  `),g}finally{await Xp(c,{recursive:!0,force:!0})}}class S7{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new cR({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await dR(St(fR(),"brains-ops-directory-sync-stress-"));let t=St(this.#r,"content");this.#i=St(this.#r,"id_ed25519"),this.#o=St(this.#r,"known_hosts"),this.#a=await this.#m(),await Yn(this.#i,rEe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Vke(this.#i,384);let r=await this.#b("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await Yn(this.#o,r.stdout,{mode:384});let i=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=i.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await Cu.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await Xa(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let o=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#f();let s=await this.#t.waitForHealthSnapshot(60000);if(!s)throw Error("Smoke health was unavailable before stress testing");return this.#c=`ops/directory-sync-stress-backup-${this.#e.runId}`,await n.run(["push","origin",`HEAD:refs/heads/${this.#c}`]),await this.#t.discoverEndpoints(),await Yn(St(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:Qp(s),version:s.version}},null,2)}
468
468
  `),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Qp(s),version:s.version}}async startMonitoring(){this.#x(),this.#t.start()}async executePhase(e,t){this.#x();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return $u(e,"health did not provide a drained queue before the phase");await v7(r.dir,e),await r.commitAll(`test(directory-sync): stress ${e.id}`),await r.pushMainWithRebase();let s=this.#e.now().getTime(),a=await r.output(["rev-parse","HEAD"]),c=await this.#p(a,900000);if(c===void 0)return $u(e,"runtime did not pull the phase commit");let l;if(e.operation==="rename"){let m=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let y=await this.#t.waitForStableEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-s,!y)return $u(e,`health did not stabilize at ${m} notes`,c,l)}else if(e.operation==="add"||e.operation==="delete"){let m=t.notes+e.targetProbeCount,y=this.#e.now().getTime(),g=await this.#t.waitForEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-y,!g)return $u(e,`health did not reach ${m} notes`,c,l)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let u=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(o.completedImports+u,1200000))return $u(e,`health did not observe ${u} completed import job(s) with a drained queue`,c,l);let p=this.#t.healthSamples.slice(i).find((m)=>!m.ok);if(p)return $u(e,`${p.endpoint} unavailable (${p.status===0?p.error??"unknown":p.status})`,c,l);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:c,...l===void 0?{}:{persistenceLatencyMs:l}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await hR(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await Xa(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=i===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:i,...n?{finalEntities:n.entities,finalNotes:Qp(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await Xa(t.dir)).length,error:ct(r)}}}async stopMonitoring(){await this.#t.stop(),await Yn(St(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
@@ -775,7 +775,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
775
775
  `),o}async function z7(e,t){let r=await Ct(e),i=r.users.find((n)=>n.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:i}}async function N7(e){let t=await dEe(Ii(fEe(),"brains-ops-watchdog-smoke-")),r=Ii(t,"id_ed25519"),i=Ii(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),o=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!o.ok)throw Error(`Hetzner server lookup failed with ${o.status}`);let s=pEe.parse(await o.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await Ou(r,gEe(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await uEe(r,384);let c=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(c.exitCode!==0||!c.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Ou(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await xR(t,{recursive:!0,force:!0}),n}}async function bR(e,t,r){return e.commandRunner("ssh",[...D7(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:SR()})}async function mEe(e,t,r){return e.commandRunner("scp",[...D7(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function D7(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function hEe(e){try{return await lEe(e),!0}catch{return!1}}async function Fx(e,t,r){await Promise.all([Ou(Ii(e,`${t}.stdout.log`),r.stdout),Ou(Ii(e,`${t}.stderr.log`),r.stderr)])}function gEe(e){return`${e.replace(/\r\n/g,`
776
776
  `).replace(/\\n/g,`
777
777
  `).trimEnd()}
778
- `}var O7,pEe;var Hx=x(async()=>{Re();A7();Dn();Gp();await I7();O7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),pEe=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as BN,chmod as BE,mkdir as Zh,readFile as qN,writeFile as jN}from"fs/promises";import{dirname as rX,join as Bc}from"path";import{fileURLToPath as nX}from"url";var tm={name:"@rizom/ops",version:"0.2.0-alpha.518",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun run build && bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};zs();Lc();var iX=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],jE=new Set([".kamal/hooks/pre-deploy"]),oX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),sX=nX(new URL("../templates/rover-pilot/",import.meta.url)),aX=[`service: rover
778
+ `}var O7,pEe;var Hx=x(async()=>{Re();A7();Dn();Gp();await I7();O7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),pEe=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as BN,chmod as BE,mkdir as Zh,readFile as qN,writeFile as jN}from"fs/promises";import{dirname as rX,join as Bc}from"path";import{fileURLToPath as nX}from"url";var tm={name:"@rizom/ops",version:"0.2.0-alpha.519",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun run build && bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};zs();Lc();var iX=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],jE=new Set([".kamal/hooks/pre-deploy"]),oX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),sX=nX(new URL("../templates/rover-pilot/",import.meta.url)),aX=[`service: rover
779
779
  image: <%= ENV['IMAGE_REPOSITORY'] %>
780
780
 
781
781
  servers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rizom/ops",
3
- "version": "0.2.0-alpha.518",
3
+ "version": "0.2.0-alpha.519",
4
4
  "description": "Operator CLI for managing private brain fleet registry repos",
5
5
  "keywords": [
6
6
  "brains",