@a-company/paradigm 5.38.0 → 6.0.4
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-OATWIRHP.js → accept-orchestration-TIXUQQGR.js} +1 -1
- package/dist/add-UOR4INIV.js +8 -0
- package/dist/agent-MB3H5EZA.js +33 -0
- package/dist/{agent-loader-RIVI6QPP.js → agent-loader-VGBPL3TH.js} +1 -1
- package/dist/{agent-loader-RJRVO5GQ.js → agent-loader-W3RQJVW7.js} +1 -1
- package/dist/{agents-suggest-HYTFMQD3.js → agents-suggest-IKY6VD2R.js} +1 -1
- package/dist/{ambient-WTLYUAQM.js → ambient-AI42BOM5.js} +12 -12
- package/dist/{ambient-76YMUA5Q.js → ambient-FNNFB4AP.js} +1 -1
- package/dist/{assess-UFPYEJKP.js → assess-63WXHWJV.js} +1 -1
- package/dist/authority-FA3HLEOA.js +2 -0
- package/dist/{calibration-OLJYB5HN.js → calibration-BDHGYJOK.js} +1 -1
- package/dist/chunk-23T6UG73.js +605 -0
- package/dist/{chunk-4L7665QV.js → chunk-2AU5L333.js} +1 -1
- package/dist/{chunk-BOYQAMGC.js → chunk-4N56FRNE.js} +1 -1
- package/dist/{chunk-5QOCKWK5.js → chunk-4PSD5R7N.js} +2 -2
- package/dist/{chunk-MQIG6SMF.js → chunk-6QXBXZF6.js} +1 -1
- package/dist/{chunk-ORDKEGII.js → chunk-AMLD7IYC.js} +1 -1
- package/dist/{chunk-3DZK54RU.js → chunk-DBEWOKD6.js} +32 -7
- package/dist/{chunk-AGFPVSX5.js → chunk-F6E3HW45.js} +1 -1
- package/dist/{chunk-X3U3IGYT.js → chunk-GD4F2HC6.js} +2 -2
- package/dist/chunk-GRZQIKST.js +2 -0
- package/dist/{chunk-HOBHJPTL.js → chunk-IOVHF4SR.js} +1 -1
- package/dist/{chunk-RLCH7DXQ.js → chunk-K7X3Z3GL.js} +1 -1
- package/dist/{chunk-74SGKSRQ.js → chunk-KAFQA7HV.js} +2 -2
- package/dist/{chunk-NEJ4ZLCY.js → chunk-LAYBUKMB.js} +1 -1
- package/dist/{chunk-4VKSEOXZ.js → chunk-LPBCQM5Y.js} +3 -3
- package/dist/chunk-Q527BPUF.js +2 -0
- package/dist/{chunk-AO7ZSRME.js → chunk-TQOT2LBO.js} +2 -2
- 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-WXF5VFB4.js +111 -0
- package/dist/chunk-XQLO5URP.js +11 -0
- package/dist/{chunk-DOCDDDTD.js → chunk-YNDPSWOE.js} +5 -5
- package/dist/chunk-Z5QW6USC.js +2 -0
- package/dist/{compliance-D7GD6ZYC.js → compliance-J3VOV445.js} +1 -1
- package/dist/config-schema-FLHRVZMI.js +2 -0
- package/dist/{context-audit-XRPT3OU2.js → context-audit-JVCA6GSV.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-YGHBIJY5.js → diff-75MABOSL.js} +1 -1
- package/dist/{dist-KGRCLBJP-2QAPFYNF.js → dist-GQ42YS5N-4HIJZVBB.js} +10 -10
- package/dist/{docs-USDAF26F.js → docs-TSAAS4W3.js} +1 -1
- package/dist/doctor-L5XZENCF.js +2 -0
- package/dist/{edit-GUU3HBVW.js → edit-P3MDAZLU.js} +1 -1
- package/dist/{flow-FVZR3YJ4.js → flow-BGXOVE2V.js} +1 -1
- package/dist/{hooks-TFMMMB2H.js → hooks-KUEE5KMM.js} +1 -1
- package/dist/index.js +6 -6
- package/dist/init-M44SO65G.js +2 -0
- package/dist/{init-XYB62Q3X.js → init-V4KSEKPK.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 +4 -4
- package/dist/metrics-UESGUHTA.js +2 -0
- package/dist/{migrate-Z5UQN57G.js → migrate-ZPNYDNM4.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/migration-notices-BHLEYC4T.js +4 -0
- package/dist/{nomination-engine-EALA5MGI.js → nomination-engine-NCLTGMAK.js} +1 -1
- package/dist/{notebook-loader-PXNRBBXD.js → notebook-loader-3J2OFMS3.js} +1 -1
- package/dist/{orchestrate-M5PBZBJQ.js → orchestrate-K4KBTBYK.js} +1 -1
- package/dist/{platform-server-DNAMH4YI.js → platform-server-ANOALDPL.js} +1 -1
- package/dist/{portal-check-ZMLVBIGW.js → portal-check-DV2VSJ5E.js} +1 -1
- package/dist/portal-compliance-JONQ4SOP.js +2 -0
- package/dist/{probe-3FTG6LYO.js → probe-5HAXULAD.js} +1 -1
- package/dist/{providers-AWA7WLLM.js → providers-TBPOE4DI.js} +1 -1
- package/dist/quiz-WYIZJG5K.js +10 -0
- package/dist/{record-YXPB34MY.js → record-N3VNYYKJ.js} +1 -1
- package/dist/registry-OUTA3DXW.js +20 -0
- package/dist/reindex-IZCD2JGD.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/{sentinel-HYAZ3CO5.js → sentinel-EFPEX246.js} +1 -1
- package/dist/{sentinel-bridge-VR357PKL.js → sentinel-bridge-UR2MKARY.js} +1 -1
- package/dist/{serve-U47GULB6.js → serve-3FMUWW5K.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-HHNY6J4I.js +2 -0
- package/dist/{session-work-log-ZP45TREI.js → session-work-log-MEJ33TYD.js} +1 -1
- package/dist/{session-work-log-PAKXOFGL.js → session-work-log-ZVVJGO7X.js} +1 -1
- package/dist/{setup-FEWSYS3Y.js → setup-ZSEC72BS.js} +1 -1
- package/dist/shift-WGMZGWOC.js +60 -0
- package/dist/{show-PJ5LFLIL.js → show-JH7LJ5MT.js} +1 -1
- package/dist/show-WVHAL4VU.js +7 -0
- package/dist/{spawn-M5BAV252.js → spawn-KKDDR6UR.js} +1 -1
- package/dist/status-S7Z5FVIE.js +6 -0
- package/dist/{summary-PYTEIJ4U.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-PDK64JXI.js → team-2LGZQRP4.js} +1 -1
- package/dist/{timeline-K3ZFKJ3R.js → timeline-RK7O2SCM.js} +1 -1
- package/dist/tools-4RRFTU5H.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-451-agent-routing.md +117 -0
- package/dist/university-content/notes/N-para-451-archetypes-vs-instances.md +82 -0
- package/dist/university-content/notes/N-para-451-identity-layers.md +76 -0
- package/dist/university-content/notes/N-para-451-orchestration-modes.md +85 -0
- package/dist/university-content/notes/N-para-451-paradigm-shift.md +95 -0
- package/dist/university-content/notes/N-para-451-partners-primitive.md +107 -0
- package/dist/university-content/notes/N-para-451-roster-management.md +132 -0
- package/dist/university-content/notes/N-para-451-roster-reference.md +106 -0
- package/dist/university-content/notes/N-para-451-the-team-pattern.md +87 -0
- package/dist/university-content/notes/N-para-451-tiers.md +81 -0
- package/dist/university-content/notes/N-para-451-welcome.md +55 -0
- package/dist/university-content/notes/N-para-451-what-is-an-agent.md +73 -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-451.yaml +69 -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-451-foundations.yaml +154 -0
- package/dist/university-content/quizzes/Q-para-451-when-to-invoke.yaml +182 -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-XUQZTF3H.js +9 -0
- package/dist/{watch-YCODNIET.js → watch-25GJHQYT.js} +1 -1
- 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 +2 -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/dist/add-P76GEMGF.js +0 -8
- package/dist/agent-X6I2YWOB.js +0 -33
- package/dist/chunk-JQKKVAAN.js +0 -2
- package/dist/chunk-NQ47TA6C.js +0 -111
- package/dist/chunk-ODVKPZZ4.js +0 -2
- package/dist/chunk-Q2J542ST.js +0 -2
- package/dist/chunk-RBLK34IA.js +0 -11
- package/dist/chunk-RN4VE6P3.js +0 -521
- package/dist/chunk-WS2N27RX.js +0 -3
- package/dist/config-schema-GUQY2QN7.js +0 -2
- package/dist/decision-loader-2XPZE4EZ.js +0 -2
- package/dist/doctor-WMVULMQD.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-compliance-6YR27IQU.js +0 -2
- package/dist/quiz-FE5UGAY2.js +0 -10
- package/dist/registry-KOOKFUWD.js +0 -20
- package/dist/reindex-I6LPAKCC.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/shift-PC6C7NUX.js +0 -60
- package/dist/show-BOAVWZPZ.js +0 -7
- package/dist/status-A37ECYNJ.js +0 -6
- package/dist/sync-DLUBV5HQ.js +0 -2
- package/dist/tools-5ITPEPSV.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/platform-ui/dist/assets/LoreSection-oO5dCe6O.js +0 -1
- /package/dist/{chunk-BV5PRPLB.js → chunk-HXGYVS2N.js} +0 -0
- /package/templates/paradigm/specs/{scan.md → probe.md} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {c,b}from'./chunk-5TAVYPOV.js';import*as e from'fs';import*as o from'path';var D={};c(D,{appendSessionWorkEntry:()=>C,appendVerdictEntry:()=>N,clearActivityMetrics:()=>j,clearSessionWorkLog:()=>I,countNotebookReferences:()=>w,getAgentEntries:()=>S,getAgentVerdicts:()=>P,getContributingAgents:()=>A,getNotebookReferences:()=>h,getSessionActivitySummary:()=>W,markVerdictsConsumed:()=>O,readPendingVerdicts:()=>M,readSessionWorkLog:()=>g,recordActivityMetric:()=>F,recordNotebookReference:()=>R});function C(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
|
|
3
3
|
`).filter(a=>a.trim()).length>=x)return;let f=JSON.stringify(n)+`
|
|
4
|
-
`;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-
|
|
4
|
+
`;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-W3RQJVW7.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let a=c(i,n.agent);if(a?.expertise){let u=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(u!==0){for(let v of n.symbols){let l=a.expertise.find(k=>k.symbol===v);l&&(l.confidence=Math.max(0,Math.min(1,l.confidence+u)),l.sessions=(l.sessions||0)+1,l.lastTouch=new Date().toISOString());}s(n.agent,a,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
5
5
|
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function I(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function N(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
|
|
6
6
|
`,"utf8");}catch{}}function M(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
7
7
|
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function O(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),c=e.readFileSync(t,"utf8").trim().split(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {h as h$1}from'./chunk-ZJQY5PPP.js';import*as y from'fs';import*as h from'path';import*as
|
|
2
|
+
import {h as h$1}from'./chunk-ZJQY5PPP.js';import*as y from'fs';import*as h from'path';import*as B from'js-yaml';import {execFileSync}from'child_process';function k(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;let a=new Array(e.length+1),r=new Array(e.length+1);for(let s=0;s<=e.length;s++)a[s]=s;for(let s=1;s<=t.length;s++){r[0]=s;for(let n=1;n<=e.length;n++){let c=t.charCodeAt(s-1)===e.charCodeAt(n-1)?0:1;r[n]=Math.min(r[n-1]+1,a[n]+1,a[n-1]+c);}let o=a;a=r,r=o;}return a[e.length]}function S(t,e){if(!t||e.length===0)return;let a;for(let r of e){if(r===t)continue;let s=k(t,r),o=Math.max(t.length,r.length);if(o===0)continue;let n=s/o;(s<=2||n<=.3)&&(!a||s<a.distance)&&(a={didYouMean:r,distance:s});}return a}function M(t,e){let a=[];for(let r of t){let s=S(r,e);s&&a.push({gate:r,didYouMean:s.didYouMean,distance:s.distance});}return a}function $(t,e){let a=[];for(let r of t){let s=S(r,e);s&&a.push({gate:r,didYouMean:s.didYouMean,distance:s.distance});}return a}var R=["node_modules",".git","dist","build","coverage",".paradigm","vendor","__pycache__",".next","target"];function w(t){let e=h.join(t,"portal.yaml");if(!y.existsSync(e))return {status:"missing"};let a;try{a=y.readFileSync(e,"utf-8");}catch{return {status:"unparseable",errorClass:"other",detail:"file read error"}}try{return {status:"ok",data:B.load(a)}}catch(r){let{errorClass:s,detail:o}=h$1(r);return {status:"unparseable",errorClass:s,detail:o}}}function Y(t){let e=new Set;if(t.gates)for(let a of Object.keys(t.gates)){let r=a.startsWith("^")?a.slice(1):a;e.add(r);}if(t.routes)for(let a of Object.values(t.routes)){let r=Array.isArray(a)?a:a.gates||[];for(let s of r){let o=s.startsWith("^")?s.slice(1):s;e.add(o);}}return Array.from(e)}function v(t){let e=new Set;if(t.routes)for(let a of Object.values(t.routes)){let r=Array.isArray(a)?a:a.gates||[];for(let s of r){let o=s.startsWith("^")?s.slice(1):s;e.add(o);}}return e}function N(t,e){let a={encoding:"utf-8",maxBuffer:10485760,stdio:["ignore","pipe","pipe"]};try{let n=["-n","--no-ignore-vcs",...R.flatMap(c=>["--glob",`!${c}/**`]),"--engine","auto",e,t];return execFileSync("rg",n,a)}catch{}let s=["-rn",...R.map(o=>`--exclude-dir=${o}`),"-E",e,"--",t];try{return execFileSync("grep",s,a)}catch(o){return o?.code===1||o?.status===1,""}}var D=["**/.purpose","**/portal.yaml","**/.paradigm/**/*.yaml","**/.paradigm/**/*.yml"];function _(t){let e=[];for(let s of D){h.join(t,s);let n;try{n=execFileSync("find",[t,"-path","*/node_modules","-prune","-o","-path","*/.git","-prune","-o","(","-name",".purpose","-o","-name","portal.yaml",")","-print"],{encoding:"utf-8",maxBuffer:5242880}).split(`
|
|
3
3
|
`).filter(Boolean);}catch{n=[];}for(let c of n)try{let u=y.readFileSync(c,"utf-8").split(`
|
|
4
4
|
`);for(let d=0;d<u.length;d++){let p=u[d],l=p.matchAll(/\^([a-z][a-z0-9-]+)/g);for(let m of l)e.push({gate:m[1],file:h.relative(t,c),line:d+1,context:p.trim().slice(0,100),matchType:"symbol"});}}catch{}}let r=[{pattern:`checkGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`requireGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`@Gate\\s*\\(['"]?([^'"\\)]+)['"]?\\)`,type:"function"}];for(let{pattern:s,type:o}of r){let n=N(t,s);for(let c of n.split(`
|
|
5
|
-
`).filter(Boolean)){let f=c.match(/^(.+?):(\d+):(.*)$/);if(f){let[,u,d,p]=f,l=p.match(new RegExp(s));if(l&&l[1]){let m=l[1].startsWith("^")?l[1].slice(1):l[1];e.push({gate:m,file:h.relative(t,u),line:parseInt(d,10),context:p.trim().slice(0,100),matchType:o});}}}}return e}function
|
|
6
|
-
`)}function
|
|
5
|
+
`).filter(Boolean)){let f=c.match(/^(.+?):(\d+):(.*)$/);if(f){let[,u,d,p]=f,l=p.match(new RegExp(s));if(l&&l[1]){let m=l[1].startsWith("^")?l[1].slice(1):l[1];e.push({gate:m,file:h.relative(t,u),line:parseInt(d,10),context:p.trim().slice(0,100),matchType:o});}}}}return e}function E(t){return [...new Set(t.map(e=>e.gate))]}async function L(t){let e=w(t);if(e.status==="unparseable"){let i=e.errorClass==="duplicate-key"?"duplicate mapping key detected":e.errorClass==="syntax"?"YAML syntax error":"YAML parse error";return {status:"violations",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:["__portal_unparseable__"],properlyDeclared:[],suggestions:[`portal.yaml unparseable: ${i} \u2014 run 'paradigm doctor' for details`],references:[],portalError:{kind:"unparseable",errorClass:e.errorClass,detail:e.detail}}}if(e.status==="missing"){let i=_(t),C=E(i);return C.length===0?{status:"compliant",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:[],properlyDeclared:[],suggestions:["No portal.yaml found, and no gate references detected in code."],references:[]}:{status:"violations",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:C,properlyDeclared:[],suggestions:["Gate references found in code but no portal.yaml exists.","Create a portal.yaml file to declare these gates:",...C.map(P=>` - ^${P}`),"","Run: paradigm portal init"],references:i}}let a=e.data,r=Y(a),s=v(a),o=_(t),n=E(o),c=new Set(r),f=new Set(n),u=r.filter(i=>!f.has(i)),d=u.filter(i=>s.has(i)),p=u.filter(i=>!s.has(i)),l=n.filter(i=>!c.has(i)),m=r.filter(i=>f.has(i)),g=[];if(d.length>0){g.push("Gates documented on routes but no checkGate/requireGate in code:");for(let i of d)g.push(` - ^${i} (documented on routes; if enforced by middleware, this may be intentional)`);g.push("");}if(p.length>0){g.push("Orphan gates (declared but never on a route or in code):");for(let i of p)g.push(` - ^${i} (add to a route or remove from portal.yaml)`);g.push("");}if(l.length>0){g.push("Gates used in code but not declared in portal.yaml:");for(let i of l)g.push(` - ^${i} (add to portal.yaml with proper definition)`);g.push("");}let A="compliant";l.length>0?A="violations":u.length>0&&(A="warnings");let U=[],x=l.filter(i=>i!=="__portal_unparseable__");return x.length>0&&U.push(...M(x,r)),u.length>0&&x.length>0&&U.push(...$(u,x)),{status:A,declaredButUnused:u,routeAttachedUnused:d,orphanUnused:p,usedButUndeclared:l,properlyDeclared:m,suggestions:g,references:o,...U.length>0?{nearMatches:U}:{}}}function I(t){let e=[],a=t.status==="compliant"?"\u2713":t.status==="warnings"?"\u26A0":"\u2717";if(e.push(`Portal Compliance: ${a} ${t.status.toUpperCase()}`),e.push(""),e.push(`Properly Declared: ${t.properlyDeclared.length}`),t.routeAttachedUnused.length>0&&e.push(`Route-Attached, No Code: ${t.routeAttachedUnused.length}`),t.orphanUnused.length>0&&e.push(`Orphan Gates: ${t.orphanUnused.length}`),t.usedButUndeclared.length>0&&e.push(`Used but Undeclared: ${t.usedButUndeclared.length}`),e.push(""),t.properlyDeclared.length>0){e.push("Gates in Use:");for(let n of t.properlyDeclared)e.push(` \u2713 ^${n}`);e.push("");}if(t.routeAttachedUnused.length>0){e.push("Route-Attached (no checkGate/requireGate in code):");for(let n of t.routeAttachedUnused)e.push(` \u26A0 ^${n}`);e.push("");}if(t.orphanUnused.length>0){e.push("Orphan Gates (declared but never on route or in code):");for(let n of t.orphanUnused)e.push(` \u26A0 ^${n}`);e.push("");}t.portalError&&(e.push("Portal Unparseable:"),e.push(` \u2717 ${t.portalError.detail} \u2014 run 'paradigm doctor' for details`),e.push(""));let r=t.usedButUndeclared.filter(n=>n!=="__portal_unparseable__"),s=new Map,o=new Map;if(t.nearMatches)for(let n of t.nearMatches)r.includes(n.gate)&&!s.has(n.gate)?s.set(n.gate,{didYouMean:n.didYouMean,distance:n.distance}):t.declaredButUnused.includes(n.gate)&&!o.has(n.gate)&&o.set(n.gate,{didYouMean:n.didYouMean,distance:n.distance});if(r.length>0){e.push("Undeclared Gates (used but not in portal.yaml):");for(let n of r){e.push(` \u2717 ^${n}`);let c=s.get(n);c&&e.push(` Did you mean: ^${c.didYouMean}? (declared in portal.yaml)`);let f=t.references.filter(u=>u.gate===n).slice(0,3);for(let u of f)e.push(` at ${u.file}:${u.line}`);}e.push("");}if(o.size>0){e.push("Possible Typos (declared gates may be misspelled references):");for(let[n,c]of o)e.push(` ? ^${n} \u2014 did you mean to reference as ^${c.didYouMean}?`);e.push("");}if(t.suggestions.length>0&&t.status!=="compliant"){e.push("Suggestions:");for(let n of t.suggestions)n&&e.push(` ${n}`);}return e.join(`
|
|
6
|
+
`)}function z(t){if(t.status==="compliant")return {status:"ok",message:`${t.properlyDeclared.length} gates properly declared`};if(t.status==="warnings"){let e=[];return t.routeAttachedUnused.length>0&&e.push(`${t.routeAttachedUnused.length} route-attached`),t.orphanUnused.length>0&&e.push(`${t.orphanUnused.length} orphan`),{status:"warn",message:e.length>0?e.join(", ")+" gate(s)":`${t.declaredButUnused.length} unused gates`}}return {status:"error",message:`${t.usedButUndeclared.length} gates used but not declared`}}export{w as a,Y as b,_ as c,L as d,I as e,z as f};
|
|
@@ -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};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as
|
|
2
|
+
import*as s from'fs';import*as c from'path';import*as a from'js-yaml';var A={architect:{tier:"high",description:"Complex planning needs best reasoning"},security:{tier:"high",description:"Deep security analysis"},reviewer:{tier:"medium",description:"Balanced critique"},builder:{tier:"low",description:"Fast implementation, lower cost"},tester:{tier:"low",description:"Quick validation"}},y={architect:{role:`You design system architecture, write specifications, and plan features.
|
|
3
3
|
You do NOT write implementation code - that's the Builder's job.
|
|
4
4
|
When your spec is ready, hand off to Builder with 'paradigm team handoff --to builder'.`,focus:{reads:["@features","$flows","specs/*.md","health.yaml"],writes:["specs/*.md",".purpose"]},triggers:[{type:"keyword",match:["design","architect","plan","spec"]},{type:"symbol",match:["@*","$*"]}],handoff_to:["builder","reviewer"],defaultModel:"opus",context:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml"],exclude:["src/**","tests/**","node_modules/**"]}},builder:{role:`You implement code based on specifications from the Architect.
|
|
5
5
|
Follow the spec exactly. If spec is unclear, hand back to Architect.
|
|
@@ -10,4 +10,4 @@ Hand back to Builder for fixes, or to Tester when approved.`,focus:{reads:["^gat
|
|
|
10
10
|
Run tests, check portal validations, verify health status.
|
|
11
11
|
Report issues back to Builder. Update health.yaml when verified.`,focus:{reads:["tests/**","portal.yaml","health.yaml","#components"],writes:["tests/**","health.yaml"]},triggers:[{type:"keyword",match:["test","verify","qa","validate"]},{type:"handoff",from:"reviewer"}],handoff_to:["builder","architect"],defaultModel:"haiku",context:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**"]}},security:{role:`You audit for security issues, especially around ^gates.
|
|
12
12
|
Review auth flows, check for vulnerabilities.
|
|
13
|
-
Flag issues but do NOT implement fixes - hand to Builder for that.`,focus:{reads:["^gates","!signals","portal.yaml","src/**"],writes:["security/*.md"]},triggers:[{type:"keyword",match:["security","audit","vulnerability","auth"]}],handoff_to:["builder","architect"],defaultModel:"opus",context:{include:["portal.yaml","src/middleware/**","src/auth/**"],exclude:["src/routes/**","tests/**","node_modules/**"]}}};function
|
|
13
|
+
Flag issues but do NOT implement fixes - hand to Builder for that.`,focus:{reads:["^gates","!signals","portal.yaml","src/**"],writes:["security/*.md"]},triggers:[{type:"keyword",match:["security","audit","vulnerability","auth"]}],handoff_to:["builder","architect"],defaultModel:"opus",context:{include:["portal.yaml","src/middleware/**","src/auth/**"],exclude:["src/routes/**","tests/**","node_modules/**"]}}};function d(e){return c.join(e,".paradigm")}function u(e){return c.join(d(e),"agents.yaml")}function x(e){return c.join(d(e),"team-state.yaml")}function g(e){return c.join(d(e),"handoffs")}function R(e){return s.existsSync(u(e))}function P(e){let t=u(e);if(!s.existsSync(t))return null;try{let n=s.readFileSync(t,"utf8");return a.load(n)}catch{return null}}function H(e,t){let n=u(e),r=d(e);s.existsSync(r)||s.mkdirSync(r,{recursive:true});let o={...t,agents:Object.fromEntries(Object.entries(t.agents).map(([f,b])=>{let{partners:l,...h}=b;return [f,l&&l.length>0?{...h,partners:l}:h]}))},i=a.dump(o,{lineWidth:-1,noRefs:true,quotingType:'"'});s.writeFileSync(n,i);}function p(e){let t=x(e);if(!s.existsSync(t))return {current:null,queue:[],recent:[],blocked:[]};try{let n=s.readFileSync(t,"utf8");return a.load(n)}catch{return {current:null,queue:[],recent:[],blocked:[]}}}function m(e,t){let n=x(e),r=d(e);s.existsSync(r)||s.mkdirSync(r,{recursive:true});let o=a.dump(t,{lineWidth:-1,noRefs:true,quotingType:'"'});s.writeFileSync(n,o);}function w(e,t){let n=c.join(g(e),`${t}.yaml`);if(!s.existsSync(n))return null;try{let r=s.readFileSync(n,"utf8");return a.load(r)}catch{return null}}function j(e,t){let n=g(e);s.existsSync(n)||s.mkdirSync(n,{recursive:true});let r=c.join(n,`${t.id}.yaml`),o=a.dump(t,{lineWidth:-1,noRefs:true,quotingType:'"'});s.writeFileSync(r,o);}function v(e){let t=g(e);if(!s.existsSync(t))return [];let n=s.readdirSync(t).filter(o=>o.endsWith(".yaml")),r=[];for(let o of n){let i=o.replace(".yaml",""),f=w(e,i);f&&r.push(f);}return r.sort((o,i)=>new Date(i.timestamp).getTime()-new Date(o.timestamp).getTime())}function C(e){return v(e).filter(t=>t.status==="pending")}function I(e="project",t){let n={};for(let[r,o]of Object.entries(y))if(n[r]={name:r,...o},t&&t[r]){let i=t[r].id.toLowerCase();i.includes("opus")||i.includes("gpt-4")&&!i.includes("mini")||i.includes("o1")&&!i.includes("mini")||i.includes("pro")&&!i.includes("mini")||i.includes("large")?n[r].defaultModel="opus":i.includes("haiku")||i.includes("mini")||i.includes("flash")||i.includes("small")?n[r].defaultModel="haiku":n[r].defaultModel="sonnet";}return {version:"1.0.0",team:{name:`${e}-team`,default_agent:"architect",require_handoff:false},agents:n}}function q(e,t){let n=p(e);n.recent.unshift({...t,timestamp:new Date().toISOString()}),n.recent=n.recent.slice(0,20),m(e,n);}function O(e,t,n){let r=p(e);r.current={agent:t,task:n,started:new Date().toISOString(),symbols_touched:[]},m(e,r);}function E(e){let t=p(e);t.current=null,m(e,t);}export{A as a,d as b,u as c,R as d,P as e,H as f,p as g,m as h,j as i,v as j,C as k,I as l,q as m,O as n,E as o};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {d,f,b,a as a$1,g,c,e as e$1,h}from'./chunk-
|
|
2
|
+
import {d,f,b,a as a$1,g,c,e as e$1,h}from'./chunk-YNDPSWOE.js';import {a}from'./chunk-LKAT7IAK.js';import*as S from'path';import e from'chalk';import M from'ora';async function q(b$1,a$2){let i=process.cwd(),r=M(),x=a$2.target||b$1,o=a$2.quiet;o||console.log(e.blue(`
|
|
3
3
|
\u{1F504} Paradigm Sync
|
|
4
4
|
`)),o||r.start("Loading .paradigm/ configuration...");let f$1=d(i);if(!f$1)throw o||(r.fail("No .paradigm/ directory found"),console.log(e.gray("\nRun `paradigm init` to initialize Paradigm in this project.\n"))),a.command("sync").error("Missing .paradigm/ directory"),o||process.exit(1),new Error("No .paradigm/ directory found");if(o||r.succeed(`Loaded configuration for ${e.cyan(f$1.projectName)}`),a.command("sync").debug("Configuration loaded",{projectName:f$1.projectName}),a$2.all){console.log(e.gray(`
|
|
5
5
|
Syncing to all IDEs...
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as t from'js-yaml';var n={"#":{name:"Component",description:"Any documented code unit",owner:"purpose",examples:["#Button","#api-client","#AuthProvider"]},$:{name:"Flow",description:"Multi-step processes or user journeys",owner:"shared",examples:["$checkout-flow","$auth-flow"]},"^":{name:"Gate",description:"Authorization checkpoints",owner:"portal",examples:["^authenticated","^admin-only","^resource-owner"]},"!":{name:"Signal",description:"Events for side effects",owner:"portal",examples:["!payment-completed","!login-failed","!rate-limited"]},"~":{name:"Aspect",description:"Rules with required code anchors",owner:"purpose",examples:["~audit-required","~rate-limited","~cache-invalidation"]}},i=["Use kebab-case for all symbol IDs (feature-name, not featureName)","Document flows when logic spans 3+ components","Reference related items using symbol prefixes (@ # $ % ~ ^ ! ?)","Add descriptions to all features and gates","Update .purpose files when changing feature behavior","Keep gates minimal - one responsibility per gate","Use signals for side effects, not direct state mutations"];function o(e){return {version:"1.0",project:e,"agent-guidelines":{overview:`${e} uses Paradigm for structured planning and context management.`,"how-to-use":["Check .purpose files in directories for context before making changes","Run `paradigm status` to see the project symbol index","Run `paradigm visualize` to explore the Dreamscape","Reference symbols using prefixes: @feature #component ^gate",'Attach an image and say "paradigm scan" to map UI to code'],"update-rules":["When adding a feature, create/update the nearest .purpose file","When adding authorization, update portal.yaml","When exploring ideas, add to .premise or use ?symbol prefix","Always update references when renaming symbols"]},"symbol-system":n,states:{user:{authenticated:{type:"boolean",default:false,description:"User is logged in"},role:{type:"enum",values:["guest","user","admin"],description:"User access level"}},app:{loading:{type:"boolean",default:false,description:"App is loading"}}},"purpose-required":[{pattern:"src/features/*",depth:1},{pattern:"src/components/*",depth:1}],conventions:i}}function r(e){return t.dump(e,{lineWidth:-1,quotingType:'"'})}function a(e){return t.load(e)}export{n as a,i as b,o as c,r as d,a as e};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-5TAVYPOV.js';import {execSync}from'child_process';import*as W from'os';import*as o from'fs';import*as d from'path';import*as f from'js-yaml';function R(s){let e=s.toLowerCase();return e.includes("claude")||e.includes("anthropic")?"anthropic":e.includes("gpt")||e.includes("openai")||e.includes("o1")||e.includes("o3")?"openai":e.includes("gemini")||e.includes("google")||e.includes("palm")?"google":e.includes("llama")||e.includes("meta")?"meta":e.includes("mistral")||e.includes("mixtral")?"mistral":e.includes("deepseek")?"deepseek":e.includes("cohere")||e.includes("command")?"cohere":"unknown"}function v(s){let e=s,t=e.author;if(e.type||(e.type="agent-session"),typeof t=="string")return s;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;n.type==="agent"?(e.author="unknown",e.agent={provider:n.model?R(n.model):R(n.id),model:n.model||n.id}):e.author=n.id||"unknown",delete e.assistedBy;}return e}function w(s){return s.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function P(){let s=process.env.PARADIGM_AUTHOR;if(s)return w(s);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return w(e)}catch{}try{let e=W.userInfo().username;if(e)return w(e)}catch{}return "unknown"}function $(s,e){let t=s;if(e.author&&(t=t.filter(n=>n.author===e.author)),e.hasAgent!==void 0?t=t.filter(n=>e.hasAgent?n.agent!=null:n.agent==null):e.authorType&&(t=t.filter(n=>e.authorType==="agent"?n.agent!=null:n.agent==null)),e.symbol&&(t=t.filter(n=>n.symbols_touched?.includes(e.symbol)||n.symbols_created?.includes(e.symbol))),e.dateFrom){let n=new Date(e.dateFrom).getTime();t=t.filter(i=>new Date(i.timestamp).getTime()>=n);}if(e.dateTo){let n=new Date(e.dateTo).getTime();t=t.filter(i=>new Date(i.timestamp).getTime()<=n);}if(e.type&&(t=t.filter(n=>n.type===e.type)),e.tag){let n=e.tag;t=t.filter(i=>i.tags?.some(r=>r===n||r.startsWith(n+":")||n.includes(":")&&r===n));}return e.tags&&e.tags.length>0&&(t=t.filter(n=>e.tags.some(i=>n.tags?.includes(i)))),e.hasBody!==void 0&&(t=t.filter(n=>e.hasBody?n.body!=null&&n.body.length>0:!n.body||n.body.length===0)),e.hasReview!==void 0&&(t=t.filter(n=>e.hasReview?n.review!=null:n.review==null)),e.hasConfidence!==void 0&&(t=t.filter(n=>e.hasConfidence?n.confidence!=null:n.confidence==null)),e.hasAssessment!==void 0&&(t=t.filter(n=>e.hasAssessment?n.assessment!=null:n.assessment==null)),e.minCompleteness!==void 0&&(t=t.filter(n=>n.review!=null&&n.review.completeness>=e.minCompleteness)),t.sort((n,i)=>new Date(i.timestamp).getTime()-new Date(n.timestamp).getTime()),e.offset&&(t=t.slice(e.offset)),e.limit&&(t=t.slice(0,e.limit)),t}var L=".paradigm/lore",_="entries",D="timeline.yaml";function x(s){return s.endsWith(".yaml")||s.endsWith(".lore")}function E(s,e,t){let n=d.join(s,L,_,e),i=d.join(n,`${t}.lore`);if(o.existsSync(i))return i;let r=d.join(n,`${t}.yaml`);return o.existsSync(r)?r:null}function O(s){try{let e=execSync("git rev-parse HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),t=execSync("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),n=execSync("git status --porcelain",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();return {ref:e,branch:t,dirty:n.length>0}}catch{return}}function N(s,e){let t={unregistered:[],warnings:[]};if(e.length===0)return t;let n=new Set;try{let c=a("child_process").execSync(`find "${s}" -name ".purpose" -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null || true`,{encoding:"utf-8"});for(let l of c.split(`
|
|
3
|
+
`).filter(Boolean))try{let m=o.readFileSync(l,"utf8").matchAll(/^([#$^!~][\w-]+):/gm);for(let u of m)n.add(u[1]);}catch{}}catch{return t}let i=d.join(s,".paradigm","flows.yaml");if(o.existsSync(i))try{let l=o.readFileSync(i,"utf8").matchAll(/([#$^!~][\w-]+)/g);for(let a of l)n.add(a[1]);}catch{}let r=d.join(s,"portal.yaml");if(o.existsSync(r))try{let l=o.readFileSync(r,"utf8").matchAll(/\^([\w-]+)/g);for(let a of l)n.add(`^${a[1]}`);}catch{}for(let c of e)n.has(c)||(t.unregistered.push(c),t.warnings.push(`Symbol "${c}" not found in .purpose files or project index`));return t}async function H(s,e,t){if(e.type==="decision")throw new Error("lore type 'decision' was removed in v6.0. Use `paradigm decision record` (CLI) or `paradigm_decision_record` (MCP) instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry will be written automatically.");let n;if(t?.validateSymbols){let a=[...e.symbols_touched||[],...e.symbols_created||[]];n=N(s,a);}let i=d.join(s,L),r=e.timestamp.slice(0,10),c=d.join(i,_,r);o.existsSync(c)||o.mkdirSync(c,{recursive:true}),e.author||(e.author=P()),e.git_context||(e.git_context=O(s)),e.id||(e.id=B(s,r,e.author,e.timestamp));let l=d.join(c,`${e.id}.lore`);return o.writeFileSync(l,f.dump(e,{lineWidth:-1,noRefs:true})),await j(s),{validation:n}}async function A(s,e){let t=d.join(s,L,_);if(!o.existsSync(t))return [];z(s);let n=[],i=o.readdirSync(t).filter(r=>/^\d{4}-\d{2}-\d{2}$/.test(r)).sort().reverse();for(let r of i){if(e?.dateFrom&&r<e.dateFrom.slice(0,10)||e?.dateTo&&r>e.dateTo.slice(0,10))continue;let c=d.join(t,r),l=o.readdirSync(c).filter(x).sort();for(let a of l)try{let m=o.readFileSync(d.join(c,a),"utf8"),u=f.load(m);n.push(v(u));}catch{}}return e?$(n,e):n}async function j(s){let e=d.join(s,L),t=d.join(e,_);if(!o.existsSync(t))return;z(s);let n=new Set,i=0,r="",c=o.readdirSync(t).filter(u=>/^\d{4}-\d{2}-\d{2}$/.test(u));for(let u of c){let g=d.join(t,u),h=o.readdirSync(g).filter(x);for(let S of h)try{let y=o.readFileSync(d.join(g,S),"utf8"),p=f.load(y),b=v(p);n.add(b.author),i++,(!r||b.timestamp>r)&&(r=b.timestamp);}catch{}}let l="unknown",a=d.join(s,".paradigm","config.yaml");if(o.existsSync(a))try{let u=f.load(o.readFileSync(a,"utf8"));l=u.project||u.name||"unknown";}catch{}let m={version:"1.0",project:l,entries:i,last_updated:r||new Date().toISOString(),authors:Array.from(n)};o.existsSync(e)||o.mkdirSync(e,{recursive:true}),o.writeFileSync(d.join(e,D),f.dump(m,{lineWidth:-1,noRefs:true}));}async function G(s,e,t){let i=(await A(s)).find(l=>l.id===e);if(!i)return false;let r=i.timestamp.slice(0,10),c=E(s,r,e);return c?(i.review=t,o.writeFileSync(c,f.dump(i,{lineWidth:-1,noRefs:true})),true):false}function q(s){switch(s){case "correct":return 1;case "partial":return .5;case "incorrect":return 0}}async function K(s,e,t){let i=(await A(s)).find(l=>l.id===e);if(!i)return false;let r=i.timestamp.slice(0,10),c=E(s,r,e);return c?(i.assessment=t,i.confidence!=null&&(i.assessment_delta=q(t.verdict)-i.confidence),o.writeFileSync(c,f.dump(i,{lineWidth:-1,noRefs:true})),true):false}async function C(s,e){let t=e.match(/^L-(\d{4}-\d{2}-\d{2})-/);if(t){let i=t[1],r=E(s,i,e);if(r)try{let c=o.readFileSync(r,"utf8"),l=f.load(c);return v(l)}catch{return null}}return (await A(s)).find(i=>i.id===e)||null}async function Z(s,e,t){let n=await C(s,e);if(!n)return false;let i=n.timestamp.slice(0,10),r=E(s,i,e);return r?(t.title!==void 0&&(n.title=t.title),t.summary!==void 0&&(n.summary=t.summary),t.type!==void 0&&(n.type=t.type),t.duration_minutes!==void 0&&(n.duration_minutes=t.duration_minutes),t.symbols_touched!==void 0&&(n.symbols_touched=t.symbols_touched),t.symbols_created!==void 0&&(n.symbols_created=t.symbols_created),t.files_created!==void 0&&(n.files_created=t.files_created),t.files_modified!==void 0&&(n.files_modified=t.files_modified),t.lines_added!==void 0&&(n.lines_added=t.lines_added),t.lines_removed!==void 0&&(n.lines_removed=t.lines_removed),t.commit!==void 0&&(n.commit=t.commit),t.decisions!==void 0&&(n.decisions=t.decisions),t.errors_encountered!==void 0&&(n.errors_encountered=t.errors_encountered),t.learnings!==void 0&&(n.learnings=t.learnings),t.verification!==void 0&&(n.verification=t.verification),t.tags!==void 0&&(n.tags=t.tags),t.body!==void 0&&(n.body=t.body),t.linked_lore!==void 0&&(n.linked_lore=t.linked_lore),t.linked_tasks!==void 0&&(n.linked_tasks=t.linked_tasks),t.linked_commits!==void 0&&(n.linked_commits=t.linked_commits),t.confidence!==void 0&&(n.confidence=t.confidence),t.assessment!==void 0&&(n.assessment=t.assessment),t.assessment_delta!==void 0&&(n.assessment_delta=t.assessment_delta),o.writeFileSync(r,f.dump(n,{lineWidth:-1,noRefs:true})),await j(s),true):false}async function J(s,e){let t=await C(s,e);if(!t)return false;let n=t.timestamp.slice(0,10),i=E(s,n,e);if(!i)return false;o.unlinkSync(i);let r=d.dirname(i);return o.readdirSync(r).filter(x).length===0&&o.rmdirSync(r),await j(s),true}function z(s){let e=d.join(s,L,_);if(!o.existsSync(e))return 0;let t=o.readdirSync(e).filter(i=>x(i)&&!i.startsWith(".")),n=0;for(let i of t){let r=d.join(e,i);if(o.statSync(r).isFile())try{let l=o.readFileSync(r,"utf8"),a=f.load(l);if(a.author&&typeof a.author=="object"||typeof a.author=="string"&&a.timestamp)continue;let m=typeof a.date=="string"?a.date.slice(0,10):new Date().toISOString().slice(0,10),u=d.join(e,m);o.existsSync(u)||o.mkdirSync(u,{recursive:!0});let g=P(),h=`${m}T00:00:00.000Z`,S=B(s,m,g,h),y=String(a.type||"agent-session"),p=y==="decision",b=p?"insight":["agent-session","human-note","review","incident","milestone","insight"].includes(y)?y:"agent-session",T;if(a.test_results&&typeof a.test_results=="object"){let k=a.test_results;T={status:k.total===k.passed?"pass":"partial",details:{tests:k.total===k.passed?"pass":"fail"}};}let M=["migrated",y];p&&M.push("v6-migrated:from-decision");let I={id:S,type:b,timestamp:h,author:"unknown",agent:{provider:"unknown",model:"unknown"},title:String(a.title||i.replace(/\.(yaml|lore)$/,"")),summary:String(a.summary||""),symbols_touched:Array.isArray(a.symbols_touched)?a.symbols_touched:[],files_modified:Array.isArray(a.files_modified)?a.files_modified:void 0,...T?{verification:T}:{},tags:M};o.writeFileSync(d.join(u,`${S}.lore`),f.dump(I,{lineWidth:-1,noRefs:!0})),o.unlinkSync(r),n++;}catch{}}return n}function B(s,e,t,n){let i=w(t),r=new Date(n),c=String(r.getUTCHours()).padStart(2,"0"),l=String(r.getUTCMinutes()).padStart(2,"0"),a=String(r.getUTCSeconds()).padStart(2,"0"),m=`${c}${l}${a}`,u=`L-${e}-${i}-${m}`,g=d.join(s,L,_,e);if(!o.existsSync(g))return `${u}-001`;let h=o.readdirSync(g).filter(y=>y.startsWith(u)&&x(y)).map(y=>{let p=y.match(/-(\d{3})\.(yaml|lore)$/);return p?parseInt(p[1],10):0}),S=h.length>0?Math.max(...h)+1:1;return `${u}-${String(S).padStart(3,"0")}`}export{v as a,P as b,H as c,A as d,G as e,K as f,C as g,Z as h,J as i};
|
|
@@ -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-6QXBXZF6.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-NCLTGMAK.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};
|