@rizom/ops 0.2.0-alpha.602 → 0.2.0-alpha.604

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
@@ -418,7 +418,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
418
418
  hash text NOT NULL,
419
419
  created_at numeric
420
420
  )
421
- `;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.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(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var BC;var BK=S(()=>{ze();BC=class BC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Vb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!ap(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 Hn,jK,jC,gSe=()=>({union:ySe,unionAll:bSe,intersect:SSe,except:xSe}),ySe,bSe,SSe,xSe;var UC=S(()=>{ze();BK();no();La();ur();Mn();vr();Dr();to();iu();yp();Hn=class Hn{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(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,ao))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Bb(e);return new jC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};jK=class jK extends BC{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=cp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=cp(t);for(let o of Fn(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"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(gSe()):r;if(!ap(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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};jC=class jC extends jK{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=kn(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()}};yH(jC,[Lr]);ySe=Vb("union",!1),bSe=Vb("union",!0),SSe=Vb("intersect",!1),xSe=Vb("except",!1)});var Ba;var Wb=S(()=>{ze();La();Jb();Mn();UC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,su)?e:void 0,this.dialectConfig=ae(e,su)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new DC(this.dialectConfig);return this.dialect}}});var Gb,qC;var UK=S(()=>{ze();no();ur();io();vr();Dr();iu();Wb();Gb=class Gb{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]=ae(s,Te)?s:new an(s,n[o])}return i});return new qC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!ap(this.table[Nb],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 qC(this.table,t,this.session,this.dialect,this.withList,!0)}};qC=class qC extends Lr{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[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Lb(this.config.table,e.set));return this.config.onConflict.push(U` 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:Fn(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 Qb,qK;var ZK=S(()=>{ze();no();La();io();Mn();vr();Dr();to();iu();yp();Qb=class Qb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new qK(this.table,Lb(this.table,e),this.session,this.dialect,this.withList)}};qK=class qK extends Lr{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=cp(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?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,ao)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({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 bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 ZC=S(()=>{PK();UK();Wb();UC();ZK()});var bp;var MK=S(()=>{ze();ur();bp=class bp extends Te{constructor(e){super(bp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=bp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 FC,Yb,MC;var FK=S(()=>{ze();no();fp();FC=class FC{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 MC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Yb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new MC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Yb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Yb=class Yb extends Lr{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)=>Zb(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()}};MC=class MC extends Yb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var au;var HK=S(()=>{ze();no();au=class au extends Lr{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 Sp;var Xb=S(()=>{ze();La();ur();ZC();Mn();MK();FK();HK();Sp=class Sp{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 FC(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 Ba(r.dialect));return new Proxy(new ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new bp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Qb(a,t.session,t.dialect,e)}function o(a){return new Gb(a,t.session,t.dialect,e)}function s(a){return new Hb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Qb(e,this.session,this.dialect)}$cache;insert(e){return new Gb(e,this.session,this.dialect)}delete(e){return new Hb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.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"?U.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"?U.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"?U.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 HC(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 KK,xp;var KC=S(()=>{ze();KK=class KK{static[J]="Cache"};xp=class xp extends KK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var JK=S(()=>{KC()});function VK(e,t){return new Proxy(e,new Da(t,!1))}var WK=S(()=>{hp()});var GK,JC,VC,WC;var GC=S(()=>{KC();ze();Kb();no();Xb();GK=class GK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};JC=class JC{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||ae(this.cache,xp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new so(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new so(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 so(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new so(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await HC(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 so(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await HC(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 so(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 GK(()=>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)}}};VC=class VC{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 ou({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")}};WC=class WC extends Sp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new PC}}});var QC,wSe,vSe,eS;var QK=S(()=>{ze();La();Dr();Wb();io();yp();QC=class QC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};wSe=class wSe extends QC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};vSe=class vSe extends QC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Bb(gp(e,t))}existing(){return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};eS=class eS extends ao{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var tS=S(()=>{WK();IK();NC();Xb();Jb();vC();CK();OK();ZC();GC();io();kC();iu();QK()});function YK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function rS(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 nS,YC,XK;var XC=S(()=>{JK();ze();jb();ur();tS();GC();Dr();nS=class nS extends VC{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 hC,this.cache=i.cache??new xp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new XK(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 nS(this.client,this.dialect,this.schema,this.options,r),n=new YC("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}};YC=class YC extends WC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new YC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};XK=class XK extends JC{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=sp(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=sp(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)=>YK(r));if(this.customResultMapper)return this.customResultMapper(e,rS);return e.map((r)=>fC(this.fields,Array.prototype.slice.call(r).map((i)=>rS(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=sp(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 YK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,rS);return fC(this.fields,Array.prototype.slice.call(r).map((i)=>rS(i)),this.joinsNotNullableMap)}async values(e){let t=sp(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 cu(e,t={}){let r=new LC({casing:t.casing}),i;if(t.logger===!0)i=new mC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=qH(t.schema,MH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new nS(e,r,n,{logger:i,cache:t.cache},void 0),s=new eJ("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var eJ;var tJ=S(()=>{ze();jb();fp();Xb();Jb();XC();eJ=class eJ extends Sp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function iS(...e){if(typeof e[0]==="string"){let t=Xl({url:e[0]});return cu(t,e[1])}if(bH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return cu(r,i);let n=typeof t==="string"?Xl({url:t}):Xl(t);return cu(n,i)}return cu(e[0],e[1])}var rJ=S(()=>{tC();Dr();tJ();((e)=>{function t(r){return cu({},r)}e.mock=t})(iS||(iS={}))});var nJ=S(()=>{rJ();XC()});function _Se(){return new Promise((e)=>setTimeout(e,0))}function ESe(){if(eR)return;eR=!0,setTimeout(()=>{eR=!1,tR=performance.now()},0)}async function wp(e=kSe){if(ESe(),performance.now()-tR<e)return;await _Se(),tR=performance.now()}var kSe=50,tR,eR=!1;var iJ=S(()=>{tR=performance.now()});function oJ(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function $Se(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function oS(e,t){let r=Date.now()+(t.budgetMs??ISe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!$Se(o))throw o;await t.afterRefusal?.();let s=Math.min(TSe*2**(n-1),ASe),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 rR(e,t={}){let r=Xl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let 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())}};async function u(f,p){return await wp(),oS(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await wp(),oS(()=>a(f,p),l)),r.migrate=async(f)=>(await wp(),oS(()=>c(f),l)),r.transaction=async(f)=>(await wp(),oS(()=>i(f),l))}return r}function sS(e){let{url:t,schema:r}=e,i=oJ(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?rR({url:t,authToken:i},n):rR({url:t},n);return{db:iS(o,{schema:r}),client:o,url:t}}async function aS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var ISe=5000,TSe=5,ASe=40;var nR=S(()=>{tC();nJ();iJ()});var sJ=S(()=>{g$();nR()});var iR=S(()=>{nR();sJ()});var oR=S(()=>{hp();Ob();Zn();ze();Kb();jb();no();fp();zC();Mn();vr();Dr();to()});var ne,pt;var sR=S(()=>{tS();oR();Of();ne=gp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:oo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:oo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:oo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:oo("idx_job_queue_source").on(e.source),rootJobIdx:oo("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:oo("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=gp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:oo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:oo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function aJ(e){return sS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var cJ=S(()=>{iR();sR()});class aR{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()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class cR{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 lR{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===Ue.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=CSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var CSe;var lJ=S(()=>{Ae();as();CSe=d.looseObject({deduplicationKey:d.string().optional()})});class uR{db;transactionClient;databaseUrl;logger;deduplicator=new lR;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??RSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return NSe.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,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.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:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.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(OSe*2**(i-1),PSe),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=at(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=ss){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=ss){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(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(It(Qe(pt.slotId,e),Qe(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(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.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(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.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(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).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(ne).set({status:s?Ue.PENDING:Ue.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(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.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(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.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(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.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:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`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=zSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.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(ne).where(It(xi(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),ru(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ss(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),lp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Ue.PROCESSING),xi(En(ne.attemptId),up(l),ru(ne.leaseExpiresAt,t))),f=VK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),lp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(Ub(ne.type,[...a]),up(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(Ss(ne.type,s),m,xi(It(Qe(ne.status,Ue.PENDING),ru(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(Ss(ne.id,g),qb(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var RSe=2000,OSe=5,PSe=40,zSe,NSe;var uJ=S(()=>{oR();tS();sR();Ae();as();zf();lJ();zSe=d.number().int().min(0).max(1000),NSe=new cR});import{AsyncLocalStorage as DSe}from"async_hooks";class vp{storage=new DSe;static createFresh(){return new vp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=ko.parse(e),n=LSe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function LSe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var dR=S(()=>{ti()});class _p{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new _p(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=aJ(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??vp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new aR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new uR(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 aS(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=Gi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.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:at(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 ko.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{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=ss){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ss){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 dJ=S(()=>{Of();g$();zf();as();iR();cJ();uJ();ti();dR()});var fR=()=>{};var fJ=S(()=>{Of();as();zf();as();fR();dR()});var pJ=S(()=>{as();fR()});var SWe;var mJ=S(()=>{ti();Ae();Pf();SWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var vWe;var hJ=S(()=>{Ae();vWe=d.record(d.string(),d.unknown())});var gJ=S(()=>{ti();Of()});var yJ=S(()=>{dJ();fJ();pJ();mJ();hJ();zf();as();Pf();gJ()});var pR={};Ht(pR,{LEGACY_PROJECTION_JOB_TYPES:()=>SJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>wJ,legacyProjectionJobTypeSchema:()=>xJ,retireLegacyProjectionJob:()=>JSe});import{existsSync as FSe}from"fs";import{resolve as HSe}from"path";function bJ(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 KSe(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 JSe(e){let t=HSe(e.databasePath);if(!FSe(t))throw Error(`Job database does not exist: ${t}`);let r=xJ.parse(e.jobType),i=_p.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(KSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:bJ(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:wJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:bJ(s),retired:!0}}finally{i.close()}}var SJ,xJ,wJ="Retired legacy projection job superseded by scheduler-owned projections";var mR=S(()=>{yJ();Ae();SJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],xJ=d.enum(SJ)});function Yt(e,t,r,i,n){return _J.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function gR(e){return Ep.parse(structuredClone(QSe[e]))}function Ip(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 lS(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(),hR.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 hR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:YSe(c)})}finally{clearTimeout(a)}}async function yR(e,t){let r=Ep.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${cS(c)}`}if(!n)for(let c of r.phases)try{let l=kJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=cS(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=EJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=cS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=IJ.parse(await t.stopMonitoring())}catch(c){let l=cS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=AJ(a,r.maximumExternalAiCalls??0),TJ.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 AJ(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 YSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function cS(e){return at(e)}var kp,vJ,_J,Ep,VSe,hR,WSe,kJ,EJ,GSe,IJ,TJ,QSe;var uS=S(()=>{Ae();kp=d.enum(["regression","load","stress"]),vJ=d.enum(["add","update","rename","delete"]),_J=d.object({id:d.string().min(1),operation:vJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),Ep=d.object({profile:kp,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(_J).min(1)}),VSe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),hR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),WSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),kJ=d.object({id:d.string().min(1),operation:vJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),EJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),GSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),IJ=d.object({health:d.array(hR),runtime:d.array(WSe),externalAiCalls:d.number().int().nonnegative().optional(),container:GSe.optional()}),TJ=d.object({profile:kp,success:d.boolean(),baseline:VSe,phases:d.array(kJ),cleanup:EJ,metrics:IJ,failure:d.string().optional()}),QSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as XSe}from"child_process";async function $J(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var co=async(e,t,r={})=>new Promise((i,n)=>{let o=XSe(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 Tp=()=>{};class lu{#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 lu(e,r,i);return await $J(e,"git",["-c","credential.helper=","-c",`credential.helper=${CJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",CJ]),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 vi("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 CJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var RJ=S(()=>{Tp()});function Ap(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class bR{#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 lS(`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 exe.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||Ap(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await lS(`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 exe;var OJ=S(()=>{Ae();uS();exe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var dS={};Ht(dS,{applyDirectorySyncStressPhase:()=>jJ,cleanupDirectorySyncStress:()=>DJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>UJ,removeProbeFiles:()=>ER,runDeployedDirectorySyncStress:()=>zJ,runStressCommand:()=>co,verifyDirectorySyncStressAccess:()=>NJ});import{chmod as txe,mkdir as xR,mkdtemp as wR,readFile as rxe,readdir as nxe,rename as ixe,rm as Cp,writeFile as Kn}from"fs/promises";import{tmpdir as vR}from"os";import{join as St,resolve as _R}from"path";async function zJ(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=IR(r),n=_R(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await xR(n,{recursive:!0});let{pilot:o,user:s}=await kR(e.rootDir,e.handle);Ip({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=kp.parse(e.profile),c=e.plan?Ep.parse(e.plan):gR(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)BJ(s);let l=oxe.parse(e.env??process.env),u=new LJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??co,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await yR(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:f};return await uxe(p),p}async function NJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=IR(r),n=_R(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await xR(n,{recursive:!0});let{pilot:o,user:s}=await kR(e.rootDir,e.handle);Ip({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),BJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await wR(St(vR(),"brains-ops-directory-sync-access-check-"));try{let l=await lu.clone(e.commandRunner??co,`${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 f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
421
+ `;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.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(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var BC;var BK=S(()=>{ze();BC=class BC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Vb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!ap(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 Hn,jK,jC,gSe=()=>({union:ySe,unionAll:bSe,intersect:SSe,except:xSe}),ySe,bSe,SSe,xSe;var UC=S(()=>{ze();BK();no();La();ur();Mn();vr();Dr();to();iu();yp();Hn=class Hn{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(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,ao))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Bb(e);return new jC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};jK=class jK extends BC{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=cp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=cp(t);for(let o of Fn(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"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(gSe()):r;if(!ap(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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};jC=class jC extends jK{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=kn(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()}};yH(jC,[Lr]);ySe=Vb("union",!1),bSe=Vb("union",!0),SSe=Vb("intersect",!1),xSe=Vb("except",!1)});var Ba;var Wb=S(()=>{ze();La();Jb();Mn();UC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,su)?e:void 0,this.dialectConfig=ae(e,su)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new DC(this.dialectConfig);return this.dialect}}});var Gb,qC;var UK=S(()=>{ze();no();ur();io();vr();Dr();iu();Wb();Gb=class Gb{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]=ae(s,Te)?s:new an(s,n[o])}return i});return new qC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!ap(this.table[Nb],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 qC(this.table,t,this.session,this.dialect,this.withList,!0)}};qC=class qC extends Lr{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[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Lb(this.config.table,e.set));return this.config.onConflict.push(U` 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:Fn(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 Qb,qK;var ZK=S(()=>{ze();no();La();io();Mn();vr();Dr();to();iu();yp();Qb=class Qb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new qK(this.table,Lb(this.table,e),this.session,this.dialect,this.withList)}};qK=class qK extends Lr{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=cp(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?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,ao)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({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 bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 ZC=S(()=>{PK();UK();Wb();UC();ZK()});var bp;var MK=S(()=>{ze();ur();bp=class bp extends Te{constructor(e){super(bp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=bp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 FC,Yb,MC;var FK=S(()=>{ze();no();fp();FC=class FC{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 MC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Yb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new MC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Yb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Yb=class Yb extends Lr{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)=>Zb(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()}};MC=class MC extends Yb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var au;var HK=S(()=>{ze();no();au=class au extends Lr{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 Sp;var Xb=S(()=>{ze();La();ur();ZC();Mn();MK();FK();HK();Sp=class Sp{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 FC(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 Ba(r.dialect));return new Proxy(new ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new bp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Qb(a,t.session,t.dialect,e)}function o(a){return new Gb(a,t.session,t.dialect,e)}function s(a){return new Hb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Qb(e,this.session,this.dialect)}$cache;insert(e){return new Gb(e,this.session,this.dialect)}delete(e){return new Hb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.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"?U.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"?U.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"?U.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 HC(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 KK,xp;var KC=S(()=>{ze();KK=class KK{static[J]="Cache"};xp=class xp extends KK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var JK=S(()=>{KC()});function VK(e,t){return new Proxy(e,new Da(t,!1))}var WK=S(()=>{hp()});var GK,JC,VC,WC;var GC=S(()=>{KC();ze();Kb();no();Xb();GK=class GK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};JC=class JC{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||ae(this.cache,xp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new so(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new so(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 so(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new so(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await HC(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 so(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await HC(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 so(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 GK(()=>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)}}};VC=class VC{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 ou({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")}};WC=class WC extends Sp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new PC}}});var QC,wSe,vSe,eS;var QK=S(()=>{ze();La();Dr();Wb();io();yp();QC=class QC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};wSe=class wSe extends QC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};vSe=class vSe extends QC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Bb(gp(e,t))}existing(){return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new eS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};eS=class eS extends ao{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var tS=S(()=>{WK();IK();NC();Xb();Jb();vC();CK();OK();ZC();GC();io();kC();iu();QK()});function YK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function rS(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 nS,YC,XK;var XC=S(()=>{JK();ze();jb();ur();tS();GC();Dr();nS=class nS extends VC{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 hC,this.cache=i.cache??new xp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new XK(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 nS(this.client,this.dialect,this.schema,this.options,r),n=new YC("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}};YC=class YC extends WC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new YC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};XK=class XK extends JC{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=sp(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=sp(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)=>YK(r));if(this.customResultMapper)return this.customResultMapper(e,rS);return e.map((r)=>fC(this.fields,Array.prototype.slice.call(r).map((i)=>rS(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=sp(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 YK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,rS);return fC(this.fields,Array.prototype.slice.call(r).map((i)=>rS(i)),this.joinsNotNullableMap)}async values(e){let t=sp(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 cu(e,t={}){let r=new LC({casing:t.casing}),i;if(t.logger===!0)i=new mC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=qH(t.schema,MH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new nS(e,r,n,{logger:i,cache:t.cache},void 0),s=new eJ("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var eJ;var tJ=S(()=>{ze();jb();fp();Xb();Jb();XC();eJ=class eJ extends Sp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function iS(...e){if(typeof e[0]==="string"){let t=Xl({url:e[0]});return cu(t,e[1])}if(bH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return cu(r,i);let n=typeof t==="string"?Xl({url:t}):Xl(t);return cu(n,i)}return cu(e[0],e[1])}var rJ=S(()=>{tC();Dr();tJ();((e)=>{function t(r){return cu({},r)}e.mock=t})(iS||(iS={}))});var nJ=S(()=>{rJ();XC()});function _Se(){return new Promise((e)=>setTimeout(e,0))}function ESe(){if(eR)return;eR=!0,setTimeout(()=>{eR=!1,tR=performance.now()},0)}async function wp(e=kSe){if(ESe(),performance.now()-tR<e)return;await _Se(),tR=performance.now()}var kSe=50,tR,eR=!1;var iJ=S(()=>{tR=performance.now()});function oJ(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function $Se(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function oS(e,t){let r=Date.now()+(t.budgetMs??ISe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!$Se(o))throw o;await t.afterRefusal?.();let s=Math.min(TSe*2**(n-1),ASe),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 rR(e,t={}){let r=Xl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let 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())}};async function u(f,p){return await wp(),oS(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await wp(),oS(()=>a(f,p),l)),r.migrate=async(f)=>(await wp(),oS(()=>c(f),l)),r.transaction=async(f)=>(await wp(),oS(()=>i(f),l))}return r}function sS(e){let{url:t,schema:r}=e,i=oJ(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?rR({url:t,authToken:i},n):rR({url:t},n);return{db:iS(o,{schema:r}),client:o,url:t}}async function aS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var ISe=5000,TSe=5,ASe=40;var nR=S(()=>{tC();nJ();iJ()});var sJ=S(()=>{g$();nR()});var iR=S(()=>{nR();sJ()});var oR=S(()=>{hp();Ob();Zn();ze();Kb();jb();no();fp();zC();Mn();vr();Dr();to()});var ne,pt;var sR=S(()=>{tS();oR();Of();ne=gp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:oo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:oo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:oo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:oo("idx_job_queue_source").on(e.source),rootJobIdx:oo("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:oo("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=gp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:oo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:oo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function aJ(e){return sS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var cJ=S(()=>{iR();sR()});class aR{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()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class cR{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 lR{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===Ue.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=CSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var CSe;var lJ=S(()=>{Ae();as();CSe=d.looseObject({deduplicationKey:d.string().optional()})});class uR{db;transactionClient;databaseUrl;logger;deduplicator=new lR;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??RSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return NSe.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,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.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:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.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(OSe*2**(i-1),PSe),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=at(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=ss){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=ss){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(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(It(Qe(pt.slotId,e),Qe(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(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.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(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.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(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).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(ne).set({status:s?Ue.PENDING:Ue.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(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.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(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.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(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.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:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`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=zSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.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(ne).where(It(xi(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),ru(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ss(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),lp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Ue.PROCESSING),xi(En(ne.attemptId),up(l),ru(ne.leaseExpiresAt,t))),f=VK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),lp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(Ub(ne.type,[...a]),up(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(Ss(ne.type,s),m,xi(It(Qe(ne.status,Ue.PENDING),ru(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(Ss(ne.id,g),qb(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var RSe=2000,OSe=5,PSe=40,zSe,NSe;var uJ=S(()=>{oR();tS();sR();Ae();as();zf();lJ();zSe=d.number().int().min(0).max(1000),NSe=new cR});import{AsyncLocalStorage as DSe}from"async_hooks";class vp{storage=new DSe;static createFresh(){return new vp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=ko.parse(e),n=LSe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function LSe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var dR=S(()=>{ti()});class _p{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new _p(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=aJ(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??vp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new aR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new uR(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 aS(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=Gi(),c=i?.rootJobId??(i?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.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:at(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 ko.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{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=ss){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ss){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 dJ=S(()=>{Of();g$();zf();as();iR();cJ();uJ();ti();dR()});var fR=()=>{};var fJ=S(()=>{Of();as();zf();as();fR();dR()});var pJ=S(()=>{as();fR()});var SWe;var mJ=S(()=>{ti();Ae();Pf();SWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var vWe;var hJ=S(()=>{Ae();vWe=d.record(d.string(),d.unknown())});var gJ=S(()=>{ti();Of()});var yJ=S(()=>{dJ();fJ();pJ();mJ();hJ();zf();as();Pf();gJ()});var pR={};Ht(pR,{LEGACY_PROJECTION_JOB_TYPES:()=>SJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>wJ,legacyProjectionJobTypeSchema:()=>xJ,retireLegacyProjectionJob:()=>JSe});import{existsSync as FSe}from"fs";import{resolve as HSe}from"path";function bJ(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 KSe(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 JSe(e){let t=HSe(e.databasePath);if(!FSe(t))throw Error(`Job database does not exist: ${t}`);let r=xJ.parse(e.jobType),i=_p.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(KSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:bJ(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:wJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:bJ(s),retired:!0}}finally{i.close()}}var SJ,xJ,wJ="Retired legacy projection job superseded by scheduler-owned projections";var mR=S(()=>{yJ();Ae();SJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],xJ=d.enum(SJ)});function Yt(e,t,r,i,n){return _J.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function gR(e){return Ep.parse(structuredClone(QSe[e]))}function Ip(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 lS(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(),hR.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 hR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:YSe(c)})}finally{clearTimeout(a)}}async function yR(e,t){let r=Ep.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${cS(c)}`}if(!n)for(let c of r.phases)try{let l=kJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=cS(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=EJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=cS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=IJ.parse(await t.stopMonitoring())}catch(c){let l=cS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=AJ(a,r.maximumExternalAiCalls??0),TJ.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 AJ(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 YSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function cS(e){return at(e)}var kp,vJ,_J,Ep,VSe,hR,WSe,kJ,EJ,GSe,IJ,TJ,QSe;var uS=S(()=>{Ae();kp=d.enum(["regression","load","stress"]),vJ=d.enum(["add","update","rename","delete"]),_J=d.object({id:d.string().min(1),operation:vJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),Ep=d.object({profile:kp,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(_J).min(1)}),VSe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),hR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),WSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),kJ=d.object({id:d.string().min(1),operation:vJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),EJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),GSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),IJ=d.object({health:d.array(hR),runtime:d.array(WSe),externalAiCalls:d.number().int().nonnegative().optional(),container:GSe.optional()}),TJ=d.object({profile:kp,success:d.boolean(),baseline:VSe,phases:d.array(kJ),cleanup:EJ,metrics:IJ,failure:d.string().optional()}),QSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as XSe}from"child_process";async function $J(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var co=async(e,t,r={})=>new Promise((i,n)=>{let o=XSe(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 Tp=()=>{};class lu{#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 lu(e,r,i);return await $J(e,"git",["-c","credential.helper=","-c",`credential.helper=${CJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",CJ]),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 vi("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 CJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var RJ=S(()=>{Tp()});function Ap(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class bR{#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 lS(`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 exe.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||Ap(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await lS(`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 exe;var OJ=S(()=>{Ae();uS();exe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var dS={};Ht(dS,{applyDirectorySyncStressPhase:()=>jJ,cleanupDirectorySyncStress:()=>DJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>UJ,removeProbeFiles:()=>ER,runDeployedDirectorySyncStress:()=>zJ,runStressCommand:()=>co,verifyDirectorySyncStressAccess:()=>NJ});import{chmod as txe,mkdir as xR,mkdtemp as wR,readFile as rxe,readdir as nxe,rename as ixe,rm as Cp,writeFile as Kn}from"fs/promises";import{tmpdir as vR}from"os";import{join as St,resolve as _R}from"path";async function zJ(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=IR(r),n=_R(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await xR(n,{recursive:!0});let{pilot:o,user:s}=await kR(e.rootDir,e.handle);Ip({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=kp.parse(e.profile),c=e.plan?Ep.parse(e.plan):gR(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)BJ(s);let l=oxe.parse(e.env??process.env),u=new LJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??co,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await yR(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:f};return await uxe(p),p}async function NJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=IR(r),n=_R(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await xR(n,{recursive:!0});let{pilot:o,user:s}=await kR(e.rootDir,e.handle);Ip({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),BJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await wR(St(vR(),"brains-ops-directory-sync-access-check-"));try{let l=await lu.clone(e.commandRunner??co,`${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 f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
422
422
  `),f}finally{await Cp(c,{recursive:!0,force:!0})}}async function DJ(e){let t=e.now??(()=>new Date),r=_R(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`cleanup-${IR(t().toISOString())}`));await xR(r,{recursive:!0});let{pilot:i,user:n}=await kR(e.rootDir,e.handle);Ip({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??co,a=e.logger??console.info,c=await wR(St(vR(),"brains-ops-directory-sync-cleanup-")),l=St(c,"content");try{let u=await lu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),f=await ER(u.dir),p;if(f>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${f} directory-sync stress probes`);let m=(await ja(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:f,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Kn(St(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
423
423
  `),g}finally{await Cp(c,{recursive:!0,force:!0})}}class LJ{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new bR({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await wR(St(vR(),"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 Kn(this.#i,lxe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await txe(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 Kn(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 lu.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await ja(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 Kn(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:Ap(s),version:s.version}},null,2)}
424
424
  `),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Ap(s),version:s.version}}async startMonitoring(){this.#S(),this.#t.start()}async executePhase(e,t){this.#S();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 uu(e,"health did not provide a drained queue before the phase");await jJ(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 uu(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 uu(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 uu(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 uu(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 uu(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 ER(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await ja(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:Ap(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 ja(t.dir)).length,error:at(r)}}}async stopMonitoring(){await this.#t.stop(),await Kn(St(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
@@ -731,7 +731,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
731
731
  `),o}async function QJ(e,t){let r=await xt(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 YJ(e){let t=await bxe(_i(Sxe(),"brains-ops-watchdog-smoke-")),r=_i(t,"id_ed25519"),i=_i(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=xxe.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 du(r,_xe(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await yxe(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 du(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await $R(t,{recursive:!0,force:!0}),n}}async function AR(e,t,r){return e.commandRunner("ssh",[...XJ(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:CR()})}async function wxe(e,t,r){return e.commandRunner("scp",[...XJ(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function XJ(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function vxe(e){try{return await gxe(e),!0}catch{return!1}}async function fS(e,t,r){await Promise.all([du(_i(e,`${t}.stdout.log`),r.stdout),du(_i(e,`${t}.stderr.log`),r.stderr)])}function _xe(e){return`${e.replace(/\r\n/g,`
732
732
  `).replace(/\\n/g,`
733
733
  `).trimEnd()}
734
- `}var VJ,xxe;var mS=S(async()=>{Ae();FJ();un();Tp();await MJ();VJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),xxe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as VN,chmod as sE,mkdir as xh,readFile as GN,writeFile as WN}from"fs/promises";import{dirname as PG,join as Tc}from"path";import{fileURLToPath as zG}from"url";var Op={name:"@rizom/ops",version:"0.2.0-alpha.602",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/auth-service":"workspace:*","@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 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"};ks();Ic();var NG=["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"],aE=new Set([".kamal/hooks/pre-deploy"]),DG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),LG=zG(new URL("../templates/rover-pilot/",import.meta.url)),BG=[`service: rover
734
+ `}var VJ,xxe;var mS=S(async()=>{Ae();FJ();un();Tp();await MJ();VJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),xxe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as VN,chmod as sE,mkdir as xh,readFile as GN,writeFile as WN}from"fs/promises";import{dirname as PG,join as Tc}from"path";import{fileURLToPath as zG}from"url";var Op={name:"@rizom/ops",version:"0.2.0-alpha.604",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/auth-service":"workspace:*","@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 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"};ks();Ic();var NG=["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"],aE=new Set([".kamal/hooks/pre-deploy"]),DG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),LG=zG(new URL("../templates/rover-pilot/",import.meta.url)),BG=[`service: rover
735
735
  image: <%= ENV['IMAGE_REPOSITORY'] %>
736
736
 
737
737
  servers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rizom/ops",
3
- "version": "0.2.0-alpha.602",
3
+ "version": "0.2.0-alpha.604",
4
4
  "description": "Operator CLI for managing private brain fleet registry repos",
5
5
  "keywords": [
6
6
  "brains",