@a-company/paradigm 7.3.0 → 7.5.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 (115) hide show
  1. package/dist/{accept-orchestration-JA3A3TSU.js → accept-orchestration-NFNY5A4Q.js} +1 -1
  2. package/dist/{aggregate-H7SB2UYT.js → aggregate-647KIGV6.js} +1 -1
  3. package/dist/ambient-5TA5CD7Z.js +2 -0
  4. package/dist/{ambient-TFLZFV5Y.js → ambient-N24SR3BC.js} +1 -1
  5. package/dist/ambient-W3SPKLKC.js +2 -0
  6. package/dist/{arch-loader-YVOS3QRY.js → arch-loader-6TDQOSUE.js} +1 -1
  7. package/dist/arch-loader-NAGXLWUQ.js +2 -0
  8. package/dist/{beacon-WVN264OT.js → beacon-4XQSMTNN.js} +1 -1
  9. package/dist/captain-2MEKZKJS.js +2 -0
  10. package/dist/captain-V5XPN4UP.js +2 -0
  11. package/dist/{chunk-IBKCMLOW.js → chunk-43H6PB2A.js} +27 -27
  12. package/dist/chunk-54C2PETP.js +12 -0
  13. package/dist/{chunk-RGSFU2YW.js → chunk-5LIE2QMS.js} +1 -1
  14. package/dist/{chunk-ACJWUOMA.js → chunk-74NGU6YN.js} +1 -1
  15. package/dist/chunk-ABHILQLA.js +42 -0
  16. package/dist/{chunk-VR2LLUYE.js → chunk-AMZ3ESAK.js} +2 -2
  17. package/dist/chunk-BTMT4K73.js +93 -0
  18. package/dist/{chunk-MBKTVQS2.js → chunk-BXKFSYIN.js} +1 -1
  19. package/dist/chunk-CHFY3JSF.js +504 -0
  20. package/dist/chunk-D2T5AV5N.js +504 -0
  21. package/dist/{chunk-6VZSOQ7Y.js → chunk-DQ4MMMTP.js} +1 -1
  22. package/dist/chunk-F3OBFUOE.js +2 -0
  23. package/dist/chunk-GADXREYG.js +18 -0
  24. package/dist/{chunk-A5EEY6NO.js → chunk-HGT7RNOL.js} +1 -1
  25. package/dist/chunk-HLPYCWE5.js +6 -0
  26. package/dist/chunk-IGB2CIMK.js +93 -0
  27. package/dist/{chunk-27EK3OQZ.js → chunk-JJ3AUHQU.js} +1 -1
  28. package/dist/chunk-JOHPASZG.js +4 -0
  29. package/dist/{chunk-7BZPDOOQ.js → chunk-JOWT6J4C.js} +4 -4
  30. package/dist/chunk-L4MKNG56.js +42 -0
  31. package/dist/chunk-PRZZL57E.js +7 -0
  32. package/dist/{chunk-SD3KVW5Q.js → chunk-QBIME67A.js} +1 -1
  33. package/dist/{chunk-KA6QEI3C.js → chunk-QTMJVEEW.js} +1 -1
  34. package/dist/chunk-SGLIPRIC.js +3 -0
  35. package/dist/chunk-SOVBBLFK.js +6 -0
  36. package/dist/{chunk-VKVVIN6J.js → chunk-SPU3R5GW.js} +4 -4
  37. package/dist/{chunk-YNFF7XHV.js → chunk-T577TTVG.js} +2 -2
  38. package/dist/{chunk-3F4QP2Z5.js → chunk-VHVUJGZ2.js} +2 -2
  39. package/dist/chunk-WUSTIEYA.js +4 -0
  40. package/dist/{commands-4ENQMHFO.js → commands-RSHKXKXN.js} +1 -1
  41. package/dist/{compliance-3M6COUCO.js → compliance-EFNXWHDL.js} +1 -1
  42. package/dist/{constellation-TIKNCZWR.js → constellation-26225R5K.js} +1 -1
  43. package/dist/{diff-NZSJW3V3.js → diff-G52RYZNF.js} +1 -1
  44. package/dist/dist-N4NYCS3D.js +2 -0
  45. package/dist/dist-O7KGTIYK.js +4 -0
  46. package/dist/{docs-DWU3T2BV.js → docs-2O7HUSBX.js} +1 -1
  47. package/dist/doctor-KGQXLGOQ.js +2 -0
  48. package/dist/graph-slice-2WECDOEN.js +2 -0
  49. package/dist/index.js +5 -5
  50. package/dist/{init-QPMLEQWQ.js → init-JGYCABZZ.js} +1 -1
  51. package/dist/{integrity-FRGF5BFS.js → integrity-YUCXTQX3.js} +1 -1
  52. package/dist/mcp.js +2 -2
  53. package/dist/nomination-engine-3EYXJOZZ.js +2 -0
  54. package/dist/nomination-engine-BUPERVPR.js +2 -0
  55. package/dist/notebook-loader-QM4KUT4R.js +2 -0
  56. package/dist/{orchestrate-C7SI4J7C.js → orchestrate-RIKQB2DV.js} +1 -1
  57. package/dist/{orchestration-S2ESNKSA.js → orchestration-GFNPCEUU.js} +1 -1
  58. package/dist/orchestration-I62QXOWV.js +2 -0
  59. package/dist/{platform-server-IOWHNS7Q.js → platform-server-AAEDDBS3.js} +2 -2
  60. package/dist/{probe-G3TKOJYW.js → probe-GD3VDWGT.js} +1 -1
  61. package/dist/reindex-FNL4QRUZ.js +2 -0
  62. package/dist/reindex-N4NTDLJY.js +2 -0
  63. package/dist/{review-WHRNLW2W.js → review-YG4LWV22.js} +1 -1
  64. package/dist/{ripple-B6U7263T.js → ripple-S6VBP5C6.js} +1 -1
  65. package/dist/sentinel.js +1 -1
  66. package/dist/{serve-PWAFVYYC.js → serve-NPRYOGQX.js} +1 -1
  67. package/dist/session-tracker-HYN6ZYPH.js +2 -0
  68. package/dist/{session-work-log-T2IE4Y4T.js → session-work-log-KZX4PGUL.js} +1 -1
  69. package/dist/{setup-L5OP24US.js → setup-GPOTHS3N.js} +1 -1
  70. package/dist/{shift-HGXZ5THV.js → shift-ZIJTQ5SW.js} +2 -2
  71. package/dist/{snapshot-MT5L6XE4.js → snapshot-2ARNF3U2.js} +1 -1
  72. package/dist/{status-4QGKLOP6.js → status-NTWWESOR.js} +1 -1
  73. package/dist/{summary-6QNVQZJV.js → summary-4QXYLXAB.js} +1 -1
  74. package/dist/{sync-layer-C2PF273N.js → sync-layer-Z266WBWF.js} +1 -1
  75. package/dist/{task-PRLQ4VPK.js → task-6F527BNU.js} +1 -1
  76. package/dist/{task-loader-EIXPKHA3.js → task-loader-75NBBLRQ.js} +1 -1
  77. package/dist/{task-loader-LFEE6OU7.js → task-loader-INPLZRG5.js} +1 -1
  78. package/dist/{task-settlement-ZXOY4YGX.js → task-settlement-3ROAHAND.js} +2 -2
  79. package/dist/{task-settlement-A2T6EACG.js → task-settlement-F7CIKUG3.js} +2 -2
  80. package/dist/{team-KP4HMUB5.js → team-PFJTOCPM.js} +1 -1
  81. package/dist/tools-MAH6K5UL.js +142 -0
  82. package/dist/tools-Z354SXGS.js +2 -0
  83. package/dist/{workspace-4D4TQ637.js → workspace-HADUT5XT.js} +1 -1
  84. package/package.json +2 -1
  85. package/dist/ambient-OW5M5LVN.js +0 -2
  86. package/dist/ambient-VCTUHHIG.js +0 -2
  87. package/dist/arch-loader-G3AAM4E2.js +0 -2
  88. package/dist/captain-ILBN2IKJ.js +0 -2
  89. package/dist/captain-J4FZ5PRU.js +0 -2
  90. package/dist/chunk-33ERV2MW.js +0 -18
  91. package/dist/chunk-5VR7FKS5.js +0 -93
  92. package/dist/chunk-7HUPVOAY.js +0 -504
  93. package/dist/chunk-D6BSCELB.js +0 -2
  94. package/dist/chunk-FG3M6VVO.js +0 -30
  95. package/dist/chunk-HSY75GRR.js +0 -6
  96. package/dist/chunk-KAUGQMXU.js +0 -4
  97. package/dist/chunk-L3AOKDMU.js +0 -93
  98. package/dist/chunk-O4ADSTSY.js +0 -504
  99. package/dist/chunk-RVXQNS6K.js +0 -30
  100. package/dist/chunk-TMDPDIWA.js +0 -3
  101. package/dist/chunk-XBK244QR.js +0 -6
  102. package/dist/chunk-Y76OIMDO.js +0 -7
  103. package/dist/chunk-ZSWXLFN7.js +0 -12
  104. package/dist/dist-PW5YPGFF.js +0 -2
  105. package/dist/dist-RXYJK7AZ.js +0 -2
  106. package/dist/doctor-CBZYYQQH.js +0 -2
  107. package/dist/nomination-engine-EFXDEPZN.js +0 -2
  108. package/dist/nomination-engine-YRHZZZUN.js +0 -2
  109. package/dist/notebook-loader-TZVIMNDJ.js +0 -2
  110. package/dist/orchestration-4MJKBSGM.js +0 -2
  111. package/dist/reindex-G2JLIGOQ.js +0 -2
  112. package/dist/reindex-JR3PXYQE.js +0 -2
  113. package/dist/session-tracker-BZ7FU4AT.js +0 -2
  114. package/dist/tools-NOMEIBS7.js +0 -2
  115. package/dist/tools-YW3Q27UI.js +0 -142
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import {c,b}from'./chunk-5TAVYPOV.js';import*as e from'fs';import*as o from'path';var L={};c(L,{appendSessionWorkEntry:()=>N,appendVerdictEntry:()=>O,clearActivityMetrics:()=>J,clearSessionWorkLog:()=>C,countNotebookReferences:()=>_,getAgentEntries:()=>h,getAgentVerdicts:()=>j,getContributingAgents:()=>M,getNotebookReferences:()=>v,getSessionActivitySummary:()=>W,markIterationRevisionsConsumed:()=>A,markVerdictsConsumed:()=>P,readPendingIterationRevisions:()=>F,readPendingVerdicts:()=>R,readSessionWorkLog:()=>g,recordActivityMetric:()=>w,recordNotebookReference:()=>D});function N(r,n){try{let t=o.join(r,y),i=o.dirname(t);if(e.existsSync(i)||e.mkdirSync(i,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
3
+ `).filter(c=>c.trim()).length>=I)return;let f=JSON.stringify(n)+`
4
+ `;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-W3RQJVW7.js').then(({loadAgentProfile:a,saveAgentProfile:s})=>{try{let c=a(r,n.agent);if(c?.expertise){let l=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(l!==0){for(let b of n.symbols){let u=c.expertise.find(k=>k.symbol===b);u&&(u.confidence=Math.max(0,Math.min(1,u.confidence+l)),u.sessions=(u.sessions||0)+1,u.lastTouch=new Date().toISOString());}s(n.agent,c,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(r){try{let n=o.join(r,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
5
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(r){try{let n=o.join(r,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function O(r,n){try{let t=o.join(r,p),i=o.dirname(t);e.existsSync(i)||e.mkdirSync(i,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
6
+ `,"utf8");}catch{}}function R(r){try{let n=o.join(r,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
7
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function P(r,n){try{let t=o.join(r,p);if(!e.existsSync(t))return;let i=new Set(n),a=e.readFileSync(t,"utf8").trim().split(`
8
+ `).filter(s=>s.trim()).map(s=>{try{let c=JSON.parse(s);return c.nominationId&&i.has(c.nominationId)?JSON.stringify({...c,consumed:!0}):s}catch{return s}});e.writeFileSync(t,a.join(`
9
+ `)+`
10
+ `,"utf8");}catch{}}function F(r){try{let n=o.join(r,m);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
11
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="iteration-revision"&&!t.consumed):[]}catch{return []}}function A(r,n){try{let t=o.join(r,m);if(!e.existsSync(t))return;let i=new Set(n),a=e.readFileSync(t,"utf8").trim().split(`
12
+ `).filter(s=>s.trim()).map(s=>{try{let c=JSON.parse(s);return c.id&&i.has(c.id)?JSON.stringify({...c,consumed:!0}):s}catch{return s}});e.writeFileSync(t,a.join(`
13
+ `)+`
14
+ `,"utf8");}catch{}}function M(r){let n=g(r),t=new Set;for(let i of n)i.agent&&t.add(i.agent);return Array.from(t)}function h(r,n){return g(r).filter(t=>t.agent===n)}function j(r,n){let t=h(r,n),i=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),a=[];for(let s of i)a.push({contribution:s});for(let s of f){let c=a.find(l=>!l.verdict&&l.contribution);c?c.verdict=s:a.push({verdict:s});}return a}function w(r,n){try{let t=o.join(r,d),i=o.dirname(t);e.existsSync(i)||e.mkdirSync(i,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},a=JSON.stringify(f)+`
15
+ `;e.appendFileSync(t,a,"utf8");}catch{}}function B(r){try{let n=o.join(r,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
16
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function W(r){let n=B(r),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let i of n)if(i.toolCallCount!=null&&(t.toolCallCount+=i.toolCallCount),i.responsePayloadBytes!=null&&(t.responsePayloadBytes+=i.responsePayloadBytes),i.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,i.sessionDurationMs)),i.agentId){t.agentBreakdown[i.agentId]||(t.agentBreakdown[i.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[i.agentId];i.toolCallCount!=null&&(f.toolCalls+=i.toolCallCount),i.responsePayloadBytes!=null&&(f.payloadBytes+=i.responsePayloadBytes);}return t}function J(r){try{let n=o.join(r,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function D(r,n,t,i){try{if(t.length===0)return;let f=o.join(r,S),a=o.dirname(f);e.existsSync(a)||e.mkdirSync(a,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...i?{orchestrationId:i}:{}},c=JSON.stringify(s)+`
17
+ `;e.appendFileSync(f,c,"utf8");}catch{}}function v(r){try{let n=o.join(r,S);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
18
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function _(r){return v(r).length}var y,d,p,m,I,S,T=b(()=>{y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",m=".paradigm/events/iteration-revisions.jsonl",I=200,S=".paradigm/events/notebook-refs.jsonl";});export{N as a,g as b,C as c,O as d,R as e,P as f,F as g,A as h,M as i,h as j,j as k,w as l,W as m,J as n,D as o,v as p,_ as q,L as r,T as s};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {r}from'./chunk-D6BSCELB.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r$1=new Set;for(let o of t.tiers)for(let p of o.components)r$1.add(p);let s=new Set;try{let o=r(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r$1.has(o)),h=Array.from(r$1).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {r}from'./chunk-JOHPASZG.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r$1=new Set;for(let o of t.tiers)for(let p of o.components)r$1.add(p);let s=new Set;try{let o=r(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r$1.has(o)),h=Array.from(r$1).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
3
3
  `)}export{g as a,u as b,S as c,b as d,k as e};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {e as e$2,f as f$4}from'./chunk-F3OBFUOE.js';import {C,b,l,x,w,v,z as z$1,p as p$1,r,s as s$1,a,t,A,B,q,g as g$1,h as h$1,f as f$3,j as j$2,i,k}from'./chunk-L4MKNG56.js';import {m,j as j$1,k as k$1,l as l$1}from'./chunk-WUSTIEYA.js';import {s,e as e$1,g,b as b$3,f as f$2,h,p as p$2}from'./chunk-GADXREYG.js';import {e}from'./chunk-Q527BPUF.js';import {z,f as f$1,p}from'./chunk-KAFQA7HV.js';import {b as b$1,a as a$2}from'./chunk-EK4ZRIFJ.js';import {f,b as b$2,a as a$1}from'./chunk-ECO3LHCE.js';import*as _ from'fs';import*as j from'path';C();b();b$1();m();s();l();var Ee=new Set(["dismissed","revised"]);function $e(i){let t=(i.reason||"").toLowerCase();return t.includes("override")||t.includes("human-override")?"human-override":"reviewer-reject"}function Fe(i){return i.verdict==="dismissed"?"high":"medium"}function ge(i,t){let e={failuresRecorded:0,entriesRevised:0,certsOverturned:0,scenariosCreated:0},d,r;try{d=b$3(i).filter(n=>n.type==="user-verdict"&&n.verdict&&Ee.has(n.verdict)),r=p$2(i);}catch(n){return a$2.component("#field-failure-reducer").warn("failed to read session inputs",{error:n instanceof Error?n.message:String(n)}),e}if(d.length===0||r.length===0)return e;let m=new Map;for(let n of r){if(!n.orchestrationId)continue;let s=m.get(n.orchestrationId)??[];s.push(n),m.set(n.orchestrationId,s);}let u=new Set;for(let n of g$1(i))for(let s of n.attributedEntryIds)u.add(`${s}::${n.orchestrationId}`);for(let n of d){let s=n.orchestrationId;if(!s)continue;let f=m.get(s);if(!f||f.length===0)continue;let b=$e(n),l=Fe(n),a=n.symbols??[],c=n.reason||n.revisionDelta||`${n.verdict} verdict`;for(let p of f){let y=p.agentId;for(let v of p.notebookEntryIds){let S=`${v}::${s}`;if(u.has(S))continue;u.add(S);let R=h$1(s,v),o={ts:new Date().toISOString(),orchestrationId:s,agent:y,signal:b,severity:l,attributedEntryIds:[v],symbols:a,detail:c,sourceEvent:`verdict:${n.verdict}`};f$3(i,o),e.failuresRecorded++,j$1(y,v,{failureId:R,signal:b,detail:c,severity:l},i)&&e.entriesRevised++,j$2(i,v,R)&&e.certsOverturned++;let D=e$2(R);f$4(i,{id:D,scenario:c,probes:[{agent:y,learning_ref:v,claim:c}],origin:"field-failure",origin_ref:R,expected:{must:"survive"}})&&e.scenariosCreated++;}}}return e.failuresRecorded>0&&a$2.flow("$classroom-fail-loop").info("field-failure reducer pass complete",{failuresRecorded:e.failuresRecorded,entriesRevised:e.entriesRevised,certsOverturned:e.certsOverturned,scenariosCreated:e.scenariosCreated}),e}b$1();l();m();var ke=14,Ae=30,Pe=2,Oe=.05,xe=1440*60*1e3;function ye(i,t){if(!i)return null;let e=Date.parse(i);return Number.isNaN(e)?null:(t-e)/xe}function he(i$1,t={}){let e={certsSurvived:0,entriesDecayed:0},d=t.now??Date.now(),r=t.survivalWindowDays??ke,m=t.idleWindowDays??Ae,u=t.lowAppliedThreshold??Pe,n=t.decayDecrement??Oe;try{let s=i(i$1),f=g$1(i$1),b=new Set;for(let a of f)for(let c of a.attributedEntryIds??[])b.add(c);let l=new Set;for(let a of s){if(a.outcome!=="pending"||l.has(a.entryId)||b.has(a.entryId))continue;let c=ye(typeof a.ts=="string"?a.ts:void 0,d);c===null||c<r||k(i$1,a.entryId)&&(l.add(a.entryId),e.certsSurvived++);}}catch(s){a$2.component("#classroom-decay").warn("survived-flip pass failed",{error:s instanceof Error?s.message:String(s)});}try{for(let s of k$1(i$1)){let{entry:f}=s;if((f.appliedCount??0)>u)continue;let l=ye(f.lastAppliedAt,d);l===null||l<m||l$1(s,n)&&e.entriesDecayed++;}}catch(s){a$2.component("#classroom-decay").warn("unused-decay pass failed",{error:s instanceof Error?s.message:String(s)});}return (e.certsSurvived>0||e.entriesDecayed>0)&&a$2.flow("$classroom-fail-loop").info("decay pass complete",{certsSurvived:e.certsSurvived,entriesDecayed:e.entriesDecayed}),e}z();f();s();function ot(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ne(i){let t=Date.now(),e=i.match(/^(\d+)(m|h|d)$/);if(e){let d=parseInt(e[1],10),r=e[2],m=r==="m"?d*6e4:r==="h"?d*36e5:d*864e5;return new Date(t-m).toISOString()}return i}async function st(i,t$1,e$1){let d=r=>JSON.stringify(r,null,2);switch(i){case "paradigm_ambient_nominations":{t(e$1.rootDir);let m=t$1.pending_only!==false,u=t$1.limit||20,n=p$1(e$1.rootDir,{agent:t$1.agent,urgency:t$1.urgency,pending_only:m,limit:u+20}),s=A(e$1.rootDir);n=B(n,s).slice(0,u);let f=j.join(e$1.rootDir,".paradigm/events/nominations.jsonl");if(_.existsSync(f))try{let l=_.readFileSync(f,"utf8"),a=new Set(n.map(p=>p.id)),c=l.trim().split(`
3
+ `).map(p=>{try{let y=JSON.parse(p);return a.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):p}catch{return p}});_.writeFileSync(f,c.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let b={count:n.length,nominations:n.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t$1.include_debates){let a=q(e$1.rootDir).filter(c=>!c.resolution);b.debates=a.map(c=>({id:c.id,topic:c.topic,type:c.type,nominations:c.nominations})),b.debate_count=a.length;}return {text:d(b),handled:true}}case "paradigm_ambient_events":{let r=t$1.since?Ne(t$1.since):void 0,m=t$1.limit||50,u=a(e$1.rootDir,{type:t$1.type,source:t$1.source,symbol:t$1.symbol,agent:t$1.agent,since:r,limit:m});return {text:d({count:u.length,events:u.map(n=>({id:n.id,type:n.type,source:n.source,timestamp:n.timestamp,path:n.path,symbols:n.symbols,context:n.context,agent:n.agent,tool:n.tool,severity:n.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r$1=t$1.nomination_id,m=t$1.response,u=t$1.reason,n=r(e$1.rootDir,r$1,m,u);if(n)try{let{appendSessionWorkEntry:f,appendVerdictEntry:b}=await import('./session-work-log-KZX4PGUL.js'),a=p$1(e$1.rootDir,{limit:500}).find(p=>p.id===r$1),c={timestamp:new Date().toISOString(),type:"user-verdict",agent:a?.agent,nominationId:r$1,verdict:m,reason:u};f(e$1.rootDir,c),b(e$1.rootDir,c);}catch{}let s=false;return t$1.resolve_debate&&n&&(s=s$1(e$1.rootDir,t$1.resolve_debate,r$1,t$1.reason)),{text:d({engaged:n,nomination_id:r$1,response:m,debate_resolved:s||void 0}),handled:true}}case "paradigm_context_compose":{let r=t$1.agent,m=t$1.symbols||[],u=t$1.include_nominations!==false,n=t$1.include_decisions!==false,s=t$1.include_journal!==false,f=t$1.max_decisions||5,b=t$1.max_journal||5,l=f$1(e$1.rootDir,r);if(!l)return {text:d({error:`Agent profile not found: ${r}`}),handled:true};let a=[],c=p(l,m);if(c.trim()&&a.push(c),n){let p=e(e$1.rootDir,{status:"active",limit:f});if(p.length>0){a.push("## Recent Team Decisions");for(let y of p)a.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);a.push("");}}if(s){let p=b$2(r,{transferable:true,limit:b});if(p.length>0){a.push("## Transferable Insights");for(let y of p)a.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);a.push("");}}if(u){let p=p$1(e$1.rootDir,{pending_only:true,limit:10});if(p.length>0){a.push("## Pending Nominations");for(let y of p)a.push(`- [${y.urgency}] ${y.brief}`);a.push("");}}return {text:d({agent:r,context:a.join(`
6
+ `),sections_included:{profile:true,decisions:n,journal:s,nominations:u}}),handled:true}}case "paradigm_ambient_promote":{let r=t$1.agent,m=z$1(e$1.rootDir,r);return {text:d({agent:r,promoted:m.promoted,entries:m.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t$1.agent,m=t$1.dry_run===true,u=w(e$1.rootDir,r);if(m)return {text:d({agent:r,dry_run:true,stats:u,note:u.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(u.acceptRate*100).toFixed(0)}% \u2014 ${u.acceptRate>.8?"would lower threshold":u.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let n=v(e$1.rootDir,r);return {text:d({agent:r,...n,stats:u}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=x(e$1.rootDir);return {text:d(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:d(await He(e$1.rootDir,t$1)),handled:true};default:return {text:`Unknown ambient tool: ${i}`,handled:false}}}var Ce={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function We(i){try{let t=j.join(i,".paradigm","config.yaml");if(_.existsSync(t)){let d=_.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(d)return d[1].trim()}}catch{}return j.basename(i)}async function He(i,t={}){let e=t.dry_run===true,d=We(i),r=e$1(i).filter(o=>o.verdict&&o.agent),m=g(i).filter(o=>o.agent&&o.corrections.length>0),u=b$3(i),n=e?{failuresRecorded:0,entriesRevised:0,certsOverturned:0}:ge(i),s=e?{certsSurvived:0,entriesDecayed:0}:he(i);if(r.length===0&&m.length===0)return {sessionEntries:u.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[],fieldFailures:n,decay:s};let f=new Map;for(let o of r){let g=o.agent;f.has(g)||f.set(g,[]),f.get(g).push(o);}let b=u.filter(o=>o.type==="agent-contribution"),l=new Map;for(let o of b)o.agent&&(l.has(o.agent)||l.set(o.agent,[]),l.get(o.agent).push(o));let a=[],c={},p=0;for(let[o,g]of f){c[o]=0;let I=g.filter(h=>h.verdict==="accepted").length;g.filter(h=>h.verdict==="dismissed").length;g.filter(h=>h.verdict==="revised").length;let k=g.length,be=k>0?I/k:0;for(let h of g){let A=Ce[h.verdict];if(!A)continue;let ve=l.get(o)?.shift(),N=Te(h,ve,{acceptRate:be,total:k,accepted:I}),_e=typeof h.confidence=="number"?h.confidence:h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Re={agent:o,verdict:h.verdict,trigger:A,insight:N,symbols:h.symbols};if(a.push(Re),e)c[o]++,p++;else try{a$1(o,{trigger:A,insight:N,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:_e,project:d,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(we=>`symbol:${we}`)]}),c[o]++,p++;}catch{}}}let y=new Set;for(let o of m){let g=o.agent;y.add(g),c[g]===void 0&&(c[g]=0);let I=`Self-revision during iteration round ${o.round}: ${o.corrections.join("; ")}`;if(a.push({agent:g,verdict:"iteration-revision",trigger:"self_reflection",insight:I,symbols:o.symbols}),e)c[g]++,p++;else try{a$1(g,{trigger:"self_reflection",insight:I,confidence_before:.6,confidence_after:typeof o.confidence=="number"?o.confidence:.75,project:d,transferable:!1,tags:["postflight","iteration-revision",`round:${o.round}`,...(o.symbols||[]).map(D=>`symbol:${D}`)]}),c[g]++,p++;}catch{}}let v={},S=0,R=new Set([...f.keys(),...y]);if(!e)for(let o of R)try{let g=z$1(i,o);g.promoted>0&&(v[o]=g.promoted,S+=g.promoted);}catch{}return !e&&r.length>0&&f$2(i,r.map(o=>o.nominationId).filter(Boolean)),!e&&m.length>0&&h(i,m.map(o=>o.id)),{sessionEntries:u.length,agentsProcessed:Array.from(R),journalsWritten:p,journalsByAgent:c,promoted:S,promotedByAgent:v,dryRun:e,details:a,fieldFailures:n,decay:s}}function Te(i,t,e){let d=i.symbols?.length?` (symbols: ${i.symbols.join(", ")})`:"",r=i.reason?` Reason: ${i.reason}.`:"";switch(i.verdict){case "accepted":return `Contribution accepted by user${d}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${d}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${d}.${r}`+(i.revisionDelta?` Delta: "${i.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${i.verdict}"${d}.${r}`}}export{ot as a,st as b,He as c};
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,j as j$1,M as M$1,B as B$1}from'./chunk-VHVUJGZ2.js';import {a as a$1,b as b$4,c as c$1}from'./chunk-M4UMM6DC.js';import {d as d$1}from'./chunk-F3OBFUOE.js';import {m,b as b$3}from'./chunk-WUSTIEYA.js';import {r,i,a as a$2,f}from'./chunk-SGLIPRIC.js';import {j,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 y from'fs';import*as T from'path';import*as U from'crypto';import {execSync}from'child_process';import*as k from'js-yaml';import*as Q from'os';import It from'sql.js';var je={};c(je,{contentSearch:()=>Rt,detectFileRename:()=>Me,generateFingerprint:()=>ke,levenshteinDistance:()=>Oe,levenshteinSimilarity:()=>ce,searchSiblingFiles:()=>Pe,slidingWindowSearch:()=>ee});function ke(e){let t=e.split(`
3
+ `).filter(n=>n.trim()!=="");return {firstLine:Z(t[0]||""),lastLine:Z(t[t.length-1]||""),lineCount:t.length,structuralHash:Fe(t)}}function Fe(e){let t=e.map(n=>n.trim()).filter(n=>Ce.test(n)).map(n=>{let r=n.match(Ce);return r?r[1].trim():""}).join("|");return U.createHash("sha256").update(t).digest("hex").slice(0,16)}function Z(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function Oe(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let n=e.length,r=t.length;if(n>5e3||r>5e3)return Math.abs(n-r);let s=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)s[a]=a;for(let a=1;a<=r;a++){i[0]=a;for(let c=1;c<=n;c++){let o=e[c-1]===t[a-1]?0:1;i[c]=Math.min(s[c]+1,i[c-1]+1,s[c-1]+o);}[s,i]=[i,s];}return s[n]}function ce(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-Oe(e,t)/n}function ee(e,t,n,r=3){let{lineCount:s}=t,i=Math.max(1,Math.floor(s*.8)),a=Math.ceil(s*1.2),c=[],o=ae(n);for(let u of [s,i,a])if(!(u>e.length))for(let d=0;d<=e.length-u;d++){let p=e.slice(d,d+u),S=_t(p,t,o);if(S>=.5){let m=p.join(`
4
+ `);c.push({windowStart:d+1,windowEnd:d+u,similarity:ce(ae(m),o),score:S});}}let l=new Map;for(let u of c){let d=l.get(u.windowStart);(!d||u.score>d.score)&&l.set(u.windowStart,u);}return Array.from(l.values()).sort((u,d)=>d.score-u.score).slice(0,r)}function _t(e,t,n){let r=e.filter(p=>p.trim()!=="");if(r.length===0)return 0;let s=0,i=Z(r[0]),a=Z(r[r.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),s+=c*Tt,Fe(r)===t.structuralHash&&(s+=bt);let l=r.join(`
5
+ `),u=ce(ae(l),n);u>=.8&&(s+=(u-.8)/.2*wt);let d=r.length/t.lineCount;if(d>=.8&&d<=1.2){let p=1-Math.abs(1-d)/.2;s+=p*xt;}return s}function ae(e){return e.split(`
6
+ `).map(t=>t.trim()).filter(t=>t!=="").join(`
7
+ `)}function Me(e,t){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let r=n.split(`
8
+ `);for(let s of r){let i=s.split(" ");if(i.length>=3&&i[0].startsWith("R"))return i[2]}return null}catch{return null}}function Pe(e,t,n,r,s=10){let i=T.isAbsolute(t)?t:T.join(e,t);if(!y.existsSync(i))return [];let a=[];try{let c=y.readdirSync(i).filter(o=>!o.startsWith(".")&&y.statSync(T.join(i,o)).isFile()).slice(0,s);for(let o of c)try{let u=y.readFileSync(T.join(i,o),"utf8").split(`
9
+ `),d=ee(u,n,r,1);if(d.length>0&&d[0].score>=.7){let p=T.relative(e,T.join(i,o));a.push({file:p,score:d[0].score,start:d[0].windowStart,end:d[0].windowEnd});}}catch{}}catch{return []}return a.sort((c,o)=>o.score-c.score)}function Rt(e,t,n,r=true){let s=ke(n),i=T.isAbsolute(t)?t:T.join(e,t);if(y.existsSync(i)){let u=y.readFileSync(i,"utf8").split(`
10
+ `),d=ee(u,s,n);if(d.length>0){let p=d[0];return {found:p.score>=.7,score:p.score,suggestedStart:p.windowStart,suggestedEnd:p.windowEnd,similarity:p.similarity}}}let a=Me(e,t);if(a){let l=T.join(e,a);if(y.existsSync(l)){let d=y.readFileSync(l,"utf8").split(`
11
+ `),p=ee(d,s,n);if(p.length>0&&p[0].score>=.7)return {found:true,score:p[0].score,suggestedStart:p[0].windowStart,suggestedEnd:p[0].windowEnd,suggestedPath:a,similarity:p[0].similarity}}}let c=T.dirname(t),o=Pe(e,c,s,n);if(o.length>0&&o[0].score>=.7){let l=o[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==t?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var Ce,Tt,bt,wt,xt,De=b(()=>{Ce=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;Tt=.4,bt=.3,wt=.2,xt=.1;});var rt="0.1.0",ot="1.0.0";function oe(e,t){let n={$meta:it(t.projectName,e),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let s of e.symbols)at(s,n,t);if(t.screenDefinitions)for(let[s,i]of Object.entries(t.screenDefinitions))n.screens[s]||(n.screens[s]={id:s,name:D(s),route:i.route,path:"",components:i.components,features:i.features});let r={};for(let s of Object.values(n.components))s.componentType&&(r[s.componentType]=(r[s.componentType]||0)+1);for(let s of Object.values(n.features))s.componentType&&(r[s.componentType]=(r[s.componentType]||0)+1);return Object.keys(r).length>0&&(n.$meta.componentTypes=r),gt(n),n}function it(e,t){return {version:ot,project:e,generatedAt:new Date().toISOString(),paradigmVersion:rt,sources:{purposeFiles:t.purposeFiles.length,portalFiles:t.portalFiles.length,premiseFiles:t.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function at(e,t,n){let{type:r}=e;switch(r){case "component":ct(e,t,n);break;case "feature":lt(e,t,n);break;case "flow":ut(e,t);break;case "state":dt(e,t);break;case "gate":pt(e,t);break;case "signal":ft(e,t);break;case "aspect":ht(e,t);break;}}function ct(e,t,n){let r=B(e.symbol),s=Le(r,e.data,n.visualTagMappings),i={id:r,name:D(r),symbol:e.symbol,category:"components",path:e.filePath,description:e.description,visualTags:s,related:e.references,componentType:e.componentType,parent:e.parentSymbol};t.components[r]=i,t.symbolMap[e.symbol]={category:"components",id:r};}function lt(e,t,n){let r=B(e.symbol),s=Le(r,e.data,n.visualTagMappings),i={id:r,name:D(r),symbol:e.symbol,category:"features",path:e.filePath,description:e.description,visualTags:s,related:e.references,componentType:e.componentType,parent:e.parentSymbol};t.features[r]=i,t.symbolMap[e.symbol]={category:"features",id:r};}function ut(e,t){let n=B(e.symbol),r=e.data,s=[];if(r?.steps)for(let a=0;a<r.steps.length;a++){let c=r.steps[a];s.push({id:`${n}-step-${a}`,name:c.action||`Step ${a+1}`,target:c.component,description:c.description,order:a});}let i={id:n,name:D(n),symbol:e.symbol,path:e.filePath,description:e.description,steps:s};t.flows[n]=i,t.symbolMap[e.symbol]={category:"flows",id:n};}function dt(e,t){let n=B(e.symbol),r={id:n,name:D(n),symbol:e.symbol,path:e.filePath,description:e.description,consumers:e.referencedBy};t.state[n]=r,t.symbolMap[e.symbol]={category:"state",id:n};}function pt(e,t){let n=B(e.symbol),r={id:n,name:D(n),symbol:e.symbol,category:"gates",path:e.filePath,description:e.description,related:e.references};t.gates[n]=r,t.symbolMap[e.symbol]={category:"gates",id:n};}function ft(e,t){let n=B(e.symbol),r={id:n,name:D(n),symbol:e.symbol,category:"signals",path:e.filePath,description:e.description,related:e.references};t.signals[n]=r,t.symbolMap[e.symbol]={category:"signals",id:n};}function ht(e,t){let n=B(e.symbol),r={id:n,name:D(n),symbol:e.symbol,category:"aspects",path:e.filePath,description:e.description,related:e.references};t.aspects[n]=r,t.symbolMap[e.symbol]={category:"aspects",id:n};}function gt(e){for(let t of Object.values(e.screens))if(t.components)for(let n of t.components){let r=e.components[n];r&&(r.screens=r.screens||[],r.screens.includes(t.id)||r.screens.push(t.id));}}function B(e){return e.slice(1)}function D(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Le(e,t,n){let r=[];if(n?.[e])return n[e];let s=[[/button/i,"button"],[/btn/i,"button"],[/form/i,"form"],[/input/i,"input"],[/field/i,"input"],[/select/i,"input"],[/card/i,"card"],[/list/i,"list"],[/table/i,"list"],[/modal/i,"modal"],[/dialog/i,"modal"],[/drawer/i,"modal"],[/nav/i,"nav"],[/menu/i,"menu"],[/dropdown/i,"menu"],[/header/i,"header"],[/footer/i,"footer"],[/sidebar/i,"sidebar"],[/hero/i,"hero"],[/grid/i,"grid"],[/chart/i,"chart"],[/graph/i,"chart"],[/icon/i,"icon"],[/image/i,"image"],[/avatar/i,"avatar"],[/badge/i,"badge"],[/tag/i,"badge"],[/tab/i,"tab"],[/accordion/i,"accordion"],[/toast/i,"toast"],[/notification/i,"toast"],[/alert/i,"toast"],[/spinner/i,"spinner"],[/loader/i,"spinner"],[/loading/i,"spinner"],[/skeleton/i,"skeleton"]];for(let[i,a]of s)i.test(e)&&r.push(a);return r}function ie(e){return JSON.stringify(e,null,2)}var mt=300*1e3,Y=null;function ve(){Y=null;}function M(e,t){return y.existsSync(T.join(e,t))}function H(e,t){return y.existsSync(T.join(e,t))}function yt(e,t,n){let r=e;try{if(!y.existsSync(r))return !1;let s=y.readdirSync(r,{withFileTypes:!0});for(let i of s){if(i.isFile()&&i.name.endsWith(t))return !0;if(i.isDirectory())try{if(y.readdirSync(T.join(r,i.name)).some(c=>c.endsWith(t)))return !0}catch{}}}catch{}return false}var St={wisdom:e=>M(e,".paradigm/wisdom"),history:e=>M(e,".paradigm/history"),lore:e=>M(e,".paradigm/lore"),habits:e=>H(e,".paradigm/habits.yaml"),sentinel:e=>{try{let t=T.join(e,".paradigm","config.yaml");return y.existsSync(t)?y.readFileSync(t,"utf-8").includes("sentinel"):!1}catch{return false}},flows:e=>H(e,".paradigm/flow-index.json")||H(e,".paradigm/flows.yaml"),fixtures:e=>H(e,".paradigm/fixtures.yaml"),orchestration:e=>H(e,".paradigm/agents.yaml"),tasks:e=>M(e,".paradigm/tasks"),assessment:e=>M(e,".paradigm/lore"),personas:e=>yt(e,".persona"),protocols:e=>M(e,".paradigm/protocols"),symphony:()=>{let e=T.join(Q.homedir(),".paradigm","score");return y.existsSync(e)},university:e=>M(e,".paradigm/university"),agents:e=>{let t=T.join(Q.homedir(),".paradigm","agents");return M(e,".paradigm/agents")||y.existsSync(t)},"aspect-graph":e=>H(e,".paradigm/aspect-graph.db"),pan:e=>H(e,".pan")||H(e,"nevr.yaml"),notebooks:e=>{let t=T.join(Q.homedir(),".paradigm","notebooks");return M(e,".paradigm/notebooks")||y.existsSync(t)}},Ae=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(t){this.rootDir=t;}register(t){this.modules.set(t.key,t);}registerAll(t){for(let n of t)this.register(n);}detectActiveFeatures(){if(Y&&Date.now()-Y.timestamp<mt)return Y.features;let t=new Set;for(let[n,r]of this.modules){if(r.tier==="core"){t.add(n);continue}if(r.tier==="advanced"){this.activatedAdvanced.has(n)&&t.add(n);continue}let s=r.detect||St[n];if(s)try{s(this.rootDir)&&t.add(n);}catch{}else t.add(n);}return Y={features:t,timestamp:Date.now()},t}getActiveTools(){let t=this.detectActiveFeatures(),n=[];for(let[r,s]of this.modules)t.has(r)&&n.push(...s.getToolsList());return n}activateAdvanced(t){let n=this.modules.get(t);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(t),n.getToolsList())}getAvailableAdvanced(){let t=[];for(let[n,r]of this.modules)r.tier==="advanced"&&!this.activatedAdvanced.has(n)&&t.push({key:n,toolCount:r.getToolsList().length});return t}async dispatch(t,n,r,s){let i=this.detectActiveFeatures();for(let[a,c]of this.modules)if(i.has(a))try{let o=await c.handleTool(t,n,r,s);if(o.handled)return o}catch(o){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${a}"`,message:o.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let t=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let r of this.modules.values())n[r.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...t],availableAdvanced:[...this.modules.entries()].filter(([r,s])=>s.tier==="advanced"&&!this.activatedAdvanced.has(r)).map(([r])=>r)}}};var le=null;async function Lt(){return le||(le=await It()),le}var At=[`CREATE TABLE IF NOT EXISTS aspects (
12
+ id TEXT PRIMARY KEY,
13
+ description TEXT NOT NULL,
14
+ category TEXT DEFAULT 'rule',
15
+ severity TEXT DEFAULT 'medium',
16
+ value TEXT,
17
+ enforcement TEXT,
18
+ defined_in TEXT NOT NULL,
19
+ tags TEXT,
20
+ created_at TEXT NOT NULL,
21
+ updated_at TEXT NOT NULL
22
+ )`,`CREATE TABLE IF NOT EXISTS anchors (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
25
+ file_path TEXT NOT NULL,
26
+ start_line INTEGER NOT NULL,
27
+ end_line INTEGER NOT NULL,
28
+ content_hash TEXT,
29
+ normalized_hash TEXT,
30
+ materialized_at_commit TEXT,
31
+ last_verified TEXT,
32
+ drifted INTEGER DEFAULT 0
33
+ )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ source TEXT NOT NULL,
36
+ target TEXT NOT NULL,
37
+ relation TEXT NOT NULL,
38
+ weight REAL DEFAULT 1.0,
39
+ origin TEXT DEFAULT 'explicit',
40
+ created_at TEXT NOT NULL
41
+ )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
42
+ aspect_id TEXT NOT NULL,
43
+ lore_id TEXT NOT NULL,
44
+ PRIMARY KEY (aspect_id, lore_id)
45
+ )`,`CREATE TABLE IF NOT EXISTS search_log (
46
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ query TEXT NOT NULL,
48
+ results_returned TEXT NOT NULL,
49
+ selected_result TEXT,
50
+ timestamp TEXT NOT NULL
51
+ )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
52
+ query_normalized TEXT NOT NULL,
53
+ aspect_id TEXT NOT NULL,
54
+ weight REAL DEFAULT 1.0,
55
+ hit_count INTEGER DEFAULT 1,
56
+ last_hit TEXT NOT NULL,
57
+ PRIMARY KEY (query_normalized, aspect_id)
58
+ )`,`CREATE TABLE IF NOT EXISTS heatmap (
59
+ aspect_id TEXT NOT NULL,
60
+ access_type TEXT NOT NULL,
61
+ count INTEGER DEFAULT 0,
62
+ last_accessed TEXT NOT NULL,
63
+ PRIMARY KEY (aspect_id, access_type)
64
+ )`],vt=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
65
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ anchor_id INTEGER NOT NULL,
67
+ action TEXT NOT NULL,
68
+ old_start INTEGER,
69
+ old_end INTEGER,
70
+ new_start INTEGER,
71
+ new_end INTEGER,
72
+ old_path TEXT,
73
+ new_path TEXT,
74
+ confidence REAL,
75
+ commit_hash TEXT,
76
+ healed_at TEXT NOT NULL
77
+ )`],Ct="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function v(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=[];for(;r.step();)s.push(r.getAsObject());return r.free(),s}function Nt(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=null;return r.step()&&(s=r.getAsObject()),r.free(),s}async function Ue(e){let t=await Lt(),n=T.join(e,".paradigm"),r=T.join(n,"aspect-graph.db"),s;if(y.existsSync(r)){let i=y.readFileSync(r);s=new t.Database(i);}else y.existsSync(n)||y.mkdirSync(n,{recursive:true}),s=new t.Database;for(let i of At)s.run(i);try{s.run(Ct);}catch{}for(let i of vt)try{s.run(i);}catch{}return s}function We(e,t){if(t){let n=T.join(t,".paradigm");y.existsSync(n)||y.mkdirSync(n,{recursive:true});let r=T.join(n,"aspect-graph.db"),s=e.export();y.writeFileSync(r,Buffer.from(s));}e.close();}function Xe(e,t,n){let r=t.filter(a=>a.type==="aspect"),s=new Date().toISOString(),i=null;try{i=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}e.run("DELETE FROM anchors"),e.run("DELETE FROM edges"),e.run("DELETE FROM aspects");try{e.run("DELETE FROM aspects_fts");}catch{}for(let a of r){let c=a.data??{},o=Mt(c,a),l=Pt(c,a),u=c.value!=null?String(c.value):null,d=a.enforcement??(c.enforcement!=null?String(c.enforcement):null),p=a.tags?JSON.stringify(a.tags):null;if(e.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
78
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,a.description??"",o,l,u,d,a.filePath,p,a.created??s,a.modified??s]),a.anchors)for(let m of a.anchors){let{startLine:_,endLine:F}=$e(m),L=Ot();e.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
79
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,m.path,_,F,L.exact,L.normalized,i,s,L.normalizedContent]);}let S=c.edges;if(Array.isArray(S))for(let m of S)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
80
+ VALUES (?, ?, ?, ?, ?, ?)`,[m.source??a.symbol,m.target??"",m.relation??"related-to",m.weight??1,m.origin??"explicit",s]);if(a.appliesTo)for(let m of a.appliesTo)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
81
+ VALUES (?, ?, ?, ?, ?, ?)`,[a.symbol,m,"related-to",.5,"inferred",s]);try{e.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
82
+ VALUES (?, ?, ?, ?)`,[a.symbol,a.description??"",d??"",p??""]);}catch{}}}function wn(e,t){return Nt(e,"SELECT * FROM aspects WHERE id = ?",[t])}function xn(e,t){return v(e,"SELECT * FROM anchors WHERE aspect_id = ?",[t])}function _n(e,t){return v(e,"SELECT * FROM edges WHERE source = ?",[t])}function Rn(e,t){return v(e,"SELECT * FROM edges WHERE target = ?",[t])}function In(e,t){return v(e,"SELECT * FROM edges WHERE source = ? OR target = ?",[t,t])}function Ln(e,t,n){let r=new Date().toISOString();e.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
83
+ VALUES (?, ?, 1, ?)
84
+ ON CONFLICT(aspect_id, access_type)
85
+ DO UPDATE SET count = count + 1, last_accessed = ?`,[t,n,r,r]);}function An(e,t=20,n){return n?v(e,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,t]):v(e,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[t])}function vn(e,t,n,r$1=true,s=.7,i=.85){let a=n?v(e,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):v(e,"SELECT * FROM anchors"),c=[];for(let o of a){let u=v(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id])[0]?.defined_in,d$1=u?T.dirname(T.isAbsolute(u)?u:T.resolve(t,u)):t,p=r(o.file_path,d$1,t),S=p.resolvedPath;if(!p.exists){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let _=y.readFileSync(S,"utf8").split(`
86
+ `),F=Math.max(0,o.start_line-1),L=Math.min(_.length,o.end_line),W=_.slice(F,L).join(`
87
+ `),X=U.createHash("sha256").update(W).digest("hex");if(o.content_hash!=null&&X===o.content_hash){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),o.drifted===1&&e.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[o.id]);continue}let G=U.createHash("sha256").update(de(W)).digest("hex");if(o.normalized_hash!=null&&G===o.normalized_hash){e.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[X,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(o.content_hash==null&&o.normalized_hash==null){e.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[X,G,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let $=!1;if(o.materialized_at_commit){let g=Ft(t,o.file_path,o.materialized_at_commit,o.start_line,o.end_line);if(g){let h=Math.max(0,g.currentStart-1),z=Math.min(_.length,g.currentEnd),O=_.slice(h,z).join(`
88
+ `),f=U.createHash("sha256").update(O).digest("hex");if(o.content_hash!=null&&f===o.content_hash){let E=r$1;if(E){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[g.currentStart,g.currentEnd,o.id]);let C=v(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);C.length>0&&ue(t,C[0].defined_in,o.file_path,o.start_line,o.end_line,g.currentStart,g.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:E?g.currentStart:o.start_line,endLine:E?g.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:g.currentStart,suggestedEnd:g.currentEnd,autoHealed:E}),$=!0;}else {let E=U.createHash("sha256").update(de(O)).digest("hex");if(o.normalized_hash!=null&&E===o.normalized_hash){if(r$1){let C=U.createHash("sha256").update(O).digest("hex");e.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[g.currentStart,g.currentEnd,C,o.id]);let V=v(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);V.length>0&&ue(t,V[0].defined_in,o.file_path,o.start_line,o.end_line,g.currentStart,g.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:r$1?g.currentStart:o.start_line,endLine:r$1?g.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:g.currentStart,suggestedEnd:g.currentEnd,autoHealed:r$1}),$=!0;}}}}if($)continue;if(o.original_content){let{contentSearch:g}=(De(),d(je)),h=g(t,o.file_path,o.original_content,r$1);if(h.found&&h.score>=s){if(r$1&&h.score>=i&&!h.suggestedPath&&h.suggestedStart&&h.suggestedEnd){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[h.suggestedStart,h.suggestedEnd,o.id]);try{e.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
89
+ VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[o.id,o.start_line,o.end_line,h.suggestedStart,h.suggestedEnd,h.score,new Date().toISOString()]);}catch{}let O=v(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);O.length>0&&ue(t,O[0].defined_in,o.file_path,o.start_line,o.end_line,h.suggestedStart,h.suggestedEnd),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:h.suggestedStart,endLine:h.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:h.similarity,suggestedStart:h.suggestedStart,suggestedEnd:h.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:o.aspect_id,path:h.suggestedPath||o.file_path,startLine:o.start_line,endLine:o.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:h.similarity,suggestedStart:h.suggestedStart,suggestedEnd:h.suggestedEnd,autoHealed:!1,drifted:!0});continue}}e.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:W,drifted:!0});}catch{c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function $e(e){let{lines:t}=e;return typeof t=="number"?{startLine:t,endLine:t}:Array.isArray(t)?t.length===2?{startLine:t[0],endLine:t[1]}:{startLine:Math.min(...t),endLine:Math.max(...t)}:{startLine:1,endLine:1}}function kt(e){let t=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,r;for(;(r=n.exec(e))!==null;)t.push({oldStart:parseInt(r[1],10),oldCount:r[2]!==void 0?parseInt(r[2],10):1,newStart:parseInt(r[3],10),newCount:r[4]!==void 0?parseInt(r[4],10):1});return t}function Ft(e,t,n,r,s){let i;try{i=execSync(`git diff ${n}..HEAD --unified=0 -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3});}catch{return null}if(!i.trim())return {originalStart:r,originalEnd:s,currentStart:r,currentEnd:s};let a=kt(i),c=0;for(let o of a){if(o.oldStart+o.oldCount<=r){c+=o.newCount-o.oldCount;continue}if(o.oldStart<s)return null;break}return c===0?null:{originalStart:r,originalEnd:s,currentStart:r+c,currentEnd:s+c}}function ue(e,t,n,r,s,i,a){let c=T.isAbsolute(t)?t:T.join(e,t);if(!y.existsSync(c))return false;try{let o=y.readFileSync(c,"utf8"),l=r===s?`${n}:${r}`:`${n}:${r}-${s}`,u=i===a?`${n}:${i}`:`${n}:${i}-${a}`;if(!o.includes(l))return !1;let d=o.replace(l,u);return y.writeFileSync(c,d,"utf8"),!0}catch{return false}}function de(e){return e.split(`
90
+ `).map(t=>t.trimEnd()).filter(t=>t.trim()!=="").map(t=>t.replace(/\s+/g," ")).join(`
91
+ `)}function Ot(e,t,n){return {exact:null,normalized:null,normalizedContent:null};}function Mt(e,t){if(typeof e.category=="string")return e.category;let n=(t.description??"").toLowerCase();return /\b(must|require|always)\b/.test(n)?"rule":/\b(decided|chose)\b/.test(n)?"decision":/\b(limit|cannot)\b/.test(n)?"constraint":/\b(set to|configured|value)\b/.test(n)?"configuration":"rule"}function Pt(e,t){if(typeof e.severity=="string")return e.severity;let n=t.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j();var jt=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function ze(e,t){e.run("DELETE FROM lore_links");let n=await a$4(t);if(n.length===0)return 0;let r=Dt(n),s=new Map;for(let l of n)s.set(l.id,l);let i=new Set,a=e.exec("SELECT id, enforcement FROM aspects");if(a.length>0){let{columns:l,values:u}=a[0],d=l.indexOf("id"),p=l.indexOf("enforcement");for(let S of u){let m=String(S[d]),_=S[p];if(_&&typeof _=="string"){let F=_.match(jt);if(F)for(let L of F)s.has(L)&&i.add(`${m}\0${L}`);}}}let c=e.exec("SELECT source, target FROM edges");if(c.length>0&&a.length>0){let l=Ht(e,c);for(let[u,d]of l)for(let p of d){let S=r.get(p);if(S)for(let m of S)i.add(`${u}\0${m}`);}}if(i.size===0)return 0;let o=e.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of i){let[u,d]=l.split("\0");o.bind([u,d]),o.step(),o.reset();}}finally{o.free();}return i.size}async function kn(e,t,n){let r=e.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(r.length===0||r[0].values.length===0)return [];let s=r[0].values.map(i=>String(i[0]));return Ut(t,s)}async function Be(e,t){let n=await a$4(t);if(n.length===0)return 0;let r=e.exec("SELECT id FROM aspects"),s=new Set;if(r.length>0)for(let o of r[0].values)s.add(String(o[0]));if(s.size<2)return 0;let i=new Date().toISOString(),a=0,c=e.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
92
+ VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let o of n){if(!o.symbols_touched||o.symbols_touched.length<2)continue;let l=[];for(let u of o.symbols_touched){let d=u.startsWith("~")?u.slice(1):u;s.has(d)&&l.push(d);}for(let u=0;u<l.length;u++)for(let d=u+1;d<l.length;d++){let[p,S]=l[u]<l[d]?[l[u],l[d]]:[l[d],l[u]];c.bind([p,S,i]),c.step(),c.reset(),a++;}}}finally{c.free();}return a}function Dt(e){let t=new Map;for(let n of e)if(n.symbols_touched)for(let r of n.symbols_touched){let s=t.get(r);s||(s=new Set,t.set(r,s)),s.add(n.id);}return t}function Ht(e,t){let n=e.exec("SELECT id FROM aspects"),r=new Set;if(n.length>0)for(let l of n[0].values)r.add(String(l[0]));let s=new Map;if(t.length===0)return s;let{columns:i,values:a}=t[0],c=i.indexOf("source"),o=i.indexOf("target");for(let l of a){let u=String(l[c]),d=String(l[o]);if(r.has(u)){let p=s.get(u);p||(p=new Set,s.set(u,p)),p.add(d),p.add(`~${u}`);}if(r.has(d)){let p=s.get(d);p||(p=new Set,s.set(d,p)),p.add(u),p.add(`~${d}`);}}return s}async function Ut(e,t){let n=new Set,r=[];for(let s of t){if(n.has(s))continue;n.add(s);let i=await b$2(e,s);i&&r.push(Wt(i));}return r}function Wt(e){return {id:e.id,title:e.title,summary:e.summary,timestamp:e.timestamp,symbolsTouched:e.symbols_touched}}b$1();m();var q=".paradigm/curriculum",Xt="index.yaml";async function Ge(e){let t=T.join(e,q);if(!y.existsSync(t))return [];let n=y.readdirSync(t).filter(s=>s.endsWith(".syllabus")).sort(),r=[];for(let s of n)try{let i=y.readFileSync(T.join(t,s),"utf8"),a=k.load(i);a?.id&&a?.agent&&r.push(a);}catch{}return r}async function Pn(e,t){let n=T.join(e,q,`${t}.syllabus`);if(y.existsSync(n))try{let i=y.readFileSync(n,"utf8"),a=k.load(i);if(a?.id)return a}catch{}let s=(await Ge(e)).filter(i=>i.agent===t);return s.length===0?null:s.reduce((i,a)=>a.version>i.version?a:i)}async function jn(e,t){let n=T.join(e,q);y.existsSync(n)||y.mkdirSync(n,{recursive:true});let r=new Date().toISOString(),s=T.join(n,`${t.agent}.syllabus`),i=1;if(y.existsSync(s))try{let o=k.load(y.readFileSync(s,"utf8"));o?.version&&(i=o.version+1);}catch{}let a=`SY-${t.agent}`,c={id:a,agent:t.agent,version:i,sources:t.sources||[],scope:t.scope,success_criteria:t.success_criteria||[],notebook_target:t.notebook_target,approved_by:t.approved_by,approved_at:t.approved_at||r,term_ttl_days:t.term_ttl_days,status:"current",last_ratified:t.last_ratified||r,recorded_from:t.recorded_from};return y.writeFileSync(s,k.dump(c,{lineWidth:-1,noRefs:true}),"utf8"),a}function $t(e,t){let n=[],r="current",s=Date.parse(t.last_ratified),i=!Number.isNaN(s),a=b$3(t.agent,e),c=new Map(a.map(o=>[o.id,o]));for(let o of t.sources)if(o.kind==="notebook"){let l=c.get(o.ref);if(!l){n.push(`Notebook source missing: ${o.ref}`),r="broken";continue}if(i&&l.updated){let u=Date.parse(l.updated);!Number.isNaN(u)&&u>s&&(n.push(`Notebook source updated since ratification: ${o.ref}`),r!=="broken"&&(r="stale"));}}else o.kind==="scenario"&&(zt(e).has(o.ref)||(n.push(`Scenario source missing: ${o.ref}`),r="broken"));if(i&&typeof t.term_ttl_days=="number"){let o=s+t.term_ttl_days*24*60*60*1e3;Date.now()>o&&r==="current"?(n.push(`Term expired: ratified ${t.last_ratified}, ttl ${t.term_ttl_days}d`),r="expired"):Date.now()>o&&r==="stale"&&(n.push(`Term expired: ratified ${t.last_ratified}, ttl ${t.term_ttl_days}d`),r="expired");}return {status:r,issues:n}}function zt(e){try{let t=T.join(e,".paradigm/curriculum/scenarios");if(!y.existsSync(t))return new Set;let n=new Set;for(let r of y.readdirSync(t))if(r.endsWith(".scenario"))try{let s=k.load(y.readFileSync(T.join(t,r),"utf8"));s?.id&&n.add(s.id);}catch{}return n}catch{return new Set}}async function Ye(e){let t=await Ge(e),n=[],r=0,s=0,i=0,a=0;for(let l of t){let u=$t(e,l);if(l.status!==u.status){l.status=u.status;let d=T.join(e,q,`${l.agent}.syllabus`);y.existsSync(d)&&y.writeFileSync(d,k.dump(l,{lineWidth:-1,noRefs:true}),"utf8");}switch(u.status){case "current":r++;break;case "stale":s++;break;case "broken":i++;break;case "expired":a++;break}n.push({id:l.id,agent:l.agent,version:l.version,status:u.status,last_ratified:l.last_ratified,scope:l.scope});}let c={version:"1.0",generated:new Date().toISOString(),syllabi:n,health:{total:t.length,current:r,stale:s,broken:i,expired:a}},o=T.join(e,q);return t.length>0&&(y.existsSync(o)||y.mkdirSync(o,{recursive:true}),y.writeFileSync(T.join(o,Xt),k.dump(c,{lineWidth:-1,noRefs:true}),"utf8")),(i>0||a>0)&&a$3.component("#syllabus-loader").warn("syllabi require re-ratification",{broken:i,expired:a,stale:s}),c}var Bt="PARADIGM_STRICT";function te(){let e=process.env[Bt];if(e===void 0||e==="")return false;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var qe=new Set(["duplicate-key-detected"]);function Gt(e){let t=e.trim();if(t.includes("/")||t.includes("\\")){let n=t.split(/[/\\]/);t=n[n.length-1]||"unknown";}return t.length>40&&(t=t.slice(0,40)),t||"unknown"}var ne=class{transforms=new Map;record(t,n,r=1){let s=Gt(n),i=`${t}::${s}`,a=this.transforms.get(i);a?a.count+=r:this.transforms.set(i,{kind:t,surface:s,count:r});}report(){let t=Array.from(this.transforms.values()).sort((r,s)=>r.kind!==s.kind?r.kind.localeCompare(s.kind):r.surface.localeCompare(s.surface)),n=t.filter(r=>qe.has(r.kind)).reduce((r,s)=>r+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:t,lossy_count:n,strict_mode:te()}}hasLossy(){for(let t of this.transforms.values())if(qe.has(t.kind))return true;return false}totalCount(){let t=0;for(let n of this.transforms.values())t+=n.count;return t}};b$1();var Yt={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},qt={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},Vt={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},pe={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function os(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function is(e,t,n,r){if(e!=="paradigm_reindex")return {handled:false,text:""};try{let s=await Kt(n.rootDir,n);await r(),a.clear(),ve();let i=(s.integrityReport?.brokenReferences?.length||0)+(s.integrityReport?.duplicateSymbols?.length||0)+(s.componentAnchorIssues||0)+(s.crossFileIssues||0),a$1={success:!0,symbolCount:s.symbolCount,breakdown:s.breakdown,flowCount:s.flowCount,filesWritten:s.filesWritten.length,...s.aspectGraphStats?{aspects:s.aspectGraphStats.aspects,loreLinks:s.aspectGraphStats.loreLinks}:{},...s.protocolHealth?{protocols:s.protocolHealth.total,staleProtocols:s.protocolHealth.stale}:{},...s.syllabusHealth?{syllabi:s.syllabusHealth.total,syllabiNeedingRatification:s.syllabusHealth.stale+s.syllabusHealth.broken+s.syllabusHealth.expired}:{},...s.scenarioHealth?{scenarios:s.scenarioHealth.total}:{},...i>0?{issues:i}:{}};s.consistency&&(a$1.consistency=s.consistency);let c=JSON.stringify(a$1,null,2);return O(c.length,e),{handled:!0,text:c}}catch(s){let i=JSON.stringify({error:s.message},null,2);return O(i.length,e),{handled:true,text:i}}}async function Kt(e,t){let n=[],r=new ne,s;t?s=t.aggregation:s=await i(e);let i$1=t?.projectName||T.basename(e),a=T.join(e,".paradigm");y.existsSync(a)||y.mkdirSync(a,{recursive:true}),Jt(e,r),Qt(s.purposeFiles,r);let c=oe({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:i$1}),o=T.join(a,"scan-index.json");y.writeFileSync(o,ie(c),"utf8"),n.push(".paradigm/scan-index.json");let l=Zt(e,s),u=T.join(a,"navigator.yaml");y.writeFileSync(u,k.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let d=on(e,s.purposeFiles),p=0;if(d&&Object.keys(d.flows).length>0){let f=T.join(a,"flow-index.json");y.writeFileSync(f,JSON.stringify(d,null,2),"utf8"),n.push(".paradigm/flow-index.json"),p=Object.keys(d.flows).length;}let S;try{let f=await Ue(e);Xe(f,s.symbols,e);let E=await ze(f,e),C=await Be(f,e),V=f.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,Je=f.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,Qe=f.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;We(f,e),n.push(".paradigm/aspect-graph.db"),S={aspects:V,anchors:Je,edges:Qe,loreLinks:E};}catch{}let m=0;try{let f=await j$1(e);m=Object.keys(f.personas).length,m>0&&n.push(".paradigm/personas/index.yaml");}catch{}let _;try{let f=await M$1(e);f.health.total>0&&(_=f.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let F;try{let f=await Ye(e);f.health.total>0&&(F=f.health,n.push(".paradigm/curriculum/index.yaml"));}catch{}let L;try{let f=await d$1(e);f.health.total>0&&(L={total:f.health.total,active:f.health.active,retired:f.health.retired},n.push(".paradigm/curriculum/scenarios/index.yaml"));}catch{}let W;try{let f=T.join(e,".paradigm","university");if(y.existsSync(f)){let E=B$1(e);(E.totalContent>0||E.diplomaCount>0)&&(W={totalContent:E.totalContent,diplomaCount:E.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let X;try{X=a$1(s,e);}catch{}let G;try{let f=b$4(s.symbols,e),E=f.missing+f.outOfBounds;E>0&&(G=E);}catch{}let $;try{$=c$1(s.purposeFiles,e);}catch{}let g;try{let f$1=[];for(let E of s.purposeFiles){let C=a$2(E);C.data&&f$1.push({filePath:E,data:C.data});}if(f$1.length>0){let C=f(f$1).issues.length;C>0&&(g=C);}}catch{}let h={};for(let f of s.symbols)h[f.type]=(h[f.type]||0)+1;let z={};for(let f of s.symbols)f.type==="component"&&f.componentType&&(z[f.componentType]=(z[f.componentType]||0)+1);let O=r.report();try{let f=T.join(a,"manifest.consistency.json");y.writeFileSync(f,JSON.stringify(O,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$3.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(te()&&r.hasLossy())throw new Error(`reindex aborted: ${O.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:s.symbols.length,breakdown:h,flowCount:p,aspectGraphStats:S,personaCount:m,protocolHealth:_,...F?{syllabusHealth:F}:{},...L?{scenarioHealth:L}:{},consistency:O,...Object.keys(z).length>0?{componentTypeBreakdown:z}:{},...W?{universityStats:W}:{},...X?{integrityReport:X}:{},...G!==void 0?{componentAnchorIssues:G}:{},...$?{purposeHealth:$}:{},...g!==void 0?{crossFileIssues:g}:{}}}function Jt(e,t){let n=T.join(e,"portal.yaml");if(!y.existsSync(n))return;let r;try{r=y.readFileSync(n,"utf-8");}catch{return}try{k.load(r);}catch(o){(o?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","portal.yaml");return}let s;try{s=k.load(r,{schema:k.FAILSAFE_SCHEMA});}catch{return}if(!s||typeof s!="object")return;let i=s,a=i.gates;if(a&&typeof a=="object"&&!Array.isArray(a)){let o=0;for(let l of Object.keys(a))l.startsWith("^")&&o++;o>0&&t.record("prefix-stripped","portal.yaml",o);}else Array.isArray(a)&&a.length>0&&t.record("array-coerced","portal.yaml");let c=i.routes;Array.isArray(c)&&c.length>0&&t.record("array-coerced","portal.yaml"),i.version||t.record("default-applied","portal.yaml");}function Qt(e,t){for(let n of e){let r;try{r=y.readFileSync(n,"utf-8");}catch{continue}try{k.load(r);}catch(u){(u?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=k.load(r,{schema:k.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let i=s,a=["components","features","gates","signals","aspects","states"],c=0;for(let u of a)Array.isArray(i[u])&&c++;c>0&&t.record("array-coerced","purpose.yaml",c);let o=(u,d)=>{if(!u||typeof u!="object"||Array.isArray(u))return 0;let p=0;for(let S of Object.keys(u))S.startsWith(d)&&p++;return p},l=o(i.gates,"^")+o(i.signals,"!")+o(i.aspects,"~")+o(i.components,"#")+o(i.features,"#");l>0&&t.record("prefix-stripped","purpose.yaml",l);}}function Zt(e,t){let n={};for(let r of t.symbols)if(r.type==="component"&&r.componentType){let s=r.componentType;n[s]||(n[s]=[]),n[s].push(r.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:en(e),key_files:tn(e),skip_patterns:nn(e),symbols:rn(t.symbols,t.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function en(e){let t={};for(let[n,r]of Object.entries(qt)){let s=r.filter(i=>y.existsSync(T.join(e,i)));if(s.length>0){let i=Object.values(Yt).find(a=>a.category===n);t[n]={paths:s,symbol:i?.prefix||"@"};}}return t}function tn(e){let t={};for(let[n,r]of Object.entries(Vt)){let s=r.filter(i=>y.existsSync(T.join(e,i)));s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function nn(e){let t={always:[...pe.always],unless_testing:[...pe.unless_testing],unless_docs:[...pe.unless_docs]},n=T.join(e,".gitignore");if(y.existsSync(n))try{let s=y.readFileSync(n,"utf8").split(`
93
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).filter(i=>i.endsWith("/")||i.includes("*")||["node_modules","dist","build",".cache"].some(a=>i.includes(a))).slice(0,20);for(let i of s)t.always.includes(i)||t.always.push(i);}catch{}return t}function sn(e){switch(e){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function rn(e,t,n){let r={};for(let s of e){let a=`${sn(s.type)}${s.id}`;if(s.filePath)r[a]=s.filePath;else {let c=t.find(o=>T.dirname(o).toLowerCase().includes(s.id.toLowerCase()));c&&(r[a]=T.dirname(c)+"/");}}return r}function on(e,t){let n={},r={};for(let s of t)try{let i=y.readFileSync(s,"utf8"),a=k.load(i);if(!a?.flows)continue;if(Array.isArray(a.flows))for(let c of a.flows){let o=c;if(!o.name)continue;let l=`$${o.name}`,u=Ve(o.steps);u.length>0&&(n[l]={id:l,description:o.description||"",steps:u,definedIn:T.relative(e,s)},Ke(l,u,r));}else for(let[c,o]of Object.entries(a.flows)){let l=c.startsWith("$")?c:`$${c}`,u=Ve(o.steps);u.length>0&&(n[l]={id:l,description:o.description||"",trigger:o.trigger,steps:u,validation:o.validation,definedIn:T.relative(e,s)},Ke(l,u,r));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:r}}function Ve(e){if(!e||!Array.isArray(e))return [];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(typeof r=="object"&&r!==null){let s=r,i=s.action||s.description||s.component||"";i&&t.push({id:s.id||`step-${n+1}`,action:i,symbol:s.symbol||s.component,expect:s.expect});}}return t}function Ke(e,t,n){for(let r of t)r.symbol&&(n[r.symbol]||(n[r.symbol]=[]),n[r.symbol].includes(e)||n[r.symbol].push(e));}export{Ae as a,te as b,Ue as c,We as d,wn as e,xn as f,_n as g,Rn as h,In as i,Ln as j,An as k,vn as l,kn as m,Ge as n,Pn as o,jn as p,$t as q,os as r,is as s,Kt as t};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b as b$1}from'./chunk-Y76OIMDO.js';import {a as a$2,g as g$1,h,d as d$2,f}from'./chunk-UIKLE3WD.js';import {g}from'./chunk-D6BSCELB.js';import {d}from'./chunk-K6TLYNRQ.js';import {c,d as d$1,e}from'./chunk-YNDPSWOE.js';import {a as a$1}from'./chunk-LKAT7IAK.js';import*as i from'fs';import*as a from'path';import {fileURLToPath}from'url';import t from'chalk';import q from'ora';function b(s){try{return i.readFileSync(s,"utf8").split(`
2
+ import {b as b$1}from'./chunk-PRZZL57E.js';import {a as a$2,g as g$1,h,d as d$2,f}from'./chunk-UIKLE3WD.js';import {g}from'./chunk-JOHPASZG.js';import {d}from'./chunk-K6TLYNRQ.js';import {c,d as d$1,e}from'./chunk-YNDPSWOE.js';import {a as a$1}from'./chunk-LKAT7IAK.js';import*as i from'fs';import*as a from'path';import {fileURLToPath}from'url';import t from'chalk';import q from'ora';function b(s){try{return i.readFileSync(s,"utf8").split(`
3
3
  `).length}catch{return 0}}function _(s){let o=g$1(s);if(o&&f[o])return f[o].name;let e=a$2(s);if(e!=="backend")return e.charAt(0).toUpperCase()+e.slice(1)}function U(s){let o=[],e=0,n={name:"cursor",displayName:"Cursor"},g=a.join(s,".cursorrules"),r=a.join(s,".cursor","rules");if(i.existsSync(g)){let l=b(g);n.legacy={path:".cursorrules",lines:l,type:"legacy"},e+=l;}if(i.existsSync(r)){let l=i.readdirSync(r).filter(m=>m.endsWith(".mdc"));l.length>0&&(n.modern=l.map(m=>{let x=a.join(r,m),j=b(x);return e+=j,{path:`.cursor/rules/${m}`,lines:j,type:"modern"}}));}(n.legacy||n.modern)&&o.push(n);let u={name:"copilot",displayName:"GitHub Copilot"},c=a.join(s,".github","copilot-instructions.md"),f=a.join(s,".github","instructions");if(i.existsSync(c)){let l=b(c);u.legacy={path:".github/copilot-instructions.md",lines:l,type:"legacy"},e+=l;}if(i.existsSync(f)){let l=i.readdirSync(f).filter(m=>m.endsWith(".md"));l.length>0&&(u.modern=l.map(m=>{let x=a.join(f,m),j=b(x);return e+=j,{path:`.github/instructions/${m}`,lines:j,type:"modern"}}));}(u.legacy||u.modern)&&o.push(u);let h=a.join(s,".windsurfrules");if(i.existsSync(h)){let l=b(h);o.push({name:"windsurf",displayName:"Windsurf",legacy:{path:".windsurfrules",lines:l,type:"legacy"}}),e+=l;}let w=a.join(s,"CLAUDE.md");if(i.existsSync(w)){let l=b(w);o.push({name:"claude",displayName:"Claude",legacy:{path:"CLAUDE.md",lines:l,type:"legacy"}}),e+=l;}let p=a.join(s,"AGENTS.md");if(i.existsSync(p)){let l=b(p);o.push({name:"agents",displayName:"AGENTS.md",legacy:{path:"AGENTS.md",lines:l,type:"legacy"}}),e+=l;}let y=a$2(s),d=g$1(s);return {ides:o,hasExisting:o.length>0,totalLines:e,projectType:_(s),discipline:y!=="backend"?y:void 0,stack:d||void 0}}function O(s,o){let e=[];e.push("# Migrate IDE Instructions to Paradigm Format"),e.push(""),e.push("## Overview"),e.push(""),e.push(`Migrate existing IDE instruction files for **${o}** to Paradigm's managed, scoped format.`),e.push(""),e.push("## Source Files Found"),e.push("");for(let n of s.ides)if(n.legacy&&e.push(`- \`${n.legacy.path}\` (${n.legacy.lines} lines) - ${n.displayName} ${n.legacy.type} format`),n.modern)for(let g of n.modern)e.push(`- \`${g.path}\` (${g.lines} lines) - ${n.displayName} modern format`);return e.push(""),s.ides.some(n=>n.name==="cursor")&&(e.push("## Cursor Migration \u2192 `.cursor/rules/*.mdc`"),e.push(""),e.push("Split the existing `.cursorrules` into scoped `.mdc` files with YAML frontmatter:"),e.push(""),e.push("### File Structure"),e.push(""),e.push("```"),e.push(".cursor/rules/"),e.push("\u251C\u2500\u2500 project-core.mdc # Always applies - project overview, architecture"),e.push("\u251C\u2500\u2500 code-style.mdc # globs: **/*.{ts,tsx,js,jsx} - naming, formatting"),e.push("\u251C\u2500\u2500 components.mdc # globs: **/components/**/* - component patterns"),e.push("\u251C\u2500\u2500 api-patterns.mdc # globs: **/api/**/* - API conventions"),e.push("\u251C\u2500\u2500 testing.mdc # globs: **/*.test.* - testing guidelines"),e.push("\u2514\u2500\u2500 custom.mdc # Any project-specific rules"),e.push("```"),e.push(""),e.push("### Frontmatter Format"),e.push(""),e.push("```yaml"),e.push("---"),e.push("description: Brief description of what these rules cover"),e.push('globs: "**/*.ts" # File pattern (OR use alwaysApply)'),e.push("alwaysApply: true # Apply to all files (OR use globs)"),e.push("---"),e.push("```"),e.push("")),s.ides.some(n=>n.name==="copilot")&&(e.push("## Copilot Migration \u2192 `.github/instructions/*.instructions.md`"),e.push(""),e.push("Split into scoped instruction files with `applyTo` frontmatter:"),e.push(""),e.push("### File Structure"),e.push(""),e.push("```"),e.push(".github/"),e.push("\u251C\u2500\u2500 copilot-instructions.md # Always applies - core rules"),e.push("\u2514\u2500\u2500 instructions/"),e.push(" \u251C\u2500\u2500 typescript.instructions.md # applyTo: **/*.ts"),e.push(" \u251C\u2500\u2500 react.instructions.md # applyTo: **/*.tsx"),e.push(" \u251C\u2500\u2500 api.instructions.md # applyTo: **/api/**"),e.push(" \u2514\u2500\u2500 testing.instructions.md # applyTo: **/*.test.*"),e.push("```"),e.push(""),e.push("### Frontmatter Format"),e.push(""),e.push("```yaml"),e.push("---"),e.push('applyTo: "**/*.ts"'),e.push("---"),e.push("```"),e.push("")),e.push("## Migration Steps"),e.push(""),e.push("1. **Read each source file** and identify logical sections:"),e.push(" - Project overview / architecture"),e.push(" - Code style / naming conventions"),e.push(" - Language-specific patterns"),e.push(" - Framework-specific rules"),e.push(" - Testing guidelines"),e.push(" - API patterns"),e.push(""),e.push("2. **Create scoped target files** with appropriate frontmatter"),e.push(""),e.push("3. **Backup originals** by renaming to `.bak`:"),e.push(" - `.cursorrules` \u2192 `.cursorrules.bak`"),e.push(" - `.github/copilot-instructions.md` \u2192 `.github/copilot-instructions.md.bak`"),e.push(""),e.push("4. **Verify** the migration by checking that rules apply correctly"),e.push(""),e.push("## Tips"),e.push(""),e.push("- **Prefer specific globs** over `alwaysApply` when possible"),e.push("- **Keep files focused** - one concern per file"),e.push("- **Use descriptive names** that indicate the scope"),e.push("- **Paradigm will generate its own rules** - keep custom rules separate"),e.push("- After migration, run `paradigm sync` to add Paradigm-managed rules"),e.push(""),e.push("---"),e.push(""),e.push("*Generated by `paradigm init --migrate`*"),e.join(`
4
4
  `)}function G(){let s=fileURLToPath(import.meta.url),o=a.dirname(s),e=[a.join(o,"..","..","templates","paradigm"),a.join(o,"..","templates","paradigm"),a.join(o,"..","..","src","templates","paradigm")];for(let n of e)if(i.existsSync(n))return n;return a.join(o,"..","templates","paradigm")}var A={directories:["prompts"],files:["echoes.yaml","docs/commands.md","docs/queries.md","specs/disciplines.md","specs/context-tracking.md"]};function z(s){for(let o of A.directories)if(s===o||s.startsWith(o+"/"))return true;return !!A.files.includes(s)}function N(s,o,e,n=""){i.existsSync(o)||i.mkdirSync(o,{recursive:true});let g=i.readdirSync(s,{withFileTypes:true});for(let r of g){let u=a.join(s,r.name),c=a.join(o,r.name),f=n?`${n}/${r.name}`:r.name;if(!z(f))if(r.isDirectory())N(u,c,e,f);else {let h=i.readFileSync(u,"utf8");h=h.replace(/\{\{PROJECT_NAME\}\}/g,e),i.writeFileSync(c,h,"utf8");}}}function M(s,o){if(console.log(t.blue(`
5
5
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(t.blue("\u2502")+t.white.bold(" Welcome to Paradigm ")+t.blue("\u2502")),console.log(t.blue("\u2502")+t.gray(" Let's set up your project ")+t.blue("\u2502")),console.log(t.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {g,h,i,j as j$1,k,l,m,n,o}from'./chunk-K6TLYNRQ.js';import {a,e}from'./chunk-ZJQY5PPP.js';import*as C from'fs';import*as E from'js-yaml';import {z}from'zod';import*as x from'path';var pe={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},de={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},me=["#","$","^","!","~"];function ye(e){return me.includes(e)}var ge=z.object({x:z.number(),y:z.number()}),he=z.object({x:z.number(),y:z.number(),zoom:z.number()}),Q=z.object({path:z.string(),include:z.array(z.string()).optional(),exclude:z.array(z.string()).optional()}),oe=z.object({id:z.string(),symbol:z.string(),type:z.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z.string().optional(),position:ge,tags:z.array(z.string()).optional(),created:z.string(),modified:z.string().optional()}),ne=z.object({from:z.string(),to:z.string(),label:z.string().optional(),type:z.string().optional()}),be=z.object({id:z.string(),name:z.string(),nodes:z.array(z.string()),color:z.string().optional()}),se=z.object({viewport:he,groups:z.array(be).optional()}),Se=z.object({nodes:z.array(oe),connections:z.array(ne),layout:se}),we=z.object({id:z.string(),name:z.string(),timestamp:z.string(),description:z.string().optional(),state:Se}),$e=z.object({version:z.string(),metadata:z.object({name:z.string(),created:z.string(),modified:z.string()}),sources:z.object({purpose:z.array(Q).optional(),portal:z.array(Q).optional()}),nodes:z.array(oe),connections:z.array(ne),layout:se,snapshots:z.array(we).optional()});function et(e){let t=[],o;try{o=C.readFileSync(e,"utf8");}catch(n){return t.push(`Cannot read file: ${n.message}`),{data:null,errors:t,rawContent:void 0}}return ve(o)}function ve(e){let t=[],o=null;try{o=E.load(e);}catch(s){let a=s,r=a.mark?.line?a.mark.line+1:void 0;return t.push(`YAML syntax error: ${a.reason||s.message}${r?` (line ${r})`:""}`),{data:null,errors:t,rawContent:e}}if(o==null)return {data:re(),errors:[],rawContent:e};let n=$e.safeParse(o);if(!n.success){for(let s of n.error.issues){let a=s.path.join(".");t.push(`Schema error at ${a||"/"}: ${s.message}`);}return {data:o,errors:t,rawContent:e}}return {data:n.data,errors:[],rawContent:e}}function re(e="Untitled"){let t=new Date().toISOString();return {version:"1.0.0",metadata:{name:e,created:t,modified:t},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function xe(e){return e.metadata.modified=new Date().toISOString(),E.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function tt(e="My Project"){return xe(re(e))}function ot(e,t){return {...e,nodes:[...e.nodes,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function nt(e,t,o){return {...e,nodes:e.nodes.map(n=>n.id===t?{...n,position:o,modified:new Date().toISOString()}:n),metadata:{...e.metadata,modified:new Date().toISOString()}}}function st(e,t){return e.connections.some(n=>n.from===t.from&&n.to===t.to)?e:{...e,connections:[...e.connections,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function rt(e,t,o){let n={id:`snap-${Date.now()}`,name:t,timestamp:new Date().toISOString(),description:o,state:{nodes:[...e.nodes],connections:[...e.connections],layout:{...e.layout}}};return {...e,snapshots:[...e.snapshots||[],n],metadata:{...e.metadata,modified:new Date().toISOString()}}}async function Pe(e$1,t){let o$1=[],n$1=[],s=[],a$1=[];if(e$1.sources.purpose)for(let l$1 of e$1.sources.purpose){let p=x.resolve(t,l$1.path);try{let d=await g(p);s.push(...d.map(c=>c.filePath));let m$1=h(d);for(let[c,{item:u,filePath:b}]of m$1){let T=["feature",...u.tags||[]];o$1.push(S({id:`purpose-feature-${c}`,symbol:`#${c}`,type:"component",source:"purpose",filePath:b,data:u,description:u.description,tags:T,componentType:u.type,parentSymbol:u.parent,anchors:u.anchors?.map(ue=>F(ue))}));}let h$1=i(d);for(let[c,{item:u,filePath:b}]of h$1)o$1.push(S({id:`purpose-component-${c}`,symbol:`#${c}`,type:"component",source:"purpose",filePath:b,data:u,description:u.description,tags:u.tags,componentType:u.type,parentSymbol:u.parent,anchors:u.anchors?.map(T=>F(T))}));let $=j$1(d);for(let[c,{item:u,filePath:b}]of $)o$1.push(S({id:`purpose-gate-${c}`,symbol:`^${c}`,type:"gate",source:"purpose",filePath:b,data:u,description:u.description}));let y=k(d);for(let[c,{item:u,filePath:b}]of y)o$1.push(S({id:`purpose-state-${c}`,symbol:`#${c}`,type:"component",source:"purpose",filePath:b,data:u,description:u.description,tags:["state"]}));let g$1=l(d);for(let[c,{item:u,filePath:b}]of g$1)o$1.push(S({id:`purpose-flow-${c}`,symbol:`$${c}`,type:"flow",source:"purpose",filePath:b,data:u,description:u.description}));let v=m(d);for(let[c,{item:u,filePath:b}]of v)o$1.push(S({id:`purpose-signal-${c}`,symbol:`!${c}`,type:"signal",source:"purpose",filePath:b,data:u,description:u.description}));let I=n(d);for(let[c,{item:u,filePath:b}]of I)o$1.push(S({id:`purpose-aspect-${c}`,symbol:`~${c}`,type:"aspect",source:"purpose",filePath:b,data:u,description:u.description,anchors:u.anchors?.map(T=>F(T)),appliesTo:u["applies-to"],tags:u.tags,enforcement:u.enforcement}));let k$1=o(d),w=new Set(o$1.map(c=>c.symbol));for(let c of k$1)w.has(c.symbol)||(w.add(c.symbol),o$1.push(S({id:`purpose-ref-${c.type}-${c.symbol.slice(1)}`,symbol:c.symbol,type:c.type,source:"purpose",filePath:c.filePath,data:{referencedFrom:c.sourceSymbol},description:`Referenced from ${c.sourceSymbol}`})));}catch(d){n$1.push({source:"purpose",filePath:p,message:d.message});}}if(e$1.sources.portal)for(let l of e$1.sources.portal){let p=x.resolve(t,l.path);try{let d;if(p.endsWith(".yaml")||p.endsWith(".yml"))d=await a(p),a$1.push(p);else {let m=await e(p);if(a$1.push(...m),m.length>0){d=await a(m[0]);for(let h=1;h<m.length;h++){let $=await a(m[h]);d.gates.push(...$.gates),d.flows.push(...$.flows);}}else continue}for(let m of d.gates){o$1.push(Ce(m,p));for(let h of m.prizes)o$1.push(S({id:`gate-signal-${m.id}-${h.id}`,symbol:`!${h.id}`,type:"signal",source:"portal",filePath:p,data:h,description:`Signal from gate ${m.id}`}));}for(let m of d.flows)o$1.push(Ae(m,p));}catch(d){n$1.push({source:"portal",filePath:p,message:d.message});}}for(let l of e$1.nodes){let p=l.tags?.includes("idea");if(!l.content&&!p){let d=o$1.find(m=>m.symbol===l.symbol);if(d){d.position=l.position,d.tags=l.tags;continue}}o$1.push(S({id:l.id,symbol:l.symbol,type:l.type,source:"premise",filePath:".premise",data:l,description:l.content,position:l.position,tags:l.tags,created:l.created,modified:l.modified}));}Ie(o$1);let r=new Map;for(let l of o$1){let p=r.get(l.symbol)||[];p.includes(l.filePath)||p.push(l.filePath),r.set(l.symbol,p);}let f=[];for(let[l,p]of r)p.length>1&&f.push({symbol:l,files:p});return {symbols:o$1,purposeFiles:s,portalFiles:a$1,errors:n$1,timestamp:Date.now(),...f.length>0?{duplicateSymbols:f}:{}}}function S(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function Ce(e,t){let o=e.id.startsWith("^")?e.id.slice(1):e.id;return S({id:`gate-${o}`,symbol:`^${o}`,type:"gate",source:"portal",filePath:t,data:e,description:e.description,position:e.position})}function Ae(e,t){return S({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:t,data:e,description:e.description})}function F(e){let t=e.lastIndexOf(":");if(t===-1||t===e.length-1)return {path:e,lines:0,raw:e};let o=e.slice(t+1),n=e.slice(0,t);if(!/^[\d,\- ]+$/.test(o))return {path:e,lines:0,raw:e};if(o.includes("-")){let[s,a]=o.split("-").map(Number);return {path:n,lines:[s,a],raw:e}}else if(o.includes(",")){let s=o.split(",").map(Number);return {path:n,lines:s,raw:e}}else return {path:n,lines:Number(o),raw:e}}var Re=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ie(e){let t=new Map(e.map(o=>[o.symbol,o]));for(let o of e){let n=JSON.stringify(o.data),s=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,a=(n.match(s)||[]).filter(r=>!Re.has(r));for(let r of a)if(r!==o.symbol&&t.has(r)){o.references.includes(r)||o.references.push(r);let f=t.get(r);f&&!f.referencedBy.includes(o.symbol)&&f.referencedBy.push(o.symbol);}}}async function Te(e){let t={metadata:{name:x.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Pe(t,e)}function Me(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function Oe(e){let t=Me();t.timestamp=e.timestamp;for(let o of e.symbols)t.entries.set(o.id,o),t.byType.has(o.type)||t.byType.set(o.type,[]),t.byType.get(o.type).push(o),t.bySource.has(o.source)||t.bySource.set(o.source,[]),t.bySource.get(o.source).push(o);return t}function P(e,t){for(let o of e.entries.values())if(o.symbol===t)return o}function ct(e,t){return e.entries.get(t)}function A(e,t){return e.byType.get(t)||[]}function lt(e,t){return e.bySource.get(t)||[]}function je(e,t){let o=t.toLowerCase(),n=[];for(let s of e.entries.values()){if(s.symbol.toLowerCase().includes(o)){n.push(s);continue}if(s.description?.toLowerCase().includes(o)){n.push(s);continue}if(s.tags?.some(a=>a.toLowerCase().includes(o))){n.push(s);continue}if(s.componentType?.toLowerCase().includes(o)){n.push(s);continue}}return n}function ft(e,t){return A(e,"component").filter(n=>n.componentType===t)}function ut(e){let t=new Set,o=A(e,"component");for(let n of o)n.componentType&&t.add(n.componentType);return Array.from(t).sort()}function pt(e,t){return A(e,"component").filter(n=>n.parentSymbol===t)}function Le(e,t){let o=P(e,t);return o?o.referencedBy.map(n=>P(e,n)).filter(n=>n!==void 0):[]}function Z(e,t){let o=P(e,t);return o?o.references.map(n=>P(e,n)).filter(n=>n!==void 0):[]}function dt(e,t){let o=[];for(let n of e.entries.values())n.tags?.includes(t)&&o.push(n);return o}function mt(e){let t=new Set;for(let o of e.entries.values())for(let n of o.tags||[])t.add(n);return Array.from(t).sort()}function yt(e){let t={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[o,n]of e.byType)o in t&&(t[o]=n.length);return t}function Ee(e){return Array.from(e.entries.values())}function ae(e){if(e.length<2)return null;let t=e[0],o=e.slice(1);return ye(t)?{type:de[t],name:o}:null}function gt(e,t){return `${pe[e]}${t}`}function ht(e){return ae(e)!==null}function bt(e,t,o=10){let n=t.toLowerCase(),s=ae(t);return s?A(e,s.type).filter(r=>r.symbol.toLowerCase().includes(n)).slice(0,o):je(e,t).slice(0,o)}function De(e,t,o){if(x.isAbsolute(e))return {resolvedPath:e,baseUsed:"absolute",exists:C.existsSync(e)};let n=x.join(o,e);if(C.existsSync(n))return {resolvedPath:n,baseUsed:"project-root",exists:true};let s=x.resolve(t,e);return C.existsSync(s)?{resolvedPath:s,baseUsed:"purpose-dir",exists:true}:{resolvedPath:n,baseUsed:"project-root",exists:false}}function St(e,t,o){if(x.isAbsolute(e)){let a=C.existsSync(e);return {rootResolves:a,purposeResolves:a,mismatch:false}}let n=C.existsSync(x.join(o,e)),s=C.existsSync(x.resolve(t,e));return {rootResolves:n,purposeResolves:s,mismatch:n!==s}}function _e(e,t){return e.includes("*")?new RegExp("^"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(t):e===t}function wt(e,t,o){let n=[],s=A(e,"aspect"),a=new Set;for(let r of s){let f=r.appliesTo||[];if(f.length!==0)for(let l of f)for(let p of t){if(!_e(l,p))continue;let d=r.anchors||[];if(d.length===0){let m=`${r.symbol}::__no-anchors__`;a.has(m)||(a.add(m),n.push({aspectSymbol:r.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let m=r.filePath?x.isAbsolute(r.filePath)?r.filePath:x.resolve(o,r.filePath):o,h=r.filePath?x.dirname(m):o;for(let $ of d){let y=`${r.symbol}::${$.raw}`;if(a.has(y))continue;De($.path,h,o).exists||(a.add(y),n.push({aspectSymbol:r.symbol,anchorRaw:$.raw,kind:"missing-file"}));}}}}return n}var ke=1,Fe=3,N=8,Ne=5,H={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},j={component:"component",flow:"flow",gate:"gate",signal:"signal",aspect:"aspect"};async function Be(e){let t=await Te(e),o=Oe(t),n=Ee(o).map(r=>r.symbol),s=new Map,a=new Map;for(let r of A(o,"flow")){let f=r.data,l=f?.sequence||f?.gates||r.references;if(Array.isArray(l))for(let p of l)typeof p!="string"||!p||(s.has(p)||s.set(p,new Set),s.get(p).add(r.symbol),a.has(r.symbol)||a.set(r.symbol,new Set),a.get(r.symbol).add(p));}return {index:o,allSymbols:n,symbolFlows:s,flowMembers:a,generatedAt:new Date().toISOString()}}function ze(e,t){let o=Ue(t.radius),n=t.mode??"ego",s=Ge(t.symbol,e),a={generatedAt:e.generatedAt,stale:false};if(!s||!P(e.index,s)){let y=Ve(t.symbol,e.allSymbols);return {root:t.symbol,freshness:a,nodes:[],edges:[],truncated:false,didYouMean:y}}let r=new Set([s]),f=new Set([s]),l=new Map,p=new Map,d=false,m=[s];for(let y=0;y<o;y++){let g=[];for(let v of m){let I=Ye(v,e,n),k=I.slice(0,N);if(I.length>N){d=true;let w=I.length-N,c=`${v}::+more`;f.add(c),l.set(`${v}|${c}|uses`,{source:v,target:c,kind:"uses"}),p.set(c,w);}for(let{target:w,kind:c}of k){let u=`${v}|${w}|${c}`;l.has(u)||l.set(u,{source:v,target:w,kind:c}),f.add(w),r.has(w)||(r.add(w),g.push(w));}}if(m=g,m.length===0)break}let h=[];for(let y of f){if(p.has(y)){h.push({id:y,kind:"component",label:`+${p.get(y)} more`});continue}let g=P(e.index,y),v=ce(y,g);h.push({id:y,kind:v,label:Ke(y,g),...g?.filePath?{path:g.filePath}:{}});}h.sort((y,g)=>y.id.localeCompare(g.id));let $=Array.from(l.values()).sort((y,g)=>y.source!==g.source?y.source.localeCompare(g.source):y.target!==g.target?y.target.localeCompare(g.target):y.kind.localeCompare(g.kind));return {root:s,freshness:a,nodes:h,edges:$,truncated:d}}async function $t(e,t){let o=await Be(e);return ze(o,t)}function vt(e){let t=["graph LR"],o=new Map,n=0;for(let s of e.nodes){let a=`n${n++}`;o.set(s.id,a);let r=qe(s.kind,s.id,s.label);t.push(` ${a}${r}`);}for(let s of e.edges){let a=o.get(s.source),r=o.get(s.target);!a||!r||t.push(` ${a} -->|${s.kind}| ${r}`);}return t.join(`
3
+ `)}function Ue(e){let t=typeof e=="number"&&!Number.isNaN(e)?Math.floor(e):ke;return Math.min(Math.max(t,1),Fe)}function L(e){return e.replace(/^[#$^!~@%?&]{1,2}/,"")}function ie(e){let t=/^[#$^!~]/.exec(e);return t?t[0]:""}function ce(e,t){if(t?.type&&j[t.type])return j[t.type];let o=ie(e);return o&&H[o]?H[o]:"component"}function Ke(e,t){return t?.data?.name||L(e)}function Ge(e,t){if(!e)return null;if(P(t.index,e))return e;let o=L(e);for(let n of ["#","$","$$","^","!","~"]){let s=`${n}${o}`;if(P(t.index,s))return s}return null}function Ye(e,t,o){let n=new Map,s=(r,f)=>{!r||r===e||n.set(`${r}|${f}`,{target:r,kind:f});};if(o==="ego"||o==="ripple"){for(let r of Z(t.index,e))s(r.symbol,Xe(r));for(let r of Le(t.index,e))B(r)==="flow"&&(t.symbolFlows.get(e)?.has(r.symbol)??false)?s(r.symbol,"in-flow"):s(r.symbol,"used-by");}else for(let r of Z(t.index,e))B(r)==="flow"&&s(r.symbol,"in-flow");for(let r of t.symbolFlows.get(e)||[])s(r,"in-flow");if(o==="flow")for(let r of t.symbolFlows.get(e)||[])for(let f of t.flowMembers.get(r)||[])s(f,"uses");return Array.from(n.values()).sort((r,f)=>r.target!==f.target?r.target.localeCompare(f.target):r.kind.localeCompare(f.kind))}function B(e){return e.type&&j[e.type]?j[e.type]:ce(e.symbol)}function Xe(e){let t=B(e);return t==="gate"?"gated-by":t==="flow"?"in-flow":"uses"}function Ve(e,t){let o=L(e).toLowerCase(),n=[];for(let s of t){let a=L(s).toLowerCase();if(a===o){n.push({sym:s,dist:0});continue}if(a.includes(o)||o.includes(a)){n.push({sym:s,dist:1});continue}let r=We(o,a);r<=4&&n.push({sym:s,dist:r});}return n.sort((s,a)=>s.dist!==a.dist?s.dist-a.dist:s.sym.localeCompare(a.sym)),n.slice(0,Ne).map(s=>s.sym)}function We(e,t){let o=e.length,n=t.length;if(o===0)return n;if(n===0)return o;let s=new Array(n+1),a=new Array(n+1);for(let r=0;r<=n;r++)s[r]=r;for(let r=1;r<=o;r++){a[0]=r;for(let f=1;f<=n;f++){let l=e[r-1]===t[f-1]?0:1;a[f]=Math.min(s[f]+1,a[f-1]+1,s[f-1]+l);}[s,a]=[a,s];}return s[n]}function qe(e,t,o){let n=Je(`${ie(t)||""}${o}`);switch(e){case "flow":return `([${n}])`;case "gate":return `{{${n}}}`;case "signal":return `[/${n}/]`;case "aspect":return `[[${n}]]`;default:return `(${n})`}}function Je(e){return `"${e.replace(/"/g,"'")}"`}var le=x.join(".paradigm","events"),Qe="classroom-certifications.jsonl",Ze="field-failures.jsonl";function fe(e){try{return C.existsSync(e)?C.readFileSync(e,"utf8").trim().split(`
4
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function xt(e){return fe(x.join(e,le,Qe))}function Pt(e){return fe(x.join(e,le,Ze))}function ee(e,t){return e>0?Number((t/e).toFixed(3)):null}function Ct(e){let t=0,o=0,n={};for(let s of e){let a=s.agent;if(!a)continue;let r=s.outcome==="overturned";if(!(r||s.outcome==="survived"))continue;let l=n[a]??{resolved:0,overturned:0,rate:null};l.resolved+=1,r&&(l.overturned+=1),n[a]=l,t+=1,r&&(o+=1);}for(let s of Object.keys(n)){let a=n[s];a.rate=ee(a.resolved,a.overturned);}return {overall:ee(t,o),perAgent:n}}export{mt as A,yt as B,Ee as C,ae as D,gt as E,ht as F,bt as G,De as H,St as I,wt as J,Be as K,ze as L,$t as M,vt as N,xt as O,Pt as P,Ct as Q,pe as a,de as b,et as c,ve as d,re as e,xe as f,tt as g,ot as h,nt as i,st as j,rt as k,Pe as l,Te as m,Me as n,Oe as o,P as p,ct as q,A as r,lt as s,je as t,ft as u,ut as v,pt as w,Le as x,Z as y,dt as z};