agentix-cli 0.68.0 → 0.69.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 (100) hide show
  1. package/dist/{agent-HM7GNNUR.js → agent-VQIC7O5T.js} +2 -2
  2. package/dist/{board-dashboard-LEUIFDNJ.js → board-dashboard-ZPJHXX3U.js} +185 -185
  3. package/dist/board-dashboard-ZPJHXX3U.js.map +1 -0
  4. package/dist/{chunk-AQYST6P6.js → chunk-4NXIJEYU.js} +217 -215
  5. package/dist/chunk-4NXIJEYU.js.map +1 -0
  6. package/dist/chunk-5AMQFDLE.js +649 -0
  7. package/dist/chunk-5AMQFDLE.js.map +1 -0
  8. package/dist/{chunk-RX5VVHT4.js → chunk-ART666G6.js} +2 -2
  9. package/dist/chunk-AU6FFC4I.js +5 -0
  10. package/dist/chunk-AU6FFC4I.js.map +1 -0
  11. package/dist/{chunk-QHD473UI.js → chunk-B65FS265.js} +2 -2
  12. package/dist/{chunk-YQT4ZKY5.js → chunk-BYKF3UTL.js} +2 -2
  13. package/dist/{chunk-FZSEHYYU.js → chunk-CUZWGTXT.js} +2 -2
  14. package/dist/{chunk-G5JUY265.js → chunk-F2DEKA2Q.js} +2 -2
  15. package/dist/chunk-GQ76J72O.js +3 -0
  16. package/dist/chunk-GQ76J72O.js.map +1 -0
  17. package/dist/{chunk-DXOLLHVZ.js → chunk-HEJOWP7O.js} +2 -2
  18. package/dist/{chunk-7R334NQ5.js → chunk-KSDVKLHN.js} +2 -2
  19. package/dist/chunk-NMFXY3QU.js +2 -0
  20. package/dist/chunk-NMFXY3QU.js.map +1 -0
  21. package/dist/chunk-NVJHA63C.js +21 -0
  22. package/dist/chunk-NVJHA63C.js.map +1 -0
  23. package/dist/{chunk-FGRD3JAX.js → chunk-Q2WW2HF4.js} +2 -2
  24. package/dist/{chunk-CW63GAH5.js → chunk-QDRAKJSY.js} +65 -64
  25. package/dist/chunk-QDRAKJSY.js.map +1 -0
  26. package/dist/chunk-S4ASFOJU.js +2 -0
  27. package/dist/chunk-S4ASFOJU.js.map +1 -0
  28. package/dist/chunk-ST6KPQOY.js +3 -0
  29. package/dist/chunk-ST6KPQOY.js.map +1 -0
  30. package/dist/{chunk-TX7MWUC4.js → chunk-VOS2IW4V.js} +2 -2
  31. package/dist/chunk-ZXR6GNEK.js +3 -0
  32. package/dist/chunk-ZXR6GNEK.js.map +1 -0
  33. package/dist/cli.js +1 -1
  34. package/dist/cli.js.map +1 -1
  35. package/dist/fact-proposals-ERRQXV2J.js +2 -0
  36. package/dist/facts-X44PF73W.js +22 -0
  37. package/dist/facts-X44PF73W.js.map +1 -0
  38. package/dist/index.d.ts +57 -12
  39. package/dist/index.js +1 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/ledger-DHYRP4TN.js +2 -0
  42. package/dist/memory-migrate-ED37IBEL.js +2 -0
  43. package/dist/memory-migrate-ED37IBEL.js.map +1 -0
  44. package/dist/program-6PFRDQFT.js +2 -0
  45. package/dist/{promote-FDEKCVAE.js → promote-XRKH73IB.js} +2 -2
  46. package/dist/query-6272PJPD.js +2 -0
  47. package/dist/questions-QGITDLJY.js +2 -0
  48. package/dist/registry-KP3C4EZ4.js +2 -0
  49. package/dist/{request-planner-KQLWWR3U.js → request-planner-73Y5GI3D.js} +2 -2
  50. package/dist/{review-candidates-A6CLXAFS.js → review-candidates-VF5IWP5P.js} +2 -2
  51. package/dist/rotation-memo-store-X63HYIMV.js +2 -0
  52. package/dist/rotation-memo-store-X63HYIMV.js.map +1 -0
  53. package/dist/routing-T24BMMLM.js +2 -0
  54. package/dist/routing-T24BMMLM.js.map +1 -0
  55. package/dist/{seat-W3ZTOJUT.js → seat-XNA2O6EO.js} +2 -2
  56. package/dist/seat-XNA2O6EO.js.map +1 -0
  57. package/dist/{select-VPOWFRSN.js → select-WOUZIR3Y.js} +2 -2
  58. package/dist/web/activity-graph.global.js +75 -11
  59. package/dist/web/activity-graph.global.js.map +1 -1
  60. package/dist/wiki-W6WI6HL3.js +2 -0
  61. package/dist/wiki-W6WI6HL3.js.map +1 -0
  62. package/package.json +1 -1
  63. package/dist/board-dashboard-LEUIFDNJ.js.map +0 -1
  64. package/dist/chunk-ANGX6XPA.js +0 -20
  65. package/dist/chunk-ANGX6XPA.js.map +0 -1
  66. package/dist/chunk-AQYST6P6.js.map +0 -1
  67. package/dist/chunk-CW63GAH5.js.map +0 -1
  68. package/dist/chunk-L52X3YGH.js +0 -2
  69. package/dist/chunk-L52X3YGH.js.map +0 -1
  70. package/dist/chunk-WDRLN7F2.js +0 -648
  71. package/dist/chunk-WDRLN7F2.js.map +0 -1
  72. package/dist/facts-4YPSHIXJ.js +0 -22
  73. package/dist/facts-4YPSHIXJ.js.map +0 -1
  74. package/dist/program-KWSQLVSV.js +0 -2
  75. package/dist/query-PJG52OHP.js +0 -2
  76. package/dist/questions-2V2VGIT4.js +0 -3
  77. package/dist/questions-2V2VGIT4.js.map +0 -1
  78. package/dist/registry-6XJMNXY6.js +0 -2
  79. package/dist/routing-5G22WTPR.js +0 -2
  80. package/dist/wiki-ZM6BEOFX.js +0 -2
  81. /package/dist/{agent-HM7GNNUR.js.map → agent-VQIC7O5T.js.map} +0 -0
  82. /package/dist/{chunk-RX5VVHT4.js.map → chunk-ART666G6.js.map} +0 -0
  83. /package/dist/{chunk-QHD473UI.js.map → chunk-B65FS265.js.map} +0 -0
  84. /package/dist/{chunk-YQT4ZKY5.js.map → chunk-BYKF3UTL.js.map} +0 -0
  85. /package/dist/{chunk-FZSEHYYU.js.map → chunk-CUZWGTXT.js.map} +0 -0
  86. /package/dist/{chunk-G5JUY265.js.map → chunk-F2DEKA2Q.js.map} +0 -0
  87. /package/dist/{chunk-DXOLLHVZ.js.map → chunk-HEJOWP7O.js.map} +0 -0
  88. /package/dist/{chunk-7R334NQ5.js.map → chunk-KSDVKLHN.js.map} +0 -0
  89. /package/dist/{chunk-FGRD3JAX.js.map → chunk-Q2WW2HF4.js.map} +0 -0
  90. /package/dist/{chunk-TX7MWUC4.js.map → chunk-VOS2IW4V.js.map} +0 -0
  91. /package/dist/{program-KWSQLVSV.js.map → fact-proposals-ERRQXV2J.js.map} +0 -0
  92. /package/dist/{promote-FDEKCVAE.js.map → ledger-DHYRP4TN.js.map} +0 -0
  93. /package/dist/{query-PJG52OHP.js.map → program-6PFRDQFT.js.map} +0 -0
  94. /package/dist/{registry-6XJMNXY6.js.map → promote-XRKH73IB.js.map} +0 -0
  95. /package/dist/{routing-5G22WTPR.js.map → query-6272PJPD.js.map} +0 -0
  96. /package/dist/{seat-W3ZTOJUT.js.map → questions-QGITDLJY.js.map} +0 -0
  97. /package/dist/{wiki-ZM6BEOFX.js.map → registry-KP3C4EZ4.js.map} +0 -0
  98. /package/dist/{request-planner-KQLWWR3U.js.map → request-planner-73Y5GI3D.js.map} +0 -0
  99. /package/dist/{review-candidates-A6CLXAFS.js.map → review-candidates-VF5IWP5P.js.map} +0 -0
  100. /package/dist/{select-VPOWFRSN.js.map → select-WOUZIR3Y.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{e as o}from"./chunk-CUZWGTXT.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
+ //# sourceMappingURL=chunk-S4ASFOJU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n listAgents(): string[] {\n const agents = new Set<string>()\n\n const entries = this.sharedStore.listEntries()\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n const agentWiki = this.getAgentWiki(agentId)\n const agentEntries = this.getAgentEntries(agentId)\n\n const absorbedIds = new Set<string>()\n const index = agentWiki.rebuildIndex()\n for (const article of index.articles) {\n if (article.sources) {\n for (const s of article.sources) absorbedIds.add(s)\n }\n }\n\n return agentEntries.filter(e => !absorbedIds.has(e.id))\n }\n\n summary(): AgentWikiSummary[] {\n const agents = this.listAgents()\n return agents.map(agentId => {\n const entries = this.getAgentEntries(agentId)\n const wiki = this.getAgentWiki(agentId)\n const index = wiki.rebuildIndex()\n const unabsorbed = this.getUnabsorbedEntries(agentId)\n\n return {\n agentId,\n totalEntries: entries.length,\n totalArticles: index.articles.length,\n unabsorbed: unabsorbed.length,\n articles: index.articles,\n }\n })\n }\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,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KAAK,YAAY,YAAY,CAAE,QAAAA,CAAQ,CAAC,CACjD,CAEA,qBAAqBA,EAA8B,CACjD,IAAMQ,EAAY,KAAK,aAAaR,CAAO,EACrCS,EAAe,KAAK,gBAAgBT,CAAO,EAE3CU,EAAc,IAAI,IAClBC,EAAQH,EAAU,aAAa,EACrC,QAAWI,KAAWD,EAAM,SAC1B,GAAIC,EAAQ,QACV,QAAWC,KAAKD,EAAQ,QAASF,EAAY,IAAIG,CAAC,EAItD,OAAOJ,EAAa,OAAOH,GAAK,CAACI,EAAY,IAAIJ,EAAE,EAAE,CAAC,CACxD,CAEA,SAA8B,CAE5B,OADe,KAAK,WAAW,EACjB,IAAIN,GAAW,CAC3B,IAAMK,EAAU,KAAK,gBAAgBL,CAAO,EAEtCW,EADO,KAAK,aAAaX,CAAO,EACnB,aAAa,EAC1Bc,EAAa,KAAK,qBAAqBd,CAAO,EAEpD,MAAO,CACL,QAAAA,EACA,aAAcK,EAAQ,OACtB,cAAeM,EAAM,SAAS,OAC9B,WAAYG,EAAW,OACvB,SAAUH,EAAM,QAClB,CACF,CAAC,CACH,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","agents","entries","e","dir","agentWiki","agentEntries","absorbedIds","index","article","s","unabsorbed"]}
@@ -0,0 +1,3 @@
1
+ import{b,c as k,d as F,f as A}from"./chunk-GQ76J72O.js";import{a as B,b as v}from"./chunk-ZXR6GNEK.js";import{createHash as P}from"crypto";import{existsSync as _,statSync as q}from"fs";import{resolve as J}from"path";import{closeSync as L,existsSync as M,mkdirSync as S,openSync as C,readFileSync as E,renameSync as T,statSync as O,unlinkSync as $,writeFileSync as R}from"fs";import{dirname as x}from"path";var y=class extends Error{constructor(e,s){super(`fact ledger ${e} is unreadable (${s}). Nothing was written to it. Repair the JSON, or move the file aside to start an empty ledger.`);this.file=e;this.name="LedgerCorruptError"}};function j(r){if(!M(r))return null;let t;try{t=JSON.parse(E(r,"utf-8"))}catch(e){throw new y(r,String(e?.message??e))}if(!t||typeof t!="object"||!Array.isArray(t.facts)||t.proposals!==void 0&&!Array.isArray(t.proposals))throw new y(r,"not a ledger: expected { facts: [], proposals: [] }");return{facts:t.facts,proposals:t.proposals??[]}}function W(r,t){S(x(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;R(e,JSON.stringify(t,null,2)+`
2
+ `),T(e,r)}var N=r=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r);function I(r,t,e={}){let s=`${r}.lock`,i=e.timeoutMs??3e3,l=e.staleMs??15e3;S(x(s),{recursive:!0});let o=Date.now()+i,c;for(;c===void 0;)try{c=C(s,"wx")}catch(d){if(d?.code!=="EEXIST")throw d;try{if(Date.now()-O(s).mtimeMs>l){$(s);continue}}catch{continue}if(Date.now()>o)throw new Error(`fact ledger is busy (${s}); try again`);N(25)}try{return t()}finally{L(c);try{$(s)}catch{}}}var n=r=>r.toLowerCase().replace(/\s+/g," ").trim();function H(r,t){return"f-"+P("sha1").update(`${n(r)}\0${n(t)}`).digest("hex").slice(0,10)}var D=class{constructor(t){this.wikiDir=t;this.file=J(t,"_facts.json")}file;cache;reported;load(){if(!_(this.file))return{version:1,facts:[],proposals:[]};let t=q(this.file).mtimeMs;if(this.cache?.mtimeMs===t)return structuredClone(this.cache.data);let e;try{e=j(this.file)}catch(i){throw this.reported!==t&&(this.reported=t,console.error(`[wiki-facts] ${i.message}`)),i}let s={version:1,facts:e?.facts??[],proposals:e?.proposals??[]};return this.cache={mtimeMs:t,data:s},structuredClone(s)}update(t){return I(this.file,()=>{this.cache=void 0;let e=this.load(),{save:s,result:i}=t(e);return s&&(W(this.file,e),this.cache=void 0),i})}list(){return this.load().facts}get(t){return this.list().find(e=>e.id===t||t.length>=6&&e.id.startsWith(t))??null}write(t,e={}){let s=e.now??Date.now(),i=new Date(s).toISOString();if(!t.source?.trim())throw new Error('a fact needs a source: a system, URL, command or "owner said"');if(!t.subject?.trim()||!t.attribute?.trim()||!t.value?.trim())throw new Error("a fact needs a subject, an attribute and a value");let l=t.verifiedAt==="now"?s:Date.parse(t.verifiedAt??""),o=Number.isFinite(l),c=o?new Date(Math.min(l,s)).toISOString():i,d=b(t.volatility)?t.volatility:F(t.attribute,`${t.subject} ${t.attribute} is ${t.value}`),g={source:t.source.trim(),verifiedAt:c,verifiedBy:t.verifiedBy||"unknown",volatility:d,...typeof t.ttlDays=="number"?{ttlDays:t.ttlDays}:{}},h=H(t.subject,t.attribute),u=this.update(f=>{let a=f.facts.find(m=>m.id===h);if(!a){let m={id:h,subject:t.subject.trim(),attribute:t.attribute.trim(),value:t.value.trim(),...g,createdAt:i,updatedAt:i,...e.confirmedBy?{confirmedBy:e.confirmedBy}:{}};return f.facts.push(m),{save:!0,result:{status:"created",fact:m}}}let p=Date.parse(a.verifiedAt),w=o&&(!Number.isFinite(p)||Date.parse(c)>p);return n(a.value)===n(t.value)?!w&&!e.confirmedBy?{save:!1,result:{status:"unchanged",fact:a}}:(Object.assign(a,g,{updatedAt:i},e.confirmedBy?{confirmedBy:e.confirmedBy}:{}),{save:!0,result:{status:"verified",fact:a}}):!e.confirmedBy&&(!w||a.confirmedBy)?{save:!1,result:{contradiction:a}}:(a.history=[...a.history??[],{value:a.value,source:a.source,verifiedAt:a.verifiedAt,verifiedBy:a.verifiedBy,replacedAt:i}].slice(-10),a.value=t.value.trim(),Object.assign(a,g,{updatedAt:i}),e.confirmedBy?a.confirmedBy=e.confirmedBy:delete a.confirmedBy,{save:!0,result:{status:"updated",fact:a}})});if("contradiction"in u){let f=Q(this.wikiDir,u.contradiction,{...t,verifiedAt:o?c:"undated"});return{status:"contradiction",fact:u.contradiction,questionId:f}}return u}};function Q(r,t,e){let s=new v(r),i={kind:"contradiction",agentId:e.verifiedBy||"unknown",path:"_facts.json",subject:t.subject,field:`${t.attribute}=${n(e.value)}`,tier:"pillar",factId:t.id,proposed:{value:e.value.trim(),source:e.source.trim(),verifiedAt:e.verifiedAt,verifiedBy:e.verifiedBy},question:`${t.subject} \xB7 ${t.attribute}: the wiki says "${t.value}" (${t.source}, checked ${t.verifiedAt.slice(0,10)}), but ${e.verifiedBy} reports "${e.value.trim()}" (${e.source.trim()}, checked ${e.verifiedAt.slice(0,10)}). Which is true?`};return s.add([i]),B(i.kind,i.agentId,i.subject,i.field)}function et(r){return new v(r).list("open").filter(t=>t.kind==="contradiction").map(t=>({type:"contradiction",articles:[`_facts.json#${t.factId??"?"}`],message:`[${t.id}] ${t.question}`,confidence:"high"}))}function rt(r,t=Date.now()){return A(r,t)}function it(r,t){let e=n(r),s=null;for(let i of t){let l=n(i.subject);if(l.length<3||!e.includes(l))continue;let o=n(i.attribute).split(" ").filter(d=>d.length>2);(e.includes(n(i.value))||i.volatility!=="stable"&&k(r)===i.volatility||o.length>0&&o.every(d=>e.includes(d)))&&(!s||i.subject.length>s.subject.length)&&(s=i)}return s}export{H as a,D as b,et as c,rt as d,it as e};
3
+ //# sourceMappingURL=chunk-ST6KPQOY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/facts/ledger.ts","../src/wiki/facts/ledger-file.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { existsSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { readLedger, withLock, writeLedger } from \"./ledger-file\"\nimport { classifyAttribute, classifyFact, isFactClass, isPastTtl, type FactClass, type Provenance } from \"@/agents/fact-freshness\"\nimport type { ContradictionIssue } from \"../lint-contradictions\"\nimport { QuestionStore, questionId } from \"../questions\"\n\n// --- The wiki fact ledger: durable facts with provenance (#273) ---\n//\n// Articles are prose. A fact an agent states to a person (\"the vendor\n// account is past due\") needs more than prose: where it came from, when\n// it was last checked, by whom, and how long it stays true. This is that\n// record — one small JSON sidecar beside `_questions.json`, skipped by the\n// article index like every `_` file.\n//\n// Every other store references it: memory lines that restate a ledger\n// fact are replaced by a reference at injection (agents/memory-context),\n// and memo claims wait here as proposals (fact-proposals.ts) instead of\n// becoming memory.\n//\n// Overwrite safety: a write that disagrees with the current value needs a\n// check newer than the current one, or a person's confirmation. Otherwise\n// the old value stays and a contradiction question joins the wiki's\n// question queue (`agentx wiki questions`), where the answer is written\n// back through here.\n\nexport interface WikiFact extends Provenance {\n id: string\n subject: string\n attribute: string\n value: string\n createdAt: string\n updatedAt: string\n /** Set when a person confirmed the value over a newer-dated one. */\n confirmedBy?: string\n /** Earlier values, newest last. Nothing is replaced silently. */\n history?: Array<{ value: string; source: string; verifiedAt: string; verifiedBy: string; replacedAt: string }>\n}\n\nexport interface FactInput {\n subject: string\n attribute: string\n value: string\n source: string\n verifiedBy: string\n /** When the source was checked (ISO date, or \"now\"). Without it the\n * write is undated and never counts as newer than an existing fact. */\n verifiedAt?: string\n volatility?: FactClass\n ttlDays?: number\n}\n\nexport type WriteStatus = \"created\" | \"verified\" | \"unchanged\" | \"updated\" | \"contradiction\"\n\nexport interface WriteResult {\n status: WriteStatus\n fact: WikiFact\n /** The queued question, for a contradiction. */\n questionId?: string\n}\n\nexport interface LedgerFile {\n version: 1\n facts: WikiFact[]\n proposals: import(\"./fact-proposals\").FactProposal[]\n}\n\nconst norm = (s: string) => s.toLowerCase().replace(/\\s+/g, \" \").trim()\n\n/** Stable per subject and attribute, so a re-check lands on the same fact. */\nexport function factId(subject: string, attribute: string): string {\n return \"f-\" + createHash(\"sha1\").update(`${norm(subject)}\\u0000${norm(attribute)}`).digest(\"hex\").slice(0, 10)\n}\n\nexport class FactLedger {\n readonly file: string\n private cache?: { mtimeMs: number; data: LedgerFile }\n private reported?: number\n\n constructor(readonly wikiDir: string) {\n this.file = resolve(wikiDir, \"_facts.json\")\n }\n\n /** The ledger as stored. Throws LedgerCorruptError on a file that does\n * not parse: it is never read as empty, so it is never overwritten. */\n load(): LedgerFile {\n if (!existsSync(this.file)) return { version: 1, facts: [], proposals: [] }\n const mtimeMs = statSync(this.file).mtimeMs\n if (this.cache?.mtimeMs === mtimeMs) return structuredClone(this.cache.data)\n let raw\n try {\n raw = readLedger(this.file)\n } catch (e) {\n // Once per version of the bad file, not once per prompt.\n if (this.reported !== mtimeMs) {\n this.reported = mtimeMs\n console.error(`[wiki-facts] ${(e as Error).message}`)\n }\n throw e\n }\n const data: LedgerFile = { version: 1, facts: (raw?.facts ?? []) as WikiFact[], proposals: (raw?.proposals ?? []) as LedgerFile[\"proposals\"] }\n this.cache = { mtimeMs, data }\n return structuredClone(data)\n }\n\n /**\n * Load, change and save under the ledger's lock, so concurrent writers\n * (a daemon proposing memo claims, a CLI `set`) can't drop each other's\n * change. `fn` returns whether to save, and a result.\n */\n update<T>(fn: (data: LedgerFile) => { save: boolean; result: T }): T {\n return withLock(this.file, () => {\n this.cache = undefined\n const data = this.load()\n const { save, result } = fn(data)\n if (save) {\n writeLedger(this.file, data)\n this.cache = undefined\n }\n return result\n })\n }\n\n list(): WikiFact[] { return this.load().facts }\n\n get(id: string): WikiFact | null {\n return this.list().find((f) => f.id === id || (id.length >= 6 && f.id.startsWith(id))) ?? null\n }\n\n /**\n * Record a checked fact. Refuses a fact with no source. A different value\n * replaces the current one only with a dated check newer than the current\n * one, or `confirmedBy`. A value a person confirmed is replaced only by\n * another confirmation. Otherwise the current value stays and a\n * contradiction question is raised.\n *\n * A write with no `verifiedAt` is undated: it can create a fact, but it\n * never counts as newer than a fact already there.\n */\n write(input: FactInput, opts: { confirmedBy?: string; now?: number } = {}): WriteResult {\n const now = opts.now ?? Date.now()\n const nowIso = new Date(now).toISOString()\n if (!input.source?.trim()) throw new Error(\"a fact needs a source: a system, URL, command or \\\"owner said\\\"\")\n if (!input.subject?.trim() || !input.attribute?.trim() || !input.value?.trim()) {\n throw new Error(\"a fact needs a subject, an attribute and a value\")\n }\n const checked = input.verifiedAt === \"now\" ? now : Date.parse(input.verifiedAt ?? \"\")\n const dated = Number.isFinite(checked)\n // A check can't be dated after it happened.\n const verifiedAt = dated ? new Date(Math.min(checked, now)).toISOString() : nowIso\n const volatility = isFactClass(input.volatility)\n ? input.volatility\n : classifyAttribute(input.attribute, `${input.subject} ${input.attribute} is ${input.value}`)\n const provenance: Provenance = {\n source: input.source.trim(), verifiedAt, verifiedBy: input.verifiedBy || \"unknown\", volatility,\n ...(typeof input.ttlDays === \"number\" ? { ttlDays: input.ttlDays } : {}),\n }\n const id = factId(input.subject, input.attribute)\n\n const out = this.update<WriteResult | { contradiction: WikiFact }>((data) => {\n const existing = data.facts.find((f) => f.id === id)\n if (!existing) {\n const fact: WikiFact = {\n id, subject: input.subject.trim(), attribute: input.attribute.trim(), value: input.value.trim(),\n ...provenance, createdAt: nowIso, updatedAt: nowIso,\n ...(opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {}),\n }\n data.facts.push(fact)\n return { save: true, result: { status: \"created\", fact } }\n }\n\n const prior = Date.parse(existing.verifiedAt)\n const newer = dated && (!Number.isFinite(prior) || Date.parse(verifiedAt) > prior)\n if (norm(existing.value) === norm(input.value)) {\n if (!newer && !opts.confirmedBy) return { save: false, result: { status: \"unchanged\", fact: existing } }\n Object.assign(existing, provenance, { updatedAt: nowIso }, opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {})\n return { save: true, result: { status: \"verified\", fact: existing } }\n }\n\n // A person's confirmation outranks any agent's date.\n if (!opts.confirmedBy && (!newer || existing.confirmedBy)) {\n return { save: false, result: { contradiction: existing } }\n }\n\n existing.history = [...(existing.history ?? []), {\n value: existing.value, source: existing.source, verifiedAt: existing.verifiedAt,\n verifiedBy: existing.verifiedBy, replacedAt: nowIso,\n }].slice(-10)\n existing.value = input.value.trim()\n Object.assign(existing, provenance, { updatedAt: nowIso })\n if (opts.confirmedBy) existing.confirmedBy = opts.confirmedBy\n else delete existing.confirmedBy\n return { save: true, result: { status: \"updated\", fact: existing } }\n })\n\n if (\"contradiction\" in out) {\n const questionId = raiseContradiction(this.wikiDir, out.contradiction, { ...input, verifiedAt: dated ? verifiedAt : \"undated\" })\n return { status: \"contradiction\", fact: out.contradiction, questionId }\n }\n return out\n }\n}\n\nfunction raiseContradiction(wikiDir: string, current: WikiFact, input: FactInput & { verifiedAt: string }): string {\n const store = new QuestionStore(wikiDir)\n const item = {\n kind: \"contradiction\" as const,\n agentId: input.verifiedBy || \"unknown\",\n path: \"_facts.json\",\n subject: current.subject,\n // One question per refused value: a second, different claim is a new\n // question, while repeating the same claim does not ask twice.\n field: `${current.attribute}=${norm(input.value)}`,\n tier: \"pillar\",\n factId: current.id,\n proposed: { value: input.value.trim(), source: input.source.trim(), verifiedAt: input.verifiedAt, verifiedBy: input.verifiedBy },\n question:\n `${current.subject} · ${current.attribute}: the wiki says \"${current.value}\" ` +\n `(${current.source}, checked ${current.verifiedAt.slice(0, 10)}), but ${input.verifiedBy} reports ` +\n `\"${input.value.trim()}\" (${input.source.trim()}, checked ${input.verifiedAt.slice(0, 10)}). Which is true?`,\n }\n store.add([item])\n return questionId(item.kind, item.agentId, item.subject, item.field)\n}\n\n/** Open fact contradictions, in the shape `wiki lint` reports. */\nexport function factContradictions(wikiDir: string): ContradictionIssue[] {\n return new QuestionStore(wikiDir).list(\"open\")\n .filter((q) => q.kind === \"contradiction\")\n .map((q) => ({\n type: \"contradiction\" as const,\n articles: [`_facts.json#${q.factId ?? \"?\"}`],\n message: `[${q.id}] ${q.question}`,\n confidence: \"high\" as const,\n }))\n}\n\n/** A fact is stale when it is past its class TTL. */\nexport function isStaleFact(f: WikiFact, now = Date.now()): boolean {\n return isPastTtl(f, now)\n}\n\n/**\n * The ledger fact a memory line restates, if any. The line must name the\n * fact's subject, and either repeat its value, share its volatility class,\n * or name its attribute.\n */\nexport function matchFact(content: string, facts: WikiFact[]): WikiFact | null {\n const text = norm(content)\n let best: WikiFact | null = null\n for (const f of facts) {\n const subject = norm(f.subject)\n if (subject.length < 3 || !text.includes(subject)) continue\n const attrWords = norm(f.attribute).split(\" \").filter((w) => w.length > 2)\n const hit = text.includes(norm(f.value))\n || (f.volatility !== \"stable\" && classifyFact(content) === f.volatility)\n || (attrWords.length > 0 && attrWords.every((w) => text.includes(w)))\n if (hit && (!best || f.subject.length > best.subject.length)) best = f\n }\n return best\n}\n","import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"fs\"\nimport { dirname } from \"path\"\n\n// --- The fact ledger's file: strict reads, locked writes (#273) ---\n//\n// Two rules keep the ledger from losing facts with nobody watching:\n// 1. A file that does not parse is never treated as empty. Reading it\n// throws LedgerCorruptError, so no write can replace it; the file is\n// left exactly as it is for a person to repair.\n// 2. load → modify → save runs under a lockfile, so a daemon proposing\n// memo claims and a CLI `set` or `approve` can't drop each other's\n// write.\n\nexport class LedgerCorruptError extends Error {\n constructor(readonly file: string, cause: string) {\n super(\n `fact ledger ${file} is unreadable (${cause}). Nothing was written to it. ` +\n `Repair the JSON, or move the file aside to start an empty ledger.`,\n )\n this.name = \"LedgerCorruptError\"\n }\n}\n\nexport interface RawLedger {\n facts: unknown[]\n proposals: unknown[]\n}\n\n/** Null when the file does not exist; throws when it exists but is not a ledger. */\nexport function readLedger(file: string): RawLedger | null {\n if (!existsSync(file)) return null\n let raw: any\n try {\n raw = JSON.parse(readFileSync(file, \"utf-8\"))\n } catch (e) {\n throw new LedgerCorruptError(file, String((e as Error)?.message ?? e))\n }\n if (!raw || typeof raw !== \"object\" || !Array.isArray(raw.facts) || (raw.proposals !== undefined && !Array.isArray(raw.proposals))) {\n throw new LedgerCorruptError(file, \"not a ledger: expected { facts: [], proposals: [] }\")\n }\n return { facts: raw.facts, proposals: raw.proposals ?? [] }\n}\n\nexport function writeLedger(file: string, data: unknown): void {\n mkdirSync(dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(data, null, 2) + \"\\n\")\n renameSync(tmp, file)\n}\n\nconst sleep = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n\n/**\n * Run `fn` holding `<file>.lock`. Waits up to `timeoutMs` for another\n * holder; a lock older than `staleMs` is a crashed holder and is taken over.\n */\nexport function withLock<T>(file: string, fn: () => T, opts: { timeoutMs?: number; staleMs?: number } = {}): T {\n const lock = `${file}.lock`\n const timeoutMs = opts.timeoutMs ?? 3000\n const staleMs = opts.staleMs ?? 15_000\n mkdirSync(dirname(lock), { recursive: true })\n const deadline = Date.now() + timeoutMs\n let fd: number | undefined\n while (fd === undefined) {\n try {\n fd = openSync(lock, \"wx\")\n } catch (e: any) {\n if (e?.code !== \"EEXIST\") throw e\n try {\n if (Date.now() - statSync(lock).mtimeMs > staleMs) { unlinkSync(lock); continue }\n } catch { continue }\n if (Date.now() > deadline) throw new Error(`fact ledger is busy (${lock}); try again`)\n sleep(25)\n }\n }\n try {\n return fn()\n } finally {\n closeSync(fd)\n try { unlinkSync(lock) } catch { /* already gone */ }\n }\n}\n"],"mappings":"uGAAA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,YAAAC,MAAgB,KACrC,OAAS,WAAAC,MAAe,OCFxB,OAAS,aAAAC,EAAW,cAAAC,EAAY,aAAAC,EAAW,YAAAC,EAAU,gBAAAC,EAAc,cAAAC,EAAY,YAAAC,EAAU,cAAAC,EAAY,iBAAAC,MAAqB,KAC1H,OAAS,WAAAC,MAAe,OAYjB,IAAMC,EAAN,cAAiC,KAAM,CAC5C,YAAqBC,EAAcC,EAAe,CAChD,MACE,eAAeD,oBAAuBC,kGAExC,EAJmB,UAAAD,EAKnB,KAAK,KAAO,oBACd,CACF,EAQO,SAASE,EAAWF,EAAgC,CACzD,GAAI,CAACV,EAAWU,CAAI,EAAG,OAAO,KAC9B,IAAIG,EACJ,GAAI,CACFA,EAAM,KAAK,MAAMV,EAAaO,EAAM,OAAO,CAAC,CAC9C,OAAS,EAAP,CACA,MAAM,IAAID,EAAmBC,EAAM,OAAQ,GAAa,SAAW,CAAC,CAAC,CACvE,CACA,GAAI,CAACG,GAAO,OAAOA,GAAQ,UAAY,CAAC,MAAM,QAAQA,EAAI,KAAK,GAAMA,EAAI,YAAc,QAAa,CAAC,MAAM,QAAQA,EA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d,EAAE,CACN,CAGO,SAASC,GAAYzB,EAAaG,EAAM,KAAK,IAAI,EAAY,CAClE,OAAOuB,EAAU1B,EAAGG,CAAG,CACzB,CAOO,SAASwB,GAAUC,EAAiBC,EAAoC,CAC7E,IAAMC,EAAOpD,EAAKkD,CAAO,EACrBG,EAAwB,KAC5B,QAAW/B,KAAK6B,EAAO,CACrB,IAAMhD,EAAUH,EAAKsB,EAAE,OAAO,EAC9B,GAAInB,EAAQ,OAAS,GAAK,CAACiD,EAAK,SAASjD,CAAO,EAAG,SACnD,IAAMmD,EAAYtD,EAAKsB,EAAE,SAAS,EAAE,MAAM,GAAG,EAAE,OAAQiC,GAAMA,EAAE,OAAS,CAAC,GAC7DH,EAAK,SAASpD,EAAKsB,EAAE,KAAK,CAAC,GACjCA,EAAE,aAAe,UAAYkC,EAAaN,CAAO,IAAM5B,EAAE,YACzDgC,EAAU,OAAS,GAAKA,EAAU,MAAOC,GAAMH,EAAK,SAASG,CAAC,CAAC,KACzD,CAACF,GAAQ/B,EAAE,QAAQ,OAAS+B,EAAK,QAAQ,UAASA,EAAO/B,GAEvE,OAAO+B,CACT","names":["createHash","existsSync","statSync","resolve","closeSync","existsSync","mkdirSync","openSync","readFileSync","renameSync","statSync","unlinkSync","writeFileSync","dirname","LedgerCorruptError","file","cause","readLedger","raw","writeLedger","data","tmp","sleep","ms","withLock","fn","opts","lock","timeoutMs","staleMs","deadline","fd","e","norm","s","factId","subject","attribute","createHash","FactLedger","wikiDir","resolve","existsSync","mtimeMs","statSync","raw","readLedger","e","data","fn","withLock","save","result","writeLedger","id","f","input","opts","now","nowIso","checked","dated","verifiedAt","volatility","isFactClass","classifyAttribute","provenance","out","existing","fact","prior","newer","questionId","raiseContradiction","current","store","QuestionStore","item","factContradictions","q","isStaleFact","isPastTtl","matchFact","content","facts","text","best","attrWords","w","classifyFact"]}
@@ -1,4 +1,4 @@
1
- import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";import{a as ne,b as He}from"./chunk-FCPTN6NF.js";import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{o as we,p as Ke}from"./chunk-SZJMS7K4.js";import{y as We,z as Ze}from"./chunk-N5NPJ6DJ.js";import{a as rt,b as ot,c as st,d as it,e as at,f as ct,g as ut,h as lt,i as dt,j as pt,k as mt,l as bt}from"./chunk-RGDKHYY2.js";import{a as E,b as Ye,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function gt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import yt from"better-sqlite3";import{createHash as ht}from"crypto";import{mkdirSync as wt}from"fs";import{dirname as Tt,resolve as Et}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function kt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function xt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&Rt(e),t<2&&At(e),t<3&&St(e)}function St(e){e.exec(`
1
+ import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";import{a as ne,b as He}from"./chunk-FCPTN6NF.js";import{o as we,p as Ke}from"./chunk-SZJMS7K4.js";import{y as We,z as Ze}from"./chunk-N5NPJ6DJ.js";import{a as rt,b as ot,c as st,d as it,e as at,f as ct,g as ut,h as lt,i as dt,j as pt,k as mt,l as bt}from"./chunk-RGDKHYY2.js";import{a as E,b as Ye,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function gt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import yt from"better-sqlite3";import{createHash as ht}from"crypto";import{mkdirSync as wt}from"fs";import{dirname as Tt,resolve as Et}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function kt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function xt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&Rt(e),t<2&&At(e),t<3&&St(e)}function St(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function At(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:g,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function $t(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:B,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:B}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===B),u=a&&a.type==="tool_use"?a.input:null;return{answers:Pe(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Vt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Pe(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Pe(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function zt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Jt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,Pt,qt,Be,Xt,be=E(()=>{"use strict";Ke();Ue();ft();j();Y();N();z();Bt="claude-code",Pt="claude-haiku-4-5-20251001",qt=24e3,Be=2e3,Xt=3e4});import{readFileSync as Gt}from"fs";import{homedir as Yt}from"os";import{join as Kt}from"path";function v(e={}){let t=(e.baseUrl??Ht).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??Zt,s=e.maxChoiceOptions??en,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),on(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:y,dispose:d}=sn(a.abortSignal,a.timeoutMs??e.timeoutMs??Wt);try{let b={"Content-Type":"application/json"},g=rn(e.apiKeyEnv,e.apiKeyFile);g&&(b.Authorization=`Bearer ${g}`);let w=await p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:nn(a.questions)}),signal:y});if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await w.json(),m=F(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function nn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:tn[n.type]};return t}function rn(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Kt(Yt(),t.slice(2)):t;if(!Z.has(n))try{let o=Gt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function on(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function sn(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Ht,Wt,Zt,en,tn,Z,fe=E(()=>{"use strict";j();N();z();Y();Ht="http://127.0.0.1:8000/v1",Wt=3e4,Zt=6e3,en=50;tn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var qe={};Ye(qe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>B,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>gt,agreement:()=>rt,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>lt,askSeat:()=>pn,band:()=>Ie,bootstrapInterval:()=>pt,brier:()=>at,buildDesign:()=>Ne,calibrationReport:()=>mt,choice:()=>tt,compareCalibrators:()=>Lt,confidenceFor:()=>re,configureDecisions:()=>cn,coverageCurve:()=>ut,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>v,decisionsRuntime:()=>ln,describeIssues:()=>U,ece:()=>st,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>ve,fitRecalibrator:()=>P,fitTemperature:()=>dt,getDecisionBackend:()=>D,getSeatMode:()=>Ve,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ct,logit:()=>le,mce:()=>it,measureConsistency:()=>Qt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>et,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>F,recordSeatOutcome:()=>dn,registerBuiltinDecisionBackends:()=>an,registerDecisionBackend:()=>R,reliabilityBins:()=>ot,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>un,score:()=>nt,seatEnvVar:()=>$e,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function an(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>v(t)),R("jev",()=>v({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>v({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var Xe=E(()=>{"use strict";ke();N();j();z();C();Y();V();bt();Me();je();ze();pe();be();fe();C();pe();be();fe()});function cn(e){T={...ye,...T,...e},ee=!0}function un(){T={...ye,seats:{}},ee=!1}function mn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(Ze(),he(We)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=(Xe(),he(qe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function ln(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return bn.includes(t)?t:null}function $e(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Ve(e,t=process.env){mn();let r=ge(t[$e(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function dn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function pn(e,t,r,n={}){let o=Ve(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=fn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return gn(e,o,t,r,i,n,s,a,u),yn(e,i,u),null}}function fn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ge(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function gn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ge(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ge(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function yn(e,t,r){let n=Date.now();n-Je<6e4||(Je=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,bn,Je,ze=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;bn=["off","shadow","active"];Je=0});export{D as a,Ee as b,C as c,I as d,V as e,Lt as f,Me as g,Qt as h,je as i,me as j,Un as k,Ue as l,an as m,Xe as n,cn as o,un as p,ln as q,ge as r,$e as s,Ve as t,dn as u,pn as v,ze as w};
114
- //# sourceMappingURL=chunk-TX7MWUC4.js.map
114
+ //# sourceMappingURL=chunk-VOS2IW4V.js.map
@@ -0,0 +1,3 @@
1
+ import{createHash as l}from"crypto";import{existsSync as f,mkdirSync as c,readFileSync as g,writeFileSync as p}from"fs";import{dirname as h,resolve as v}from"path";function m(u,i,s,t){return l("sha1").update([u,i,s.toLowerCase().trim(),t??""].join("\0")).digest("hex").slice(0,12)}var d=class{file;constructor(i){this.file=v(i,"_questions.json")}get path(){return this.file}load(){if(!f(this.file))return{version:1,questions:[]};try{let i=JSON.parse(g(this.file,"utf-8"));return Array.isArray(i?.questions)?{version:1,questions:i.questions}:{version:1,questions:[]}}catch{return{version:1,questions:[]}}}save(i){c(h(this.file),{recursive:!0}),p(this.file,`${JSON.stringify(i,null,2)}
2
+ `)}list(i){let s=this.load().questions;return i?s.filter(t=>t.status===i):s}add(i){let s=this.load(),t=new Set(s.questions.map(n=>n.id)),r=0,e=0,o=new Date().toISOString();for(let n of i){let a=m(n.kind,n.agentId,n.subject,n.field);if(t.has(a)){e++;continue}t.add(a),s.questions.push({...n,id:a,status:"open",asked:o}),r++}return r>0&&this.save(s),{added:r,skipped:e}}resolve(i,s,t){let r=this.load(),e=r.questions.find(o=>o.id===i||o.id.startsWith(i));return e?(e.status=s,e.answered=new Date().toISOString(),t!==void 0&&(e.answer=t),this.save(r),e):null}};export{m as a,d as b};
3
+ //# sourceMappingURL=chunk-ZXR6GNEK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/questions.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// The gaps a lookup cannot close.\n//\n// Two things were producing gap signal and throwing it away. Absorb has\n// always emitted a `gaps` array — entities it referenced but has no\n// article for — and the command printed it and moved on, so the signal\n// lived in a cron log nobody reads. And the field grader can now name a\n// missing `role` or `ourOwner` that no system of record holds.\n//\n// Both are the same thing: a question only a person can answer. They\n// get one queue rather than two, because a second parallel store is\n// precisely what the wiki-as-source-of-truth decision rules out.\n//\n// Stored as JSON beside the other wiki sidecars (_index.json,\n// _backlinks.json), because this is derived state that is rebuilt and\n// rewritten, not knowledge. The knowledge is what lands in the article\n// once the question is answered.\n\nexport type QuestionStatus = \"open\" | \"answered\" | \"dismissed\"\n\nexport interface WikiQuestion {\n id: string\n /** \"field\" — a named gap in an existing article.\n * \"article\" — absorb referenced something with no article at all.\n * \"contradiction\" — a write disagreed with a wiki fact and could not\n * replace it (facts/ledger.ts); the answer is the true value. */\n kind: \"field\" | \"article\" | \"contradiction\"\n agentId: string\n /** Article path for a field question; empty for a missing article. */\n path: string\n /** Article title, or the referenced name for a missing article. */\n subject: string\n /** Required-field key, for `kind: \"field\"`. */\n field?: string\n /** What tier of the build this gap sits at, so asking can be ordered. */\n tier?: string\n question: string\n /** For a contradiction: the wiki fact and the value that was refused. */\n factId?: string\n proposed?: { value: string; source: string; verifiedAt: string; verifiedBy: string }\n status: QuestionStatus\n asked: string\n answered?: string\n answer?: string\n}\n\nexport interface QuestionsFile {\n version: 1\n questions: WikiQuestion[]\n}\n\n/**\n * Stable across runs, so re-grading the same article does not ask the\n * same question twice and cannot resurrect one already dismissed.\n */\nexport function questionId(kind: string, agentId: string, subject: string, field?: string): string {\n return createHash(\"sha1\")\n .update([kind, agentId, subject.toLowerCase().trim(), field ?? \"\"].join(\"\\u0000\"))\n .digest(\"hex\")\n .slice(0, 12)\n}\n\nexport class QuestionStore {\n private readonly file: string\n\n constructor(wikiDir: string) {\n this.file = resolve(wikiDir, \"_questions.json\")\n }\n\n get path(): string { return this.file }\n\n load(): QuestionsFile {\n if (!existsSync(this.file)) return { version: 1, questions: [] }\n try {\n const parsed = JSON.parse(readFileSync(this.file, \"utf-8\")) as Partial<QuestionsFile>\n if (!Array.isArray(parsed?.questions)) return { version: 1, questions: [] }\n return { version: 1, questions: parsed.questions as WikiQuestion[] }\n } catch {\n // A corrupt queue must not stop an absorb. Worst case the\n // questions are asked again; they are idempotent by id.\n return { version: 1, questions: [] }\n }\n }\n\n private save(f: QuestionsFile): void {\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(this.file, `${JSON.stringify(f, null, 2)}\\n`)\n }\n\n list(status?: QuestionStatus): WikiQuestion[] {\n const all = this.load().questions\n return status ? all.filter((q) => q.status === status) : all\n }\n\n /**\n * Add questions that are not already on the queue.\n *\n * An existing id is left completely alone — including an answered or\n * dismissed one. Re-asking something a person has already dealt with\n * is how a queue becomes noise and then becomes ignored.\n */\n add(items: Array<Omit<WikiQuestion, \"id\" | \"status\" | \"asked\">>): { added: number; skipped: number } {\n const f = this.load()\n const seen = new Set(f.questions.map((q) => q.id))\n let added = 0, skipped = 0\n const now = new Date().toISOString()\n\n for (const item of items) {\n const id = questionId(item.kind, item.agentId, item.subject, item.field)\n if (seen.has(id)) { skipped++; continue }\n seen.add(id)\n f.questions.push({ ...item, id, status: \"open\", asked: now })\n added++\n }\n if (added > 0) this.save(f)\n return { added, skipped }\n }\n\n /** Returns the question so the caller can act on its subject/field. */\n resolve(id: string, status: \"answered\" | \"dismissed\", answer?: string): WikiQuestion | null {\n const f = this.load()\n const q = f.questions.find((x) => x.id === id || x.id.startsWith(id))\n if (!q) return null\n q.status = status\n q.answered = new Date().toISOString()\n if (answer !== undefined) q.answer = answer\n this.save(f)\n return q\n }\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,EAAS,WAAAC,MAAe,OAwD1B,SAASC,EAAWC,EAAcC,EAAiBC,EAAiBC,EAAwB,CACjG,OAAOX,EAAW,MAAM,EACrB,OAAO,CAACQ,EAAMC,EAASC,EAAQ,YAAY,EAAE,KAAK,EAAGC,GAAS,EAAE,EAAE,KAAK,IAAQ,CAAC,EAChF,OAAO,KAAK,EACZ,MAAM,EAAG,EAAE,CAChB,CAEO,IAAMC,EAAN,KAAoB,CACR,KAEjB,YAAYC,EAAiB,CAC3B,KAAK,KAAOP,EAAQO,EAAS,iBAAiB,CAChD,CAEA,IAAI,MAAe,CAAE,OAAO,KAAK,IAAK,CAEtC,MAAsB,CACpB,GAAI,CAACZ,EAAW,KAAK,IAAI,EAAG,MAAO,CAAE,QAAS,EAAG,UAAW,CAAC,CAAE,EAC/D,GAAI,CACF,IAAMa,EAAS,KAAK,MAAMX,EAAa,KAAK,KAAM,OAAO,CAAC,EAC1D,OAAK,MAAM,QAAQW,GAAQ,SAAS,EAC7B,CAAE,QAAS,EAAG,UAAWA,EAAO,SAA4B,EADrB,CAAE,QAAS,EAAG,UAAW,CAAC,CAAE,CAE5E,MAAE,CAGA,MAAO,CAAE,QAAS,EAAG,UAAW,CAAC,CAAE,CACrC,CACF,CAEQ,KAAKC,EAAwB,CACnCb,EAAUG,EAAQ,KAAK,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACjDD,EAAc,KAAK,KAAM,GAAG,KAAK,UAAUW,EAAG,KAAM,CAAC;AAAA,CAAK,CAC5D,CAEA,KAAKC,EAAyC,CAC5C,IAAMC,EAAM,KAAK,KAAK,EAAE,UACxB,OAAOD,EAASC,EAAI,OAAQC,GAAMA,EAAE,SAAWF,CAAM,EAAIC,CAC3D,CASA,IAAIE,EAAiG,CACnG,IAAMJ,EAAI,KAAK,KAAK,EACdK,EAAO,IAAI,IAAIL,EAAE,UAAU,IAAKG,GAAMA,EAAE,EAAE,CAAC,EAC7CG,EAAQ,EAAGC,EAAU,EACnBC,EAAM,IAAI,KAAK,EAAE,YAAY,EAEnC,QAAWC,KAAQL,EAAO,CACxB,IAAMM,EAAKlB,EAAWiB,EAAK,KAAMA,EAAK,QAASA,EAAK,QAASA,EAAK,KAAK,EACvE,GAAIJ,EAAK,IAAIK,CAAE,EAAG,CAAEH,IAAW,SAC/BF,EAAK,IAAIK,CAAE,EACXV,EAAE,UAAU,KAAK,CAAE,GAAGS,EAAM,GAAAC,EAAI,OAAQ,OAAQ,MAAOF,CAAI,CAAC,EAC5DF,IAEF,OAAIA,EAAQ,GAAG,KAAK,KAAKN,CAAC,EACnB,CAAE,MAAAM,EAAO,QAAAC,CAAQ,CAC1B,CAGA,QAAQG,EAAYT,EAAkCU,EAAsC,CAC1F,IAAMX,EAAI,KAAK,KAAK,EACdG,EAAIH,EAAE,UAAU,KAAMY,GAAMA,EAAE,KAAOF,GAAME,EAAE,GAAG,WAAWF,CAAE,CAAC,EACpE,OAAKP,GACLA,EAAE,OAASF,EACXE,EAAE,SAAW,IAAI,KAAK,EAAE,YAAY,EAChCQ,IAAW,SAAWR,EAAE,OAASQ,GACrC,KAAK,KAAKX,CAAC,EACJG,GALQ,IAMjB,CACF","names":["createHash","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","resolve","questionId","kind","agentId","subject","field","QuestionStore","wikiDir","parsed","f","status","all","q","items","seen","added","skipped","now","item","id","answer","x"]}
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as n}from"./chunk-WDRLN7F2.js";import"./chunk-G3SOCQII.js";import"./chunk-DXOLLHVZ.js";import"./chunk-Z3IP66SL.js";import"./chunk-APKKQGTG.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-AQYST6P6.js";import"./chunk-QHD473UI.js";import"./chunk-G5JUY265.js";import"./chunk-ZVP6GB4G.js";import"./chunk-BYJ3A55Y.js";import"./chunk-LQRBGQIR.js";import"./chunk-NEC4RXFT.js";import"./chunk-RX5VVHT4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-CW63GAH5.js";import"./chunk-ANGX6XPA.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-YQT4ZKY5.js";import"./chunk-SFQUP3BP.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-FGRD3JAX.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-L52X3YGH.js";import"./chunk-FZSEHYYU.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-7R334NQ5.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-TX7MWUC4.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-FX3D7YON.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
2
+ import{a as n}from"./chunk-5AMQFDLE.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-HEJOWP7O.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-4NXIJEYU.js";import"./chunk-B65FS265.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-QDRAKJSY.js";import"./chunk-NVJHA63C.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-BYKF3UTL.js";import"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/signal-exit.ts","../src/cli.ts"],"sourcesContent":["// --- Ctrl-C / SIGTERM for CLI commands ---\n//\n// Short commands should exit at once when stopped. Long-running ones (the\n// daemon above all) install their own handler to finish in-flight work first.\n// The CLI's quick exit used to be registered unconditionally, before the\n// daemon's, and Node runs listeners in registration order — so every stop\n// exited the process before the daemon's drain began and killed in-flight\n// agent tasks mid-turn (#103). Now the quick exit only fires when nobody\n// else handles the signal.\n\ntype SignalTarget = Pick<NodeJS.Process, \"on\" | \"listenerCount\" | \"exit\">\n\nexport const CLI_EXIT_SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const\n\nexport function installCliSignalExit(proc: SignalTarget = process): void {\n for (const sig of CLI_EXIT_SIGNALS) {\n proc.on(sig, () => {\n // This listener is always one of them; anything more means a command\n // is handling the stop itself.\n if (proc.listenerCount(sig) <= 1) proc.exit(0)\n })\n }\n}\n","#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\nimport { installCliSignalExit } from \"@/utils/signal-exit\"\n\ninstallCliSignalExit()\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";wrDAYO,IAAMA,EAAmB,CAAC,SAAU,SAAS,EAE7C,SAASC,EAAqBC,EAAqB,QAAe,CACvE,QAAWC,KAAOH,EAChBE,EAAK,GAAGC,EAAK,IAAM,CAGbD,EAAK,cAAcC,CAAG,GAAK,GAAGD,EAAK,KAAK,CAAC,CAC/C,CAAC,CAEL,CClBAE,EAAqB,EAErB,eAAeC,GAAO,CACpB,IAAMC,EAAU,MAAMC,EAAa,EAGnC,GADa,QAAQ,KAAK,MAAM,CAAC,EACxB,SAAW,EAAG,CACrBD,EAAQ,WAAW,EACnB,OAGFA,EAAQ,MAAM,CAChB,CAEAD,EAAK","names":["CLI_EXIT_SIGNALS","installCliSignalExit","proc","sig","installCliSignalExit","main","program","buildProgram"]}
1
+ {"version":3,"sources":["../src/utils/signal-exit.ts","../src/cli.ts"],"sourcesContent":["// --- Ctrl-C / SIGTERM for CLI commands ---\n//\n// Short commands should exit at once when stopped. Long-running ones (the\n// daemon above all) install their own handler to finish in-flight work first.\n// The CLI's quick exit used to be registered unconditionally, before the\n// daemon's, and Node runs listeners in registration order — so every stop\n// exited the process before the daemon's drain began and killed in-flight\n// agent tasks mid-turn (#103). Now the quick exit only fires when nobody\n// else handles the signal.\n\ntype SignalTarget = Pick<NodeJS.Process, \"on\" | \"listenerCount\" | \"exit\">\n\nexport const CLI_EXIT_SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const\n\nexport function installCliSignalExit(proc: SignalTarget = process): void {\n for (const sig of CLI_EXIT_SIGNALS) {\n proc.on(sig, () => {\n // This listener is always one of them; anything more means a command\n // is handling the stop itself.\n if (proc.listenerCount(sig) <= 1) proc.exit(0)\n })\n }\n}\n","#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\nimport { installCliSignalExit } from \"@/utils/signal-exit\"\n\ninstallCliSignalExit()\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";wyDAYO,IAAMA,EAAmB,CAAC,SAAU,SAAS,EAE7C,SAASC,EAAqBC,EAAqB,QAAe,CACvE,QAAWC,KAAOH,EAChBE,EAAK,GAAGC,EAAK,IAAM,CAGbD,EAAK,cAAcC,CAAG,GAAK,GAAGD,EAAK,KAAK,CAAC,CAC/C,CAAC,CAEL,CClBAE,EAAqB,EAErB,eAAeC,GAAO,CACpB,IAAMC,EAAU,MAAMC,EAAa,EAGnC,GADa,QAAQ,KAAK,MAAM,CAAC,EACxB,SAAW,EAAG,CACrBD,EAAQ,WAAW,EACnB,OAGFA,EAAQ,MAAM,CAChB,CAEAD,EAAK","names":["CLI_EXIT_SIGNALS","installCliSignalExit","proc","sig","installCliSignalExit","main","program","buildProgram"]}
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f}from"./chunk-AU6FFC4I.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-QIJLFPWE.js";export{d as approveFactProposal,c as listFactProposals,a as parseClaim,b as proposeFacts,e as rejectFactProposal,f as routeMemo};
2
+ //# sourceMappingURL=fact-proposals-ERRQXV2J.js.map
@@ -0,0 +1,22 @@
1
+ import{b as A}from"./chunk-NMFXY3QU.js";import"./chunk-QIJLFPWE.js";import{existsSync as C,readFileSync as j}from"fs";import{resolve as M}from"path";import{execFile as G}from"child_process";function p(n,t,o={}){return new Promise(e=>{G(n,t,{timeout:o.timeoutMs??15e3,signal:o.signal,maxBuffer:4*1024*1024,env:{...process.env,PATH:[process.env.PATH??"","/opt/homebrew/bin","/usr/local/bin",`${process.env.HOME??""}/.local/bin`].filter(Boolean).join(":")}},(r,a,i)=>{let s=r&&typeof r.code=="number"?r.code:r?1:0;e({stdout:String(a??""),stderr:String(i??""),code:s})})})}async function y(n){let{code:t}=await p("command",["-v",n],{timeoutMs:3e3}).catch(()=>({code:1}));if(t===0)return!0;let{code:o}=await p("/usr/bin/which",[n],{timeoutMs:3e3});return o===0}var I=[["216","Tunisia"],["966","Saudi Arabia"],["971","UAE"],["974","Qatar"],["965","Kuwait"],["973","Bahrain"],["968","Oman"],["962","Jordan"],["961","Lebanon"],["212","Morocco"],["213","Algeria"],["218","Libya"],["249","Sudan"],["20","Egypt"],["90","Turkey"],["33","France"],["49","Germany"],["39","Italy"],["34","Spain"],["44","United Kingdom"],["31","Netherlands"],["32","Belgium"],["41","Switzerland"],["1","US/Canada"]];function m(n){let t=n.replace(/\D/g,""),o,e=0;for(let[r,a]of I)t.startsWith(r)&&r.length>e&&(o=a,e=r.length);return o}function F(n){let t=[];for(let o of n.split(`
2
+ `)){let e=o.trim();if(!e||e.startsWith("ALIAS"))continue;let r=e.split(/\s{2,}/).filter(Boolean);if(r.length<2)continue;let a=r[r.length-1];if(!a.includes("@"))continue;let i=r[r.length-2],s=r.length>=3?r[r.length-3]:"";if(!s||!/\d/.test(i))continue;let l=m(i);t.push({name:s,source:"wacli",fields:{phone:`+${i.replace(/\D/g,"")}`,whatsapp:a,...l?{country:l}:{}}})}return t}function w(){return{name:"wacli",provides:["contact value","country"],async available(){if(!await y("wacli"))return{kind:"not-installed",hint:"brew install wacli \u2014 see https://wacli.sh"};let{stdout:n,stderr:t,code:o}=await p("wacli",["contacts","search","__agentx_probe__"],{timeoutMs:1e4});return o!==0&&/auth|not logged in|no session|login/i.test(n+t)?{kind:"not-configured",hint:"wacli auth \u2014 scan the QR to link the account"}:null},async lookup(n,t){let o=[],e=new Set;for(let r of n)for(let a of T(r.name)){let{stdout:i,code:s}=await p("wacli",["contacts","search",a],{signal:t,timeoutMs:15e3});if(s!==0)continue;let l=F(i).filter(u=>E(u.name,r.name));if(l.length!==0){for(let u of l){let c=u.fields.whatsapp;e.has(c)||(e.add(c),o.push({...u,fuzzy:!P(u.name,r.name)}))}break}}return o}}}var h=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim(),P=(n,t)=>h(n)===h(t);function T(n){let t=h(n).split(/\s+/).filter(o=>o.length>2);return t.length>1?[n,t[t.length-1]]:[n]}function E(n,t){let o=h(n).split(/\s+/).filter(Boolean),e=h(t).split(/\s+/).filter(Boolean);if(o.length===0||e.length===0)return!1;let[r,a]=o.length<=e.length?[o,e]:[e,o];return r.every(i=>a.includes(i))}var D={whatsapp:"whatsapp",telegram:"telegram",gitlab:"gitlab",github:"github",email:"email",phone:"phone",slack:"slack",discord:"discord"};function z(n=".agentx"){return M(process.cwd(),n,"contacts.json")}function S(n){if(!C(n))return[];try{let t=JSON.parse(j(n,"utf-8"));return Array.isArray(t?.contacts)?t.contacts:[]}catch{return[]}}var b=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim();function _(n){return[n.name,n.id,...n.aliases??[]].filter(t=>!!(t&&t.trim())).map(b)}function L(n){let t={};for(let[o,e]of Object.entries(n.channels??{})){let r=String(e??"").trim();if(!r)continue;let a=D[o.toLowerCase()]??o.toLowerCase();if(a==="whatsapp"){let i=r.split("@")[0].replace(/\D/g,"");if(t.whatsapp=r.includes("@")?r:`${i}@s.whatsapp.net`,i){t.phone??=`+${i}`;let s=m(i);s&&(t.country??=s)}continue}if(a==="phone"){let i=r.replace(/\D/g,"");t.phone=r.startsWith("+")?r:`+${i}`;let s=m(i);s&&(t.country??=s);continue}if(a==="telegram"&&/^\d+$/.test(r)){t.telegramId=r;continue}t[a]=a==="gitlab"||a==="github"?r.startsWith("@")?r:`@${r}`:r}return t}function k(n={}){let t=n.path??z();return{name:"contacts",provides:["contact value","handles","country"],async available(){return C(t)?S(t).length>0?null:{kind:"not-configured",hint:`${t} has no contacts`}:{kind:"not-configured",hint:`no ${t} \u2014 add {"contacts":[{"name":"\u2026","aliases":[],"channels":{"whatsapp":"\u2026"}}]}`}},async lookup(o){let e=S(t);if(e.length===0)return[];let r=new Map;for(let s of e)for(let l of _(s))l&&r.set(l,s);let a=[],i=new Set;for(let s of o){let l=r.get(b(s.name));if(!l||i.has(l))continue;i.add(l);let u=L(l);Object.keys(u).length!==0&&a.push({name:l.name??s.name,source:"contacts",fields:u,fuzzy:b(l.name??"")!==b(s.name)})}return a}}}function v(n={}){let t=(n.baseUrl??process.env.GITLAB_URL??"").replace(/\/+$/,""),o=n.token??process.env.GITLAB_ADMIN_TOKEN??process.env.GITLAB_TOKEN;return{name:"gitlab",provides:["email","handle","profile URL"],async available(){if(!t)return{kind:"not-configured",hint:"export GITLAB_URL=https://<your-gitlab-host>"};if(!o)return{kind:"not-configured",hint:"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)"};try{let e=await fetch(`${t}/api/v4/user`,{headers:{"PRIVATE-TOKEN":o}});if(e.status===401||e.status===403)return{kind:"not-configured",hint:`GitLab rejected the token (${e.status}) \u2014 set a valid GITLAB_ADMIN_TOKEN`};if(!e.ok)return{kind:"failed",hint:`GitLab returned ${e.status} for the auth probe`}}catch(e){return{kind:"failed",hint:`cannot reach ${t}: ${String(e?.message??e)}`}}return null},async lookup(e,r){if(!o||!t)return[];let a=[],i=new Set;for(let s of e){let l=`${t}/api/v4/users?search=${encodeURIComponent(s.name)}&per_page=5`,u;try{let c=await fetch(l,{headers:{"PRIVATE-TOKEN":o},signal:r});if(!c.ok)continue;u=await c.json()}catch{continue}if(Array.isArray(u))for(let c of u){let d=c.username??c.web_url??"";if(!d||i.has(d))continue;i.add(d);let f={},g=c.email||c.public_email;g&&(f.email=g),c.username&&(f.gitlab=`@${c.username}`),c.web_url&&(f.profile=c.web_url),c.organization&&(f.organisation=c.organization),c.job_title&&(f.role=c.job_title),c.state&&c.state!=="active"&&(f.accountState=c.state),Object.keys(f).length!==0&&a.push({name:c.name??s.name,source:"gitlab",fields:f,fuzzy:(c.name??"").toLowerCase()!==s.name.toLowerCase()})}}return a}}}function x(){return{name:"gog",provides:["contact value","email","organisation","role","country"],async available(){if(!await y("gog"))return{kind:"not-installed",hint:"brew install gog \u2014 Google CLI"};let{stdout:n,stderr:t}=await p("gog",["contacts","list","-j"],{timeoutMs:2e4}),o=n+t;return/unknown flag|Run with --help/i.test(o)?{kind:"failed",hint:`gog rejected the probe: ${o.split(`
3
+ `)[0]}`}:/accessNotConfigured|has not been used in project/i.test(o)?{kind:"not-configured",hint:"enable the People API on the gog OAuth project, then retry (console.developers.google.com \u2192 APIs \u2192 People API)"}:/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(o)?{kind:"not-configured",hint:"gog auth login \u2014 the stored token is expired or lacks contacts scope"}:null},async lookup(n,t){let o=[];for(let e of n){let{stdout:r,code:a}=await p("gog",["contacts","search",e.name,"-j","--results-only"],{signal:t,timeoutMs:2e4});if(a!==0)continue;let i;try{i=JSON.parse(r)}catch{continue}let s=Array.isArray(i)?i:i?.results??i?.people??[];for(let l of s){let u={},c=l.phoneNumbers?.[0]?.value,d=l.emailAddresses?.[0]?.value,f=l.organizations?.[0];c&&(u.phone=c),d&&(u.email=d),f?.name&&(u.organisation=f.name),f?.title&&(u.role=f.title);let g=l.addresses?.[0]?.country;g&&(u.country=g),Object.keys(u).length!==0&&o.push({name:l.names?.[0]?.displayName??e.name,source:"gog",fields:u})}}return o}}}var R=n=>typeof n=="string"&&n.trim()?n.trim():void 0;function $(n){return String(n??"").split("@")[0].split(":")[0].toLowerCase()}function H(n){let t=new Map;for(let o of n){let e=R(o.meta?.sender);if(!e||A(e))continue;let r=R(o.meta?.senderId),a=R(o.meta?.senderUsername),i=$(o.source),s={};if(r&&/@s\.whatsapp\.net$/.test(r)){let c=r.split("@")[0].replace(/\D/g,"");if(c){s.phone=`+${c}`,s.whatsapp=r;let d=m(c);d&&(s.country=d)}}else if(i==="whatsapp"&&r&&/^\d{6,}$/.test(r)){s.phone=`+${r}`,s.whatsapp=`${r}@s.whatsapp.net`;let c=m(r);c&&(s.country=c)}if(a){let c=a.startsWith("@")?a:`@${a}`;i==="gitlab"?s.gitlab=c:i==="github"?s.github=c:i==="telegram"?s.telegram=c:s.handle=c}if(r&&!s.phone&&!a&&(s[`${i||"platform"}Id`]=r),Object.keys(s).length===0)continue;let l=e.toLowerCase(),u=t.get(l);if(!u){t.set(l,{name:e,source:"entries",fields:s});continue}for(let[c,d]of Object.entries(s))u.fields[c]??=d}return Array.from(t.values())}function U(n){let t;return{...n,available:()=>t??=n.available(),lookup:(o,e)=>n.lookup(o,e)}}function N(){return[k(),w(),v(),x()].map(U)}function ut(n,t={}){let o=t.max??25,e=new Map;for(let a of n){let i=(a.sender??"").trim();i&&O(i)&&e.set(i.toLowerCase(),{name:i,origin:"sender",type:"person"})}for(let a of n){let i=(a.context??"").trim();if(!O(i))continue;let s=i.toLowerCase();e.has(s)||e.set(s,{name:i,origin:"context"})}let r=(t.known??[]).filter(a=>a.trim().length>2);if(r.length>0){let a=n.map(i=>i.content??"").join(`
4
+ `).toLowerCase();for(let i of r){let s=i.toLowerCase().trim();e.has(s)||a.includes(s)&&e.set(s,{name:i,origin:"body",type:"person"})}}return Array.from(e.values()).slice(0,o)}var B=new Set(["me","user","system","cron","unknown","anonymous","bot","agent","self","test","admin","none","null","n/a"]),W=new Set(["group","team","chat","channel","squad","crew","room","family","project","board","committee","club","staff","office","dept","department","support","sales","ops","admins","everyone","all"]);function O(n){let t=n.trim();if(!t||t.length>48||B.has(t.toLowerCase())||/[\d@/\\#:|_]/.test(t))return!1;let o=t.split(/\s+/);return o.length<2||o.length>4||o.some(e=>W.has(e.toLowerCase()))?!1:o.every(e=>/^[\p{Lu}][\p{L}'’.-]*$/u.test(e))}async function ft(n,t={}){let o=t.sources??N(),e=n.slice(0,t.maxEntities??25);if(e.length===0)return{records:[],results:[]};let r=new AbortController,a=setTimeout(()=>r.abort(),t.timeoutMs??12e4);try{let i=await Promise.all(o.map(async s=>{let l=Date.now();try{let u=await s.available();if(u)return{source:s.name,records:[],unavailable:u,ms:Date.now()-l};let c=await s.lookup(e,r.signal);return{source:s.name,records:c,ms:Date.now()-l}}catch(u){return{source:s.name,records:[],unavailable:{kind:"failed",hint:String(u?.message??u)},ms:Date.now()-l}}}));for(let s of i)t.onResult?.(s);return{records:i.flatMap(s=>s.records),results:i}}finally{clearTimeout(a)}}function dt(n,t=N()){let o=new Map(t.map(e=>[e.name,e.provides]));return n.filter(e=>e.unavailable&&e.unavailable.kind!=="failed").map(e=>({source:e.source,kind:e.unavailable.kind,hint:e.unavailable.hint,provides:o.get(e.source)??[]}))}function pt(n){let t=new Map;for(let o of n){let e=o.name.toLowerCase().trim(),r=t.get(e);r||(r={name:o.name,fields:{}},t.set(e,r));for(let[a,i]of Object.entries(o.fields)){if(!i?.trim())continue;let s=r.fields[a];if(!s){r.fields[a]={value:i,source:o.source};continue}s.value!==i&&(r.fields[`${a} (${o.source})`]??={value:i,source:o.source})}}return Array.from(t.values())}function mt(n){if(n.length===0)return"";let t=n.filter(o=>Object.keys(o.fields).length>0).map(o=>{let e=Object.entries(o.fields).map(([r,a])=>` - ${r}: \`${a.value}\` _(${a.source})_`).join(`
5
+ `);return`- **${o.name}**
6
+ ${e}`});return t.length===0?"":`
7
+ ## Verified facts
8
+
9
+ These were read from systems of record \u2014 WhatsApp, GitLab, Google, the
10
+ ERP \u2014 not from the entries. They are more reliable than anything the
11
+ conversation implies, and they are the identity fields articles are
12
+ graded on.
13
+
14
+ Copy every value that belongs to an article you write, **verbatim**, into
15
+ its Identity section. Do not paraphrase an identifier, reformat it, or
16
+ replace it with the name of the channel it belongs to. Where a fact here
17
+ contradicts the entries, this wins and the entry is stale.
18
+
19
+ ${t.join(`
20
+ `)}
21
+ `}export{m as countryFromPhone,k as createContactsSource,v as createGitlabSource,x as createGogSource,w as createWacliSource,N as defaultSources,ut as extractHints,L as factsFrom,dt as installPrompts,O as isPersonName,S as loadContacts,U as memoizeAvailability,pt as mergeRecords,_ as namesOf,F as parseContactsTable,$ as platformOf,E as plausible,H as recordsFromEntries,mt as renderFactsBlock,ft as resolveFacts};
22
+ //# sourceMappingURL=facts-X44PF73W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/facts/sources/contacts.ts","../src/wiki/facts/exec.ts","../src/wiki/facts/sources/wacli.ts","../src/wiki/facts/sources/gitlab.ts","../src/wiki/facts/sources/gog.ts","../src/wiki/facts/sources/entries.ts","../src/wiki/facts/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\n\n// The contact registry an operator maintains by hand.\n//\n// `.agentx/contacts.json` already existed and nothing in the wiki layer\n// read it, which meant the one place a person had deliberately written\n// down \"this human is these accounts\" was invisible to the pipeline\n// asking that exact question.\n//\n// It ranks above every other source. wacli knows what WhatsApp knows,\n// GitLab knows what GitLab knows, and the entries know who sent a\n// message; this is the only source where someone decided that a name,\n// an alias and a set of handles all refer to one person. Where it\n// disagrees with a directory, the deliberate answer wins — and the\n// disagreement is kept and rendered rather than resolved silently.\n//\n// It is also the only source that resolves aliases, which is what makes\n// a single registry entry cover a given name, a \"first.last\" handle and\n// the display name a phone happens to be saved under.\n\nexport interface ContactRecord {\n id?: string\n name?: string\n aliases?: string[]\n channels?: Record<string, string>\n}\n\n/** Channel key → the fact field it supplies. */\nconst CHANNEL_FIELDS: Record<string, string> = {\n whatsapp: \"whatsapp\",\n telegram: \"telegram\",\n gitlab: \"gitlab\",\n github: \"github\",\n email: \"email\",\n phone: \"phone\",\n slack: \"slack\",\n discord: \"discord\",\n}\n\nexport function contactsPath(agentxDir = \".agentx\"): string {\n return resolve(process.cwd(), agentxDir, \"contacts.json\")\n}\n\nexport function loadContacts(path: string): ContactRecord[] {\n if (!existsSync(path)) return []\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { contacts?: unknown }\n return Array.isArray(parsed?.contacts) ? (parsed.contacts as ContactRecord[]) : []\n } catch {\n return []\n }\n}\n\nconst norm = (s: string) =>\n s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\n\n/** Every spelling this registry entry answers to. */\nexport function namesOf(c: ContactRecord): string[] {\n return [c.name, c.id, ...(c.aliases ?? [])]\n .filter((x): x is string => Boolean(x && x.trim()))\n .map(norm)\n}\n\n/**\n * Turn one registry entry's channels into fact fields.\n *\n * A WhatsApp JID is also a number and a country, so it expands rather\n * than being copied across verbatim — the same unpacking the entries\n * source does, because a reader wants the number, not the routing\n * address it happens to be embedded in.\n */\nexport function factsFrom(c: ContactRecord): Record<string, string> {\n const fields: Record<string, string> = {}\n for (const [key, raw] of Object.entries(c.channels ?? {})) {\n const value = String(raw ?? \"\").trim()\n if (!value) continue\n const field = CHANNEL_FIELDS[key.toLowerCase()] ?? key.toLowerCase()\n\n if (field === \"whatsapp\") {\n const digits = value.split(\"@\")[0].replace(/\\D/g, \"\")\n fields.whatsapp = value.includes(\"@\") ? value : `${digits}@s.whatsapp.net`\n if (digits) {\n fields.phone ??= `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n }\n continue\n }\n if (field === \"phone\") {\n const digits = value.replace(/\\D/g, \"\")\n fields.phone = value.startsWith(\"+\") ? value : `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n continue\n }\n // A bare numeric Telegram id is an account, not a way to reach\n // someone — same rule the entries source applies.\n if (field === \"telegram\" && /^\\d+$/.test(value)) {\n fields.telegramId = value\n continue\n }\n fields[field] = field === \"gitlab\" || field === \"github\"\n ? (value.startsWith(\"@\") ? value : `@${value}`)\n : value\n }\n return fields\n}\n\nexport function createContactsSource(opts: { path?: string } = {}): FactSource {\n const path = opts.path ?? contactsPath()\n\n return {\n name: \"contacts\",\n provides: [\"contact value\", \"handles\", \"country\"],\n async available() {\n if (!existsSync(path)) {\n return {\n kind: \"not-configured\",\n hint: `no ${path} — add {\"contacts\":[{\"name\":\"…\",\"aliases\":[],\"channels\":{\"whatsapp\":\"…\"}}]}`,\n }\n }\n return loadContacts(path).length > 0\n ? null\n : { kind: \"not-configured\", hint: `${path} has no contacts` }\n },\n async lookup(hints: EntityHint[]) {\n const contacts = loadContacts(path)\n if (contacts.length === 0) return []\n\n const index = new Map<string, ContactRecord>()\n for (const c of contacts) for (const n of namesOf(c)) if (n) index.set(n, c)\n\n const out: FactRecord[] = []\n const seen = new Set<ContactRecord>()\n for (const h of hints) {\n const c = index.get(norm(h.name))\n if (!c || seen.has(c)) continue\n seen.add(c)\n const fields = factsFrom(c)\n if (Object.keys(fields).length === 0) continue\n out.push({\n name: c.name ?? h.name,\n source: \"contacts\",\n fields,\n // Matched on an alias rather than the registry's own name.\n fuzzy: norm(c.name ?? \"\") !== norm(h.name),\n })\n }\n return out\n },\n }\n}\n","import { execFile } from \"child_process\"\n\n/**\n * execFile, not exec — an entity name is untrusted input that reaches\n * this from chat messages and GitLab issue titles. Through a shell,\n * a contact called `; rm -rf ~` is a command. execFile passes argv\n * directly and never opens one.\n */\nexport function run(\n cmd: string,\n args: string[],\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n execFile(\n cmd,\n args,\n {\n timeout: opts.timeoutMs ?? 15_000,\n signal: opts.signal,\n maxBuffer: 4 * 1024 * 1024,\n // The daemon's PATH is not a login shell's. wacli and gog live in\n // Homebrew, and ~/.local/bin is where the fleet's own tools land.\n env: {\n ...process.env,\n PATH: [\n process.env.PATH ?? \"\",\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n `${process.env.HOME ?? \"\"}/.local/bin`,\n ].filter(Boolean).join(\":\"),\n },\n },\n (err, stdout, stderr) => {\n const code = err && typeof (err as { code?: unknown }).code === \"number\"\n ? ((err as { code: number }).code)\n : err ? 1 : 0\n resolve({ stdout: String(stdout ?? \"\"), stderr: String(stderr ?? \"\"), code })\n },\n )\n })\n}\n\nexport async function binaryExists(cmd: string): Promise<boolean> {\n const { code } = await run(\"command\", [\"-v\", cmd], { timeoutMs: 3000 }).catch(() => ({ code: 1 }) as never)\n if (code === 0) return true\n // `command` is a shell builtin, so the above fails on most systems.\n const { code: which } = await run(\"/usr/bin/which\", [cmd], { timeoutMs: 3000 })\n return which === 0\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Phone numbers, from the WhatsApp contact store.\n//\n// This is the source that closes the gap the grader found. It also\n// answers country for free: a JID is an E.164 number, so the dialling\n// prefix identifies the country without a second lookup.\n\nconst CC: Array<[string, string]> = [\n [\"216\", \"Tunisia\"], [\"966\", \"Saudi Arabia\"], [\"971\", \"UAE\"], [\"974\", \"Qatar\"],\n [\"965\", \"Kuwait\"], [\"973\", \"Bahrain\"], [\"968\", \"Oman\"], [\"962\", \"Jordan\"],\n [\"961\", \"Lebanon\"], [\"212\", \"Morocco\"], [\"213\", \"Algeria\"], [\"218\", \"Libya\"],\n [\"249\", \"Sudan\"], [\"20\", \"Egypt\"], [\"90\", \"Turkey\"], [\"33\", \"France\"],\n [\"49\", \"Germany\"], [\"39\", \"Italy\"], [\"34\", \"Spain\"], [\"44\", \"United Kingdom\"],\n [\"31\", \"Netherlands\"], [\"32\", \"Belgium\"], [\"41\", \"Switzerland\"], [\"1\", \"US/Canada\"],\n]\n\n/** Longest prefix wins, or \"1\" would claim every +1xx number. */\nexport function countryFromPhone(phone: string): string | undefined {\n const d = phone.replace(/\\D/g, \"\")\n let best: string | undefined\n let bestLen = 0\n for (const [code, name] of CC) {\n if (d.startsWith(code) && code.length > bestLen) { best = name; bestLen = code.length }\n }\n return best\n}\n\n/**\n * `wacli contacts search` prints a fixed-width table, not JSON:\n *\n * ALIAS NAME PHONE JID\n * Sample Person <e164> <e164>@s.whatsapp.net\n *\n * Parsed from the right, because ALIAS is frequently empty and NAME\n * contains spaces — splitting from the left mis-assigns both.\n */\nexport function parseContactsTable(stdout: string): FactRecord[] {\n const out: FactRecord[] = []\n for (const line of stdout.split(\"\\n\")) {\n const t = line.trim()\n if (!t || t.startsWith(\"ALIAS\")) continue\n const cols = t.split(/\\s{2,}/).filter(Boolean)\n if (cols.length < 2) continue\n const jid = cols[cols.length - 1]\n if (!jid.includes(\"@\")) continue\n const phone = cols[cols.length - 2]\n const name = cols.length >= 3 ? cols[cols.length - 3] : \"\"\n if (!name || !/\\d/.test(phone)) continue\n const country = countryFromPhone(phone)\n out.push({\n name,\n source: \"wacli\",\n fields: {\n phone: `+${phone.replace(/\\D/g, \"\")}`,\n whatsapp: jid,\n ...(country ? { country } : {}),\n },\n })\n }\n return out\n}\n\nexport function createWacliSource(): FactSource {\n return {\n name: \"wacli\",\n provides: [\"contact value\", \"country\"],\n async available() {\n if (!(await binaryExists(\"wacli\"))) {\n return { kind: \"not-installed\", hint: \"brew install wacli — see https://wacli.sh\" }\n }\n // Installed but never authenticated returns an empty store for\n // every query, which looks identical to \"this person is not a\n // contact\" and would quietly teach us the corpus has no numbers.\n const { stdout, stderr, code } = await run(\"wacli\", [\"contacts\", \"search\", \"__agentx_probe__\"], { timeoutMs: 10_000 })\n if (code !== 0 && /auth|not logged in|no session|login/i.test(stdout + stderr)) {\n return { kind: \"not-configured\", hint: \"wacli auth — scan the QR to link the account\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n // Search the surname alone when the full name misses; the\n // contact store often holds a shorter form than the wiki does.\n for (const q of queriesFor(h.name)) {\n const { stdout, code } = await run(\"wacli\", [\"contacts\", \"search\", q], { signal, timeoutMs: 15_000 })\n if (code !== 0) continue\n const hit = parseContactsTable(stdout).filter((r) => plausible(r.name, h.name))\n if (hit.length === 0) continue\n for (const r of hit) {\n const key = r.fields.whatsapp\n if (seen.has(key)) continue\n seen.add(key)\n records.push({ ...r, fuzzy: !sameName(r.name, h.name) })\n }\n break\n }\n }\n return records\n },\n }\n}\n\nconst norm = (s: string) => s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\nconst sameName = (a: string, b: string) => norm(a) === norm(b)\n\nfunction queriesFor(name: string): string[] {\n const parts = norm(name).split(/\\s+/).filter((p) => p.length > 2)\n return parts.length > 1 ? [name, parts[parts.length - 1]] : [name]\n}\n\n/**\n * A surname search returns everyone who shares it. Requiring every token\n * of the shorter name to appear in the longer one keeps a two-word wiki\n * name matching a contact stored under just the first name, while\n * rejecting an unrelated person who shares the surname.\n */\nexport function plausible(candidate: string, wanted: string): boolean {\n const a = norm(candidate).split(/\\s+/).filter(Boolean)\n const b = norm(wanted).split(/\\s+/).filter(Boolean)\n if (a.length === 0 || b.length === 0) return false\n const [short, long] = a.length <= b.length ? [a, b] : [b, a]\n return short.every((t) => long.includes(t))\n}\n","import type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Emails, handles and profile URLs, from the GitLab instance.\n//\n// Where most of a fleet's entries arrive through GitLab, this is the\n// system that knows who the people in them are. The user search returns\n// `organization` and `job_title` too, but both are optional and often\n// blank — the source reports what it has and stays quiet about the\n// rest, so a blank job title never reaches the prompt as a fact.\n//\n// Host and token come from the environment. There is no default host:\n// guessing one would send entity names from a private corpus to\n// whatever answers at that address.\n\nexport interface GitlabSourceOptions {\n baseUrl?: string\n token?: string\n}\n\ninterface GitlabUser {\n username?: string\n name?: string\n email?: string\n public_email?: string\n organization?: string\n job_title?: string\n web_url?: string\n state?: string\n}\n\nexport function createGitlabSource(opts: GitlabSourceOptions = {}): FactSource {\n const baseUrl = (opts.baseUrl ?? process.env.GITLAB_URL ?? \"\").replace(/\\/+$/, \"\")\n const token = opts.token ?? process.env.GITLAB_ADMIN_TOKEN ?? process.env.GITLAB_TOKEN\n\n return {\n name: \"gitlab\",\n provides: [\"email\", \"handle\", \"profile URL\"],\n async available() {\n if (!baseUrl) {\n return { kind: \"not-configured\", hint: \"export GITLAB_URL=https://<your-gitlab-host>\" }\n }\n if (!token) {\n return { kind: \"not-configured\", hint: \"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)\" }\n }\n // A present-but-rejected token is the dangerous case: every lookup\n // returns nothing, which is indistinguishable from \"this person is\n // not in GitLab\", and the corpus quietly grows a hole while the\n // source reports itself healthy. One authenticated call turns that\n // into a prompt.\n try {\n const res = await fetch(`${baseUrl}/api/v4/user`, { headers: { \"PRIVATE-TOKEN\": token } })\n if (res.status === 401 || res.status === 403) {\n return { kind: \"not-configured\", hint: `GitLab rejected the token (${res.status}) — set a valid GITLAB_ADMIN_TOKEN` }\n }\n if (!res.ok) {\n return { kind: \"failed\", hint: `GitLab returned ${res.status} for the auth probe` }\n }\n } catch (err) {\n return { kind: \"failed\", hint: `cannot reach ${baseUrl}: ${String((err as Error)?.message ?? err)}` }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n if (!token || !baseUrl) return []\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n const url = `${baseUrl}/api/v4/users?search=${encodeURIComponent(h.name)}&per_page=5`\n let users: GitlabUser[]\n try {\n const res = await fetch(url, { headers: { \"PRIVATE-TOKEN\": token }, signal })\n if (!res.ok) continue\n users = (await res.json()) as GitlabUser[]\n } catch {\n continue\n }\n if (!Array.isArray(users)) continue\n for (const u of users) {\n const key = u.username ?? u.web_url ?? \"\"\n if (!key || seen.has(key)) continue\n seen.add(key)\n const fields: Record<string, string> = {}\n const email = u.email || u.public_email\n if (email) fields.email = email\n if (u.username) fields.gitlab = `@${u.username}`\n if (u.web_url) fields.profile = u.web_url\n // Blank strings are the instance's default, not a stated fact.\n if (u.organization) fields.organisation = u.organization\n if (u.job_title) fields.role = u.job_title\n if (u.state && u.state !== \"active\") fields.accountState = u.state\n if (Object.keys(fields).length === 0) continue\n records.push({\n name: u.name ?? h.name,\n source: \"gitlab\",\n fields,\n fuzzy: (u.name ?? \"\").toLowerCase() !== h.name.toLowerCase(),\n })\n }\n }\n return records\n },\n }\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Contact cards, from Google Contacts via `gog`.\n//\n// On this install the People API is not enabled on the OAuth project and\n// every call returns 403 accessNotConfigured. That is the normal case\n// for a source, not an exception: `available()` reports false, the\n// resolver drops it, and the absorb runs with one fewer input. Enabling\n// the API turns it on with no code change.\n\ninterface GogContact {\n names?: Array<{ displayName?: string }>\n emailAddresses?: Array<{ value?: string }>\n phoneNumbers?: Array<{ value?: string }>\n organizations?: Array<{ name?: string; title?: string }>\n addresses?: Array<{ formattedValue?: string; country?: string }>\n}\n\nexport function createGogSource(): FactSource {\n return {\n name: \"gog\",\n provides: [\"contact value\", \"email\", \"organisation\", \"role\", \"country\"],\n async available() {\n if (!(await binaryExists(\"gog\"))) {\n return { kind: \"not-installed\", hint: \"brew install gog — Google CLI\" }\n }\n // A 403 for a disabled API is reported on stdout with exit 0, so\n // the exit code alone would call this source healthy. The probe\n // takes no flags beyond -j: an unknown flag makes gog print a\n // usage error instead of calling the API, and the probe then\n // passes while every real lookup fails.\n const { stdout, stderr } = await run(\"gog\", [\"contacts\", \"list\", \"-j\"], { timeoutMs: 20_000 })\n const out = stdout + stderr\n if (/unknown flag|Run with --help/i.test(out)) {\n return { kind: \"failed\", hint: `gog rejected the probe: ${out.split(\"\\n\")[0]}` }\n }\n if (/accessNotConfigured|has not been used in project/i.test(out)) {\n return {\n kind: \"not-configured\",\n hint: \"enable the People API on the gog OAuth project, then retry (console.developers.google.com → APIs → People API)\",\n }\n }\n if (/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(out)) {\n return { kind: \"not-configured\", hint: \"gog auth login — the stored token is expired or lacks contacts scope\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n for (const h of hints) {\n const { stdout, code } = await run(\"gog\", [\"contacts\", \"search\", h.name, \"-j\", \"--results-only\"], { signal, timeoutMs: 20_000 })\n if (code !== 0) continue\n let parsed: unknown\n try { parsed = JSON.parse(stdout) } catch { continue }\n const list: GogContact[] = Array.isArray(parsed)\n ? (parsed as GogContact[])\n : ((parsed as { results?: unknown[]; people?: unknown[] })?.results as GogContact[])\n ?? ((parsed as { people?: unknown[] })?.people as GogContact[])\n ?? []\n for (const c of list) {\n const fields: Record<string, string> = {}\n const phone = c.phoneNumbers?.[0]?.value\n const email = c.emailAddresses?.[0]?.value\n const org = c.organizations?.[0]\n if (phone) fields.phone = phone\n if (email) fields.email = email\n if (org?.name) fields.organisation = org.name\n if (org?.title) fields.role = org.title\n const country = c.addresses?.[0]?.country\n if (country) fields.country = country\n if (Object.keys(fields).length === 0) continue\n records.push({ name: c.names?.[0]?.displayName ?? h.name, source: \"gog\", fields })\n }\n }\n return records\n },\n }\n}\n","import type { FactRecord } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\nimport { isAgentSender } from \"@/a2a/initiator\"\n\n// Identifiers the entries already carry.\n//\n// Every other source in this directory asks an outside system who\n// someone is. This one asks the batch, because since senders are\n// stamped at capture the platform's own identifier travels with the\n// message: a WhatsApp JID is the number, a GitLab sender is the handle.\n//\n// That makes it the best source available, not a fallback. It needs no\n// tool installed, no token, and no network — it works on a server with\n// none of the CLIs — and it cannot mismatch, because there is no name\n// resolution step to get wrong. `wacli` answers \"who is called Alex\n// Rivera\"; this answers \"who sent this message\", and only the second\n// question has one right answer.\n\nexport interface SenderStampedEntry {\n source?: string\n meta?: Record<string, unknown> | undefined\n}\n\nconst str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.trim() ? v.trim() : undefined\n\n/** \"whatsapp@peer-server\" and \"gitlab\" both normalise to their platform. */\nexport function platformOf(source?: string): string {\n return String(source ?? \"\").split(\"@\")[0].split(\":\")[0].toLowerCase()\n}\n\n/**\n * Turn stamped sender metadata into fact records.\n *\n * Deliberately conservative about what counts as a contact value. A\n * Telegram numeric user id identifies an account but cannot be dialled,\n * messaged by a human, or pasted anywhere useful, so it is recorded as\n * an account id and never as a way to reach someone — writing it into\n * an article's contact line would satisfy the grader while helping\n * nobody, which is the exact failure this whole layer exists to undo.\n */\nexport function recordsFromEntries(entries: SenderStampedEntry[]): FactRecord[] {\n const byName = new Map<string, FactRecord>()\n\n for (const e of entries) {\n const name = str(e.meta?.sender)\n if (!name) continue\n // An agent's post (\"agent:<id>\", even one made with a person's forge\n // account) says nothing about how to reach a person.\n if (isAgentSender(name)) continue\n const id = str(e.meta?.senderId)\n const username = str(e.meta?.senderUsername)\n const platform = platformOf(e.source)\n\n const fields: Record<string, string> = {}\n\n if (id && /@s\\.whatsapp\\.net$/.test(id)) {\n const digits = id.split(\"@\")[0].replace(/\\D/g, \"\")\n if (digits) {\n fields.phone = `+${digits}`\n fields.whatsapp = id\n const country = countryFromPhone(digits)\n if (country) fields.country = country\n }\n } else if (platform === \"whatsapp\" && id && /^\\d{6,}$/.test(id)) {\n fields.phone = `+${id}`\n fields.whatsapp = `${id}@s.whatsapp.net`\n const country = countryFromPhone(id)\n if (country) fields.country = country\n }\n\n if (username) {\n const handle = username.startsWith(\"@\") ? username : `@${username}`\n if (platform === \"gitlab\") fields.gitlab = handle\n else if (platform === \"github\") fields.github = handle\n else if (platform === \"telegram\") fields.telegram = handle\n else fields.handle = handle\n }\n\n // An account id is provenance, not a contact value.\n if (id && !fields.phone && !username) fields[`${platform || \"platform\"}Id`] = id\n\n if (Object.keys(fields).length === 0) continue\n\n const key = name.toLowerCase()\n const existing = byName.get(key)\n if (!existing) {\n byName.set(key, { name, source: \"entries\", fields })\n continue\n }\n // Same person across several entries — union the identifiers rather\n // than letting the last message win.\n for (const [k, v] of Object.entries(fields)) existing.fields[k] ??= v\n }\n\n return Array.from(byName.values())\n}\n","import { createContactsSource } from \"./sources/contacts\"\nimport { createGitlabSource } from \"./sources/gitlab\"\nimport { createGogSource } from \"./sources/gog\"\nimport { createWacliSource } from \"./sources/wacli\"\nimport type { EntityHint, FactRecord, FactSource, FactSourceResult, Unavailable } from \"./types\"\n\nexport * from \"./types\"\nexport { countryFromPhone, parseContactsTable, plausible } from \"./sources/wacli\"\nexport { createGitlabSource } from \"./sources/gitlab\"\nexport { createGogSource } from \"./sources/gog\"\nexport { createWacliSource } from \"./sources/wacli\"\nexport { platformOf, recordsFromEntries } from \"./sources/entries\"\nexport { createContactsSource, factsFrom, loadContacts, namesOf } from \"./sources/contacts\"\nexport type { ContactRecord } from \"./sources/contacts\"\nexport type { SenderStampedEntry } from \"./sources/entries\"\n\nexport interface ResolveOptions {\n sources?: FactSource[]\n /** Whole-resolve budget. A slow address book must not stall an absorb. */\n timeoutMs?: number\n /** Cap on entities looked up per batch — each one is N network calls. */\n maxEntities?: number\n onResult?: (r: FactSourceResult) => void\n}\n\n/**\n * Probe each source once per process, not once per lookup.\n *\n * Availability does not change mid-run, but the probes are real work —\n * gog's costs about 1.4s because it has to make an API call to\n * distinguish \"installed\" from \"installed but the API is disabled\".\n * Backfilling 50 articles re-ran every probe 50 times and spent longer\n * asking whether the sources worked than using them.\n *\n * The promise is cached, not the result, so concurrent callers share one\n * probe rather than racing.\n */\nexport function memoizeAvailability(source: FactSource): FactSource {\n let probe: Promise<Unavailable | null> | undefined\n return {\n ...source,\n available: () => (probe ??= source.available()),\n lookup: (hints, signal) => source.lookup(hints, signal),\n }\n}\n\n/**\n * Ordered by authority, because mergeRecords lets the first source to\n * state a field win.\n *\n * The hand-maintained registry comes first: it is the only source where\n * a person decided that a name, its aliases and a set of handles all\n * refer to one human. Directories only know their own corner, and they\n * cannot resolve an alias at all.\n */\nexport function defaultSources(): FactSource[] {\n return [\n createContactsSource(),\n createWacliSource(),\n createGitlabSource(),\n createGogSource(),\n ].map(memoizeAvailability)\n}\n\n/**\n * Names worth a lookup, taken from the batch.\n *\n * Only entities the batch already mentions are ever queried. That is a\n * deliberate limit and not just an efficiency one: exporting the address\n * book into a prompt would put identifiers for people who have nothing\n * to do with the work into a model's context. A lookup is justified by\n * the entry that names the person.\n */\nexport function extractHints(\n entries: Array<{ context?: string; content?: string; sender?: string }>,\n opts: { max?: number; known?: string[] } = {},\n): EntityHint[] {\n const max = opts.max ?? 25\n const byName = new Map<string, EntityHint>()\n\n // The stamped sender first: it is the platform's own record of who\n // spoke, so it beats both a heuristic over `context` and a substring\n // scan of the body. Entries captured before senders were recorded\n // simply have none, and fall through to the other two.\n for (const e of entries) {\n const s = (e.sender ?? \"\").trim()\n if (s && isPersonName(s)) byName.set(s.toLowerCase(), { name: s, origin: \"sender\", type: \"person\" })\n }\n\n for (const e of entries) {\n const ctx = (e.context ?? \"\").trim()\n if (!isPersonName(ctx)) continue\n const key = ctx.toLowerCase()\n if (byName.has(key)) continue\n byName.set(key, { name: ctx, origin: \"context\" })\n }\n\n // `context` only names a person for one-to-one channels. On a GitLab\n // entry it is the issue title, and in a group chat it is the group —\n // so the people who talk in groups, which is most of them, were never\n // looked up at all. The first article written with this layer live\n // said \"Contact identifiers: unknown … no number is recorded\" about\n // someone the contact store knew perfectly well.\n //\n // The bodies do name them, but harvesting capitalised word pairs out\n // of free text would spend lookups on noise and, worse, resolve\n // strangers. So the corpus is its own dictionary: a name is a hint\n // only if the wiki already has a person article for it. That is\n // precise by construction, and it targets exactly the articles a\n // second pass is going to rewrite.\n const known = (opts.known ?? []).filter((n) => n.trim().length > 2)\n if (known.length > 0) {\n const haystack = entries.map((e) => e.content ?? \"\").join(\"\\n\").toLowerCase()\n for (const name of known) {\n const key = name.toLowerCase().trim()\n if (byName.has(key)) continue\n if (haystack.includes(key)) byName.set(key, { name, origin: \"body\", type: \"person\" })\n }\n }\n\n return Array.from(byName.values()).slice(0, max)\n}\n\nconst NOT_A_PERSON = new Set([\n \"me\", \"user\", \"system\", \"cron\", \"unknown\", \"anonymous\", \"bot\", \"agent\",\n \"self\", \"test\", \"admin\", \"none\", \"null\", \"n/a\",\n])\n\n/**\n * Words that make a capitalised phrase a collection rather than a person.\n *\n * A group chat's `context` is its name, and plenty of group names are\n * shaped exactly like a person's — \"Team Group\", \"Acme Family\". Shape\n * alone cannot separate them, and treating one as a person spends a\n * lookup and risks matching a real contact with a similar name.\n */\nconst COLLECTION_NOUNS = new Set([\n \"group\", \"team\", \"chat\", \"channel\", \"squad\", \"crew\", \"room\", \"family\",\n \"project\", \"board\", \"committee\", \"club\", \"staff\", \"office\", \"dept\",\n \"department\", \"support\", \"sales\", \"ops\", \"admins\", \"everyone\", \"all\",\n])\n\n/**\n * Two to four capitalised words, no digits, not a known placeholder.\n *\n * `context` holds a person's name for chat sources and an issue title\n * for GitLab ones, and issue titles are long and full of punctuation.\n * The bar is deliberately high: a false positive costs a wasted lookup\n * and, worse, risks putting an unrelated person's identifiers into the\n * prompt, so a missed name is the cheaper error.\n */\nexport function isPersonName(s: string): boolean {\n const t = s.trim()\n if (!t || t.length > 48) return false\n if (NOT_A_PERSON.has(t.toLowerCase())) return false\n if (/[\\d@/\\\\#:|_]/.test(t)) return false\n const words = t.split(/\\s+/)\n if (words.length < 2 || words.length > 4) return false\n if (words.some((w) => COLLECTION_NOUNS.has(w.toLowerCase()))) return false\n return words.every((w) => /^[\\p{Lu}][\\p{L}'’.-]*$/u.test(w))\n}\n\nexport async function resolveFacts(\n hints: EntityHint[],\n opts: ResolveOptions = {},\n): Promise<{ records: FactRecord[]; results: FactSourceResult[] }> {\n const sources = opts.sources ?? defaultSources()\n const picked = hints.slice(0, opts.maxEntities ?? 25)\n if (picked.length === 0) return { records: [], results: [] }\n\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 120_000)\n try {\n const results = await Promise.all(sources.map(async (s): Promise<FactSourceResult> => {\n const t0 = Date.now()\n try {\n const why = await s.available()\n if (why) return { source: s.name, records: [], unavailable: why, ms: Date.now() - t0 }\n const records = await s.lookup(picked, ac.signal)\n return { source: s.name, records, ms: Date.now() - t0 }\n } catch (err) {\n // A source that throws contributes nothing and blocks nothing.\n return {\n source: s.name,\n records: [],\n unavailable: { kind: \"failed\", hint: String((err as Error)?.message ?? err) },\n ms: Date.now() - t0,\n }\n }\n }))\n for (const r of results) opts.onResult?.(r)\n return { records: results.flatMap((r) => r.records), results }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * What to tell the operator about the sources that did not answer.\n *\n * A source silently contributing nothing is the worst outcome: the\n * corpus quietly develops a hole shaped like the missing tool, and the\n * grader reports the resulting gaps as though the fact did not exist\n * anywhere. Installing `wacli` is a one-line fix that nobody makes if\n * nobody is told. `failed` is left out — a transient error is noise, not\n * a task.\n */\nexport function installPrompts(\n results: FactSourceResult[],\n sources: FactSource[] = defaultSources(),\n): Array<{ source: string; kind: string; hint: string; provides: string[] }> {\n const provides = new Map(sources.map((s) => [s.name, s.provides]))\n return results\n .filter((r) => r.unavailable && r.unavailable.kind !== \"failed\")\n .map((r) => ({\n source: r.source,\n kind: r.unavailable!.kind,\n hint: r.unavailable!.hint,\n provides: provides.get(r.source) ?? [],\n }))\n}\n\nexport interface MergedEntity {\n name: string\n /** field → value, with the source that supplied it. */\n fields: Record<string, { value: string; source: string }>\n}\n\n/**\n * Merge per entity, first source to state a field wins.\n *\n * Order is the source order, which puts WhatsApp's number ahead of\n * Google's. That is intentional rather than arbitrary: the WhatsApp\n * number is the one the agent will actually message on, so where the two\n * disagree the messaging channel's own record is the operative fact.\n * Conflicts are kept and rendered, never silently resolved.\n */\nexport function mergeRecords(records: FactRecord[]): MergedEntity[] {\n const out = new Map<string, MergedEntity>()\n for (const r of records) {\n const key = r.name.toLowerCase().trim()\n let e = out.get(key)\n if (!e) { e = { name: r.name, fields: {} }; out.set(key, e) }\n for (const [k, v] of Object.entries(r.fields)) {\n if (!v?.trim()) continue\n const existing = e.fields[k]\n if (!existing) { e.fields[k] = { value: v, source: r.source }; continue }\n if (existing.value !== v) {\n // Two systems of record disagree. The writer should see both.\n e.fields[`${k} (${r.source})`] ??= { value: v, source: r.source }\n }\n }\n }\n return Array.from(out.values())\n}\n\n/**\n * The prompt block.\n *\n * Phrased as an instruction to copy rather than as context to consider.\n * Absorb's whole disposition is to summarise, and an identifier\n * summarised is an identifier lost — which is the failure this exists\n * to fix.\n */\nexport function renderFactsBlock(entities: MergedEntity[]): string {\n if (entities.length === 0) return \"\"\n const lines = entities\n .filter((e) => Object.keys(e.fields).length > 0)\n .map((e) => {\n const fields = Object.entries(e.fields)\n .map(([k, v]) => ` - ${k}: \\`${v.value}\\` _(${v.source})_`)\n .join(\"\\n\")\n return `- **${e.name}**\\n${fields}`\n })\n if (lines.length === 0) return \"\"\n return `\n## Verified facts\n\nThese were read from systems of record — WhatsApp, GitLab, Google, the\nERP — not from the entries. They are more reliable than anything the\nconversation implies, and they are the identity fields articles are\ngraded on.\n\nCopy every value that belongs to an article you write, **verbatim**, into\nits Identity section. Do not paraphrase an identifier, reformat it, or\nreplace it with the name of the channel it belongs to. Where a fact here\ncontradicts the entries, this wins and the entry is stale.\n\n${lines.join(\"\\n\")}\n`\n}\n"],"mappings":"oEAAA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,KACzC,OAAS,WAAAC,MAAe,OCDxB,OAAS,YAAAC,MAAgB,gBAQlB,SAASC,EACdC,EACAC,EACAC,EAAqD,CAAC,EACK,CAC3D,OAAO,IAAI,QAASC,GAAY,CAC9BL,EACEE,EACAC,EACA,CACE,QAASC,EAAK,WAAa,KAC3B,OAAQA,EAAK,OACb,UAAW,EAAI,KAAO,KAGtB,IAAK,CACH,GAAG,QAAQ,IACX,KAAM,CACJ,QAAQ,IAAI,MAAQ,GACpB,oBACA,iBACA,GAAG,QAAQ,IAAI,MAAQ,eACzB,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,CAC5B,CACF,EACA,CAACE,EAAKC,EAAQC,IAAW,CACvB,IAAMC,EAAOH,GAAO,OAAQA,EAA2B,MAAS,SAC1DA,EAAyB,KAC3BA,EAAM,EAAI,EACdD,EAAQ,CAAE,OAAQ,OAAOE,GAAU,EAAE,EAAG,OAAQ,OAAOC,GAAU,EAAE,EAAG,KAAAC,CAAK,CAAC,CAC9E,CACF,CACF,CAAC,CACH,CAEA,eAAsBC,EAAaR,EAA+B,CAChE,GAAM,CAAE,KAAAO,CAAK,EAAI,MA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AAM,EAAE,OAAS,CAAC,EAC9C,IAAKA,GAAM,CACV,IAAMkC,EAAS,OAAO,QAAQlC,EAAE,MAAM,EACnC,IAAI,CAAC,CAAC4B,EAAGC,CAAC,IAAM,OAAOD,QAAQC,EAAE,aAAaA,EAAE,UAAU,EAC1D,KAAK;AAAA,CAAI,EACZ,MAAO,OAAO7B,EAAE;AAAA,EAAWkC,GAC7B,CAAC,EACH,OAAID,EAAM,SAAW,EAAU,GACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaPA,EAAM,KAAK;AAAA,CAAI;AAAA,CAEjB","names":["existsSync","readFileSync","resolve","execFile","run","cmd","args","opts","resolve","err","stdout","stderr","code","binaryExists","which","CC","countryFromPhone","phone","d","best","bestLen","code","name","parseContactsTable","stdout","out","line","t","cols","jid","country","createWacliSource","binaryExists","stderr","run","hints","signal","records","seen","h","q","queriesFor","hit","r","plausible","key","sameName","norm","s","a","b","parts","p","candidate","wanted","short","long","CHANNEL_FIELDS","contactsPath","agentxDir","resolve","loadContacts","path","existsSync","parsed","readFileSync","norm","s","namesOf","c","x","factsFrom","fields","key","raw","value","field","digits","country","countryFromPhone","createContactsSource","opts","hints","contacts","index","n","out","seen","h","createGitlabSource","opts","baseUrl","token","res","err","hints","signal","records","seen","h","url","users","u","key","fields","email","createGogSource","binaryExists","stdout","stderr","run","out","hints","signal","records","h","code","parsed","list","c","fields","phone","email","org","country","str","v","platformOf","source","recordsFromEntries","entries","byName","e","name","isAgentSender","id","username","platform","fields","digits","country","countryFromPhone","handle","key","existing","k","memoizeAvailability","source","probe","hints","signal","defaultSources","createContactsSource","createWacliSource","createGitlabSource","createGogSource","extractHints","entries","opts","max","byName","e","s","isPersonName","ctx","key","known","n","haystack","name","NOT_A_PERSON","COLLECTION_NOUNS","words","w","resolveFacts","sources","picked","ac","timer","results","t0","why","records","err","r","installPrompts","provides","mergeRecords","out","k","v","existing","renderFactsBlock","entities","lines","fields"]}