@a-company/paradigm 7.2.0 → 7.3.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 (92) hide show
  1. package/dist/{accept-orchestration-XW44LF5Y.js → accept-orchestration-JA3A3TSU.js} +1 -1
  2. package/dist/calibrate-SH6PRZFD.js +2 -0
  3. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  4. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  5. package/dist/{captain-CAXGHC2V.js → captain-ILBN2IKJ.js} +1 -1
  6. package/dist/{captain-CWCLFOXV.js → captain-J4FZ5PRU.js} +1 -1
  7. package/dist/{chunk-W3VWORQZ.js → chunk-3F4QP2Z5.js} +1 -1
  8. package/dist/{chunk-QPQBXRXX.js → chunk-5VR7FKS5.js} +1 -1
  9. package/dist/chunk-7BZPDOOQ.js +25 -0
  10. package/dist/{chunk-XSKIXXFW.js → chunk-7HUPVOAY.js} +12 -12
  11. package/dist/{chunk-ASBK55FU.js → chunk-DLMDHS2X.js} +1 -1
  12. package/dist/{chunk-6HYRS3PH.js → chunk-IBKCMLOW.js} +8 -8
  13. package/dist/{chunk-USYV5QYU.js → chunk-KA6QEI3C.js} +1 -1
  14. package/dist/{chunk-UNSI6DVD.js → chunk-L3AOKDMU.js} +1 -1
  15. package/dist/chunk-MBKTVQS2.js +2 -0
  16. package/dist/{chunk-RZRFYGND.js → chunk-O4ADSTSY.js} +12 -12
  17. package/dist/chunk-RPGSQQTS.js +2 -0
  18. package/dist/chunk-RQHZUPLO.js +4 -0
  19. package/dist/chunk-SD3KVW5Q.js +2 -0
  20. package/dist/chunk-VKVVIN6J.js +25 -0
  21. package/dist/{chunk-2KK4JQ55.js → chunk-VR2LLUYE.js} +1 -1
  22. package/dist/{chunk-NRP2KJ6I.js → chunk-YNFF7XHV.js} +2 -2
  23. package/dist/{diff-Z2YSIRC4.js → diff-NZSJW3V3.js} +1 -1
  24. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  25. package/dist/{docs-OWJ7EPD7.js → docs-DWU3T2BV.js} +1 -1
  26. package/dist/github-GI3HX3N5.js +4 -0
  27. package/dist/index.js +6 -6
  28. package/dist/mcp.js +1 -1
  29. package/dist/{orchestrate-C5NM5MFN.js → orchestrate-C7SI4J7C.js} +1 -1
  30. package/dist/orchestration-4MJKBSGM.js +2 -0
  31. package/dist/orchestration-S2ESNKSA.js +2 -0
  32. package/dist/platform-server-IOWHNS7Q.js +25 -0
  33. package/dist/{reindex-W67B2LQP.js → reindex-G2JLIGOQ.js} +1 -1
  34. package/dist/reindex-JR3PXYQE.js +2 -0
  35. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  36. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  37. package/dist/serve-PWAFVYYC.js +9 -0
  38. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  39. package/dist/{shift-UDKXCIW7.js → shift-HGXZ5THV.js} +1 -1
  40. package/dist/{spawn-I6XG57S2.js → spawn-PHA2SVQ3.js} +1 -1
  41. package/dist/sync-layer-C2PF273N.js +2 -0
  42. package/dist/task-PRLQ4VPK.js +3 -0
  43. package/dist/task-loader-EIXPKHA3.js +2 -0
  44. package/dist/task-loader-LFEE6OU7.js +2 -0
  45. package/dist/task-settlement-A2T6EACG.js +3 -0
  46. package/dist/task-settlement-ZXOY4YGX.js +3 -0
  47. package/dist/{team-6WNNLBAO.js → team-KP4HMUB5.js} +1 -1
  48. package/dist/tools-NOMEIBS7.js +2 -0
  49. package/dist/{tools-SDWAFQMQ.js → tools-YW3Q27UI.js} +11 -11
  50. package/package.json +2 -6
  51. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  52. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  53. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  54. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  55. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  56. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  57. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  58. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  59. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  60. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  61. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  62. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  63. package/platform-ui/dist/index.html +1 -1
  64. package/dist/calibrate-PHVP7RPH.js +0 -4
  65. package/dist/chunk-3I3TITBA.js +0 -25
  66. package/dist/chunk-3YM5ABNX.js +0 -2
  67. package/dist/chunk-727PXENG.js +0 -2
  68. package/dist/chunk-K7KT6FL3.js +0 -25
  69. package/dist/chunk-XMAV5AG6.js +0 -2
  70. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  71. package/dist/github-4X4MYINS.js +0 -4
  72. package/dist/lore-server-FC2GMDLT.js +0 -14
  73. package/dist/orchestration-EVWQWTOV.js +0 -2
  74. package/dist/orchestration-UP3KFUJT.js +0 -2
  75. package/dist/platform-server-FXF3XFHM.js +0 -25
  76. package/dist/reindex-QZYOD5K4.js +0 -2
  77. package/dist/serve-L52ZUTU6.js +0 -10
  78. package/dist/serve-ZT2Z54NK.js +0 -8
  79. package/dist/task-KFND4HLF.js +0 -3
  80. package/dist/task-loader-HBZ3KRH2.js +0 -2
  81. package/dist/task-loader-IO4UVFUD.js +0 -2
  82. package/dist/task-settlement-NF7PFSNE.js +0 -3
  83. package/dist/task-settlement-TATNPY6L.js +0 -3
  84. package/dist/tools-GDWT74O6.js +0 -2
  85. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  86. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  87. package/graph-ui/dist/index.html +0 -13
  88. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  89. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  90. package/lore-ui/dist/index.html +0 -13
  91. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  92. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-NRP2KJ6I.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ASBK55FU.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-FYDRENK7.js';import'./chunk-3YM5ABNX.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
2
+ import {b}from'./chunk-YNFF7XHV.js';import'./chunk-TYWB5IQJ.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-MBKTVQS2.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
3
3
  Orchestration ID required.`)),console.log(e.gray(`Usage: paradigm team accept <orchestration-id>
4
4
  `)));return}let l=new b(a),o=l.getOrchestration(n);if(!o){r.json?console.log(JSON.stringify({error:"Orchestration not found",id:n})):console.log(e.red(`
