wiki-graph 0.3.0 → 0.4.0

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.
Files changed (69) hide show
  1. package/README.md +10 -271
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +2983 -4
  4. package/dist/cli.js.map +1 -0
  5. package/{data → dist/data}/editor/text_compressor.jinja +17 -13
  6. package/{data → dist/data}/help/commands/archive/next.jinja +7 -2
  7. package/{data → dist/data}/help/commands/gc.jinja +2 -1
  8. package/{data → dist/data}/help/commands/legacy/migrate.jinja +6 -1
  9. package/{data → dist/data}/help/commands/legacy.jinja +3 -2
  10. package/dist/data/help/commands/library-predicate.jinja +296 -0
  11. package/dist/data/help/commands/library.jinja +235 -0
  12. package/{data → dist/data}/help/commands/maintenance/chapter/add.jinja +3 -3
  13. package/{data → dist/data}/help/commands/maintenance/chapter/list.jinja +4 -4
  14. package/{data → dist/data}/help/commands/maintenance/chapter/move.jinja +4 -4
  15. package/{data → dist/data}/help/commands/maintenance/chapter/remove.jinja +1 -1
  16. package/{data → dist/data}/help/commands/maintenance/chapter/reset.jinja +1 -1
  17. package/{data → dist/data}/help/commands/maintenance/chapter/set-source.jinja +2 -2
  18. package/{data → dist/data}/help/commands/maintenance/chapter/set-summary.jinja +1 -1
  19. package/{data → dist/data}/help/commands/maintenance/chapter/set-title.jinja +3 -3
  20. package/{data → dist/data}/help/commands/maintenance/chapter/tree.jinja +6 -6
  21. package/{data → dist/data}/help/commands/maintenance/chapter.jinja +10 -10
  22. package/{data → dist/data}/help/commands/maintenance/meta.jinja +7 -7
  23. package/dist/data/help/commands/maintenance/upgrade.jinja +35 -0
  24. package/dist/data/help/commands/maintenance.jinja +23 -0
  25. package/{data → dist/data}/help/commands/predicate.jinja +204 -28
  26. package/{data → dist/data}/help/commands/root.jinja +10 -3
  27. package/{data → dist/data}/help/commands/uri.jinja +165 -6
  28. package/{data → dist/data}/help/topics/config.jinja +10 -3
  29. package/dist/data/help/topics/library.jinja +87 -0
  30. package/{data → dist/data}/help/topics/readiness.jinja +32 -2
  31. package/{data → dist/data}/help/topics/recipe.jinja +42 -17
  32. package/{data → dist/data}/help/topics/runtime.jinja +20 -3
  33. package/{data → dist/data}/help/topics/uri.jinja +51 -25
  34. package/dist/gc-worker.d.ts +1 -0
  35. package/dist/gc-worker.js +548 -0
  36. package/dist/gc-worker.js.map +1 -0
  37. package/dist/index.cjs +12463 -19690
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +36 -842
  40. package/dist/index.d.ts +36 -842
  41. package/dist/index.js +13871 -9
  42. package/dist/index.js.map +1 -0
  43. package/dist/queue-worker.d.ts +1 -0
  44. package/dist/queue-worker.js +2110 -0
  45. package/dist/queue-worker.js.map +1 -0
  46. package/package.json +18 -45
  47. package/dist/cli.cjs +0 -41734
  48. package/dist/cli.cjs.map +0 -1
  49. package/docs/images/flowchart.excalidraw +0 -3293
  50. package/docs/images/flowchart.svg +0 -4
  51. package/docs/images/terminal-cn.png +0 -0
  52. package/docs/images/terminal-en.png +0 -0
  53. package/docs/wikispine-runtime.md +0 -143
  54. /package/{data → dist/data}/editor/clue_reviewer.jinja +0 -0
  55. /package/{data → dist/data}/editor/clue_reviewer_generator.jinja +0 -0
  56. /package/{data → dist/data}/editor/revision_feedback.jinja +0 -0
  57. /package/{data → dist/data}/guaranteed/response_intent_classifier.jinja +0 -0
  58. /package/{data → dist/data}/help/commands/maintenance/cover.jinja +0 -0
  59. /package/{data → dist/data}/help/commands/transform.jinja +0 -0
  60. /package/{data → dist/data}/help/topics/format.jinja +0 -0
  61. /package/{data → dist/data}/output/epub/cover.xhtml.jinja +0 -0
  62. /package/{data → dist/data}/output/epub/nav.xhtml.jinja +0 -0
  63. /package/{data → dist/data}/output/epub/package.opf.xml.jinja +0 -0
  64. /package/{data → dist/data}/output/epub/section.xhtml.jinja +0 -0
  65. /package/{data → dist/data}/topologization/book_coherence_extraction.jinja +0 -0
  66. /package/{data → dist/data}/topologization/chunk_extraction.jinja +0 -0
  67. /package/{data → dist/data}/topologization/evidence_choice.jinja +0 -0
  68. /package/{data → dist/data}/topologization/translate_chunks.jinja +0 -0
  69. /package/{data → dist/data}/topologization/user_focused_extraction.jinja +0 -0
