@rizom/ops 0.2.0-alpha.492 → 0.2.0-alpha.493
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/brains-ops.js +4 -4
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -462,7 +462,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
462
462
|
hash text NOT NULL,
|
|
463
463
|
created_at numeric
|
|
464
464
|
)
|
|
465
|
-
`;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var CO;var xV=x(()=>{De();CO=class CO{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ix(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Rp(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 Yn,SV,$O,cke=()=>({union:lke,unionAll:uke,intersect:dke,except:fke}),lke,uke,dke,fke;var OO=x(()=>{De();xV();lo();Va();pr();Gn();Ir();Ur();so();_u();qp();Yn=class Yn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,Te))r={};else r=mx(e);return new $O({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};SV=class SV extends CO{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=Pp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Qn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=Pp(t);for(let o of Qn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,Te)){let o=ce(t,vt)?t._.selectedFields:ce(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(cke()):r;if(!Rp(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(...Qn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Qn(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}};$O=class $O extends SV{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=On(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()}};QJ($O,[Mr]);lke=Ix("union",!1),uke=Ix("union",!0),dke=Ix("intersect",!1),fke=Ix("except",!1)});var Ga;var Ax=x(()=>{De();Va();Ex();Gn();OO();Ga=class Ga{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,Eu)?e:void 0,this.dialectConfig=ce(e,Eu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Cp(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 Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new AO(this.dialectConfig);return this.dialect}}});var Tx,RO;var wV=x(()=>{De();lo();pr();uo();Ir();Ur();_u();Ax();Tx=class Tx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,Te)?s:new mn(s,n[o])}return i});return new RO(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ga):e;if(!ce(t,Te)&&!Rp(this.table[dx],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new RO(this.table,t,this.session,this.dialect,this.withList,!0)}};RO=class RO extends Mr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=On(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,px(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Qn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Cx,vV;var _V=x(()=>{De();lo();Va();uo();Gn();Ir();Ur();so();_u();qp();Cx=class Cx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new vV(this.table,px(this.table,e),this.session,this.dialect,this.withList)}};vV=class vV extends Mr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=Pp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Mt)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new 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[Mt.Symbol.Columns]){return this.config.returning=On(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:Qn(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 PO=x(()=>{mV();wV();Ax();OO();_V()});var Up;var kV=x(()=>{De();pr();Up=class Up extends Te{constructor(e){super(Up.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Up.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var NO,$x,zO;var EV=x(()=>{De();lo();Np();NO=class NO{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 zO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new zO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};$x=class $x extends Mr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>xx(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};zO=class zO extends $x{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Iu;var IV=x(()=>{De();lo();Iu=class Iu extends Mr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Mp;var Ox=x(()=>{De();Va();pr();PO();Gn();kV();EV();IV();Mp=class Mp{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 NO(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 Ga(r.dialect));return new Proxy(new Cp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Up({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Cx(a,t.session,t.dialect,e)}function o(a){return new Tx(a,t.session,t.dialect,e)}function s(a){return new _x(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Cx(e,this.session,this.dialect)}$cache;insert(e){return new Tx(e,this.session,this.dialect)}delete(e){return new _x(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(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 DO(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 AV,Fp;var LO=x(()=>{De();AV=class AV{static[J]="Cache"};Fp=class Fp extends AV{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var TV=x(()=>{LO()});var CV=()=>{};var $V,BO,jO,qO;var UO=x(()=>{LO();De();kx();lo();Ox();$V=class $V extends Mr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};BO=class BO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Fp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await DO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await DO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new $V(()=>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)}}};jO=class jO{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 ku({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")}};qO=class qO extends Mp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new kO}}});var MO,pke,mke,Rx;var OV=x(()=>{De();Va();Ur();Ax();uo();qp();MO=class MO{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};pke=class pke extends MO{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ga);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};mke=class mke extends MO{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=mx(jp(e,t))}existing(){return new Proxy(new Rx({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 Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Rx=class Rx extends po{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var FO=x(()=>{CV();aV();IO();Ox();Ex();pO();dV();pV();PO();UO();uo();hO();_u();OV()});function RV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Px(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var zx,ZO,PV;var HO=x(()=>{TV();De();hx();pr();FO();UO();Ur();zx=class zx extends jO{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 sO,this.cache=i.cache??new Fp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new PV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new zx(this.client,this.dialect,this.schema,this.options,r),n=new ZO("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}};ZO=class ZO extends qO{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new ZO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};PV=class PV extends BO{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=Op(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=Op(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)=>RV(r));if(this.customResultMapper)return this.customResultMapper(e,Px);return e.map((r)=>nO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Op(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 RV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Px);return nO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap)}async values(e){let t=Op(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 Au(e,t={}){let r=new TO({casing:t.casing}),i;if(t.logger===!0)i=new oO;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=v9(t.schema,k9);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new zx(e,r,n,{logger:i,cache:t.cache},void 0),s=new zV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var zV;var NV=x(()=>{De();hx();Np();Ox();Ex();HO();zV=class zV extends Mp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Nx(...e){if(typeof e[0]==="string"){let t=bu({url:e[0]});return Au(t,e[1])}if(YJ(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Au(r,i);let n=typeof t==="string"?bu({url:t}):bu(t);return Au(n,i)}return Au(e[0],e[1])}var DV=x(()=>{K$();Ur();NV();((e)=>{function t(r){return Au({},r)}e.mock=t})(Nx||(Nx={}))});var LV=x(()=>{DV();HO()});function BV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function bke(e){return e instanceof je&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Zp(e,t){let r=Date.now()+(t.budgetMs??hke),i=async(n)=>{if(t.isClosed())throw new je("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!bke(o))throw o;await t.afterRefusal?.();let s=Math.min(gke*2**(n-1),yke),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 KO(e,t={}){let r=bu({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(d,p){return Zp(()=>typeof d==="string"?s(d,p):s(d),{isClosed:n,budgetMs:o})},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(d,p)=>Zp(()=>a(d,p),l),r.migrate=(d)=>Zp(()=>c(d),l),r.transaction=(d)=>Zp(()=>i(d),l)}return r}function Dx(e){let{url:t,schema:r}=e,i=BV(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?KO({url:t,authToken:i},n):KO({url:t},n);return{db:Nx(o,{schema:r}),client:o,url:t}}async function Lx(e,t){if(!t.startsWith("file:"))return;let r=()=>e.closed===!0;for(let i of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await Zp(()=>e.execute(i),{isClosed:r})}var hke=5000,gke=5,yke=40;var JO=x(()=>{K$();LV()});var jV=x(()=>{a$();JO()});var VO=x(()=>{JO();jV()});var oe,ft;var WO=x(()=>{FO();np();oe=jp("job_queue",{id:mr("id").primaryKey().$defaultFn(()=>to()),type:mr("type").notNull(),data:mr("data").notNull(),result:mr("result",{mode:"json"}),progress:mr("progress",{mode:"json"}).$type(),source:mr("source"),metadata:mr("metadata",{mode:"json"}).$type().notNull(),status:mr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:Ar("priority").notNull().default(0),retryCount:Ar("retryCount").notNull().default(0),maxRetries:Ar("maxRetries").notNull().default(3),lastError:mr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:mr("attemptId"),workerSlotId:mr("workerSlotId"),workerSessionId:mr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Wa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Wa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Wa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Wa("idx_job_queue_source").on(e.source)})),ft=jp("job_worker_sessions",{slotId:mr("slotId").primaryKey(),sessionId:mr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Wa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Wa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function qV(e){return Dx({url:e.url,schema:{jobQueue:oe,jobWorkerSessions:ft},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var UV=x(()=>{VO();WO()});class GO{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var MV=x(()=>{Sx();cx();Wn();De();kx();hx();lo();Np();EO();Gn();Ir();Ur();so()});class QO{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 YO{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===He.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=xke.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var xke;var FV=x(()=>{Re();gs();xke=f.looseObject({deduplicationKey:f.string().optional()})});class XO{db;transactionClient;databaseUrl;logger;deduplicator=new YO;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??Ske}async insert(e){await this.write("insert",async()=>this.db.insert(oe).values(e))}async enqueueAtomic(e){return kke.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[He.FAILED,"Replaced by newer job",p,p,d.id,He.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,He.PENDING,He.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==He.PENDING&&r!==He.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(wke*2**(i-1),vke),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=hs){let n=r+i;await this.write("start worker session",async()=>this.db.insert(ft).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:ft.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=hs){return(await this.write("heartbeat worker session",async()=>this.db.update(ft).set({heartbeatAt:r,expiresAt:r+i}).where(Nt(et(ft.slotId,e),et(ft.sessionId,t))).returning({slotId:ft.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(ft).where(Nt(et(ft.slotId,e),et(ft.sessionId,t))).returning({slotId:ft.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(oe).set({status:He.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(oe).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(oe).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(oe).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:oe.retryCount,maxRetries:oe.maxRetries,type:oe.type,scheduledFor:oe.scheduledFor,startedAt:oe.startedAt,runtimeUpdatedAt:oe.runtimeUpdatedAt}).from(oe).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(oe).set({status:s?He.PENDING:He.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Nt(this.attemptWriteGuard(e,r),et(oe.retryCount,o.retryCount))).returning({id:oe.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(oe).set({status:He.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Nt(et(oe.id,e.jobId),et(oe.type,e.expectedType),ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)),Rn(oe.attemptId),Rn(oe.workerSlotId),Rn(oe.workerSessionId),Rn(oe.leaseExpiresAt),Rn(oe.attemptHeartbeatAt),Rn(oe.progress),Rn(oe.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(oe).where(et(oe.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(oe).where(q`json_extract(${oe.metadata}, '$.rootJobId') = ${e}`).orderBy(co(oe.createdAt),co(oe.id))}async getStatusByEntityId(e){return(await this.db.select().from(oe).where(q`json_extract(${oe.data}, '$.id') = ${e}`).orderBy(Ja(oe.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:oe.type,status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.type,oe.status),this.db.select({oldestPendingAt:q`min(case when ${oe.status} = ${He.PENDING} then ${oe.createdAt} end)`,duePending:q`coalesce(sum(case when ${oe.status} = ${He.PENDING} and ${oe.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${oe.status} = ${He.PENDING} and ${oe.scheduledFor} <= ${e} then ${oe.scheduledFor} end)`,latestClaimAt:q`max(${oe.startedAt})`,oldestProcessingAt:q`min(case when ${oe.status} = ${He.PROCESSING} then ${oe.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${oe.status} = ${He.PROCESSING} and ${oe.leaseExpiresAt} is not null and ${oe.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(oe),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${ft.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${ft.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${ft.heartbeatAt})`}).from(ft)]),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=_ke.parse(t);if(r===0)return[];return(await this.db.select().from(oe).where(q`(${oe.runtimeUpdatedAt}, ${oe.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(oe.runtimeUpdatedAt),co(oe.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(oe).where(Nt(ao(et(oe.status,He.COMPLETED),et(oe.status,He.FAILED)),wu(oe.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)),r=e&&e.length>0?Nt(t,Ts(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ts(oe.type,e):void 0;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt)).limit(t)}async getFailedJobs(e){let t=et(oe.status,He.FAILED),r=e&&e.length>0?Nt(t,Ts(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:ft.slotId}).from(ft).where(Nt(et(ft.slotId,i),et(ft.sessionId,n),gx(ft.expiresAt,t))),c=this.db.select({slotId:ft.slotId}).from(ft).where(Nt(et(ft.slotId,oe.workerSlotId),et(ft.sessionId,oe.workerSessionId))),l=Nt(et(oe.status,He.PROCESSING),ao(Rn(oe.attemptId),bx(c),wu(oe.leaseExpiresAt,t))),u=q`${oe.status} = ${He.PROCESSING} AND ${oe.retryCount} + 1 > ${oe.maxRetries}`,d=this.db.select({id:oe.id}).from(oe).where(Nt(Ts(oe.type,s),ao(Nt(et(oe.status,He.PENDING),wu(oe.scheduledFor,t)),l))).orderBy(co(oe.priority),co(oe.createdAt)).limit(1),m=(await this.write("claim",async()=>this.db.update(oe).set({status:q`CASE WHEN ${u} THEN ${He.FAILED} ELSE ${He.PROCESSING} END`,retryCount:q`CASE WHEN ${oe.status} = ${He.PROCESSING} THEN ${oe.retryCount} + 1 ELSE ${oe.retryCount} END`,lastError:q`CASE WHEN ${oe.status} = ${He.PROCESSING} THEN 'Attempt lease expired' ELSE ${oe.lastError} END`,startedAt:q`CASE WHEN ${u} THEN ${oe.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${u} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${u} THEN ${oe.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${u} THEN ${oe.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${u} THEN ${oe.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${u} THEN ${oe.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${u} THEN ${oe.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${u} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${oe.runtimeUpdatedAt} END`}).where(Nt(Ts(oe.id,d),yx(a))).returning()))[0];if(m?.status!==He.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:m.id,attemptId:m.attemptId,workerSlotId:i,workerSessionId:n}),m}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${oe.runtimeUpdatedAt}) from ${oe}), 0) + 1)`}attemptWriteGuard(e,t){return t?Nt(et(oe.id,e),et(oe.status,He.PROCESSING),et(oe.attemptId,t)):Nt(et(oe.id,e),Rn(oe.attemptId),ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)))}}var Ske=2000,wke=5,vke=40,_ke,kke;var ZV=x(()=>{MV();WO();Re();gs();op();FV();_ke=f.number().int().min(0).max(1000),kke=new QO});import{AsyncLocalStorage as Eke}from"async_hooks";class Hp{storage=new Eke;static createFresh(){return new Hp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Ro.parse(e),n=Ike(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Ike(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var eR=x(()=>{Po()});class Kp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Kp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=qV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Hp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new GO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new XO(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 Lx(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:He.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 Ro.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=hs){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=hs){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 HV=x(()=>{np();a$();op();gs();VO();UV();ZV();Po();eR()});var tR=()=>{};var KV=x(()=>{np();gs();op();gs();tR();eR()});var JV=x(()=>{gs();tR()});var Wet;var VV=x(()=>{Po();Re();ip();Wet=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var Yet;var WV=x(()=>{Re();Yet=f.record(f.string(),f.unknown())});var GV=x(()=>{Po();np()});var QV=x(()=>{HV();KV();JV();VV();WV();op();gs();ip();GV()});var rR={};tr(rR,{LEGACY_PROJECTION_JOB_TYPES:()=>XV,LEGACY_PROJECTION_RETIREMENT_REASON:()=>t7,legacyProjectionJobTypeSchema:()=>e7,retireLegacyProjectionJob:()=>Nke});import{existsSync as Rke}from"fs";import{resolve as Pke}from"path";function YV(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 zke(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 Nke(e){let t=Pke(e.databasePath);if(!Rke(t))throw Error(`Job database does not exist: ${t}`);let r=e7.parse(e.jobType),i=Kp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(zke(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:YV(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:t7,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:YV(s),retired:!0}}finally{i.close()}}var XV,e7,t7="Retired legacy projection job superseded by scheduler-owned projections";var nR=x(()=>{QV();Re();XV=["conversation-memory:project","skill:project","swot:derive","topic:project"],e7=f.enum(XV)});function er(e,t,r,i,n){return n7.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function oR(e){return Vp.parse(structuredClone(jke[e]))}function Wp(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function jx(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(),iR.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 iR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:qke(c)})}finally{clearTimeout(a)}}async function sR(e,t){let r=Vp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${Bx(c)}`}if(!n)for(let c of r.phases)try{let l=i7.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=Bx(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=o7.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=Bx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=s7.parse(await t.stopMonitoring())}catch(c){let l=Bx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=c7(a,r.maximumExternalAiCalls??0),a7.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 c7(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 qke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Bx(e){return at(e)}var Jp,r7,n7,Vp,Dke,iR,Lke,i7,o7,Bke,s7,a7,jke;var qx=x(()=>{Re();Jp=f.enum(["regression","load","stress"]),r7=f.enum(["add","update","rename","delete"]),n7=f.object({id:f.string().min(1),operation:r7,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Vp=f.object({profile:Jp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(n7).min(1)}),Dke=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),iR=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),Lke=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),i7=f.object({id:f.string().min(1),operation:r7,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),o7=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),Bke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),s7=f.object({health:f.array(iR),runtime:f.array(Lke),externalAiCalls:f.number().int().nonnegative().optional(),container:Bke.optional()}),a7=f.object({profile:Jp,success:f.boolean(),baseline:Dke,phases:f.array(i7),cleanup:o7,metrics:s7,failure:f.string().optional()}),jke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as Uke}from"child_process";async function l7(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=Uke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Gp=()=>{};class Tu{#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 Tu(e,r,i);return await l7(e,"git",["-c","credential.helper=","-c",`credential.helper=${u7}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",u7]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Ei("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var u7='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var d7=x(()=>{Gp()});function Qp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class aR{#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 jx(`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 Mke.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Qp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await jx(`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 Mke;var f7=x(()=>{Re();qx();Mke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Ux={};tr(Ux,{applyDirectorySyncStressPhase:()=>x7,cleanupDirectorySyncStress:()=>g7,listProbeFiles:()=>Qa,parseStressRuntimeSample:()=>S7,removeProbeFiles:()=>mR,runDeployedDirectorySyncStress:()=>m7,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>h7});import{chmod as Fke,mkdir as lR,mkdtemp as uR,readFile as Zke,readdir as Hke,rename as Kke,rm as Xp,writeFile as Xn}from"fs/promises";import{tmpdir as dR}from"os";import{join as xt,resolve as fR}from"path";async function m7(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=hR(r),n=fR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",i));await lR(n,{recursive:!0});let{pilot:o,user:s}=await pR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Jp.parse(e.profile),c=e.plan?Vp.parse(e.plan):oR(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)b7(s);let l=Jke.parse(e.env??process.env),u=new y7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await sR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await Yke(p),p}async function h7(e){let r=(e.now??(()=>new Date))().toISOString(),i=hR(r),n=fR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`access-check-${i}`));await lR(n,{recursive:!0});let{pilot:o,user:s}=await pR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),b7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await uR(xt(dR(),"brains-ops-directory-sync-access-check-"));try{let l=await Tu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,xt(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Xn(xt(n,"access-check.json"),`${JSON.stringify(d,null,2)}
|
|
465
|
+
`;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var CO;var xV=x(()=>{De();CO=class CO{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ix(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Rp(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 Yn,SV,$O,cke=()=>({union:lke,unionAll:uke,intersect:dke,except:fke}),lke,uke,dke,fke;var OO=x(()=>{De();xV();lo();Va();pr();Gn();Ir();Ur();so();_u();qp();Yn=class Yn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,Te))r={};else r=mx(e);return new $O({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};SV=class SV extends CO{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=Pp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Qn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=Pp(t);for(let o of Qn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,Te)){let o=ce(t,vt)?t._.selectedFields:ce(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(cke()):r;if(!Rp(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(...Qn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Qn(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}};$O=class $O extends SV{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=On(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()}};QJ($O,[Mr]);lke=Ix("union",!1),uke=Ix("union",!0),dke=Ix("intersect",!1),fke=Ix("except",!1)});var Ga;var Ax=x(()=>{De();Va();Ex();Gn();OO();Ga=class Ga{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,Eu)?e:void 0,this.dialectConfig=ce(e,Eu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Cp(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 Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new AO(this.dialectConfig);return this.dialect}}});var Tx,RO;var wV=x(()=>{De();lo();pr();uo();Ir();Ur();_u();Ax();Tx=class Tx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,Te)?s:new mn(s,n[o])}return i});return new RO(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ga):e;if(!ce(t,Te)&&!Rp(this.table[dx],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new RO(this.table,t,this.session,this.dialect,this.withList,!0)}};RO=class RO extends Mr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Mt.Symbol.Columns]){return this.config.returning=On(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,px(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Qn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Cx,vV;var _V=x(()=>{De();lo();Va();uo();Gn();Ir();Ur();so();_u();qp();Cx=class Cx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new vV(this.table,px(this.table,e),this.session,this.dialect,this.withList)}};vV=class vV extends Mr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=Pp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Mt)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new 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[Mt.Symbol.Columns]){return this.config.returning=On(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:Qn(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 PO=x(()=>{mV();wV();Ax();OO();_V()});var Up;var kV=x(()=>{De();pr();Up=class Up extends Te{constructor(e){super(Up.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Up.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var NO,$x,zO;var EV=x(()=>{De();lo();Np();NO=class NO{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 zO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new zO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new $x(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};$x=class $x extends Mr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>xx(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};zO=class zO extends $x{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Iu;var IV=x(()=>{De();lo();Iu=class Iu extends Mr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Mp;var Ox=x(()=>{De();Va();pr();PO();Gn();kV();EV();IV();Mp=class Mp{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 NO(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 Ga(r.dialect));return new Proxy(new Cp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Up({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Cx(a,t.session,t.dialect,e)}function o(a){return new Tx(a,t.session,t.dialect,e)}function s(a){return new _x(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Cx(e,this.session,this.dialect)}$cache;insert(e){return new Tx(e,this.session,this.dialect)}delete(e){return new _x(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new Iu(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 DO(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 AV,Fp;var LO=x(()=>{De();AV=class AV{static[J]="Cache"};Fp=class Fp extends AV{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var TV=x(()=>{LO()});var CV=()=>{};var $V,BO,jO,qO;var UO=x(()=>{LO();De();kx();lo();Ox();$V=class $V extends Mr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};BO=class BO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Fp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await DO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await DO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new $V(()=>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)}}};jO=class jO{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 ku({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")}};qO=class qO extends Mp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new kO}}});var MO,pke,mke,Rx;var OV=x(()=>{De();Va();Ur();Ax();uo();qp();MO=class MO{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};pke=class pke extends MO{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ga);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Rx({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};mke=class mke extends MO{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=mx(jp(e,t))}existing(){return new Proxy(new Rx({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 Rx({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Rx=class Rx extends po{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var FO=x(()=>{CV();aV();IO();Ox();Ex();pO();dV();pV();PO();UO();uo();hO();_u();OV()});function RV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Px(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var zx,ZO,PV;var HO=x(()=>{TV();De();hx();pr();FO();UO();Ur();zx=class zx extends jO{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 sO,this.cache=i.cache??new Fp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new PV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new zx(this.client,this.dialect,this.schema,this.options,r),n=new ZO("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}};ZO=class ZO extends qO{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new ZO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};PV=class PV extends BO{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=Op(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=Op(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)=>RV(r));if(this.customResultMapper)return this.customResultMapper(e,Px);return e.map((r)=>nO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=Op(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 RV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Px);return nO(this.fields,Array.prototype.slice.call(r).map((i)=>Px(i)),this.joinsNotNullableMap)}async values(e){let t=Op(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 Au(e,t={}){let r=new TO({casing:t.casing}),i;if(t.logger===!0)i=new oO;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=v9(t.schema,k9);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new zx(e,r,n,{logger:i,cache:t.cache},void 0),s=new zV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var zV;var NV=x(()=>{De();hx();Np();Ox();Ex();HO();zV=class zV extends Mp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Nx(...e){if(typeof e[0]==="string"){let t=bu({url:e[0]});return Au(t,e[1])}if(YJ(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Au(r,i);let n=typeof t==="string"?bu({url:t}):bu(t);return Au(n,i)}return Au(e[0],e[1])}var DV=x(()=>{K$();Ur();NV();((e)=>{function t(r){return Au({},r)}e.mock=t})(Nx||(Nx={}))});var LV=x(()=>{DV();HO()});function BV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function bke(e){return e instanceof je&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Zp(e,t){let r=Date.now()+(t.budgetMs??hke),i=async(n)=>{if(t.isClosed())throw new je("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!bke(o))throw o;await t.afterRefusal?.();let s=Math.min(gke*2**(n-1),yke),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 KO(e,t={}){let r=bu({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let u=function(d,p){return Zp(()=>typeof d==="string"?s(d,p):s(d),{isClosed:n,budgetMs:o})},i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};r.execute=u,r.batch=(d,p)=>Zp(()=>a(d,p),l),r.migrate=(d)=>Zp(()=>c(d),l),r.transaction=(d)=>Zp(()=>i(d),l)}return r}function Dx(e){let{url:t,schema:r}=e,i=BV(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?KO({url:t,authToken:i},n):KO({url:t},n);return{db:Nx(o,{schema:r}),client:o,url:t}}async function Lx(e,t){if(!t.startsWith("file:"))return;let r=()=>e.closed===!0;for(let i of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await Zp(()=>e.execute(i),{isClosed:r})}var hke=5000,gke=5,yke=40;var JO=x(()=>{K$();LV()});var jV=x(()=>{a$();JO()});var VO=x(()=>{JO();jV()});var oe,ft;var WO=x(()=>{FO();np();oe=jp("job_queue",{id:mr("id").primaryKey().$defaultFn(()=>to()),type:mr("type").notNull(),data:mr("data").notNull(),result:mr("result",{mode:"json"}),progress:mr("progress",{mode:"json"}).$type(),source:mr("source"),metadata:mr("metadata",{mode:"json"}).$type().notNull(),status:mr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:Ar("priority").notNull().default(0),retryCount:Ar("retryCount").notNull().default(0),maxRetries:Ar("maxRetries").notNull().default(3),lastError:mr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:mr("attemptId"),workerSlotId:mr("workerSlotId"),workerSessionId:mr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Wa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Wa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Wa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Wa("idx_job_queue_source").on(e.source)})),ft=jp("job_worker_sessions",{slotId:mr("slotId").primaryKey(),sessionId:mr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Wa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Wa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function qV(e){return Dx({url:e.url,schema:{jobQueue:oe,jobWorkerSessions:ft},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var UV=x(()=>{VO();WO()});class GO{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var MV=x(()=>{Sx();cx();Wn();De();kx();hx();lo();Np();EO();Gn();Ir();Ur();so()});class QO{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 YO{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===He.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=xke.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var xke;var FV=x(()=>{Re();gs();xke=f.looseObject({deduplicationKey:f.string().optional()})});class XO{db;transactionClient;databaseUrl;logger;deduplicator=new YO;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??Ske}async insert(e){await this.write("insert",async()=>this.db.insert(oe).values(e))}async enqueueAtomic(e){return kke.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[He.FAILED,"Replaced by newer job",p,p,d.id,He.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,He.PENDING,He.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==He.PENDING&&r!==He.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(wke*2**(i-1),vke),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=hs){let n=r+i;await this.write("start worker session",async()=>this.db.insert(ft).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:ft.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=hs){return(await this.write("heartbeat worker session",async()=>this.db.update(ft).set({heartbeatAt:r,expiresAt:r+i}).where(Nt(et(ft.slotId,e),et(ft.sessionId,t))).returning({slotId:ft.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(ft).where(Nt(et(ft.slotId,e),et(ft.sessionId,t))).returning({slotId:ft.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(oe).set({status:He.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(oe).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:oe.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(oe).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(oe).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:oe.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:oe.retryCount,maxRetries:oe.maxRetries,type:oe.type,scheduledFor:oe.scheduledFor,startedAt:oe.startedAt,runtimeUpdatedAt:oe.runtimeUpdatedAt}).from(oe).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(oe).set({status:s?He.PENDING:He.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Nt(this.attemptWriteGuard(e,r),et(oe.retryCount,o.retryCount))).returning({id:oe.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(oe).set({status:He.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Nt(et(oe.id,e.jobId),et(oe.type,e.expectedType),ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)),Rn(oe.attemptId),Rn(oe.workerSlotId),Rn(oe.workerSessionId),Rn(oe.leaseExpiresAt),Rn(oe.attemptHeartbeatAt),Rn(oe.progress),Rn(oe.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(oe).where(et(oe.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(oe).where(q`json_extract(${oe.metadata}, '$.rootJobId') = ${e}`).orderBy(co(oe.createdAt),co(oe.id))}async getStatusByEntityId(e){return(await this.db.select().from(oe).where(q`json_extract(${oe.data}, '$.id') = ${e}`).orderBy(Ja(oe.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:oe.type,status:oe.status,count:q`count(*)`}).from(oe).groupBy(oe.type,oe.status),this.db.select({oldestPendingAt:q`min(case when ${oe.status} = ${He.PENDING} then ${oe.createdAt} end)`,duePending:q`coalesce(sum(case when ${oe.status} = ${He.PENDING} and ${oe.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${oe.status} = ${He.PENDING} and ${oe.scheduledFor} <= ${e} then ${oe.scheduledFor} end)`,latestClaimAt:q`max(${oe.startedAt})`,oldestProcessingAt:q`min(case when ${oe.status} = ${He.PROCESSING} then ${oe.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${oe.status} = ${He.PROCESSING} and ${oe.leaseExpiresAt} is not null and ${oe.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(oe),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${ft.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${ft.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${ft.heartbeatAt})`}).from(ft)]),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=_ke.parse(t);if(r===0)return[];return(await this.db.select().from(oe).where(q`(${oe.runtimeUpdatedAt}, ${oe.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(oe.runtimeUpdatedAt),co(oe.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(oe).where(Nt(ao(et(oe.status,He.COMPLETED),et(oe.status,He.FAILED)),wu(oe.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)),r=e&&e.length>0?Nt(t,Ts(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ts(oe.type,e):void 0;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt)).limit(t)}async getFailedJobs(e){let t=et(oe.status,He.FAILED),r=e&&e.length>0?Nt(t,Ts(oe.type,e)):t;return this.db.select().from(oe).where(r).orderBy(Ja(oe.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:ft.slotId}).from(ft).where(Nt(et(ft.slotId,i),et(ft.sessionId,n),gx(ft.expiresAt,t))),c=this.db.select({slotId:ft.slotId}).from(ft).where(Nt(et(ft.slotId,oe.workerSlotId),et(ft.sessionId,oe.workerSessionId))),l=Nt(et(oe.status,He.PROCESSING),ao(Rn(oe.attemptId),bx(c),wu(oe.leaseExpiresAt,t))),u=q`${oe.status} = ${He.PROCESSING} AND ${oe.retryCount} + 1 > ${oe.maxRetries}`,d=this.db.select({id:oe.id}).from(oe).where(Nt(Ts(oe.type,s),ao(Nt(et(oe.status,He.PENDING),wu(oe.scheduledFor,t)),l))).orderBy(co(oe.priority),co(oe.createdAt)).limit(1),m=(await this.write("claim",async()=>this.db.update(oe).set({status:q`CASE WHEN ${u} THEN ${He.FAILED} ELSE ${He.PROCESSING} END`,retryCount:q`CASE WHEN ${oe.status} = ${He.PROCESSING} THEN ${oe.retryCount} + 1 ELSE ${oe.retryCount} END`,lastError:q`CASE WHEN ${oe.status} = ${He.PROCESSING} THEN 'Attempt lease expired' ELSE ${oe.lastError} END`,startedAt:q`CASE WHEN ${u} THEN ${oe.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${u} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${u} THEN ${oe.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${u} THEN ${oe.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${u} THEN ${oe.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${u} THEN ${oe.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${u} THEN ${oe.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${u} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${oe.runtimeUpdatedAt} END`}).where(Nt(Ts(oe.id,d),yx(a))).returning()))[0];if(m?.status!==He.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:m.id,attemptId:m.attemptId,workerSlotId:i,workerSessionId:n}),m}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${oe.runtimeUpdatedAt}) from ${oe}), 0) + 1)`}attemptWriteGuard(e,t){return t?Nt(et(oe.id,e),et(oe.status,He.PROCESSING),et(oe.attemptId,t)):Nt(et(oe.id,e),Rn(oe.attemptId),ao(et(oe.status,He.PENDING),et(oe.status,He.PROCESSING)))}}var Ske=2000,wke=5,vke=40,_ke,kke;var ZV=x(()=>{MV();WO();Re();gs();op();FV();_ke=f.number().int().min(0).max(1000),kke=new QO});import{AsyncLocalStorage as Eke}from"async_hooks";class Hp{storage=new Eke;static createFresh(){return new Hp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Ro.parse(e),n=Ike(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Ike(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var eR=x(()=>{Po()});class Kp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Kp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=qV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Hp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new GO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new XO(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 Lx(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:He.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 Ro.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=hs){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=hs){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 HV=x(()=>{np();a$();op();gs();VO();UV();ZV();Po();eR()});var tR=()=>{};var KV=x(()=>{np();gs();op();gs();tR();eR()});var JV=x(()=>{gs();tR()});var Xet;var VV=x(()=>{Po();Re();ip();Xet=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var rtt;var WV=x(()=>{Re();rtt=f.record(f.string(),f.unknown())});var GV=x(()=>{Po();np()});var QV=x(()=>{HV();KV();JV();VV();WV();op();gs();ip();GV()});var rR={};tr(rR,{LEGACY_PROJECTION_JOB_TYPES:()=>XV,LEGACY_PROJECTION_RETIREMENT_REASON:()=>t7,legacyProjectionJobTypeSchema:()=>e7,retireLegacyProjectionJob:()=>Nke});import{existsSync as Rke}from"fs";import{resolve as Pke}from"path";function YV(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 zke(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 Nke(e){let t=Pke(e.databasePath);if(!Rke(t))throw Error(`Job database does not exist: ${t}`);let r=e7.parse(e.jobType),i=Kp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(zke(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:YV(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:t7,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:YV(s),retired:!0}}finally{i.close()}}var XV,e7,t7="Retired legacy projection job superseded by scheduler-owned projections";var nR=x(()=>{QV();Re();XV=["conversation-memory:project","skill:project","swot:derive","topic:project"],e7=f.enum(XV)});function er(e,t,r,i,n){return n7.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function oR(e){return Vp.parse(structuredClone(jke[e]))}function Wp(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function jx(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(),iR.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 iR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:qke(c)})}finally{clearTimeout(a)}}async function sR(e,t){let r=Vp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${Bx(c)}`}if(!n)for(let c of r.phases)try{let l=i7.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=Bx(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=o7.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=Bx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=s7.parse(await t.stopMonitoring())}catch(c){let l=Bx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=c7(a,r.maximumExternalAiCalls??0),a7.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 c7(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 qke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Bx(e){return at(e)}var Jp,r7,n7,Vp,Dke,iR,Lke,i7,o7,Bke,s7,a7,jke;var qx=x(()=>{Re();Jp=f.enum(["regression","load","stress"]),r7=f.enum(["add","update","rename","delete"]),n7=f.object({id:f.string().min(1),operation:r7,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Vp=f.object({profile:Jp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(n7).min(1)}),Dke=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),iR=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),Lke=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),i7=f.object({id:f.string().min(1),operation:r7,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),o7=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),Bke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),s7=f.object({health:f.array(iR),runtime:f.array(Lke),externalAiCalls:f.number().int().nonnegative().optional(),container:Bke.optional()}),a7=f.object({profile:Jp,success:f.boolean(),baseline:Dke,phases:f.array(i7),cleanup:o7,metrics:s7,failure:f.string().optional()}),jke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as Uke}from"child_process";async function l7(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=Uke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Gp=()=>{};class Tu{#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 Tu(e,r,i);return await l7(e,"git",["-c","credential.helper=","-c",`credential.helper=${u7}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",u7]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Ei("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var u7='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var d7=x(()=>{Gp()});function Qp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class aR{#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 jx(`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 Mke.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Qp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await jx(`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 Mke;var f7=x(()=>{Re();qx();Mke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Ux={};tr(Ux,{applyDirectorySyncStressPhase:()=>x7,cleanupDirectorySyncStress:()=>g7,listProbeFiles:()=>Qa,parseStressRuntimeSample:()=>S7,removeProbeFiles:()=>mR,runDeployedDirectorySyncStress:()=>m7,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>h7});import{chmod as Fke,mkdir as lR,mkdtemp as uR,readFile as Zke,readdir as Hke,rename as Kke,rm as Xp,writeFile as Xn}from"fs/promises";import{tmpdir as dR}from"os";import{join as xt,resolve as fR}from"path";async function m7(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=hR(r),n=fR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",i));await lR(n,{recursive:!0});let{pilot:o,user:s}=await pR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Jp.parse(e.profile),c=e.plan?Vp.parse(e.plan):oR(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)b7(s);let l=Jke.parse(e.env??process.env),u=new y7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await sR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await Yke(p),p}async function h7(e){let r=(e.now??(()=>new Date))().toISOString(),i=hR(r),n=fR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`access-check-${i}`));await lR(n,{recursive:!0});let{pilot:o,user:s}=await pR(e.rootDir,e.handle);Wp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),b7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await uR(xt(dR(),"brains-ops-directory-sync-access-check-"));try{let l=await Tu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,xt(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Xn(xt(n,"access-check.json"),`${JSON.stringify(d,null,2)}
|
|
466
466
|
`),d}finally{await Xp(c,{recursive:!0,force:!0})}}async function g7(e){let t=e.now??(()=>new Date),r=fR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`cleanup-${hR(t().toISOString())}`));await lR(r,{recursive:!0});let{pilot:i,user:n}=await pR(e.rootDir,e.handle);Wp({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??mo,a=e.logger??console.info,c=await uR(xt(dR(),"brains-ops-directory-sync-cleanup-")),l=xt(c,"content");try{let u=await Tu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),d=await mR(u.dir),p;if(d>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${d} directory-sync stress probes`);let m=(await Qa(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:d,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Xn(xt(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
|
|
467
467
|
`),g}finally{await Xp(c,{recursive:!0,force:!0})}}class y7{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new aR({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await uR(xt(dR(),"brains-ops-directory-sync-stress-"));let t=xt(this.#r,"content");this.#i=xt(this.#r,"id_ed25519"),this.#o=xt(this.#r,"known_hosts"),this.#a=await this.#m(),await Xn(this.#i,Qke(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Fke(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 Xn(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 Tu.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await Qa(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 Xn(xt(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:Qp(s),version:s.version}},null,2)}
|
|
468
468
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Qp(s),version:s.version}}async startMonitoring(){this.#x(),this.#t.start()}async executePhase(e,t){this.#x();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return Cu(e,"health did not provide a drained queue before the phase");await x7(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 Cu(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 Cu(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 Cu(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 Cu(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 Cu(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 mR(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await Qa(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=i===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:i,...n?{finalEntities:n.entities,finalNotes:Qp(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await Qa(t.dir)).length,error:at(r)}}}async stopMonitoring(){await this.#t.stop(),await Xn(xt(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -476,7 +476,7 @@ Update marker: ${t.id}.
|
|
|
476
476
|
`}function hR(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function Yke(e){await Xn(xt(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
|
|
477
477
|
`),await Xn(xt(e.artifactsDir,"report.md"),Xke(e))}function Xke(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,i=t.map((a)=>a.cpuPercent).sort((a,c)=>a-c),n=t.map((a)=>a.memoryPercent),o=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${p7(a.commitLatencyMs)} | ${p7(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${Yp(cR(i,0.5))} / ${Yp(cR(i,0.95))} / ${Yp(cR(i,0.99))} / ${Yp(i.at(-1))}`,`- Memory max: ${Yp(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${o.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
|
|
478
478
|
`)}
|
|
479
|
-
`}function cR(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Yp(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function p7(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Jke,Vke,Wke;var em=x(()=>{Re();qx();Ln();Gp();d7();f7();Gp();Jke=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1),CONTENT_REPO_ADMIN_TOKEN:f.string().min(1)}),Vke=f.object({servers:f.array(f.object({id:f.number().int(),status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))}),Wke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),resources:f.object({queue:f.object({totals:f.object({pending:f.number().int().nonnegative(),processing:f.number().int().nonnegative()}),byType:f.array(f.object({type:f.string(),status:f.string(),count:f.number().int().nonnegative()}))})})})});var w7=x(()=>{Rs()});var eEe="/usr/local/sbin/brains-health-watchdog",tEe="ai.rizom.brain.watchdog",rEe="true",gR,v7,
|
|
479
|
+
`}function cR(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Yp(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function p7(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Jke,Vke,Wke;var em=x(()=>{Re();qx();Ln();Gp();d7();f7();Gp();Jke=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1),CONTENT_REPO_ADMIN_TOKEN:f.string().min(1)}),Vke=f.object({servers:f.array(f.object({id:f.number().int(),status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))}),Wke=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),resources:f.object({queue:f.object({totals:f.object({pending:f.number().int().nonnegative(),processing:f.number().int().nonnegative()}),byType:f.array(f.object({type:f.string(),status:f.string(),count:f.number().int().nonnegative()}))})})})});var w7=x(()=>{Rs()});var eEe="/usr/local/sbin/brains-health-watchdog",tEe="ai.rizom.brain.watchdog",rEe="true",gR,v7,Ytt;var _7=x(async()=>{w7();gR=`${tEe}=${rEe}`,v7=`#!/usr/bin/env bash
|
|
480
480
|
set -euo pipefail
|
|
481
481
|
umask 077
|
|
482
482
|
|
|
@@ -535,7 +535,7 @@ while read -r container_id; do
|
|
|
535
535
|
logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
|
|
536
536
|
docker restart "$container_id"
|
|
537
537
|
done < <(docker ps --filter health=unhealthy --filter label=${gR} --format '{{.ID}}')
|
|
538
|
-
`,
|
|
538
|
+
`,Ytt=`[Unit]
|
|
539
539
|
Description=Restart persistently unhealthy Brain containers
|
|
540
540
|
After=docker.service
|
|
541
541
|
Requires=docker.service
|
|
@@ -775,7 +775,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
775
775
|
`),o}async function O7(e,t){let r=await Ct(e),i=r.users.find((n)=>n.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:i}}async function R7(e){let t=await sEe(Ii(aEe(),"brains-ops-watchdog-smoke-")),r=Ii(t,"id_ed25519"),i=Ii(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),o=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!o.ok)throw Error(`Hetzner server lookup failed with ${o.status}`);let s=cEe.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 $u(r,dEe(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await oEe(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 $u(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await bR(t,{recursive:!0,force:!0}),n}}async function yR(e,t,r){return e.commandRunner("ssh",[...P7(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:xR()})}async function lEe(e,t,r){return e.commandRunner("scp",[...P7(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function P7(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function uEe(e){try{return await iEe(e),!0}catch{return!1}}async function Mx(e,t,r){await Promise.all([$u(Ii(e,`${t}.stdout.log`),r.stdout),$u(Ii(e,`${t}.stderr.log`),r.stderr)])}function dEe(e){return`${e.replace(/\r\n/g,`
|
|
776
776
|
`).replace(/\\n/g,`
|
|
777
777
|
`).trimEnd()}
|
|
778
|
-
`}var T7,cEe;var Zx=x(async()=>{Re();k7();Ln();Gp();await _7();T7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),cEe=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as BN,chmod as LE,mkdir as Zh,readFile as qN,writeFile as jN}from"fs/promises";import{dirname as XY,join as Lc}from"path";import{fileURLToPath as eX}from"url";var tm={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
778
|
+
`}var T7,cEe;var Zx=x(async()=>{Re();k7();Ln();Gp();await _7();T7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),cEe=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as BN,chmod as LE,mkdir as Zh,readFile as qN,writeFile as jN}from"fs/promises";import{dirname as XY,join as Lc}from"path";import{fileURLToPath as eX}from"url";var tm={name:"@rizom/ops",version:"0.2.0-alpha.493",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun run build && bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Rs();Dc();var tX=["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"],BE=new Set([".kamal/hooks/pre-deploy"]),rX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),nX=eX(new URL("../templates/rover-pilot/",import.meta.url)),iX=[`service: rover
|
|
779
779
|
image: <%= ENV['IMAGE_REPOSITORY'] %>
|
|
780
780
|
|
|
781
781
|
servers:
|