5
5
  Orchestration not found: ${n}
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {d,a as a$1}from'./chunk-RQHZUPLO.js';export{a as MIN_SAMPLES,c as aggregateActuals,b as percentile}from'./chunk-RQHZUPLO.js';import {c,e,f,g,a,b}from'./chunk-WR6D3SC6.js';import'./chunk-5TAVYPOV.js';import*as u from'path';var y=".paradigm/events/estimate-actuals.jsonl",L=".paradigm/learned/token-estimates.json";async function S(i={}){let f$1=i.project?u.resolve(i.project):process.cwd(),c$1=d(f$1);if(!c$1){c(`No captured actuals yet (${y} not found).`),e("Run some orchestrations first \u2014 actuals are captured per agent-step.");return}let{groups:o,samplesRead:h}=c$1,s=o.filter(e=>e.learned),l=o.filter(e=>!e.learned);if(f("Calibration \u2014 learned token-estimate table"),g("Samples read",String(h)),g("Groups",String(o.length)),g("Written to",L),s.length>0){a(""),b(`${s.length} group(s) learned (n >= ${a$1}):`);for(let e of s)g(`${e.archetype} \xB7 ${e.taskType}`,`${e.band.min}\u2013${e.band.max} tokens (n=${e.band.n})`);}else a(""),c(`No group reached the ${a$1}-sample floor \u2014 table written empty; planner uses the constant.`);if(l.length>0){a(""),e(`${l.length} group(s) below floor (n < ${a$1}) \u2014 still using the constant prior:`);for(let e$1 of l)e(` ${e$1.archetype} \xB7 ${e$1.taskType} (n=${e$1.n})`);}}export{S as calibrateCommand};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{a as MIN_SAMPLES,c as aggregateActuals,b as percentile,d as rebuildLearnedTable}from'./chunk-RQHZUPLO.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import'./chunk-5TAVYPOV.js';import*as c from'fs';import*as p from'path';var y=8,g=".paradigm/events/estimate-actuals.jsonl",m=".paradigm/learned/token-estimates.json";function h(i,l){if(i.length===0)return 0;let n=[...i].sort((o,s)=>o-s);if(n.length===1)return n[0];let a=l*(n.length-1),e=Math.floor(a),t=Math.ceil(a);if(e===t)return n[e];let r=a-e;return n[e]+(n[t]-n[e])*r}function b(i){let l=new Map;for(let e of i){let t=e.trim();if(!t)continue;let r;try{r=JSON.parse(t);}catch{continue}let{archetype:o,taskType:s}=r,u=r.actualTokens?.total;if(typeof o!="string"||typeof s!="string"||typeof u!="number"||!Number.isFinite(u))continue;let d=`${o} ${s}`,f=l.get(d);f?f.push(u):l.set(d,[u]);}let n={},a=[];for(let[e,t]of l){let[r,o]=e.split(" "),s=t.length;if(s>=y){let u={min:Math.round(h(t,.1)),max:Math.round(h(t,.9)),n:s};n[r]||(n[r]={}),n[r][o]=u,a.push({archetype:r,taskType:o,n:s,learned:true,band:u});}else a.push({archetype:r,taskType:o,n:s,learned:false});}return a.sort((e,t)=>e.archetype===t.archetype?e.taskType.localeCompare(t.taskType):e.archetype.localeCompare(t.archetype)),{table:n,groups:a}}function k(i){try{let l=p.join(i,g);if(!c.existsSync(l))return null;let n=c.readFileSync(l,"utf8").split(`
3
+ `),{table:a,groups:e}=b(n),t=p.join(i,p.dirname(m));return c.existsSync(t)||c.mkdirSync(t,{recursive:!0}),c.writeFileSync(p.join(i,m),JSON.stringify(a,null,2)+`
4
+ `,"utf8"),{table:a,groups:e,samplesRead:e.reduce((r,o)=>r+o.n,0)}}catch{return null}}export{y as MIN_SAMPLES,b as aggregateActuals,h as percentile,k as rebuildLearnedTable};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{E as assembleCaptainBoard,C as getCaptainToolsList,D as handleCaptainTool,F as proposeClaimantFor}from'./chunk-K7KT6FL3.js';import'./chunk-W3VWORQZ.js';import'./chunk-Q527BPUF.js';import'./chunk-VOPJ47QY.js';import'./chunk-RGSFU2YW.js';import'./chunk-TMDPDIWA.js';import'./chunk-KLBH26PA.js';import'./chunk-GRZQIKST.js';import'./chunk-ACJWUOMA.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';
2
+ export{E as assembleCaptainBoard,C as getCaptainToolsList,D as handleCaptainTool,F as proposeClaimantFor}from'./chunk-VKVVIN6J.js';import'./chunk-3F4QP2Z5.js';import'./chunk-Q527BPUF.js';import'./chunk-VOPJ47QY.js';import'./chunk-RGSFU2YW.js';import'./chunk-TMDPDIWA.js';import'./chunk-KLBH26PA.js';import'./chunk-GRZQIKST.js';import'./chunk-ACJWUOMA.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{z as assembleCaptainBoard,x as getCaptainToolsList,y as handleCaptainTool,A as proposeClaimantFor}from'./chunk-3I3TITBA.js';import'./chunk-4QADCWPU.js';import'./chunk-NKYNHSA5.js';import'./chunk-2KK4JQ55.js';import'./chunk-M7JHVVDW.js';import'./chunk-A5EEY6NO.js';import'./chunk-ACJWUOMA.js';import'./chunk-Q527BPUF.js';import'./chunk-33ERV2MW.js';import'./chunk-VOPJ47QY.js';import'./chunk-GRZQIKST.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
2
+ export{z as assembleCaptainBoard,x as getCaptainToolsList,y as handleCaptainTool,A as proposeClaimantFor}from'./chunk-7BZPDOOQ.js';import'./chunk-4QADCWPU.js';import'./chunk-NKYNHSA5.js';import'./chunk-VR2LLUYE.js';import'./chunk-M7JHVVDW.js';import'./chunk-ACJWUOMA.js';import'./chunk-A5EEY6NO.js';import'./chunk-Q527BPUF.js';import'./chunk-33ERV2MW.js';import'./chunk-VOPJ47QY.js';import'./chunk-GRZQIKST.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
@@ -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-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(`
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-A2T6EACG.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-ILBN2IKJ.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-LFEE6OU7.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-LFEE6OU7.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};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,O,j as j$2,M as M$1,B}from'./chunk-W3VWORQZ.js';import {a as a$1,b as b$3,c as c$1}from'./chunk-M4UMM6DC.js';import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {j as j$1,b as b$2,a as a$4}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as j from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as Y from'os';import ht from'sql.js';var ve={};c(ve,{contentSearch:()=>gt,detectFileRename:()=>Ae,generateFingerprint:()=>xe,levenshteinDistance:()=>Ie,levenshteinSimilarity:()=>se,searchSiblingFiles:()=>Ce,slidingWindowSearch:()=>V});function xe(e){let t=e.split(`
2
+ import {a,O,j as j$2,M as M$1,B}from'./chunk-3F4QP2Z5.js';import {a as a$1,b as b$3,c as c$1}from'./chunk-M4UMM6DC.js';import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {j as j$1,b as b$2,a as a$4}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as j from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as Y from'os';import ht from'sql.js';var ve={};c(ve,{contentSearch:()=>gt,detectFileRename:()=>Ae,generateFingerprint:()=>xe,levenshteinDistance:()=>Ie,levenshteinSimilarity:()=>se,searchSiblingFiles:()=>Ce,slidingWindowSearch:()=>V});function xe(e){let t=e.split(`
3
3
  `).filter(n=>n.trim()!=="");return {firstLine:q(t[0]||""),lastLine:q(t[t.length-1]||""),lineCount:t.length,structuralHash:Le(t)}}function Le(e){let t=e.map(n=>n.trim()).filter(n=>Re.test(n)).map(n=>{let s=n.match(Re);return s?s[1].trim():""}).join("|");return j.createHash("sha256").update(t).digest("hex").slice(0,16)}function q(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function Ie(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,s=t.length;if(n>5e3||s>5e3)return Math.abs(n-s);let r=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)r[a]=a;for(let a=1;a<=s;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(r[c]+1,i[c-1]+1,r[c-1]+o);}[r,i]=[i,r];}return r[n]}function se(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-Ie(e,t)/n}function V(e,t,n,s=3){let{lineCount:r}=t,i=Math.max(1,Math.floor(r*.8)),a=Math.ceil(r*1.2),c=[],o=ne(n);for(let l of [r,i,a])if(!(l>e.length))for(let d=0;d<=e.length-l;d++){let p=e.slice(d,d+l),y=ft(p,t,o);if(y>=.5){let m=p.join(`
4
4
  `);c.push({windowStart:d+1,windowEnd:d+l,similarity:se(ne(m),o),score:y});}}let u=new Map;for(let l of c){let d=u.get(l.windowStart);(!d||l.score>d.score)&&u.set(l.windowStart,l);}return Array.from(u.values()).sort((l,d)=>d.score-l.score).slice(0,s)}function ft(e,t,n){let s=e.filter(p=>p.trim()!=="");if(s.length===0)return 0;let r=0,i=q(s[0]),a=q(s[s.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),r+=c*lt,Le(s)===t.structuralHash&&(r+=ut);let u=s.join(`
5
5
  `),l=se(ne(u),n);l>=.8&&(r+=(l-.8)/.2*dt);let d=s.length/t.lineCount;if(d>=.8&&d<=1.2){let p=1-Math.abs(1-d)/.2;r+=p*pt;}return r}function ne(e){return e.split(`
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a as a$5}from'./chunk-NKYNHSA5.js';import {f,a as a$1,q as q$1,t as t$1,y as y$1,s,x as x$1,w as w$1,v,A}from'./chunk-VR2LLUYE.js';import {w}from'./chunk-M7JHVVDW.js';import {d,g,e,h,j as j$1,f as f$1}from'./chunk-ACJWUOMA.js';import {b as b$2}from'./chunk-A5EEY6NO.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {j,a as a$3,i,b as b$1,h as h$1,g as g$1,c,d as d$2}from'./chunk-GRZQIKST.js';import {b,a}from'./chunk-EK4ZRIFJ.js';import {t,C,p,x,y,r}from'./chunk-D6BSCELB.js';import*as F from'fs';import*as E from'path';import*as J from'js-yaml';import {execSync}from'child_process';import*as _t from'os';b();b();var Rt=".paradigm/navigator.yaml";async function Qe(n){let e=E.join(n,Rt);if(!F.existsSync(e))return {config:null,configPath:null};try{let o=F.readFileSync(e,"utf8");return {config:J.load(o),configPath:e}}catch(o){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function Ye(n,e,o){switch(e.intent){case "find":return Ft(n,e.target||"");case "explore":return It(n,e.target||"");case "context":return At(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Ft(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Ot(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=ue(t.paths,n),t}function It(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=ue(t.paths,n),t}function At(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Nt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(d=>c.includes(d)||d.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=ue(t.paths,n),t}function Ot(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Nt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function ue(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function ge(n,e){let o=[];for(let[t$1,r]of n.siblingIndices){let s=t(r.index,e);for(let i of s)o.push({project:t$1,symbol:`${t$1}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function Xe(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=C(s.index);for(let c of a){let d=c.references||[],p=c.description||"",u=d.some(S=>S===t||S===e||S.endsWith(`/${t}`)),P=p.includes(t);(u||P)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}var Tt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Bn(){return [Tt]}async function tt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await Qe(o.rootDir);if(r.config||(r={config:Wt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await f.getOrCompute(s,()=>{let c=Ye(r.config,t,o.rootDir),d={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(d.auto_generated=true,d.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(d.note="No paths found.",d.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(d.tip=d.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let p=ge(o.workspace,t.target);p.length>0&&(d.workspaceResults=p.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})),d.note="Not found locally. Found in workspace siblings.",d.recovery=void 0);}else if(t.intent==="context"&&t.task){let p=ge(o.workspace,t.task);p.length>0&&(d.workspaceContext=p.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})));}}return JSON.stringify(d,null,2)}),a=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}try{let c=E.join(o.rootDir,".paradigm",".nav-called");F.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a}}function Wt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=C(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function ot(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let d of i)try{if(a=execSync(d,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
+ `);for(let d of c.slice(0,t)){let p=d.match(/^(.+?):(\d+):(.*)$/);if(p){let[,u,P,S]=p,v=E.relative(n,u),y="unknown";v.includes(".purpose")||v.includes("portal.yaml")?y="purpose":S.includes("//")||S.includes("#")||S.includes("*")?y="comment":y="code",r.push({filePath:v,line:parseInt(P,10),content:S.trim().slice(0,200),context:y});}}return r}b();var Ht=30*1e3,st=new Map;async function rt(n){let e=E.resolve(n),o=st.get(e);if(o&&Date.now()-o.loadedAt<Ht)return o.index;let t=await Mt(e);return t&&st.set(e,{index:t,loadedAt:Date.now()}),t}async function Mt(n){let e=E.join(n,".paradigm","flow-index.json");if(!F.existsSync(e))return null;try{let o=F.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function Bt(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let d=s.steps.slice(c+1).map(p=>p.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:d,validation:s.validation});}}return t}function it(n,e){let o=Bt(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function to(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function se(n,e,o){if(n!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r$1=3,includeWorkspace:s=false,response_format:i}=e,a=p(o.index,t);if(!a){let m=Jt(o.rootDir,t);return a$1(m.length,n),{handled:true,text:m}}let c=Math.min(Math.max(r$1||3,1),5),d=x(o.index,t),p$1=new Set([t]),u=new Map;function P(m,C){if(C>=c)return;let x$1=[];for(let b of m){if(p$1.has(b))continue;p$1.add(b);let D=x(o.index,b);for(let T of D)p$1.has(T.symbol)||x$1.push(T.symbol);}x$1.length>0&&(u.set(C+1,x$1),P(x$1,C+1));}P(d.map(m=>m.symbol),1);let S=new Set;for(let[,m]of u)for(let C of m)C!==t&&!d.find(x=>x.symbol===C)&&S.add(C);let v=y(o.index,t),y$1=d.length+S.size,j="low";y$1>10?j="high":y$1>3&&(j="medium");let N=await rt(o.rootDir),R=null;if(N){let m=it(N,t);m.totalFlows>0&&(m.impactLevel==="high"&&j==="low"?j="medium":m.impactLevel==="high"&&(j="high"),R={totalFlows:m.totalFlows,affectedFlows:m.affectedFlows.map(C=>({flowId:C.flowId,impactLevel:C.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${C.stepAffected.position}, affects ${C.downstreamSteps.length} downstream steps`})),validationSuggestion:m.validationCommands.length>0?`Run: ${m.validationCommands[0]}`:void 0});}let $=new Set([t,...d.map(m=>m.symbol),...S]),I=[];try{let m=r(o.index,"gate");for(let C of m)$.has(C.symbol)&&I.push({gate:C.symbol,description:C.description});for(let C of d)C.type==="gate"&&!I.find(x=>x.gate===C.symbol)&&I.push({gate:C.symbol,description:C.description});}catch{}let l={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:j,analysis:{directlyAffected:d.map(m=>({symbol:m.symbol,type:m.type,description:m.description})),indirectlyAffected:Array.from(S),indirectByLevel:Object.fromEntries(u),dependsOn:v.map(m=>({symbol:m.symbol,type:m.type}))},summary:{directCount:d.length,indirectCount:S.size,totalAffected:y$1,dependsOnCount:v.length,levelsAnalyzed:c},recommendation:Gt(j)};R&&(l.affectedFlows=R),I.length>0&&(l.affectedGates=I),l.suggestedReviewScope=qt(j,d.length,S.size,I.length,R?.totalFlows??0);try{let m=await q$1(o.rootDir,t);m.length>0&&(l.personas_affected=m,m.length>2&&j==="low"&&(l.impact="medium"));}catch{}try{let m=w(o.rootDir,t);m.length>0&&(l.university_content_affected=m.map(C=>({id:C.id,title:C.title,type:C.type,stale:C.stale})));}catch{}if(s&&o.workspace){let m=Xe(o.workspace,t);if(m.length>0){l.workspaceImpact={siblings:m.map(x=>({project:x.project,references:x.references.map(b=>({symbol:b.symbol,type:b.type,description:b.description}))}))};let C=m.reduce((x,b)=>x+b.references.length,0);C>0&&j==="low"&&(l.impact="medium"),C>5&&(l.impact="high");}}let k=i==="concise"?{symbol:l.symbol,impact:l.impact,summary:l.summary}:l,A=JSON.stringify(k,null,2);return a$1(A.length,n),{handled:true,text:A}}function Jt(n,e){let o=ot(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Gt(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function qt(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var Ut=30*1e3,ye=new Map,ct=".paradigm/wisdom";async function lt(n){let e=E.resolve(n),o=ye.get(e);if(o&&Date.now()-o.loadedAt<Ut)return o.context;let t=await zt(e);return ye.set(e,{context:t,loadedAt:Date.now()}),t}async function zt(n){let e$1=E.join(n,ct),o=F.existsSync(e$1),[t,r,s,i]=o?await Promise.all([Vt(e$1),Kt(e$1),Qt(e$1),Yt(e$1)]):[null,[],null,[]],a=[],c=[],d$1=null;try{a=d(),c=e(),d$1=f$1();}catch{}let p=new Set(r.map(y=>y.id)),u=r.map(y=>({...y,scope:"project"}));for(let y of a)p.has(y.id)||u.push({...y,scope:"global"});let P=new Set(i.map(y=>y.id)),S=i.map(y=>({...y,scope:"project"}));for(let y of c)P.has(y.id)||S.push({...y,scope:"global"});let v=t;if(d$1&&!t)v=d$1;else if(d$1&&t){let y={...t.by_symbol};if(d$1.by_symbol)for(let[j,N]of Object.entries(d$1.by_symbol))y[j]||(y[j]=N);v={...t,by_symbol:y,global:{...d$1.global,...t.global}};}return {preferences:v,antipatterns:u,decisions:S,expertise:s}}function q(n){let e=E.resolve(n);ye.delete(e);}async function Vt(n){let e=E.join(n,"preferences.yaml");if(!F.existsSync(e))return null;try{let o=F.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function Kt(n){let e=E.join(n,"antipatterns.yaml");if(!F.existsSync(e))return [];try{let o=F.readFileSync(e,"utf8");return J.load(o).antipatterns||[]}catch(o){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function Qt(n){let e=E.join(n,"expertise.yaml");if(!F.existsSync(e))return null;try{let o=F.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var at=new Set;async function Yt(n){let e=E.join(n,"decisions");if(!F.existsSync(e))return [];let o=[];try{let t=F.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!at.has(e)&&(at.add(e),a.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=E.join(e,s);try{let a=F.readFileSync(i,"utf8"),c=J.load(a);o.push(c);}catch(a$1){a.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a$1});}}}catch(t){a.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function dt(n,e){return e.map(o=>Xt(n,o))}function Xt(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||re(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||re(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||re(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function pt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||re(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function re(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function ft(n,e){let o=E.join(n,ct),t=E.join(o,"antipatterns.yaml");F.existsSync(o)||F.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(F.existsSync(t))try{let s=F.readFileSync(t,"utf8"),i=J.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),F.writeFileSync(t,J.dump(r,{lineWidth:-1})),q(n);}b();var mt=".paradigm/history";async function ut(n){let e=E.join(n,mt);if(!F.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([Zt(e),en(e)]);return {index:o,validation:t}}async function Zt(n){let e=E.join(n,"index.yaml");if(!F.existsSync(e))return null;try{let o=F.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function en(n){let e=E.join(n,"validation.yaml");if(!F.existsSync(e))return null;try{let o=F.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function ao(n,e){return e.map(o=>tn(n,o))}function tn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function co(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(d=>d.symbol===i);c&&!o.find(d=>d.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let d=c.symbols.filter(p=>p!==i&&!e.includes(p));d.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${d.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function nn(n,e){let o=E.join(n,mt),t=E.join(o,"log.jsonl");F.existsSync(o)||F.mkdirSync(o,{recursive:true});let r=on(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return F.appendFileSync(t,a),r}async function lo(n,e,o,t){return nn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function on(n){let e=1;return F.existsSync(n)&&(e=F.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function ae(n){return n.wisdom||(n.wisdom=await lt(n.rootDir)),n.wisdom}async function vo(n){return n.history||(n.history=await ut(n.rootDir)),n.history}j();b();var gt=false;function Ao(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ht(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await ae(o),i=dt(s,t),a={symbols:t,wisdom:i.map(p=>({symbol:p.symbol,preferences:p.preferences,antipatterns:p.antipatterns.map(u=>({id:u.id,description:u.description,reason:u.reason,alternative:u.alternative,scope:u.scope||"project"})),decisions:p.decisions.map(u=>({id:u.id,title:u.title,status:u.status,decision:u.decision,scope:u.scope||"project"})),experts:p.experts.map(u=>u.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((p,u)=>p+u.antipatterns.length,0),d=i.reduce((p,u)=>p+u.decisions.length,0);a.summary={symbols_with_preferences:i.filter(p=>p.preferences).length,total_antipatterns:c,total_decisions:d,has_experts:i.some(p=>p.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let p={},u=[];for(let P of t){let S=await a$3(o.rootDir,{symbol:P,hasAssessment:!0,limit:100});if(S.length===0)continue;let v={correct:0,partial:0,incorrect:0},y=0,j=0;for(let R of S){let $=R.assessment.verdict;v[$]++,R.confidence!=null&&(y+=R.confidence,j++);}p[P]={total:S.length,...v,avgConfidence:j>0?Math.round(y/j*1e3)/1e3:null};let N=(v.correct+v.partial*.5)/S.length;N<.6&&S.length>=3&&u.push(`Low historical accuracy for ${P}: ${Math.round(N*100)}% across ${S.length} entries. Proceed with extra caution.`);}Object.keys(p).length>0&&(a.calibration=p),u.length>0&&(a.calibration_warnings=u);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a$1,alternative:c,title:d,status:p,rationale:u,consequences:P,scope:S="project"}=e$1;if(t==="antipattern"){if(!i||!a$1||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let v={id:r,symbols:s,description:i,reason:a$1,alternative:c};return S==="global"?g(v):await ft(o.rootDir,v),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:S,message:`Antipattern recorded to ${S} scope`})}}if(t==="decision"){if(!d||!i||!u||!P)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(gt||(gt=true,a.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),S==="global"){let j={id:r,title:d,status:p||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a$1||"",decision:i,rationale:u,consequences:P};return h(j),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let v=a$2(o.rootDir,{title:d,decision:i,rationale:{factors:u.factors,conclusion:u.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:p==="accepted"?"active":p==="proposed"?"proposed":"active",context:a$1||void 0,consequences:P,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(o.rootDir,v.id);return q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:v.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${v.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await ae(o),i=E.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(d=>d.id===r);return a?d().some(d=>d.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g({...a,learned_from:`promoted from ${i}`}),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(d=>d.id===r);return a?e().some(d=>d.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await ae(o),i=pt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Eo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function bt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await v(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(rn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await t$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=y$1(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await w$1(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await x$1(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await t$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=y$1(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s$1=(await s(o.rootDir)).map(a=>{let c=y$1(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s$1.length,current:s$1.filter(a=>a.status==="current").length,stale:s$1.filter(a=>a.status==="stale").length,broken:s$1.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s$1,health:i},null,2)}}default:return {handled:false,text:""}}}function rn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var V=null,he=false;async function be(n){if(V)he||(await V.ensureReady(),he=true);else {let e=E.join(n,".paradigm","sentinel","sentinel.db");V=new a$5(e),await V.ensureReady(),he=true;}return V}async function an(n,e){return (await be(n)).recordPracticeEvent(e)}async function Wo(n,e){return (await be(n)).getPracticeEvents(e)}async function we(n,e){return (await be(n)).getComplianceRate(e)}async function St(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await we(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Lo(n,e,o){let t=[];for(let r of e){let s=await an(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function xt(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var ce={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function vt(){let n=process.env.PARADIGM_AUTHOR;if(n)return Se(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Se(e)}catch{}try{let e=_t.userInfo().username;if(e)return Se(e)}catch{}return "unknown"}function Se(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Ko(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function xe(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(kt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a$1,files_created:c,files_modified:d,lines_added:p,lines_removed:u,commit:P,duration_minutes:S,decisions:v,errors_encountered:y,learnings:j,verification:N,tags:R,meta:$,body:I,linked_lore:l,linked_tasks:k,linked_commits:A$1,confidence:m}=e;if(t==="decision")return a.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:ce.removed_in,successor_tool:ce.successor_tool}),xt(ce);let C;try{let w=new Date(Date.now()-2592e6).toISOString(),h=await we(o.rootDir,{dateFrom:w});if(h.total>0){let f=(await St(o.rootDir,{dateFrom:w})).filter(_=>_.rate<60).map(_=>_.category);C={rate:h.rate,followed:h.followed,skipped:h.skipped,partial:h.partial,weakAreas:f.length>0?f:void 0};}}catch{}let x={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:S,author:vt(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a$1,files_created:c,files_modified:d,lines_added:p,lines_removed:u,commit:P,decisions:v,errors_encountered:y,learnings:j,verification:N,tags:R,meta:$||void 0,habit_compliance:C,body:I,linked_lore:l,linked_tasks:k,linked_commits:A$1,confidence:m!=null&&m>=0&&m<=1?m:void 0},b=await d$2(o.rootDir,x);j$1().setLastLoreEntryId(b);try{let w=process.env.PARADIGM_AGENT_ID;if(w&&i&&i.length>0){let{updateExpertiseFromLore:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,w,{symbols_touched:i,confidence:m!=null&&m>=0&&m<=1?m:void 0});}}catch{}let D=null;try{c&&c.length>=2&&(D=A(o.rootDir,c,d||[]));}catch{}let T;if(e.stream){let w=e.stream,h=w==="auto"?ln(e):w;try{if(h==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:x.agent?.model||"unknown",summary:x.summary,outcome:x.verification?.status==="pass"?"pass":x.verification?.status==="fail"?"fail":"partial",files_modified:x.files_modified,symbols_touched:x.symbols_touched,commit:x.commit,linked_lore:x.id||b}),T="work-log";}else if(h==="journal"&&x.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let f of x.learnings)g(x.agent?.model||"unknown",{trigger:"self_reflection",insight:f,project:o.projectName||"unknown",transferable:!1,linked_work_log:x.id||b});T="journal";}else if(h==="decision"&&x.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let f of x.decisions)g(o.rootDir,{title:f.decision.slice(0,100),decision:f.decision,rationale:f.rationale,participants:[{id:`agent/${x.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:x.symbols_touched,status:"active",linked_lore:x.id||b});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:b,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...D?{protocol_suggestion:D}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let d of s)for(let p of d.symbols_touched)i[p]=(i[p]||0)+1;let a=Object.entries(i).sort(([,d],[,p])=>p-d).slice(0,10).map(([d,p])=>({symbol:d,count:p})),c$1={};for(let d of s){let p=d.author;c$1[p]||(c$1[p]={count:0,lastActive:d.timestamp,hasAgent:d.agent!=null}),c$1[p].count++,d.agent&&(c$1[p].hasAgent=true),d.timestamp>c$1[p].lastActive&&(c$1[p].lastActive=d.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(kt),hotSymbols:a,authors:Object.entries(c$1).map(([d,p])=>({id:d,hasAgent:p.hasAgent,entries:p.count,lastActive:p.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,d]of Object.entries(s))d!==void 0&&(i[c]=d);let a=await g$1(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:vt(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let P=process.env.PARADIGM_AGENT_ID;if(P&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:S}=await import('./agent-loader-W3RQJVW7.js');S(o.rootDir,P,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let d=r==="correct"?1:r==="partial"?.5:0,p=i.confidence!=null?d-i.confidence:null,u=p!=null?p>.1?"Under-confident (actual outcome better than predicted)":p<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:p,deltaDescription:u,message:c?`Assessment recorded: ${r}${p!=null?` (delta: ${p>0?"+":""}${p.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(I=>I.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},d=0,p=0,u=0;for(let I of r){let l=I.assessment.verdict;c[l]++;let k=l==="correct"?1:l==="partial"?.5:0;d+=k,I.confidence!=null&&(p+=I.confidence,u+=Math.abs(k-I.confidence));}let P=i>0?d/i:0,S=a>0?p/a:null,v=a>0?d/i-p/a:null,y=a>0?1-u/a:null,j=e.groupBy,N;if(j&&i>0){let I=new Map;for(let l of r){let k=[];j==="symbol"?k=l.symbols_touched||[]:j==="tag"?k=l.tags||[]:j==="type"&&(k=[l.type||"agent-session"]);for(let A of k)I.has(A)||I.set(A,[]),I.get(A).push(l);}N=Array.from(I.entries()).map(([l,k])=>{let A=k.filter(D=>D.confidence!=null),m={correct:0,partial:0,incorrect:0},C=0,x=0,b=0;for(let D of k){let T=D.assessment.verdict;m[T]++;let w=T==="correct"?1:T==="partial"?.5:0;C+=w,D.confidence!=null&&(x+=D.confidence,b+=Math.abs(w-D.confidence));}return {key:l,total:k.length,accuracyRate:C/k.length,avgConfidence:A.length>0?x/A.length:null,calibrationScore:A.length>0?1-b/A.length:null,verdictBreakdown:m}}).sort((l,k)=>k.total-l.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),y!=null&&(y>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),v!=null&&(v>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):v<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(P*1e3)/1e3,avgConfidence:S!=null?Math.round(S*1e3)/1e3:null,avgDelta:v!=null?Math.round(v*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:R},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function ln(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function kt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function ls(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ds(n,e,o){return n==="paradigm_captain_brief"?dn(e,o):n==="paradigm_captain_debrief"?pn(e,o):n==="paradigm_captain_board"?gn(e,o):{handled:false,text:""}}async function dn(n,e){let o=n.taskDescription,t$1=n.symbols||[],r=n.depth||"standard",s=E.join(e.rootDir,".paradigm"),i=E.join(s,".cid-session"),a=E.join(s,".cid-briefed");try{F.existsSync(a)&&F.unlinkSync(a);let w={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};F.mkdirSync(s,{recursive:!0}),F.writeFileSync(i,JSON.stringify(w,null,2),"utf8");}catch{}let c=_n(o),d=[],p=new Set;for(let w of t$1)if(!p.has(w)){p.add(w);let h=jt(w);d.push({id:w,type:h,description:"Provided as anchor symbol"});}let u=[];try{for(let w of c.slice(0,3)){let g=t(e.index,w).slice(0,5);for(let f of g)if(!p.has(f.symbol)){p.add(f.symbol);let _=Pn(f.type);d.push({id:f.symbol,type:_,description:f.description||"",file:f.file}),u.push(f.symbol);}}}catch{}let P={directories:[],files:[]};try{let w=await tt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(w.handled){let h=JSON.parse(w.text);if(h.files)for(let g of h.files){let f=typeof g=="string"?g:g.path||g.file||"";f&&P.files.push(f);}if(h.directories)for(let g of h.directories){let f=typeof g=="string"?g:g.path||g.directory||"";f&&P.directories.push(f);}if(h.symbols)for(let g of h.symbols){let f=typeof g=="string"?g:g.id;f&&!p.has(f)&&(p.add(f),d.push({id:f,type:jt(f),description:typeof g=="object"&&g.description||""}));}}}catch{}let S=new Set(P.directories);for(let w of P.files){let h=E.dirname(w);h&&h!=="."&&S.add(h);}let v=d.slice(0,r==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&v.length>0)for(let w of v)try{let h=await se("paradigm_ripple",{symbol:w.id,depth:2,response_format:"concise"},e);if(h.handled){let g=JSON.parse(h.text);if(g.analysis){for(let f of g.analysis.directlyAffected||[]){let _=f.symbol||f;_&&!y.affectedSymbols.includes(_)&&y.affectedSymbols.push(_);}for(let f of g.analysis.indirectlyAffected||[])f&&!y.affectedSymbols.includes(f)&&y.affectedSymbols.push(f);}if(g.affectedFlows?.affectedFlows)for(let f of g.affectedFlows.affectedFlows){let _=f.flowId||f;_&&!y.affectedFlows.includes(_)&&y.affectedFlows.push(_);}if(g.affectedGates)for(let f of g.affectedGates){let _=f.gate||f;_&&!y.affectedGates.includes(_)&&y.affectedGates.push(_);}g.impact==="high"&&(y.fragileSymbols.includes(w.id)||y.fragileSymbols.push(w.id));}}catch{}let j=[],N=Cn(o);if(N.length>0)try{let{handleGatesForRoute:w}=await import('./tools-YW3Q27UI.js').catch(()=>({handleGatesForRoute:null})),h=E.join(e.rootDir,"portal.yaml");if(F.existsSync(h)){let g=F.readFileSync(h,"utf8");for(let f of N){let _=g.includes(f);j.push({route:f,gate:"^authenticated",declared:_});}}else for(let g of N)j.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&d.length>0)try{let w=d.slice(0,5).map(g=>g.id),h=await ht("paradigm_wisdom_context",{symbols:w,include_global:!0},e);if(h.handled){let g=JSON.parse(h.text);if(g.antipatterns)for(let f of g.antipatterns.slice(0,3)){let _=f.pattern||f.description||f.text||String(f);_&&!R.includes(_)&&R.push(_);}if(g.wisdom?.antipatterns)for(let f of g.wisdom.antipatterns.slice(0,3)){let _=f.pattern||f.description||String(f);_&&!R.includes(_)&&R.push(_);}}}catch{}let $={matched:false};try{let w=await bt("paradigm_protocol_search",{task:o,limit:1},e);if(w.handled){let h=JSON.parse(w.text),g=h.matches||h.protocols||h.results||[];if(g.length>0){let f=g[0];$={matched:!0,id:f.id,name:f.name||f.title,steps:(f.steps||[]).slice(0,5).map(_=>typeof _=="string"?_:_.description||String(_))};}}}catch{}let I=[];if(r!=="quick")try{let w=d[0]?.id,h={limit:r==="deep"?5:3};w&&(h.symbol=w);let g=await xe("paradigm_lore_search",h,e);if(g.handled){let _=JSON.parse(g.text).entries||[];for(let M of _.slice(0,3))I.push({id:M.id,summary:(M.summary||M.title||"").slice(0,100),relevance:w?`Related to ${w}`:"Recent project history"});}}catch{}let l=Array.from(S),k=0;for(let w of l){let h=E.join(e.rootDir,w,".purpose");if(F.existsSync(h))try{F.readFileSync(h,"utf8").trim().length>50&&k++;}catch{}}let A=l.length>0?k/l.length:.5,m=jn(A),C=Dn(A,m,l.length),x=y.affectedSymbols.length+P.files.length,b=x>20?"large":x>8?"medium":x>2?"small":"tiny",D={territory:{directories:l.slice(0,10),files:P.files.slice(0,10),estimatedScope:b},symbols:d.slice(0,10),blastRadius:y,gates:j,protocol:$,warnings:R,coverage:{score:A,label:m,note:C},loreRefs:I,archMap:b$2(e.rootDir),renderedBrief:""};D.renderedBrief=Rn(D);try{let w={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:A};F.writeFileSync(i,JSON.stringify(w,null,2),"utf8");}catch{}let T=JSON.stringify(D,null,2);return a$1(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function pn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a$2=E.join(e.rootDir,".paradigm"),c=E.join(a$2,".cid-briefed"),d=E.join(a$2,".pending-review"),p=new Set;for(let b of r){let D=E.dirname(b);D&&D!=="."&&p.add(D);}let u=0,P=p.size;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(F.existsSync(D))try{F.readFileSync(D,"utf8").trim().length>50&&u++;}catch{}}let S=P>0?u/P:1,v=[],y=[];for(let b of p){let D=E.join(e.rootDir,b,".purpose"),T=E.join(e.rootDir,b),w=false;if(F.existsSync(D))try{w=F.readFileSync(D,"utf8").trim().length>50;}catch{}if(w){if(r.some(g=>E.dirname(g)===b&&s.length>0)){y.push(b);try{let g=JSON.stringify({path:b,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});F.appendFileSync(d,g+`
6
+ `,"utf8");}catch{}}}else try{if(!F.existsSync(T))continue;let h=E.basename(b),g=Fn(h,b,r);F.writeFileSync(D,g,"utf8"),v.push(b),y.push(b);try{let f=JSON.stringify({path:b,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(_=>E.dirname(_)===b).join(", ")}`,timestamp:new Date().toISOString()});F.appendFileSync(d,f+`
7
+ `,"utf8");}catch{}}catch{}}let j=0;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(F.existsSync(D))try{F.readFileSync(D,"utf8").trim().length>50&&j++;}catch{}}let N=P>0?j/P:1,R="";try{let b=await xe("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:S,after:N},coverageAdded:v,...i?{notes:i}:{}}},e);if(b.handled){let D=JSON.parse(b.text);R=D.id||D.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=un(a$2),!$.ranThisSession)try{let{runPostflightLearning:b}=await import('./ambient-VCTUHHIG.js');await b(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(b){$.selfHealError=b instanceof Error?b.message:String(b),a.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:D}=await import('./propose-block-ZEMEWJQF.js');await D("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let I=false;try{let b={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};F.mkdirSync(a$2,{recursive:!0}),F.writeFileSync(c,JSON.stringify(b,null,2),"utf8"),I=!0;}catch{}let l={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:S,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let b=E.join(a$2,"events","session-log.jsonl");if(F.existsSync(b)){let w=F.readFileSync(b,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),h=new Map;for(let g of w)try{let f=JSON.parse(g),_=f.agentId||f.agent||f.role||"";if(!_)continue;h.has(_)||h.set(_,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let M=h.get(_),ve=f.action||f.event||f.message||"";if(ve&&M.contributions.push(String(ve).slice(0,120)),Array.isArray(f.symbols))for(let K of f.symbols)M.symbolsTouched.add(String(K));let ke=f.symbol||"";if(ke&&M.symbolsTouched.add(ke),Array.isArray(f.patterns))for(let K of f.patterns)M.patternsObserved.includes(String(K))||M.patternsObserved.push(String(K));}catch{}for(let[g,f]of h.entries())l.agentContributions.push({agentId:g,contribution:f.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(f.symbolsTouched).slice(0,10),patternsObserved:f.patternsObserved.slice(0,5)});}}catch{}let k=l.agentContributions.length;l.agentContributions.length===0&&l.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),k>0&&a$4(e.rootDir,{verdicts:k,source:"debrief"});let A={coverageAdded:v,delegatedToDocumentor:y,loreEntryId:R,coverageScore:{before:S,after:N,delta:N-S},stopHookCleared:I,postflight:$,sessionInsights:l},m=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
9
+ `),x=JSON.stringify(A,null,2)+`
10
+ `+m;return a$1(x.length,"paradigm_captain_debrief"),{handled:true,text:x}}var fn=E.join("events","settlement-liveness.jsonl"),mn=360*60*1e3;function un(n){let e=E.join(n,fn);if(!F.existsSync(e))return false;try{let t=F.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-mn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function gn(n,e){let o=n.action||"read";if(o==="claim")return vn(n,e);if(o==="advance")return kn(n,e);let t=await Sn(e.rootDir,{},e),r=JSON.stringify(t,null,2);return a$1(r.length,"paradigm_captain_board"),{handled:true,text:r}}function yn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function hn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Ct(n,e){let o=Dt(n).slice(0,3),t=[];for(let r of o)try{let s=await se("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var bn=/[#$^!~][a-z][a-z0-9-]*/gi;function Dt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(bn)||[];for(let t of o)e.add(t);return Array.from(e)}async function wn(n,e){let o=Dt(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await se("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,d=a.analysis?.indirectlyAffected?.length??0;t+=c*2+d,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Pt={high:0,medium:1,low:2};async function Sn(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-EIXPKHA3.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(l){a.flow("$captain-board").warn("Board task load failed",{error:l instanceof Error?l.message:String(l)});}let i=s.filter(l=>l.external_ref?.provider==="orchestration"&&!l.parentTaskId&&!l.settledAt),a$1=[];for(let l of i){let k=hn(s.filter(m=>m.parentTaskId===l.id)),A=[];for(let m of k){let C=t?await Ct(m,t):[];A.push({taskId:m.id,blurb:m.blurb,stage:m.stage,status:m.status,claimant:m.claimant,dependsOn:m.dependsOn||[],fragileSymbols:C});}a$1.push({epicTaskId:l.id,blurb:l.blurb,runStatus:yn(l,k),settledAt:l.settledAt,nodes:A});}let c=s.filter(l=>l.status==="open"&&!l.claimant),d=[];for(let l of c){let{score:k,fragile:A}=t?await wn(l,t):{score:0,fragile:[]},m;e.proposeClaimants&&(m=await xn(l,n)),d.push({taskId:l.id,blurb:l.blurb,priority:l.priority,tags:l.tags||[],rippleScore:k,fragileSymbols:A,proposedClaimant:m});}d.sort((l,k)=>{if(k.rippleScore!==l.rippleScore)return k.rippleScore-l.rippleScore;let A=(Pt[l.priority]??1)-(Pt[k.priority]??1);return A!==0?A:k.taskId.localeCompare(l.taskId)});let p=s.filter(l=>l.status==="in-progress").length,u=s.filter(l=>l.status==="open").length,P=new Set(i.map(l=>l.id)),S=new Set(c.map(l=>l.id)),v=[];for(let l of s){if(!l.id||l.status==="done"||l.status==="shelved"||l.parentTaskId||P.has(l.id)||S.has(l.id))continue;let k=t?await Ct(l,t):[];v.push({taskId:l.id,blurb:l.blurb,stage:l.stage,status:l.status,claimant:l.claimant,dependsOn:l.dependsOn||[],fragileSymbols:k});}let{validateTaskDag:y}=await import('./task-loader-EIXPKHA3.js'),j=y(s),N=a$1.filter(l=>!l.settledAt&&l.nodes.length>0&&l.nodes.every(k=>k.status==="done"||k.status==="shelved")).map(l=>({epicTaskId:l.epicTaskId,blurb:l.blurb,reason:"all children terminal but run never settled"})),R=7,$=Date.now(),I=s.filter(l=>l.status==="open"&&l.claimant?.kind==="archetype"&&!l.started_at).map(l=>({task:l,ageDays:Math.floor(($-new Date(l.created).getTime())/864e5)})).filter(({ageDays:l})=>Number.isFinite(l)&&l>=R).map(({task:l,ageDays:k})=>({taskId:l.id,blurb:l.blurb,claimant:l.claimant,ageDays:k}));return {runs:a$1,unclaimed:d,loose:v,summary:{runs:a$1.length,open:u,inFlight:p,unclaimed:d.length,loose:v.length},integrity:j.length>0?j:void 0,settlementDebt:N.length>0?N:void 0,staleClaims:I.length>0?I:void 0}}async function xn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-4MJKBSGM.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function vn(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-EIXPKHA3.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a$1=i.claimant;if(a$1&&a$1.kind!=="archetype"&&t.kind==="archetype")return a.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a$1.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a$1.kind}:${a$1.ref}; archetype proposal cannot override`,claimant:a$1})};let c=await s(e.rootDir,o,{claimant:t});return a.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function kn(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-EIXPKHA3.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a$1=await s(e.rootDir,o,{blocked_on:t});return a.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a$1}),{handled:true,text:JSON.stringify({ok:a$1,taskId:o,blocked_on:t,status:i.status})}}function _n(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Cn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function jt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Pn(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function jn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Dn(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Rn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(p=>p.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let p=n.gates.slice(0,2).map(u=>`${u.route} \u2192 ${u.gate} (${u.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${p.join("; ")}`);}if(n.protocol.matched){let p=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${p} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let d=Math.round(n.coverage.score*100);return e.push(`Coverage: ${d}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
12
+ `)}function Fn(n,e,o){let r=o.filter(s=>E.dirname(s)===e).slice(0,3).map(s=>`# - ${E.basename(s)}`).join(`
13
+ `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
+ # Delegate to Scribe (Documentor) for rich documentation
15
+ name: ${n}
16
+ description: "TODO: describe what this directory/module does"
17
+ context:
18
+ - "Stub created by Cid during coverage audit \u2014 update with real context"
19
+ ${r?`# Key files touched:
20
+ ${r}`:""}
21
+ components:
22
+ ${n}:
23
+ description: "TODO: describe this component"
24
+ tags: []
25
+ `}export{xn as A,ge as a,Bn as b,tt as c,ot as d,rt as e,it as f,to as g,se as h,ao as i,co as j,nn as k,lo as l,vo as m,Ao as n,ht as o,Eo as p,bt as q,Wo as r,we as s,St as t,Lo as u,Ko as v,xe as w,ls as x,ds as y,Sn as z};