@a-company/paradigm 7.0.0 → 7.2.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 (145) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-XW44LF5Y.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/ambient-OW5M5LVN.js +2 -0
  5. package/dist/{ambient-OX7YJ4PJ.js → ambient-TFLZFV5Y.js} +1 -1
  6. package/dist/ambient-VCTUHHIG.js +2 -0
  7. package/dist/arch-loader-YVOS3QRY.js +2 -0
  8. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  9. package/dist/calibrate-PHVP7RPH.js +4 -0
  10. package/dist/captain-CAXGHC2V.js +2 -0
  11. package/dist/captain-CWCLFOXV.js +2 -0
  12. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  13. package/dist/chunk-2KK4JQ55.js +17 -0
  14. package/dist/chunk-3I3TITBA.js +25 -0
  15. package/dist/chunk-3YM5ABNX.js +2 -0
  16. package/dist/{chunk-47YPID6H.js → chunk-6HYRS3PH.js} +21 -21
  17. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  18. package/dist/chunk-727PXENG.js +2 -0
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  21. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  22. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  23. package/dist/chunk-ECO3LHCE.js +2 -0
  24. package/dist/chunk-FG3M6VVO.js +30 -0
  25. package/dist/chunk-FNYYQNJY.js +2 -0
  26. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  27. package/dist/chunk-K6TLYNRQ.js +7 -0
  28. package/dist/chunk-K7KT6FL3.js +25 -0
  29. package/dist/chunk-KAUGQMXU.js +4 -0
  30. package/dist/chunk-M7JHVVDW.js +6 -0
  31. package/dist/chunk-NFN5UUJB.js +2 -0
  32. package/dist/chunk-NRP2KJ6I.js +33 -0
  33. package/dist/{chunk-WROJSWAO.js → chunk-QPQBXRXX.js} +1 -1
  34. package/dist/chunk-RVXQNS6K.js +30 -0
  35. package/dist/chunk-RZRFYGND.js +504 -0
  36. package/dist/chunk-UNSI6DVD.js +93 -0
  37. package/dist/{chunk-JCGCPAHF.js → chunk-USYV5QYU.js} +1 -1
  38. package/dist/chunk-VOPJ47QY.js +2 -0
  39. package/dist/{chunk-QBIQ2FYB.js → chunk-W3VWORQZ.js} +1 -1
  40. package/dist/chunk-WMTES556.js +2 -0
  41. package/dist/chunk-XBK244QR.js +6 -0
  42. package/dist/chunk-XSKIXXFW.js +504 -0
  43. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  44. package/dist/chunk-YYRP7FLC.js +2 -0
  45. package/dist/{compliance-MLG4W6S4.js → compliance-3M6COUCO.js} +3 -3
  46. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  47. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  48. package/dist/{diff-MC6AXLKX.js → diff-Z2YSIRC4.js} +1 -1
  49. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  50. package/dist/{docs-3YFNNZRV.js → docs-OWJ7EPD7.js} +1 -1
  51. package/dist/github-4X4MYINS.js +4 -0
  52. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  53. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  54. package/dist/index.js +9 -9
  55. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  56. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  57. package/dist/journal-loader-CNNA4EAU.js +2 -0
  58. package/dist/lint-Y4P3MHBV.js +26 -0
  59. package/dist/list-5XRLWD7K.js +12 -0
  60. package/dist/mcp.js +1 -1
  61. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  62. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-EFXDEPZN.js} +1 -1
  63. package/dist/nomination-engine-YRHZZZUN.js +2 -0
  64. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  65. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-C5NM5MFN.js} +1 -1
  66. package/dist/orchestration-EVWQWTOV.js +2 -0
  67. package/dist/orchestration-UP3KFUJT.js +2 -0
  68. package/dist/{platform-server-WIBVYHIV.js → platform-server-FXF3XFHM.js} +1 -1
  69. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  70. package/dist/quiz-QKIKAVL7.js +10 -0
  71. package/dist/registry-NEW4OJ44.js +2 -0
  72. package/dist/reindex-QZYOD5K4.js +2 -0
  73. package/dist/{reindex-XTRF23F7.js → reindex-W67B2LQP.js} +1 -1
  74. package/dist/remember-KZYAY77S.js +14 -0
  75. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  76. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  77. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  78. package/dist/{serve-SMGWGJLM.js → serve-ZT2Z54NK.js} +1 -1
  79. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  80. package/dist/{shift-JBCEDCGA.js → shift-UDKXCIW7.js} +3 -3
  81. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  82. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  83. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  84. package/dist/status-45KIG32R.js +6 -0
  85. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  86. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  87. package/dist/symphony-KQJ6HIXB.js +53 -0
  88. package/dist/symphony-VDNDFK7H.js +2 -0
  89. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  90. package/dist/task-KFND4HLF.js +3 -0
  91. package/dist/task-loader-HBZ3KRH2.js +2 -0
  92. package/dist/task-loader-IO4UVFUD.js +2 -0
  93. package/dist/task-settlement-NF7PFSNE.js +3 -0
  94. package/dist/task-settlement-TATNPY6L.js +3 -0
  95. package/dist/team-6WNNLBAO.js +2 -0
  96. package/dist/thread-2A7QKU72.js +41 -0
  97. package/dist/tools-GDWT74O6.js +2 -0
  98. package/dist/tools-SDWAFQMQ.js +142 -0
  99. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  100. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  101. package/dist/university-ui/index.html +1 -1
  102. package/dist/validate-OZTX3FYX.js +13 -0
  103. package/dist/validate-RIMSY3RP.js +9 -0
  104. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  105. package/package.json +1 -1
  106. package/dist/add-V6XR7DU5.js +0 -12
  107. package/dist/agent-loader-VGBPL3TH.js +0 -2
  108. package/dist/ambient-7HBJHJL2.js +0 -2
  109. package/dist/ambient-SST5CLEC.js +0 -35
  110. package/dist/captain-YUP3KVCA.js +0 -2
  111. package/dist/chunk-3MZ4J2LF.js +0 -2
  112. package/dist/chunk-6AKNXD22.js +0 -32
  113. package/dist/chunk-7SWEOPWF.js +0 -2
  114. package/dist/chunk-CVPKQ3JH.js +0 -8
  115. package/dist/chunk-EKNLG73M.js +0 -6
  116. package/dist/chunk-FRQRREJ6.js +0 -29
  117. package/dist/chunk-GD4F2HC6.js +0 -3
  118. package/dist/chunk-JIXHEBGK.js +0 -7
  119. package/dist/chunk-K54L6CFR.js +0 -25
  120. package/dist/chunk-MBPLJKE5.js +0 -3
  121. package/dist/chunk-QEQCPVF5.js +0 -4
  122. package/dist/chunk-QGZRM6ZB.js +0 -2
  123. package/dist/chunk-QO7YPQXC.js +0 -2
  124. package/dist/chunk-S4J337EQ.js +0 -504
  125. package/dist/chunk-V6MIKLMY.js +0 -18
  126. package/dist/journal-loader-GLH7XFTK.js +0 -2
  127. package/dist/lint-IGKE6UPS.js +0 -26
  128. package/dist/list-NC3QGT75.js +0 -12
  129. package/dist/lore-loader-D2ISOASW.js +0 -2
  130. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  131. package/dist/orchestration-G5MAY6IA.js +0 -2
  132. package/dist/quiz-TNV6APBM.js +0 -10
  133. package/dist/remember-MJRNTXYS.js +0 -14
  134. package/dist/session-work-log-QXPAXY5K.js +0 -2
  135. package/dist/status-ENAI35NL.js +0 -6
  136. package/dist/symphony-7INZR43F.js +0 -53
  137. package/dist/symphony-G6IENE4K.js +0 -2
  138. package/dist/symphony-relay-2RHG25Z4.js +0 -3
  139. package/dist/task-loader-IGQQ6ZFL.js +0 -2
  140. package/dist/task-settlement-NW4XMJGJ.js +0 -3
  141. package/dist/team-J2YXPEGX.js +0 -2
  142. package/dist/thread-HFXK65D4.js +0 -41
  143. package/dist/tools-HNJ7D5IO.js +0 -2
  144. package/dist/validate-IQG7DBFC.js +0 -9
  145. package/dist/validate-LSCDOLBO.js +0 -13
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import {f,a,o,z}from'./chunk-2KK4JQ55.js';import {t}from'./chunk-M7JHVVDW.js';import {a as a$2,b as b$4,c as c$1}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$5}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$4}from'./chunk-EK4ZRIFJ.js';import {a as a$1,b as b$3}from'./chunk-4TXOVRWD.js';import {H,m}from'./chunk-D6BSCELB.js';import {a as a$3,q as q$1}from'./chunk-K6TLYNRQ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as D from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as B from'os';import te from'sql.js';var At={};c(At,{contentSearch:()=>Zt,detectFileRename:()=>xt,generateFingerprint:()=>Rt,levenshteinDistance:()=>bt,levenshteinSimilarity:()=>Z,searchSiblingFiles:()=>Lt,slidingWindowSearch:()=>Y});function Rt(e){let t=e.split(`
3
+ `).filter(n=>n.trim()!=="");return {firstLine:G(t[0]||""),lastLine:G(t[t.length-1]||""),lineCount:t.length,structuralHash:_t(t)}}function _t(e){let t=e.map(n=>n.trim()).filter(n=>St.test(n)).map(n=>{let r=n.match(St);return r?r[1].trim():""}).join("|");return D.createHash("sha256").update(t).digest("hex").slice(0,16)}function G(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function bt(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let n=e.length,r=t.length;if(n>5e3||r>5e3)return Math.abs(n-r);let s=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)s[a]=a;for(let a=1;a<=r;a++){i[0]=a;for(let c=1;c<=n;c++){let o=e[c-1]===t[a-1]?0:1;i[c]=Math.min(s[c]+1,i[c-1]+1,s[c-1]+o);}[s,i]=[i,s];}return s[n]}function Z(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-bt(e,t)/n}function Y(e,t,n,r=3){let{lineCount:s}=t,i=Math.max(1,Math.floor(s*.8)),a=Math.ceil(s*1.2),c=[],o=Q(n);for(let l of [s,i,a])if(!(l>e.length))for(let u=0;u<=e.length-l;u++){let f=e.slice(u,u+l),y=Qt(f,t,o);if(y>=.5){let h=f.join(`
4
+ `);c.push({windowStart:u+1,windowEnd:u+l,similarity:Z(Q(h),o),score:y});}}let d=new Map;for(let l of c){let u=d.get(l.windowStart);(!u||l.score>u.score)&&d.set(l.windowStart,l);}return Array.from(d.values()).sort((l,u)=>u.score-l.score).slice(0,r)}function Qt(e,t,n){let r=e.filter(f=>f.trim()!=="");if(r.length===0)return 0;let s=0,i=G(r[0]),a=G(r[r.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),s+=c*qt,_t(r)===t.structuralHash&&(s+=Kt);let d=r.join(`
5
+ `),l=Z(Q(d),n);l>=.8&&(s+=(l-.8)/.2*Vt);let u=r.length/t.lineCount;if(u>=.8&&u<=1.2){let f=1-Math.abs(1-u)/.2;s+=f*Jt;}return s}function Q(e){return e.split(`
6
+ `).map(t=>t.trim()).filter(t=>t!=="").join(`
7
+ `)}function xt(e,t){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let r=n.split(`
8
+ `);for(let s of r){let i=s.split(" ");if(i.length>=3&&i[0].startsWith("R"))return i[2]}return null}catch{return null}}function Lt(e,t,n,r,s=10){let i=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(i))return [];let a=[];try{let c=S.readdirSync(i).filter(o=>!o.startsWith(".")&&S.statSync(T.join(i,o)).isFile()).slice(0,s);for(let o of c)try{let l=S.readFileSync(T.join(i,o),"utf8").split(`
9
+ `),u=Y(l,n,r,1);if(u.length>0&&u[0].score>=.7){let f=T.relative(e,T.join(i,o));a.push({file:f,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return a.sort((c,o)=>o.score-c.score)}function Zt(e,t,n,r=true){let s=Rt(n),i=T.isAbsolute(t)?t:T.join(e,t);if(S.existsSync(i)){let l=S.readFileSync(i,"utf8").split(`
10
+ `),u=Y(l,s,n);if(u.length>0){let f=u[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let a=xt(e,t);if(a){let d=T.join(e,a);if(S.existsSync(d)){let u=S.readFileSync(d,"utf8").split(`
11
+ `),f=Y(u,s,n);if(f.length>0&&f[0].score>=.7)return {found:true,score:f[0].score,suggestedStart:f[0].windowStart,suggestedEnd:f[0].windowEnd,suggestedPath:a,similarity:f[0].similarity}}}let c=T.dirname(t),o=Lt(e,c,s,n);if(o.length>0&&o[0].score>=.7){let d=o[0];return {found:true,score:d.score,suggestedStart:d.start,suggestedEnd:d.end,suggestedPath:d.file!==t?d.file:void 0,similarity:d.score}}return {found:false,score:0}}var St,qt,Kt,Vt,Jt,It=b(()=>{St=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;qt=.4,Kt=.3,Vt=.2,Jt=.1;});var $t=300*1e3,W=null;function Tt(){W=null;}function O(e,t){return S.existsSync(T.join(e,t))}function M(e,t){return S.existsSync(T.join(e,t))}function Bt(e,t,n){let r=e;try{if(!S.existsSync(r))return !1;let s=S.readdirSync(r,{withFileTypes:!0});for(let i of s){if(i.isFile()&&i.name.endsWith(t))return !0;if(i.isDirectory())try{if(S.readdirSync(T.join(r,i.name)).some(c=>c.endsWith(t)))return !0}catch{}}}catch{}return false}var Gt={wisdom:e=>O(e,".paradigm/wisdom"),history:e=>O(e,".paradigm/history"),lore:e=>O(e,".paradigm/lore"),habits:e=>M(e,".paradigm/habits.yaml"),sentinel:e=>{try{let t=T.join(e,".paradigm","config.yaml");return S.existsSync(t)?S.readFileSync(t,"utf-8").includes("sentinel"):!1}catch{return false}},flows:e=>M(e,".paradigm/flow-index.json")||M(e,".paradigm/flows.yaml"),fixtures:e=>M(e,".paradigm/fixtures.yaml"),orchestration:e=>M(e,".paradigm/agents.yaml"),tasks:e=>O(e,".paradigm/tasks"),assessment:e=>O(e,".paradigm/lore"),personas:e=>Bt(e,".persona"),protocols:e=>O(e,".paradigm/protocols"),symphony:()=>{let e=T.join(B.homedir(),".paradigm","score");return S.existsSync(e)},university:e=>O(e,".paradigm/university"),agents:e=>{let t=T.join(B.homedir(),".paradigm","agents");return O(e,".paradigm/agents")||S.existsSync(t)},"aspect-graph":e=>M(e,".paradigm/aspect-graph.db"),pan:e=>M(e,".pan")||M(e,"nevr.yaml"),notebooks:e=>{let t=T.join(B.homedir(),".paradigm","notebooks");return O(e,".paradigm/notebooks")||S.existsSync(t)}},Et=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(t){this.rootDir=t;}register(t){this.modules.set(t.key,t);}registerAll(t){for(let n of t)this.register(n);}detectActiveFeatures(){if(W&&Date.now()-W.timestamp<$t)return W.features;let t=new Set;for(let[n,r]of this.modules){if(r.tier==="core"){t.add(n);continue}if(r.tier==="advanced"){this.activatedAdvanced.has(n)&&t.add(n);continue}let s=r.detect||Gt[n];if(s)try{s(this.rootDir)&&t.add(n);}catch{}else t.add(n);}return W={features:t,timestamp:Date.now()},t}getActiveTools(){let t=this.detectActiveFeatures(),n=[];for(let[r,s]of this.modules)t.has(r)&&n.push(...s.getToolsList());return n}activateAdvanced(t){let n=this.modules.get(t);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(t),n.getToolsList())}getAvailableAdvanced(){let t=[];for(let[n,r]of this.modules)r.tier==="advanced"&&!this.activatedAdvanced.has(n)&&t.push({key:n,toolCount:r.getToolsList().length});return t}async dispatch(t,n,r,s){let i=this.detectActiveFeatures();for(let[a,c]of this.modules)if(i.has(a))try{let o=await c.handleTool(t,n,r,s);if(o.handled)return o}catch(o){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${a}"`,message:o.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let t=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let r of this.modules.values())n[r.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...t],availableAdvanced:[...this.modules.entries()].filter(([r,s])=>s.tier==="advanced"&&!this.activatedAdvanced.has(r)).map(([r])=>r)}}};var tt=null;async function ee(){return tt||(tt=await te()),tt}var ne=[`CREATE TABLE IF NOT EXISTS aspects (
12
+ id TEXT PRIMARY KEY,
13
+ description TEXT NOT NULL,
14
+ category TEXT DEFAULT 'rule',
15
+ severity TEXT DEFAULT 'medium',
16
+ value TEXT,
17
+ enforcement TEXT,
18
+ defined_in TEXT NOT NULL,
19
+ tags TEXT,
20
+ created_at TEXT NOT NULL,
21
+ updated_at TEXT NOT NULL
22
+ )`,`CREATE TABLE IF NOT EXISTS anchors (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
25
+ file_path TEXT NOT NULL,
26
+ start_line INTEGER NOT NULL,
27
+ end_line INTEGER NOT NULL,
28
+ content_hash TEXT,
29
+ normalized_hash TEXT,
30
+ materialized_at_commit TEXT,
31
+ last_verified TEXT,
32
+ drifted INTEGER DEFAULT 0
33
+ )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ source TEXT NOT NULL,
36
+ target TEXT NOT NULL,
37
+ relation TEXT NOT NULL,
38
+ weight REAL DEFAULT 1.0,
39
+ origin TEXT DEFAULT 'explicit',
40
+ created_at TEXT NOT NULL
41
+ )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
42
+ aspect_id TEXT NOT NULL,
43
+ lore_id TEXT NOT NULL,
44
+ PRIMARY KEY (aspect_id, lore_id)
45
+ )`,`CREATE TABLE IF NOT EXISTS search_log (
46
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ query TEXT NOT NULL,
48
+ results_returned TEXT NOT NULL,
49
+ selected_result TEXT,
50
+ timestamp TEXT NOT NULL
51
+ )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
52
+ query_normalized TEXT NOT NULL,
53
+ aspect_id TEXT NOT NULL,
54
+ weight REAL DEFAULT 1.0,
55
+ hit_count INTEGER DEFAULT 1,
56
+ last_hit TEXT NOT NULL,
57
+ PRIMARY KEY (query_normalized, aspect_id)
58
+ )`,`CREATE TABLE IF NOT EXISTS heatmap (
59
+ aspect_id TEXT NOT NULL,
60
+ access_type TEXT NOT NULL,
61
+ count INTEGER DEFAULT 0,
62
+ last_accessed TEXT NOT NULL,
63
+ PRIMARY KEY (aspect_id, access_type)
64
+ )`],se=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
65
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ anchor_id INTEGER NOT NULL,
67
+ action TEXT NOT NULL,
68
+ old_start INTEGER,
69
+ old_end INTEGER,
70
+ new_start INTEGER,
71
+ new_end INTEGER,
72
+ old_path TEXT,
73
+ new_path TEXT,
74
+ confidence REAL,
75
+ commit_hash TEXT,
76
+ healed_at TEXT NOT NULL
77
+ )`],re="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function I(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=[];for(;r.step();)s.push(r.getAsObject());return r.free(),s}function oe(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=null;return r.step()&&(s=r.getAsObject()),r.free(),s}async function Nt(e){let t=await ee(),n=T.join(e,".paradigm"),r=T.join(n,"aspect-graph.db"),s;if(S.existsSync(r)){let i=S.readFileSync(r);s=new t.Database(i);}else S.existsSync(n)||S.mkdirSync(n,{recursive:true}),s=new t.Database;for(let i of ne)s.run(i);try{s.run(re);}catch{}for(let i of se)try{s.run(i);}catch{}return s}function Ot(e,t){if(t){let n=T.join(t,".paradigm");S.existsSync(n)||S.mkdirSync(n,{recursive:true});let r=T.join(n,"aspect-graph.db"),s=e.export();S.writeFileSync(r,Buffer.from(s));}e.close();}function vt(e,t,n){let r=t.filter(a=>a.type==="aspect"),s=new Date().toISOString(),i=null;try{i=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}e.run("DELETE FROM anchors"),e.run("DELETE FROM edges"),e.run("DELETE FROM aspects");try{e.run("DELETE FROM aspects_fts");}catch{}for(let a of r){let c=a.data??{},o=le(c,a),d=de(c,a),l=c.value!=null?String(c.value):null,u=a.enforcement??(c.enforcement!=null?String(c.enforcement):null),f=a.tags?JSON.stringify(a.tags):null;if(e.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
78
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,a.description??"",o,d,l,u,a.filePath,f,a.created??s,a.modified??s]),a.anchors)for(let h of a.anchors){let{startLine:_,endLine:N}=Ft(h),L=ce();e.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
79
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,h.path,_,N,L.exact,L.normalized,i,s,L.normalizedContent]);}let y=c.edges;if(Array.isArray(y))for(let h of y)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
80
+ VALUES (?, ?, ?, ?, ?, ?)`,[h.source??a.symbol,h.target??"",h.relation??"related-to",h.weight??1,h.origin??"explicit",s]);if(a.appliesTo)for(let h of a.appliesTo)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
81
+ VALUES (?, ?, ?, ?, ?, ?)`,[a.symbol,h,"related-to",.5,"inferred",s]);try{e.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
82
+ VALUES (?, ?, ?, ?)`,[a.symbol,a.description??"",u??"",f??""]);}catch{}}}function He(e,t){return oe(e,"SELECT * FROM aspects WHERE id = ?",[t])}function Ue(e,t){return I(e,"SELECT * FROM anchors WHERE aspect_id = ?",[t])}function Xe(e,t){return I(e,"SELECT * FROM edges WHERE source = ?",[t])}function We(e,t){return I(e,"SELECT * FROM edges WHERE target = ?",[t])}function ze(e,t){return I(e,"SELECT * FROM edges WHERE source = ? OR target = ?",[t,t])}function $e(e,t,n){let r=new Date().toISOString();e.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
83
+ VALUES (?, ?, 1, ?)
84
+ ON CONFLICT(aspect_id, access_type)
85
+ DO UPDATE SET count = count + 1, last_accessed = ?`,[t,n,r,r]);}function Be(e,t=20,n){return n?I(e,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,t]):I(e,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[t])}function Ge(e,t,n,r=true,s=.7,i=.85){let a=n?I(e,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):I(e,"SELECT * FROM anchors"),c=[];for(let o of a){let l=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id])[0]?.defined_in,u=l?T.dirname(T.isAbsolute(l)?l:T.resolve(t,l)):t,f=H(o.file_path,u,t),y=f.resolvedPath;if(!f.exists){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let _=S.readFileSync(y,"utf8").split(`
86
+ `),N=Math.max(0,o.start_line-1),L=Math.min(_.length,o.end_line),P=_.slice(N,L).join(`
87
+ `),j=D.createHash("sha256").update(P).digest("hex");if(o.content_hash!=null&&j===o.content_hash){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),o.drifted===1&&e.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[o.id]);continue}let U=D.createHash("sha256").update(nt(P)).digest("hex");if(o.normalized_hash!=null&&U===o.normalized_hash){e.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[j,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(o.content_hash==null&&o.normalized_hash==null){e.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[j,U,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let H=!1;if(o.materialized_at_commit){let m=ae(t,o.file_path,o.materialized_at_commit,o.start_line,o.end_line);if(m){let g=Math.max(0,m.currentStart-1),p=Math.min(_.length,m.currentEnd),E=_.slice(g,p).join(`
88
+ `),F=D.createHash("sha256").update(E).digest("hex");if(o.content_hash!=null&&F===o.content_hash){let k=r;if(k){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,o.id]);let X=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);X.length>0&&et(t,X[0].defined_in,o.file_path,o.start_line,o.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:k?m.currentStart:o.start_line,endLine:k?m.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:k}),H=!0;}else {let k=D.createHash("sha256").update(nt(E)).digest("hex");if(o.normalized_hash!=null&&k===o.normalized_hash){if(r){let X=D.createHash("sha256").update(E).digest("hex");e.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,X,o.id]);let z=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);z.length>0&&et(t,z[0].defined_in,o.file_path,o.start_line,o.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:r?m.currentStart:o.start_line,endLine:r?m.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:r}),H=!0;}}}}if(H)continue;if(o.original_content){let{contentSearch:m}=(It(),d(At)),g=m(t,o.file_path,o.original_content,r);if(g.found&&g.score>=s){if(r&&g.score>=i&&!g.suggestedPath&&g.suggestedStart&&g.suggestedEnd){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[g.suggestedStart,g.suggestedEnd,o.id]);try{e.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
89
+ VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[o.id,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd,g.score,new Date().toISOString()]);}catch{}let E=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);E.length>0&&et(t,E[0].defined_in,o.file_path,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:g.suggestedStart,endLine:g.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:o.aspect_id,path:g.suggestedPath||o.file_path,startLine:o.start_line,endLine:o.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!1,drifted:!0});continue}}e.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:P,drifted:!0});}catch{c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Ft(e){let{lines:t}=e;return typeof t=="number"?{startLine:t,endLine:t}:Array.isArray(t)?t.length===2?{startLine:t[0],endLine:t[1]}:{startLine:Math.min(...t),endLine:Math.max(...t)}:{startLine:1,endLine:1}}function ie(e){let t=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,r;for(;(r=n.exec(e))!==null;)t.push({oldStart:parseInt(r[1],10),oldCount:r[2]!==void 0?parseInt(r[2],10):1,newStart:parseInt(r[3],10),newCount:r[4]!==void 0?parseInt(r[4],10):1});return t}function ae(e,t,n,r,s){let i;try{i=execSync(`git diff ${n}..HEAD --unified=0 -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3});}catch{return null}if(!i.trim())return {originalStart:r,originalEnd:s,currentStart:r,currentEnd:s};let a=ie(i),c=0;for(let o of a){if(o.oldStart+o.oldCount<=r){c+=o.newCount-o.oldCount;continue}if(o.oldStart<s)return null;break}return c===0?null:{originalStart:r,originalEnd:s,currentStart:r+c,currentEnd:s+c}}function et(e,t,n,r,s,i,a){let c=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(c))return false;try{let o=S.readFileSync(c,"utf8"),d=r===s?`${n}:${r}`:`${n}:${r}-${s}`,l=i===a?`${n}:${i}`:`${n}:${i}-${a}`;if(!o.includes(d))return !1;let u=o.replace(d,l);return S.writeFileSync(c,u,"utf8"),!0}catch{return false}}function nt(e){return e.split(`
90
+ `).map(t=>t.trimEnd()).filter(t=>t.trim()!=="").map(t=>t.replace(/\s+/g," ")).join(`
91
+ `)}function ce(e,t,n){return {exact:null,normalized:null,normalizedContent:null};}function le(e,t){if(typeof e.category=="string")return e.category;let n=(t.description??"").toLowerCase();return /\b(must|require|always)\b/.test(n)?"rule":/\b(decided|chose)\b/.test(n)?"decision":/\b(limit|cannot)\b/.test(n)?"constraint":/\b(set to|configured|value)\b/.test(n)?"configuration":"rule"}function de(e,t){if(typeof e.severity=="string")return e.severity;let n=t.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j();var ue=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function kt(e,t){e.run("DELETE FROM lore_links");let n=await a$5(t);if(n.length===0)return 0;let r=fe(n),s=new Map;for(let d of n)s.set(d.id,d);let i=new Set,a=e.exec("SELECT id, enforcement FROM aspects");if(a.length>0){let{columns:d,values:l}=a[0],u=d.indexOf("id"),f=d.indexOf("enforcement");for(let y of l){let h=String(y[u]),_=y[f];if(_&&typeof _=="string"){let N=_.match(ue);if(N)for(let L of N)s.has(L)&&i.add(`${h}\0${L}`);}}}let c=e.exec("SELECT source, target FROM edges");if(c.length>0&&a.length>0){let d=pe(e,c);for(let[l,u]of d)for(let f of u){let y=r.get(f);if(y)for(let h of y)i.add(`${l}\0${h}`);}}if(i.size===0)return 0;let o=e.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let d of i){let[l,u]=d.split("\0");o.bind([l,u]),o.step(),o.reset();}}finally{o.free();}return i.size}async function Ke(e,t,n){let r=e.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(r.length===0||r[0].values.length===0)return [];let s=r[0].values.map(i=>String(i[0]));return ge(t,s)}async function Mt(e,t){let n=await a$5(t);if(n.length===0)return 0;let r=e.exec("SELECT id FROM aspects"),s=new Set;if(r.length>0)for(let o of r[0].values)s.add(String(o[0]));if(s.size<2)return 0;let i=new Date().toISOString(),a=0,c=e.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
92
+ VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let o of n){if(!o.symbols_touched||o.symbols_touched.length<2)continue;let d=[];for(let l of o.symbols_touched){let u=l.startsWith("~")?l.slice(1):l;s.has(u)&&d.push(u);}for(let l=0;l<d.length;l++)for(let u=l+1;u<d.length;u++){let[f,y]=d[l]<d[u]?[d[l],d[u]]:[d[u],d[l]];c.bind([f,y,i]),c.step(),c.reset(),a++;}}}finally{c.free();}return a}function fe(e){let t=new Map;for(let n of e)if(n.symbols_touched)for(let r of n.symbols_touched){let s=t.get(r);s||(s=new Set,t.set(r,s)),s.add(n.id);}return t}function pe(e,t){let n=e.exec("SELECT id FROM aspects"),r=new Set;if(n.length>0)for(let d of n[0].values)r.add(String(d[0]));let s=new Map;if(t.length===0)return s;let{columns:i,values:a}=t[0],c=i.indexOf("source"),o=i.indexOf("target");for(let d of a){let l=String(d[c]),u=String(d[o]);if(r.has(l)){let f=s.get(l);f||(f=new Set,s.set(l,f)),f.add(u),f.add(`~${l}`);}if(r.has(u)){let f=s.get(u);f||(f=new Set,s.set(u,f)),f.add(l),f.add(`~${u}`);}}return s}async function ge(e,t){let n=new Set,r=[];for(let s of t){if(n.has(s))continue;n.add(s);let i=await b$2(e,s);i&&r.push(me(i));}return r}function me(e){return {id:e.id,title:e.title,summary:e.summary,timestamp:e.timestamp,symbolsTouched:e.symbols_touched}}var he="PARADIGM_STRICT";function q(){let e=process.env[he];if(e===void 0||e==="")return false;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var Dt=new Set(["duplicate-key-detected"]);function ye(e){let t=e.trim();if(t.includes("/")||t.includes("\\")){let n=t.split(/[/\\]/);t=n[n.length-1]||"unknown";}return t.length>40&&(t=t.slice(0,40)),t||"unknown"}var K=class{transforms=new Map;record(t,n,r=1){let s=ye(n),i=`${t}::${s}`,a=this.transforms.get(i);a?a.count+=r:this.transforms.set(i,{kind:t,surface:s,count:r});}report(){let t=Array.from(this.transforms.values()).sort((r,s)=>r.kind!==s.kind?r.kind.localeCompare(s.kind):r.surface.localeCompare(s.surface)),n=t.filter(r=>Dt.has(r.kind)).reduce((r,s)=>r+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:t,lossy_count:n,strict_mode:q()}}hasLossy(){for(let t of this.transforms.values())if(Dt.has(t.kind))return true;return false}totalCount(){let t=0;for(let n of this.transforms.values())t+=n.count;return t}};b$1();var Ee={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Te={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},Se={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},st={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function hn(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function yn(e,t,n,r){if(e!=="paradigm_reindex")return {handled:false,text:""};try{let s=await we(n.rootDir,n);await r(),f.clear(),Tt();let i=(s.integrityReport?.brokenReferences?.length||0)+(s.integrityReport?.duplicateSymbols?.length||0)+(s.componentAnchorIssues||0)+(s.crossFileIssues||0),a$1={success:!0,symbolCount:s.symbolCount,breakdown:s.breakdown,flowCount:s.flowCount,filesWritten:s.filesWritten.length,...s.aspectGraphStats?{aspects:s.aspectGraphStats.aspects,loreLinks:s.aspectGraphStats.loreLinks}:{},...s.protocolHealth?{protocols:s.protocolHealth.total,staleProtocols:s.protocolHealth.stale}:{},...i>0?{issues:i}:{}};s.consistency&&(a$1.consistency=s.consistency);let c=JSON.stringify(a$1,null,2);return a(c.length,e),{handled:!0,text:c}}catch(s){let i=JSON.stringify({error:s.message},null,2);return a(i.length,e),{handled:true,text:i}}}async function we(e,t$1){let n=[],r=new K,s;t$1?s=t$1.aggregation:s=await m(e);let i=t$1?.projectName||T.basename(e),a=T.join(e,".paradigm");S.existsSync(a)||S.mkdirSync(a,{recursive:true}),Re(e,r),_e(s.purposeFiles,r);let c=a$1({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:i}),o$1=T.join(a,"scan-index.json");S.writeFileSync(o$1,b$3(c),"utf8"),n.push(".paradigm/scan-index.json");let d=be(e,s),l=T.join(a,"navigator.yaml");S.writeFileSync(l,C.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let u=Ne(e,s.purposeFiles),f=0;if(u&&Object.keys(u.flows).length>0){let p=T.join(a,"flow-index.json");S.writeFileSync(p,JSON.stringify(u,null,2),"utf8"),n.push(".paradigm/flow-index.json"),f=Object.keys(u.flows).length;}let y;try{let p=await Nt(e);vt(p,s.symbols,e);let E=await kt(p,e),F=await Mt(p,e),k=p.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,X=p.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,z=p.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Ot(p,e),n.push(".paradigm/aspect-graph.db"),y={aspects:k,anchors:X,edges:z,loreLinks:E};}catch{}let h=0;try{let p=await o(e);h=Object.keys(p.personas).length,h>0&&n.push(".paradigm/personas/index.yaml");}catch{}let _;try{let p=await z(e);p.health.total>0&&(_=p.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let N;try{let p=T.join(e,".paradigm","university");if(S.existsSync(p)){let E=t(e);(E.totalContent>0||E.diplomaCount>0)&&(N={totalContent:E.totalContent,diplomaCount:E.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let L;try{L=a$2(s,e);}catch{}let P;try{let p=b$4(s.symbols,e),E=p.missing+p.outOfBounds;E>0&&(P=E);}catch{}let j;try{j=c$1(s.purposeFiles,e);}catch{}let U;try{let p=[];for(let E of s.purposeFiles){let F=a$3(E);F.data&&p.push({filePath:E,data:F.data});}if(p.length>0){let F=q$1(p).issues.length;F>0&&(U=F);}}catch{}let H={};for(let p of s.symbols)H[p.type]=(H[p.type]||0)+1;let m$1={};for(let p of s.symbols)p.type==="component"&&p.componentType&&(m$1[p.componentType]=(m$1[p.componentType]||0)+1);let g=r.report();try{let p=T.join(a,"manifest.consistency.json");S.writeFileSync(p,JSON.stringify(g,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$4.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(q()&&r.hasLossy())throw new Error(`reindex aborted: ${g.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:s.symbols.length,breakdown:H,flowCount:f,aspectGraphStats:y,personaCount:h,protocolHealth:_,consistency:g,...Object.keys(m$1).length>0?{componentTypeBreakdown:m$1}:{},...N?{universityStats:N}:{},...L?{integrityReport:L}:{},...P!==void 0?{componentAnchorIssues:P}:{},...j?{purposeHealth:j}:{},...U!==void 0?{crossFileIssues:U}:{}}}function Re(e,t){let n=T.join(e,"portal.yaml");if(!S.existsSync(n))return;let r;try{r=S.readFileSync(n,"utf-8");}catch{return}try{C.load(r);}catch(o){(o?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","portal.yaml");return}let s;try{s=C.load(r,{schema:C.FAILSAFE_SCHEMA});}catch{return}if(!s||typeof s!="object")return;let i=s,a=i.gates;if(a&&typeof a=="object"&&!Array.isArray(a)){let o=0;for(let d of Object.keys(a))d.startsWith("^")&&o++;o>0&&t.record("prefix-stripped","portal.yaml",o);}else Array.isArray(a)&&a.length>0&&t.record("array-coerced","portal.yaml");let c=i.routes;Array.isArray(c)&&c.length>0&&t.record("array-coerced","portal.yaml"),i.version||t.record("default-applied","portal.yaml");}function _e(e,t){for(let n of e){let r;try{r=S.readFileSync(n,"utf-8");}catch{continue}try{C.load(r);}catch(l){(l?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=C.load(r,{schema:C.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let i=s,a=["components","features","gates","signals","aspects","states"],c=0;for(let l of a)Array.isArray(i[l])&&c++;c>0&&t.record("array-coerced","purpose.yaml",c);let o=(l,u)=>{if(!l||typeof l!="object"||Array.isArray(l))return 0;let f=0;for(let y of Object.keys(l))y.startsWith(u)&&f++;return f},d=o(i.gates,"^")+o(i.signals,"!")+o(i.aspects,"~")+o(i.components,"#")+o(i.features,"#");d>0&&t.record("prefix-stripped","purpose.yaml",d);}}function be(e,t){let n={};for(let r of t.symbols)if(r.type==="component"&&r.componentType){let s=r.componentType;n[s]||(n[s]=[]),n[s].push(r.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:xe(e),key_files:Le(e),skip_patterns:Ae(e),symbols:Ce(t.symbols,t.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function xe(e){let t={};for(let[n,r]of Object.entries(Te)){let s=r.filter(i=>S.existsSync(T.join(e,i)));if(s.length>0){let i=Object.values(Ee).find(a=>a.category===n);t[n]={paths:s,symbol:i?.prefix||"@"};}}return t}function Le(e){let t={};for(let[n,r]of Object.entries(Se)){let s=r.filter(i=>S.existsSync(T.join(e,i)));s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function Ae(e){let t={always:[...st.always],unless_testing:[...st.unless_testing],unless_docs:[...st.unless_docs]},n=T.join(e,".gitignore");if(S.existsSync(n))try{let s=S.readFileSync(n,"utf8").split(`
93
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).filter(i=>i.endsWith("/")||i.includes("*")||["node_modules","dist","build",".cache"].some(a=>i.includes(a))).slice(0,20);for(let i of s)t.always.includes(i)||t.always.push(i);}catch{}return t}function Ie(e){switch(e){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function Ce(e,t,n){let r={};for(let s of e){let a=`${Ie(s.type)}${s.id}`;if(s.filePath)r[a]=s.filePath;else {let c=t.find(o=>T.dirname(o).toLowerCase().includes(s.id.toLowerCase()));c&&(r[a]=T.dirname(c)+"/");}}return r}function Ne(e,t){let n={},r={};for(let s of t)try{let i=S.readFileSync(s,"utf8"),a=C.load(i);if(!a?.flows)continue;if(Array.isArray(a.flows))for(let c of a.flows){let o=c;if(!o.name)continue;let d=`$${o.name}`,l=Pt(o.steps);l.length>0&&(n[d]={id:d,description:o.description||"",steps:l,definedIn:T.relative(e,s)},jt(d,l,r));}else for(let[c,o]of Object.entries(a.flows)){let d=c.startsWith("$")?c:`$${c}`,l=Pt(o.steps);l.length>0&&(n[d]={id:d,description:o.description||"",trigger:o.trigger,steps:l,validation:o.validation,definedIn:T.relative(e,s)},jt(d,l,r));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:r}}function Pt(e){if(!e||!Array.isArray(e))return [];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(typeof r=="object"&&r!==null){let s=r,i=s.action||s.description||s.component||"";i&&t.push({id:s.id||`step-${n+1}`,action:i,symbol:s.symbol||s.component,expect:s.expect});}}return t}function jt(e,t,n){for(let r of t)r.symbol&&(n[r.symbol]||(n[r.symbol]=[]),n[r.symbol].includes(e)||n[r.symbol].push(e));}export{Et as a,q as b,Nt as c,Ot as d,He as e,Ue as f,Xe as g,We as h,ze as i,$e as j,Be as k,Ge as l,Ke as m,hn as n,yn as o,we as p};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-6AKNXD22.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-YXLGVOZO.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
2
+ import {b}from'./chunk-NRP2KJ6I.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-YXLGVOZO.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
3
3
  Configure Agent Models
4
4
  `)),console.log(e$1.gray(` Environment: ${c.source}`)),console.log(e$1.gray(` Available: ${c.models.length} models
5
5
  `));let i={},o=n.groupByTier(c.models),a$2=t=>{let r=a$1[t],s=r.tier==="high"?o.high:r.tier==="medium"?o.medium:o.low,l=[];for(let f of s){let P=l.length===0;l.push({title:P?`${f.name} (recommended)`:f.name,value:f.id,description:`${f.provider} - ${r.tier} tier`});}let u=o.high.filter(f=>!s.includes(f)),y=o.medium.filter(f=>!s.includes(f)),v=o.low.filter(f=>!s.includes(f));for(let f of u)l.push({title:f.name,value:f.id,description:`${f.provider} - high tier`});for(let f of y)l.push({title:f.name,value:f.id,description:`${f.provider} - medium tier`});for(let f of v)l.push({title:f.name,value:f.id,description:`${f.provider} - low tier`});return l};for(let t of ["architect","builder","tester","reviewer","security"]){let r=a$1[t],s=t.charAt(0).toUpperCase()+t.slice(1),l=a$2(t),u=await E({type:"select",name:"model",message:`${s} (${r.description})`,choices:l,initial:0},{onCancel:()=>{console.log(e$1.yellow(`
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b,a}from'./chunk-EK4ZRIFJ.js';import*as t from'fs';import*as o from'path';b();function p(s,e){try{let r=o.join(s,".paradigm");t.mkdirSync(r,{recursive:!0});let a=o.join(r,".orchestrated"),n={timestamp:new Date().toISOString(),type:"orchestrated",verdicts:e.verdicts,source:e.source};return t.writeFileSync(a,JSON.stringify(n),"utf8"),!0}catch(r){return a.component("#orchestration-marker").warn("Failed to write orchestration completion marker",{source:e.source,error:r instanceof Error?r.message:String(r)}),false}}export{p as a};
@@ -16,5 +16,5 @@ ${i.map((w,I)=>`${I+1}. ${w}`).join(`
16
16
  - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
17
17
  - Symbols touched: ${l.length>0?l.join(", "):"(not specified)"}
18
18
  - Open questions: ${d.length>0?d.join(", "):"(none)"}
19
- `;return Mt(),{handled:true,text:JSON.stringify({handoff:f,markdownSummary:b,persisted:g,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),i=n.getCostBreakdown(),a=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=Je(o.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let d=Date.now()-s.timestamp,c=Math.round(d/6e4),u=Math.round(d/36e5);r.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${c} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(a){let d=Date.now()-a.lastActivity,c=Math.round(d/6e4),u=Math.round(d/36e5),h=a.breadcrumbs.slice(-10).map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${c} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=h;}if(i.length>0){r.pendingHandoffs=i.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of i)try{c(o.rootDir,d.id);}catch{}}let l="Continue where the previous session left off.";if(s)l=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(l+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let d=i[i.length-1];l=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(l+=`Start with: ${d.nextSteps[0]}`);}else if(a){let d=a.breadcrumbs.slice(-10);if(d.length>0){let c=d[d.length-1];c.symbol&&(l=`Last work involved ${c.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=l,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(o.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,l=e.modifiedFiles,d=e.symbolsTouched,c=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:l,symbolsTouched:d,decisions:c}),h=p.local||p.global;return {handled:true,text:JSON.stringify({saved:h,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function Je(t){let e=j$1();e.setRootDir(t);let o=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b(t);}catch{}return {checkpoint:o,pendingHandoffs:s,previousSession:n}}async function kn(t){let{checkpoint:e,pendingHandoffs:o}=Je(t);if(!e&&o.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;n.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(o.length>0){let s=o[o.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:l}=await import('./task-settlement-NW4XMJGJ.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-YUP3KVCA.js'),a=await s(t,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){n.push(""),n.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:l,loadTask:d}=await import('./task-loader-IGQQ6ZFL.js');for(let c of r){let u=c.tags.length>0?` [${c.tags.join(", ")}]`:"",p=c.proposedClaimant;if(!p){let h=await d(t,c.taskId);h&&(p=await i(h,t));}if(p){try{let h=await d(t,c.taskId);h&&!h.claimant&&h.status==="open"&&await l(t,c.taskId,{claimant:p});}catch{}n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u} \u2192 proposed ${p.ref}`);}else n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await s(t,{status:"open",limit:5});if(i.length>0){n.push(""),n.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";n.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(t,{limit:10})).filter(r=>r.tags?.some(l=>l.startsWith("arc:")));if(a.length>0){let r=new Map;for(let c of a){let u=c.tags?.find(p=>p.startsWith("arc:"))||"";r.set(u,(r.get(u)||0)+1);}let l=e?.symbolsTouched||[];if((l.length>0?a.filter(c=>c.symbols_touched?.some(u=>l.includes(u))):a.slice(0,3)).length>0||r.size>0){n.push(""),n.push("Active lore arcs:");for(let[c,u]of r)n.push(` ${c} (${u} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-AQHU2KBU.js'),i=s(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))n.push(` [${a.urgency}] ${a.brief}`);i.length>5&&n.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),n.push("---"),n.join(`
19
+ `;return Mt(),{handled:true,text:JSON.stringify({handoff:f,markdownSummary:b,persisted:g,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),i=n.getCostBreakdown(),a=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=Je(o.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let d=Date.now()-s.timestamp,c=Math.round(d/6e4),u=Math.round(d/36e5);r.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${c} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(a){let d=Date.now()-a.lastActivity,c=Math.round(d/6e4),u=Math.round(d/36e5),h=a.breadcrumbs.slice(-10).map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${c} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=h;}if(i.length>0){r.pendingHandoffs=i.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of i)try{c(o.rootDir,d.id);}catch{}}let l="Continue where the previous session left off.";if(s)l=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(l+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let d=i[i.length-1];l=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(l+=`Start with: ${d.nextSteps[0]}`);}else if(a){let d=a.breadcrumbs.slice(-10);if(d.length>0){let c=d[d.length-1];c.symbol&&(l=`Last work involved ${c.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=l,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(o.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,l=e.modifiedFiles,d=e.symbolsTouched,c=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:l,symbolsTouched:d,decisions:c}),h=p.local||p.global;return {handled:true,text:JSON.stringify({saved:h,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function Je(t){let e=j$1();e.setRootDir(t);let o=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b(t);}catch{}return {checkpoint:o,pendingHandoffs:s,previousSession:n}}async function kn(t){let{checkpoint:e,pendingHandoffs:o}=Je(t);if(!e&&o.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;n.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(o.length>0){let s=o[o.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:l}=await import('./task-settlement-NF7PFSNE.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-CAXGHC2V.js'),a=await s(t,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){n.push(""),n.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:l,loadTask:d}=await import('./task-loader-IO4UVFUD.js');for(let c of r){let u=c.tags.length>0?` [${c.tags.join(", ")}]`:"",p=c.proposedClaimant;if(!p){let h=await d(t,c.taskId);h&&(p=await i(h,t));}if(p){try{let h=await d(t,c.taskId);h&&!h.claimant&&h.status==="open"&&await l(t,c.taskId,{claimant:p});}catch{}n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u} \u2192 proposed ${p.ref}`);}else n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-IO4UVFUD.js'),i=await s(t,{status:"open",limit:5});if(i.length>0){n.push(""),n.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";n.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(t,{limit:10})).filter(r=>r.tags?.some(l=>l.startsWith("arc:")));if(a.length>0){let r=new Map;for(let c of a){let u=c.tags?.find(p=>p.startsWith("arc:"))||"";r.set(u,(r.get(u)||0)+1);}let l=e?.symbolsTouched||[];if((l.length>0?a.filter(c=>c.symbols_touched?.some(u=>l.includes(u))):a.slice(0,3)).length>0||r.size>0){n.push(""),n.push("Active lore arcs:");for(let[c,u]of r)n.push(` ${c} (${u} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-YRHZZZUN.js'),i=s(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))n.push(` [${a.urgency}] ${a.brief}`);i.length>5&&n.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),n.push("---"),n.join(`
20
20
  `)}export{vt as A,Ue as B,kt as C,$t as D,jt as E,le as F,Et as G,cn as H,dn as I,ln as J,un as K,Ot as L,fn as M,pn as N,gn as O,Sn as P,bn as Q,wn as R,vn as S,kn as T,Lt as a,z as b,W as c,Wt as d,ye as e,Ut as f,Ht as g,qt as h,Gt as i,te as j,Jt as k,Bt as l,Kt as m,Vt as n,O as o,st as p,oe as q,B as r,Y as s,yt as t,ht as u,Ne as v,gt as w,ae as x,St as y,bt as z};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b,c,d}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as a from'path';import*as h from'js-yaml';var g,ke,x=b(()=>{g={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},ke=new Set(["tool-called","context-checked"]);});var D={};c(D,{getAllStates:()=>K,getConfig:()=>Y,getState:()=>S,incrementFailure:()=>X,invalidateGraduationCache:()=>Z,isGraduated:()=>z,loadGraduation:()=>p,markNeverGraduate:()=>Q,saveGraduation:()=>k,setTier:()=>J});function T(e){return a.join(e,".paradigm","graduation.yaml")}function p(e){let t=a.resolve(e);if(m&&y===t&&Date.now()-v<B)return m;let o=T(t),i;if(s.existsSync(o))try{let r=s.readFileSync(o,"utf8");i=h.load(r);}catch{i={version:"1.0",config:{},states:{}};}else i={version:"1.0",config:{},states:{}};return i.version||(i.version="1.0"),i.config||(i.config={}),i.states||(i.states={}),m=i,y=t,v=Date.now(),i}function k(e,t){let o=a.resolve(e),i=T(o),r=a.dirname(i);s.existsSync(r)||s.mkdirSync(r,{recursive:true});let n=h.dump(t,{lineWidth:120,noRefs:true,sortKeys:true});s.writeFileSync(i,n,"utf8"),m=t,y=o,v=Date.now();}function Y(e){let t=p(e);return {...g,...t.config,thresholds:{...g.thresholds,...t.config?.thresholds},demotion:{...g.demotion,...t.config?.demotion},neverGraduate:t.config?.neverGraduate??g.neverGraduate}}function w(e){return {habitId:e,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function S(e,t){let i=p(e).states[t];return i?{...w(t),...i,habitId:t}:w(t)}function K(e){let t=p(e),o={};for(let[i,r]of Object.entries(t.states))o[i]={...w(i),...r,habitId:i};return o}function z(e,t){return S(e,t).tier==="hook"}function J(e,t,o,i){let r=p(e),n=r.states[t]||{};r.states[t]={...n,tier:o,previousTier:n.tier||"habit",...o==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...o==="habit"&&n.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...i},k(e,r);}function Q(e,t){let o=p(e);o.states[t]||(o.states[t]={}),o.states[t].neverGraduate=true,o.states[t].tier="habit",k(e,o);}function X(e,t){let o=p(e);o.states[t]||(o.states[t]={});let i=(o.states[t].failureCount||0)+1;return o.states[t].failureCount=i,k(e,o),i}function Z(){m=null,y=null,v=0;}var m,y,v,B,R=b(()=>{x();m=null,y=null,v=0,B=3e4;});var F=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],ee=30*1e3,C=new Map;function _e(e){let t=a.resolve(e),o=C.get(t);if(o&&Date.now()-o.loadedAt<ee)return o.habits;let i=te(t);return C.set(t,{habits:i,loadedAt:Date.now()}),i}function te(e){let t=new Map;for(let l of F)t.set(l.id,{...l});let o=process.env.HOME||process.env.USERPROFILE||"~",i=G(a.join(o,".paradigm","habits.yaml"));i&&A(t,i);let r=M(a.join(o,".paradigm","habits"));for(let l of r)t.set(l.id,l);let n=G(a.join(e,".paradigm","habits.yaml"));n&&A(t,n);let u=M(a.join(e,".paradigm","habits"));for(let l of u)t.set(l.id,l);return Array.from(t.values())}function G(e){if(!s.existsSync(e))return null;try{let t=s.readFileSync(e,"utf8");return h.load(t)}catch{return null}}function A(e,t){if(t.habits)for(let o of t.habits)e.set(o.id,{...o});if(t.overrides)for(let[o,i]of Object.entries(t.overrides)){let r=e.get(o);r&&(i.severity!==void 0&&(r.severity=i.severity),i.enabled!==void 0&&(r.enabled=i.enabled));}}function oe(e,t){return e.filter(o=>o.enabled&&o.trigger===t)}function _(e){C.delete(a.resolve(e));}function M(e){if(!s.existsSync(e))return [];try{let t=s.readdirSync(e).filter(i=>i.endsWith(".habit")).sort(),o=[];for(let i of t)try{let r=s.readFileSync(a.join(e,i),"utf8"),n=h.load(r);n?.id&&n?.name&&o.push(n);}catch{}return o}catch{return []}}var j=["discovery","verification","testing","documentation","collaboration","security"],$=["preflight","postflight","on-commit","on-stop"],P=["advisory","warn","block"],W=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function He(e){let t=[];if(e.id||t.push("Missing required field: id"),e.name||t.push("Missing required field: name"),e.description||t.push("Missing required field: description"),e.category||t.push("Missing required field: category"),e.trigger||t.push("Missing required field: trigger"),e.severity||t.push("Missing required field: severity"),e.check||t.push("Missing required field: check"),(e.enabled===void 0||e.enabled===null)&&t.push("Missing required field: enabled"),e.id&&!ie.test(e.id)&&t.push(`Invalid id format: "${e.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),e.category&&!j.includes(e.category)&&t.push(`Invalid category: "${e.category}" \u2014 must be one of: ${j.join(", ")}`),e.trigger&&!$.includes(e.trigger)&&t.push(`Invalid trigger: "${e.trigger}" \u2014 must be one of: ${$.join(", ")}`),e.severity&&!P.includes(e.severity)&&t.push(`Invalid severity: "${e.severity}" \u2014 must be one of: ${P.join(", ")}`),e.check){W.includes(e.check.type)||t.push(`Invalid check.type: "${e.check.type}" \u2014 must be one of: ${W.join(", ")}`);let o=e.check.params||{};switch(e.check.type){case "tool-called":(!o.tools||!Array.isArray(o.tools)||o.tools.length===0)&&t.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!o.patterns||!Array.isArray(o.patterns)||o.patterns.length===0)&&t.push(`check.type "${e.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!o.messagePatterns||!Array.isArray(o.messagePatterns)||o.messagePatterns.length===0)&&t.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:t.length===0,errors:t}}var re=new Set(F.map(e=>e.id));function ne(e){return re.has(e)}function Ee(e,t,o="project"){let i=o==="global"?a.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):a.join(e,".paradigm","habits");s.existsSync(i)||s.mkdirSync(i,{recursive:true});let r=a.join(i,`${t.id}.habit`),n=h.dump(t,{lineWidth:120,noRefs:true});return s.writeFileSync(r,n,"utf8"),_(e),r}function xe(e,t){if(ne(t))return {removed:false,reason:`"${t}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let o=a.join(e,".paradigm","habits",`${t}.habit`);if(s.existsSync(o))return s.unlinkSync(o),_(e),{removed:true};let i=process.env.HOME||process.env.USERPROFILE||"~",r=a.join(i,".paradigm","habits",`${t}.habit`);return s.existsSync(r)?(s.unlinkSync(r),_(e),{removed:true}):{removed:false,reason:`No .habit file found for "${t}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var se=0;function Te(e,t,o,i,r){let n=oe(e,t);i&&(n=n.filter(d=>!d.platforms||d.platforms.includes(i)));let u=0;if(r)try{let{isGraduated:d$1}=(R(),d(D)),O=n.length;n=n.filter(U=>!d$1(r,U.id)),u=O-n.length;}catch{}se=u;let l=n.map(d=>ae(d,o)),N=l.filter(d=>d.result==="followed").length,q=l.filter(d=>d.result==="skipped").length,I=l.filter(d=>d.result==="partial").length,H=l.filter(d=>d.result==="skipped"&&d.habit.severity==="block").length;return {trigger:t,evaluations:l,summary:{total:l.length,followed:N,skipped:q,partial:I,blockingViolations:H},blocksCompletion:H>0}}function Se(e){return {toolsCalled:e.toolsCalled||[],filesModified:e.filesModified||[],symbolsTouched:e.symbolsTouched||[],loreRecorded:e.loreRecorded||false,hasPortalRoutes:e.hasPortalRoutes||false,taskAddsRoutes:e.taskAddsRoutes||false,taskDescription:e.taskDescription,gitClean:e.gitClean}}function ae(e,t){switch(e.check.type){case "tool-called":return le(e,t);case "file-exists":return de(e,t);case "file-modified":return ge(e,t);case "lore-recorded":return ce(e,t);case "symbols-registered":return ue(e,t);case "gates-declared":return fe(e,t);case "tests-exist":return pe(e,t);case "git-clean":return me(e,t);case "commit-message-format":return he(e,t);case "flow-coverage":return ye(e,t);case "context-checked":return ve(e,t);case "aspect-anchored":return be(e,t);default:return {habit:e,result:"partial",reason:`Unknown check: ${e.check.type}`}}}function le(e,t){let o=e.check.params.tools||[];if(o.length===0)return {habit:e,result:"followed",reason:"No tools required"};let i=o.filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, habit not applicable"}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] were called before modifying code`}}function de(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};if(t.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:e,result:"followed",reason:"Purpose files updated"};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".yml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/"));return i.length===0?{habit:e,result:"followed",reason:"Only non-source files modified"}:{habit:e,result:"skipped",reason:`${i.length} source file(s) without .purpose updates`,evidence:i.slice(0,5)}}function ce(e,t){let o=t.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return o.length<3?{habit:e,result:"followed",reason:"Session not significant (< 3 source files)"}:t.loreRecorded||t.toolsCalled.includes("paradigm_lore_record")?{habit:e,result:"followed",reason:"Lore recorded"}:{habit:e,result:"skipped",reason:`${o.length} source files modified, no lore entry`,evidence:o.slice(0,5)}}function ue(e,t){if(t.symbolsTouched.length===0)return {habit:e,result:"followed",reason:"No symbols touched"};let i=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Purpose tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"partial",reason:`${t.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function fe(e,t){if(!t.taskAddsRoutes)return {habit:e,result:"followed",reason:"No routes added"};if(t.hasPortalRoutes)return {habit:e,result:"followed",reason:"Portal.yaml has routes"};let i=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Gate tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:"Routes added without gate declarations"}}function pe(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=t.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(o.length>0)return {habit:e,result:"followed",reason:`Test files: ${o.length}`,evidence:o.slice(0,5)};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/")&&!r.includes("node_modules/"));return i.length===0?{habit:e,result:"followed",reason:"No source files to test"}:{habit:e,result:"partial",reason:`${i.length} source file(s), no test files updated`,evidence:i.slice(0,5)}}function ge(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=e.check.params.patterns||[];if(o.length===0)return {habit:e,result:"followed",reason:"No patterns specified"};if(e.trigger==="on-stop"&&e.severity==="block"){let r=t.filesModified.filter(n=>o.some(u=>n.includes(u)||a.basename(n)===u));return r.length>0?{habit:e,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:e,result:"partial",reason:`None of [${o.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let i=t.filesModified.filter(r=>o.some(n=>r.includes(n)||a.basename(r)===n));return i.length>0?{habit:e,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] found in modified files`}}function me(e,t){return t.filesModified.length===0?{habit:e,result:"followed",reason:"No files modified"}:e.trigger==="on-stop"?{habit:e,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:t.gitClean===void 0?{habit:e,result:"partial",reason:"Git status not available"}:t.gitClean?{habit:e,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:e,result:"skipped",reason:"Uncommitted changes in working tree"}}function he(e,t){if(!t.commitMessage)return {habit:e,result:"followed",reason:"No commit message to check (not a commit trigger)"};let o=e.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],i=o.filter(r=>new RegExp(r,"m").test(t.commitMessage));if(i.length===o.length)return {habit:e,result:"followed",reason:"Commit message matches all required patterns",evidence:i};if(i.length>0){let r=o.filter(n=>!new RegExp(n,"m").test(t.commitMessage));return {habit:e,result:"partial",reason:`Matches ${i.length}/${o.length} patterns. Missing: ${r.join(", ")}`}}return {habit:e,result:"skipped",reason:"Commit message does not match required format patterns"}}function ye(e,t){let o=t.symbolsTouched.filter(n=>n.startsWith("#"));if(o.length<3)return {habit:e,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(t.hasFlowCoverage)return {habit:e,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(n=>t.toolsCalled.includes(n));return r.length>0?{habit:e,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:e,result:"skipped",reason:`${o.length} components touched without flow coverage`,evidence:o.slice(0,5)}}function ve(e,t){let i=(e.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Context tools called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, context check not applicable"}:{habit:e,result:"skipped",reason:"No context/session tools called during session"}}function be(e,t){let o=t.symbolsTouched.filter(i=>i.startsWith("~"));return o.length===0?{habit:e,result:"followed",reason:"No aspects touched"}:t.aspectAnchorsValid===true?{habit:e,result:"followed",reason:"Aspect anchors validated and valid"}:t.toolsCalled.includes("paradigm_aspect_check")?{habit:e,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:e,result:"skipped",reason:`${o.length} aspect(s) touched without anchor validation`,evidence:o.slice(0,5)}}export{ke as a,x as b,Y as c,S as d,K as e,R as f,_e as g,He as h,ne as i,Ee as j,xe as k,se as l,Te as m,Se as n};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FG3M6VVO.js';import {e}from'./chunk-Q527BPUF.js';import {s,e as e$1,g,b as b$2,f as f$2,h}from'./chunk-33ERV2MW.js';import {z,f as f$1,p as p$1}from'./chunk-KAFQA7HV.js';import {f,b as b$1,a as a$1}from'./chunk-ECO3LHCE.js';import*as v from'fs';import*as j from'path';v$1();b();z();f();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
+ `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f$1(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
+ `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g$1=new Set;for(let n of l){let u=n.agent;g$1.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g$1]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$2(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};