@@ -0,0 +1,548 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath as __WIKIGRAPH_FILE_URL_TO_PATH__ } from "url";
3
+ import { resolve as __WIKIGRAPH_RESOLVE__ } from "path";
4
+ globalThis.__WIKIGRAPH_CLI_DIST_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL(".", import.meta.url)));
5
+ globalThis.__WIKIGRAPH_DATA_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL("./data", import.meta.url)));
6
+ var i=(e,t)=>()=>(e&&(t=e(e=0)),t);import{AsyncLocalStorage as Qs}from"async_hooks";import{homedir as Gf}from"os";import{join as je,resolve as zs}from"path";function me(){let e=Bf.getStore()?.path;if(e!==void 0&&e.trim()!=="")return zs(e);let t=Xs.getStore()?.path;return t!==void 0&&t.trim()!==""?zs(t):je(Gf(),".wikigraph")}async function vi(e,t){return await Xs.run({path:e},t)}function j(){return je(me(),"core.sqlite")}function Ge(){return je(me(),"cache")}function Dt(){return je(Ge(),"cache.sqlite")}function ot(){return je(me(),"jobs")}function q(){return je(me(),"staging")}function st(){return je(me(),"tmp")}var Bf,Xs,N=i(()=>{"use strict";Bf=new Qs,Xs=new Qs});import{mkdir as kx,mkdtemp as Ix}from"fs/promises";import{join as Uf}from"path";function ct(){return st()}function Vs(e){let t=ct();return e===void 0?t:Uf(t,e)}var pe=i(()=>{"use strict";N()});var Tx,Mt=i(()=>{"use strict";Tx=new RegExp("\\p{Script=Han}","u")});var Ti=i(()=>{"use strict"});import{AsyncLocalStorage as Hf}from"async_hooks";import{stat as qf}from"fs/promises";import{resolve as $f}from"path";async function Jf(e){let t=await qf(e).catch(r=>{if(!(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT"))throw r});return t===void 0||t.size===0}function g(e,t){let r=e[t];if(typeof r!="number")throw new TypeError(`Expected ${t} to be a number`);return r}function w(e,t){let r=e[t];if(typeof r!="string")throw new TypeError(`Expected ${t} to be a string`);return r}async function zf(e,t={}){let r=await Qf(),n=(t.readonly===!0?r.OPEN_READONLY:r.OPEN_READWRITE|r.OPEN_CREATE)|r.OPEN_FULLMUTEX;return await new Promise((a,o)=>{let s=new r.Database(e,n,c=>{if(c!==null){o(c);return}a(s)})})}async function Qf(){let e=await import("sqlite3");return Xf(e)}function Xf(e){if(typeof e=="object"&&e!==null&&"default"in e&&typeof e.default=="object"&&e.default!==null&&"Database"in e.default)return e.default;if(typeof e=="object"&&e!==null&&"Database"in e)return e;throw new TypeError("Could not load sqlite3")}function _i(e){return e??[]}var Kf,k,f=i(()=>{"use strict";Kf=900*1e3;k=class e{#e;#t;#r=new Hf;#n;#i=!1;#d=Promise.resolve();#c=0;constructor(t,r={}){this.#e=t,this.#t=r.onWrite}static async open(t,r="",n={}){let a=$f(t),o=n.readonly!==!0&&r.trim()!==""&&await Jf(a),s=await zf(a,n),c=new e(s,n);return await c.#o(`PRAGMA busy_timeout = ${Kf}`),n.readonly!==!0&&r.trim()!==""&&(await c.#o(r),o&&c.#u()),c}static async initialize(t,r){let n=await e.open(t);try{r.trim()!==""&&await n.#o(r)}finally{await n.close()}}async queryAll(t,r,n){return await this.#a(async()=>(this.#s(),(await this.#m(t,r)).map(n)))}async queryOne(t,r,n){return await this.#a(async()=>{this.#s();let a=await this.#p(t,r);return a===void 0?void 0:n(a)})}async run(t,r){await this.#a(async()=>{this.#s(),await this.#h(t,r),this.#u()})}async transaction(t){return await this.#a(async()=>{this.#s();let r=this.#c===0,n=this.#n??Symbol("database transaction scope");r&&(await this.#o("BEGIN IMMEDIATE"),this.#n=n),this.#c+=1;try{let a=await this.#r.run(n,t);return r&&await this.#o("COMMIT"),a}catch(a){throw r&&await this.#o("ROLLBACK"),a}finally{this.#c-=1,r&&(this.#n=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let t=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,r=>g(r,"row_id"));if(t===void 0)throw new Error("Could not read last_insert_rowid()");return t}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(t){let r=this.#r.getStore();if(r!==void 0&&r===this.#n)return await t();let n=this.#d.then(t);return this.#d=n.then(()=>{},()=>{}),await n}#u(){this.#t?.()}async#l(){await new Promise((t,r)=>{this.#e.close(n=>{if(n!==null){r(n);return}t()})})}async#o(t){await new Promise((r,n)=>{this.#e.exec(t,a=>{if(a!==null){n(a);return}r()})})}async#m(t,r){return await new Promise((n,a)=>{this.#e.all(t,_i(r),(o,s)=>{if(o!==null){a(o);return}n(s)})})}async#p(t,r){return await new Promise((n,a)=>{this.#e.get(t,_i(r),(o,s)=>{if(o!==null){a(o);return}n(s)})})}async#h(t,r){await new Promise((n,a)=>{this.#e.run(t,_i(r),o=>{if(o!==null){a(o);return}n()})})}}});function h(e){return e instanceof Error}function Be(e){let t=[],r=new Set,n=e;for(;n!==void 0&&!r.has(n);){if(r.add(n),n instanceof Error){Ys(t,Vf(n)),n=n.cause;continue}Ys(t,String(n));break}return t.join(": ")}function Vf(e){let t=e,r=e.message.trim(),n=typeof t.code=="string"&&t.code!==""?t.code:void 0,a=typeof t.path=="string"&&t.path!==""?t.path:void 0;return n==="ENOENT"?a===void 0?"File not found (ENOENT)":`File not found: ${a} (ENOENT)`:n==="EACCES"||n==="EPERM"?a===void 0?`Permission denied (${n})`:`Permission denied: ${a} (${n})`:r===""?n===void 0?e.name:`${e.name} (${n})`:n===void 0?r:`${r} (${n})`}function Ys(e,t){let r=t.trim();if(r==="")return;let n=e.at(-1);if(n===void 0){e.push(r);return}if(!(n===r||n.includes(r))){if(r.includes(n)){e[e.length-1]=r;return}e.push(r)}}var b=i(()=>{"use strict"});import{mkdir as Yf,rm as Zf,stat as tc}from"fs/promises";import{dirname as ey,join as A,resolve as Pi}from"path";async function $(){let e=j(),t=Pi(e),r=await Xr(e);if(Ci(t,r))return;if(Ue!==void 0){await Ue;let a=await Xr(e);if(Ci(t,a))return}let n=await Xr(e);if(Ue!==void 0)return await Ue,$();if(!Ci(t,n)){Ue=(async()=>{if(!await he(e)){await ec(e,Qr),await Zs(t);return}let a=await Yr(e);if(a>Qr)throw new Error(`Unsupported Wiki Graph home schema version: ${a}.`);a<Qr&&(await oy(),await ay(),await uy(),await ec(e,Qr)),await Zs(t)})();try{await Ue;return}finally{Ue=void 0}}}async function Zs(e){let t=await Xr(e);if(t===void 0){Wt=void 0;return}Wt={fingerprint:t,path:e}}async function Xr(e){try{let t=await tc(e);return{dev:t.dev,ino:t.ino,mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(h(t)&&t.code==="ENOENT")return;throw t}}function Ci(e,t){return t===void 0||Wt===void 0?!1:Wt.path===e&&ny(Wt.fingerprint,t)}function ny(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Yr(e=j()){if(!await he(e))return 0;let t=await k.open(e,"",{readonly:!0});try{return await ee(t,"schema_versions")?await t.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>Number(n.version))??1:1}finally{await t.close()}}function rc(e){let t=Pi(e);return iy().some(r=>t===Pi(r))}function iy(){let e=Ge();return[j(),A(e,"search-sessions.sqlite"),A(e,"continuation-cursors.sqlite"),Dt(),A(ot(),"job.sqlite"),A(st(),"gc.sqlite"),A(q(),"staging.sqlite")]}async function ec(e,t){await Yf(ey(e),{recursive:!0});let r=await k.open(e);try{await r.run(ry),await r.run(`
7
+ INSERT INTO schema_versions (scope, version, updated_at)
8
+ VALUES (?, ?, ?)
9
+ ON CONFLICT(scope) DO UPDATE SET
10
+ version = excluded.version,
11
+ updated_at = excluded.updated_at
12
+ `,["home",t,new Date().toISOString()])}finally{await r.close()}}async function ay(){let e=Ge(),t=q(),r=ot(),n=st();await Z(A(e,"search-sessions.sqlite")),await Z(A(e,"continuation-cursors.sqlite")),await Z(Dt()),await Z(A(t,"library")),await Z(A(n,"gc.sqlite")),await Z(A(n,"gc.last-run")),await Z(A(r,"cache")),await Z(A(r,"job.sqlite"));let a=A(t,"staging.sqlite");await he(a)&&(await my(a),await py(a))}async function oy(){await sy(),await cy(),await dy(),await ly()}async function sy(){let e=j();if(!await he(e))return;let t=await k.open(e,"",{readonly:!0});try{if(await ee(t,"library_locks")&&(await t.queryAll(`
13
+ SELECT owner_pid, heartbeat_at
14
+ FROM library_locks
15
+ `,void 0,a=>({heartbeatAt:Number(a.heartbeat_at),ownerPid:Number(a.owner_pid)}))).some(a=>Ft(a.ownerPid,a.heartbeatAt)))throw new Error("Cannot upgrade home with active library locks.");if(!await ee(t,"state_locks"))return;if((await t.queryAll(`
16
+ SELECT owner_pid, heartbeat_at
17
+ FROM state_locks
18
+ WHERE scope = 'library'
19
+ `,void 0,n=>({heartbeatAt:Number(n.heartbeat_at),ownerPid:Number(n.owner_pid)}))).some(n=>Ft(n.ownerPid,n.heartbeatAt)))throw new Error("Cannot upgrade home with active library locks.")}finally{await t.close()}}async function cy(){let e=A(st(),"gc.sqlite");if(!await he(e))return;let t=await k.open(e,"",{readonly:!0});try{if(!await ee(t,"gc_locks"))return;if((await t.queryAll("SELECT owner_pid, heartbeat_at FROM gc_locks",void 0,n=>({heartbeatAt:Number(n.heartbeat_at),ownerPid:Number(n.owner_pid)}))).some(n=>Ft(n.ownerPid,n.heartbeatAt)))throw new Error("Cannot upgrade home with an active GC lock.")}finally{await t.close()}}async function dy(){let e=A(q(),"staging.sqlite");if(!await he(e))return;let t=await k.open(e,"",{readonly:!0});try{for(let r of["archive_owners","entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await ee(t,r))continue;if((await t.queryAll(`
20
+ SELECT owner_pid, heartbeat_at
21
+ FROM ${r}
22
+ `,void 0,a=>({heartbeatAt:Number(a.heartbeat_at),ownerPid:Number(a.owner_pid)}))).some(a=>Ft(a.ownerPid,a.heartbeatAt)))throw new Error(`Cannot upgrade home with active coordinator state: ${r}.`)}}finally{await t.close()}}async function uy(){let e=A(q(),"staging.sqlite");if(!await he(e))return;let t=await k.open(e,"",{readonly:!0});try{if(!await ee(t,"entry_overlays"))return;if((await t.queryAll(`
23
+ SELECT entry_path
24
+ FROM entry_overlays
25
+ `,void 0,a=>String(a.entry_path))).find(a=>a!==Vr)!==void 0)throw new Error("Cannot upgrade home with non-derived coordinator overlays.")}finally{await t.close()}}async function ly(){let e=A(ot(),"job.sqlite");if(!await he(e))return;let t=await k.open(e,"",{readonly:!0});try{if(await ee(t,"build_jobs")&&(await t.queryAll(`
26
+ SELECT job_id
27
+ FROM build_jobs
28
+ WHERE state IN ('queued', 'running', 'canceling', 'paused')
29
+ `,void 0,n=>String(n.job_id))).length>0)throw new Error("Cannot upgrade home with active build jobs.");if(await ee(t,"build_worker_lease")){let r=await t.queryOne(`
30
+ SELECT owner_pid, heartbeat_at
31
+ FROM build_worker_lease
32
+ WHERE id = 1
33
+ `,void 0,n=>({heartbeatAt:n.heartbeat_at===null?void 0:Number(n.heartbeat_at),ownerPid:n.owner_pid===null?void 0:Number(n.owner_pid)}));if(r?.ownerPid!==void 0&&r.heartbeatAt!==void 0&&Ft(r.ownerPid,r.heartbeatAt))throw new Error("Cannot upgrade home with an active build worker lease.")}}finally{await t.close()}}async function my(e,t){let r=await k.open(e);try{if(!await ee(r,"entry_overlays"))return;let n=t===void 0?"WHERE entry_path = ?":"WHERE archive_key = ? AND entry_path = ?",a=t===void 0?[Vr]:[t,Vr],o=await r.queryAll(`
34
+ SELECT archive_key, workspace_path
35
+ FROM entry_overlays
36
+ ${n}
37
+ `,a,s=>({archiveKey:String(s.archive_key),workspacePath:s.workspace_path===null?void 0:String(s.workspace_path)}));for(let s of o)s.workspacePath!==void 0&&await Z(s.workspacePath);await r.run(`
38
+ DELETE FROM entry_overlays
39
+ ${n}
40
+ `,a)}finally{await r.close()}}async function py(e){let t=await k.open(e);try{if(!await ee(t,"entry_overlays"))return;let r=await t.queryAll(`
41
+ SELECT archive_key, archive_path, entry_path, workspace_path
42
+ FROM entry_overlays
43
+ WHERE entry_path IN (?, ?)
44
+ `,["database.db",Vr],n=>({archiveKey:String(n.archive_key),archivePath:String(n.archive_path),entryPath:String(n.entry_path),workspacePath:n.workspace_path===null?void 0:String(n.workspace_path)}));for(let n of r)await he(n.archivePath)||(n.workspacePath!==void 0&&await Z(n.workspacePath),await t.run(`
45
+ DELETE FROM entry_overlays
46
+ WHERE archive_key = ? AND entry_path = ?
47
+ `,[n.archiveKey,n.entryPath]))}finally{await t.close()}}async function ee(e,t){return await e.queryOne(`
48
+ SELECT 1 AS present
49
+ FROM sqlite_master
50
+ WHERE type = 'table' AND name = ?
51
+ `,[t],()=>!0)===!0}function Ft(e,t){return Date.now()-t<=ty&&hy(e)}function hy(e){try{return process.kill(e,0),!0}catch{return!1}}async function Z(e){await Zf(e,{force:!0,recursive:!0})}async function he(e){try{return await tc(e),!0}catch{return!1}}var Qr,ty,Vr,Ue,Wt,ry,He=i(()=>{"use strict";N();b();f();Qr=2,ty=300*1e3,Vr="fts.db",ry=`
52
+ CREATE TABLE IF NOT EXISTS schema_versions (
53
+ scope TEXT PRIMARY KEY,
54
+ version INTEGER NOT NULL,
55
+ updated_at TEXT NOT NULL
56
+ );
57
+ `});import{createHash as fy}from"crypto";import{chmod as yy,mkdir as ac,readFile as oc,rename as gy,rm as sc,stat as cc,writeFile as dc}from"fs/promises";import{dirname as by,resolve as Sy}from"path";import{setTimeout as wy}from"timers/promises";async function v(e,t,r={}){return await Iy(e),await uc(e,t),await k.open(e,"",r)}function Iy(e){return rc(e)?$():Promise.resolve()}async function uc(e,t){let r=Sy(e),n=Ay(r),a=Oy(t);if(await ic(r,n,a)){await ve(r),await ve(n);return}await ac(by(r),{recursive:!0}),await Ry(r,async()=>{if(await ic(r,n,a)){await ve(r),await ve(n);return}await k.initialize(r,t),await ve(r),await xy(n,a)}),await ve(r),await ve(n)}async function xy(e,t){let r=`${e}.${process.pid}.tmp`;await dc(r,`${t}
58
+ `,{encoding:"utf8",mode:384}),await gy(r,e),await ve(e)}async function Ry(e,t){let r=`${e}.init.lock`;for(;;)try{await ac(r,{mode:448});break}catch(n){if(!h(n)||n.code!=="EEXIST")throw n;await vy(r),await wy(Ey)}try{await nc(r);let n=setInterval(()=>{nc(r).catch(()=>{})},ky);try{return await t()}finally{clearInterval(n)}}finally{await sc(r,{force:!0,recursive:!0})}}async function nc(e){await dc(`${e}/owner.json`,`${JSON.stringify({at:Date.now(),pid:process.pid},null,2)}
59
+ `,{encoding:"utf8",mode:384})}async function vy(e){try{let t=await Ty(e);if(t!==void 0){if(Py(t.pid)||Date.now()-t.at<Ai)return}else if(!await Cy(e,Ai))return;await sc(e,{force:!0,recursive:!0})}catch(t){if(h(t)&&t.code==="ENOENT")return;throw t}}async function Ty(e){try{let t=JSON.parse(await oc(`${e}/owner.json`,"utf8"));return _y(t)?t:void 0}catch(t){if(h(t)&&t.code==="ENOENT"||t instanceof SyntaxError)return;throw t}}function _y(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0&&typeof t.at=="number"}async function Cy(e,t){let r=await cc(e);return Date.now()-r.mtimeMs>=t}function Py(e){try{return process.kill(e,0),!0}catch(t){return!(h(t)&&t.code==="ESRCH")}}async function ic(e,t,r){if(!await Ly(e))return!1;try{return(await oc(t,"utf8")).trim()===r}catch(n){if(h(n)&&n.code==="ENOENT")return!1;throw n}}function Ay(e){return`${e}.initialized`}async function Ly(e){try{return(await cc(e)).isFile()}catch(t){if(h(t)&&t.code==="ENOENT")return!1;throw t}}async function ve(e){try{await yy(e,384)}catch(t){if(h(t)&&t.code==="ENOENT")return;throw t}}function Oy(e){return fy("sha256").update(e).digest("hex")}var Ey,Ai,ky,lc=i(()=>{"use strict";b();He();f();Ey=50,Ai=300*1e3,ky=Math.floor(Ai/2)});import{mkdir as Xx,readFile as Vx,readdir as Yx,rm as Zx,writeFile as eR}from"fs/promises";var mc=i(()=>{"use strict";b()});function dt(e){let t=new Set(Object.values(e));return r=>t.has(r)}function jt(e,t){let r=dt(e);return n=>{if(r(n))return n;throw new Error(`Unknown ${t}: ${n}`)}}var Li=i(()=>{"use strict"});var K,pc,hc,te,fc,Oi,fe=i(()=>{"use strict";Li();K=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(K||{}),pc=dt(K),hc=jt(K,"chunk retention"),te=(n=>(n.Critical="critical",n.Important="important",n.Helpful="helpful",n))(te||{}),fc=dt(te),Oi=jt(te,"chunk importance")});var Ni=i(()=>{"use strict";fe()});var gc=i(()=>{"use strict";fe()});var Di=i(()=>{"use strict"});import{join as wR,resolve as ER}from"path";var Mi=i(()=>{"use strict";fe();Ni();gc();Di()});import{join as CR,resolve as PR}from"path";var bc=i(()=>{"use strict";mc();Mi()});var Wi=i(()=>{"use strict";bc();Ni();Mi();Di()});import{mkdir as GR,readFile as BR,readdir as UR,writeFile as HR}from"fs/promises";var Zr=i(()=>{"use strict";b()});var Fi=i(()=>{"use strict"});import{join as zR,resolve as QR}from"path";var wc=i(()=>{"use strict";Zr()});var Ec=i(()=>{"use strict"});var ji=i(()=>{"use strict"});import{join as sv,resolve as cv}from"path";var Gi=i(()=>{"use strict";b();Fi();Zr();wc();Ec();ji()});import{join as gv,resolve as bv}from"path";var kc=i(()=>{"use strict";Zr();Gi()});var Bi=i(()=>{"use strict";kc();Fi();Gi();ji()});import{z as J}from"zod";var Ic,Te,xc,Rc,Gt=i(()=>{"use strict";Ic=["epub","pdf","txt","markdown"],Te=1,xc=J.enum(Ic),Rc=J.object({version:J.literal(Te),sourceFormat:xc,title:J.string().min(1).nullable(),authors:J.array(J.string().min(1)),language:J.string().min(1).nullable(),identifier:J.string().min(1).nullable(),publisher:J.string().min(1).nullable(),publishedAt:J.string().min(1).nullable(),description:J.string().min(1).nullable()})});import{randomBytes as Pv}from"crypto";function vc(e,t="chapter key"){if(e===""||e==="."||e===".."||e.includes("/"))throw new Error(`Invalid ${t}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(e))throw new Error(`Invalid ${t}: ${e}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(e))throw new Error(`Invalid ${t}: numeric chapter keys are not accepted.`);if(Fy.has(e))throw new Error(`Invalid ${t}: ${e} is reserved.`);return e}var Fy,ye=i(()=>{"use strict";Fy=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as ge}from"zod";var qe,Ui,Hi,en=i(()=>{"use strict";ye();qe=1,Ui=ge.object({key:ge.string().min(1).transform(e=>vc(e)).optional(),title:ge.string().min(1).nullable().optional(),serialId:ge.number().int().nonnegative().optional(),children:ge.lazy(()=>ge.array(Ui))}),Hi=ge.object({version:ge.literal(qe),items:ge.array(Ui)})});import{createHash as jy}from"crypto";import{posix as qi}from"path";import{PassThrough as Gy}from"stream";import{open as By}from"yauzl";function be(e){let t=e.replaceAll("\\","/").trim(),r=t.startsWith("/")?t.slice(1):t;return qi.normalize(r).replace(/^(\.\/)+/,"").replace(/^\/+/,"")}function Uy(e){let[t]=e.split("#",1);return be(t??"")}function $i(e){if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;return t===""?void 0:t}function Bt(e){let[t,r]=e.split("#",2);return{path:be(t??""),fragment:$i(r)}}async function Hy(e){return await new Promise((t,r)=>{By(e,{autoClose:!1,lazyEntries:!0},(n,a)=>{if(n!==null||a===void 0){r(n??new Error(`Cannot open EPUB archive: ${e}`));return}t(a)})})}async function qy(e){return await new Promise((t,r)=>{let n=new Map;e.on("entry",a=>{if(a.fileName.endsWith("/")){e.readEntry();return}n.set(be(a.fileName),a),e.readEntry()}),e.once("end",()=>{t(n)}),e.once("error",a=>{r(a)}),e.readEntry()})}function $y(e){if(Buffer.isBuffer(e))return e;if(typeof e=="string")return Buffer.from(e,"utf8");throw new Error("Unexpected ZIP stream chunk type")}async function Tc(e){return await new Promise((t,r)=>{let n=[];e.on("data",a=>{n.push($y(a))}),e.once("end",()=>{t(Buffer.concat(n))}),e.once("error",a=>{r(a)}),e.resume()})}async function Ky(e,t){return await new Promise((r,n)=>{e.openReadStream(t,(a,o)=>{if(a!==null||o===void 0){n(a??new Error(`Cannot open EPUB entry: ${t.fileName}`));return}r(Jy(o))})})}function Jy(e){let t=new Gy;return e.once("error",r=>{t.destroy(r)}),t.once("close",()=>{e.unpipe(t),e.destroyed||e.destroy()}),e.pipe(t),t}var tn,Ut=i(()=>{"use strict";tn=class e{#e;#t;#r;#n=!1;constructor(t,r,n){this.#e=t,this.#t=r,this.#r=n}static async open(t){let r=await Hy(t),n=await qy(r);return new e(t,r,n)}close(){return this.#n||(this.#n=!0,this.#t.close()),Promise.resolve()}hasEntry(t){return this.#r.has(be(t))}listEntries(){return[...this.#r.keys()]}async openReadStream(t){let r=this.#i(t);return await Ky(this.#t,r)}async readText(t){let r=await this.openReadStream(t);return(await Tc(r)).toString("utf8")}async readBuffer(t){let r=await this.openReadStream(t);return await Tc(r)}resolveRelativePath(t,r){let n=Uy(r);if(n==="")throw new Error(`Invalid EPUB href: ${r}`);return be(qi.join(qi.dirname(be(t)),n))}createSectionId(t,r){let n=be(t);return r===void 0||r===""?n:`${n}#${r}`}createSyntheticSectionId(t,r){let n=be(t);return`toc:${jy("sha1").update(`${n}:${r??""}`).digest("hex").slice(0,10)}`}get path(){return this.#e}#i(t){let r=be(t),n=this.#r.get(r);if(n===void 0)throw new Error(`EPUB entry does not exist: ${r}`);return n}}});import{Parser as zy}from"htmlparser2";async function Cc(e,t){let r=new Map;for(let[n,a]of t.entries()){let o=await e.openReadStream(n);o.setEncoding("utf8");let s=await Pc(o,a);for(let c of a){let d=s.get(c.id)??"";r.set(c.id,{hasContent:d.trim()!=="",wordsCount:eg(d)})}}return r}function Xy(e){let t=new Map;for(let[r,n]of e.entries())for(let a of n)t.set(a.id,{path:r,targets:n});return t}async function Vy(e,t){return await Pc(e,t)}async function Pc(e,t){let r=new Map,n=new Map,a=[...t],o=a.map(()=>""),c=a[0]?.fragment===void 0&&a[0]!==void 0?0:-1,d=0;a.forEach((p,S)=>{n.set(p.id,""),p.fragment!==void 0&&!r.has(p.fragment)&&r.set(p.fragment,S)});let m=new zy({onopentag(p,S){let C=p.toLowerCase();if(_c.has(C)){d+=1;return}let E=S.id??S["xml:id"];if(E!==void 0){let T=r.get(E);T!==void 0&&T>c&&(c=T)}C==="br"&&Ki(o,c,`
60
+ `)},ontext(p){d>0||Ki(o,c,p)},onclosetag(p){let S=p.toLowerCase();if(_c.has(S)){d=Math.max(0,d-1);return}Qy.has(S)&&Ki(o,c,`
61
+
62
+ `)}},{decodeEntities:!0});for await(let p of e)m.write(Zy(p));return m.end(),a.forEach((p,S)=>{n.set(p.id,Yy(o[S]??""))}),n}function Ki(e,t,r){t<0||t>=e.length||(e[t]+=r)}function Yy(e){return e.replace(/\r\n/gu,`
63
+ `).replace(/\n{3,}/gu,`
64
+
65
+ `).trim()}function Zy(e){if(typeof e=="string")return e;if(Buffer.isBuffer(e))return e.toString("utf8");throw new Error("Unexpected HTML stream chunk type")}function eg(e){return[...tg().segment(e)].filter(t=>t.isWordLike).length}function tg(){return Ji===void 0&&(Ji=new Intl.Segmenter(void 0,{granularity:"word"})),Ji}var Qy,_c,rn,Ji,Ac=i(()=>{"use strict";Qy=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),_c=new Set(["script","style"]),rn=class{#e;#t;constructor(t,r){this.#e=t,this.#t=Xy(r)}async openSection(t){let r=this.#t.get(t);return r===void 0?[]:[(await this.#r(r.path,r.targets)).get(t)??""]}async#r(t,r){let n=await this.#e.openReadStream(t);return n.setEncoding("utf8"),await Vy(n,r)}}});import{SaxesParser as rg}from"saxes";function Ht(e){let t=new rg({xmlns:!1}),r=[],n;if(t.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([c,d])=>[c,String(d)])),children:[],text:""},s=r[r.length-1];s===void 0?n=o:s.children.push(o),r.push(o)}),t.on("text",a=>{let o=r[r.length-1];o!==void 0&&(o.text+=a)}),t.on("cdata",a=>{let o=r[r.length-1];o!==void 0&&(o.text+=a)}),t.on("closetag",()=>{r.pop()}),t.write(e).close(),n===void 0)throw new Error("XML document is empty");return Lc(n)}function z(e,t){return e.children.find(r=>$t(r.name)===t)}function _e(e,t){return e.children.filter(r=>$t(r.name)===t)}function D(e,t){return e.attributes[t]}function qt(e){let t=e.text;for(let r of e.children)t+=qt(r);return t}function $t(e){let t=e.indexOf(":");return t===-1?e:e.slice(t+1)}function Lc(e){return{name:e.name,attributes:Object.freeze({...e.attributes}),children:Object.freeze(e.children.map(Lc)),text:e.text}}var zi=i(()=>{"use strict"});import{posix as ng}from"path";async function Nc(e){let t=await og(e),r=Ht(await e.readText(t)),n=sg(D(r,"version")),a=z(r,"metadata"),o=z(r,"manifest"),s=z(r,"spine"),c=z(r,"guide"),d=dg(e,t,o),m=new Map([...d.values()].map(Re=>[Re.path,Re])),p=ug(s,d),S=lg(e,t,c),C=cg(a),E=mg(d),T=pg(d,s),O=hg(d,a);return{version:n,opfPath:t,metadata:{...C,version:Te,sourceFormat:"epub"},manifest:d,manifestByPath:m,spine:p,navPath:E,ncxPath:T,coverPath:O?.path,coverMediaType:O?.mediaType,guideNonContentPaths:S}}async function og(e){let t=Ht(await e.readText("META-INF/container.xml")),n=z(t,"rootfiles")?.children.find(o=>$t(o.name)==="rootfile"),a=n===void 0?void 0:D(n,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function sg(e){return e?.trim().startsWith("3")===!0?3:2}function cg(e){if(e===void 0)return Oc();let t=$e(e,"title"),r=$e(e,"creator"),n=$e(e,"language"),a=$e(e,"identifier"),o=$e(e,"publisher"),s=$e(e,"date"),c=$e(e,"description");return{...Oc(),title:t[0]??null,authors:[...r],language:n[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:c[0]??null}}function Oc(){return{version:Te,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function $e(e,t){return e.children.filter(r=>$t(r.name)===t).map(r=>yg(qt(r))).filter(r=>r!==void 0)}function dg(e,t,r){let n=new Map;if(r===void 0)return n;for(let a of _e(r,"item")){let o=D(a,"id"),s=D(a,"href"),c=D(a,"media-type")??"";o===void 0||s===void 0||n.set(o,{id:o,path:e.resolveRelativePath(t,s),mediaType:c,properties:new Set((D(a,"properties")??"").split(/\s+/u).map(d=>d.trim().toLowerCase()).filter(d=>d!==""))})}return n}function ug(e,t){return e===void 0?[]:_e(e,"itemref").map(r=>D(r,"idref")).filter(r=>r!==void 0).map(r=>{let n=t.get(r);if(!(n===void 0||n.mediaType!=="application/xhtml+xml"&&n.mediaType!=="text/html"))return{idref:r,path:n.path,mediaType:n.mediaType}}).filter(r=>r!==void 0)}function lg(e,t,r){let n=new Set;if(r===void 0)return n;for(let a of _e(r,"reference")){let o=(D(a,"type")??"").trim().toLowerCase();if(!ag.has(o))continue;let s=D(a,"href");s===void 0||s.trim()===""||n.add(e.resolveRelativePath(t,Bt(s).path))}return n}function mg(e){for(let t of e.values())if(t.properties.has("nav"))return t.path}function pg(e,t){let r=t===void 0?void 0:D(t,"toc");if(r!==void 0)return e.get(r)?.path;for(let n of e.values())if(n.mediaType==="application/x-dtbncx+xml")return n.path}function hg(e,t){for(let n of e.values())if(n.properties.has("cover-image")&&n.mediaType.startsWith("image/"))return n;let r=fg(t);if(r!==void 0){let n=e.get(r);if(n?.mediaType.startsWith("image/")===!0)return n}for(let n of ig){let a=e.get(n);if(a?.mediaType.startsWith("image/")===!0)return a}for(let n of e.values())if(n.mediaType.startsWith("image/")&&ng.basename(n.path).toLowerCase().includes("cover"))return n}function fg(e){if(e!==void 0)for(let t of _e(e,"meta")){if((D(t,"name")??"").trim().toLowerCase()!=="cover")continue;let n=D(t,"content");if(n!==void 0&&n.trim()!=="")return n.trim()}}function yg(e){let t=e.replace(/\s+/gu," ").trim();return t===""?void 0:t}var ig,ag,Qi=i(()=>{"use strict";Gt();Ut();zi();ig=["cover-image","coverimg","cover-img","cover"],ag=new Set(["cover","titlepage","other.titlepage"])});import{basename as gg,extname as bg,posix as Sg}from"path";import{parseDocument as wg}from"htmlparser2";async function Mc(e,t){let r=await kg(e,t)??await Ig(e,t)??[];if(r.length===0)return Dc(t,new Set);let n=jc(r),a=Dc(t,n);return a.length===0?r:[...r,...a]}async function kg(e,t){if(t.navPath===void 0)return;let r=wg(await e.readText(t.navPath),{decodeEntities:!0}),n=Xi(r,s=>Ce(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(d=>d.trim().toLowerCase()).includes("toc"));if(n===void 0)return;let a=Xi(n,s=>Ce(s)==="ol");if(a===void 0)return;let o=Kt(a).filter(s=>Ce(s)==="li").map(s=>Wc(e,t.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function Ig(e,t){if(t.ncxPath===void 0)return;let r=Ht(await e.readText(t.ncxPath)),n=z(r,"navMap");if(n===void 0)return;let a=_e(n,"navPoint").map(o=>Fc(e,t.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function Wc(e,t,r){let n=Gc(r),a=n===void 0?void 0:Hc(Bc(n)),o=n!==void 0&&Ce(n)==="a"?n.attribs?.href:void 0,s=Rg(e,t,o),c=Kt(r).filter(d=>Ce(d)==="ol").flatMap(d=>Kt(d)).filter(d=>Ce(d)==="li").map(d=>Wc(e,t,d)).filter(d=>d!==void 0);if(!(a===void 0&&s.path===void 0&&c.length===0))return{title:a,path:s.path,fragment:s.fragment,children:c}}function Fc(e,t,r){let n=z(r,"navLabel"),a=n===void 0?void 0:z(n,"text"),o=a===void 0?void 0:Hc(qt(a)),s=z(r,"content"),c=vg(e,t,D(s??r,"src")),d=_e(r,"navPoint").map(m=>Fc(e,t,m)).filter(m=>m!==void 0);if(!(o===void 0&&c.path===void 0&&d.length===0))return{title:o,path:c.path,fragment:c.fragment,children:d}}function Dc(e,t){return e.spine.filter(r=>!xg(e,r.path,t)).filter(r=>!t.has(r.path)).map(r=>({title:Tg(r.path),path:r.path,fragment:void 0,children:[]}))}function xg(e,t,r){if(e.guideNonContentPaths.has(t))return!0;let n=Sg.basename(t).toLowerCase();return e.navPath===t?!0:Eg.has(n)&&!r.has(t)}function jc(e){let t=new Set;for(let r of e){r.path!==void 0&&t.add(r.path);for(let n of jc(r.children))t.add(n)}return t}function Rg(e,t,r){if(r===void 0||r.trim()==="")return{path:void 0,fragment:void 0};let{path:n,fragment:a}=Bt(r);return{path:n===""?void 0:e.resolveRelativePath(t,n),fragment:a}}function vg(e,t,r){if(r===void 0||r.trim()==="")return{path:void 0,fragment:void 0};let{path:n,fragment:a}=Bt(r);return{path:n===""?void 0:e.resolveRelativePath(t,n),fragment:a}}function Xi(e,t){if(Uc(e)&&t(e))return e;for(let r of e.children??[]){let n=Xi(r,t);if(n!==void 0)return n}}function Gc(e){for(let t of Kt(e)){let r=Ce(t);if(r==="a"||r==="span")return t}for(let t of Kt(e)){if(Ce(t)==="ol")continue;let r=Gc(t);if(r!==void 0)return r}}function Bc(e){return e.type==="text"?e.data??"":(e.children??[]).map(Bc).join("")}function Kt(e){return(e.children??[]).filter(Uc)}function Uc(e){return e.type==="tag"||e.type==="script"||e.type==="style"}function Ce(e){return e.name?.toLowerCase()}function Tg(e){let t=gg(e,bg(e)).trim();return t===""?void 0:t}function Hc(e){let t=e.replace(/\s+/gu," ").trim();return t===""?void 0:t}var Eg,qc=i(()=>{"use strict";Ut();Qi();zi();Eg=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function _g(e){if(e.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function Cg(e,t){if(!(t.coverPath===void 0||t.coverMediaType===void 0))return{path:t.coverPath,mediaType:t.coverMediaType,data:await e.readBuffer(t.coverPath)}}function Pg(e,t){let r=new Map;return t.map((n,a)=>$c(e,n,[a],r))}function $c(e,t,r,n){let a=$i(t.fragment),o=t.path===void 0?`toc:${r.join(".")}`:e.createSectionId(t.path,a),s=Ag(o,n);return{hasContent:t.path!==void 0,id:s,title:t.title,path:t.path,fragment:a,wordsCount:0,children:t.children.map((c,d)=>$c(e,c,[...r,d],n))}}function Kc(e,t){return e.map(r=>{let n=t.get(r.id);return{...r,hasContent:n?.hasContent??!1,wordsCount:n?.wordsCount??0,children:Kc(r.children,t)}})}function Ag(e,t){let r=t.get(e)??0;return t.set(e,r+1),r===0?e:`${e}~${r+1}`}function Lg(e){let t=new Map;for(let r of Jc(e)){if(r.path===void 0)continue;let n=t.get(r.path)??[];n.push({id:r.id,path:r.path,fragment:r.fragment}),t.set(r.path,n)}return t}function Jc(e){let t=[];for(let r of e)t.push(r),t.push(...Jc(r.children));return t}var Vi,Yi,Jt,Zi,zc=i(()=>{"use strict";Ut();Ut();Ac();qc();Qi();Vi=class e{#e;#t;constructor(t,r){this.#e=t,this.#t=r}get id(){return this.#t.id}get hasContent(){return this.#t.hasContent}get title(){return this.#t.title}get wordsCount(){return this.#t.wordsCount}get children(){return this.#t.children.map(t=>new e(this.#e,t))}async open(){return await this.#e.openSection(this.#t.id)}},Yi=class e{#e;#t;#r;#n;constructor(t,r,n,a){this.#e=t,this.#t=r,this.#r=n,this.#n=a}static async open(t){_g(t);let r=await Nc(t),n=await Mc(t,r),a=Pg(t,n),o=Lg(a),s=await Cc(t,o),c=Kc(a,s),d=await Cg(t,r);return new e(r,d,c,new rn(t,o))}readMeta(){return Promise.resolve(this.#e.metadata)}readCover(){return Promise.resolve(this.#t)}readSections(){return Promise.resolve(this.#r.map(t=>new Vi(this,t)))}async openSection(t){return await this.#n.openSection(t)}},Jt=class{get format(){return"epub"}async openSession(t,r){let n=await tn.open(t);try{let a=await Yi.open(n);return await r(a)}finally{await n.close()}}},Zi=new Jt});var Qc=i(()=>{"use strict";zc()});import{createReadStream as Og}from"fs";import{stat as Ng}from"fs/promises";import{basename as Dg,extname as Mg,resolve as ra}from"path";function Fg(e){let t=Dg(e,Mg(e)).trim();return t===""?null:t}var Wg,ea,ta,zt,Xc,Vc,Yc=i(()=>{"use strict";Gt();Wg="root",ea=class{#e;#t;constructor(t,r=Wg){this.#e=ra(t),this.#t=r}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Og(this.#e,{encoding:"utf8"}))}},ta=class{#e;#t;#r;constructor(t,r){this.#e=ra(t),this.#t=r,this.#r=new ea(this.#e)}readMeta(){return Promise.resolve({version:Te,sourceFormat:this.#t,title:Fg(this.#e),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#r])}},zt=class{#e;constructor(t){this.#e=t}get format(){return this.#e}async openSession(t,r){let n=ra(t);if(!(await Ng(n)).isFile())throw new Error(`Source file is not a regular file: ${n}`);return await r(new ta(n,this.#e))}},Xc=new zt("txt"),Vc=new zt("markdown")});var Ke=i(()=>{"use strict";Gt();Qc();Yc();en()});var na=i(()=>{"use strict"});var Qt=i(()=>{"use strict";Ke();ye();na()});var Zc,ed,Xt=i(()=>{"use strict";Zc=`
66
+ id INTEGER PRIMARY KEY,
67
+ archive_id INTEGER NOT NULL,
68
+ kind INTEGER NOT NULL,
69
+ chapter_id INTEGER NOT NULL,
70
+ sentence_index INTEGER NOT NULL,
71
+ words_count INTEGER NOT NULL DEFAULT 0,
72
+ byte_offset INTEGER NOT NULL DEFAULT 0,
73
+ byte_length INTEGER NOT NULL DEFAULT 0,
74
+ UNIQUE(archive_id, kind, chapter_id, sentence_index)
75
+ `,ed=`
76
+ CREATE TABLE IF NOT EXISTS search_index_state (
77
+ key TEXT PRIMARY KEY,
78
+ value TEXT NOT NULL
79
+ );
80
+
81
+ CREATE TABLE IF NOT EXISTS text_sentence_records (
82
+ ${Zc}
83
+ );
84
+
85
+ CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
86
+ ON text_sentence_records(archive_id, kind, chapter_id, sentence_index);
87
+
88
+ CREATE VIRTUAL TABLE IF NOT EXISTS text_sentence_fts USING fts5(
89
+ tier1,
90
+ tier2,
91
+ tier3,
92
+ tokenize='ascii'
93
+ );
94
+
95
+ CREATE TABLE IF NOT EXISTS search_object_properties_records (
96
+ id INTEGER PRIMARY KEY,
97
+ archive_id INTEGER NOT NULL,
98
+ owner_kind INTEGER NOT NULL,
99
+ owner_id TEXT NOT NULL,
100
+ property_kind INTEGER NOT NULL,
101
+ chapter_id INTEGER
102
+ );
103
+
104
+ CREATE INDEX IF NOT EXISTS idx_search_object_properties_records_owner
105
+ ON search_object_properties_records(archive_id, owner_kind, owner_id);
106
+
107
+ CREATE INDEX IF NOT EXISTS idx_search_object_properties_records_chapter
108
+ ON search_object_properties_records(archive_id, chapter_id, owner_kind, owner_id);
109
+
110
+ CREATE VIRTUAL TABLE IF NOT EXISTS search_object_properties_fts USING fts5(
111
+ tier1,
112
+ tier2,
113
+ tier3,
114
+ tokenize='ascii'
115
+ );
116
+
117
+ CREATE TABLE IF NOT EXISTS index_dirty_chapters (
118
+ archive_id INTEGER NOT NULL,
119
+ chapter_id INTEGER NOT NULL,
120
+ updated_at INTEGER NOT NULL,
121
+ PRIMARY KEY (archive_id, chapter_id)
122
+ );
123
+ `});var Je=i(()=>{"use strict";f();fe()});var td=i(()=>{"use strict";f();Je()});var rd=i(()=>{"use strict";f()});import{createHash as jT}from"crypto";var nn=i(()=>{"use strict"});var id=i(()=>{"use strict";f();nn()});var ad=i(()=>{"use strict";f();Je()});var od=i(()=>{"use strict";f();Je()});var sd=i(()=>{"use strict";f();Je()});var cd=i(()=>{"use strict";f();Je()});var dd=i(()=>{"use strict";f();Je()});var ud=i(()=>{"use strict";f()});var ld=i(()=>{"use strict";f()});var md=i(()=>{"use strict";f()});var pd=i(()=>{"use strict";ud();ld();md()});var oa=i(()=>{"use strict";td();rd();id();ad();od();sd();cd();dd();pd()});var sa=i(()=>{"use strict"});import{mkdir as M_,readFile as W_,readdir as F_,rm as j_,unlink as G_,writeFile as B_}from"fs/promises";import{join as H_}from"path";var ca=i(()=>{"use strict";b()});import{join as J_}from"path";var Rd=i(()=>{"use strict";b()});import{stat as V_}from"fs/promises";import{join as Z_}from"path";var vd=i(()=>{"use strict";b();f();Xt()});var Td=i(()=>{"use strict";b();sa()});var _d=i(()=>{"use strict"});import{AsyncLocalStorage as vC}from"async_hooks";import{join as _C,resolve as CC}from"path";import{z as da}from"zod";var $C,Ad=i(()=>{"use strict";Gt();en();Qt();f();Wi();Xt();oa();fe();sa();ca();Rd();vd();Td();_d();$C=da.object({mediaType:da.string().min(1),path:da.string()})});var Ld=i(()=>{"use strict"});var ua=i(()=>{"use strict";Ad();ca();Ld()});var Nd=i(()=>{"use strict";Bi()});var I=i(()=>{"use strict";f();lc();Wi();Bi();ua();Nd();Xt();oa();fe()});var la,Qe=i(()=>{"use strict";la=`
124
+ CREATE TABLE IF NOT EXISTS search_sessions (
125
+ session_id TEXT PRIMARY KEY,
126
+ archive_key TEXT NOT NULL,
127
+ query TEXT NOT NULL,
128
+ options_json TEXT NOT NULL,
129
+ terms_json TEXT NOT NULL,
130
+ lens TEXT NOT NULL,
131
+ match TEXT NOT NULL,
132
+ object_caches_populated INTEGER NOT NULL DEFAULT 0,
133
+ created_at INTEGER NOT NULL,
134
+ expires_at INTEGER NOT NULL,
135
+ accessed_at INTEGER NOT NULL
136
+ );
137
+
138
+ CREATE TABLE IF NOT EXISTS search_results (
139
+ session_id TEXT NOT NULL,
140
+ rank INTEGER NOT NULL,
141
+ item_json TEXT NOT NULL,
142
+ PRIMARY KEY (session_id, rank)
143
+ );
144
+
145
+ CREATE TABLE IF NOT EXISTS predicate_dictionary (
146
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
147
+ value TEXT NOT NULL UNIQUE
148
+ );
149
+
150
+ CREATE TABLE IF NOT EXISTS search_evidence_hit_events (
151
+ session_id TEXT NOT NULL,
152
+ archive_id INTEGER NOT NULL,
153
+ evidence_kind INTEGER NOT NULL,
154
+ evidence_id TEXT NOT NULL,
155
+ chapter_id INTEGER NOT NULL,
156
+ sentence_index INTEGER NOT NULL,
157
+ score REAL NOT NULL,
158
+ PRIMARY KEY (
159
+ session_id,
160
+ archive_id,
161
+ evidence_kind,
162
+ evidence_id,
163
+ chapter_id,
164
+ sentence_index
165
+ )
166
+ );
167
+
168
+ CREATE INDEX IF NOT EXISTS idx_search_evidence_hit_events_evidence_rank
169
+ ON search_evidence_hit_events(session_id, archive_id, evidence_kind, evidence_id, score DESC, chapter_id, sentence_index);
170
+
171
+ CREATE INDEX IF NOT EXISTS idx_search_evidence_hit_events_sentence
172
+ ON search_evidence_hit_events(session_id, archive_id, chapter_id, sentence_index, evidence_kind, evidence_id);
173
+
174
+ CREATE TABLE IF NOT EXISTS search_entity_hits (
175
+ session_id TEXT NOT NULL,
176
+ archive_id INTEGER NOT NULL,
177
+ qid TEXT NOT NULL,
178
+ property_top_scores_json TEXT NOT NULL DEFAULT '[]',
179
+ evidence_top_scores_json TEXT NOT NULL DEFAULT '[]',
180
+ property_score REAL NOT NULL DEFAULT 0,
181
+ evidence_score REAL NOT NULL DEFAULT 0,
182
+ result_score REAL NOT NULL DEFAULT 0,
183
+ PRIMARY KEY (session_id, archive_id, qid)
184
+ );
185
+
186
+ CREATE INDEX IF NOT EXISTS idx_search_entity_hits_rank
187
+ ON search_entity_hits(session_id, result_score DESC, archive_id, qid);
188
+
189
+ CREATE TABLE IF NOT EXISTS search_triple_hits (
190
+ session_id TEXT NOT NULL,
191
+ archive_id INTEGER NOT NULL,
192
+ subject_qid TEXT NOT NULL,
193
+ predicate_id INTEGER NOT NULL,
194
+ object_qid TEXT NOT NULL,
195
+ evidence_top_scores_json TEXT NOT NULL DEFAULT '[]',
196
+ result_score REAL NOT NULL DEFAULT 0,
197
+ PRIMARY KEY (session_id, archive_id, subject_qid, predicate_id, object_qid),
198
+ FOREIGN KEY (predicate_id) REFERENCES predicate_dictionary(id)
199
+ );
200
+
201
+ CREATE INDEX IF NOT EXISTS idx_search_triple_hits_rank
202
+ ON search_triple_hits(session_id, result_score DESC, archive_id, subject_qid, predicate_id, object_qid);
203
+
204
+ CREATE TABLE IF NOT EXISTS search_chunk_hits (
205
+ session_id TEXT NOT NULL,
206
+ archive_id INTEGER NOT NULL,
207
+ chunk_id INTEGER NOT NULL,
208
+ property_top_scores_json TEXT NOT NULL DEFAULT '[]',
209
+ evidence_top_scores_json TEXT NOT NULL DEFAULT '[]',
210
+ property_score REAL NOT NULL DEFAULT 0,
211
+ evidence_score REAL NOT NULL DEFAULT 0,
212
+ result_score REAL NOT NULL DEFAULT 0,
213
+ PRIMARY KEY (session_id, archive_id, chunk_id)
214
+ );
215
+
216
+ CREATE INDEX IF NOT EXISTS idx_search_chunk_hits_rank
217
+ ON search_chunk_hits(session_id, result_score DESC, archive_id, chunk_id);
218
+
219
+ CREATE INDEX IF NOT EXISTS idx_search_sessions_archive
220
+ ON search_sessions(archive_key, session_id);
221
+
222
+ CREATE INDEX IF NOT EXISTS idx_search_sessions_expires
223
+ ON search_sessions(expires_at);
224
+
225
+ CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
226
+ ON search_sessions(accessed_at DESC, created_at DESC, session_id);
227
+ `});import{join as Bg}from"path";import{rm as Md}from"fs/promises";async function ut(){let e=pa(),t=await v(e,la);return ma===e?t:await Hg(t)?(ma=e,t):(await t.close(),await Md(e,{force:!0}),await Md(`${e}.initialized`,{force:!0}),ma=e,await v(e,la))}function pa(){return Bg(Ug(),"search-sessions.sqlite")}function Ug(){return Ge()}async function Hg(e){return await an(e,"search_entity_hits","archive_id")&&await an(e,"search_chunk_hits","archive_id")&&await an(e,"search_triple_hits","archive_id")&&await an(e,"search_evidence_hit_events","archive_id")}async function an(e,t,r){return(await e.queryAll(`PRAGMA table_info(${t})`,void 0,a=>String(a.name))).includes(r)}var ma,lt=i(()=>{"use strict";N();I();Qe()});var on=i(()=>{"use strict"});async function ha(e,t){await e.run("DELETE FROM search_results WHERE session_id = ?",[t]),await e.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[t]),await e.run("DELETE FROM search_entity_hits WHERE session_id = ?",[t]),await e.run("DELETE FROM search_triple_hits WHERE session_id = ?",[t]),await e.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[t]),await e.run("DELETE FROM search_sessions WHERE session_id = ?",[t])}async function Wd(e){await e.run(`
228
+ DELETE FROM predicate_dictionary
229
+ WHERE NOT EXISTS (
230
+ SELECT 1
231
+ FROM search_triple_hits
232
+ WHERE search_triple_hits.predicate_id = predicate_dictionary.id
233
+ )
234
+ `)}var fa=i(()=>{"use strict";f();lt();on();Qe()});import{stat as Kg}from"fs/promises";async function sn(e){let t=pa(),r=await Fd(t),n=await ut();try{let a=await n.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,m=>g(m,"count")),o=e.force?await zg(n):await Jg(n,e.now),s=e.force?[]:await Qg(n),c=[...new Set([...o,...s])].sort();!e.dryRun&&c.length>0&&(await n.transaction(async()=>{for(let m of c)await ha(n,m);await Wd(n)}),await n.run("VACUUM"));let d=await Fd(t);return{freedBytes:Math.max(0,r-d),removed:c.length,scanned:a??0}}finally{await n.close()}}async function Jg(e,t){return await e.queryAll(`
235
+ SELECT session_id
236
+ FROM search_sessions
237
+ WHERE expires_at < ?
238
+ `,[t],r=>w(r,"session_id"))}async function zg(e){return await e.queryAll("SELECT session_id FROM search_sessions",void 0,t=>w(t,"session_id"))}async function Qg(e){return await e.queryAll(`
239
+ SELECT session_id
240
+ FROM search_sessions
241
+ ORDER BY accessed_at DESC, created_at DESC, session_id
242
+ LIMIT -1 OFFSET ?
243
+ `,[500],t=>w(t,"session_id"))}async function Fd(e){try{return(await Kg(e)).size}catch(t){if(h(t)&&t.code==="ENOENT")return 0;throw t}}var jd=i(()=>{"use strict";f();b();lt();Qe();fa()});var Gd=i(()=>{"use strict";Qe()});var ya=i(()=>{"use strict"});var cn=i(()=>{"use strict";f();lt();on();Gd();ya()});import{createHash as KP}from"crypto";var Ud=i(()=>{"use strict";Qe()});var Hd=i(()=>{"use strict";f();Ti();lt();cn();Ud();on();Qe();fa()});var qd=i(()=>{"use strict";f();lt();cn()});var Xe=i(()=>{"use strict";Ti();jd();cn();Hd();qd();ya()});var un=i(()=>{"use strict"});var Yd=i(()=>{"use strict"});var ba=i(()=>{"use strict"});var ln=i(()=>{"use strict"});var Sa=i(()=>{"use strict";ln()});var wa=i(()=>{"use strict";ln()});var pn=i(()=>{"use strict";un();ba();Sa();wa()});var ka=i(()=>{"use strict"});import{isAbsolute as ZA,relative as eL,resolve as tL}from"path";import{homedir as nL}from"os";var Pe=i(()=>{"use strict";ka()});var iu=i(()=>{"use strict";Pe()});var au=i(()=>{"use strict";un();Yd();ba();ln();pn();Sa();wa();iu()});var R=i(()=>{"use strict";au()});var Ia=i(()=>{"use strict"});var xa=i(()=>{"use strict";Qt();na();Ia()});var ou=i(()=>{"use strict";xa()});var W=i(()=>{"use strict";xa();ou();Ia()});import{createHash as ML}from"crypto";var WL,FL,tr=i(()=>{"use strict";WL=new RegExp("\\p{Script=Han}+","gu"),FL=new RegExp("^\\p{Script=Han}+$","u")});import{createHash as BL}from"crypto";async function mt(e){return await e.queryOne(`
244
+ SELECT value
245
+ FROM search_index_state
246
+ WHERE key = 'fingerprint'
247
+ `,void 0,t=>String(t.value))}var fn=i(()=>{"use strict"});var pt=i(()=>{"use strict"});var va=i(()=>{"use strict";pt()});var uu=i(()=>{"use strict";f();va()});var mu=i(()=>{"use strict";tr();fn();uu();pt()});var hu=i(()=>{"use strict";pt()});var fu=i(()=>{"use strict";tr()});var yu=i(()=>{"use strict"});var _a=i(()=>{"use strict";f();yu();fn()});var gu=i(()=>{"use strict";f();tr();fu();va();pt();_a()});var bu=i(()=>{"use strict";f()});var Su=i(()=>{"use strict";mu();hu();fn();gu();bu();_a();pt()});var Le=i(()=>{"use strict";Su();tr()});var rr=i(()=>{"use strict";W();Le()});var L=i(()=>{"use strict";Pe();R()});var Q=i(()=>{"use strict";Pe();R()});var ie=i(()=>{"use strict";R();L()});var X=i(()=>{"use strict";W();Le();R();L();Q();ie();R();rr()});var sr=i(()=>{"use strict";Xe();Le();X();Q()});var La=i(()=>{"use strict";W();Mt();R();L();ie();Q()});var cr=i(()=>{"use strict"});var oe=i(()=>{"use strict";W();cr();R();L();ie()});var dr=i(()=>{"use strict";ie()});var ur=i(()=>{"use strict";L();ie();oe()});var Oa=i(()=>{"use strict";R();oe();dr();ur()});var Pu=i(()=>{"use strict";Le();R();X();oe();dr();Oa();ur();ur();dr()});var Au=i(()=>{"use strict";Pu();Oa();dr();ur()});var mr=i(()=>{"use strict";Au()});var Ou=i(()=>{"use strict";Xe();R();L();ie();oe();Q();mr()});var hr=i(()=>{"use strict";L();oe();R();Q();mr();Ou()});var Ma=i(()=>{"use strict";W();R();L();ie();oe();hr();fr();Q()});var fr=i(()=>{"use strict";R();L();ie();Q();Ma()});var kn=i(()=>{"use strict";R();X();Q()});var In=i(()=>{"use strict";R();X()});var xn=i(()=>{"use strict";W();Mt();Xe();Le();R();sr();La();hr();fr();X();kn();In()});var Fu=i(()=>{"use strict";Mt();Xe();R();rr();sr();La();hr();fr();xn();X()});var ju=i(()=>{"use strict";Fu();kn();In();xn();sr();X()});var Rn=i(()=>{"use strict";oe();mr();L()});var yr=i(()=>{"use strict";R()});var vn=i(()=>{"use strict";R();L();X();sr();Le();yr()});var Fa=i(()=>{"use strict";R();Q();Rn();vn();yr()});import{stat as Hb}from"fs/promises";async function ja(e){let t=Dt(),r=await Gu(t);if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let n=await v(t,qb);try{await Jb(n);let a=await Xb(n),o=new Date(e.now-$b).toISOString(),s=await Vb(n,o);!e.dryRun&&s>0&&(await n.transaction(async()=>{await n.run("DELETE FROM qid_cache WHERE checked_at < ?",[o]),await n.run("DELETE FROM disambiguation_cache WHERE checked_at < ?",[o])}),await n.run("VACUUM"));let c=await Gu(t);return{freedBytes:e.dryRun?Kb(r,a,s):Math.max(0,r-(c??0)),removed:s,scanned:a}}finally{await n.close()}}function Kb(e,t,r){return t===0||r===0?0:Math.round(e*(r/t))}async function Jb(e){await zb(e),await Qb(e)}async function zb(e){(await gr(e,"qid_cache")).has("language")||await e.transaction(async()=>{(await gr(e,"qid_cache")).has("language")||(await e.run("ALTER TABLE qid_cache RENAME TO qid_cache_legacy"),await e.run(Bu),await e.run(`
248
+ INSERT OR IGNORE INTO qid_cache (
249
+ qid, language, label, description, pages_json, checked_at, updated_at
250
+ )
251
+ SELECT qid, 'en', label, description, pages_json, checked_at, updated_at
252
+ FROM qid_cache_legacy
253
+ `),await e.run("DROP TABLE qid_cache_legacy"))})}async function Qb(e){(await gr(e,"disambiguation_cache")).has("wiki")||await e.transaction(async()=>{(await gr(e,"disambiguation_cache")).has("wiki")||(await e.run("ALTER TABLE disambiguation_cache RENAME TO disambiguation_cache_legacy"),await e.run(Uu),await e.run(`
254
+ INSERT OR IGNORE INTO disambiguation_cache (
255
+ qid, wiki, pages_json, profile_json, checked_at
256
+ )
257
+ SELECT qid, 'enwiki', pages_json, profile_json, checked_at
258
+ FROM disambiguation_cache_legacy
259
+ `),await e.run("DROP TABLE disambiguation_cache_legacy"))}),(await gr(e,"disambiguation_cache")).has("profile_error_json")||await e.run("ALTER TABLE disambiguation_cache ADD COLUMN profile_error_json TEXT")}async function gr(e,t){let r=await e.queryAll(`PRAGMA table_info(${t})`,void 0,n=>Yb(n.name,"name"));return new Set(r)}async function Xb(e){let t=await Tn(e,"qid_cache"),r=await Tn(e,"disambiguation_cache");return t+r}async function Vb(e,t){let r=await Tn(e,"qid_cache",t),n=await Tn(e,"disambiguation_cache",t);return r+n}async function Tn(e,t,r){return await e.queryOne(`
260
+ SELECT COUNT(*) AS count
261
+ FROM ${t}
262
+ ${r===void 0?"":"WHERE checked_at < ?"}
263
+ `,r===void 0?void 0:[r],n=>g(n,"count"))??0}async function Gu(e){try{return(await Hb(e)).size}catch(t){if(h(t)&&t.code==="ENOENT")return;throw t}}function Yb(e,t){if(typeof e!="string")throw new Error(`Expected ${t} to be a string.`);return e}var Bu,Uu,qb,$b,Ga=i(()=>{"use strict";N();f();I();b();Bu=`
264
+ CREATE TABLE IF NOT EXISTS qid_cache (
265
+ qid TEXT NOT NULL,
266
+ language TEXT NOT NULL,
267
+ label TEXT,
268
+ description TEXT,
269
+ pages_json TEXT NOT NULL,
270
+ checked_at TEXT NOT NULL,
271
+ updated_at TEXT NOT NULL,
272
+ PRIMARY KEY (qid, language)
273
+ );
274
+ `,Uu=`
275
+ CREATE TABLE IF NOT EXISTS disambiguation_cache (
276
+ qid TEXT NOT NULL,
277
+ wiki TEXT NOT NULL,
278
+ pages_json TEXT NOT NULL,
279
+ profile_json TEXT,
280
+ profile_error_json TEXT,
281
+ checked_at TEXT NOT NULL,
282
+ PRIMARY KEY (qid, wiki)
283
+ );
284
+ `,qb=`
285
+ ${Bu}
286
+
287
+ CREATE INDEX IF NOT EXISTS idx_qid_cache_checked_at
288
+ ON qid_cache(checked_at);
289
+
290
+ ${Uu}
291
+
292
+ CREATE INDEX IF NOT EXISTS idx_disambiguation_cache_checked_at
293
+ ON disambiguation_cache(checked_at);
294
+ `,$b=720*60*60*1e3});var Ba=i(()=>{"use strict"});var Ua=i(()=>{"use strict"});import{jsonrepair as JW}from"jsonrepair";var Hu=i(()=>{"use strict"});var qu=i(()=>{"use strict";Ua();Ba();Hu()});var G=i(()=>{"use strict";Ba();Ua();qu()});import{z as B}from"zod";var rS,yF,$u=i(()=>{"use strict";G();rS=B.object({category:B.string().min(1).optional(),information:B.string(),name:B.string().min(1),priority:B.enum(["primary","secondary","other"]),qid:B.union([B.string(),B.null()])}).strict(),yF=B.object({meanings:B.array(rS),sourceQid:B.string().regex(/^Q[1-9]\d*$/u),surface:B.string().min(1).optional()}).strict()});var $a=i(()=>{"use strict"});import{AsyncLocalStorage as nS}from"async_hooks";import{randomUUID as EF}from"crypto";import{existsSync as IF,mkdirSync as xF}from"fs";import{dirname as vF,join as TF,resolve as _F}from"path";import iS,{multistream as PF}from"pino";import LF from"pino-pretty";var OF,NF,V=i(()=>{"use strict";OF=new nS,NF=iS({enabled:!1})});import{createHash as FF}from"crypto";import{appendFile as GF}from"fs/promises";var Ku=i(()=>{"use strict";V();b()});var _n=i(()=>{"use strict"});import{DomUtils as KF,parseDocument as JF}from"htmlparser2";var Ka=i(()=>{"use strict";_n()});var Ju=i(()=>{"use strict"});var Ja=i(()=>{"use strict";_n()});var Xu=i(()=>{"use strict";V();b();$a();Ka();_n();Ju();Ja()});var za=i(()=>{"use strict";Xu();Ka();Ja()});var Pj,Zu=i(()=>{"use strict";Ga();Ku();G();za();Pj=360*60*1e3});var Sr=i(()=>{"use strict";Ga();$u();$a();Zu();za()});var Xa=i(()=>{"use strict";Sr()});var tl=i(()=>{"use strict";cr();R();oe();Rn();Fa();vn();yr();Xa();L()});var Cn=i(()=>{"use strict";tl();Fa();Rn();vn();yr();Xa()});var Va=i(()=>{"use strict";Pe();W();cr();R();oe();mr();fr();Q();Cn();L();ie()});var rl=i(()=>{"use strict";Va();Cn();L()});var so=i(()=>{"use strict";ju();Va();Cn();rr();L();Ma();hr();rl()});var nl=i(()=>{"use strict";so()});import{randomBytes as qG}from"crypto";import{join as KG}from"path";var pS,il=i(()=>{"use strict";N();f();I();pS=10080*60*1e3});var al=i(()=>{"use strict"});var ol=i(()=>{"use strict";f();il();al()});var sl=i(()=>{"use strict"});var cl=i(()=>{"use strict";ol();sl()});var yt=i(()=>{"use strict";nl();cl();Xe()});import{existsSync as ml,statSync as pl}from"fs";import{fileURLToPath as hS}from"url";import{dirname as hl,join as ll,parse as fS,resolve as co}from"path";function On(){let e=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof e=="string"&&e!=="")return e;let t=yS();return t!==void 0?t:gS()}function yS(){let e=hl(hS(import.meta.url));for(let t of[co(e,"../../../data"),co(e,"../../data"),co(e,"../data")])if(ml(t)&&pl(t).isDirectory())return t}function gS(){let e=process.cwd(),t=fS(e).root;for(;;){for(let r of[ll(e,"data"),ll(e,"packages","core","data")])if(ml(r)&&pl(r).isDirectory())return r;if(e===t)throw new Error("Could not locate data directory");e=hl(e)}}var Nn=i(()=>{"use strict"});import{readFile as w0,writeFile as E0}from"fs/promises";import{join as I0}from"path";var fl=i(()=>{"use strict";b()});import{existsSync as _0,mkdirSync as C0,statSync as P0}from"fs";import{resolve as L0}from"path";var yl=i(()=>{"use strict";fl()});var gl=i(()=>{"use strict"});var bl=i(()=>{"use strict";b()});var Sl=i(()=>{"use strict"});import{APICallError as G0}from"ai";var wl=i(()=>{"use strict"});import{readFileSync as H0,statSync as q0}from"fs";import{resolve as K0,sep as J0}from"path";import{Environment as Q0,Loader as X0}from"nunjucks";var Dn=i(()=>{"use strict"});var Ze,kr=i(()=>{"use strict";Ze=class{#e=0;#t;#r=[];constructor(t){if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");this.#t=t}async use(t){await this.#n();try{return await t()}finally{this.#i()}}async#n(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(t=>{this.#r.push(()=>{this.#e+=1,t()})})}#i(){this.#e-=1,this.#r.shift()?.()}}});var uo=i(()=>{"use strict";V()});var lo=i(()=>{"use strict"});import{appendFile as nB}from"fs/promises";var El=i(()=>{"use strict";V()});var mo=i(()=>{"use strict"});import{setTimeout as SB}from"timers/promises";import{generateText as vB,streamText as TB}from"ai";var xl=i(()=>{"use strict";yl();gl();bl();Sl();wl();V();Dn();kr();nn();b();uo();lo();El();mo()});var Rl=i(()=>{"use strict";xl()});var ho=i(()=>{"use strict";Rl();uo();lo();mo()});var fo=i(()=>{"use strict";V()});var vl=i(()=>{"use strict";fo()});var Tl=i(()=>{"use strict";vl();fo()});var _l=i(()=>{"use strict"});var Cl=i(()=>{"use strict"});var Pl=i(()=>{"use strict";_l();Cl()});function Mn(e){let t=e.trim();return t===""?[]:Array.from(RS.segment(t)).map(r=>r.segment.trim()).filter(r=>r!=="")}function Y(e){let t=e.replace(/\s+/gu," ").trim(),r=vS(t),n="";for(let a of r)if(!TS(a)){if(!Ir(a)){n+=a;continue}n+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return n}function vS(e){let t=[],r=0;for(;r<e.length;){let n=e[r];if(n===void 0)break;if(n!==" "){t.push(n),r+=1;continue}if(t.length>=2&&xS.has(t[t.length-1]??"")&&Ir(t[t.length-2]??"")&&r<e.length-1&&Ir(e[r+1]??"")){t.pop(),r+=1;continue}let a=t[t.length-1]??"",o=e[r+1]??"";a!==""&&o!==""&&Ir(a)&&Ir(o)&&t.push(n),r+=1}return t}function Ir(e){return e!==""&&new RegExp("\\p{Script=Latin}","u").test(e)&&new RegExp("\\p{L}","u").test(e)}function TS(e){return/[\p{P}\p{S}]/u.test(e)}var xS,RS,xr=i(()=>{"use strict";xS=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),RS=new Intl.Segmenter(void 0,{granularity:"sentence"})});function go(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Ll(e,t){let r=Wn(e,2),n=Wn(t,2),a=Wn(e,3),o=Wn(t,3);return(Al(r,n)+Al(a,o))/2}function Wn(e,t){if(e.length<=t)return e===""?new Set:new Set([e]);let r=new Set;for(let n=0;n<=e.length-t;n+=1)r.add(e.slice(n,n+t));return r}function Al(e,t){if(e.size===0||t.size===0)return 0;let r=0;for(let n of e)t.has(n)&&(r+=1);return 2*r/(e.size+t.size)}function Ol(e,t){if(e===t)return 1;if(e===""||t==="")return 0;let r=Array.from({length:t.length+1},(o,s)=>s),n=new Array(t.length+1).fill(0);for(let[o,s]of[...e].entries()){n[0]=o+1;for(let[c,d]of[...t].entries()){let m=(n[c]??0)+1,p=(r[c+1]??0)+1,S=(r[c]??0)+(s===d?0:1);n[c+1]=Math.min(m,p,S)}[r,n]=[n,r]}return 1-(r[t.length]??Math.max(e.length,t.length))/Math.max(e.length,t.length)}function Nl(e,t){return 1-Math.abs(e.length-t.length)/Math.max(e.length,t.length)}function Dl(e,t){if(e===t)return 1;let r=e.length,n=t.length;if(r===0||n===0)return 0;let a=Array.from({length:r+1},()=>new Array(n+1).fill(0)),o=0;for(let s=1;s<=r;s+=1)for(let c=1;c<=n;c+=1){if(e[s-1]!==t[c-1])continue;let d=a[s];d!==void 0&&(d[c]=(a[s-1]?.[c-1]??0)+1,o=Math.max(o,d[c]??0))}return 2*o/(r+n)}function Ml(e){return` - ${e.occurrenceId} score=${e.score.toFixed(3)}
295
+ prev: ${yo(e.prevText)}
296
+ text: ${yo(e.text,120)}
297
+ next: ${yo(e.nextText)}`}function yo(e,t=80){let r=e.replace(/\s+/gu," ").trim();return r===""?"(none)":r.length<=t?r:`${r.slice(0,t-3)}...`}var bo=i(()=>{"use strict"});var So=i(()=>{"use strict"});function Fl(e,t,r){return e.mode==="head_tail"?PS(e,t):wo(e.text??"",t,r)}function PS(e,t){let r=e.head??"",n=e.tail??"",a=Y(t),o=Y(r),s=Y(n);if(o===""||s==="")return go();let c=a.indexOf(o),d=a.lastIndexOf(s);if(c!==-1&&d!==-1&&c<=d){let C=o.length+s.length,E=Math.min(1,C/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:d+s.length,matchStart:c,score:.82+.18*E}}let m=wo(r,t,"start_anchor"),p=wo(n,t,"end_anchor"),S=m.matchStart<=p.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(m.matchEnd,p.matchEnd),matchStart:Math.min(m.matchStart,p.matchStart),score:(m.score+p.score)/2*S}}function wo(e,t,r){let n=e.trim(),a=t.trim(),o=Y(n),s=Y(a);if(o===""||s==="")return go();if(n===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let E=s.indexOf(o),T=o.length/Math.max(1,s.length),O=Wl({candidateNormalized:s,label:r,matchEnd:E+o.length,matchStart:E,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:E+o.length,matchStart:E,score:Math.min(1,.75+.25*T+O)}}if(o.includes(s)){let E=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*E)}}let c=0,d=-1,m=-1,p=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),S=Math.min(p,Math.max(1,Math.floor(o.length*.8))),C=new Set(o);for(let E=S;E<=p;E+=1)for(let T=0;T<=s.length-E;T+=1){let O=s.slice(T,T+E),Re=new Set(O),Ks=new Set([...C,...Re]).size,Ff=[...C].filter(jf=>Re.has(jf)).length;if((Ks===0?0:Ff/Ks)<.35)continue;let Js=.35*Ll(o,O)+.35*Dl(o,O)+.2*Ol(o,O)+.1*Nl(o,O)+Wl({candidateNormalized:s,label:r,matchEnd:T+E,matchStart:T,queryNormalized:o});Js>c&&(c=Math.min(1,Js),d=T,m=T+E)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:m,matchStart:d,score:c}}function Wl(e){if(e.matchStart<0||e.matchEnd<0||e.queryNormalized.length<12||e.label==="start_anchor"&&e.matchStart!==0||e.label==="end_anchor"&&e.matchEnd!==e.candidateNormalized.length)return 0;let t=e.queryNormalized.length/Math.max(1,e.candidateNormalized.length);return .08*(.5+.5*Math.min(1,t))}var jl=i(()=>{"use strict";xr();bo();So()});function Gl(e){if(e==null)return[void 0,"anchor is required"];if(typeof e=="string"){let o=e.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(c=>c.trim()).filter(c=>c!=="");if(s.length>=2){let c=s[0],d=s[s.length-1];return c===void 0||d===void 0?[void 0,"anchor string is empty"]:[{head:c,mode:"head_tail",tail:d},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof e!="object")return[void 0,`expected string or object, got ${typeof e}`];let t=e;if((t.mode==="head_tail"||t.head!==void 0?"head_tail":"full")==="full"){let o=typeof t.text=="string"?t.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let n=typeof t.head=="string"?t.head.trim():"",a=typeof t.tail=="string"?t.tail.trim():"";return n!==""&&a===""?[{mode:"full",text:n},void 0]:n===""&&a!==""?[{mode:"full",text:a},void 0]:n===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:n,mode:"head_tail",tail:a},void 0]}function Bl(e,t){if(e===void 0)return;if(e.mode==="head_tail"){let n=t==="end_anchor"?Eo(e.tail??"","end_anchor"):Eo(e.head??"","start_anchor");return n===""?void 0:{mode:"full",text:n}}return{mode:"full",text:Eo(e.text??"",t)}}function ko(e){return e.mode==="head_tail"?Y(e.head??"").length+Y(e.tail??"").length:Y(e.text??"").length}function Eo(e,t){let r=Mn(e);return r.length<=1?e.trim():t==="end_anchor"?r[r.length-1]??e.trim():r[0]??e.trim()}var Ul=i(()=>{"use strict";xr()});var et,Kl=i(()=>{"use strict";jl();Ul();bo();So();et=class{resolve(t,r,n){let a=t.start_anchor??t.start,o=t.end_anchor??t.end,[s,c]=this.parseAnchor(a,"start_anchor");if(c!==void 0)return[void 0,c];let d;if(o!==void 0){let[O,Re]=this.parseAnchor(o,"end_anchor");if(Re!==void 0)return[void 0,Re];d=O}let[m,p,S]=this.resolveAnchor({anchor:s,candidateSentenceIds:r,candidateTexts:n,label:"start_anchor"});if(S!==void 0)return[void 0,S];if(m===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(d===void 0)return[{confidence:m.score,sentenceIds:[m.sentenceId],strategy:p},void 0];let[C,E,T]=this.resolveAnchor({anchor:d,candidateSentenceIds:r,candidateTexts:n,label:"end_anchor",minIndex:m.index});return T!==void 0?[void 0,T]:C===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:C.index<m.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${m.occurrenceId} -> ${C.occurrenceId}).`}]:[{confidence:Math.min(m.score,C.score),sentenceIds:r.slice(m.index,C.index+1),strategy:`${p}+${E}`},void 0]}resolveWithOverrides(t){let r=t.evidence.start_anchor??t.evidence.start,n=t.evidence.end_anchor??t.evidence.end,[a,o]=this.parseAnchor(r,"start_anchor");if(o!==void 0)return[void 0,o];let s=t.overrides.start_anchor,[c,d,m]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:t.candidateSentenceIds,candidateTexts:t.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(m!==void 0)return[void 0,m];if(c===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(n===void 0)return[{confidence:c.score,sentenceIds:[c.sentenceId],strategy:d},void 0];let[p,S]=this.parseAnchor(n,"end_anchor");if(S!==void 0)return[void 0,S];let C=t.overrides.end_anchor,[E,T,O]=C===void 0?this.resolveAnchor({anchor:p,candidateSentenceIds:t.candidateSentenceIds,candidateTexts:t.candidateTexts,label:"end_anchor",minIndex:c.index}):[C,"choice_final",void 0];return O!==void 0?[void 0,O]:E===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:E.index<c.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${c.occurrenceId} -> ${E.occurrenceId}).`}]:[{confidence:Math.min(c.score,E.score),sentenceIds:t.candidateSentenceIds.slice(c.index,E.index+1),strategy:`${d}+${T}`},void 0]}parseAnchor(t,r){let[n,a]=Gl(t);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:r,message:`Invalid evidence.${r}: ${a}`}]:[Bl(n,r),void 0]}resolveAnchor(t){if(t.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:t.label,message:`${t.label} is missing`}];let r=this.rankAnchor(t.anchor,t.candidateSentenceIds,t.candidateTexts,t.label),n=t.minIndex;if(n!==void 0&&(r=r.filter(p=>p.index>=n)),r.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:t.label,message:`${t.label} could not be matched: no candidates available`}];let a=r.filter(p=>p.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(t.label,"ambiguous_exact_raw",a)];let o=r.filter(p=>p.exactSubstring);if(o.length===1&&ko(t.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&ko(t.anchor)>=8){let p=this.#e(o);return p!==void 0?[p,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(t.label,"ambiguous_exact_substring",o)]}let s=r.filter(p=>p.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let p=this.#e(s);return p!==void 0?[p,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(t.label,"ambiguous_exact_normalized",s)]}let c=r[0];if(c===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:t.label,message:`${t.label} could not be matched: no candidates available`}];let d=r[1]?.score??0,m=c.score-d;return c.score<.55?[void 0,"low_confidence",{candidates:r.slice(0,3),code:"low_confidence",fieldName:t.label,message:`${t.label} could not be matched confidently. Best candidate score=${c.score.toFixed(3)}.`}]:r.length===1?[c,"auto_top1_single_candidate",void 0]:c.score>=.97?[c,"auto_top1_very_high",void 0]:c.score>=.9&&m>=.07?[c,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(t.label,"ambiguous_ranked",r)]}rankAnchor(t,r,n,a){let o=[];for(let[s,c]of r.entries()){let d=n[s]??"",m=s>0?n[s-1]??"":"",p=s<n.length-1?n[s+1]??"":"",S=Fl(t,d,a);o.push({exactNormalized:S.exactNormalized,exactRaw:S.exactRaw,exactSubstring:S.exactSubstring,index:s,nextText:p,occurrenceId:`S${s+1}`,prevText:m,score:S.score,sentenceId:c,text:d})}return o.sort((s,c)=>s.score!==c.score?c.score-s.score:s.exactRaw!==c.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==c.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==c.exactNormalized?s.exactNormalized?-1:1:s.index-c.index),o}#e(t){if(t.length===0)return;if(t.length===1)return t[0];let r=t[0];if(r===void 0)return;let n=t[1]?.score??0;if(r.score>=.9&&r.score-n>=.07)return r}#t(t,r,n){let a=n.slice(0,3),o=a.map(s=>Ml(s)).join(`
298
+ `);return{candidates:a,code:r,fieldName:t,message:`${t} is ambiguous. Top candidates:
299
+ ${o}
300
+ Please provide a more specific anchor or surrounding context.`}}}});var Jl=i(()=>{"use strict"});var zl=i(()=>{"use strict";Kl();Jl()});var Fn,Ql=i(()=>{"use strict";Fn=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
301
+ `)});var Io=i(()=>{"use strict"});var Xl=i(()=>{"use strict";Io();xr()});var gt=i(()=>{"use strict";zl();Ql();Io();Xl();xr()});var Rr=i(()=>{"use strict";G()});var Yl=i(()=>{"use strict";I();Rr()});var Zl=i(()=>{"use strict";Rr()});var em=i(()=>{"use strict"});import{z as y}from"zod";var tm,GS,rm,BS,US,HS,qS,$S,KS,Gn=i(()=>{"use strict";I();tm=y.object({from:y.union([y.number().int(),y.string()]),strength:y.string().optional(),to:y.union([y.number().int(),y.string()])}),GS=y.object({quote:y.string().optional(),sentence_id:y.string().optional()}).passthrough(),rm=y.union([y.record(y.string(),y.unknown()),y.array(GS)]),BS=y.object({content:y.string(),evidence:rm.nullish(),label:y.string(),retention:y.enum(["verbatim","detailed","focused","relevant"]),temp_id:y.string()}).passthrough(),US=y.object({chunks:y.array(BS),fragment_summary:y.string(),links:y.array(tm)}),HS=y.object({content:y.string(),evidence:rm.nullish(),importance:y.enum(["critical","important","helpful"]),label:y.string(),temp_id:y.string()}).passthrough(),qS=y.object({chunk_id:y.number().int(),importance:y.enum(["critical","important","helpful"])}),$S=y.object({chunks:y.array(HS),importance_annotations:y.array(qS),links:y.array(tm)}),KS=y.object({choice:y.string()})});var nm=i(()=>{"use strict";G();gt();em();Rr();Gn()});var im=i(()=>{"use strict";G();I();Yl();Rr();Zl();nm();Gn()});var am=i(()=>{"use strict";im();Gn()});var Bn=i(()=>{"use strict"});var Se=i(()=>{"use strict"});import{detect as AH,validateISO2 as LH}from"tinyld";var Ro=i(()=>{"use strict";Se()});var om=i(()=>{"use strict";Ro();Se()});var sm=i(()=>{"use strict"});import{z as vr}from"zod";var VS,eq,dm=i(()=>{"use strict";G();gt();am();Bn();Bn();om();sm();VS=vr.object({content:vr.string(),id:vr.number(),label:vr.string()}),eq=vr.array(VS)});var vo=i(()=>{"use strict";dm()});var um=i(()=>{"use strict"});var To=i(()=>{"use strict";um()});var lm=i(()=>{"use strict";Pl();vo();To()});var Un=i(()=>{"use strict";lm();To()});var Hn=i(()=>{"use strict"});var qn=i(()=>{"use strict";Un();Hn()});var mm=i(()=>{"use strict";qn()});var nw,Co,pm,Tr=i(()=>{"use strict";nw=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Co=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),pm=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var hm=i(()=>{"use strict"});var $n=i(()=>{"use strict"});var fm=i(()=>{"use strict";$n()});var bt,Pq,iw,Kn=i(()=>{"use strict";Li();bt=(n=>(n.Critical="critical",n.Major="major",n.Minor="minor",n))(bt||{}),Pq=dt(bt),iw=jt(bt,"review severity")});var Dq,Po=i(()=>{"use strict";$n();Kn();Dq=Object.freeze({critical:9,major:3,minor:1})});var ym=i(()=>{"use strict";Ro();Se();Kn()});import{appendFile as Hq,writeFile as qq}from"fs/promises";var gm=i(()=>{"use strict";V();Po()});var Ao=i(()=>{"use strict";I()});var bm=i(()=>{"use strict"});import{z as St}from"zod";var aw,ow,o$,Sm=i(()=>{"use strict";V();G();$n();Ao();Kn();aw=["critical","major","minor"],ow=St.object({problem:St.string(),severity:St.enum(aw),suggestion:St.string().default("")}),o$=St.object({issues:St.array(ow)})});var wm=i(()=>{"use strict";hm();fm();Po();ym();gm();Ao();bm();Sm()});var Lo=i(()=>{"use strict";wm()});var km=i(()=>{"use strict"});var Im=i(()=>{"use strict"});var xm=i(()=>{"use strict";km();Im()});var _r=i(()=>{"use strict"});var G$,B$,wt=i(()=>{"use strict";I();G$={critical:9,helpful:1,important:3},B$={detailed:9,focused:3,relevant:1,verbatim:27}});var Et=i(()=>{"use strict"});var Cr=i(()=>{"use strict"});var Oo=i(()=>{"use strict";Et()});var No=i(()=>{"use strict";wt();Et();_r();Cr();Oo()});var Do=i(()=>{"use strict";_r();No();Cr()});var vm=i(()=>{"use strict";wt();Et();Cr()});var Tm=i(()=>{"use strict";wt();Et();_r();Cr();Oo()});var _m=i(()=>{"use strict";Do();Et();_r();vm();No();Tm()});var Cm=i(()=>{"use strict";_m();Do()});var Pm=i(()=>{"use strict";wt()});var Am=i(()=>{"use strict";Cm();Pm()});var Lm=i(()=>{"use strict";xm();Am();wt()});var Om=i(()=>{"use strict";Lm()});var Mo=i(()=>{"use strict"});var Nm=i(()=>{"use strict"});var Wo=i(()=>{"use strict";qn()});var zn=i(()=>{"use strict"});var Dm=i(()=>{"use strict";kr();Tr();Lo();Un();Om();qn();Hn();Mo();Nm();Wo();zn()});var Mm=i(()=>{"use strict";Mo();zn()});var Wm=i(()=>{"use strict";mm();Dm();Hn();Mm();Wo();zn()});var kt=i(()=>{"use strict";Wm()});var Fm=i(()=>{"use strict";ye();kr();kt();Ke()});import{mkdir as QK,writeFile as XK}from"fs/promises";import{dirname as YK}from"path";var jm=i(()=>{"use strict"});var Qn=i(()=>{"use strict"});var Pr=i(()=>{"use strict";Nn();Dn()});import{createWriteStream as oJ}from"fs";import{dirname as cJ,extname as dJ}from"path";import{finished as lJ}from"stream/promises";import{mkdir as pJ}from"fs/promises";import{ZipFile as fJ}from"yazl";var Go=i(()=>{"use strict";Qn();Pr()});var Gm=i(()=>{"use strict";Pr()});var Bm=i(()=>{"use strict";Qn();Pr()});var Bo=i(()=>{"use strict";Pr()});var Um=i(()=>{"use strict";Go();Gm();Bm();Bo();Qn()});var Hm=i(()=>{"use strict";Go();Um();Bo()});var qm=i(()=>{"use strict";jm();Hm()});var Ne=i(()=>{"use strict"});import{posix as ez,resolve as tz,sep as rz}from"path";var tt=i(()=>{"use strict";Ne()});import{randomBytes as oz}from"crypto";import{z as Uo}from"zod";var Yn,Ho,Ew,dz,It=i(()=>{"use strict";Ne();Yn=1,Ho=2,Ew=`${JSON.stringify({formatVersion:Yn,schemaVersion:Ho})}
302
+ `,dz=Uo.object({formatVersion:Uo.literal(Yn),schemaVersion:Uo.number().int().positive().optional()})});import{open as mz}from"fs/promises";import{inflateRaw as hz}from"zlib";import{open as yz}from"yauzl";var Ar=i(()=>{"use strict";Ne();It();tt()});import{mkdir as Iz,open as xz,writeFile as Rz}from"fs/promises";import{dirname as Tz,resolve as _z}from"path";var Jm=i(()=>{"use strict";tt();Ar()});import{readdir as Oz}from"fs/promises";import{join as Dz,posix as Mz,relative as Wz,sep as Fz}from"path";var zm=i(()=>{"use strict";f();Ne();tt()});import{createWriteStream as Xz}from"fs";import{mkdir as Yz,open as Zz}from"fs/promises";import{dirname as tQ}from"path";import{finished as nQ}from"stream/promises";import{ZipFile as aQ}from"yazl";var Ko=i(()=>{"use strict";Ne();zm();It();tt();Ar()});import{createHash as pQ,randomUUID as xw}from"crypto";import{stat as Qm}from"fs/promises";import{resolve as yQ}from"path";async function ei(e){let t=await Qm(e);return`${t.size}:${t.mtimeMs}`}function ti(){return`${process.pid}-${xw()}`}async function Xm(e){await new Promise(t=>{setTimeout(t,e)})}async function xt(e){try{return await Qm(e),!0}catch(t){if(h(t)&&t.code==="ENOENT")return!1;throw t}}var we=i(()=>{"use strict";b()});import{randomUUID as EQ}from"crypto";import{mkdtemp as IQ,rename as xQ,rm as RQ,stat as vQ,writeFile as TQ}from"fs/promises";import{tmpdir as CQ}from"os";import{dirname as AQ,join as LQ,resolve as OQ}from"path";var $Q,ri=i(()=>{"use strict";f();Qt();He();N();Ne();It();tt();Ar();Ko();we();en();He();$Q=300*1e3});import{open as QQ,readFile as XQ}from"fs/promises";import{join as YQ}from"path";var Vm=i(()=>{"use strict";Ne();It();tt();Ar();ri()});var De=i(()=>{"use strict";Jm();Vm();It();Ko()});var mp=i(()=>{"use strict";Pe()});var ai,Me,ce=i(()=>{"use strict";ai="database.db",Me="fts.db"});import{join as Cw}from"path";async function de(e){let t=Date.now(),r=new Set;for(let n of["archive_owners","entry_locks","entry_sqlite_leases","archive_commit_locks"]){let a=await e.queryAll(`
303
+ SELECT DISTINCT owner_pid
304
+ FROM ${n}
305
+ WHERE owner_pid IS NOT NULL
306
+ AND heartbeat_at <= ?
307
+ `,[t-6e4],o=>Ee(o,"owner_pid"));for(let o of a)Lw(o)||r.add(o)}r.size!==0&&(await e.run(`
308
+ DELETE FROM archive_owners
309
+ WHERE owner_pid IN (${Lr(r.size)})
310
+ `,[...r]),await e.run(`
311
+ DELETE FROM entry_locks
312
+ WHERE owner_pid IN (${Lr(r.size)})
313
+ `,[...r]),await e.run(`
314
+ DELETE FROM entry_sqlite_leases
315
+ WHERE owner_pid IN (${Lr(r.size)})
316
+ `,[...r]),await e.run(`
317
+ DELETE FROM archive_commit_locks
318
+ WHERE owner_pid IN (${Lr(r.size)})
319
+ `,[...r]))}function Lr(e){return Array.from({length:e},()=>"?").join(", ")}function Lw(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&"code"in t&&t.code==="ESRCH")}}async function M(e){return await Aw.use(async()=>{let t=await Ow();try{return await e(t)}finally{await t.close()}})}async function Ow(){let e=await v(Cw(ts(),"staging.sqlite"),Pw);return await Nw(e),e}async function Nw(e){let t=await e.queryAll("PRAGMA table_info(entry_overlays)",void 0,n=>U(n,"name"));t.includes("archive_signature")||await e.run(`
320
+ ALTER TABLE entry_overlays
321
+ ADD COLUMN archive_signature TEXT
322
+ `),t.includes("mutation_token")||await e.run(`
323
+ ALTER TABLE entry_overlays
324
+ ADD COLUMN mutation_token TEXT
325
+ `),(await e.queryAll("PRAGMA table_info(entry_sqlite_leases)",void 0,n=>U(n,"name"))).includes("mode")||await e.run(`
326
+ ALTER TABLE entry_sqlite_leases
327
+ ADD COLUMN mode TEXT NOT NULL DEFAULT 'read'
328
+ `)}function ts(){return q()}function Rt(e){let t=Zo(e,"workspace_path"),r=Zo(e,"archive_signature"),n=Zo(e,"mutation_token");return{archiveKey:U(e,"archive_key"),archivePath:U(e,"archive_path"),...r===void 0?{}:{archiveSignature:r},entryPath:U(e,"entry_path"),kind:Mw(e),...n===void 0?{}:{mutationToken:n},updatedAt:Ee(e,"updated_at"),...t===void 0?{}:{workspacePath:t}}}function pp(e){return{entryPath:U(e,"entry_path"),mode:Dw(e),ownerId:U(e,"owner_id")}}function Dw(e){let t=U(e,"mode");if(t==="read"||t==="state"||t==="write")return t;throw new Error(`Unsupported entry lock mode: ${t}.`)}function Mw(e){let t=U(e,"kind");if(t==="deleted"||t==="file")return t;throw new Error(`Unsupported entry overlay kind: ${t}.`)}function U(e,t){let r=e[t];if(typeof r!="string")throw new TypeError(`Expected ${t} to be a string`);return r}function Ee(e,t){let r=e[t];if(typeof r!="number")throw new TypeError(`Expected ${t} to be a number`);return r}function Zo(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new TypeError(`Expected ${t} to be a string`);return r}}var Pw,Aw,ke=i(()=>{"use strict";N();I();kr();ce();Pw=`
329
+ CREATE TABLE IF NOT EXISTS entry_overlays (
330
+ archive_key TEXT NOT NULL,
331
+ archive_path TEXT NOT NULL,
332
+ entry_path TEXT NOT NULL,
333
+ kind TEXT NOT NULL,
334
+ workspace_path TEXT,
335
+ archive_signature TEXT,
336
+ mutation_token TEXT,
337
+ updated_at INTEGER NOT NULL,
338
+ PRIMARY KEY (archive_key, entry_path)
339
+ );
340
+
341
+ CREATE TABLE IF NOT EXISTS entry_locks (
342
+ archive_key TEXT NOT NULL,
343
+ entry_path TEXT NOT NULL,
344
+ mode TEXT NOT NULL,
345
+ owner_id TEXT NOT NULL,
346
+ owner_pid INTEGER NOT NULL,
347
+ heartbeat_at INTEGER NOT NULL,
348
+ created_at INTEGER NOT NULL,
349
+ PRIMARY KEY (archive_key, entry_path, owner_id)
350
+ );
351
+
352
+ CREATE TABLE IF NOT EXISTS archive_owners (
353
+ archive_key TEXT NOT NULL,
354
+ owner_id TEXT NOT NULL,
355
+ owner_pid INTEGER NOT NULL,
356
+ heartbeat_at INTEGER NOT NULL,
357
+ created_at INTEGER NOT NULL,
358
+ PRIMARY KEY (archive_key, owner_id)
359
+ );
360
+
361
+ CREATE TABLE IF NOT EXISTS entry_sqlite_leases (
362
+ archive_key TEXT NOT NULL,
363
+ entry_path TEXT NOT NULL,
364
+ mode TEXT NOT NULL DEFAULT 'read',
365
+ owner_id TEXT NOT NULL,
366
+ owner_pid INTEGER NOT NULL,
367
+ heartbeat_at INTEGER NOT NULL,
368
+ created_at INTEGER NOT NULL,
369
+ PRIMARY KEY (archive_key, entry_path, owner_id)
370
+ );
371
+
372
+ CREATE TABLE IF NOT EXISTS archive_commit_locks (
373
+ archive_key TEXT PRIMARY KEY,
374
+ owner_id TEXT NOT NULL,
375
+ owner_pid INTEGER NOT NULL,
376
+ heartbeat_at INTEGER NOT NULL,
377
+ created_at INTEGER NOT NULL
378
+ );
379
+ `,Aw=new Ze(1)});async function Or(e,t,r){let n=ti();for(;;){if(await M(async o=>(await de(o),await o.transaction(async()=>(await o.queryAll(`
380
+ SELECT *
381
+ FROM entry_locks
382
+ WHERE archive_key = ?
383
+ `,[e],pp)).some(c=>c.ownerId!==n&&jw(t,c.entryPath)&&Fw(r,c.mode))?!1:(await o.run(`
384
+ INSERT INTO entry_locks (
385
+ archive_key, entry_path, mode, owner_id, owner_pid, heartbeat_at, created_at
386
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
387
+ `,[e,t,r,n,process.pid,Date.now(),Date.now()]),!0)))))return async()=>{await M(async o=>{await o.run(`
388
+ DELETE FROM entry_locks
389
+ WHERE archive_key = ? AND entry_path = ? AND owner_id = ?
390
+ `,[e,t,n])})};await Xm(100)}}function Fw(e,t){return e==="state"||t==="state"?e==="state"&&t==="state":!(e==="read"&&t==="read")}function jw(e,t){return e===t||hp(e,t)||hp(t,e)}function hp(e,t){return e.endsWith("/")&&t.startsWith(e)}var Nr=i(()=>{"use strict";we();ce();ke()});async function oi(e,t){return await M(async r=>await r.queryOne("SELECT * FROM entry_overlays WHERE archive_key = ? AND entry_path = ?",[e,t],Rt))}async function si(e){return await M(async t=>await t.queryAll(`
391
+ SELECT *
392
+ FROM entry_overlays
393
+ WHERE archive_key = ?
394
+ ORDER BY entry_path ASC
395
+ `,[e],Rt))}async function ci(e,t){await M(async r=>{await r.run("DELETE FROM entry_overlays WHERE archive_key = ? AND entry_path = ?",[e,t])})}var vt=i(()=>{"use strict";De();we();ce();ke()});var Tt=i(()=>{"use strict";Le()});async function rs(e,t){return await M(async r=>{await de(r);let n=await r.queryOne("SELECT COUNT(*) AS count FROM archive_owners WHERE archive_key = ?",[e],o=>Ee(o,"count")),a=await r.queryOne(`
396
+ SELECT COUNT(*) AS count
397
+ FROM entry_sqlite_leases
398
+ WHERE archive_key = ?
399
+ AND entry_path = ?
400
+ `,[e,t],o=>Ee(o,"count"));return(n??0)>0||(a??0)>0})}async function ns(e){return await M(async t=>{await de(t);let r=await t.queryOne("SELECT COUNT(*) AS count FROM archive_owners WHERE archive_key = ?",[e],o=>Ee(o,"count")),n=await t.queryOne("SELECT COUNT(*) AS count FROM entry_sqlite_leases WHERE archive_key = ?",[e],o=>Ee(o,"count")),a=await t.queryOne("SELECT COUNT(*) AS count FROM entry_locks WHERE archive_key = ?",[e],o=>Ee(o,"count"));return(r??0)>0||(n??0)>0||(a??0)>0})}var is=i(()=>{"use strict";ke()});import{mkdir as WX,readdir as Kw}from"fs/promises";import{basename as jX,dirname as GX,join as fp}from"path";function as(){return fp(ts(),"work")}async function os(e){let t;try{t=await Kw(e,{withFileTypes:!0})}catch(n){if(h(n)&&n.code==="ENOENT")return[];throw n}let r=[];for(let n of t){let a=fp(e,n.name);n.isDirectory()?r.push(...await os(a)):n.isFile()&&r.push(a)}return r}var Dr=i(()=>{"use strict";b();ke()});import{mkdir as $X,rename as KX,rm as JX}from"fs/promises";import{dirname as QX}from"path";async function yp(e){if(e.workspacePath===void 0||!await xt(e.workspacePath))return"missing";if(!await xt(e.archivePath))return"dirty";try{let t=await zw(e.workspacePath),r=await ei(e.archivePath);return t===void 0?"dirty":e.archiveSignature===r?"current":"dirty"}catch{return"dirty"}}async function zw(e){await $();let t=await k.open(e,"",{readonly:!0});try{return await mt(t)}finally{await t.close()}}var ss=i(()=>{"use strict";I();He();Tt();De();we();is();ce();Nr();vt();ke();Dr()});import{mkdir as gV,readFile as bV,rename as SV,rm as wV,writeFile as EV}from"fs/promises";import{dirname as IV,posix as xV,resolve as RV}from"path";var cs=i(()=>{"use strict";He();De();we();ce();Nr();vt();ss();Dr()});import{mkdir as GV,mkdtemp as BV,rename as UV,rm as HV}from"fs/promises";import{tmpdir as $V}from"os";import{basename as JV,dirname as zV,join as QV,resolve as XV}from"path";var di=i(()=>{"use strict";De();we();ce();Nr();vt();ke()});var gp=i(()=>{"use strict";ce();di();ke()});import{mkdir as yY,rm as gY,writeFile as bY}from"fs/promises";import{dirname as wY,isAbsolute as EY,relative as kY,resolve as IY}from"path";var ds=i(()=>{"use strict";pe();De();we();ce();cs();di();gp();vt();Dr()});import{rm as DY}from"fs/promises";import{resolve as WY}from"path";var bp=i(()=>{"use strict";pe();De();cs();ds()});import{readdir as ui,rm as Zw,rmdir as eE,stat as us}from"fs/promises";import{join as li}from"path";function ls(e){return tE.has(e)}async function mi(e){let t=await ui(e).catch(n=>{if(!(h(n)&&n.code==="ENOENT"))throw n});if(t===void 0||t.some(n=>!ls(n)))return 0;let r=0;for(let n of t){let a=li(e,n);r+=await F(a),await Zw(a,{force:!0,recursive:!0})}return await eE(e).catch(n=>{if(!(h(n)&&n.code==="ENOENT"))throw n}),r}async function pi(e){let t=await ui(e,{withFileTypes:!0}).catch(o=>{if(h(o)&&o.code==="ENOENT")return[];throw o}),r=0,n=0,a=0;for(let o of t){if(!o.isDirectory())continue;a+=1;let s=li(e,o.name),c=await us(s).catch(m=>{if(!(h(m)&&m.code==="ENOENT"))throw m});if(c===void 0||Date.now()-c.mtimeMs<rE)continue;let d=await mi(s);if(await Sp(s)){r+=d;continue}r+=d,n+=1}return{freedBytes:r,removed:n,scanned:a}}async function ms(e){let t=await ui(e,{withFileTypes:!0}).catch(o=>{if(h(o)&&o.code==="ENOENT")return[];throw o}),r=0,n=0,a=0;for(let o of t){if(!o.isDirectory())continue;let s=li(e,o.name),c=await ms(s);r+=c.freedBytes,n+=c.removed,a+=c.scanned+1;let d=await mi(s);if(await Sp(s)){r+=d;continue}r+=d,n+=1}return{freedBytes:r,removed:n,scanned:a}}async function F(e){try{let t=await us(e);if(t.isDirectory()){let r=await ui(e),n=0;for(let a of r)n+=await F(li(e,a));return n}return t.size}catch(t){if(h(t)&&t.code==="ENOENT")return 0;throw t}}async function Sp(e){try{return await us(e),!0}catch(t){if(h(t)&&t.code==="ENOENT")return!1;throw t}}var tE,rE,Wr=i(()=>{"use strict";b();tE=new Set([".DS_Store"]),rE=6e4});import{readdir as iE,rm as Ep}from"fs/promises";import{basename as aE,dirname as oE,join as wp}from"path";async function hi(e){let t=await sE(),r=0,n=0;for(let s of t){let c=await cE(s,e);c.removed&&(r+=1,n+=c.freedBytes)}let a=await lE(e),o=e.dryRun?{freedBytes:0,removed:0,scanned:0}:await pi(as());return{freedBytes:n+a.freedBytes+o.freedBytes,removed:r+a.removed+o.removed,scanned:t.length+a.scanned+o.scanned}}async function sE(){return await M(async e=>(await de(e),await e.queryAll(`
401
+ SELECT overlay.*
402
+ FROM entry_overlays AS overlay
403
+ WHERE overlay.entry_path IN (?, ?)
404
+ AND overlay.kind = 'file'
405
+ AND overlay.workspace_path IS NOT NULL
406
+ ORDER BY overlay.updated_at ASC
407
+ `,[ai,Me],Rt)))}async function cE(e,t){let r=await Or(e.archiveKey,e.entryPath,"write");try{let n=await Or(e.archiveKey,e.entryPath,"state");try{let a=await oi(e.archiveKey,e.entryPath);if(a?.workspacePath===void 0||a.workspacePath!==e.workspacePath||!await dE(a,t))return{freedBytes:0,removed:!1};let o=await F(a.workspacePath);return t.dryRun||(await ci(a.archiveKey,a.entryPath),await Ep(a.workspacePath,{force:!0}),o+=await mi(oE(a.workspacePath))),{freedBytes:o,removed:!0}}finally{await n()}}finally{await r()}}async function dE(e,t){return await rs(e.archiveKey,e.entryPath)||e.workspacePath===void 0?!1:await uE(e)?!0:!(!t.force&&t.now-e.updatedAt<36e5||e.entryPath===Me&&!t.force)}async function uE(e){return e.workspacePath===void 0||!await xt(e.workspacePath)||!await xt(e.archivePath)?!0:e.entryPath!==Me?!1:await yp(e)!=="current"}async function lE(e){let t=as(),r;try{r=await iE(t,{withFileTypes:!0})}catch(s){if(h(s)&&s.code==="ENOENT")return{freedBytes:0,removed:0,scanned:0};throw s}let n=0,a=0,o=0;for(let s of r){if(!s.isDirectory())continue;let c=s.name;if(await ns(c))continue;let d=new Set((await si(c)).map(m=>m.workspacePath).filter(m=>m!==void 0));for(let m of await os(wp(t,c))){if(o+=1,ls(aE(m))||d.has(m))continue;let p=await F(m);e.dryRun||await Ep(m,{force:!0}),n+=p,a+=1}if(!e.dryRun){let m=await ms(wp(t,c));n+=m.freedBytes,a+=m.removed,o+=m.scanned}}return{freedBytes:n,removed:a,scanned:o}}var kp=i(()=>{"use strict";Wr();b();is();we();ce();Nr();vt();ss();ke();Dr()});var xp=i(()=>{"use strict";bp();ds();di();kp()});var ps=i(()=>{"use strict";xp()});import{resolve as f2}from"path";var Rp=i(()=>{"use strict";I();ps();yt();fi()});var ue=i(()=>{"use strict";De();mp();Rp();ps()});var fi=i(()=>{"use strict";qm();ue()});import{rm as A2}from"fs/promises";import{resolve as O2}from"path";var vp=i(()=>{"use strict";pe();Ke();Ke();I();ye();Tl();kt();Fm();fi()});var $2,fs=i(()=>{"use strict";Tr();$2=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Tp,We=i(()=>{"use strict";Tp=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var ys=i(()=>{"use strict";We()});var s8,_p=i(()=>{"use strict";Nn();V();ho();vp();fs();ue();ys();s8=On()});var gs,bs=i(()=>{"use strict";gs=["queued","running","canceling","paused","succeeded","failed","canceled"]});import{mkdir as l8}from"fs/promises";import{join as Cp}from"path";function Pp(){return Cp(Lp(),"job.sqlite")}function Ap(){return Cp(Lp(),"work")}function Lp(){return ot()}var yi=i(()=>{"use strict";N()});import{createHash as y8}from"crypto";import{resolve as b8}from"path";var Ct=i(()=>{"use strict"});var Ss=i(()=>{"use strict"});import{appendFile as k8,readFile as I8}from"fs/promises";var jr=i(()=>{"use strict"});var Op,Np=i(()=>{"use strict";Op=`
408
+ CREATE TABLE IF NOT EXISTS build_jobs (
409
+ job_id TEXT PRIMARY KEY,
410
+ archive_key TEXT NOT NULL,
411
+ archive_path TEXT NOT NULL,
412
+ chapter_id INTEGER NOT NULL,
413
+ target TEXT NOT NULL,
414
+ current_step TEXT,
415
+ state TEXT NOT NULL,
416
+ queue_rank INTEGER NOT NULL,
417
+ workspace_path TEXT NOT NULL,
418
+ cache_path TEXT NOT NULL,
419
+ log_path TEXT NOT NULL,
420
+ events_path TEXT NOT NULL,
421
+ input_revision INTEGER,
422
+ llm_json TEXT,
423
+ prompt TEXT,
424
+ owner_id TEXT,
425
+ owner_pid INTEGER,
426
+ reading_summary_started_at INTEGER,
427
+ created_at INTEGER NOT NULL,
428
+ updated_at INTEGER NOT NULL,
429
+ finished_at INTEGER,
430
+ error_json TEXT
431
+ );
432
+
433
+ DROP INDEX IF EXISTS idx_build_jobs_active_chapter;
434
+
435
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_build_jobs_active_knowledge_chapter
436
+ ON build_jobs(archive_key, chapter_id)
437
+ WHERE target = 'knowledge-graph'
438
+ AND state IN ('queued', 'running', 'canceling', 'paused');
439
+
440
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_build_jobs_active_reading_chapter
441
+ ON build_jobs(archive_key, chapter_id)
442
+ WHERE target IN ('reading-graph', 'reading-summary')
443
+ AND state IN ('queued', 'running', 'canceling', 'paused');
444
+
445
+ CREATE INDEX IF NOT EXISTS idx_build_jobs_queue
446
+ ON build_jobs(state, queue_rank, updated_at);
447
+
448
+ CREATE TABLE IF NOT EXISTS build_worker_lease (
449
+ id INTEGER PRIMARY KEY CHECK (id = 1),
450
+ owner_id TEXT,
451
+ owner_pid INTEGER,
452
+ heartbeat_at INTEGER
453
+ );
454
+
455
+ INSERT OR IGNORE INTO build_worker_lease (id)
456
+ VALUES (1);
457
+ `});function rt(e){let t=yE(Pt(e,"current_step"),"current_step"),r=Pt(e,"owner_id"),n=e.owner_pid===null?void 0:H(e,"owner_pid"),a=e.reading_summary_started_at===null?void 0:H(e,"reading_summary_started_at"),o=e.finished_at===null?void 0:H(e,"finished_at"),s=Pt(e,"error_json"),c=e.input_revision===null?void 0:H(e,"input_revision"),d=Pt(e,"llm_json"),m=Pt(e,"prompt");return{archiveKey:le(e,"archive_key"),archivePath:le(e,"archive_path"),cachePath:le(e,"cache_path"),chapterId:H(e,"chapter_id"),createdAt:H(e,"created_at"),...t===void 0?{}:{currentStep:t},...s===void 0?{}:{errorJSON:s},eventsPath:le(e,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:le(e,"job_id"),...c===void 0?{}:{inputRevision:c},logPath:le(e,"log_path"),...d===void 0?{}:{llmJSON:d},...r===void 0?{}:{ownerId:r},...n===void 0?{}:{ownerPid:n},...m===void 0?{}:{prompt:m},queueRank:H(e,"queue_rank"),state:fE(le(e,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:Dp(le(e,"target"),"target"),updatedAt:H(e,"updated_at"),workspacePath:le(e,"workspace_path")}}function fE(e){if(gs.includes(e))return e;throw new Error(`Invalid build job state: ${e}`)}function Dp(e,t){if(e==="reading-graph"||e==="knowledge-graph"||e==="reading-summary")return e;throw new Error(`Invalid ${t}: ${e}`)}function yE(e,t){return e===void 0?void 0:Dp(e,t)}function le(e,t){let r=e[t];if(typeof r!="string")throw new TypeError(`Expected ${t} to be a string`);return r}function H(e,t){let r=e[t];if(typeof r!="number")throw new TypeError(`Expected ${t} to be a number`);return r}function Pt(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new TypeError(`Expected ${t} to be a string`);return r}}var nt=i(()=>{"use strict";bs()});async function At(){return await v(Pp(),Op)}var Lt=i(()=>{"use strict";I();Np();yi();nt()});import{rm as D8}from"fs/promises";var gi=i(()=>{"use strict";Ct();jr();Lt()});import{rm as U8}from"fs/promises";var bi=i(()=>{"use strict";Ct();nt();gi()});import{randomUUID as i3}from"crypto";import{resolve as o3}from"path";var ws=i(()=>{"use strict";yi();Ct();Ss();jr();Lt();bi();gi();nt()});import{resolve as g3}from"path";var jp=i(()=>{"use strict";Ct();Lt();bi();nt()});import{randomUUID as A3}from"crypto";var Gp=i(()=>{"use strict";Ct();Ss();jr();Lt();bi();gi();ws();nt()});import{rm as Si}from"fs/promises";async function wi(e){let t=await At(),r=e.force?e.now:e.now-10080*60*1e3;try{let n=await t.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>H(c,"count")),a=await t.queryAll(`
458
+ SELECT *
459
+ FROM build_jobs
460
+ WHERE state IN ('succeeded', 'failed', 'canceled')
461
+ AND updated_at <= ?
462
+ `,[r],rt),o=e.dryRun?{freedBytes:0,removed:0,scanned:0}:await pi(Ap()),s=0;for(let c of a)s+=await F(c.workspacePath),s+=await F(c.cachePath),s+=await F(c.logPath),s+=await F(c.eventsPath),e.dryRun||(await Si(c.workspacePath,{force:!0,recursive:!0}),await Si(c.cachePath,{force:!0,recursive:!0}),await Si(c.logPath,{force:!0,recursive:!0}),await Si(c.eventsPath,{force:!0}),await t.run("DELETE FROM build_jobs WHERE job_id = ?",[c.jobId]));return{freedBytes:s+o.freedBytes,removed:a.length+o.removed,scanned:(n??0)+o.scanned}}finally{await t.close()}}var Bp=i(()=>{"use strict";Wr();yi();Lt();nt()});var ih=i(()=>{"use strict";bs();ws();jp();Gp();jr();Bp()});var Ei=i(()=>{"use strict"});import{createReadStream as r5,createWriteStream as n5}from"fs";import{createInterface as a5}from"readline";import{z as u}from"zod";var ah,P,kE,IE,oh,xE,RE,vE,TE,_E,CE,PE,AE,LE,OE,NE,DE,ME,WE,d5,Ot=i(()=>{"use strict";fe();Ei();ah=1,P=u.number().int().nonnegative(),kE=u.literal(ah),IE=u.string().regex(/^Q[1-9][0-9]*$/u),oh=u.number().min(0).max(1).optional(),xE=u.object({text:u.string(),wordsCount:P}).strict(),RE=u.object({type:u.literal("meta"),schemaVersion:kE,chapterId:u.number().int(),stream:u.enum(["knowledge-graph","reading-graph","summary"])}).strict(),vE=u.object({type:u.literal("parameter"),scope:u.enum(["knowledge-graph","reading-graph","summary"]),language:u.string().optional(),prompt:u.string()}).strict(),TE=u.object({type:u.literal("source-fragment"),fragmentId:P,summary:u.string(),sentences:u.array(xE)}).strict(),_E=u.object({type:u.literal("reading-chunk"),id:u.string().min(1),generation:u.number().int(),sentenceIndex:P,label:u.string(),content:u.string(),sentenceIndexes:u.array(P).min(1),retention:u.enum(K).optional(),importance:u.enum(te).optional(),wordsCount:P,weight:u.number()}).strict(),CE=u.object({type:u.literal("reading-edge"),fromChunkId:u.string().min(1),toChunkId:u.string().min(1),strength:u.string().optional(),weight:u.number()}).strict(),PE=u.object({type:u.literal("fragment-group"),groupId:P,startSentenceIndex:P,endSentenceIndex:P}).strict(),AE=u.object({type:u.literal("snake"),id:u.string().min(1),groupId:P,localSnakeId:P,size:P,firstLabel:u.string(),lastLabel:u.string(),wordsCount:P,weight:u.number()}).strict(),LE=u.object({type:u.literal("snake-chunk"),snakeId:u.string().min(1),chunkId:u.string().min(1),position:P}).strict(),OE=u.object({type:u.literal("snake-edge"),fromSnakeId:u.string().min(1),toSnakeId:u.string().min(1),weight:u.number()}).strict(),NE=u.object({type:u.literal("summary"),text:u.string()}).strict(),DE=u.object({type:u.literal("mention"),id:u.string().min(1),fragmentId:P.optional(),sentenceIndex:P.optional(),rangeStart:P,rangeEnd:P,surface:u.string().min(1),qid:IE,confidence:oh,note:u.string().optional()}).strict(),ME=u.object({type:u.literal("mention-link"),id:u.string().min(1),sourceMentionId:u.string().min(1),targetMentionId:u.string().min(1),predicate:u.string().min(1),evidenceSentenceIndexes:u.array(P).min(1),confidence:oh,note:u.string().optional()}).strict(),WE=u.object({type:u.literal("end")}).strict(),d5=u.discriminatedUnion("type",[RE,vE,TE,_E,CE,PE,AE,LE,OE,NE,DE,ME,WE])});var sh=i(()=>{"use strict";Se();We()});var ch=i(()=>{"use strict";I();Un()});import{mkdir as E5,rm as k5}from"fs/promises";import{join as x5}from"path";var uh=i(()=>{"use strict";I();W();kt();Ot();sh();ch()});var ki=i(()=>{"use strict"});var lh=i(()=>{"use strict";ki()});var mh=i(()=>{"use strict"});var ph=i(()=>{"use strict";ki()});var hh=i(()=>{"use strict";ki()});var fh=i(()=>{"use strict";lh();mh();ph();hh()});import{z as l}from"zod";var yh,GE,BE,UE,HE,qE,$E,KE,JE,zE,QE,gh=i(()=>{"use strict";fe();yh=l.tuple([l.number(),l.number()]),GE=l.object({text:l.string(),wordsCount:l.number()}),BE=l.object({serialId:l.number(),fragmentId:l.number(),summary:l.string(),sentences:l.array(GE)}),UE=l.object({documentOrder:l.number().optional(),id:l.number(),knowledgeGraphReady:l.boolean(),knowledgeGraphParameterHash:l.string().optional(),revision:l.number().optional(),topologyParameterHash:l.string().optional(),topologyReady:l.boolean()}).transform(e=>({documentOrder:e.documentOrder??e.id,id:e.id,knowledgeGraphReady:e.knowledgeGraphReady,...e.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:e.knowledgeGraphParameterHash},revision:e.revision??0,topologyReady:e.topologyReady,...e.topologyParameterHash===void 0?{}:{topologyParameterHash:e.topologyParameterHash}})),HE=l.object({id:l.number(),generation:l.number(),sentenceId:yh,label:l.string(),content:l.string(),sentenceIds:l.array(yh),retention:l.enum(K).optional(),importance:l.enum(te).optional(),wordsCount:l.number(),weight:l.number()}),qE=l.object({fromId:l.number(),toId:l.number(),strength:l.string().optional(),weight:l.number()}),$E=l.object({id:l.number(),serialId:l.number(),groupId:l.number(),localSnakeId:l.number(),size:l.number(),firstLabel:l.string(),lastLabel:l.string(),wordsCount:l.number(),weight:l.number()}),KE=l.object({snakeId:l.number(),chunkId:l.number(),position:l.number()}),JE=l.object({fromSnakeId:l.number(),toSnakeId:l.number(),weight:l.number()}),zE=l.object({serialId:l.number(),groupId:l.number(),startSentenceIndex:l.number(),endSentenceIndex:l.number()}),QE=l.object({chunks:l.array(HE),fragmentGroups:l.array(zE),fragments:l.array(BE),readingEdges:l.array(qE),serial:UE,snakeChunks:l.array(KE),snakeEdges:l.array(JE),snakes:l.array($E)})});import{readFile as b6,writeFile as S6}from"fs/promises";var bh=i(()=>{"use strict";gh()});var Sh=i(()=>{"use strict";Tr();Lo()});import{mkdir as A6}from"fs/promises";import{join as O6}from"path";var wh=i(()=>{"use strict";I();W();fh();bh();Ei();Sh();Ot()});var Eh=i(()=>{"use strict"});var xs=i(()=>{"use strict";wh();Ei();Eh()});var kh=i(()=>{"use strict";W();xs()});var Ih=i(()=>{"use strict"});var xh=i(()=>{"use strict";uh();kh();Ih()});var Rh=i(()=>{"use strict";xh();xs()});import{createReadStream as aZ,createWriteStream as oZ}from"fs";import{createInterface as cZ}from"readline";import{z as _}from"zod";var uZ,VE,lZ,Rs=i(()=>{"use strict";uZ=_.object({id:_.string().min(1),chapterId:_.number().int(),sentenceIndex:_.number().int().nonnegative().optional(),rangeStart:_.number().int().nonnegative(),rangeEnd:_.number().int().nonnegative(),surface:_.string().min(1),qid:_.string().regex(/^Q[1-9][0-9]*$/),confidence:_.number().min(0).max(1).optional(),note:_.string().optional()}),VE=_.tuple([_.number().int().nonnegative(),_.number().int().nonnegative()]).readonly(),lZ=_.object({id:_.string().min(1),sourceMentionId:_.string().min(1),targetMentionId:_.string().min(1),predicate:_.string().min(1),evidenceSentenceIds:_.array(VE).min(1),confidence:_.number().min(0).max(1).optional(),note:_.string().optional()})});import{mkdir as gZ,rm as bZ}from"fs/promises";import{join as wZ}from"path";var vs=i(()=>{"use strict";Se();Ot();Rs()});var Th=i(()=>{"use strict";Ot();Rs()});var Gr=i(()=>{"use strict"});import{z as Ie}from"zod";var ek,tk,OZ,_s=i(()=>{"use strict";G();Gr();ek=Ie.object({candidateId:Ie.string().min(1),decision:Ie.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ie.string().nullable().optional()}).strict(),tk=Ie.object({decisions:Ie.array(ek),groupId:Ie.string().min(1)}).strict(),OZ=Ie.object({groups:Ie.array(tk)}).strict()});import{z as Br}from"zod";var ik,jZ,Ch=i(()=>{"use strict";G();Gr();_s();ik=Br.object({decision:Br.enum(["keep","reject"]),qid:Br.string().regex(/^Q[1-9][0-9]*$/)}).strict(),jZ=Br.object({qids:Br.array(ik)}).strict()});var Ph=i(()=>{"use strict";Sr()});import{z as Ur}from"zod";var ak,$Z,Ah=i(()=>{"use strict";G();ak=Ur.object({note:Ur.string().max(24).optional(),surfaceId:Ur.string().min(1)}).strict(),$Z=Ur.object({protectedSurfaces:Ur.array(ak)}).strict()});var Cs=i(()=>{"use strict"});var Lh=i(()=>{"use strict";Cs()});import{spawn as VZ}from"child_process";var Oh=i(()=>{"use strict"});var Ps=i(()=>{"use strict"});var Nh=i(()=>{"use strict";Ps();Gr()});var it=i(()=>{"use strict";_s();Ch();Gr();Ph();Ah();Lh();Cs();Oh();Nh();Ps()});var Ii=i(()=>{"use strict"});var Wh=i(()=>{"use strict";it();Ii()});var As=i(()=>{"use strict"});var Fh=i(()=>{"use strict";it()});var Ls=i(()=>{"use strict"});var Os=i(()=>{"use strict";it();Ii();Fh();Ls()});var Gh=i(()=>{"use strict";Os()});var Bh=i(()=>{"use strict";Se()});var Ns=i(()=>{"use strict"});var Uh=i(()=>{"use strict";vo();gt();Bn()});import{z as x}from"zod";var Hh,bk,Sk,wk,Z9,e4,qh=i(()=>{"use strict";G();gt();Uh();Hh=x.object({head:x.string().optional(),mode:x.enum(["full","head_tail"]).optional(),tail:x.string().optional(),text:x.string().optional()}).strict(),bk=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).strict(),Sk=x.union([x.object({end_anchor:x.union([x.string(),Hh]).optional(),quote:x.string().optional(),sentence_id:x.string().optional(),start_anchor:x.union([x.string(),Hh]).optional()}).strict(),x.array(bk)]),wk=x.object({confidence:x.number().min(0).max(1).optional(),evidence:Sk,predicate:x.string().min(1).max(64),sourceMentionId:x.string().min(1),targetMentionId:x.string().min(1)}).strict(),Z9=x.object({relations:x.array(wk)}).strict(),e4=new et});var $h=i(()=>{"use strict"});var Kh=i(()=>{"use strict";qh();$h()});var Jh=i(()=>{"use strict";Kh();Ii();Ls()});var Ds=i(()=>{"use strict";W();As()});var Yh=i(()=>{"use strict";it();We();vs();Wh();As();Gh();Bh();Ns();Jh();Ds()});var Zh=i(()=>{"use strict"});var ef=i(()=>{"use strict";vs();Th();Yh();Os();Ns();Ds();Zh()});var tf=i(()=>{"use strict";ef()});var Hr=i(()=>{"use strict";W()});var Ms=i(()=>{"use strict";We()});var Ws=i(()=>{"use strict";Se();We();kt();Hr();Ms()});var af=i(()=>{"use strict";We();Hr();Ws()});var Fs=i(()=>{"use strict";ye()});var of=i(()=>{"use strict";ye();Qt();Ke();Fs()});var sf=i(()=>{"use strict";kt();ye();Hr();of();Fs()});import{z as at}from"zod";var cf,N7,df=i(()=>{"use strict";cf=at.object({children:at.lazy(()=>at.array(cf)),uri:at.string().min(1),title:at.string().nullable().optional()}).strict(),N7=at.object({chapters:at.array(cf)}).strict()});var uf=i(()=>{"use strict";W()});var lf=i(()=>{"use strict";af();Hr();Ws();sf();Ms();df();uf()});var mf=i(()=>{"use strict";cr()});var Fe=i(()=>{"use strict";_p();yt();ih();Rh();tf();yt();ys();lf();mf();fi()});import{randomUUID as lee}from"crypto";async function pf(e){let t=await tI(e.databasePath);try{return await eI(t,e),await t.queryOne(`
463
+ SELECT 1 AS active
464
+ FROM state_locks
465
+ WHERE scope = ? AND resource_key = ?
466
+ LIMIT 1
467
+ `,[e.scope,e.resourceKey],()=>!0)===!0}finally{await t.close()}}async function eI(e,t){let r=[],n=[];t.scope!==void 0&&(r.push("scope = ?"),n.push(t.scope)),t.resourceKey!==void 0&&(r.push("resource_key = ?"),n.push(t.resourceKey));let a=await e.queryAll(`
468
+ SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
469
+ FROM state_locks
470
+ ${r.length===0?"":`WHERE ${r.join(" AND ")}`}
471
+ `,n,o=>({lock:rI(o),resourceKey:w(o,"resource_key"),scope:w(o,"scope")}));for(let{lock:o,resourceKey:s,scope:c}of a)iI(o,t.staleMs)&&await e.run(`
472
+ DELETE FROM state_locks
473
+ WHERE scope = ?
474
+ AND resource_key = ?
475
+ AND owner_id = ?
476
+ AND heartbeat_at = ?
477
+ `,[c,s,o.ownerId,o.heartbeatAt])}async function tI(e){return await v(e,Yk)}function rI(e){return{heartbeatAt:g(e,"heartbeat_at"),mode:nI(w(e,"mode")),ownerId:w(e,"owner_id"),ownerPid:g(e,"owner_pid")}}function nI(e){return e==="read"||e==="write"?e:"write"}function iI(e,t=Zk){return Date.now()-e.heartbeatAt>t&&!aI(e.ownerPid)}function aI(e){try{return process.kill(e,0),!0}catch(t){return!(h(t)&&t.code==="ESRCH")}}var Yk,Zk,hf=i(()=>{"use strict";f();I();b();Yk=`
478
+ CREATE TABLE IF NOT EXISTS state_locks (
479
+ scope TEXT NOT NULL,
480
+ resource_key TEXT NOT NULL,
481
+ mode TEXT NOT NULL,
482
+ owner_id TEXT NOT NULL,
483
+ owner_pid INTEGER NOT NULL,
484
+ heartbeat_at INTEGER NOT NULL,
485
+ created_at INTEGER NOT NULL,
486
+ PRIMARY KEY (scope, resource_key, owner_id)
487
+ );
488
+
489
+ CREATE INDEX IF NOT EXISTS idx_state_locks_resource
490
+ ON state_locks(scope, resource_key);
491
+ `,Zk=300*1e3});async function yf(e){return await pf({databasePath:j(),resourceKey:cI(e),scope:sI,staleMs:ff})||await dI(e)}function cI(e){return String(e)}async function dI(e){let t=await uI();try{let r=await t.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[e],n=>({heartbeatAt:g(n,"heartbeat_at"),ownerPid:g(n,"owner_pid")}));return r!==void 0&&mI(r)}finally{await t.close()}}async function uI(){let e=await v(j(),oI);return await lI(e),e}async function lI(e){new Set(await e.queryAll("PRAGMA table_info(library_locks)",void 0,r=>w(r,"name"))).has("heartbeat_at")||await e.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function mI(e){return Date.now()-e.heartbeatAt<=ff&&pI(e.ownerPid)}function pI(e){try{return process.kill(e,0),!0}catch(t){return!(h(t)&&t.code==="ESRCH")}}var oI,sI,ff,qr=i(()=>{"use strict";f();I();N();hf();b();oI=`
492
+ CREATE TABLE IF NOT EXISTS library_locks (
493
+ library_id INTEGER PRIMARY KEY,
494
+ mode TEXT NOT NULL,
495
+ owner_id TEXT NOT NULL,
496
+ owner_pid INTEGER NOT NULL,
497
+ heartbeat_at INTEGER NOT NULL,
498
+ created_at INTEGER NOT NULL
499
+ );
500
+ `,sI="library",ff=300*1e3});import{randomBytes as Ree}from"crypto";import{constants as Tee}from"fs";import{access as Cee,mkdir as Pee,stat as Aee}from"fs/promises";import{join as Oee,resolve as Nee}from"path";var Nt=i(()=>{"use strict";f();I();N();Pe();b();qr();ka()});import{createHash as $ee}from"crypto";import{mkdir as Jee,readdir as hI,rm as fI,stat as zee,writeFile as Qee}from"fs/promises";import{join as gf}from"path";async function bf(e){let t=gf(q(),"library"),r=await yI();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let n=new Set(r.map(d=>String(d))),a=await hI(t,{withFileTypes:!0}).catch(d=>{if(h(d)&&d.code==="ENOENT")return[];throw d}),o=0,s=0,c=0;for(let d of a){if(!d.isDirectory()||(o+=1,n.has(d.name)))continue;let m=Number(d.name);if(Number.isInteger(m)&&await yf(m))continue;let p=gf(t,d.name),S=await F(p);e.dryRun||await fI(p,{force:!0,recursive:!0}),s+=1,c+=S}return{freedBytes:c,removed:s,scanned:o}}async function yI(){let e=await v(j(),"");try{return await e.queryAll("SELECT id FROM libraries",void 0,t=>g(t,"id"))}catch{return}finally{await e.close()}}var Kr=i(()=>{"use strict";f();He();Xt();I();ue();rr();Tt();Wr();N();b();Jr();Nt();qr()});import{randomBytes as pte}from"crypto";import{constants as fte,copyFile as yte,mkdir as gte,opendir as bte,realpath as Ste,rename as wte,rm as Ete,stat as kte}from"fs/promises";import{dirname as xte,isAbsolute as Rte,join as vte,relative as Tte,resolve as _te}from"path";var bI,Fte,Jr=i(()=>{"use strict";f();I();N();Pe();ue();b();Nt();Kr();qr();bI=`
501
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
502
+ library_id INTEGER NOT NULL,
503
+ public_id TEXT NOT NULL,
504
+ relative_path TEXT NOT NULL,
505
+ status TEXT NOT NULL DEFAULT 'present',
506
+ last_seen_mutation_token TEXT,
507
+ last_seen_size INTEGER,
508
+ last_seen_mtime_ms INTEGER,
509
+ last_scanned_at TEXT,
510
+ created_at TEXT NOT NULL,
511
+ updated_at TEXT NOT NULL,
512
+ UNIQUE(library_id, public_id)
513
+ `,Fte=`
514
+ CREATE TABLE IF NOT EXISTS library_archives (
515
+ ${bI}
516
+ );
517
+
518
+ CREATE INDEX IF NOT EXISTS idx_library_archives_library
519
+ ON library_archives(library_id);
520
+
521
+ CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
522
+ ON library_archives(library_id, relative_path);
523
+ `});var Us=i(()=>{"use strict";ue();Jr();Nt()});var Ef=i(()=>{"use strict";un();pn();Mt();In();kn();X();xn();Xe();Tt();Kr();Us()});var kf=i(()=>{"use strict";so();pn();Ef();X();Jr();Us();Nt();Kr()});var xi=i(()=>{"use strict";Nt();Jr();kf();Kr();qr()});import{randomUUID as TI}from"crypto";import{join as _I}from"path";async function If(e="global"){let t=await Hs(),r=`${process.pid}-${TI()}`,n=Date.now(),a=!1;try{await t.transaction(async()=>{await OI(t),await t.run(`
524
+ INSERT OR IGNORE INTO gc_locks (
525
+ scope, owner_id, owner_pid, heartbeat_at, created_at
526
+ ) VALUES (?, ?, ?, ?, ?)
527
+ `,[e,r,process.pid,n,n]),a=await t.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[e],s=>w(s,"owner_id"))===r})}finally{await t.close()}if(!a)return;let o=setInterval(()=>{LI(e,r).catch(()=>{})},AI);return async()=>{clearInterval(o);let s=await Hs();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[e,r])}finally{await s.close()}}}async function LI(e,t){let r=await Hs();try{await r.run(`
528
+ UPDATE gc_locks
529
+ SET heartbeat_at = ?, owner_pid = ?
530
+ WHERE scope = ? AND owner_id = ?
531
+ `,[Date.now(),process.pid,e,t])}finally{await r.close()}}async function OI(e){let t=await e.queryAll("SELECT * FROM gc_locks",void 0,MI);for(let{lock:r,scope:n}of t.filter(({lock:a})=>NI(a)))await e.run(`
532
+ DELETE FROM gc_locks
533
+ WHERE scope = ?
534
+ AND owner_id = ?
535
+ AND heartbeat_at = ?
536
+ `,[n,r.ownerId,r.heartbeatAt])}function NI(e){return Date.now()-e.heartbeatAt<PI?!1:!WI(e.ownerPid)}async function Hs(){return await v(_I(ct(),"gc.sqlite"),CI)}function DI(e){return{createdAt:g(e,"created_at"),heartbeatAt:g(e,"heartbeat_at"),ownerId:w(e,"owner_id"),ownerPid:g(e,"owner_pid")}}function MI(e){return{lock:DI(e),scope:w(e,"scope")}}function WI(e){try{return process.kill(e,0),!0}catch(t){return!(h(t)&&t.code==="ESRCH")}}var CI,PI,AI,xf=i(()=>{"use strict";pe();f();I();b();CI=`
537
+ CREATE TABLE IF NOT EXISTS gc_locks (
538
+ scope TEXT PRIMARY KEY,
539
+ owner_id TEXT NOT NULL,
540
+ owner_pid INTEGER NOT NULL,
541
+ heartbeat_at INTEGER NOT NULL,
542
+ created_at INTEGER NOT NULL
543
+ );
544
+ `,PI=6e4,AI=2e4});import{readdir as Rf,rm as FI,stat as jI}from"fs/promises";import{join as vf}from"path";async function Tf(e){let t=Vs(),r=0,n=0,a=0;for(let o of await BI(t)){r+=1;let s=await jI(o).catch(d=>{if(!(h(d)&&d.code==="ENOENT"))throw d});if(s===void 0||!e.force&&e.now-s.mtimeMs<GI)continue;let c=await F(o);e.dryRun||await FI(o,{force:!0,recursive:!0}),n+=1,a+=c}return{freedBytes:a,removed:n,scanned:r}}async function BI(e){try{let t=await Rf(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isDirectory())continue;let a=vf(e,n.name),o=await Rf(a,{withFileTypes:!0});for(let s of o)r.push(vf(a,s.name))}return r}catch(t){if(h(t)&&t.code==="ENOENT")return[];throw t}}var GI,_f=i(()=>{"use strict";pe();b();Wr();GI=3600*1e3});import{mkdir as UI,readFile as HI,writeFile as qI}from"fs/promises";import{join as $I}from"path";async function Ri(e={}){let t=Date.now(),r=ct(),n=await If();if(n===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:t};try{if(e.opportunistic===!0&&!await QI(r,t))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:t};let a={dryRun:e.dryRun===!0,force:e.force===!0,now:t,stateDirectoryPath:r},o=[];for(let c of KI)o.push(await zI(c,a));let s={finishedAt:Date.now(),freedBytes:qs(o,"freedBytes"),jobs:o,removed:qs(o,"removed"),scanned:qs(o,"scanned"),skipped:!1,startedAt:t};return await XI(r,s.finishedAt).catch(()=>{}),s}finally{await n()}}async function zI(e,t){try{return{name:e.name,...await e.run(t)}}catch(r){return{error:Be(r),freedBytes:0,name:e.name,removed:0,scanned:0}}}function qs(e,t){return e.reduce((r,n)=>{let a=n[t];return r+(typeof a=="number"?a:0)},0)}async function QI(e,t){let r=Number((await HI(Cf(e),"utf8").catch(()=>"")).trim());return!Number.isFinite(r)||t-r>=JI}async function XI(e,t){await UI(e,{recursive:!0}),await qI(Cf(e),`${t}
545
+ `,"utf8")}function Cf(e){return $I(e,"gc.last-run")}var KI,JI,Pf=i(()=>{"use strict";pe();yt();Fe();ue();Sr();xi();b();xf();_f();KI=[{name:"wikg-coordinator",run:hi},{name:"search-cache",run:sn},{name:"library-index",run:bf},{name:"wikipage-cache",run:ja},{name:"build-queue",run:wi},{name:"tmp",run:Tf}],JI=600*1e3});var Af=i(()=>{"use strict";Pf()});Af();Se();nn();b();import{mkdir as Vre,readFile as Yre,rm as Zre,writeFile as ene}from"fs/promises";import{join as rne,resolve as nne}from"path";import{z as zr}from"zod";var VI=1,sne=zr.object({completedAt:zr.string().optional(),startedAt:zr.string(),status:zr.enum(["running","succeeded"]),version:zr.literal(VI)});ho();Tr();V();Nn();Dn();xi();N();pe();gt();Sr();it();fs();Fe();ye();ue();I();Ke();yt();ri();xi();N();import{rm as Qie}from"fs/promises";import{homedir as Vie}from"os";import{resolve as Zie}from"path";pe();I();ue();import{rm as Mie}from"fs/promises";import{join as Fie,resolve as jie}from"path";import{createWriteStream as Tne}from"fs";import{mkdir as Cne}from"fs/promises";import{dirname as Ane,resolve as Lne}from"path";import{pipeline as Nne}from"stream/promises";import{posix as pne,resolve as hne,sep as fne}from"path";import{open as gne}from"yauzl";f();f();import{rm as Eie}from"fs/promises";import{join as Iie}from"path";b();import{readFile as Hne,readdir as qne}from"fs/promises";import{join as Kne}from"path";f();import{join as Xne}from"path";ua();b();import{readFile as tie,readdir as rie}from"fs/promises";import{join as iie}from"path";import{mkdir as die,writeFile as uie}from"fs/promises";import{join as mie}from"path";ue();ri();Tt();b();Fe();Tt();Fe();Fe();Fe();Fe();We();it();I();Ot();var ox=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function Of(e){let t=sx(e.env);if(e.envPolicy==="production"){let o=ox.filter(s=>t[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:t,envPolicy:e.envPolicy,stateDir:e.stateDir}}let r=t.WIKIGRAPH_DEV??t.WIKIGRAPH_STATE_DIR,n=Lf(e.stateDir??r);if(n===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=Lf(e.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:t,envPolicy:e.envPolicy,stateDir:n}}function sx(e){return e===void 0?{...process.env}:{...process.env,...e}}function Lf(e){if(!(e===void 0||e.trim()===""))return e}var Nf="--wikigraph-internal-child",Df="--wikigraph-state-dir";async function Mf(e,t){let r=cx(process.argv.slice(2));if(r.internalChild!==e)throw new Error("This Wiki Graph worker entry is internal.");let n=Of({argv:r.argv,envPolicy:"production",stateDir:r.stateDir});return await vi(n.stateDir,()=>t(r))}function cx(e){let t=[],r,n;for(let a=0;a<e.length;a+=1){let o=e[a];if(o===Nf){if(a+1>=e.length)throw new Error(`${Nf} requires a value.`);r=e[a+1],a+=1;continue}if(o!==Df){t.push(o);continue}if(a+1>=e.length)throw new Error(`${Df} requires a value.`);n=e[a+1],a+=1}return{argv:t,internalChild:r??"",stateDir:n}}var dx={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as Goe}from"path";import{createReadStream as Voe}from"fs";import{rm as Zoe}from"fs/promises";import{join as tse}from"path";import{AsyncLocalStorage as ux}from"async_hooks";var qoe=new ux;var lx=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((e,t)=>[e,t]));function Wf(e){return`${JSON.stringify($s(e),null,2)}
546
+ `}function $s(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>$s(t)??null);if(typeof e=="object")return mx(e)}function mx(e){let t=Object.entries(e).map(([n,a],o)=>({index:o,key:n,priority:lx.get(n)??Number.MAX_SAFE_INTEGER,value:a})),r={};for(let n of t.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=$s(n.value);a!==void 0&&(r[n.key]=a)}return r}import{existsSync as lse,readFileSync as mse}from"fs";import{dirname as hse,join as fse,parse as yse,resolve as gse}from"path";async function px(){await Mf("gc-worker",async({argv:e})=>{let t=hx(e);process.stdout.write(Wf(await Ri({dryRun:t.dryRun,force:t.force})))})}function hx(e){return{dryRun:e.includes("--dry-run"),force:e.includes("--force")}}px().catch(e=>{process.stderr.write(`${e instanceof Error?e.stack??e.message:String(e)}
547
+ `),process.exitCode=1});
548
+ //# sourceMappingURL=gc-worker.js.map