@a-company/paradigm 5.37.11 → 6.0.2
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.
- package/dist/{accept-orchestration-SBZVK3H4.js → accept-orchestration-QQISPINV.js} +1 -1
- package/dist/add-UOR4INIV.js +8 -0
- package/dist/{agent-loader-RIVI6QPP.js → agent-loader-2WJHD46U.js} +1 -1
- package/dist/{agent-loader-RJRVO5GQ.js → agent-loader-YKS2PQWO.js} +1 -1
- package/dist/{aggregate-W66DM3GA.js → aggregate-A5S5MTCC.js} +1 -1
- package/dist/{ambient-76YMUA5Q.js → ambient-BE3SQXNN.js} +1 -1
- package/dist/{ambient-WTLYUAQM.js → ambient-NVKQCW2A.js} +12 -12
- package/dist/{assess-UFPYEJKP.js → assess-63WXHWJV.js} +1 -1
- package/dist/{beacon-5QVYV5DF.js → beacon-QVUD3MGP.js} +1 -1
- package/dist/{calibration-OLJYB5HN.js → calibration-BDHGYJOK.js} +1 -1
- package/dist/{chunk-SI6SV76D.js → chunk-3DZK54RU.js} +72 -19
- package/dist/{chunk-CHVQNRRT.js → chunk-4PSD5R7N.js} +2 -2
- package/dist/chunk-6SKSV5B2.js +24 -0
- package/dist/{chunk-KFNHCQ4R.js → chunk-FEYOQMZ5.js} +1 -1
- package/dist/{chunk-NEJ4ZLCY.js → chunk-GAFKOFAV.js} +1 -1
- package/dist/chunk-GRZQIKST.js +2 -0
- package/dist/{chunk-RLCH7DXQ.js → chunk-K7X3Z3GL.js} +1 -1
- package/dist/chunk-LPBCQM5Y.js +6 -0
- package/dist/{chunk-T6IDXUUA.js → chunk-LWAIVOSF.js} +1 -1
- package/dist/{chunk-74SGKSRQ.js → chunk-M2HKWR25.js} +1 -1
- package/dist/{chunk-BOYQAMGC.js → chunk-M3PPXJU4.js} +1 -1
- package/dist/chunk-PHEX6LU4.js +111 -0
- package/dist/chunk-Q527BPUF.js +2 -0
- package/dist/chunk-R5ECMBIV.js +11 -0
- package/dist/{chunk-X3U3IGYT.js → chunk-TBWWFRL5.js} +1 -1
- package/dist/{chunk-MQIG6SMF.js → chunk-TNVWGPCE.js} +1 -1
- package/dist/{chunk-SUU6M4JH.js → chunk-TOYQ2QCB.js} +1 -1
- package/dist/chunk-TZDYIPVU.js +521 -0
- package/dist/{chunk-3XGNXXCT.js → chunk-UZ5H7K6Q.js} +1 -1
- package/dist/chunk-VIG5LSGZ.js +2 -0
- package/dist/chunk-VNIX5KBT.js +3 -0
- package/dist/{chunk-AGFPVSX5.js → chunk-VXIIVMTM.js} +1 -1
- package/dist/{chunk-ORDKEGII.js → chunk-WESTEMIM.js} +1 -1
- package/dist/{chunk-LBQBWIEX.js → chunk-Y4P4SGZV.js} +1 -1
- package/dist/{chunk-DOCDDDTD.js → chunk-YNDPSWOE.js} +5 -5
- package/dist/chunk-Z5QW6USC.js +2 -0
- package/dist/chunk-ZJQY5PPP.js +7 -0
- package/dist/{commands-LMUD5L6R.js → commands-ANRJNG2W.js} +1 -1
- package/dist/compliance-BNFWQPKM.js +6 -0
- package/dist/config-schema-FLHRVZMI.js +2 -0
- package/dist/{constellation-CG7C4WFE.js → constellation-NWLXYATA.js} +1 -1
- package/dist/{context-audit-XRPT3OU2.js → context-audit-JVCA6GSV.js} +1 -1
- package/dist/{cost-IDNVMAEV.js → cost-24UZSS2P.js} +1 -1
- package/dist/{cursorrules-U5O4G5T4.js → cursorrules-ZXPXPZ3P.js} +1 -1
- package/dist/decision-loader-HELL2AMX.js +2 -0
- package/dist/{delete-P5VULXR4.js → delete-2C6ALLYY.js} +1 -1
- package/dist/{diff-JVEYCXUC.js → diff-MF55KQZH.js} +1 -1
- package/dist/{dist-KGRCLBJP-2QAPFYNF.js → dist-GQ42YS5N-4HIJZVBB.js} +10 -10
- package/dist/dist-JZZJLVMR.js +2 -0
- package/dist/{dist-3ZCH25SG.js → dist-OG6MM4VY.js} +1 -1
- package/dist/dist-SE67SOXB.js +2 -0
- package/dist/{docs-USDAF26F.js → docs-O37YLLRN.js} +1 -1
- package/dist/doctor-IG5XM4C4.js +2 -0
- package/dist/{edit-GUU3HBVW.js → edit-P3MDAZLU.js} +1 -1
- package/dist/{flow-POQP27WA.js → flow-BGXOVE2V.js} +1 -1
- package/dist/{hooks-IG2GOAHP.js → hooks-TFMMMB2H.js} +1 -1
- package/dist/index.js +6 -6
- package/dist/init-M44SO65G.js +2 -0
- package/dist/init-V4KSEKPK.js +2 -0
- package/dist/{integrity-UYDOOJDP.js → integrity-ROO3G43N.js} +1 -1
- package/dist/{list-YKIQNKGB.js → list-2XIWUEMA.js} +1 -1
- package/dist/list-CFHINXIS.js +12 -0
- package/dist/lore-loader-D2ISOASW.js +2 -0
- package/dist/lore-loader-PXFKMKAN.js +2 -0
- package/dist/mcp.js +19 -11
- package/dist/metrics-UESGUHTA.js +2 -0
- package/dist/{migrate-IBDE7VK4.js → migrate-Z5UQN57G.js} +1 -1
- package/dist/migrate-assessments-YSITX7KM.js +4 -0
- package/dist/migrate-decisions-NPLQOEEH.js +6 -0
- package/dist/migrate-plsat-EM2ACIQ3.js +6 -0
- package/dist/{nomination-engine-EALA5MGI.js → nomination-engine-QPZJH6XO.js} +1 -1
- package/dist/{notebook-loader-PXNRBBXD.js → notebook-loader-3J2OFMS3.js} +1 -1
- package/dist/{orchestrate-RCAMBOIB.js → orchestrate-RID7HHHH.js} +1 -1
- package/dist/{platform-server-DNAMH4YI.js → platform-server-UD45NTGV.js} +1 -1
- package/dist/portal-check-DV2VSJ5E.js +8 -0
- package/dist/{portal-compliance-4MG5F2GI.js → portal-compliance-JONQ4SOP.js} +1 -1
- package/dist/{probe-B22G2JKF.js → probe-5HAXULAD.js} +1 -1
- package/dist/{providers-AWA7WLLM.js → providers-4PXMWA7V.js} +1 -1
- package/dist/quiz-WYIZJG5K.js +10 -0
- package/dist/{record-YXPB34MY.js → record-N3VNYYKJ.js} +1 -1
- package/dist/reindex-FWPD2VGM.js +2 -0
- package/dist/{retag-N5XF3KXP.js → retag-72R2OSZV.js} +1 -1
- package/dist/{review-77QI6VOC.js → review-2INNWLTW.js} +1 -1
- package/dist/{review-6UAH6V3R.js → review-VMSX2PKI.js} +1 -1
- package/dist/{ripple-ZGDITCGB.js → ripple-FNZI47SH.js} +1 -1
- package/dist/{sentinel-HYAZ3CO5.js → sentinel-EFPEX246.js} +1 -1
- package/dist/{sentinel-bridge-VR357PKL.js → sentinel-bridge-UR2MKARY.js} +1 -1
- package/dist/sentinel.js +1 -1
- package/dist/{serve-U47GULB6.js → serve-MO35XIZE.js} +1 -1
- package/dist/serve-OQYUO7CR.js +12 -0
- package/dist/{server-4YNUIK4W.js → server-4D77LCST.js} +1 -1
- package/dist/server-FGUL2FWQ.js +7 -0
- package/dist/session-tracker-KGORN6B5.js +2 -0
- package/dist/{session-work-log-PAKXOFGL.js → session-work-log-4IEVE4KK.js} +1 -1
- package/dist/{session-work-log-ZP45TREI.js → session-work-log-EE4UIZ33.js} +1 -1
- package/dist/{setup-3F5IK7MO.js → setup-ZSEC72BS.js} +2 -2
- package/dist/{shift-FDADESC4.js → shift-TVNY2CQF.js} +6 -6
- package/dist/{show-PJ5LFLIL.js → show-JH7LJ5MT.js} +1 -1
- package/dist/show-WVHAL4VU.js +7 -0
- package/dist/{snapshot-L2G56RPL.js → snapshot-3IYB67D4.js} +1 -1
- package/dist/{spawn-M5BAV252.js → spawn-UH5RENSE.js} +1 -1
- package/dist/{status-77M3SDIF.js → status-DB3KNLW3.js} +1 -1
- package/dist/status-S7Z5FVIE.js +6 -0
- package/dist/{summary-LXLHFRN7.js → summary-WLI3NF4G.js} +2 -2
- package/dist/{sweep-HU74OPVW.js → sweep-7TZFN5NS.js} +1 -1
- package/dist/sync-55U6QPIA.js +2 -0
- package/dist/{sync-llms-7CAI74QL.js → sync-llms-GF7DDQDI.js} +1 -1
- package/dist/team-MGT66HZQ.js +2 -0
- package/dist/{test-BQJMS4Y2.js → test-WLEPZQFC.js} +1 -1
- package/dist/{timeline-K3ZFKJ3R.js → timeline-RK7O2SCM.js} +1 -1
- package/dist/tools-QJHAVYI6.js +2 -0
- package/dist/university-content/notes/N-para-001-build-something.md +126 -0
- package/dist/university-content/notes/N-para-001-meet-the-team.md +85 -0
- package/dist/university-content/notes/N-para-001-shift-setup.md +74 -0
- package/dist/university-content/notes/N-para-101-component-types.md +99 -0
- package/dist/university-content/notes/N-para-101-first-steps.md +134 -0
- package/dist/university-content/notes/N-para-101-five-symbols.md +128 -0
- package/dist/university-content/notes/N-para-101-paradigm-logger.md +89 -0
- package/dist/university-content/notes/N-para-101-portal-yaml.md +112 -0
- package/dist/university-content/notes/N-para-101-project-structure.md +143 -0
- package/dist/university-content/notes/N-para-101-purpose-files.md +121 -0
- package/dist/university-content/notes/N-para-101-tags-and-classification.md +93 -0
- package/dist/university-content/notes/N-para-101-welcome.md +51 -0
- package/dist/university-content/notes/N-para-201-architecture-review.md +175 -0
- package/dist/university-content/notes/N-para-201-aspect-graph.md +79 -0
- package/dist/university-content/notes/N-para-201-aspects-and-anchors.md +112 -0
- package/dist/university-content/notes/N-para-201-component-patterns.md +138 -0
- package/dist/university-content/notes/N-para-201-cross-cutting-concerns.md +145 -0
- package/dist/university-content/notes/N-para-201-disciplines.md +187 -0
- package/dist/university-content/notes/N-para-201-flows-deep-dive.md +119 -0
- package/dist/university-content/notes/N-para-201-gates-deep-dive.md +165 -0
- package/dist/university-content/notes/N-para-201-portal-protocol.md +133 -0
- package/dist/university-content/notes/N-para-201-signal-patterns.md +159 -0
- package/dist/university-content/notes/N-para-201-symbol-naming.md +149 -0
- package/dist/university-content/notes/N-para-301-context-management.md +53 -0
- package/dist/university-content/notes/N-para-301-decisions.md +99 -0
- package/dist/university-content/notes/N-para-301-doctor-and-validation.md +70 -0
- package/dist/university-content/notes/N-para-301-enforcement-levels.md +102 -0
- package/dist/university-content/notes/N-para-301-fragility-tracking.md +50 -0
- package/dist/university-content/notes/N-para-301-history-system.md +42 -0
- package/dist/university-content/notes/N-para-301-navigation-system.md +55 -0
- package/dist/university-content/notes/N-para-301-operations-review.md +55 -0
- package/dist/university-content/notes/N-para-301-paradigm-shift.md +93 -0
- package/dist/university-content/notes/N-para-301-protocols.md +113 -0
- package/dist/university-content/notes/N-para-301-ripple-analysis.md +53 -0
- package/dist/university-content/notes/N-para-301-sentinel-observability.md +87 -0
- package/dist/university-content/notes/N-para-301-sync-and-maintenance.md +57 -0
- package/dist/university-content/notes/N-para-301-wisdom-system.md +89 -0
- package/dist/university-content/notes/N-para-401-agent-identity.md +99 -0
- package/dist/university-content/notes/N-para-401-agent-interop.md +87 -0
- package/dist/university-content/notes/N-para-401-agent-roles.md +107 -0
- package/dist/university-content/notes/N-para-401-commit-conventions.md +82 -0
- package/dist/university-content/notes/N-para-401-mastery-review.md +71 -0
- package/dist/university-content/notes/N-para-401-mcp-tools-overview.md +102 -0
- package/dist/university-content/notes/N-para-401-multi-agent-coordination.md +80 -0
- package/dist/university-content/notes/N-para-401-notebooks-permissions.md +66 -0
- package/dist/university-content/notes/N-para-401-orchestration-workflow.md +101 -0
- package/dist/university-content/notes/N-para-401-pm-governance.md +71 -0
- package/dist/university-content/notes/N-para-401-provider-cascade.md +75 -0
- package/dist/university-content/notes/N-para-401-quick-check.md +95 -0
- package/dist/university-content/notes/N-para-501-advanced-workflows.md +122 -0
- package/dist/university-content/notes/N-para-501-aspect-graph-advanced.md +195 -0
- package/dist/university-content/notes/N-para-501-aspect-graph-internals.md +97 -0
- package/dist/university-content/notes/N-para-501-assessment-loops.md +116 -0
- package/dist/university-content/notes/N-para-501-conductor-workspace.md +77 -0
- package/dist/university-content/notes/N-para-501-habits-practice.md +164 -0
- package/dist/university-content/notes/N-para-501-hook-enforcement.md +100 -0
- package/dist/university-content/notes/N-para-501-lore-system.md +155 -0
- package/dist/university-content/notes/N-para-501-platform-agent-ui.md +108 -0
- package/dist/university-content/notes/N-para-501-review-compliance.md +72 -0
- package/dist/university-content/notes/N-para-501-sentinel-deep-dive.md +173 -0
- package/dist/university-content/notes/N-para-501-session-intelligence.md +104 -0
- package/dist/university-content/notes/N-para-501-symphony-a-mail.md +120 -0
- package/dist/university-content/notes/N-para-501-symphony-networking.md +119 -0
- package/dist/university-content/notes/N-para-501-task-management.md +100 -0
- package/dist/university-content/notes/N-para-601-agent-renaissance.md +121 -0
- package/dist/university-content/notes/N-para-601-attention-scoring.md +129 -0
- package/dist/university-content/notes/N-para-601-context-composition.md +146 -0
- package/dist/university-content/notes/N-para-601-data-sovereignty.md +140 -0
- package/dist/university-content/notes/N-para-601-event-stream.md +126 -0
- package/dist/university-content/notes/N-para-601-knowledge-streams.md +144 -0
- package/dist/university-content/notes/N-para-601-learning-loop.md +68 -0
- package/dist/university-content/notes/N-para-601-maestro-team-collab.md +136 -0
- package/dist/university-content/notes/N-para-601-nominations-debates.md +115 -0
- package/dist/university-content/notes/N-para-701-agent-notebooks.md +131 -0
- package/dist/university-content/notes/N-para-701-agent-pods-nevrland.md +182 -0
- package/dist/university-content/notes/N-para-701-agent-profiles.md +197 -0
- package/dist/university-content/notes/N-para-701-agent-roster.md +82 -0
- package/dist/university-content/notes/N-para-701-agent-state.md +180 -0
- package/dist/university-content/notes/N-para-701-learning-feedback-loop.md +188 -0
- package/dist/university-content/notes/N-para-701-model-tier-resolution.md +204 -0
- package/dist/university-content/notes/N-para-701-orchestration-enforcement.md +169 -0
- package/dist/university-content/notes/N-para-701-per-project-rosters.md +198 -0
- package/dist/university-content/notes/N-para-701-symphony-visibility.md +142 -0
- package/dist/university-content/paths/LP-para-001.yaml +29 -0
- package/dist/university-content/paths/LP-para-101.yaml +59 -0
- package/dist/university-content/paths/LP-para-201.yaml +69 -0
- package/dist/university-content/paths/LP-para-301.yaml +84 -0
- package/dist/university-content/paths/LP-para-401.yaml +74 -0
- package/dist/university-content/paths/LP-para-501.yaml +89 -0
- package/dist/university-content/paths/LP-para-601.yaml +59 -0
- package/dist/university-content/paths/LP-para-701.yaml +64 -0
- package/dist/university-content/quizzes/Q-para-001-build-something.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-001-meet-the-team.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-001-shift-setup.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-101-component-types.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-101-first-steps.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-101-five-symbols.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-101-paradigm-logger.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-101-portal-yaml.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-101-project-structure.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-101-purpose-files.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-101-tags-and-classification.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-101-welcome.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-architecture-review.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-201-aspect-graph.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-201-aspects-and-anchors.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-component-patterns.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-cross-cutting-concerns.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-disciplines.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-201-flows-deep-dive.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-201-gates-deep-dive.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-201-portal-protocol.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-signal-patterns.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-201-symbol-naming.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-301-context-management.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-301-decisions.yaml +76 -0
- package/dist/university-content/quizzes/Q-para-301-doctor-and-validation.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-301-enforcement-levels.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-301-fragility-tracking.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-301-history-system.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-301-navigation-system.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-301-operations-review.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-301-paradigm-shift.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-301-protocols.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-301-ripple-analysis.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-301-sentinel-observability.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-301-sync-and-maintenance.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-301-wisdom-system.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-401-agent-identity.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-401-agent-interop.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-401-agent-roles.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-401-commit-conventions.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-401-mastery-review.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-401-mcp-tools-overview.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-401-multi-agent-coordination.yaml +76 -0
- package/dist/university-content/quizzes/Q-para-401-notebooks-permissions.yaml +61 -0
- package/dist/university-content/quizzes/Q-para-401-orchestration-workflow.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-401-pm-governance.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-401-provider-cascade.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-401-quick-check.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-501-advanced-workflows.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-aspect-graph-advanced.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-aspect-graph-internals.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-assessment-loops.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-501-conductor-workspace.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-501-habits-practice.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-501-hook-enforcement.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-lore-system.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-platform-agent-ui.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-review-compliance.yaml +61 -0
- package/dist/university-content/quizzes/Q-para-501-sentinel-deep-dive.yaml +86 -0
- package/dist/university-content/quizzes/Q-para-501-session-intelligence.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-symphony-a-mail.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-symphony-networking.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-501-task-management.yaml +46 -0
- package/dist/university-content/quizzes/Q-para-601-agent-renaissance.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-601-attention-scoring.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-601-context-composition.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-601-data-sovereignty.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-601-event-stream.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-601-knowledge-streams.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-601-learning-loop.yaml +56 -0
- package/dist/university-content/quizzes/Q-para-601-maestro-team-collab.yaml +86 -0
- package/dist/university-content/quizzes/Q-para-601-nominations-debates.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-agent-notebooks.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-agent-pods-nevrland.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-agent-profiles.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-agent-roster.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-agent-state.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-learning-feedback-loop.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-model-tier-resolution.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-orchestration-enforcement.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-per-project-rosters.yaml +66 -0
- package/dist/university-content/quizzes/Q-para-701-symphony-visibility.yaml +66 -0
- package/dist/university-content/quizzes/Q-plsat-v2.yaml +904 -0
- package/dist/university-content/quizzes/Q-plsat-v3.yaml +2909 -0
- package/dist/university-content/reference.json +2 -2
- package/dist/university-ui/assets/{index-CecQrfSn.js → index-nNgzO1il.js} +2 -2
- package/dist/university-ui/assets/{index-CecQrfSn.js.map → index-nNgzO1il.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- package/dist/{upgrade-GX56QE3C.js → upgrade-NKN63VTY.js} +2 -2
- package/dist/{validate-VZXTJHGO.js → validate-BB6LRWIY.js} +1 -1
- package/dist/validate-XUQZTF3H.js +9 -0
- package/dist/{watch-YCODNIET.js → watch-25GJHQYT.js} +1 -1
- package/dist/workspace-VMSPYIBV.js +2 -0
- package/lore-ui/dist/assets/{index-Bk-K0qgN.js → index-DKhNxgtW.js} +10 -10
- package/lore-ui/dist/index.html +1 -1
- package/package.json +3 -2
- package/platform-ui/dist/assets/{AmbientSection-BYjt75R1.js → AmbientSection-CwatqcBD.js} +1 -1
- package/platform-ui/dist/assets/{CanvasSection-rKvA_vZj.js → CanvasSection-dFAthehN.js} +1 -1
- package/platform-ui/dist/assets/{DocsSection-CI9K73M-.js → DocsSection-BZ2SFJBZ.js} +1 -1
- package/platform-ui/dist/assets/{GitSection-DSGj_c6S.js → GitSection-MNNYU1tO.js} +1 -1
- package/platform-ui/dist/assets/{GraphSection-CawN7pC5.js → GraphSection-COYjb4Pt.js} +1 -1
- package/platform-ui/dist/assets/LoreSection-B0hUbfsJ.js +1 -0
- package/platform-ui/dist/assets/{SentinelSection-DNgoYMH0.js → SentinelSection-BCxW1DCp.js} +1 -1
- package/platform-ui/dist/assets/{SymphonySection-C0zfcqv3.js → SymphonySection-BsucZRqy.js} +1 -1
- package/platform-ui/dist/assets/{TeamSection-Bzd3Dt9Q.js → TeamSection-C0QNTudW.js} +1 -1
- package/platform-ui/dist/assets/{UniversitySection-tBr62R0S.js → UniversitySection-DN1-g9pw.js} +1 -1
- package/platform-ui/dist/assets/{index-BaOmyn11.js → index-DwUT8pju.js} +2 -2
- package/platform-ui/dist/index.html +1 -1
- package/templates/paradigm/specs/symbols.md +4 -2
- package/dist/add-P76GEMGF.js +0 -8
- package/dist/chunk-3TR6LLXP.js +0 -111
- package/dist/chunk-G7XFK2GI.js +0 -11
- package/dist/chunk-J6KWGCHN.js +0 -24
- package/dist/chunk-JQKKVAAN.js +0 -2
- package/dist/chunk-ODVKPZZ4.js +0 -2
- package/dist/chunk-Q2J542ST.js +0 -2
- package/dist/chunk-QT2LKB3P.js +0 -7
- package/dist/chunk-SHD27BQX.js +0 -6
- package/dist/chunk-WS2N27RX.js +0 -3
- package/dist/chunk-YT52WLBF.js +0 -521
- package/dist/compliance-WJINB5DM.js +0 -6
- package/dist/config-schema-GUQY2QN7.js +0 -2
- package/dist/decision-loader-2XPZE4EZ.js +0 -2
- package/dist/dist-R3RWD35F.js +0 -2
- package/dist/dist-VXCZWVVJ.js +0 -2
- package/dist/doctor-QJ47XAUP.js +0 -2
- package/dist/init-HIBRSVUB.js +0 -2
- package/dist/list-5IUGP3ZB.js +0 -7
- package/dist/lore-loader-RVQI5GXL.js +0 -2
- package/dist/lore-loader-XY5MZRR2.js +0 -2
- package/dist/migrate-assessments-GEI5WMI2.js +0 -4
- package/dist/portal-check-Z3OCQEQR.js +0 -8
- package/dist/quiz-FE5UGAY2.js +0 -10
- package/dist/reindex-FO5VMZVQ.js +0 -2
- package/dist/serve-OY6XYL7F.js +0 -12
- package/dist/server-2MNROHF6.js +0 -7
- package/dist/session-tracker-MWJAJA6Z.js +0 -2
- package/dist/show-BOAVWZPZ.js +0 -7
- package/dist/status-A37ECYNJ.js +0 -6
- package/dist/sync-DLUBV5HQ.js +0 -2
- package/dist/team-NSP6PMPS.js +0 -2
- package/dist/tools-CERDNVCG.js +0 -2
- package/dist/university-content/courses/.purpose +0 -492
- package/dist/university-content/courses/para-001.json +0 -166
- package/dist/university-content/courses/para-101.json +0 -615
- package/dist/university-content/courses/para-201.json +0 -794
- package/dist/university-content/courses/para-301.json +0 -830
- package/dist/university-content/courses/para-401.json +0 -868
- package/dist/university-content/courses/para-501.json +0 -1166
- package/dist/university-content/courses/para-601.json +0 -719
- package/dist/university-content/courses/para-701.json +0 -807
- package/dist/university-content/plsat/.purpose +0 -162
- package/dist/university-content/plsat/v2.0.json +0 -760
- package/dist/university-content/plsat/v3.0.json +0 -3453
- package/dist/validate-C6SMKGYD.js +0 -9
- package/dist/workspace-MKSQN7B2.js +0 -2
- package/platform-ui/dist/assets/LoreSection-oO5dCe6O.js +0 -1
- /package/dist/{chunk-BV5PRPLB.js → chunk-IZSBGW6E.js} +0 -0
- /package/templates/paradigm/specs/{scan.md → probe.md} +0 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a as a$2,b as b$4,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$3,a as a$3}from'./chunk-GRZQIKST.js';import {j as j$1,a,c as c$1,b as b$2,k}from'./chunk-TNVWGPCE.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as w from'fs';import*as P from'path';import*as se from'crypto';import {execSync}from'child_process';import*as z from'js-yaml';import {z as z$1}from'zod';import {glob}from'glob';import*as _e from'os';import Ws from'sql.js';var Qt={};c(Qt,{contentSearch:()=>Hs,detectFileRename:()=>Kt,generateFingerprint:()=>qt,levenshteinDistance:()=>Yt,levenshteinSimilarity:()=>qe,searchSiblingFiles:()=>Jt,slidingWindowSearch:()=>Ie});function qt(t){let e=t.split(`
|
|
3
|
+
`).filter(n=>n.trim()!=="");return {firstLine:Pe(e[0]||""),lastLine:Pe(e[e.length-1]||""),lineCount:e.length,structuralHash:Vt(e)}}function Vt(t){let e=t.map(n=>n.trim()).filter(n=>Bt.test(n)).map(n=>{let s=n.match(Bt);return s?s[1].trim():""}).join("|");return se.createHash("sha256").update(e).digest("hex").slice(0,16)}function Pe(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Yt(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;t.length>e.length&&([t,e]=[e,t]);let n=t.length,s=e.length;if(n>5e3||s>5e3)return Math.abs(n-s);let r=new Array(n+1),o=new Array(n+1);for(let i=0;i<=n;i++)r[i]=i;for(let i=1;i<=s;i++){o[0]=i;for(let a=1;a<=n;a++){let c=t[a-1]===e[i-1]?0:1;o[a]=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);}[r,o]=[o,r];}return r[n]}function qe(t,e){if(t.length===0&&e.length===0)return 1;let n=Math.max(t.length,e.length);return 1-Yt(t,e)/n}function Ie(t,e,n,s=3){let{lineCount:r}=e,o=Math.max(1,Math.floor(r*.8)),i=Math.ceil(r*1.2),a=[],c=Xe(n);for(let d of [r,o,i])if(!(d>t.length))for(let u=0;u<=t.length-d;u++){let p=t.slice(u,u+d),g=zs(p,e,c);if(g>=.5){let m=p.join(`
|
|
4
|
+
`);a.push({windowStart:u+1,windowEnd:u+d,similarity:qe(Xe(m),c),score:g});}}let l=new Map;for(let d of a){let u=l.get(d.windowStart);(!u||d.score>u.score)&&l.set(d.windowStart,d);}return Array.from(l.values()).sort((d,u)=>u.score-d.score).slice(0,s)}function zs(t,e,n){let s=t.filter(p=>p.trim()!=="");if(s.length===0)return 0;let r=0,o=Pe(s[0]),i=Pe(s[s.length-1]),a=0;o===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),r+=a*Ns,Vt(s)===e.structuralHash&&(r+=Ds);let l=s.join(`
|
|
5
|
+
`),d=qe(Xe(l),n);d>=.8&&(r+=(d-.8)/.2*Ms);let u=s.length/e.lineCount;if(u>=.8&&u<=1.2){let p=1-Math.abs(1-u)/.2;r+=p*Us;}return r}function Xe(t){return t.split(`
|
|
6
|
+
`).map(e=>e.trim()).filter(e=>e!=="").join(`
|
|
7
|
+
`)}function Kt(t,e){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let s=n.split(`
|
|
8
|
+
`);for(let r of s){let o=r.split(" ");if(o.length>=3&&o[0].startsWith("R"))return o[2]}return null}catch{return null}}function Jt(t,e,n,s,r=10){let o=P.isAbsolute(e)?e:P.join(t,e);if(!w.existsSync(o))return [];let i=[];try{let a=w.readdirSync(o).filter(c=>!c.startsWith(".")&&w.statSync(P.join(o,c)).isFile()).slice(0,r);for(let c of a)try{let d=w.readFileSync(P.join(o,c),"utf8").split(`
|
|
9
|
+
`),u=Ie(d,n,s,1);if(u.length>0&&u[0].score>=.7){let p=P.relative(t,P.join(o,c));i.push({file:p,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return i.sort((a,c)=>c.score-a.score)}function Hs(t,e,n,s=true){let r=qt(n),o=P.isAbsolute(e)?e:P.join(t,e);if(w.existsSync(o)){let d=w.readFileSync(o,"utf8").split(`
|
|
10
|
+
`),u=Ie(d,r,n);if(u.length>0){let p=u[0];return {found:p.score>=.7,score:p.score,suggestedStart:p.windowStart,suggestedEnd:p.windowEnd,similarity:p.similarity}}}let i=Kt(t,e);if(i){let l=P.join(t,i);if(w.existsSync(l)){let u=w.readFileSync(l,"utf8").split(`
|
|
11
|
+
`),p=Ie(u,r,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:i,similarity:p[0].similarity}}}let a=P.dirname(e),c=Jt(t,a,r,n);if(c.length>0&&c[0].score>=.7){let l=c[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==e?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var Bt,Ns,Ds,Ms,Us,Zt=b(()=>{Bt=/^\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 )/;Ns=.4,Ds=.3,Ms=.2,Us=.1;});var De=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),gt=De.extend({id:z$1.string()}),Un=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),zn=z$1.union([Un,z$1.string().transform(t=>({description:t}))]),Hn=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),Wn=z$1.union([Hn,z$1.string()]),Gn=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),St=z$1.union([Gn,z$1.string()]),Bn=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(St)}),Xn=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(St).optional()}),qn=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),Vn=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),Yn=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),Kn=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Jn=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(gt),z$1.record(De)]).optional(),components:z$1.union([z$1.array(gt),z$1.record(De)]).optional(),gates:z$1.record(qn).optional(),states:z$1.record(Vn).optional(),signals:z$1.record(zn).optional(),aspects:z$1.record(Yn).optional(),relationships:z$1.array(Wn).optional(),flows:z$1.union([z$1.array(Bn),z$1.record(Xn)]).optional(),references:z$1.array(Kn).optional()});function Me(t){let e=Qn(t);return {data:e.data,errors:e.errors}}function Qn(t){let e=[],n=[],s;try{s=w.readFileSync(t,"utf8");}catch(a){let c=`Cannot read file: ${a.message}`;return e.push(c),n.push({message:c,type:"file"}),{data:null,errors:e,detailedErrors:n,rawContent:void 0,isYamlValid:false}}let r=s.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),o=null;try{o=z.load(r);}catch(a){let c=a,l=c.mark?.line?c.mark.line+1:void 0,d=`YAML syntax error: ${c.reason||a.message}`;return e.push(`${d}${l?` (line ${l})`:""}`),n.push({message:d,line:l,type:"yaml"}),{data:null,errors:e,detailedErrors:n,rawContent:s,isYamlValid:false}}if(o==null)return {data:{},errors:[],detailedErrors:[],rawContent:s,isYamlValid:true};if(typeof o=="object"&&o!==null){let a=o,c={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let l of Object.keys(a)){let d=l[0],u=c[d];if(!u||l.length<2)continue;let p=l.slice(1),g=a[l];if(typeof g!="object"||g===null)continue;let m=a[u]||{};u in a||(a[u]=m),p in m||(m[p]=g),delete a[l];}}let i=Jn.safeParse(o);if(!i.success){for(let a of i.error.issues){let c=a.path.join("."),l=a.message;e.push(`Schema error at ${c||"/"}: ${l}`),n.push({message:l,path:c||"/",type:"schema"});}return {data:o,errors:e,detailedErrors:n,rawContent:s,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:s,isYamlValid:true}}function Jr(t){return z.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function xe(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}async function es(t){let e=P.resolve(t);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((s,r)=>{let o=s.split(P.sep).length,i=r.split(P.sep).length;return o-i})}async function bt(t){let e=await es(t),n=[];for(let s of e){let{data:r,errors:o}=Me(s);r&&(n.push({filePath:s,data:r}),o.length>0&&console.warn(`Warnings parsing ${s}:`,o));}return n}function xt(t){let e=new Map;for(let{filePath:n,data:s}of t){let r=xe(s.features);for(let[o,i]of r)e.set(o,{item:i,filePath:n});}return e}function vt(t){let e=new Map;for(let{filePath:n,data:s}of t){let r=xe(s.components);for(let[o,i]of r)e.set(o,{item:i,filePath:n});}return e}function Et(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.gates)for(let[r,o]of Object.entries(s.gates))e.set(r,{item:o,filePath:n});return e}function Tt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.states)for(let[r,o]of Object.entries(s.states))e.set(r,{item:o,filePath:n});return e}function kt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.flows)if(Array.isArray(s.flows))for(let r of s.flows)e.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:n});else for(let[r,o]of Object.entries(s.flows))e.set(r,{item:{id:r,description:o.description,gates:o.gates,signals:o.signals,components:o.components,steps:o.steps},filePath:n});return e}function _t(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.signals)for(let[r,o]of Object.entries(s.signals))e.set(r,{item:o,filePath:n});return e}function Pt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.aspects)for(let[r,o]of Object.entries(s.aspects))e.set(r,{item:o,filePath:n});return e}function It(t){let e=[],n=new Set;for(let{filePath:s,data:r}of t){let o=xe(r.features);for(let[a,c]of o)ht(`#${a}`,c,s,e,n);let i=xe(r.components);for(let[a,c]of i)ht(`#${a}`,c,s,e,n);}return e}function ht(t,e,n,s,r){if(e.flows)for(let o of e.flows){let i=o.startsWith("$")?o:`$${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"flow",sourceSymbol:t,filePath:n}));}if(e.gates)for(let o of e.gates){let i=o.startsWith("^")?o:`^${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"gate",sourceSymbol:t,filePath:n}));}if(e.signals)for(let o of e.signals){let i=o.startsWith("!")?o:`!${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"signal",sourceSymbol:t,filePath:n}));}if(e.states)for(let o of e.states){let i=o.startsWith("#")?o:o.startsWith("%")?`#${o.slice(1)}`:`#${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.components)for(let o of e.components){let i=o.startsWith("#")?o:`#${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.aspects)for(let o of e.aspects){let i=o.startsWith("~")?o:`~${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"aspect",sourceSymbol:t,filePath:n}));}if(e.description){let o=ns(e.description);for(let{symbol:i,type:a}of o)r.has(i)||(r.add(i),s.push({symbol:i,type:a,sourceSymbol:t,filePath:n}));}}var ts=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function ns(t){let e=[],n=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,s;for(;(s=n.exec(t))!==null;){let r=s[1],o=s[2],i,a;switch(r){case "#":a="component",i=`#${o}`;break;case "$":a="flow",i=`$${o}`;break;case "^":a="gate",i=`^${o}`;break;case "!":a="signal",i=`!${o}`;break;case "~":a="aspect",i=`~${o}`;break;case "%":a="component",i=`#${o}`;break;default:continue}ts.has(i)||e.push({symbol:i,type:a});}return e}function de(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}function Ne(t){return t?Array.isArray(t)?t.map(e=>e.id):Object.keys(t):[]}function Zr(t,e){let n=[],s=e?`${e}: `:"",r=de(t.features);for(let[i,a]of r)yt(i,a,"feature",s,n);let o=de(t.components);for(let[i,a]of o)yt(i,a,"component",s,n);if(t.relationships){let i=new Set([...Ne(t.features),...Ne(t.components)]);for(let a of t.relationships){if(typeof a=="string"||!a||!a.from||!a.to)continue;let c=a.from.replace(/^[@#$%~^!?]/,"");!i.has(c)&&!a.from.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown source: "${a.from}"`,path:"relationships"});let l=a.to.replace(/^[@#$%~^!?]/,"");!i.has(l)&&!a.to.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown target: "${a.to}"`,path:"relationships"});}}if(t.flows){let i=new Set(Ne(t.components));if(Array.isArray(t.flows)){for(let a of t.flows)if(!(!a||typeof a!="object")&&(a.name||n.push({type:"error",message:`${s}Flow missing required "name" field`,path:"flows"}),a.steps&&Array.isArray(a.steps)))for(let c of a.steps){if(typeof c=="string"||!c||!c.component)continue;let l=c.component.replace(/^#/,"");i.has(l)||n.push({type:"warning",message:`${s}Flow "${a.name}" references unknown component: "${c.component}"`,path:`flows.${a.name}`});}}else for(let[a,c]of Object.entries(t.flows))if(!(!c||typeof c!="object")&&c.steps&&Array.isArray(c.steps))for(let l of c.steps){if(typeof l=="string"||!l||!l.component)continue;let d=l.component.replace(/^#/,"");i.has(d)||n.push({type:"warning",message:`${s}Flow "${a}" references unknown component: "${l.component}"`,path:`flows.${a}`});}}return {valid:n.filter(i=>i.type==="error").length===0,issues:n}}function yt(t,e,n,s,r){let o=`${n}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||r.push({type:"warning",message:`${s}${n} ID "${t}" should use alphanumeric characters and hyphens`,path:o}),(!e.description||e.description.trim()==="")&&r.push({type:"warning",message:`${s}${n} "${t}" has no description`,path:o}),e.endpoints)for(let i of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(i)||r.push({type:"warning",message:`${s}Endpoint "${i}" in ${n} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${o}.endpoints`});}function Rt(t){let e=[],n=new Set;for(let{data:s}of t){let r=de(s.components);for(let[i]of r)n.add(`#${i}`),n.add(i);let o=de(s.features);for(let[i]of o)n.add(`#${i}`),n.add(i);if(s.gates)for(let i of Object.keys(s.gates))n.add(`^${i}`),n.add(i);if(s.signals)for(let i of Object.keys(s.signals))n.add(`!${i}`),n.add(i);if(s.flows)if(Array.isArray(s.flows))for(let i of s.flows)i?.name&&(n.add(`$${i.name}`),n.add(i.name));else for(let i of Object.keys(s.flows))n.add(`$${i}`),n.add(i);if(s.aspects)for(let i of Object.keys(s.aspects))n.add(`~${i}`),n.add(i);if(s.states)for(let i of Object.keys(s.states))n.add(`#${i}`),n.add(i);}for(let{filePath:s,data:r}of t){let o=s?`${s}: `:"",i=[...de(r.components),...de(r.features)];for(let[a,c]of i){if(c.parent){let d=c.parent.replace(/^["']|["']$/g,""),u=d.replace(/^[#$^!~@%?&]/,"");!n.has(d)&&!n.has(u)&&e.push({type:"warning",message:`${o}Component "${a}" references parent "${d}" which is not defined in any .purpose file`,path:`components.${a}.parent`});}let l=[{field:"gates",refs:c.gates},{field:"signals",refs:c.signals},{field:"flows",refs:c.flows},{field:"components",refs:c.components},{field:"aspects",refs:c.aspects}];for(let{field:d,refs:u}of l)if(u)for(let p of u){let g=p.replace(/^[#$^!~@%?&]/,"");!n.has(p)&&!n.has(g)&&e.push({type:"warning",message:`${o}Symbol "${a}" references ${d} "${p}" which is not defined`,path:`components.${a}.${d}`});}}if(r.flows){if(Array.isArray(r.flows)){for(let a of r.flows)if(a?.steps)for(let c of a.steps){if(typeof c=="string"||!c?.component)continue;let l=c.component.replace(/^#/,"");!n.has(c.component)&&!n.has(l)&&e.push({type:"warning",message:`${o}Flow "${a.name}" step references "${c.component}" which is not defined`,path:`flows.${a.name}.steps`});}}else for(let[a,c]of Object.entries(r.flows))if(c?.steps)for(let l of c.steps){if(typeof l=="string"||!l?.component)continue;let d=l.component.replace(/^#/,"");!n.has(l.component)&&!n.has(d)&&e.push({type:"warning",message:`${o}Flow "${a}" step references "${l.component}" which is not defined`,path:`flows.${a}.steps`});}}}return {valid:e.filter(s=>s.type==="error").length===0,issues:e}}var ss={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function Te(t){let e=P.resolve(t),n=P.dirname(e);if(!w.existsSync(e))throw new Error(`Gate config not found: ${e}`);let s=w.readFileSync(e,"utf8"),r=z.load(s);if(!r.version)throw new Error('Gate config missing required "version" field');let o=[],i=r,a=r.gates||i.portals;if(a)for(let[l,d]of Object.entries(a)){let u=l.startsWith("^")?l.slice(1):l;o.push(Ue(u,d));}if(r.include)for(let l of r.include){let d=P.join(n,l),u=await glob(d.replace(/\\/g,"/"));for(let p of u){let g=await rs(p);o.push(...g);}}let c=[];if(r.flows)for(let[l,d]of Object.entries(r.flows))c.push(as(l,d));return {version:r.version,gates:o,flows:c,settings:{dev:{...ss,...r.settings?.dev}}}}async function rs(t){let e=w.readFileSync(t,"utf8"),n=z.load(e);if(n.id){let s=n.id,r=s.startsWith("^")?s.slice(1):s;return [Ue(r,n)]}if(n.gates){let s=[];for(let[r,o]of Object.entries(n.gates)){let i=r.startsWith("^")?r.slice(1):r;s.push(Ue(i,o));}return s}return []}function Ue(t,e){let n=[];if(e.locks)for(let r of e.locks)n.push(os(r));let s=[];if(e.prizes)for(let r of e.prizes)s.push(is(r));return {id:t,description:e.description,locks:n,prizes:s,position:e.position}}function os(t){let e=t,n=[];if(e.keys){for(let s of e.keys)if(typeof s=="string")n.push({expression:s});else if(s.expression){let r=s;n.push({expression:r.expression,description:r.description});}}return {id:e.id,description:e.description,keys:n,mode:e.mode||"all"}}function is(t){let e=t;return {id:e.id,oneTime:e.oneTime??false,metadata:e.metadata}}function as(t,e){return {id:t,description:e.description,gates:e.gates||[],forkable:e.forkable}}async function Ct(t){let e=P.resolve(t);return await glob("**/portal.yaml",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function Lt(t){if(t instanceof z.YAMLException){let e=(t.reason||"").toLowerCase();return e.includes("duplicated mapping key")||e.includes("duplicate mapping key")?{errorClass:"duplicate-key",detail:"duplicate mapping key"}:["unexpected","expected","bad indentation","mapping values","cannot read a block mapping entry","end of the stream","while scanning","while parsing"].some(s=>e.includes(s))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}var cs=z$1.object({x:z$1.number(),y:z$1.number()}),ls=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),jt=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),Ft=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:cs,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),Nt=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),ds=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),Dt=z$1.object({viewport:ls,groups:z$1.array(ds).optional()}),us=z$1.object({nodes:z$1.array(Ft),connections:z$1.array(Nt),layout:Dt}),ps=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:us});z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(jt).optional(),portal:z$1.array(jt).optional()}),nodes:z$1.array(Ft),connections:z$1.array(Nt),layout:Dt,snapshots:z$1.array(ps).optional()});async function fs(t,e){let n=[],s=[],r=[],o=[];if(t.sources.purpose)for(let c of t.sources.purpose){let l=P.resolve(e,c.path);try{let d=await bt(l);r.push(...d.map(S=>S.filePath));let u=xt(d);for(let[S,{item:b,filePath:A}]of u){let N=["feature",...b.tags||[]];n.push(W({id:`purpose-feature-${S}`,symbol:`#${S}`,type:"component",source:"purpose",filePath:A,data:b,description:b.description,tags:N,componentType:b.type,parentSymbol:b.parent,anchors:b.anchors?.map(v=>ze(v))}));}let p=vt(d);for(let[S,{item:b,filePath:A}]of p)n.push(W({id:`purpose-component-${S}`,symbol:`#${S}`,type:"component",source:"purpose",filePath:A,data:b,description:b.description,tags:b.tags,componentType:b.type,parentSymbol:b.parent,anchors:b.anchors?.map(N=>ze(N))}));let g=Et(d);for(let[S,{item:b,filePath:A}]of g)n.push(W({id:`purpose-gate-${S}`,symbol:`^${S}`,type:"gate",source:"purpose",filePath:A,data:b,description:b.description}));let m=Tt(d);for(let[S,{item:b,filePath:A}]of m)n.push(W({id:`purpose-state-${S}`,symbol:`#${S}`,type:"component",source:"purpose",filePath:A,data:b,description:b.description,tags:["state"]}));let h=kt(d);for(let[S,{item:b,filePath:A}]of h)n.push(W({id:`purpose-flow-${S}`,symbol:`$${S}`,type:"flow",source:"purpose",filePath:A,data:b,description:b.description}));let x=_t(d);for(let[S,{item:b,filePath:A}]of x)n.push(W({id:`purpose-signal-${S}`,symbol:`!${S}`,type:"signal",source:"purpose",filePath:A,data:b,description:b.description}));let T=Pt(d);for(let[S,{item:b,filePath:A}]of T)n.push(W({id:`purpose-aspect-${S}`,symbol:`~${S}`,type:"aspect",source:"purpose",filePath:A,data:b,description:b.description,anchors:b.anchors?.map(N=>ze(N)),appliesTo:b["applies-to"],tags:b.tags,enforcement:b.enforcement}));let E=It(d),k=new Set(n.map(S=>S.symbol));for(let S of E)k.has(S.symbol)||(k.add(S.symbol),n.push(W({id:`purpose-ref-${S.type}-${S.symbol.slice(1)}`,symbol:S.symbol,type:S.type,source:"purpose",filePath:S.filePath,data:{referencedFrom:S.sourceSymbol},description:`Referenced from ${S.sourceSymbol}`})));}catch(d){s.push({source:"purpose",filePath:l,message:d.message});}}if(t.sources.portal)for(let c of t.sources.portal){let l=P.resolve(e,c.path);try{let d;if(l.endsWith(".yaml")||l.endsWith(".yml"))d=await Te(l),o.push(l);else {let u=await Ct(l);if(o.push(...u),u.length>0){d=await Te(u[0]);for(let p=1;p<u.length;p++){let g=await Te(u[p]);d.gates.push(...g.gates),d.flows.push(...g.flows);}}else continue}for(let u of d.gates){n.push(ms(u,l));for(let p of u.prizes)n.push(W({id:`gate-signal-${u.id}-${p.id}`,symbol:`!${p.id}`,type:"signal",source:"portal",filePath:l,data:p,description:`Signal from gate ${u.id}`}));}for(let u of d.flows)n.push(gs(u,l));}catch(d){s.push({source:"portal",filePath:l,message:d.message});}}for(let c of t.nodes){let l=c.tags?.includes("idea");if(!c.content&&!l){let d=n.find(u=>u.symbol===c.symbol);if(d){d.position=c.position,d.tags=c.tags;continue}}n.push(W({id:c.id,symbol:c.symbol,type:c.type,source:"premise",filePath:".premise",data:c,description:c.content,position:c.position,tags:c.tags,created:c.created,modified:c.modified}));}ys(n);let i=new Map;for(let c of n){let l=i.get(c.symbol)||[];l.includes(c.filePath)||l.push(c.filePath),i.set(c.symbol,l);}let a=[];for(let[c,l]of i)l.length>1&&a.push({symbol:c,files:l});return {symbols:n,purposeFiles:r,portalFiles:o,errors:s,timestamp:Date.now(),...a.length>0?{duplicateSymbols:a}:{}}}function W(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function ms(t,e){let n=t.id.startsWith("^")?t.id.slice(1):t.id;return W({id:`gate-${n}`,symbol:`^${n}`,type:"gate",source:"portal",filePath:e,data:t,description:t.description,position:t.position})}function gs(t,e){return W({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:e,data:t,description:t.description})}function ze(t){let e=t.lastIndexOf(":");if(e===-1||e===t.length-1)return {path:t,lines:0,raw:t};let n=t.slice(e+1),s=t.slice(0,e);if(!/^[\d,\- ]+$/.test(n))return {path:t,lines:0,raw:t};if(n.includes("-")){let[r,o]=n.split("-").map(Number);return {path:s,lines:[r,o],raw:t}}else if(n.includes(",")){let r=n.split(",").map(Number);return {path:s,lines:r,raw:t}}else return {path:s,lines:Number(n),raw:t}}var hs=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function ys(t){let e=new Map(t.map(n=>[n.symbol,n]));for(let n of t){let s=JSON.stringify(n.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,o=(s.match(r)||[]).filter(i=>!hs.has(i));for(let i of o)if(i!==n.symbol&&e.has(i)){n.references.includes(i)||n.references.push(i);let a=e.get(i);a&&!a.referencedBy.includes(n.symbol)&&a.referencedBy.push(n.symbol);}}}async function Mt(t){let e={metadata:{name:P.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return fs(e,t)}function ws(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function ao(t){let e=ws();e.timestamp=t.timestamp;for(let n of t.symbols)e.entries.set(n.id,n),e.byType.has(n.type)||e.byType.set(n.type,[]),e.byType.get(n.type).push(n),e.bySource.has(n.source)||e.bySource.set(n.source,[]),e.bySource.get(n.source).push(n);return e}function ke(t,e){for(let n of t.entries.values())if(n.symbol===e)return n}function co(t,e){return t.byType.get(e)||[]}function lo(t,e){let n=e.toLowerCase(),s=[];for(let r of t.entries.values()){if(r.symbol.toLowerCase().includes(n)){s.push(r);continue}if(r.description?.toLowerCase().includes(n)){s.push(r);continue}if(r.tags?.some(o=>o.toLowerCase().includes(n))){s.push(r);continue}if(r.componentType?.toLowerCase().includes(n)){s.push(r);continue}}return s}function uo(t,e){let n=ke(t,e);return n?n.referencedBy.map(s=>ke(t,s)).filter(s=>s!==void 0):[]}function po(t,e){let n=ke(t,e);return n?n.references.map(s=>ke(t,s)).filter(s=>s!==void 0):[]}function fo(t){let e={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[n,s]of t.byType)n in e&&(e[n]=s.length);return e}function mo(t){return Array.from(t.entries.values())}var Ss="0.1.0",bs="1.0.0";function He(t,e){let n={$meta:xs(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let r of t.symbols)vs(r,n,e);if(e.screenDefinitions)for(let[r,o]of Object.entries(e.screenDefinitions))n.screens[r]||(n.screens[r]={id:r,name:te(r),route:o.route,path:"",components:o.components,features:o.features});let s={};for(let r of Object.values(n.components))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);for(let r of Object.values(n.features))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);return Object.keys(s).length>0&&(n.$meta.componentTypes=s),$s(n),n}function xs(t,e){return {version:bs,project:t,generatedAt:new Date().toISOString(),paradigmVersion:Ss,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function vs(t,e,n){let{type:s}=t;switch(s){case "component":Es(t,e,n);break;case "feature":Ts(t,e,n);break;case "flow":ks(t,e);break;case "state":_s(t,e);break;case "gate":Ps(t,e);break;case "signal":Is(t,e);break;case "aspect":Rs(t,e);break;}}function Es(t,e,n){let s=ie(t.symbol),r=Ut(s,t.data,n.visualTagMappings),o={id:s,name:te(s),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:r,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[s]=o,e.symbolMap[t.symbol]={category:"components",id:s};}function Ts(t,e,n){let s=ie(t.symbol),r=Ut(s,t.data,n.visualTagMappings),o={id:s,name:te(s),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:r,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[s]=o,e.symbolMap[t.symbol]={category:"features",id:s};}function ks(t,e){let n=ie(t.symbol),s=t.data,r=[];if(s?.steps)for(let i=0;i<s.steps.length;i++){let a=s.steps[i];r.push({id:`${n}-step-${i}`,name:a.action||`Step ${i+1}`,target:a.component,description:a.description,order:i});}let o={id:n,name:te(n),symbol:t.symbol,path:t.filePath,description:t.description,steps:r};e.flows[n]=o,e.symbolMap[t.symbol]={category:"flows",id:n};}function _s(t,e){let n=ie(t.symbol),s={id:n,name:te(n),symbol:t.symbol,path:t.filePath,description:t.description,consumers:t.referencedBy};e.state[n]=s,e.symbolMap[t.symbol]={category:"state",id:n};}function Ps(t,e){let n=ie(t.symbol),s={id:n,name:te(n),symbol:t.symbol,category:"gates",path:t.filePath,description:t.description,related:t.references};e.gates[n]=s,e.symbolMap[t.symbol]={category:"gates",id:n};}function Is(t,e){let n=ie(t.symbol),s={id:n,name:te(n),symbol:t.symbol,category:"signals",path:t.filePath,description:t.description,related:t.references};e.signals[n]=s,e.symbolMap[t.symbol]={category:"signals",id:n};}function Rs(t,e){let n=ie(t.symbol),s={id:n,name:te(n),symbol:t.symbol,category:"aspects",path:t.filePath,description:t.description,related:t.references};e.aspects[n]=s,e.symbolMap[t.symbol]={category:"aspects",id:n};}function $s(t){for(let e of Object.values(t.screens))if(e.components)for(let n of e.components){let s=t.components[n];s&&(s.screens=s.screens||[],s.screens.includes(e.id)||s.screens.push(e.id));}}function ie(t){return t.slice(1)}function te(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ut(t,e,n){let s=[];if(n?.[t])return n[t];let r=[[/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[o,i]of r)o.test(t)&&s.push(i);return s}function We(t){return JSON.stringify(t,null,2)}function Ge(t,e="unknown"){j$1().trackToolCall(e,t);}function ko(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function Cs(){k();}function As(t,e){switch(t){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let n=e.intent,s=e.target,r=e.task;return n==="context"&&r?{summary:`Navigate context: "${r}"`}:s?{summary:`Navigate ${n||"find"}: ${s}`,symbol:s}:{summary:`Navigate (${n||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let n=t.replace(/^paradigm_/,""),s=Object.values(e).find(r=>typeof r=="string"&&r.length>0);return {summary:s?`${n}: ${s.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function _o(t,e){let n=j$1(),{summary:s,symbol:r}=As(t,e);n.addBreadcrumb("tool-call",s,{tool:t,symbol:r});}function Po(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Io(t,e,n){let s=j$1();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let r=e.contextWindowSize||2e5,o=e.estimatedTotalTokens,i=s.getStats(),{recommendation:a,message:c,usagePercent:l,signals:d}=s.getHandoffRecommendation(r,o),u=s.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:a,message:c,stats:{sessionDurationMinutes:u,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:o||Math.round(i.totals.totalTokens*5),contextWindowSize:r,usagePercent:l},signals:d,action:a==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let r=e.summary,o=e.nextSteps||[],i=e.agent||"builder",a$1=e.modifiedFiles||[],c=e.symbolsTouched||[],l=e.openQuestions||[],d=s.getStats(),u=s.getCostBreakdown(),p=`h${Date.now().toString(36)}`,g=new Date().toISOString(),m={id:p,timestamp:g,from:"current-session",to:i,summary:r,nextSteps:o,modifiedFiles:a$1,symbolsTouched:c,openQuestions:l,sessionStats:{duration:s.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"},h=false;try{a(n.rootDir,m),h=!0;}catch{}let x=`# Handoff: ${g}
|
|
12
|
+
|
|
13
|
+
## Session Summary
|
|
14
|
+
${r}
|
|
15
|
+
|
|
16
|
+
## Next Steps
|
|
17
|
+
${o.map((T,E)=>`${E+1}. ${T}`).join(`
|
|
18
|
+
`)||"(none specified)"}
|
|
19
|
+
|
|
20
|
+
## Key Context
|
|
21
|
+
- Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
|
|
22
|
+
- Symbols touched: ${c.length>0?c.join(", "):"(not specified)"}
|
|
23
|
+
- Open questions: ${l.length>0?l.join(", "):"(none)"}
|
|
24
|
+
`;return Cs(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:x,persisted:h,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let r=s.getStats(),o=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(r.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(r.lastActivity).toISOString()},model:{name:o.model,id:o.modelId,pricing:{inputPerMillion:`$${o.pricing.input.toFixed(2)}`,outputPerMillion:`$${o.pricing.output.toFixed(2)}`}},interactions:{toolCalls:r.totals.toolCallCount,resourceReads:r.totals.resourceReadCount,totalInteractions:r.totals.toolCallCount+r.totals.resourceReadCount},tokens:{total:r.totals.totalTokens,byCategory:{resources:o.resources.tokens,tools:o.tools.tokens}},cost:{totalUsd:`$${o.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${o.resources.costUsd.toFixed(4)}`,tools:`$${o.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:o.resources.byType,toolsByName:o.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:r,pendingHandoffs:o,previousSession:i}=zt(n.rootDir);if(!i&&o.length===0&&!r)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let a={found:true};if(r){let l=Date.now()-r.timestamp,d=Math.round(l/6e4),u=Math.round(l/36e5);a.checkpoint={phase:r.phase,context:r.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(r.timestamp).toISOString(),sessionId:r.sessionId,plan:r.plan,modifiedFiles:r.modifiedFiles,symbolsTouched:r.symbolsTouched,decisions:r.decisions,recentBreadcrumbs:r.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(i){let l=Date.now()-i.lastActivity,d=Math.round(l/6e4),u=Math.round(l/36e5),g=i.breadcrumbs.slice(-10).map(m=>({time:new Date(m.timestamp).toISOString(),action:m.action,tool:m.tool,symbol:m.symbol,summary:m.summary}));a.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},a.recentActions=g;}if(o.length>0){a.pendingHandoffs=o.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of o)try{c$1(n.rootDir,l.id);}catch{}}let c="Continue where the previous session left off.";if(r)c=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(c+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(o.length>0){let l=o[o.length-1];c=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(c+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(c=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=c,a.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",s.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){s.setRootDir(n.rootDir);let r=e.phase,o=e.context,i=e.externalId,a=e.plan,c=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:r,context:o,externalId:i,plan:a,modifiedFiles:c,symbolsTouched:l,decisions:d}),g=p.local||p.global;return {handled:true,text:JSON.stringify({saved:g,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function zt(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=e.loadPreviousSession(),r=[];try{r=b$2(t);}catch{}return {checkpoint:n,pendingHandoffs:r,previousSession:s}}async function Ro(t){let{checkpoint:e,pendingHandoffs:n}=zt(t);if(!e&&n.length===0)return null;let s=[];if(s.push("--- SESSION RECOVERY ---"),e){let r=Date.now()-e.timestamp,o=Math.round(r/6e4),i=Math.round(r/36e5),a=i>1?`${i}h ago`:`${o}m ago`;s.push(`Previous session was in "${e.phase}" phase (${a}): ${e.context}`),e.modifiedFiles?.length&&s.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&s.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&s.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&s.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let r=n[n.length-1];s.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&s.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),o=await r(t,{status:"open",limit:5});if(o.length>0){s.push(""),s.push("Open tasks:");for(let i of o){let a=i.tags.length>0?` [${i.tags.join(", ")}]`:"";s.push(` [${i.priority}] ${i.id}: ${i.blurb}${a}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-PXFKMKAN.js'),i=(await r(t,{limit:10})).filter(a=>a.tags?.some(c=>c.startsWith("arc:")));if(i.length>0){let a=new Map;for(let d of i){let u=d.tags?.find(p=>p.startsWith("arc:"))||"";a.set(u,(a.get(u)||0)+1);}let c=e?.symbolsTouched||[];if((c.length>0?i.filter(d=>d.symbols_touched?.some(u=>c.includes(u))):i.slice(0,3)).length>0||a.size>0){s.push(""),s.push("Active lore arcs:");for(let[d,u]of a)s.push(` ${d} (${u} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-QPZJH6XO.js'),o=r(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(o.length>0){s.push(""),s.push("Ambient nominations (urgent):");for(let i of o.slice(0,5))s.push(` [${i.urgency}] ${i.brief}`);o.length>5&&s.push(` ... and ${o.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return s.push(""),s.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),s.push("---"),s.join(`
|
|
25
|
+
`)}var Be=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let s=this.cache.get(e);if(s&&Date.now()-s.createdAt<this.ttlMs)return s.data;let r=await n();return this.cache.set(e,{data:r,createdAt:Date.now()}),r}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},Ht=new Be(3e4);var Ls=300*1e3,ye=null;function Gt(){ye=null;}function K(t,e){return w.existsSync(P.join(t,e))}function ne(t,e){return w.existsSync(P.join(t,e))}function js(t,e,n){let s=t;try{if(!w.existsSync(s))return !1;let r=w.readdirSync(s,{withFileTypes:!0});for(let o of r){if(o.isFile()&&o.name.endsWith(e))return !0;if(o.isDirectory())try{if(w.readdirSync(P.join(s,o.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var Os={wisdom:t=>K(t,".paradigm/wisdom"),history:t=>K(t,".paradigm/history"),lore:t=>K(t,".paradigm/lore"),habits:t=>ne(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=P.join(t,".paradigm","config.yaml");return w.existsSync(e)?w.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>ne(t,".paradigm/flow-index.json")||ne(t,".paradigm/flows.yaml"),fixtures:t=>ne(t,".paradigm/fixtures.yaml"),orchestration:t=>ne(t,".paradigm/agents.yaml"),tasks:t=>K(t,".paradigm/tasks"),assessment:t=>K(t,".paradigm/lore"),personas:t=>js(t,".persona"),protocols:t=>K(t,".paradigm/protocols"),symphony:()=>{let t=P.join(_e.homedir(),".paradigm","score");return w.existsSync(t)},university:t=>K(t,".paradigm/university"),agents:t=>{let e=P.join(_e.homedir(),".paradigm","agents");return K(t,".paradigm/agents")||w.existsSync(e)},"aspect-graph":t=>ne(t,".paradigm/aspect-graph.db"),pan:t=>ne(t,".pan")||ne(t,"nevr.yaml"),notebooks:t=>{let e=P.join(_e.homedir(),".paradigm","notebooks");return K(t,".paradigm/notebooks")||w.existsSync(e)}},Wt=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(e){this.rootDir=e;}register(e){this.modules.set(e.key,e);}registerAll(e){for(let n of e)this.register(n);}detectActiveFeatures(){if(ye&&Date.now()-ye.timestamp<Ls)return ye.features;let e=new Set;for(let[n,s]of this.modules){if(s.tier==="core"){e.add(n);continue}if(s.tier==="advanced"){this.activatedAdvanced.has(n)&&e.add(n);continue}let r=s.detect||Os[n];if(r)try{r(this.rootDir)&&e.add(n);}catch{}else e.add(n);}return ye={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),n=[];for(let[s,r]of this.modules)e.has(s)&&n.push(...r.getToolsList());return n}activateAdvanced(e){let n=this.modules.get(e);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(e),n.getToolsList())}getAvailableAdvanced(){let e=[];for(let[n,s]of this.modules)s.tier==="advanced"&&!this.activatedAdvanced.has(n)&&e.push({key:n,toolCount:s.getToolsList().length});return e}async dispatch(e,n,s,r){let o=this.detectActiveFeatures();for(let[i,a]of this.modules)if(o.has(i))try{let c=await a.handleTool(e,n,s,r);if(c.handled)return c}catch(c){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:c.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let s of this.modules.values())n[s.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([s,r])=>r.tier==="advanced"&&!this.activatedAdvanced.has(s)).map(([s])=>s)}}};var Ve=null;async function Gs(){return Ve||(Ve=await Ws()),Ve}var Bs=[`CREATE TABLE IF NOT EXISTS aspects (
|
|
26
|
+
id TEXT PRIMARY KEY,
|
|
27
|
+
description TEXT NOT NULL,
|
|
28
|
+
category TEXT DEFAULT 'rule',
|
|
29
|
+
severity TEXT DEFAULT 'medium',
|
|
30
|
+
value TEXT,
|
|
31
|
+
enforcement TEXT,
|
|
32
|
+
defined_in TEXT NOT NULL,
|
|
33
|
+
tags TEXT,
|
|
34
|
+
created_at TEXT NOT NULL,
|
|
35
|
+
updated_at TEXT NOT NULL
|
|
36
|
+
)`,`CREATE TABLE IF NOT EXISTS anchors (
|
|
37
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
38
|
+
aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
|
|
39
|
+
file_path TEXT NOT NULL,
|
|
40
|
+
start_line INTEGER NOT NULL,
|
|
41
|
+
end_line INTEGER NOT NULL,
|
|
42
|
+
content_hash TEXT,
|
|
43
|
+
normalized_hash TEXT,
|
|
44
|
+
materialized_at_commit TEXT,
|
|
45
|
+
last_verified TEXT,
|
|
46
|
+
drifted INTEGER DEFAULT 0
|
|
47
|
+
)`,"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 (
|
|
48
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
49
|
+
source TEXT NOT NULL,
|
|
50
|
+
target TEXT NOT NULL,
|
|
51
|
+
relation TEXT NOT NULL,
|
|
52
|
+
weight REAL DEFAULT 1.0,
|
|
53
|
+
origin TEXT DEFAULT 'explicit',
|
|
54
|
+
created_at TEXT NOT NULL
|
|
55
|
+
)`,"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 (
|
|
56
|
+
aspect_id TEXT NOT NULL,
|
|
57
|
+
lore_id TEXT NOT NULL,
|
|
58
|
+
PRIMARY KEY (aspect_id, lore_id)
|
|
59
|
+
)`,`CREATE TABLE IF NOT EXISTS search_log (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
query TEXT NOT NULL,
|
|
62
|
+
results_returned TEXT NOT NULL,
|
|
63
|
+
selected_result TEXT,
|
|
64
|
+
timestamp TEXT NOT NULL
|
|
65
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
|
|
66
|
+
query_normalized TEXT NOT NULL,
|
|
67
|
+
aspect_id TEXT NOT NULL,
|
|
68
|
+
weight REAL DEFAULT 1.0,
|
|
69
|
+
hit_count INTEGER DEFAULT 1,
|
|
70
|
+
last_hit TEXT NOT NULL,
|
|
71
|
+
PRIMARY KEY (query_normalized, aspect_id)
|
|
72
|
+
)`,`CREATE TABLE IF NOT EXISTS heatmap (
|
|
73
|
+
aspect_id TEXT NOT NULL,
|
|
74
|
+
access_type TEXT NOT NULL,
|
|
75
|
+
count INTEGER DEFAULT 0,
|
|
76
|
+
last_accessed TEXT NOT NULL,
|
|
77
|
+
PRIMARY KEY (aspect_id, access_type)
|
|
78
|
+
)`],Xs=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
|
|
79
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
80
|
+
anchor_id INTEGER NOT NULL,
|
|
81
|
+
action TEXT NOT NULL,
|
|
82
|
+
old_start INTEGER,
|
|
83
|
+
old_end INTEGER,
|
|
84
|
+
new_start INTEGER,
|
|
85
|
+
new_end INTEGER,
|
|
86
|
+
old_path TEXT,
|
|
87
|
+
new_path TEXT,
|
|
88
|
+
confidence REAL,
|
|
89
|
+
commit_hash TEXT,
|
|
90
|
+
healed_at TEXT NOT NULL
|
|
91
|
+
)`],qs="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function X(t,e,n){let s=t.prepare(e);n&&n.length>0&&s.bind(n);let r=[];for(;s.step();)r.push(s.getAsObject());return s.free(),r}function Vs(t,e,n){let s=t.prepare(e);n&&n.length>0&&s.bind(n);let r=null;return s.step()&&(r=s.getAsObject()),s.free(),r}async function tn(t){let e=await Gs(),n=P.join(t,".paradigm"),s=P.join(n,"aspect-graph.db"),r;if(w.existsSync(s)){let o=w.readFileSync(s);r=new e.Database(o);}else w.existsSync(n)||w.mkdirSync(n,{recursive:true}),r=new e.Database;for(let o of Bs)r.run(o);try{r.run(qs);}catch{}for(let o of Xs)try{r.run(o);}catch{}return r}function nn(t,e){if(e){let n=P.join(e,".paradigm");w.existsSync(n)||w.mkdirSync(n,{recursive:true});let s=P.join(n,"aspect-graph.db"),r=t.export();w.writeFileSync(s,Buffer.from(r));}t.close();}function sn(t,e,n){let s=e.filter(i=>i.type==="aspect"),r=new Date().toISOString(),o=null;try{o=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}t.run("DELETE FROM anchors"),t.run("DELETE FROM edges"),t.run("DELETE FROM aspects");try{t.run("DELETE FROM aspects_fts");}catch{}for(let i of s){let a=i.data??{},c=Qs(a,i),l=Zs(a,i),d=a.value!=null?String(a.value):null,u=i.enforcement??(a.enforcement!=null?String(a.enforcement):null),p=i.tags?JSON.stringify(i.tags):null;if(t.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
|
|
92
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,i.description??"",c,l,d,u,i.filePath,p,i.created??r,i.modified??r]),i.anchors)for(let m of i.anchors){let{startLine:h,endLine:x}=rn(m),T=Js();t.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
|
|
93
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,m.path,h,x,T.exact,T.normalized,o,r,T.normalizedContent]);}let g=a.edges;if(Array.isArray(g))for(let m of g)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
|
|
94
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[m.source??i.symbol,m.target??"",m.relation??"related-to",m.weight??1,m.origin??"explicit",r]);if(i.appliesTo)for(let m of i.appliesTo)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
|
|
95
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[i.symbol,m,"related-to",.5,"inferred",r]);try{t.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
|
|
96
|
+
VALUES (?, ?, ?, ?)`,[i.symbol,i.description??"",u??"",p??""]);}catch{}}}function Fo(t,e){return Vs(t,"SELECT * FROM aspects WHERE id = ?",[e])}function No(t,e){return X(t,"SELECT * FROM anchors WHERE aspect_id = ?",[e])}function Do(t,e){return X(t,"SELECT * FROM edges WHERE source = ?",[e])}function Mo(t,e){return X(t,"SELECT * FROM edges WHERE target = ?",[e])}function Uo(t,e){return X(t,"SELECT * FROM edges WHERE source = ? OR target = ?",[e,e])}function zo(t,e,n){let s=new Date().toISOString();t.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
|
|
97
|
+
VALUES (?, ?, 1, ?)
|
|
98
|
+
ON CONFLICT(aspect_id, access_type)
|
|
99
|
+
DO UPDATE SET count = count + 1, last_accessed = ?`,[e,n,s,s]);}function Ho(t,e=20,n){return n?X(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,e]):X(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function Wo(t,e,n,s=true,r=.7,o=.85){let i=n?X(t,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):X(t,"SELECT * FROM anchors"),a=[];for(let c of i){let l=P.isAbsolute(c.file_path)?c.file_path:P.join(e,c.file_path);if(!w.existsSync(l)){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let u=w.readFileSync(l,"utf8").split(`
|
|
100
|
+
`),p=Math.max(0,c.start_line-1),g=Math.min(u.length,c.end_line),m=u.slice(p,g).join(`
|
|
101
|
+
`),h=se.createHash("sha256").update(m).digest("hex");if(c.content_hash!=null&&h===c.content_hash){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),c.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[c.id]);continue}let x=se.createHash("sha256").update(Ke(m)).digest("hex");if(c.normalized_hash!=null&&x===c.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[h,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(c.content_hash==null&&c.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[h,x,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let T=!1;if(c.materialized_at_commit){let E=Ks(e,c.file_path,c.materialized_at_commit,c.start_line,c.end_line);if(E){let k=Math.max(0,E.currentStart-1),S=Math.min(u.length,E.currentEnd),b=u.slice(k,S).join(`
|
|
102
|
+
`),A=se.createHash("sha256").update(b).digest("hex");if(c.content_hash!=null&&A===c.content_hash){let N=s;if(N){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[E.currentStart,E.currentEnd,c.id]);let v=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);v.length>0&&Ye(e,v[0].defined_in,c.file_path,c.start_line,c.end_line,E.currentStart,E.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:N?E.currentStart:c.start_line,endLine:N?E.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:E.currentStart,suggestedEnd:E.currentEnd,autoHealed:N}),T=!0;}else {let N=se.createHash("sha256").update(Ke(b)).digest("hex");if(c.normalized_hash!=null&&N===c.normalized_hash){if(s){let v=se.createHash("sha256").update(b).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[E.currentStart,E.currentEnd,v,c.id]);let D=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);D.length>0&&Ye(e,D[0].defined_in,c.file_path,c.start_line,c.end_line,E.currentStart,E.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:s?E.currentStart:c.start_line,endLine:s?E.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:E.currentStart,suggestedEnd:E.currentEnd,autoHealed:s}),T=!0;}}}}if(T)continue;if(c.original_content){let{contentSearch:E}=(Zt(),d(Qt)),k=E(e,c.file_path,c.original_content,s);if(k.found&&k.score>=r){if(s&&k.score>=o&&!k.suggestedPath&&k.suggestedStart&&k.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[k.suggestedStart,k.suggestedEnd,c.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
|
|
103
|
+
VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[c.id,c.start_line,c.end_line,k.suggestedStart,k.suggestedEnd,k.score,new Date().toISOString()]);}catch{}let b=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);b.length>0&&Ye(e,b[0].defined_in,c.file_path,c.start_line,c.end_line,k.suggestedStart,k.suggestedEnd),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:k.suggestedStart,endLine:k.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:k.similarity,suggestedStart:k.suggestedStart,suggestedEnd:k.suggestedEnd,autoHealed:!0,drifted:!1});continue}a.push({aspectId:c.aspect_id,path:k.suggestedPath||c.file_path,startLine:c.start_line,endLine:c.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:k.similarity,suggestedStart:k.suggestedStart,suggestedEnd:k.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:m,drifted:!0});}catch{a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return a}function rn(t){let{lines:e}=t;return typeof e=="number"?{startLine:e,endLine:e}:Array.isArray(e)?e.length===2?{startLine:e[0],endLine:e[1]}:{startLine:Math.min(...e),endLine:Math.max(...e)}:{startLine:1,endLine:1}}function Ys(t){let e=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,s;for(;(s=n.exec(t))!==null;)e.push({oldStart:parseInt(s[1],10),oldCount:s[2]!==void 0?parseInt(s[2],10):1,newStart:parseInt(s[3],10),newCount:s[4]!==void 0?parseInt(s[4],10):1});return e}function Ks(t,e,n,s,r){let o;try{o=execSync(`git diff ${n}..HEAD --unified=0 -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3});}catch{return null}if(!o.trim())return {originalStart:s,originalEnd:r,currentStart:s,currentEnd:r};let i=Ys(o),a=0;for(let c of i){if(c.oldStart+c.oldCount<=s){a+=c.newCount-c.oldCount;continue}if(c.oldStart<r)return null;break}return a===0?null:{originalStart:s,originalEnd:r,currentStart:s+a,currentEnd:r+a}}function Ye(t,e,n,s,r,o,i){let a=P.isAbsolute(e)?e:P.join(t,e);if(!w.existsSync(a))return false;try{let c=w.readFileSync(a,"utf8"),l=s===r?`${n}:${s}`:`${n}:${s}-${r}`,d=o===i?`${n}:${o}`:`${n}:${o}-${i}`;if(!c.includes(l))return !1;let u=c.replace(l,d);return w.writeFileSync(a,u,"utf8"),!0}catch{return false}}function Ke(t){return t.split(`
|
|
104
|
+
`).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
|
|
105
|
+
`)}function Js(t,e){return {exact:null,normalized:null,normalizedContent:null};}function Qs(t,e){if(typeof t.category=="string")return t.category;let n=(e.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 Zs(t,e){if(typeof t.severity=="string")return t.severity;let n=e.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j();var er=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function on(t,e){t.run("DELETE FROM lore_links");let n=await a$3(e);if(n.length===0)return 0;let s=tr(n),r=new Map;for(let l of n)r.set(l.id,l);let o=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:l,values:d}=i[0],u=l.indexOf("id"),p=l.indexOf("enforcement");for(let g of d){let m=String(g[u]),h=g[p];if(h&&typeof h=="string"){let x=h.match(er);if(x)for(let T of x)r.has(T)&&o.add(`${m}\0${T}`);}}}let a=t.exec("SELECT source, target FROM edges");if(a.length>0&&i.length>0){let l=nr(t,a);for(let[d,u]of l)for(let p of u){let g=s.get(p);if(g)for(let m of g)o.add(`${d}\0${m}`);}}if(o.size===0)return 0;let c=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of o){let[d,u]=l.split("\0");c.bind([d,u]),c.step(),c.reset();}}finally{c.free();}return o.size}async function Xo(t,e,n){let s=t.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(s.length===0||s[0].values.length===0)return [];let r=s[0].values.map(o=>String(o[0]));return sr(e,r)}async function an(t,e){let n=await a$3(e);if(n.length===0)return 0;let s=t.exec("SELECT id FROM aspects"),r=new Set;if(s.length>0)for(let c of s[0].values)r.add(String(c[0]));if(r.size<2)return 0;let o=new Date().toISOString(),i=0,a=t.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
|
|
106
|
+
VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let c of n){if(!c.symbols_touched||c.symbols_touched.length<2)continue;let l=[];for(let d of c.symbols_touched){let u=d.startsWith("~")?d.slice(1):d;r.has(u)&&l.push(u);}for(let d=0;d<l.length;d++)for(let u=d+1;u<l.length;u++){let[p,g]=l[d]<l[u]?[l[d],l[u]]:[l[u],l[d]];a.bind([p,g,o]),a.step(),a.reset(),i++;}}}finally{a.free();}return i}function tr(t){let e=new Map;for(let n of t)if(n.symbols_touched)for(let s of n.symbols_touched){let r=e.get(s);r||(r=new Set,e.set(s,r)),r.add(n.id);}return e}function nr(t,e){let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let l of n[0].values)s.add(String(l[0]));let r=new Map;if(e.length===0)return r;let{columns:o,values:i}=e[0],a=o.indexOf("source"),c=o.indexOf("target");for(let l of i){let d=String(l[a]),u=String(l[c]);if(s.has(d)){let p=r.get(d);p||(p=new Set,r.set(d,p)),p.add(u),p.add(`~${d}`);}if(s.has(u)){let p=r.get(u);p||(p=new Set,r.set(u,p)),p.add(d),p.add(`~${u}`);}}return r}async function sr(t,e){let n=new Set,s=[];for(let r of e){if(n.has(r))continue;n.add(r);let o=await b$3(t,r);o&&s.push(rr(o));}return s}function rr(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var ue=".paradigm/personas",or="index.yaml";async function we(t,e){let n=P.join(t,ue);if(!w.existsSync(n))return [];let s=w.readdirSync(n).filter(o=>o.endsWith(".persona")),r=[];for(let o of s)try{let i=w.readFileSync(P.join(n,o),"utf8"),a=z.load(i);a&&a.id&&r.push(a);}catch{}return ir(r,e)}async function Se(t,e){let n=P.join(t,ue,`${e}.persona`);if(!w.existsSync(n))return null;try{return z.load(w.readFileSync(n,"utf8"))}catch{return null}}function ir(t,e){if(!e)return t;let n=t;return e.tag&&(n=n.filter(s=>s.tags?.includes(e.tag))),e.trigger_type&&(n=n.filter(s=>s.trigger.type===e.trigger_type)),e.gate&&(n=n.filter(s=>s.journey.some(r=>r.gates.includes(e.gate)))),e.flow&&(n=n.filter(s=>s.journey.some(r=>r.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function Vo(t,e){let n=P.join(t,ue);w.mkdirSync(n,{recursive:true});let s=P.join(n,`${e.id}.persona`);if(w.existsSync(s))throw new Error(`Persona ${e.id} already exists`);let r=new Date().toISOString(),o={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:r,updated:r};return w.writeFileSync(s,z.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await be(t),e.id}async function cn(t,e,n){let s=await Se(t,e);if(!s)return false;let r=P.join(t,ue,`${e}.persona`),o={...s,...n,id:s.id,version:s.version,created:s.created,updated:new Date().toISOString()};return w.writeFileSync(r,z.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await be(t),true}async function Yo(t,e){let n=P.join(t,ue,`${e}.persona`);if(!w.existsSync(n))return {deleted:false,warnings:[]};let s=[],r=await we(t);for(let o of r)if(o.id!==e){o.trigger.spawned_by?.startsWith(e+".")&&s.push(`Persona ${o.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of o.journey)i.spawns?.some(a=>a.persona===e)&&s.push(`Persona ${o.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return w.unlinkSync(n),await be(t),{deleted:true,warnings:s}}async function Ko(t,e,n,s){let r=await Se(t,e);if(!r)return false;if(r.journey.some(o=>o.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(s){let o=r.journey.findIndex(i=>i.id===s);if(o===-1)throw new Error(`Step ${s} not found in persona ${e}`);r.journey.splice(o+1,0,n);}else r.journey.push(n);return cn(t,e,{journey:r.journey})}async function Jo(t,e,n){let s=await Se(t,e);if(!s)return {removed:false,warnings:[]};let r=s.journey.findIndex(a=>a.id===n);if(r===-1)return {removed:false,warnings:[]};let o=s.journey[r],i=[];if(o.produces)for(let a of Object.keys(o.produces)){let c=`{{produces.${a}}}`;for(let l=r+1;l<s.journey.length;l++){let d=s.journey[l];JSON.stringify(d).includes(c)&&i.push(`Step ${d.id} consumes {{produces.${a}}} from this step`);}}if(o.spawns&&o.spawns.length>0)for(let a of o.spawns)i.push(`Step spawns persona ${a.persona} \u2014 spawn chain will break`);return s.journey.splice(r,1),await cn(t,e,{journey:s.journey}),{removed:true,warnings:i}}var ar=/^[a-z][a-z0-9-]*$/,cr=/^[a-z][a-z0-9-]*$/,lr=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function Qo(t,e,n=false){let s=[],r=[];ar.test(e.id)||s.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&s.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&s.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&s.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&s.push({type:"empty-journey",detail:"Journey must have at least one step"});let o=new Set,i=new Set;for(let a of e.journey){cr.test(a.id)||s.push({type:"invalid-step-id",step:a.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),o.has(a.id)&&s.push({type:"duplicate-step-id",step:a.id,detail:`Duplicate step ID "${a.id}"`}),o.add(a.id),lr.test(a.route)||s.push({type:"invalid-route",step:a.id,route:a.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!a.gates||a.gates.length===0)&&s.push({type:"missing-gates",step:a.id,detail:"Step must have at least one gate"}),(!a.expect||a.expect.status===void 0)&&s.push({type:"missing-expect",step:a.id,detail:"Step must have expect with status"});let l=JSON.stringify(a).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of l){let u=d.replace("{{produces.","").replace("}}","");i.has(u)||s.push({type:"unresolved-produces",step:a.id,key:u,detail:`{{produces.${u}}} used but not produced by a prior step`});}if(a.produces)for(let d of Object.keys(a.produces))i.add(d);}if(n){let a=P.join(t,"portal.yaml"),c=[],l=[];if(w.existsSync(a))try{let u=z.load(w.readFileSync(a,"utf8"));u.gates&&typeof u.gates=="object"&&(c=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(l=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let p of u.gates)c.length>0&&!c.includes(p)&&s.push({type:"gate-not-found",step:u.id,gate:p,detail:`Gate ${p} not defined in portal.yaml`});for(let u of e.journey)if(l.length>0){let p=u.route;l.some(m=>Je(m,p))||r.push({type:"route-not-in-portal",detail:`Route "${p}" (step ${u.id}) not found in portal.yaml`});}for(let u of e.journey)if(u.spawns)for(let p of u.spawns)await Se(t,p.persona)||s.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${p.persona}" does not exist`});let d=await dr(t,e.id);if(d&&s.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),l.length>0||c.length>0){let u=await we(t),p=new Set,g=new Set;for(let T of u)for(let E of T.journey){for(let k of E.gates)p.add(k);g.add(E.route);}let m=[],h=P.join(t,".paradigm","flow-index.json");if(w.existsSync(h))try{let T=JSON.parse(w.readFileSync(h,"utf8"));m=Object.keys(T.flows||{});}catch{}let x=new Set;for(let T of u)for(let E of T.journey)E.flow&&x.add(E.flow);return {persona:e.id,valid:s.length===0,errors:s,warnings:r,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(T=>!g.has(T))},gates:{covered:p.size,total:c.length,uncovered:c.filter(T=>!p.has(T))},flows:{covered:x.size,total:m.length,uncovered:m.filter(T=>!x.has(T))}}}}}return {persona:e.id,valid:s.length===0,errors:s,warnings:r}}function Je(t,e){let n=s=>s.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(t)===n(e)}async function dr(t,e){let n=new Set,s=[];async function r(o){if(n.has(o)){let a=s.indexOf(o);return a!==-1?[...s.slice(a),o]:null}n.add(o),s.push(o);let i=await Se(t,o);if(i){for(let a of i.journey)if(a.spawns)for(let c of a.spawns){let l=await r(c.persona);if(l)return l}}return s.pop(),null}return r(e)}async function be(t){let e=P.join(t,ue);w.mkdirSync(e,{recursive:true});let n=await we(t),s={},r={},o={};for(let u of n){let p=new Set,g=new Set,m=[],h=new Set;for(let x of u.journey){for(let T of x.gates)p.add(T);if(x.flow&&g.add(x.flow),m.push(x.route),x.spawns)for(let T of x.spawns)h.add(T.persona);}s[u.id]={name:u.name,trigger:u.trigger.type,spawned_by:u.trigger.spawned_by,steps:u.journey.length,gates:[...p],flows:[...g],routes:m,spawns:[...h],tags:u.tags||[]};for(let x of p)r[x]||(r[x]=[]),r[x].push(u.id);for(let x of m)o[x]||(o[x]=[]),o[x].push(u.id);}let i=[],a=P.join(t,"portal.yaml");if(w.existsSync(a))try{let u=z.load(w.readFileSync(a,"utf8"));u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes).filter(g=>!Object.keys(o).some(m=>Je(g,m))));}catch{}let c={},l=P.join(e,"chains");if(w.existsSync(l)){let u=w.readdirSync(l).filter(p=>p.endsWith(".yaml"));for(let p of u)try{let g=w.readFileSync(P.join(l,p),"utf8"),m=z.load(g);if(m&&m.id){let h=m.order.map(E=>E.persona),x=0,T=new Set;for(let E of h){let k=s[E];if(k){x+=k.steps;for(let S of k.gates)T.add(S);}}c[m.id]={description:m.description||"",order:h,total_steps:x,total_gates:T.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:s,chains:c,gate_coverage:r,route_coverage:o,uncovered_routes:i};return w.writeFileSync(P.join(e,or),z.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function Zo(t){let e=await we(t),n=new Set,s=new Set,r=new Set;for(let d of e)for(let u of d.journey){for(let p of u.gates)n.add(p);s.add(u.route),u.flow&&r.add(u.flow);}let o=[],i=[],a=P.join(t,"portal.yaml");if(w.existsSync(a))try{let d=z.load(w.readFileSync(a,"utf8"));d.gates&&typeof d.gates=="object"&&(o=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes));}catch{}let c=[],l=P.join(t,".paradigm","flow-index.json");if(w.existsSync(l))try{let d=JSON.parse(w.readFileSync(l,"utf8"));c=Object.keys(d.flows||{});}catch{}return {routes:{covered:s.size,total:i.length,uncovered:i.filter(d=>!Array.from(s).some(u=>Je(d,u)))},gates:{covered:n.size,total:o.length,uncovered:o.filter(d=>!n.has(d))},flows:{covered:r.size,total:c.length,uncovered:c.filter(d=>!r.has(d))},personas:e.length}}async function ei(t,e){let n=await we(t),s=[];for(let r of n){let o=[],i=[];for(let a of r.journey)if((a.gates.includes(e)||a.flow===e||a.route===e||a.signals?.includes(e))&&(o.push(a.id),a.spawns))for(let l of a.spawns)i.push(l.persona);o.length>0&&s.push({persona:r.id,steps:o,spawns_blocked:i});}return s}function ur(t,e){let n=e.split(/[.\[\]]+/).filter(Boolean),s=t;for(let r of n){if(s==null||typeof s!="object")return;s=s[r];}return s}function pr(t,e){let n=[];if(e.status!==t.expect.status&&n.push({type:"status",field:"status",expected:t.expect.status,actual:e.status,message:`Step ${t.id}: status is ${e.status}, expected ${t.expect.status}`}),t.expect.body?.has){let s=e.body;for(let r of t.expect.body.has)(!s||typeof s!="object"||!(r in s))&&n.push({type:"body.has",field:r,expected:true,actual:false,message:`Step ${t.id}: body missing key '${r}'`});}if(t.expect.body?.match){let s=e.body;for(let[r,o]of Object.entries(t.expect.body.match)){let i=s?ur(s,r):void 0;JSON.stringify(i)!==JSON.stringify(o)&&n.push({type:"body.match",field:r,expected:o,actual:i??null,message:`Step ${t.id}: '${r}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(o)}`});}}if(t.signals&&t.signals.length>0){let s=e.signals_fired||[];for(let r of t.signals)s.includes(r)||n.push({type:"signal",field:"signals_fired",expected:r,actual:s,message:`Step ${t.id}: signal '${r}' was not fired`});}if(t.gates.length>0&&e.gates_traversed)for(let s of t.gates)e.gates_traversed.includes(s)||n.push({type:"gate",field:"gates_traversed",expected:s,actual:e.gates_traversed,message:`Step ${t.id}: gate '${s}' was not traversed`});return n}async function ti(t,e={}){let n=[];try{let{SentinelStorage:a}=await import('./dist-W3XCATBJ.js'),c=new a,d=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(m=>{let h=JSON.parse(m.data_json||"{}");return !(e.run_id&&h.run_id!==e.run_id||e.chain_id&&h.chain_id!==e.chain_id||e.environment&&h.environment!==e.environment)}),p=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(m=>{let h=JSON.parse(m.data_json||"{}");return !(e.run_id&&h.run_id!==e.run_id||e.chain_id&&h.chain_id!==e.chain_id||e.environment&&h.environment!==e.environment)}),g=new Map;for(let m of [...d,...p]){let h=JSON.parse(m.data_json||"{}");h.step_id&&g.set(h.step_id,h);}for(let m of t.journey){let h=g.get(m.id);if(!h){n.push({step_id:m.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${m.id}' \u2014 step was never exercised`});continue}let x=pr(m,{status:h.status,body:h.body,gates_traversed:h.gates_traversed,signals_fired:h.signals_fired});n.push({step_id:m.id,matched:!0,passed:x.length===0,assertions:x});}}catch{for(let a of t.journey)n.push({step_id:a.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let s=n.filter(a=>a.matched).length,r=n.filter(a=>a.passed).length,o=n.filter(a=>a.matched&&!a.passed).length,i=n.reduce((a,c)=>a+c.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:n,summary:{total_steps:t.journey.length,matched:s,unmatched:t.journey.length-s,passed:r,failed:o,assertion_failures:i}}}var ae=".paradigm/protocols",ln="index.yaml";async function Qe(t){let e=P.join(t,ae);if(!w.existsSync(e))return [];let n=w.readdirSync(e).filter(r=>r.endsWith(".protocol")).sort(),s=[];for(let r of n)try{let o=w.readFileSync(P.join(e,r),"utf8"),i=z.load(o);i?.id&&i?.name&&s.push(i);}catch{}return s}async function fr(t,e){let n=e.replace(/^P-/,""),s=P.join(t,ae,`${n}.protocol`);if(w.existsSync(s))try{let o=w.readFileSync(s,"utf8");return z.load(o)}catch{return null}return (await Qe(t)).find(o=>o.id===e)||null}async function si(t){let e=P.join(t,ae,ln);if(!w.existsSync(e))return null;try{let n=w.readFileSync(e,"utf8");return z.load(n)}catch{return null}}async function ri(t,e,n=3){let s=await Qe(t);if(s.length===0)return [];let r=gr(e);if(r.length===0)return [];let o=[];for(let i of s){let a=0;for(let d of i.trigger){let u=d.toLowerCase();for(let p of r)u.includes(p)&&(a+=3);}for(let d of i.tags){let u=d.toLowerCase();for(let p of r)(u.includes(p)||p.includes(u))&&(a+=2);}let c=i.name.toLowerCase(),l=i.description.toLowerCase();for(let d of r)c.includes(d)&&(a+=1),l.includes(d)&&(a+=1);for(let d of i.steps)if(d.notes){let u=d.notes.toLowerCase();for(let p of r)u.includes(p)&&(a+=.5);}a>0&&o.push({protocol:i,score:a});}return o.sort((i,a)=>a.score-i.score),o.slice(0,n)}async function oi(t,e){let n=P.join(t,ae);w.existsSync(n)||w.mkdirSync(n,{recursive:true});let s=yr(e.name),r=`P-${s}`,o=new Date().toISOString(),i={id:r,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:o,last_verified:o,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},a=P.join(n,`${s}.protocol`);return w.writeFileSync(a,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),r}async function ii(t,e,n,s=false){let r=await fr(t,e);if(!r)return false;n.name!==void 0&&(r.name=n.name),n.description!==void 0&&(r.description=n.description),n.trigger!==void 0&&(r.trigger=n.trigger),n.tags!==void 0&&(r.tags=n.tags),n.symbols!==void 0&&(r.symbols=n.symbols),n.exemplar!==void 0&&(r.exemplar=n.exemplar),n.steps!==void 0&&(r.steps=n.steps),n.status!==void 0&&(r.status=n.status),n.verified_by!==void 0&&(r.verified_by=n.verified_by),s&&(r.last_verified=new Date().toISOString(),r.verified_by=n.verified_by||"claude-opus-4-6");let o=e.replace(/^P-/,""),i=P.join(t,ae,`${o}.protocol`);return w.writeFileSync(i,z.dump(r,{lineWidth:-1,noRefs:true}),"utf8"),true}function mr(t,e){let n=[],s="current";if(e.exemplar){let r=P.join(t,e.exemplar);w.existsSync(r)?w.statSync(r).mtime.toISOString()>e.last_verified&&(n.push(`Exemplar modified since last verified: ${e.exemplar}`),s!=="broken"&&(s="stale")):(n.push(`Exemplar missing: ${e.exemplar}`),s="broken");}for(let r of e.steps){if(r.template_from){let o=P.join(t,r.template_from);w.existsSync(o)||(n.push(`Template file missing: ${r.template_from}`),s="broken");}if(r.action==="modify"&&r.target){let o=P.join(t,r.target);!r.target.includes("{")&&!w.existsSync(o)&&(n.push(`Modify target missing: ${r.target}`),s="broken");}}return {status:s,issues:n}}async function dn(t){let e=await Qe(t),n=[],s=0,r=0,o=0;for(let c of e){let l=mr(t,c);if(c.status!==l.status){c.status=l.status;let d=c.id.replace(/^P-/,""),u=P.join(t,ae,`${d}.protocol`);w.existsSync(u)&&w.writeFileSync(u,z.dump(c,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":s++;break;case "stale":r++;break;case "broken":o++;break}n.push({id:c.id,name:c.name,status:l.status,last_verified:c.last_verified,trigger:c.trigger,tags:c.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:s,stale:r,broken:o}},a=P.join(t,ae);if(e.length>0){w.existsSync(a)||w.mkdirSync(a,{recursive:true});let c=P.join(a,ln);w.writeFileSync(c,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function ai(t,e,n){if(!e||e.length<2)return null;let s={};for(let r of e){let o=P.dirname(r);s[o]||(s[o]=[]),s[o].push(r);}for(let[r,o]of Object.entries(s)){if(o.length<2)continue;let i=P.join(t,r);if(!w.existsSync(i))continue;let c=w.readdirSync(i).filter(l=>{let d=P.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(l=>!o.some(d=>P.basename(d)===l));if(c.length>0){let l=P.join(r,c[0]),d=[...o.map(u=>({action:"create",target:u})),...n.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${o.length} new files in ${r}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${P.basename(r).replace(/s$/,"")}`,exemplar:l,steps:d}}}}return null}function gr(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!hr.has(e))}var hr=new Set(["a","an","the","is","are","was","were","be","been","to","of","in","for","on","with","at","by","from","it","this","that","and","or","but","if","then","so","as","do","does","did","will","would","can","could","should","may","might","must","shall","i","me","my","we","our","you","your","he","she","how","what","when","where","which","who","whom"]);function yr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Z="pack.yaml";var wr="PARADIGM_STRICT";function pe(){let t=process.env[wr];if(t===void 0||t==="")return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}function Sr(t){return Lt(t)}function fn(t,e){if(!w.existsSync(t))return {status:"missing"};let n;try{n=w.readFileSync(t,"utf-8");}catch{return Ze({status:"unparseable",errorClass:"other",detail:"file read error"},e)}let s;try{s=z.load(n);}catch(r){let{errorClass:o,detail:i}=Sr(r);return Ze({status:"unparseable",errorClass:o,detail:i},e)}if(e?.schema){let r=e.schema.safeParse(s);if(!r.success){let o={status:"invalid",errorClass:"schema",detail:`schema validation failed (${r.error.issues.length} issue(s))`};return Ze(o,e)}return {status:"ok",data:r.data}}return {status:"ok",data:s}}function Ze(t,e){if(!(e?.strict??pe())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}b$1();var mn="@a-company/university",gn=".paradigm/university",hn=".paradigm/cache/packs.json",U=class extends Error{constructor(n,s){super(`pack-load failed (${n}: ${s})`);this.errorClass=n;this.detail=s;this.name="PackLoadError";}},br=["id","name","version","schema_version","tenant_kind"],xr=new Set(["first-party","project","external"]);function fe(t){let e=P.join(t,Z),n=fn(e);switch(n.status){case "missing":throw new U("missing-manifest",`no ${Z} at pack root`);case "unparseable":throw new U("manifest-unparseable",n.detail);case "invalid":throw new U("manifest-invalid",n.detail);case "ok":{let s=n.data;if(!s||typeof s!="object")throw new U("manifest-invalid","manifest is not an object");for(let r of br){let o=s[r];if(o==null||o==="")throw new U("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!xr.has(String(s.tenant_kind)))throw new U("missing-required-field","tenant_kind must be one of first-party|project|external");return s}}}function yn(t){let e=Tr(t);if(e)return e;let n=[],s=P.join(t,"node_modules",mn);if(w.existsSync(P.join(s,Z)))try{let o=fe(s);n.push({manifest:o,rootDir:s,source:"first-party"});}catch(o){a$1.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:o instanceof U?o.errorClass:"other"});}for(let o of vr(t))try{let i=fe(o);n.push({manifest:i,rootDir:o,source:"npm"});}catch(i){a$1.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:i instanceof U?i.errorClass:"other"});}let r=P.join(t,gn);if(w.existsSync(r)&&w.statSync(r).isDirectory()){let o=P.join(r,Z),i;if(w.existsSync(o))try{i=fe(r),n.push({manifest:i,rootDir:r,source:"local"});}catch(c){a$1.component("#pack-loader").warn("local pack manifest invalid",{errorClass:c instanceof U?c.errorClass:"other"});}let a=i?.id??"project";for(let c of Er(r))try{let l=fe(c);n.push({manifest:l,rootDir:c,source:"local",parentPackId:a});}catch(l){a$1.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof U?l.errorClass:"other"});}}return kr(t,n),n}function vr(t){let e=P.join(t,"package.json");if(!w.existsSync(e))return [];let n;try{n=JSON.parse(w.readFileSync(e,"utf8"));}catch{return []}let s=new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{}),...Object.keys(n.peerDependencies||{})]);if(s.size===0)return [];let r=P.join(t,"node_modules");if(!w.existsSync(r))return [];let o=[];for(let i of s){if(i===mn)continue;let a=P.join(r,i,"package.json");if(!w.existsSync(a))continue;let c;try{c=JSON.parse(w.readFileSync(a,"utf8"));}catch{continue}let l=c.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let d=P.resolve(P.dirname(a),l);w.existsSync(P.join(d,Z))&&o.push(d);}return o}function Er(t){let e=[],n;try{n=w.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let r=P.join(t,s.name);w.existsSync(P.join(r,Z))&&e.push(r);}return e}function yi(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let n=t.indexOf(":");if(n!==-1){let r=t.slice(0,n),o=t.slice(n+1);if(!r||!o)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:r,entryId:o}}let s=t;if(e.candidatePacks&&e.entryExistsIn){let r=e.candidatePacks.filter(o=>e.entryExistsIn(o,s));if(r.length>1){let o=r.map(i=>`${i}:${s}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${s}" is ambiguous across packs. Candidates: ${o}`)}if(r.length===1)return {packId:r[0],entryId:s}}return {packId:e.activePack,entryId:s}}function wn(t){try{return w.statSync(P.join(t,"node_modules")).mtime.getTime()}catch{return}}function Sn(t){try{return w.statSync(P.join(t,gn)).mtime.getTime()}catch{return}}function Tr(t){let e=P.join(t,hn);if(!w.existsSync(e))return null;let n;try{n=JSON.parse(w.readFileSync(e,"utf8"));}catch{return null}if(n.version!==1||!Array.isArray(n.packs))return null;let s=wn(t),r=Sn(t);return n.node_modules_mtime_ms!==s||n.local_university_mtime_ms!==r?null:n.packs.map(o=>({manifest:o.manifest,rootDir:o.rootDir,source:o.source,...o.parentPackId?{parentPackId:o.parentPackId}:{}}))}function kr(t,e){let n=P.join(t,hn);try{w.mkdirSync(P.dirname(n),{recursive:!0});let s={version:1,node_modules_mtime_ms:wn(t),local_university_mtime_ms:Sn(t),packs:e.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))};w.writeFileSync(n,JSON.stringify(s,null,2),"utf8");}catch{}}b$1();var me=".paradigm/university",re="content",tt="notes",$e="policies",Ce="quizzes",Ae="paths",bn="diplomas",xn="index.yaml",_r="config.yaml";function nt(t){let e=P.join(t,me);if(w.existsSync(e))return e;try{let s=yn(t).find(r=>r.manifest.tenant_kind==="first-party");if(s)return s.rootDir}catch{}return e}function vn(t){if(!w.existsSync(t))return null;let e=P.join(t,Z);if(w.existsSync(e))try{return fe(t)}catch(s){a$1.component("#university-loader").warn("pack manifest invalid, using implicit manifest",{errorClass:s instanceof U?s.errorClass:"other"});}let n=P.basename(t)||"project";return {id:n,name:n,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored"}}function Pr(t,e,n){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!n?{}:{discipline:n}}:t}var En={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Tn={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},et={branding:En,theme:Tn,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function st(t){let e=P.join(t,me,_r);if(!w.existsSync(e))return {...et};try{let n=w.readFileSync(e,"utf8"),s=z.load(n);return s?{branding:{...En,...s.branding||{}},theme:{...Tn,...s.theme||{}},content:{categories:s.content?.categories||[],defaultDifficulty:s.content?.defaultDifficulty||"beginner",requireApproval:s.content?.requireApproval??!1,defaultCategory:s.content?.defaultCategory},diplomas:{includeGlobalPLSAT:s.diplomas?.includeGlobalPLSAT??!0,customCertStyle:s.diplomas?.customCertStyle??null}}:{...et}}catch{return {...et}}}function Le(t){let e=P.join(t,me,xn);if(!w.existsSync(e))return null;try{let n=w.readFileSync(e,"utf8");return z.load(n)}catch{return null}}function kn(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:z.load(e[1]),body:e[2].trim()}}catch{return null}}function Ir(t,e){return `---
|
|
107
|
+
${z.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
|
|
108
|
+
|
|
109
|
+
${e}
|
|
110
|
+
`}function vi(t,e,n){let s=ot(t,e,".md",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=kn(r);if(!o)return null;let i=o.frontmatter;return {frontmatter:Ar(i),body:o.body}}catch{return null}}function Ei(t,e,n,s){let r=e.type==="policy"?$e:tt,o=s??nt(t),i=P.join(o,re,r);w.mkdirSync(i,{recursive:true});let a=vn(o),c=Pr(e,a),l=P.join(i,`${c.id}.md`),d=Ir(c,n);return w.writeFileSync(l,d,"utf8"),l}function Rr(t,e,n){let s=ot(t,e,".yaml",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=z.load(r);return !o||!o.id?null:Lr(o)}catch{return null}}function Ti(t,e,n){let s=n??nt(t),r=P.join(s,re,Ce);w.mkdirSync(r,{recursive:true});let o=vn(s),i={...e,...e.pack_id||!o?{}:{pack_id:o.id}},a=P.join(r,`${i.id}.yaml`);return w.writeFileSync(a,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),a}function _n(t,e,n){let s=ot(t,e,".yaml",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=z.load(r);return !o||!o.id?null:o}catch{return null}}function ki(t,e,n){let s=n??nt(t),r=P.join(s,re,Ae);w.mkdirSync(r,{recursive:true});let o=P.join(r,`${e.id}.yaml`);return w.writeFileSync(o,z.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),o}function Pn(t,e){let n=P.join(t,me,bn);if(!w.existsSync(n))return [];let s=[];try{let r=w.readdirSync(n).filter(o=>o.endsWith(".yaml"));for(let o of r)try{let i=w.readFileSync(P.join(n,o),"utf8"),a=z.load(i);if(!a||!a.id||e?.student&&a.student!==e.student||e?.type&&a.type!==e.type)continue;s.push(a);}catch{}}catch{}return s.sort((r,o)=>o.earnedAt.localeCompare(r.earnedAt))}function _i(t,e){let n=Le(t);if(!n)return [];let s=[...n.entries];if(e.type&&(s=s.filter(o=>o.type===e.type)),e.tag&&(s=s.filter(o=>o.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(s=s.filter(o=>o.difficulty===e.difficulty)),e.symbol&&(s=s.filter(o=>o.symbols.some(i=>i===e.symbol))),e.author&&(s=s.filter(o=>o.author===e.author)),e.query){let o=e.query.toLowerCase();s=s.filter(i=>i.title.toLowerCase().includes(o)||i.id.toLowerCase().includes(o)||i.tags.some(a=>a.toLowerCase().includes(o)));}if(e.category&&(s=s.filter(o=>o.category===e.category)),e.track){let o=st(t),i=new Map;for(let a of o.content.categories)i.set(a.id,a.track||"core");s=s.filter(a=>(a.category&&i.get(a.category)||"core")===e.track);}let r=e.limit||20;return s.slice(0,r)}function rt(t){let e=P.join(t,me),n=P.join(e,re),s=[];for(let d of [tt,$e]){let u=P.join(n,d);if(w.existsSync(u))try{for(let p of w.readdirSync(u).filter(g=>g.endsWith(".md")))try{let g=w.readFileSync(P.join(u,p),"utf8"),m=kn(g);if(!m)continue;let h=m.frontmatter;s.push({id:h.id||p.replace(".md",""),title:h.title||p,type:h.type||(d===$e?"policy":"note"),author:h.author||"unknown",created:h.created||"",updated:h.updated||"",tags:Array.isArray(h.tags)?h.tags:[],symbols:Array.isArray(h.symbols)?h.symbols:[],difficulty:h.difficulty||"beginner",file:`${re}/${d}/${p}`,...h.category?{category:h.category}:{}});}catch{}}catch{}}let r=P.join(n,Ce);if(w.existsSync(r))try{for(let d of w.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=w.readFileSync(P.join(r,d),"utf8"),p=z.load(u);if(!p||!p.id)continue;s.push({id:p.id,title:p.title||d,type:"quiz",author:p.author||"unknown",created:p.created||"",updated:p.updated||"",tags:p.tags||[],symbols:p.symbols||[],difficulty:p.difficulty||"beginner",file:`${re}/${Ce}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let o=P.join(n,Ae);if(w.existsSync(o))try{for(let d of w.readdirSync(o).filter(u=>u.endsWith(".yaml")))try{let u=w.readFileSync(P.join(o,d),"utf8"),p=z.load(u);if(!p||!p.id)continue;s.push({id:p.id,title:p.title||d,type:"path",author:p.author||"unknown",created:p.created||"",updated:p.updated||"",tags:p.tags||[],symbols:[],file:`${re}/${Ae}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let i=0,a=P.join(e,bn);if(w.existsSync(a))try{i=w.readdirSync(a).filter(d=>d.endsWith(".yaml")).length;}catch{}let c={version:"1.0",generatedAt:new Date().toISOString(),totalContent:s.length,entries:s,diplomaCount:i};w.mkdirSync(e,{recursive:true});let l=P.join(e,xn);return w.writeFileSync(l,z.dump(c,{lineWidth:-1,noRefs:true}),"utf8"),c}function Pi(t,e){let n=Le(t)||rt(t),s=[],r=n.entries;e?.id&&(r=r.filter(l=>l.id===e.id));let o=null;e?.deep&&(o=In(t));let i=new Set(n.entries.map(l=>l.id));for(let l of r){if(l.title||s.push({contentId:l.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),l.type==="quiz"&&$r(t,l.id,s),l.type==="path"&&Cr(t,l.id,i,s),o&&l.symbols.length>0){st(t).content.categories.find(g=>g.id===l.category)?.validationStrictness==="relaxed";for(let g of l.symbols)o.has(g)||s.push({contentId:l.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${l.id}`});}e?.deep&&l.symbols.length>0&&l.updated&&Or(t,l,s);}let a=Pn(t);for(let l of a)if(l.total>0&&l.percentage!==Math.round(l.score/l.total*1e4)/100){let d=Math.round(l.score/l.total*1e4)/100;Math.abs(l.percentage-d)>.1&&s.push({contentId:l.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${l.percentage} doesn't match score ${l.score}/${l.total} (expected ${d})`});}let c=jr(t,n);return {status:s.some(l=>l.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:r.length,issues:s,symbolCoverage:c}}function $r(t,e,n){let s=Rr(t,e);if(!s){n.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!s.passThreshold||s.passThreshold<0||s.passThreshold>1)&&n.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${s.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let r of s.questions){if(!r.choices||typeof r.choices!="object"){n.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${r.id} has no choices defined`});continue}(!r.correct||!(r.correct in r.choices))&&n.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${r.id}: correct answer "${r.correct}" not found in choices [${Object.keys(r.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(r.choices).join(", ")}`});}}function Cr(t,e,n,s){let r=_n(t,e);if(!r){s.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let o of r.steps)o.content.startsWith("plsat:")||n.has(o.content)||s.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}" or remove this step`});}function Ii(t,e){let n=Le(t);if(!n)return [];let s=[];for(let r of n.entries)if(r.symbols.includes(e)){let o=Rn(t,r,e);s.push({id:r.id,title:r.title,type:r.type,stale:o});}return s}function Ri(t,e){let n=Le(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=st(t),r=new Set;for(let p of s.content.categories)p.excludeFromOnboarding&&r.add(p.id);let o=n.entries.filter(p=>!p.category||!r.has(p.category)),i=n.entries.filter(p=>p.category&&r.has(p.category)),a=o.filter(p=>p.type==="path"),c=e?Pn(t,{student:e}):[],l=new Set(c.map(p=>p.source)),d=a.map(p=>{let g=_n(t,p.id);return {id:p.id,title:p.title,steps:g?.steps.length||0,completed:l.has(p.id)}}),u=o.filter(p=>p.type!=="path"&&(p.difficulty==="beginner"||p.tags.includes("onboarding"))).slice(0,10);return {paths:d,suggestedContent:u,extracurricular:i,diplomaCount:c.length,totalContent:n.totalContent}}function ot(t,e,n,s){let r=s??P.join(t,me),o=P.join(r,re);for(let i of [tt,$e,Ce,Ae]){let a=P.join(o,i,`${e}${n}`);if(w.existsSync(a))return a}return null}function Ar(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{}}}function Lr(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function In(t){let e=new Set,n=P.join(t,".paradigm","scan-index.json");if(!w.existsSync(n))return e;try{let s=w.readFileSync(n,"utf8"),r=JSON.parse(s);if(r.symbols&&Array.isArray(r.symbols))for(let o of r.symbols)o.symbol&&e.add(o.symbol);}catch{}return e}function jr(t,e){let n=In(t),s=new Set;for(let o of e.entries)for(let i of o.symbols)n.has(i)&&s.add(i);let r=n.size;return {totalSymbols:r,coveredByContent:s.size,percentage:r>0?Math.round(s.size/r*100):0}}function Rn(t,e,n){if(!e.updated)return false;let s=new Date(e.updated).getTime();if(isNaN(s))return false;let r=P.join(t,".paradigm","scan-index.json");if(!w.existsSync(r))return false;try{let o=w.readFileSync(r,"utf8"),i=JSON.parse(o);if(i.symbols&&Array.isArray(i.symbols)){for(let a of i.symbols)if(a.symbol===n&&a.filePath){let c=P.join(t,a.filePath);if(w.existsSync(c)&&w.statSync(c).mtime.getTime()>s)return !0}}}catch{}return false}function Or(t,e,n){for(let s of e.symbols)if(Rn(t,e,s)){n.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${s}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${s}`});break}}var $n=new Set(["duplicate-key-detected"]);function Fr(t){let e=t.trim();if(e.includes("/")||e.includes("\\")){let n=e.split(/[/\\]/);e=n[n.length-1]||"unknown";}return e.length>40&&(e=e.slice(0,40)),e||"unknown"}var je=class{transforms=new Map;record(e,n,s=1){let r=Fr(n),o=`${e}::${r}`,i=this.transforms.get(o);i?i.count+=s:this.transforms.set(o,{kind:e,surface:r,count:s});}report(){let e=Array.from(this.transforms.values()).sort((s,r)=>s.kind!==r.kind?s.kind.localeCompare(r.kind):s.surface.localeCompare(r.surface)),n=e.filter(s=>$n.has(s.kind)).reduce((s,r)=>s+r.count,0);return {reindex_ts:new Date().toISOString(),transformations:e,lossy_count:n,strict_mode:pe()}}hasLossy(){for(let e of this.transforms.values())if($n.has(e.kind))return true;return false}totalCount(){let e=0;for(let n of this.transforms.values())e+=n.count;return e}};b$1();var Nr={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Dr={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/"]},Mr={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"]},it={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 Vi(){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 Yi(t,e,n,s){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let r=await Ur(n.rootDir,n);await s(),Ht.clear(),Gt();let o=(r.integrityReport?.brokenReferences?.length||0)+(r.integrityReport?.duplicateSymbols?.length||0)+(r.componentAnchorIssues||0)+(r.crossFileIssues||0),i={success:!0,symbolCount:r.symbolCount,breakdown:r.breakdown,flowCount:r.flowCount,filesWritten:r.filesWritten.length,...r.aspectGraphStats?{aspects:r.aspectGraphStats.aspects,loreLinks:r.aspectGraphStats.loreLinks}:{},...r.protocolHealth?{protocols:r.protocolHealth.total,staleProtocols:r.protocolHealth.stale}:{},...o>0?{issues:o}:{}};r.consistency&&(i.consistency=r.consistency);let a=JSON.stringify(i,null,2);return Ge(a.length,t),{handled:!0,text:a}}catch(r){let o=JSON.stringify({error:r.message},null,2);return Ge(o.length,t),{handled:true,text:o}}}async function Ur(t,e){let n=[],s=new je,r;e?r=e.aggregation:r=await Mt(t);let o=e?.projectName||P.basename(t),i=P.join(t,".paradigm");w.existsSync(i)||w.mkdirSync(i,{recursive:true}),zr(t,s),Hr(r.purposeFiles,s);let a=He({symbols:r.symbols,purposeFiles:r.purposeFiles,portalFiles:r.portalFiles},{projectName:o}),c=P.join(i,"scan-index.json");w.writeFileSync(c,We(a),"utf8"),n.push(".paradigm/scan-index.json");let l=Wr(t,r),d=P.join(i,"navigator.yaml");w.writeFileSync(d,z.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let u=Yr(t,r.purposeFiles),p=0;if(u&&Object.keys(u.flows).length>0){let v=P.join(i,"flow-index.json");w.writeFileSync(v,JSON.stringify(u,null,2),"utf8"),n.push(".paradigm/flow-index.json"),p=Object.keys(u.flows).length;}let g;try{let v=await tn(t);sn(v,r.symbols,t);let D=await on(v,t),ce=await an(v,t),Ln=v.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,jn=v.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,On=v.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;nn(v,t),n.push(".paradigm/aspect-graph.db"),g={aspects:Ln,anchors:jn,edges:On,loreLinks:D};}catch{}let m=0;try{let v=await be(t);m=Object.keys(v.personas).length,m>0&&n.push(".paradigm/personas/index.yaml");}catch{}let h;try{let v=await dn(t);v.health.total>0&&(h=v.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let x;try{let v=P.join(t,".paradigm","university");if(w.existsSync(v)){let D=rt(t);(D.totalContent>0||D.diplomaCount>0)&&(x={totalContent:D.totalContent,diplomaCount:D.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let T;try{T=a$2(r,t);}catch{}let E;try{let v=b$4(r.symbols,t),D=v.missing+v.outOfBounds;D>0&&(E=D);}catch{}let k;try{k=c$2(r.purposeFiles,t);}catch{}let S;try{let v=[];for(let D of r.purposeFiles){let ce=Me(D);ce.data&&v.push({filePath:D,data:ce.data});}if(v.length>0){let ce=Rt(v).issues.length;ce>0&&(S=ce);}}catch{}let b={};for(let v of r.symbols)b[v.type]=(b[v.type]||0)+1;let A={};for(let v of r.symbols)v.type==="component"&&v.componentType&&(A[v.componentType]=(A[v.componentType]||0)+1);let N=s.report();try{let v=P.join(i,"manifest.consistency.json");w.writeFileSync(v,JSON.stringify(N,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$1.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(pe()&&s.hasLossy())throw new Error(`reindex aborted: ${N.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:r.symbols.length,breakdown:b,flowCount:p,aspectGraphStats:g,personaCount:m,protocolHealth:h,consistency:N,...Object.keys(A).length>0?{componentTypeBreakdown:A}:{},...x?{universityStats:x}:{},...T?{integrityReport:T}:{},...E!==void 0?{componentAnchorIssues:E}:{},...k?{purposeHealth:k}:{},...S!==void 0?{crossFileIssues:S}:{}}}function zr(t,e){let n=P.join(t,"portal.yaml");if(!w.existsSync(n))return;let s;try{s=w.readFileSync(n,"utf-8");}catch{return}try{z.load(s);}catch(c){(c?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","portal.yaml");return}let r;try{r=z.load(s,{schema:z.FAILSAFE_SCHEMA});}catch{return}if(!r||typeof r!="object")return;let o=r,i=o.gates;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=0;for(let l of Object.keys(i))l.startsWith("^")&&c++;c>0&&e.record("prefix-stripped","portal.yaml",c);}else Array.isArray(i)&&i.length>0&&e.record("array-coerced","portal.yaml");let a=o.routes;Array.isArray(a)&&a.length>0&&e.record("array-coerced","portal.yaml"),o.version||e.record("default-applied","portal.yaml");}function Hr(t,e){for(let n of t){let s;try{s=w.readFileSync(n,"utf-8");}catch{continue}try{z.load(s);}catch(d){(d?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","purpose.yaml");continue}let r;try{r=z.load(s,{schema:z.FAILSAFE_SCHEMA});}catch{continue}if(!r||typeof r!="object")continue;let o=r,i=["components","features","gates","signals","aspects","states"],a=0;for(let d of i)Array.isArray(o[d])&&a++;a>0&&e.record("array-coerced","purpose.yaml",a);let c=(d,u)=>{if(!d||typeof d!="object"||Array.isArray(d))return 0;let p=0;for(let g of Object.keys(d))g.startsWith(u)&&p++;return p},l=c(o.gates,"^")+c(o.signals,"!")+c(o.aspects,"~")+c(o.components,"#")+c(o.features,"#");l>0&&e.record("prefix-stripped","purpose.yaml",l);}}function Wr(t,e){let n={};for(let s of e.symbols)if(s.type==="component"&&s.componentType){let r=s.componentType;n[r]||(n[r]=[]),n[r].push(s.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:Gr(t),key_files:Br(t),skip_patterns:Xr(t),symbols:Vr(e.symbols,e.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function Gr(t){let e={};for(let[n,s]of Object.entries(Dr)){let r=s.filter(o=>w.existsSync(P.join(t,o)));if(r.length>0){let o=Object.values(Nr).find(i=>i.category===n);e[n]={paths:r,symbol:o?.prefix||"@"};}}return e}function Br(t){let e={};for(let[n,s]of Object.entries(Mr)){let r=s.filter(o=>w.existsSync(P.join(t,o)));r.length>0&&(e[n]=r);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function Xr(t){let e={always:[...it.always],unless_testing:[...it.unless_testing],unless_docs:[...it.unless_docs]},n=P.join(t,".gitignore");if(w.existsSync(n))try{let r=w.readFileSync(n,"utf8").split(`
|
|
111
|
+
`).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).filter(o=>o.endsWith("/")||o.includes("*")||["node_modules","dist","build",".cache"].some(i=>o.includes(i))).slice(0,20);for(let o of r)e.always.includes(o)||e.always.push(o);}catch{}return e}function qr(t){switch(t){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 Vr(t,e,n){let s={};for(let r of t){let i=`${qr(r.type)}${r.id}`;if(r.filePath)s[i]=r.filePath;else {let a=e.find(c=>P.dirname(c).toLowerCase().includes(r.id.toLowerCase()));a&&(s[i]=P.dirname(a)+"/");}}return s}function Yr(t,e){let n={},s={};for(let r of e)try{let o=w.readFileSync(r,"utf8"),i=z.load(o);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let a of i.flows){let c=a;if(!c.name)continue;let l=`$${c.name}`,d=Cn(c.steps);d.length>0&&(n[l]={id:l,description:c.description||"",steps:d,definedIn:P.relative(t,r)},An(l,d,s));}else for(let[a,c]of Object.entries(i.flows)){let l=a.startsWith("$")?a:`$${a}`,d=Cn(c.steps);d.length>0&&(n[l]={id:l,description:c.description||"",trigger:c.trigger,steps:d,validation:c.validation,definedIn:P.relative(t,r)},An(l,d,s));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:s}}function Cn(t){if(!t||!Array.isArray(t))return [];let e=[];for(let n=0;n<t.length;n++){let s=t[n];if(typeof s=="object"&&s!==null){let r=s,o=r.action||r.description||r.component||"";o&&e.push({id:r.id||`step-${n+1}`,action:o,symbol:r.symbol||r.component,expect:r.expect});}}return e}function An(t,e,n){for(let s of e)s.symbol&&(n[s.symbol]||(n[s.symbol]=[]),n[s.symbol].includes(t)||n[s.symbol].push(t));}export{si as $,Yo as A,Ko as B,Jo as C,Qo as D,Zo as E,ei as F,ti as G,pe as H,fn as I,yn as J,yi as K,nt as L,vn as M,st as N,vi as O,Ei as P,Rr as Q,Ti as R,_n as S,ki as T,_i as U,rt as V,Pi as W,Ii as X,Ri as Y,Qe as Z,fr as _,Qn as a,ri as aa,Jr as b,oi as ba,es as c,ii as ca,Zr as d,mr as da,Te as e,ai as ea,Mt as f,tn as fa,ao as g,nn as ga,ke as h,Fo as ha,co as i,No as ia,lo as j,Do as ja,uo as k,Mo as ka,po as l,Uo as la,fo as m,zo as ma,mo as n,Ho as na,Ge as o,Wo as oa,ko as p,Xo as pa,_o as q,Vi as qa,Po as r,Yi as ra,Io as s,Ur as sa,Ro as t,Wt as u,Ht as v,we as w,Se as x,Vo as y,cn as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as a from'fs';import*as d from'path';import*as m from'js-yaml';b$1();var u=".paradigm/decisions",h=".paradigm/lore";function b(){let e=new Date().toISOString().slice(0,10),t=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `TD-${e}-${t}`}function w(o,e){let t=new Date,r=b(),n={id:r,timestamp:t.toISOString(),...e},s=d.join(o,u);a.mkdirSync(s,{recursive:true});let i=d.join(s,`${r}.yaml`);return a.writeFileSync(i,m.dump(n,{lineWidth:120,noRefs:true}),"utf8"),n}function T(o,e,t){let r=p(o,e);if(!r)return null;let n={...r,...t},s=d.join(o,u),i=d.join(s,`${e}.yaml`);return a.writeFileSync(i,m.dump(n,{lineWidth:120,noRefs:true}),"utf8"),n}function $(o,e,t){if(!p(o,e))return null;let n=Array.from(new Set([...t.supersedes??[],e])),s=w(o,{...t,supersedes:n}),i=T(o,e,{status:"superseded",superseded_by:s.id});return i?{old:i,new:s}:null}function F(o,e){try{let t=p(o,e);if(!t)return null;let r=new Date().toISOString().slice(0,10),n=process.env.USER||process.env.USERNAME||"unknown",s=String(Math.floor(Math.random()*999)+1).padStart(3,"0"),i=new Date().toISOString().slice(11,19).replace(/:/g,""),c=`L-${r}-${n}-${i}-${s}`,l={id:c,type:"insight",timestamp:new Date().toISOString(),author:n,title:`Decision ${t.id} recorded`,summary:`Companion lore entry for decision record ${t.id}. See .paradigm/decisions/${t.id}.yaml.`,symbols_touched:t.symbols_affected||[],references:{decision_id:t.id},tags:["companion-lore","decision-reference"]},f=d.join(o,h,"entries",r);a.mkdirSync(f,{recursive:!0});let D=d.join(f,`${c}.lore`);return a.writeFileSync(D,m.dump(l,{lineWidth:120,noRefs:!0}),"utf8"),c}catch(t){return a$1.component("#decision-loader").warn("companion lore write failed",{error:t.message,decisionId:e}),null}}function g(o,e){let t=d.join(o,u);if(!a.existsSync(t))return [];let r=[],n=a.readdirSync(t).filter(i=>i.endsWith(".yaml"));for(let i of n)try{let c=a.readFileSync(d.join(t,i),"utf8"),l=m.load(c);l&&l.id&&r.push(l);}catch{}let s=r;return e?.status&&(s=s.filter(i=>i.status===e.status)),e?.participant&&(s=s.filter(i=>i.participants.some(c=>c.id===e.participant))),e?.symbol&&(s=s.filter(i=>i.symbols_affected?.includes(e.symbol))),e?.tag&&(s=s.filter(i=>i.tags?.some(c=>c.startsWith(e.tag)))),e?.dateFrom&&(s=s.filter(i=>i.timestamp>=e.dateFrom)),e?.dateTo&&(s=s.filter(i=>i.timestamp<=e.dateTo)),s.sort((i,c)=>c.timestamp.localeCompare(i.timestamp)),e?.limit&&(s=s.slice(0,e.limit)),s}function p(o,e){let t=d.join(o,u),r=d.join(t,`${e}.yaml`);if(!a.existsSync(r))return null;let n=a.readFileSync(r,"utf8");return m.load(n)}function j(o,e){return g(o,{symbol:e,status:"active"})}function v(o){let e=g(o),t={},r=new Set;for(let n of e)t[n.status]=(t[n.status]||0)+1,n.symbols_affected?.forEach(s=>r.add(s));return {total:e.length,active:t.active||0,superseded:t.superseded||0,deprecated:t.deprecated||0,proposed:t.proposed||0,recentDecisions:e.slice(0,10).map(n=>({id:n.id,title:n.title,status:n.status,timestamp:n.timestamp})),symbolsCovered:[...r].sort()}}export{w as a,T as b,$ as c,F as d,g as e,p as f,j as g,v as h};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {c,a as a$1}from'./chunk-YNDPSWOE.js';import {e as e$1}from'./chunk-VIG5LSGZ.js';import {a}from'./chunk-LKAT7IAK.js';import*as e from'fs';import*as i from'path';import*as S from'js-yaml';import l from'chalk';async function rs(P={}){let p=P.rootDir||process.cwd(),s=[],w=P.quiet,N=P.context;w||(console.log(l.blue(`
|
|
3
|
+
\u{1FA7A} Paradigm Doctor
|
|
4
|
+
`)),console.log(N?l.gray(`Running context audit checks...
|
|
5
|
+
`):l.gray(`Checking Paradigm setup...
|
|
6
|
+
`)));let I=a.command("doctor").start("Running health checks");if(!N){let E=function(t){let a=[];try{let o=e.readdirSync(t,{withFileTypes:!0});for(let r of o){if(r.name==="node_modules"||r.name==="dist"||r.name===".git")continue;let f=i.join(t,r.name);r.isDirectory()?a.push(...E(f)):r.name===".purpose"&&a.push(f);}}catch{}return a};let n=i.join(p,".paradigm");if(e.existsSync(n))if(e.statSync(n).isFile())s.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {s.push({name:".paradigm/",status:"ok",message:"Directory exists"});let a=i.join(n,"config.yaml");if(e.existsSync(a))try{let g=e.readFileSync(a,"utf8");e$1(g),s.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(g){s.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${g.message}`,fix:"Check YAML syntax"});}else s.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let o=["logger.md","probe.md","symbols.md"],r=i.join(n,"specs");if(e.existsSync(r))for(let g of o){let x=i.join(r,g);e.existsSync(x)?s.push({name:`.paradigm/specs/${g}`,status:"ok",message:"Present"}):s.push({name:`.paradigm/specs/${g}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else s.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let f=i.join(n,"docs");e.existsSync(f)?s.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let h=i.join(n,"prompts");e.existsSync(h)?s.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let u=["specs","implementation-guides","prompts","decisions"],d=[];for(let g of u){let x=i.join(n,g);if(e.existsSync(x)&&e.statSync(x).isDirectory()){let k=i.join(x,".index.yaml");e.existsSync(k)||d.push(`.paradigm/${g}/`);}}d.length>0?s.push({name:"Docs-class indexes",status:"warn",message:`${d.length} director${d.length===1?"y":"ies"} missing .index.yaml: ${d.join(", ")}`,fix:"paradigm docs scaffold"}):s.push({name:"Docs-class indexes",status:"ok",message:"All docs-class directories have .index.yaml"});let y=i.join(n,"scan-index.json"),F=i.join(p,".paradigm-scan-index.json");if(e.existsSync(y)){let g=e.statSync(y),x=Date.now()-g.mtime.getTime(),k=Math.floor(x/(1e3*60*60));k>24?s.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${k} hours old)`,fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"ok",message:k>0?`${k} hours old`:"Fresh"});}else e.existsSync(F)?s.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else s.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let m=c(p);if(m.detected){let t=a$1(m.detected);if(t){let a=i.join(p,t.outputPath);e.existsSync(a)?s.push({name:t.outputPath,status:"ok",message:`Present (${m.detected})`}):s.push({name:t.outputPath,status:"missing",message:`Not generated for ${m.detected}`,fix:"paradigm sync"});}}let c$1=i.join(p,".premise");e.existsSync(c$1)?s.push({name:".premise",status:"ok",message:"Present"}):s.push({name:".premise",status:"missing",message:"Not found (optional)"});let v=i.join(p,".purpose");e.existsSync(v)?s.push({name:".purpose",status:"ok",message:"Present"}):s.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let A=i.join(p,".paradigm","config.yaml");if(e.existsSync(A))try{let t=e.readFileSync(A,"utf8"),o=S.load(t)?.["purpose-required"];if(o&&Array.isArray(o)){let r=[];for(let f of o){if(!f.pattern)continue;let{glob:h}=await import('glob'),u=await h(f.pattern,{cwd:p,nodir:!1});for(let d of u){let y=i.join(p,d);try{e.statSync(y).isDirectory()&&!e.existsSync(i.join(y,".purpose"))&&r.push(d);}catch{}}}r.length>0?s.push({name:"Purpose-required",status:"warn",message:`${r.length} director${r.length===1?"y":"ies"} missing .purpose: ${r.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):s.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let q=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,R=0,Y=E(p);for(let t of Y)try{let o=e.readFileSync(t,"utf8").match(q);o&&(R+=o.length);}catch{}R>0?s.push({name:"Clarification markers",status:"warn",message:`${R} [NEEDS CLARIFICATION] marker${R>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):Y.length>0&&s.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let L=i.join(p,"portal.yaml");if(e.existsSync(L))try{let t=e.readFileSync(L,"utf8"),a=S.load(t);if(a?.version&&a?.gates){let o=Object.keys(a.gates||{}).length,r=Object.keys(a.routes||{}).length;s.push({name:"portal.yaml",status:"ok",message:`Valid (${o} gates, ${r} routes)`});}else s.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(t){s.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in portal.yaml"});}if(e.existsSync(L))try{let{checkPortalCompliance:t,getComplianceSummary:a}=await import('./portal-compliance-JONQ4SOP.js'),o=await t(p),r=a(o);s.push({name:"Portal compliance",status:r.status,message:r.message,fix:r.status!=="ok"?"paradigm portal check":void 0});}catch{}let U=i.join(p,".paradigm","flows.yaml");if(e.existsSync(U))try{let t=e.readFileSync(U,"utf8"),a=S.load(t);if(a?.version&&a?.flows){let o=Object.keys(a.flows||{}).length,r=Object.entries(a.flows||{}).filter(([,f])=>!f?.steps||(f.steps?.length??0)===0);r.length>0?s.push({name:".paradigm/flows.yaml",status:"warn",message:`${o} flows defined, ${r.length} have no steps`,fix:"Add steps to empty flow definitions"}):s.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${o} flows)`});}else s.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(t){s.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in flows.yaml"});}let H=i.join(p,".paradigm","lore");if(e.existsSync(H))try{let t=e.readdirSync(H).filter(a=>a.endsWith(".yaml"));t.length===0?s.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):s.push({name:"Lore entries",status:"ok",message:`${t.length} lore file${t.length>1?"s":""}`});}catch{s.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let G=i.join(p,".paradigm","university");if(e.existsSync(G))try{let t=i.join(G,"content"),a=0,o=0;if(e.existsSync(t))for(let r of ["notes","policies","quizzes","paths"]){let f=i.join(t,r);e.existsSync(f)&&(a+=e.readdirSync(f).filter(h=>h.endsWith(".md")||h.endsWith(".yaml")).length);}if(a===0)s.push({name:"University content",status:"warn",message:"University directory exists but no content found",fix:'Add content: paradigm university add note --title "Getting Started"'});else {let r=i.join(t,"quizzes");if(e.existsSync(r))for(let h of e.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=S.load(e.readFileSync(i.join(r,h),"utf8"));if(u?.questions)for(let d of u.questions)d.choices&&d.correct&&!(d.correct in d.choices)&&o++;}catch{}let f=i.join(t,"paths");if(e.existsSync(f))for(let h of e.readdirSync(f).filter(u=>u.endsWith(".yaml")))try{let u=S.load(e.readFileSync(i.join(f,h),"utf8"));if(u?.steps){for(let d of u.steps)if(d.content&&!d.content.startsWith("plsat:")){let y=!1;for(let F of ["notes","policies","quizzes","paths"]){let g=i.join(t,F);if(e.existsSync(g)&&e.readdirSync(g).some(k=>k.startsWith(d.content))){y=!0;break}}y||o++;}}}catch{}o>0?s.push({name:"University content",status:"warn",message:`${a} items, ${o} issue${o>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):s.push({name:"University content",status:"ok",message:`${a} content item${a>1?"s":""}`});}}catch{s.push({name:"University content",status:"warn",message:"Could not read university directory"});}let _=i.join(p,".claude","hooks.json"),ss=i.join(p,"plugins","paradigm","hooks.json");if(e.existsSync(_)){let t=e.statSync(_),a=Date.now()-t.mtime.getTime(),o=Math.floor(a/(1e3*60*60*24));o>30?s.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${o} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):s.push({name:"Claude Code hooks",status:"ok",message:o>0?`${o} days old`:"Fresh"});}else e.existsSync(ss)?s.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):s.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let V=i.join(p,".paradigm","habits.yaml");if(e.existsSync(V))try{let t=e.readFileSync(V,"utf8"),a=S.load(t);if(a?.version&&Array.isArray(a?.habits)){let o=a.habits.filter(r=>r.enabled!==!1).length;s.push({name:"Habits config",status:"ok",message:`Valid (${o}/${a.habits.length} enabled)`});}else s.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(t){s.push({name:"Habits config",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in habits.yaml"});}let J=i.join(p,"AGENTS.md");if(e.existsSync(J)){let t=e.statSync(J),a=Date.now()-t.mtime.getTime(),o=Math.floor(a/(1e3*60*60*24));o>60?s.push({name:"AGENTS.md",status:"warn",message:`${o} days since last update \u2014 may be stale`,fix:"paradigm sync"}):s.push({name:"AGENTS.md",status:"ok",message:o>0?`Updated ${o} days ago`:"Fresh"});}}let T=0,W=0,$=0;for(let n of s){let m,c;switch(n.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,W++;break;case "error":m="\u2717",c=l.red,T++;break;case "missing":m="\u25CB",c=l.gray,$++;break}if(!w){let v=n.name.padEnd(30);console.log(` ${c(m)} ${v} ${c(n.message)}`),n.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${n.fix}`));}}let{runContextAudit:Z}=await import('./context-audit-JVCA6GSV.js'),M=await Z(p,{quiet:w}),z=0,O=0,b=0;!w&&M.length>0&&(console.log(""),console.log(l.blue(" Context Audit")),console.log(l.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));for(let n of M){let m,c;switch(n.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,O++;break;case "error":m="\u2717",c=l.red,z++;break;case "advisory":m="\u2139",c=l.cyan,b++;break}if(!w){let v=n.check.padEnd(30);if(console.log(` ${c(m)} ${v} ${c(n.message)}`),n.details&&n.details.length>0){let A=n.details.slice(0,5);for(let q of A)console.log(l.gray(` \u2502 ${q}`));n.details.length>5&&console.log(l.gray(` \u2502 ... and ${n.details.length-5} more`));}n.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${n.fix}`));}}let C=T+z,j=W+O,D=C+j+$===0;if(!w)if(console.log(""),D)console.log(l.green(`\u2728 All checks passed!
|
|
7
|
+
`));else {let n=[];C>0&&n.push(l.red(`${C} error${C>1?"s":""}`)),j>0&&n.push(l.yellow(`${j} warning${j>1?"s":""}`)),$>0&&n.push(l.gray(`${$} missing`)),b>0&&n.push(l.cyan(`${b} advisor${b>1?"ies":"y"}`)),console.log(`${n.join(", ")} found.
|
|
8
|
+
`),console.log(l.gray("Run the suggested commands to fix issues.")),console.log(l.gray(`Troubleshooting guide: .paradigm/docs/troubleshooting.md
|
|
9
|
+
`));}if(!w&&P.explain&&!D)try{let{narrateAllGaps:n}=await import('./gap-narrator-NTXLUI7I.js'),m=[];for(let c of s)c.status!=="ok"&&(c.name===".purpose"||c.name.startsWith("Purpose-required")?m.push({type:"missing-purpose",target:c.name,severity:"improvement"}):c.name===".paradigm/scan-index.json"&&c.status==="warn"?m.push({type:"index-stale",target:c.name,severity:"improvement"}):c.name==="Portal compliance"?m.push({type:"portal-mismatch",target:c.name,severity:c.status==="error"?"blocking":"improvement"}):c.name==="Clarification markers"&&m.push({type:"missing-description",target:c.name,severity:"improvement"}));if(m.length>0){let c=n(m);console.log(l.blue(`
|
|
10
|
+
Gap Narrations (--explain)
|
|
11
|
+
`)),console.log(l.gray(c.narrative)),console.log("");}}catch{}D?I.success("All health checks passed",{total:s.length+M.length}):I.error("Health checks found issues",{errors:C,warnings:j,missing:$,advisories:b});try{let{captureSnapshot:n}=await import('./metrics-UESGUHTA.js');n(p);}catch{}return D}export{rs as a};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {a}from'./chunk-MBPLJKE5.js';import*as l from'fs';import*as g from'path';import*as k from'os';import*as L from'crypto';import*as h from'js-yaml';var j={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},T={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};var b=g.join(k.homedir(),".paradigm","agents"),v=".paradigm/agents",y=".agent",R=".paradigm/roster.yaml",_=.3,O=60,E=7,D=.2;function x(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=E)return t;let i=Math.pow(.5,(s-E)/O);return t*i}function M(t){let e=g.join(t,R);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function V(t,e){let o=M(e);return o?o.includes(t):true}function X(t,e){let o=g.join(t,R),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function K(){if(!l.existsSync(b))return [];try{return l.readdirSync(b).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function w(t,e){let o=g.join(t,v,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=A(n);return n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e}),n}}catch{}let s=g.join(b,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=I(n,f),a$1=A(r);return r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:e}),r}catch{}if(n){let c=A(n);n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e});}return n}catch{}return null}function q(t,e){let o=C(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function Q(t,e){let o=w(t,e);return o||(q(t,e)[0]??null)}function C(t){let e=new Map;if(l.existsSync(b))try{let s=l.readdirSync(b).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(b,i),"utf-8"),c=h.load(n);if(c?.id){let f=A(c);c.__integrityStatus=f,f==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,v);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=I(f,c),a$1=A(r);r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:r.id}),e.set(c.id,r);}else {let r=A(c);c.__integrityStatus=r,r==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function S(t,e,o,s){let i=o==="global"?b:g.join(s||process.cwd(),v);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=N(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function U(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:j[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};j[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),T[t]&&(s.attention={...T[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=S(t,s,i,e.rootDir);return {profile:s,filePath:n}}function Z(t,e){let o=C(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>x(n.entry.confidence,n.entry.lastTouch)-x(i.entry.confidence,i.entry.lastTouch))}function ee(t,e,o){let s=w(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-_)*p.confidence+_*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=G(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,v,`${e}${y}`),r=l.existsSync(f)?"project":"global";return S(e,s,r,t),true}function te(t,e,o){let s=w(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-_)*a.confidence+_*n);}let c=g.join(t,v,`${e}${y}`),f=l.existsSync(c)?"project":"global";return S(e,s,f,t),true}function ne(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>x(i.confidence,i.lastTouch)-x(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function se(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>x(a.confidence,a.lastTouch)-x(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-x(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>D?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
|
|
3
|
-
`)}async function re(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-
|
|
3
|
+
`)}async function re(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-D2ISOASW.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||U(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(F=>F.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function W(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function H(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function ie(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function oe(t,e){return e.type==="path"?W(t,e.path,e.mode):H(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return L.createHash("sha256").update(e).digest("hex")}function Y(t){return t.integrityHash?N(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function I(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function G(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}export{x as a,M as b,V as c,X as d,K as e,w as f,q as g,Q as h,C as i,S as j,U as k,Z as l,ee as m,te as n,ne as o,se as p,re as q,d as r,A as s,W as t,H as u,ie as v,oe as w,N as x,Y as y};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {q as q$1,p}from'./chunk-NEJ4ZLCY.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function O(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function A(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8");e=h.load(t),e.antipatterns||(e.antipatterns=[]);}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",E=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:e}=(q$1(),d(p));e(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>E)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
|
|
2
|
+
import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {q as q$1,p}from'./chunk-GAFKOFAV.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function O(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function A(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8");e=h.load(t),e.antipatterns||(e.antipatterns=[]);}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",E=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:e}=(q$1(),d(p));e(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>E)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
|
|
3
3
|
export{O as a,A as b,W as c,H as d,L as e,_ as f,J as g,U as h,k as i,X as j,q as k};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b}from'./chunk-
|
|
2
|
+
import {b}from'./chunk-Y4P4SGZV.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
|
|
3
3
|
\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(e.blue("\u2502")+e.white.bold(" paradigm workspace init ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Create a multi-project workspace ")+e.blue("\u2502")),console.log(e.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
|
|
4
4
|
`));let n=a.command("workspace-init").start("Creating workspace",{cwd:c});if(r.existsSync(o)&&!l.force){console.log(e.yellow(` .paradigm-workspace already exists. Use --force to overwrite.
|
|
5
5
|
`)),n.success("Workspace already exists");return}let s=c,t=r.readdirSync(s,{withFileTypes:true}),a$1=[];for(let p of t){if(!p.isDirectory()||p.name.startsWith(".")||p.name==="node_modules")continue;let g=i.join(s,p.name),k=r.existsSync(i.join(g,".paradigm")),y=r.existsSync(i.join(g,".purpose"));if(k||y){let w=j(p.name,g);a$1.push({name:p.name,path:`./${p.name}`,...w&&{role:w}});}}if(a$1.length===0){console.log(e.yellow(" No sibling projects with .paradigm/ or .purpose found.")),console.log(e.gray(` Create .purpose files in sibling directories first.
|