@draht/coding-agent 2026.5.12 → 2026.6.11
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/CHANGELOG.md +26 -0
- package/bin/draht-tools.cjs +3756 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +4 -2
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/restore-sandbox-env.d.ts +13 -0
- package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
- package/dist/bun/restore-sandbox-env.js +32 -0
- package/dist/bun/restore-sandbox-env.js.map +1 -0
- package/dist/cli/args.d.ts +9 -4
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +88 -35
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/config-selector.d.ts +2 -2
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +1 -1
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +2 -3
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/initial-message.d.ts +1 -1
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/initial-message.js.map +1 -1
- package/dist/cli/list-models.d.ts +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +7 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/project-trust.d.ts +10 -0
- package/dist/cli/project-trust.d.ts.map +1 -0
- package/dist/cli/project-trust.js +48 -0
- package/dist/cli/project-trust.js.map +1 -0
- package/dist/cli/session-picker.d.ts +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli/startup-ui.d.ts +16 -0
- package/dist/cli/startup-ui.d.ts.map +1 -0
- package/dist/cli/startup-ui.js +112 -0
- package/dist/cli/startup-ui.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +7 -4
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +23 -13
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +264 -62
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +45 -9
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +100 -33
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +6 -4
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +7 -4
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +47 -31
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +470 -443
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts +5 -0
- package/dist/core/auth-guidance.d.ts.map +1 -0
- package/dist/core/auth-guidance.js +21 -0
- package/dist/core/auth-guidance.js.map +1 -0
- package/dist/core/auth-storage.d.ts +10 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +27 -6
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts +1 -15
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +10 -24
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +1 -2
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +6 -4
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +9 -3
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +5 -5
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +43 -37
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/index.d.ts +3 -3
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +1 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js.map +1 -1
- package/dist/core/experimental.d.ts +2 -0
- package/dist/core/experimental.d.ts.map +1 -0
- package/dist/core/experimental.js +4 -0
- package/dist/core/experimental.js.map +1 -0
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +1 -1
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/index.d.ts +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +13 -11
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template.css +69 -4
- package/dist/core/export-html/template.js +231 -57
- package/dist/core/export-html/tool-renderer.d.ts +0 -6
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +15 -2
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +8 -8
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +3 -3
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +27 -35
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +30 -12
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +215 -32
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +163 -35
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +2 -2
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +7 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +78 -54
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +21 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -0
- package/dist/core/http-dispatcher.js +48 -0
- package/dist/core/http-dispatcher.js.map +1 -0
- package/dist/core/index.d.ts +9 -8
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/keybindings.d.ts +66 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +56 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-registry.d.ts +22 -4
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +216 -44
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +2 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +48 -21
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/output-guard.d.ts +1 -0
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +52 -22
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager.d.ts +17 -2
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +363 -121
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/project-trust.d.ts +15 -0
- package/dist/core/project-trust.d.ts.map +1 -0
- package/dist/core/project-trust.js +58 -0
- package/dist/core/project-trust.js.map +1 -0
- package/dist/core/prompt-templates.d.ts +13 -11
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +67 -76
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-attribution.d.ts +4 -0
- package/dist/core/provider-attribution.d.ts.map +1 -0
- package/dist/core/provider-attribution.js +72 -0
- package/dist/core/provider-attribution.js.map +1 -0
- package/dist/core/provider-display-names.d.ts +2 -0
- package/dist/core/provider-display-names.d.ts.map +1 -0
- package/dist/core/provider-display-names.js +36 -0
- package/dist/core/provider-display-names.js.map +1 -0
- package/dist/core/resolve-config-value.d.ts +9 -1
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js +134 -11
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/resource-loader.d.ts +34 -14
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +165 -76
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +26 -10
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +45 -16
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +11 -12
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +245 -132
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +52 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +202 -38
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +10 -10
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +13 -35
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +7 -4
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +1 -1
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts +4 -4
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +14 -10
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/telemetry.d.ts +3 -0
- package/dist/core/telemetry.d.ts.map +1 -0
- package/dist/core/telemetry.js +9 -0
- package/dist/core/telemetry.js.map +1 -0
- package/dist/core/tools/bash.d.ts +11 -16
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +162 -177
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +3 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +11 -3
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +22 -24
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +199 -111
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js +27 -12
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/find.d.ts +7 -18
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +134 -95
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +11 -30
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +23 -12
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +26 -101
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +78 -52
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +6 -15
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +12 -17
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +52 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -0
- package/dist/core/tools/output-accumulator.js +184 -0
- package/dist/core/tools/output-accumulator.js.map +1 -0
- package/dist/core/tools/path-utils.d.ts +2 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +40 -22
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/read.d.ts +7 -18
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +100 -36
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +5 -2
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +18 -2
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +12 -2
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts +5 -14
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +27 -46
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts +31 -0
- package/dist/core/trust-manager.d.ts.map +1 -0
- package/dist/core/trust-manager.js +187 -0
- package/dist/core/trust-manager.js.map +1 -0
- package/dist/index.d.ts +31 -29
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -8
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +5 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +170 -87
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +2 -2
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +127 -5
- package/dist/migrations.js.map +1 -1
- package/dist/modes/index.d.ts +5 -5
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +14 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +3 -3
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +3 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts +4 -4
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +38 -11
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.d.ts +2 -2
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.js +2 -2
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts +2 -2
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +14 -6
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +8 -3
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
- package/dist/modes/interactive/components/first-time-setup.js +103 -0
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts +2 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +23 -7
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +33 -31
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +2 -0
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +5 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +19 -5
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +12 -2
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +46 -11
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +2 -2
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +8 -5
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +18 -6
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +93 -25
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +5 -12
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +45 -30
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +2 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +20 -7
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +13 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +113 -4
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +1 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +57 -14
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +18 -9
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/trust-selector.js +91 -0
- package/dist/modes/interactive/components/trust-selector.js.map +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts +2 -2
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +8 -7
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +1 -0
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +8 -7
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +68 -13
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1100 -319
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +5 -4
- package/dist/modes/interactive/theme/light.json +5 -4
- package/dist/modes/interactive/theme/theme.d.ts +22 -3
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +160 -105
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +40 -20
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +11 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +73 -8
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +2 -2
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +96 -30
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +16 -4
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts +6 -2
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +396 -21
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/prompts/commands/map-codebase.md +14 -0
- package/dist/utils/ansi.d.ts +2 -0
- package/dist/utils/ansi.d.ts.map +1 -0
- package/dist/utils/ansi.js +52 -0
- package/dist/utils/ansi.js.map +1 -0
- package/dist/utils/changelog.d.ts +2 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +78 -0
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/child-process.d.ts +5 -1
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +10 -0
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -2
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard-native.d.ts +3 -1
- package/dist/utils/clipboard-native.d.ts.map +1 -1
- package/dist/utils/clipboard-native.js +14 -8
- package/dist/utils/clipboard-native.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +84 -45
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/deprecation.d.ts +4 -0
- package/dist/utils/deprecation.d.ts.map +1 -0
- package/dist/utils/deprecation.js +13 -0
- package/dist/utils/deprecation.js.map +1 -0
- package/dist/utils/exif-orientation.d.ts +1 -1
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/exif-orientation.js.map +1 -1
- package/dist/utils/fs-watch.d.ts +5 -0
- package/dist/utils/fs-watch.d.ts.map +1 -0
- package/dist/utils/fs-watch.js +25 -0
- package/dist/utils/fs-watch.js.map +1 -0
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js +54 -22
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/html.d.ts +7 -0
- package/dist/utils/html.d.ts.map +1 -0
- package/dist/utils/html.js +40 -0
- package/dist/utils/html.js.map +1 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts +30 -0
- package/dist/utils/image-resize-core.d.ts.map +1 -0
- package/dist/utils/image-resize-core.js +124 -0
- package/dist/utils/image-resize-core.js.map +1 -0
- package/dist/utils/image-resize-worker.d.ts +2 -0
- package/dist/utils/image-resize-worker.d.ts.map +1 -0
- package/dist/utils/image-resize-worker.js +31 -0
- package/dist/utils/image-resize-worker.js.map +1 -0
- package/dist/utils/image-resize.d.ts +7 -27
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +75 -115
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/json.d.ts +3 -0
- package/dist/utils/json.d.ts.map +1 -0
- package/dist/utils/json.js +7 -0
- package/dist/utils/json.js.map +1 -0
- package/dist/utils/mime.d.ts +1 -0
- package/dist/utils/mime.d.ts.map +1 -1
- package/dist/utils/mime.js +59 -16
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/open-browser.d.ts +9 -0
- package/dist/utils/open-browser.d.ts.map +1 -0
- package/dist/utils/open-browser.js +22 -0
- package/dist/utils/open-browser.js.map +1 -0
- package/dist/utils/paths.d.ts +25 -1
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +75 -2
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/pi-user-agent.d.ts +2 -0
- package/dist/utils/pi-user-agent.d.ts.map +1 -0
- package/dist/utils/pi-user-agent.js +5 -0
- package/dist/utils/pi-user-agent.js.map +1 -0
- package/dist/utils/shell.d.ts +10 -6
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +35 -26
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +12 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -0
- package/dist/utils/syntax-highlight.js +118 -0
- package/dist/utils/syntax-highlight.js.map +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +86 -10
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +15 -0
- package/dist/utils/version-check.d.ts.map +1 -0
- package/dist/utils/version-check.js +82 -0
- package/dist/utils/version-check.js.map +1 -0
- package/dist/utils/windows-self-update.d.ts +3 -0
- package/dist/utils/windows-self-update.d.ts.map +1 -0
- package/dist/utils/windows-self-update.js +77 -0
- package/dist/utils/windows-self-update.js.map +1 -0
- package/docs/compaction.md +12 -12
- package/docs/containerization.md +111 -0
- package/docs/custom-provider.md +187 -47
- package/docs/development.md +5 -5
- package/docs/docs.json +156 -0
- package/docs/extensions.md +465 -71
- package/docs/index.md +82 -0
- package/docs/json.md +4 -4
- package/docs/keybindings.md +23 -1
- package/docs/models.md +119 -17
- package/docs/packages.md +17 -9
- package/docs/prompt-templates.md +30 -2
- package/docs/providers.md +83 -22
- package/docs/quickstart.md +165 -0
- package/docs/rpc.md +41 -10
- package/docs/sdk.md +68 -50
- package/docs/security.md +55 -0
- package/docs/{session.md → session-format.md} +11 -11
- package/docs/sessions.md +145 -0
- package/docs/settings.md +61 -11
- package/docs/skills.md +16 -17
- package/docs/terminal-setup.md +44 -2
- package/docs/termux.md +4 -4
- package/docs/themes.md +3 -3
- package/docs/tmux.md +4 -2
- package/docs/tui.md +44 -4
- package/docs/usage.md +305 -0
- package/examples/extensions/border-status-editor.ts +145 -0
- package/examples/extensions/built-in-tool-renderer.ts +3 -0
- package/examples/extensions/custom-header.ts +1 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +55 -4
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
- package/examples/extensions/doom-overlay/doom-component.ts +2 -2
- package/examples/extensions/doom-overlay/index.ts +1 -1
- package/examples/extensions/dynamic-resources/dynamic.json +1 -1
- package/examples/extensions/dynamic-tools.ts +2 -2
- package/examples/extensions/git-merge-and-resolve.ts +115 -0
- package/examples/extensions/github-issue-autocomplete.ts +185 -0
- package/examples/extensions/gondolin/index.ts +531 -0
- package/examples/extensions/gondolin/package-lock.json +185 -0
- package/examples/extensions/gondolin/package.json +19 -0
- package/examples/extensions/handoff.ts +50 -12
- package/examples/extensions/input-transform-streaming.ts +39 -0
- package/examples/extensions/interactive-shell.ts +1 -1
- package/examples/extensions/notify.ts +2 -9
- package/examples/extensions/overlay-qa-tests.ts +240 -138
- package/examples/extensions/overlay-test.ts +7 -4
- package/examples/extensions/plan-mode/utils.ts +1 -1
- package/examples/extensions/preset.ts +36 -3
- package/examples/extensions/project-trust.ts +64 -0
- package/examples/extensions/prompt-customizer.ts +97 -0
- package/examples/extensions/provider-payload.ts +4 -0
- package/examples/extensions/qna.ts +1 -1
- package/examples/extensions/question.ts +2 -2
- package/examples/extensions/questionnaire.ts +2 -2
- package/examples/extensions/reload-runtime.ts +1 -1
- package/examples/extensions/sandbox/index.ts +4 -4
- package/examples/extensions/sandbox/package-lock.json +5 -5
- package/examples/extensions/sandbox/package.json +2 -2
- package/examples/extensions/shutdown-command.ts +1 -1
- package/examples/extensions/snake.ts +1 -1
- package/examples/extensions/space-invaders.ts +1 -1
- package/examples/extensions/structured-output.ts +65 -0
- package/examples/extensions/subagent/index.ts +51 -28
- package/examples/extensions/summarize.ts +1 -1
- package/examples/extensions/tic-tac-toe.ts +1008 -0
- package/examples/extensions/titlebar-spinner.ts +2 -2
- package/examples/extensions/todo.ts +2 -2
- package/examples/extensions/tool-override.ts +1 -1
- package/examples/extensions/tools.ts +5 -0
- package/examples/extensions/truncated-tool.ts +1 -1
- package/examples/extensions/with-deps/index.ts +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +3 -3
- package/examples/extensions/working-indicator.ts +123 -0
- package/examples/extensions/working-message-test.ts +25 -0
- package/examples/sdk/01-minimal.ts +14 -10
- package/examples/sdk/02-custom-model.ts +12 -8
- package/examples/sdk/03-custom-prompt.ts +32 -17
- package/examples/sdk/04-skills.ts +5 -2
- package/examples/sdk/05-tools.ts +23 -31
- package/examples/sdk/06-extensions.ts +14 -8
- package/examples/sdk/07-context-files.ts +5 -3
- package/examples/sdk/08-prompt-templates.ts +5 -2
- package/examples/sdk/09-api-keys-and-oauth.ts +8 -4
- package/examples/sdk/10-settings.ts +8 -6
- package/examples/sdk/11-sessions.ts +4 -0
- package/examples/sdk/12-full-control.ts +13 -17
- package/package.json +13 -6
- package/prompts/commands/map-codebase.md +14 -0
package/bin/draht-tools.cjs
CHANGED
|
@@ -238,7 +238,20 @@ commands["map-codebase"] = function (dir) {
|
|
|
238
238
|
|
|
239
239
|
writeMd(path.join(outDir, "DOMAIN-HINTS.md"), `# Domain Model Hints\n\nGenerated: ${timestamp()}\n\nExtracted from codebase to help identify domain model.\n\n${domainHints}\n## TODO\n- [ ] Identify entities vs value objects\n- [ ] Map bounded contexts from directory structure\n- [ ] Define ubiquitous language glossary\n`);
|
|
240
240
|
|
|
241
|
+
// Build the living knowledge graph (MAP.json + MAP.html + GRAPH_REPORT.md) alongside the docs,
|
|
242
|
+
// so `map-codebase` is a single command that produces both the prose docs and the graphify map.
|
|
243
|
+
let kg = null;
|
|
244
|
+
try {
|
|
245
|
+
kg = visWriteOutputs(cwd);
|
|
246
|
+
} catch (err) {
|
|
247
|
+
console.error(`\n⚠️ Knowledge graph build failed (run \`draht-tools map-graph\` to retry): ${err.message}`);
|
|
248
|
+
}
|
|
249
|
+
|
|
241
250
|
console.log(`\nCreated:\n ${outDir}/STACK.md\n ${outDir}/ARCHITECTURE.md\n ${outDir}/CONVENTIONS.md\n ${outDir}/CONCERNS.md\n ${outDir}/DOMAIN-HINTS.md`);
|
|
251
|
+
if (kg) {
|
|
252
|
+
console.log(` ${path.relative(cwd, kg.jsonPath)}\n ${path.relative(cwd, kg.htmlPath)}\n ${path.relative(cwd, kg.reportPath)}`);
|
|
253
|
+
console.log(`\nIndexed ${kg.map.stats.files} modules · ${kg.map.clusters.length} clusters · view it live: draht-tools map-serve`);
|
|
254
|
+
}
|
|
242
255
|
console.log("\n→ Review and fill in the TODOs, then run: draht-tools commit-docs \"map existing codebase\"");
|
|
243
256
|
};
|
|
244
257
|
|
|
@@ -1047,6 +1060,3731 @@ commands["research-phase"] = async function (n) {
|
|
|
1047
1060
|
if (!stdinContent) console.log("→ Fill in research findings, then plan the phase.");
|
|
1048
1061
|
};
|
|
1049
1062
|
|
|
1063
|
+
// ============================================================================
|
|
1064
|
+
// Codebase visualization — MAP.json + MAP.html (living map for humans + agents)
|
|
1065
|
+
// ============================================================================
|
|
1066
|
+
|
|
1067
|
+
const VIS_DEFAULT_IGNORES = new Set([
|
|
1068
|
+
"node_modules", ".git", "dist", "build", "out", "target", ".next",
|
|
1069
|
+
".turbo", ".cache", "coverage", ".nyc_output", ".planning",
|
|
1070
|
+
".venv", "venv", "__pycache__", ".pytest_cache", ".idea", ".vscode",
|
|
1071
|
+
".DS_Store", ".sst", ".astro", ".svelte-kit", "vendor", "tmp", ".tmp",
|
|
1072
|
+
]);
|
|
1073
|
+
|
|
1074
|
+
const VIS_CODE_LANGS = new Set([
|
|
1075
|
+
"typescript", "javascript", "python", "go", "rust", "java",
|
|
1076
|
+
"kotlin", "swift", "ruby", "php", "csharp", "c", "cpp", "shell",
|
|
1077
|
+
]);
|
|
1078
|
+
|
|
1079
|
+
const LAYER_ORDER_INTERNAL = ["presentation", "application", "domain", "infrastructure", "support"];
|
|
1080
|
+
const LAYER_COLORS_INTERNAL = {
|
|
1081
|
+
presentation: "#79c0ff", application: "#7ee787", domain: "#d2a8ff",
|
|
1082
|
+
infrastructure: "#f0883e", support: "#8b949e",
|
|
1083
|
+
};
|
|
1084
|
+
|
|
1085
|
+
// Functional groups — CodeViz-style "containers" that nest workspace packages by purpose.
|
|
1086
|
+
// Maps from explicit package name → group id. Anything not listed falls through to FALLBACK_GROUP_RULES.
|
|
1087
|
+
const DEFAULT_GROUPS = [
|
|
1088
|
+
{ id: "group:frontend", name: "Frontend", color: "#79c0ff",
|
|
1089
|
+
description: "User-facing web surfaces",
|
|
1090
|
+
members: ["@draht/web-ui", "@draht/landing"] },
|
|
1091
|
+
{ id: "group:cli-runtime", name: "CLI & Runtime", color: "#ffdf5d",
|
|
1092
|
+
description: "Command-line tools and runtime gateways",
|
|
1093
|
+
members: ["draht-claude", "@draht/coding-agent", "@draht/tools", "@draht/tui", "@draht/gateway"] },
|
|
1094
|
+
{ id: "group:core", name: "Core", color: "#d2a8ff",
|
|
1095
|
+
description: "Cross-cutting libraries used everywhere",
|
|
1096
|
+
members: ["@draht/ai", "@draht/agent-core", "@draht/router"] },
|
|
1097
|
+
{ id: "group:domain-services", name: "Domain Services", color: "#7ee787",
|
|
1098
|
+
description: "Business logic and domain capabilities",
|
|
1099
|
+
members: ["@draht/mom", "@draht/knowledge", "@draht/orchestrator", "@draht/invoice", "@draht/compliance"] },
|
|
1100
|
+
{ id: "group:workflows-infra", name: "Workflows & Infra", color: "#f0883e",
|
|
1101
|
+
description: "Build pipelines, deployment, templates, ops",
|
|
1102
|
+
members: ["@draht/ci", "@draht/deploy-guardian", "@draht/pods", "@draht/workflows", "@draht/infra", "@draht/templates"] },
|
|
1103
|
+
{ id: "group:root", name: "Repo Root", color: "#8b949e",
|
|
1104
|
+
description: "Monorepo root package",
|
|
1105
|
+
members: ["draht-monorepo"] },
|
|
1106
|
+
];
|
|
1107
|
+
// Fallback by name pattern (evaluated in order)
|
|
1108
|
+
const FALLBACK_GROUP_RULES = [
|
|
1109
|
+
{ id: "group:frontend", re: /^(web-ui|landing|ui|frontend|client|app|admin)$/ },
|
|
1110
|
+
{ id: "group:cli-runtime", re: /^(cli|tui|gateway|coding|claude|tools|bin)|(?:^|-)extension(?:-|$)|^pi-/ },
|
|
1111
|
+
{ id: "group:core", re: /^(ai|agent|router|llm|core|sdk|kernel)/ },
|
|
1112
|
+
{ id: "group:domain-services", re: /^(mom|knowledge|orchestrator|invoice|compliance|chat|search|memory)/ },
|
|
1113
|
+
{ id: "group:workflows-infra", re: /^(ci|deploy|pods|workflow|infra|template|guardian|ops)/ },
|
|
1114
|
+
];
|
|
1115
|
+
|
|
1116
|
+
// Path-based fallback (when name doesn't match) — useful for example/extension dirs
|
|
1117
|
+
const PATH_GROUP_RULES = [
|
|
1118
|
+
{ id: "group:cli-runtime", re: /(?:^|\/)(examples?|extensions?|samples?)\// },
|
|
1119
|
+
{ id: "group:frontend", re: /(?:^|\/)(apps?|web|frontend|client)\// },
|
|
1120
|
+
{ id: "group:workflows-infra", re: /(?:^|\/)(scripts?|tools?|infra|deploy|ops)\// },
|
|
1121
|
+
];
|
|
1122
|
+
|
|
1123
|
+
function deriveGroups(containers, pkgs, root) {
|
|
1124
|
+
const groups = DEFAULT_GROUPS.map((g) => Object.assign({}, g, { members: [], source: "auto", moduleCount: 0 }));
|
|
1125
|
+
const otherGroup = { id: "group:other", name: "Other", color: "#8b949e",
|
|
1126
|
+
description: "Packages not yet classified", members: [], source: "auto", moduleCount: 0 };
|
|
1127
|
+
|
|
1128
|
+
const findGroup = (containerName, pkg) => {
|
|
1129
|
+
// Exact name match against DEFAULT_GROUPS
|
|
1130
|
+
for (let i = 0; i < DEFAULT_GROUPS.length; i++) {
|
|
1131
|
+
if (DEFAULT_GROUPS[i].members.includes(containerName)) return groups[i];
|
|
1132
|
+
}
|
|
1133
|
+
// Fallback regex on the scope-stripped name
|
|
1134
|
+
const bare = containerName.replace(/^@[^/]+\//, "").toLowerCase();
|
|
1135
|
+
for (const rule of FALLBACK_GROUP_RULES) {
|
|
1136
|
+
if (rule.re.test(bare)) {
|
|
1137
|
+
const idx = DEFAULT_GROUPS.findIndex((g) => g.id === rule.id);
|
|
1138
|
+
if (idx >= 0) return groups[idx];
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
// Inherit from a parent workspace package when this one lives inside another's directory
|
|
1142
|
+
// (e.g., packages/web-ui/example inherits from @draht/web-ui).
|
|
1143
|
+
if (pkg && pkg.path && pkg.path !== ".") {
|
|
1144
|
+
const parentPkg = pkgs.find((p) => p.name !== pkg.name && p.path !== "." && pkg.path !== p.path && pkg.path.startsWith(p.path + "/"));
|
|
1145
|
+
if (parentPkg) {
|
|
1146
|
+
const parentGroup = findGroup(parentPkg.name, parentPkg);
|
|
1147
|
+
if (parentGroup && parentGroup.id !== "group:other") return parentGroup;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
// Path-based fallback for apps/, examples/, scripts/ etc.
|
|
1151
|
+
if (pkg && pkg.path && pkg.path !== ".") {
|
|
1152
|
+
for (const rule of PATH_GROUP_RULES) {
|
|
1153
|
+
if (rule.re.test(pkg.path.toLowerCase())) {
|
|
1154
|
+
const idx = DEFAULT_GROUPS.findIndex((g) => g.id === rule.id);
|
|
1155
|
+
if (idx >= 0) return groups[idx];
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
// Bin-presence cue → CLI & Runtime
|
|
1160
|
+
if (pkg && pkg.path !== ".") {
|
|
1161
|
+
try {
|
|
1162
|
+
const pjPath = path.join(root || process.cwd(), pkg.path, "package.json");
|
|
1163
|
+
const pj = JSON.parse(fs.readFileSync(pjPath, "utf-8"));
|
|
1164
|
+
if (pj.bin) {
|
|
1165
|
+
const idx = DEFAULT_GROUPS.findIndex((g) => g.id === "group:cli-runtime");
|
|
1166
|
+
if (idx >= 0) return groups[idx];
|
|
1167
|
+
}
|
|
1168
|
+
} catch { /* empty */ }
|
|
1169
|
+
}
|
|
1170
|
+
return otherGroup;
|
|
1171
|
+
};
|
|
1172
|
+
|
|
1173
|
+
for (const c of containers) {
|
|
1174
|
+
const g = findGroup(c.name, pkgs.find((p) => p.name === c.name));
|
|
1175
|
+
g.members.push(c.id);
|
|
1176
|
+
g.moduleCount += c.moduleCount || 0;
|
|
1177
|
+
c.groupId = g.id;
|
|
1178
|
+
}
|
|
1179
|
+
const all = groups.filter((g) => g.members.length > 0);
|
|
1180
|
+
if (otherGroup.members.length > 0) all.push(otherGroup);
|
|
1181
|
+
return all;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
function applyGroupsCuration(groups, root) {
|
|
1185
|
+
try {
|
|
1186
|
+
const file = path.join(root, PLANNING_DIR, "codebase", "GROUPS.json");
|
|
1187
|
+
if (!fs.existsSync(file)) return groups;
|
|
1188
|
+
const user = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
1189
|
+
if (!Array.isArray(user.groups)) return groups;
|
|
1190
|
+
const byId = new Map(groups.map((g) => [g.id, g]));
|
|
1191
|
+
for (const ug of user.groups) {
|
|
1192
|
+
if (!ug.id) continue;
|
|
1193
|
+
const existing = byId.get(ug.id);
|
|
1194
|
+
const merged = Object.assign({}, existing || {}, ug, { source: "curated" });
|
|
1195
|
+
byId.set(ug.id, merged);
|
|
1196
|
+
}
|
|
1197
|
+
// Enforce single-group-per-package: later (curated) groups win
|
|
1198
|
+
const seen = new Set();
|
|
1199
|
+
const out = [];
|
|
1200
|
+
for (const g of byId.values()) {
|
|
1201
|
+
const m = (g.members || []).filter((id) => {
|
|
1202
|
+
if (seen.has(id)) return false;
|
|
1203
|
+
seen.add(id);
|
|
1204
|
+
return true;
|
|
1205
|
+
});
|
|
1206
|
+
out.push(Object.assign({}, g, { members: m }));
|
|
1207
|
+
}
|
|
1208
|
+
return out;
|
|
1209
|
+
} catch { return groups; }
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
const VIS_LANG_BY_EXT = {
|
|
1213
|
+
".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
|
|
1214
|
+
".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
|
|
1215
|
+
".py": "python", ".go": "go", ".rs": "rust", ".java": "java", ".kt": "kotlin",
|
|
1216
|
+
".swift": "swift", ".rb": "ruby", ".php": "php", ".cs": "csharp",
|
|
1217
|
+
".c": "c", ".h": "c", ".cpp": "cpp", ".hpp": "cpp", ".cc": "cpp",
|
|
1218
|
+
".md": "markdown", ".json": "json", ".yaml": "yaml", ".yml": "yaml",
|
|
1219
|
+
".toml": "toml", ".html": "html", ".css": "css", ".scss": "scss",
|
|
1220
|
+
".sh": "shell", ".bash": "shell", ".zsh": "shell", ".sql": "sql",
|
|
1221
|
+
};
|
|
1222
|
+
|
|
1223
|
+
function visLangFor(file) {
|
|
1224
|
+
const ext = path.extname(file).toLowerCase();
|
|
1225
|
+
return VIS_LANG_BY_EXT[ext] || "other";
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
function visWalk(root, options = {}) {
|
|
1229
|
+
const ignore = options.ignore || VIS_DEFAULT_IGNORES;
|
|
1230
|
+
const maxFiles = options.maxFiles || 5000;
|
|
1231
|
+
const files = [];
|
|
1232
|
+
const stack = [root];
|
|
1233
|
+
while (stack.length && files.length < maxFiles) {
|
|
1234
|
+
const dir = stack.pop();
|
|
1235
|
+
let entries;
|
|
1236
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
|
|
1237
|
+
catch { continue; }
|
|
1238
|
+
for (const e of entries) {
|
|
1239
|
+
if (ignore.has(e.name)) continue;
|
|
1240
|
+
if (e.name.startsWith(".") && !["..", "."].includes(e.name)) {
|
|
1241
|
+
if (ignore.has(e.name)) continue;
|
|
1242
|
+
}
|
|
1243
|
+
const full = path.join(dir, e.name);
|
|
1244
|
+
if (e.isDirectory()) stack.push(full);
|
|
1245
|
+
else if (e.isFile()) files.push(full);
|
|
1246
|
+
if (files.length >= maxFiles) break;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return files;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// Parse JS/TS imports into structured entries: { specifier, names: [{local, imported}], default, namespace }
|
|
1253
|
+
function visParseImports(content, language) {
|
|
1254
|
+
const out = [];
|
|
1255
|
+
if (language !== "typescript" && language !== "javascript") {
|
|
1256
|
+
// Fallback for other langs — return raw specifiers only
|
|
1257
|
+
const raw = visExtractRawImports(content, language);
|
|
1258
|
+
for (const s of raw) out.push({ specifier: s, names: [], default: null, namespace: null });
|
|
1259
|
+
return out;
|
|
1260
|
+
}
|
|
1261
|
+
// ES import statements
|
|
1262
|
+
const importRe = /import\s+(?:type\s+)?(?:([A-Za-z_$][\w$]*)\s*(?:,\s*)?)?(?:\*\s+as\s+([A-Za-z_$][\w$]*)|\{([^}]+)\})?\s*from\s*["']([^"']+)["']/g;
|
|
1263
|
+
let m;
|
|
1264
|
+
while ((m = importRe.exec(content)) !== null) {
|
|
1265
|
+
const def = m[1] || null;
|
|
1266
|
+
const ns = m[2] || null;
|
|
1267
|
+
const named = m[3];
|
|
1268
|
+
const spec = m[4];
|
|
1269
|
+
const names = [];
|
|
1270
|
+
if (named) {
|
|
1271
|
+
for (const part of named.split(",")) {
|
|
1272
|
+
const t = part.trim().replace(/^type\s+/, "");
|
|
1273
|
+
if (!t) continue;
|
|
1274
|
+
const asMatch = t.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);
|
|
1275
|
+
if (asMatch) names.push({ imported: asMatch[1], local: asMatch[2] });
|
|
1276
|
+
else names.push({ imported: t, local: t });
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
out.push({ specifier: spec, default: def, namespace: ns, names });
|
|
1280
|
+
}
|
|
1281
|
+
// require / dynamic import
|
|
1282
|
+
const reqRe = /(?:require|import)\s*\(\s*["']([^"']+)["']\s*\)/g;
|
|
1283
|
+
while ((m = reqRe.exec(content)) !== null) {
|
|
1284
|
+
out.push({ specifier: m[1], default: null, namespace: null, names: [] });
|
|
1285
|
+
}
|
|
1286
|
+
// re-exports: export { foo } from "./x"
|
|
1287
|
+
const reExportRe = /export\s+\{([^}]+)\}\s+from\s+["']([^"']+)["']/g;
|
|
1288
|
+
while ((m = reExportRe.exec(content)) !== null) {
|
|
1289
|
+
const names = m[1].split(",").map((s) => {
|
|
1290
|
+
const t = s.trim().replace(/^type\s+/, "");
|
|
1291
|
+
const asMatch = t.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);
|
|
1292
|
+
return asMatch ? { imported: asMatch[1], local: asMatch[2] }
|
|
1293
|
+
: { imported: t, local: t };
|
|
1294
|
+
}).filter((n) => n.imported);
|
|
1295
|
+
out.push({ specifier: m[2], default: null, namespace: null, names, reExport: true });
|
|
1296
|
+
}
|
|
1297
|
+
// star re-exports: export * from "./x" or export * as Foo from "./x"
|
|
1298
|
+
const starReExportRe = /export\s+\*(?:\s+as\s+([A-Za-z_$][\w$]*))?\s+from\s+["']([^"']+)["']/g;
|
|
1299
|
+
while ((m = starReExportRe.exec(content)) !== null) {
|
|
1300
|
+
out.push({ specifier: m[2], default: null, namespace: m[1] || "*", names: [], reExport: true });
|
|
1301
|
+
}
|
|
1302
|
+
return out;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
function visExtractRawImports(content, language) {
|
|
1306
|
+
const imports = [];
|
|
1307
|
+
if (language === "python") {
|
|
1308
|
+
const re = /(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g;
|
|
1309
|
+
let m;
|
|
1310
|
+
while ((m = re.exec(content)) !== null) imports.push(m[1] || m[2]);
|
|
1311
|
+
} else if (language === "go") {
|
|
1312
|
+
const re = /(?:^|\n)\s*import\s+(?:"([^"]+)"|\(([^)]+)\))/g;
|
|
1313
|
+
let m;
|
|
1314
|
+
while ((m = re.exec(content)) !== null) {
|
|
1315
|
+
if (m[1]) imports.push(m[1]);
|
|
1316
|
+
if (m[2]) for (const l of m[2].split("\n")) {
|
|
1317
|
+
const im = l.match(/"([^"]+)"/);
|
|
1318
|
+
if (im) imports.push(im[1]);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
} else if (language === "rust") {
|
|
1322
|
+
const re = /(?:^|\n)\s*use\s+([a-zA-Z0-9_:]+)/g;
|
|
1323
|
+
let m;
|
|
1324
|
+
while ((m = re.exec(content)) !== null) imports.push(m[1]);
|
|
1325
|
+
}
|
|
1326
|
+
return imports;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
// Extract exports — distinguish exported names so we can build a real call graph
|
|
1330
|
+
function visExtractExports(rawContent, language) {
|
|
1331
|
+
const out = [];
|
|
1332
|
+
const lines = rawContent.split("\n");
|
|
1333
|
+
const findLeadingDoc = (idx) => {
|
|
1334
|
+
let i = idx - 1;
|
|
1335
|
+
// Skip blank decorator/annotation lines so JSDoc directly above @decorator export still gets attached
|
|
1336
|
+
while (i >= 0 && /^\s*@[A-Za-z]/.test(lines[i])) i--;
|
|
1337
|
+
// /** ... */ block immediately above?
|
|
1338
|
+
if (i >= 0 && /\*\/\s*$/.test(lines[i])) {
|
|
1339
|
+
const block = [];
|
|
1340
|
+
while (i >= 0) {
|
|
1341
|
+
block.unshift(lines[i]);
|
|
1342
|
+
if (/^\s*\/\*\*?/.test(lines[i])) break;
|
|
1343
|
+
i--;
|
|
1344
|
+
}
|
|
1345
|
+
if (i >= 0) {
|
|
1346
|
+
return block.join("\n")
|
|
1347
|
+
.replace(/^\s*\/\*\*?/, "")
|
|
1348
|
+
.replace(/\*\/\s*$/, "")
|
|
1349
|
+
.replace(/^\s*\*\s?/gm, "")
|
|
1350
|
+
.replace(/^\s*@\w+.*$/gm, "")
|
|
1351
|
+
.split("\n").map((s) => s.trim()).filter(Boolean).join(" ")
|
|
1352
|
+
.slice(0, 240);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
// Run of // comments immediately above?
|
|
1356
|
+
const block = [];
|
|
1357
|
+
while (i >= 0 && /^\s*\/\//.test(lines[i])) {
|
|
1358
|
+
block.unshift(lines[i].replace(/^\s*\/\/\s?/, ""));
|
|
1359
|
+
i--;
|
|
1360
|
+
}
|
|
1361
|
+
if (block.length) return block.join(" ").trim().slice(0, 240);
|
|
1362
|
+
return null;
|
|
1363
|
+
};
|
|
1364
|
+
|
|
1365
|
+
if (language === "typescript" || language === "javascript") {
|
|
1366
|
+
const exportRe = /^\s*export\s+(?:default\s+)?(?:async\s+)?(class|interface|type|function|const|let|enum|var)\s+([A-Za-z_$][\w$]*)/;
|
|
1367
|
+
const namedExportRe = /^\s*export\s*\{([^}]+)\}(?!\s+from)/;
|
|
1368
|
+
const defaultRe = /^\s*export\s+default\s/;
|
|
1369
|
+
const commandRe = /^\s*commands\s*\[\s*["']([^"']+)["']\s*\]\s*=/;
|
|
1370
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1371
|
+
let m;
|
|
1372
|
+
if ((m = exportRe.exec(lines[i]))) {
|
|
1373
|
+
out.push({ name: m[2], kind: m[1], line: i + 1, doc: findLeadingDoc(i) });
|
|
1374
|
+
} else if ((m = namedExportRe.exec(lines[i]))) {
|
|
1375
|
+
const doc = findLeadingDoc(i);
|
|
1376
|
+
for (const part of m[1].split(",")) {
|
|
1377
|
+
const t = part.trim().replace(/^type\s+/, "");
|
|
1378
|
+
const asMatch = t.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);
|
|
1379
|
+
if (asMatch) out.push({ name: asMatch[2] || asMatch[1], kind: "named", line: i + 1, doc });
|
|
1380
|
+
}
|
|
1381
|
+
} else if (defaultRe.test(lines[i]) && !out.some((e) => e.name === "default")) {
|
|
1382
|
+
out.push({ name: "default", kind: "default", line: i + 1, doc: findLeadingDoc(i) });
|
|
1383
|
+
} else if ((m = commandRe.exec(lines[i]))) {
|
|
1384
|
+
out.push({ name: m[1], kind: "command", line: i + 1, doc: findLeadingDoc(i) });
|
|
1385
|
+
}
|
|
1386
|
+
if (out.length > 200) break;
|
|
1387
|
+
}
|
|
1388
|
+
} else if (language === "python") {
|
|
1389
|
+
const re = /^(class|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;
|
|
1390
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1391
|
+
const m = re.exec(lines[i]);
|
|
1392
|
+
if (m) {
|
|
1393
|
+
let doc = null;
|
|
1394
|
+
for (let j = i + 1; j < Math.min(i + 6, lines.length); j++) {
|
|
1395
|
+
const dm = lines[j].match(/^\s*("""|''')(.*)/);
|
|
1396
|
+
if (dm) { doc = dm[2].replace(/("""|''')\s*$/, "").trim().slice(0, 220) || null; break; }
|
|
1397
|
+
}
|
|
1398
|
+
out.push({ name: m[2], kind: m[1], line: i + 1, doc });
|
|
1399
|
+
}
|
|
1400
|
+
if (out.length > 200) break;
|
|
1401
|
+
}
|
|
1402
|
+
} else if (language === "go") {
|
|
1403
|
+
const re = /^\s*(?:func\s+(?:\([^)]+\)\s+)?([A-Z][a-zA-Z0-9_]*)|type\s+([A-Z][a-zA-Z0-9_]*))/;
|
|
1404
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1405
|
+
const m = re.exec(lines[i]);
|
|
1406
|
+
if (m) out.push({ name: m[1] || m[2], kind: m[1] ? "func" : "type", line: i + 1, doc: findLeadingDoc(i) });
|
|
1407
|
+
if (out.length > 200) break;
|
|
1408
|
+
}
|
|
1409
|
+
} else if (language === "rust") {
|
|
1410
|
+
const re = /^\s*pub\s+(?:fn|struct|enum|trait)\s+([A-Za-z_][A-Za-z0-9_]*)/;
|
|
1411
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1412
|
+
const m = re.exec(lines[i]);
|
|
1413
|
+
if (m) {
|
|
1414
|
+
let j = i - 1; const block = [];
|
|
1415
|
+
while (j >= 0 && /^\s*\/\/\//.test(lines[j])) { block.unshift(lines[j].replace(/^\s*\/\/\/\s?/, "")); j--; }
|
|
1416
|
+
out.push({ name: m[1], kind: "rust-pub", line: i + 1, doc: block.length ? block.join(" ").trim().slice(0, 240) : null });
|
|
1417
|
+
}
|
|
1418
|
+
if (out.length > 200) break;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
const seen = new Set();
|
|
1422
|
+
// Reject "section divider" comments like `// --- foo ---` or `// ======` that aren't real docs
|
|
1423
|
+
const looksLikeDoc = (d) => d && d.length > 8 && !/^[-=#*\s]+$|^-+\s*\w+\s*-+$/.test(d.trim());
|
|
1424
|
+
return out
|
|
1425
|
+
.filter((e) => { if (seen.has(e.name)) return false; seen.add(e.name); return true; })
|
|
1426
|
+
.map((e) => looksLikeDoc(e.doc) ? e : Object.assign({}, e, { doc: null }));
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// Locate concrete sink callsites: which line + enclosing function performs each sink.
|
|
1430
|
+
function visFindSinkSites(content, language) {
|
|
1431
|
+
if (!VIS_CODE_LANGS.has(language)) return [];
|
|
1432
|
+
const sites = [];
|
|
1433
|
+
const lines = content.split("\n");
|
|
1434
|
+
const KEYWORDS = new Set(["if","else","while","for","switch","catch","try","do","return","throw","new","await","async","typeof","instanceof","void","delete","yield","case","default","function","class","const","let","var"]);
|
|
1435
|
+
const findEnclosingFunction = (lineIdx) => {
|
|
1436
|
+
for (let i = lineIdx - 1; i >= Math.max(0, lineIdx - 200); i--) {
|
|
1437
|
+
let m;
|
|
1438
|
+
if ((m = lines[i].match(/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/))) return m[1];
|
|
1439
|
+
if ((m = lines[i].match(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>)/))) return m[1];
|
|
1440
|
+
if ((m = lines[i].match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*[:{]/))) {
|
|
1441
|
+
if (!KEYWORDS.has(m[1])) return m[1];
|
|
1442
|
+
}
|
|
1443
|
+
if ((m = lines[i].match(/^\s*def\s+([A-Za-z_$][\w$]*)/))) return m[1];
|
|
1444
|
+
if ((m = lines[i].match(/^\s*func\s+(?:\([^)]+\)\s+)?([A-Za-z_$][\w$]*)/))) return m[1];
|
|
1445
|
+
}
|
|
1446
|
+
return null;
|
|
1447
|
+
};
|
|
1448
|
+
const lineOf = (charIdx) => {
|
|
1449
|
+
let pos = 0;
|
|
1450
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1451
|
+
if (pos + lines[i].length + 1 > charIdx) return i;
|
|
1452
|
+
pos += lines[i].length + 1;
|
|
1453
|
+
}
|
|
1454
|
+
return lines.length - 1;
|
|
1455
|
+
};
|
|
1456
|
+
for (const { kind, re } of SINK_PATTERNS) {
|
|
1457
|
+
const gre = new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
|
|
1458
|
+
let m, count = 0;
|
|
1459
|
+
while ((m = gre.exec(content)) !== null && count < 2) {
|
|
1460
|
+
const lineIdx = lineOf(m.index);
|
|
1461
|
+
sites.push({
|
|
1462
|
+
kind, line: lineIdx + 1,
|
|
1463
|
+
snippet: (lines[lineIdx] || "").trim().slice(0, 140),
|
|
1464
|
+
inFunction: findEnclosingFunction(lineIdx),
|
|
1465
|
+
});
|
|
1466
|
+
count++;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
return sites;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// Side-effect / sink detection — classify what a module *does* in the world
|
|
1473
|
+
const SINK_PATTERNS = [
|
|
1474
|
+
{ kind: "fs:write", re: /\bfs(?:Promises)?\.(?:writeFile|writeFileSync|appendFile|appendFileSync|copyFile|copyFileSync|rename|renameSync|rm|rmSync|unlink|unlinkSync|mkdir|mkdirSync|symlink|symlinkSync|chmod|chmodSync)\b/ },
|
|
1475
|
+
{ kind: "fs:read", re: /\bfs(?:Promises)?\.(?:readFile|readFileSync|readdir|readdirSync|stat|statSync|access|accessSync|createReadStream)\b/ },
|
|
1476
|
+
{ kind: "net:fetch", re: /\b(?:fetch|axios\.(?:get|post|put|delete|patch|request)|undici|got\.(?:get|post))\s*\(/ },
|
|
1477
|
+
{ kind: "net:http", re: /\b(?:https?\.request|https?\.get)\s*\(|new\s+(?:XMLHttpRequest|WebSocket)\b/ },
|
|
1478
|
+
{ kind: "db:sql", re: /\b(?:pool\.query|client\.query|db\.query|knex\(|sequelize\.|pg\.Pool|new\s+Pool|drizzle\()/ },
|
|
1479
|
+
{ kind: "db:orm", re: /\b(?:prisma|mongoose|typeorm|drizzle)\.[\w$]+\.(?:create|update|delete|upsert|findMany|findFirst|findUnique|insertMany|deleteMany|updateMany|aggregate)\b/ },
|
|
1480
|
+
{ kind: "cli:io", re: /\bprocess\.(?:stdout|stderr)\.(?:write|on)\b|\bconsole\.(?:log|error|warn|info)\b/ },
|
|
1481
|
+
{ kind: "process:exec", re: /\b(?:execSync|execFileSync|spawnSync|spawn|execFile|fork)\s*\(/ },
|
|
1482
|
+
{ kind: "process:exit", re: /\bprocess\.exit\s*\(/ },
|
|
1483
|
+
{ kind: "ai:call", re: /\bnew\s+(?:Anthropic|OpenAI)\s*\(|\b(?:anthropic|openai|claude)\.(?:messages|chat|completions|complete|stream|create|invoke|generate)\b|@anthropic-ai\/sdk|@google\/generative-ai/i },
|
|
1484
|
+
{ kind: "env:read", re: /\bprocess\.env\.[A-Z_]+/ },
|
|
1485
|
+
];
|
|
1486
|
+
|
|
1487
|
+
function visDetectSinks(content) {
|
|
1488
|
+
const out = new Set();
|
|
1489
|
+
for (const { kind, re } of SINK_PATTERNS) {
|
|
1490
|
+
if (re.test(content)) out.add(kind);
|
|
1491
|
+
}
|
|
1492
|
+
return [...out];
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// HTTP route detection — common Express/Koa/Fastify/Hono/Nest/etc.
|
|
1496
|
+
const ROUTE_PATTERNS = [
|
|
1497
|
+
{ re: /\b(?:app|router|server|fastify|hono|api)\s*\.\s*(get|post|put|delete|patch|all|use|options|head)\s*\(\s*["'`]([^"'`]+)["'`]/gi, methodIdx: 1, pathIdx: 2 },
|
|
1498
|
+
{ re: /@(Get|Post|Put|Delete|Patch|All)\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g, methodIdx: 1, pathIdx: 2 },
|
|
1499
|
+
];
|
|
1500
|
+
function visDetectRoutes(content) {
|
|
1501
|
+
const out = [];
|
|
1502
|
+
for (const { re, methodIdx, pathIdx } of ROUTE_PATTERNS) {
|
|
1503
|
+
let m; re.lastIndex = 0;
|
|
1504
|
+
while ((m = re.exec(content)) !== null) {
|
|
1505
|
+
out.push({ method: m[methodIdx].toUpperCase(), path: m[pathIdx] });
|
|
1506
|
+
if (out.length > 40) break;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return out;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
// Layer heuristic — uses path + sinks to classify a module
|
|
1513
|
+
function visClassifyLayer(rel, sinks, hasRoutes, isBin, isExport) {
|
|
1514
|
+
const p = rel.toLowerCase();
|
|
1515
|
+
if (isBin || /\/(cli|bin|main)\.(?:ts|js|mjs|cjs)$/.test("/" + p) || /(^|\/)(cli|bin)\//.test(p)) return "presentation";
|
|
1516
|
+
if (hasRoutes || /(^|\/)(routes|handlers|controllers|api|http|server)\//.test(p)) return "presentation";
|
|
1517
|
+
if (/(^|\/)(domain|entities|aggregates|models|value-objects)\//.test(p)) return "domain";
|
|
1518
|
+
if (/(^|\/)(services|use[-_]?cases|application|workflows|commands|handlers|tools|features|modules)\//.test(p)) return "application";
|
|
1519
|
+
const isInfraSink = sinks.some((s) => s.startsWith("db:") || s.startsWith("net:") || s === "fs:write" || s.startsWith("process:exec"));
|
|
1520
|
+
if (isInfraSink) return "infrastructure";
|
|
1521
|
+
if (/(^|\/)(utils|helpers|lib|shared|common|types?|core)\//.test(p) && !isExport) return "support";
|
|
1522
|
+
if (isExport) return "application";
|
|
1523
|
+
return "support";
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
function visIsTest(rel) {
|
|
1527
|
+
return /(^|\/)(test|tests|__tests__|spec)\//.test(rel)
|
|
1528
|
+
|| /\.(test|spec)\.[a-z]+$/.test(rel);
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
// Discover workspace glob patterns from any of: pnpm-workspace.yaml,
|
|
1532
|
+
// root package.json `workspaces`, lerna.json `packages`. Returns
|
|
1533
|
+
// an array of glob strings (no leading `./`). Falls back to ["packages/*"]
|
|
1534
|
+
// when no manifest is found, so legacy monorepos still work.
|
|
1535
|
+
function visDiscoverWorkspacePatterns(root) {
|
|
1536
|
+
const patterns = new Set();
|
|
1537
|
+
// 1) pnpm-workspace.yaml
|
|
1538
|
+
try {
|
|
1539
|
+
const yamlPath = path.join(root, "pnpm-workspace.yaml");
|
|
1540
|
+
if (fs.existsSync(yamlPath)) {
|
|
1541
|
+
const text = fs.readFileSync(yamlPath, "utf-8");
|
|
1542
|
+
let inPackages = false;
|
|
1543
|
+
for (const rawLine of text.split("\n")) {
|
|
1544
|
+
const line = rawLine.replace(/\r$/, "");
|
|
1545
|
+
if (/^packages\s*:\s*(?:#.*)?$/.test(line)) { inPackages = true; continue; }
|
|
1546
|
+
if (!inPackages) continue;
|
|
1547
|
+
if (/^\S/.test(line) && !/^\s*-/.test(line)) { inPackages = false; continue; }
|
|
1548
|
+
const m = line.match(/^\s*-\s*['"]?([^'"\s#]+)['"]?/);
|
|
1549
|
+
if (m) patterns.add(m[1].replace(/^\.\//, "").replace(/\/$/, ""));
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
} catch { /* empty */ }
|
|
1553
|
+
// 2) root package.json `workspaces`
|
|
1554
|
+
try {
|
|
1555
|
+
const rootPkgPath = path.join(root, "package.json");
|
|
1556
|
+
if (fs.existsSync(rootPkgPath)) {
|
|
1557
|
+
const pj = JSON.parse(fs.readFileSync(rootPkgPath, "utf-8"));
|
|
1558
|
+
const w = pj.workspaces;
|
|
1559
|
+
const list = Array.isArray(w) ? w : (w && Array.isArray(w.packages) ? w.packages : []);
|
|
1560
|
+
for (const p of list) {
|
|
1561
|
+
if (typeof p === "string") patterns.add(p.replace(/^\.\//, "").replace(/\/$/, ""));
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
} catch { /* empty */ }
|
|
1565
|
+
// 3) lerna.json
|
|
1566
|
+
try {
|
|
1567
|
+
const lernaPath = path.join(root, "lerna.json");
|
|
1568
|
+
if (fs.existsSync(lernaPath)) {
|
|
1569
|
+
const lj = JSON.parse(fs.readFileSync(lernaPath, "utf-8"));
|
|
1570
|
+
for (const p of (lj.packages || [])) {
|
|
1571
|
+
if (typeof p === "string") patterns.add(p.replace(/^\.\//, "").replace(/\/$/, ""));
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
} catch { /* empty */ }
|
|
1575
|
+
// 4) Sensible default if none of the above declared a workspace layout
|
|
1576
|
+
if (patterns.size === 0) patterns.add("packages/*");
|
|
1577
|
+
return [...patterns];
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// Expand a glob pattern (e.g., "packages/*", "apps/*", "packages/functions/*",
|
|
1581
|
+
// "openauthjs/packages/*", "packages/**") rooted at `root` into a list of absolute
|
|
1582
|
+
// package.json paths. Supports `*` (single segment) and `**` (recursive descent).
|
|
1583
|
+
function visExpandWorkspacePattern(root, pattern) {
|
|
1584
|
+
// Strip trailing /package.json if a manifest used "apps/*/package.json"
|
|
1585
|
+
pattern = pattern.replace(/\/package\.json$/, "");
|
|
1586
|
+
const segments = pattern.split("/").filter(Boolean);
|
|
1587
|
+
const out = [];
|
|
1588
|
+
const visit = (currentPath, remaining) => {
|
|
1589
|
+
if (remaining.length === 0) {
|
|
1590
|
+
const pj = path.join(currentPath, "package.json");
|
|
1591
|
+
if (fs.existsSync(pj)) out.push(pj);
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1594
|
+
let stat;
|
|
1595
|
+
try { stat = fs.statSync(currentPath); } catch { return; }
|
|
1596
|
+
if (!stat.isDirectory()) return;
|
|
1597
|
+
const [next, ...rest] = remaining;
|
|
1598
|
+
if (next === "*") {
|
|
1599
|
+
let entries;
|
|
1600
|
+
try { entries = fs.readdirSync(currentPath, { withFileTypes: true }); } catch { return; }
|
|
1601
|
+
for (const e of entries) {
|
|
1602
|
+
if (!e.isDirectory()) continue;
|
|
1603
|
+
if (VIS_DEFAULT_IGNORES.has(e.name)) continue;
|
|
1604
|
+
if (e.name.startsWith(".") && !["..", "."].includes(e.name)) continue;
|
|
1605
|
+
visit(path.join(currentPath, e.name), rest);
|
|
1606
|
+
}
|
|
1607
|
+
} else if (next === "**") {
|
|
1608
|
+
// Match this depth too (zero or more directories)
|
|
1609
|
+
visit(currentPath, rest);
|
|
1610
|
+
let entries;
|
|
1611
|
+
try { entries = fs.readdirSync(currentPath, { withFileTypes: true }); } catch { return; }
|
|
1612
|
+
for (const e of entries) {
|
|
1613
|
+
if (!e.isDirectory()) continue;
|
|
1614
|
+
if (VIS_DEFAULT_IGNORES.has(e.name)) continue;
|
|
1615
|
+
if (e.name.startsWith(".")) continue;
|
|
1616
|
+
visit(path.join(currentPath, e.name), remaining); // keep ** alive
|
|
1617
|
+
}
|
|
1618
|
+
} else if (next.includes("*")) {
|
|
1619
|
+
// Partial-wildcard segment ("foo-*", "*.bar") — match by regex
|
|
1620
|
+
const re = new RegExp("^" + next.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
|
|
1621
|
+
let entries;
|
|
1622
|
+
try { entries = fs.readdirSync(currentPath, { withFileTypes: true }); } catch { return; }
|
|
1623
|
+
for (const e of entries) {
|
|
1624
|
+
if (!e.isDirectory()) continue;
|
|
1625
|
+
if (VIS_DEFAULT_IGNORES.has(e.name)) continue;
|
|
1626
|
+
if (!re.test(e.name)) continue;
|
|
1627
|
+
visit(path.join(currentPath, e.name), rest);
|
|
1628
|
+
}
|
|
1629
|
+
} else {
|
|
1630
|
+
// Literal segment
|
|
1631
|
+
visit(path.join(currentPath, next), rest);
|
|
1632
|
+
}
|
|
1633
|
+
};
|
|
1634
|
+
visit(root, segments);
|
|
1635
|
+
return out;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
function visScanPackages(root) {
|
|
1639
|
+
const pkgs = [];
|
|
1640
|
+
const seen = new Set();
|
|
1641
|
+
// Always include root manifest
|
|
1642
|
+
const rootPj = path.join(root, "package.json");
|
|
1643
|
+
if (fs.existsSync(rootPj)) seen.add(rootPj);
|
|
1644
|
+
// Expand all workspace patterns
|
|
1645
|
+
const patterns = visDiscoverWorkspacePatterns(root);
|
|
1646
|
+
const candidates = fs.existsSync(rootPj) ? [rootPj] : [];
|
|
1647
|
+
for (const pat of patterns) {
|
|
1648
|
+
const isNegated = pat.startsWith("!");
|
|
1649
|
+
if (isNegated) continue; // pnpm/npm support negations; ignore for simplicity (rare in practice)
|
|
1650
|
+
const found = visExpandWorkspacePattern(root, pat);
|
|
1651
|
+
for (const f of found) {
|
|
1652
|
+
if (!seen.has(f)) { seen.add(f); candidates.push(f); }
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
for (const p of candidates) {
|
|
1656
|
+
try {
|
|
1657
|
+
const j = JSON.parse(fs.readFileSync(p, "utf-8"));
|
|
1658
|
+
pkgs.push({
|
|
1659
|
+
name: j.name || path.basename(path.dirname(p)),
|
|
1660
|
+
version: j.version || null,
|
|
1661
|
+
path: path.relative(root, path.dirname(p)) || ".",
|
|
1662
|
+
description: j.description || null,
|
|
1663
|
+
dependencies: Object.keys(j.dependencies || {}),
|
|
1664
|
+
devDependencies: Object.keys(j.devDependencies || {}),
|
|
1665
|
+
peerDependencies: Object.keys(j.peerDependencies || {}),
|
|
1666
|
+
workspaceDeps: Object.entries(j.dependencies || {})
|
|
1667
|
+
.filter(([, v]) => typeof v === "string" && v.startsWith("workspace:"))
|
|
1668
|
+
.map(([k]) => k),
|
|
1669
|
+
workspacePatterns: p === rootPj ? patterns : undefined,
|
|
1670
|
+
});
|
|
1671
|
+
} catch { /* empty */ }
|
|
1672
|
+
}
|
|
1673
|
+
return pkgs;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
function visReadPlanning(root) {
|
|
1677
|
+
const planning = path.join(root, PLANNING_DIR);
|
|
1678
|
+
const out = { state: null, roadmap: null, project: null, domain: null };
|
|
1679
|
+
const tryRead = (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf-8") : null;
|
|
1680
|
+
out.state = tryRead(path.join(planning, "STATE.md"));
|
|
1681
|
+
out.roadmap = tryRead(path.join(planning, "ROADMAP.md"));
|
|
1682
|
+
out.project = tryRead(path.join(planning, "PROJECT.md"));
|
|
1683
|
+
out.domain = tryRead(path.join(planning, "DOMAIN.md")) || tryRead(path.join(planning, "DOMAIN-MODEL.md"));
|
|
1684
|
+
return out;
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
// ── Knowledge-graph enrichment (graphify-style: rationale, symbols, clusters, surprises) ──
|
|
1688
|
+
|
|
1689
|
+
// Inline rationale markers — design intent captured in comments (graphify NOTE/WHY/HACK nodes).
|
|
1690
|
+
const RATIONALE_TAG_RE = /\b(SECURITY|BUG|FIXME|HACK|XXX|TODO|WARNING|GOTCHA|PERF|NOTE|WHY)\b\s*[:\-]?\s*(.+)/;
|
|
1691
|
+
const RATIONALE_SEVERITY = { SECURITY: 0, BUG: 1, FIXME: 2, HACK: 3, XXX: 4, WARNING: 5, GOTCHA: 6, PERF: 7, TODO: 8, NOTE: 9, WHY: 10 };
|
|
1692
|
+
const COMMENT_STYLE = {
|
|
1693
|
+
typescript: { line: "//", block: ["/*", "*/"] }, javascript: { line: "//", block: ["/*", "*/"] },
|
|
1694
|
+
go: { line: "//", block: ["/*", "*/"] }, rust: { line: "//", block: ["/*", "*/"] },
|
|
1695
|
+
java: { line: "//", block: ["/*", "*/"] }, kotlin: { line: "//", block: ["/*", "*/"] },
|
|
1696
|
+
swift: { line: "//", block: ["/*", "*/"] }, csharp: { line: "//", block: ["/*", "*/"] },
|
|
1697
|
+
c: { line: "//", block: ["/*", "*/"] }, cpp: { line: "//", block: ["/*", "*/"] },
|
|
1698
|
+
php: { line: "//", block: ["/*", "*/"] }, sql: { line: "--", block: ["/*", "*/"] },
|
|
1699
|
+
python: { line: "#" }, shell: { line: "#" }, ruby: { line: "#" },
|
|
1700
|
+
html: { block: ["<!--", "-->"] }, markdown: { block: ["<!--", "-->"] },
|
|
1701
|
+
};
|
|
1702
|
+
|
|
1703
|
+
// Extract comment TEXT (inverse of the strip logic) so the tag regex never matches code/strings.
|
|
1704
|
+
function visExtractComments(content, language) {
|
|
1705
|
+
const s = COMMENT_STYLE[language];
|
|
1706
|
+
if (!s) return [];
|
|
1707
|
+
const out = [];
|
|
1708
|
+
const lines = content.split("\n");
|
|
1709
|
+
let inBlock = false, close = null;
|
|
1710
|
+
for (let i = 0; i < lines.length && out.length < 400; i++) {
|
|
1711
|
+
let ln = lines[i];
|
|
1712
|
+
if (inBlock) {
|
|
1713
|
+
const ci = ln.indexOf(close);
|
|
1714
|
+
if (ci < 0) { out.push({ line: i + 1, text: ln }); continue; }
|
|
1715
|
+
out.push({ line: i + 1, text: ln.slice(0, ci) });
|
|
1716
|
+
ln = ln.slice(ci + close.length); inBlock = false; close = null;
|
|
1717
|
+
}
|
|
1718
|
+
if (s.line) {
|
|
1719
|
+
let idx = ln.indexOf(s.line);
|
|
1720
|
+
while (idx > 0 && s.line === "//" && ln[idx - 1] === ":") idx = ln.indexOf(s.line, idx + 2); // skip http://
|
|
1721
|
+
if (idx >= 0) { out.push({ line: i + 1, text: ln.slice(idx + s.line.length) }); ln = ln.slice(0, idx); }
|
|
1722
|
+
}
|
|
1723
|
+
if (s.block) {
|
|
1724
|
+
const [open, cl] = s.block;
|
|
1725
|
+
const oi = ln.indexOf(open);
|
|
1726
|
+
if (oi >= 0) {
|
|
1727
|
+
const ci = ln.indexOf(cl, oi + open.length);
|
|
1728
|
+
if (ci >= 0) out.push({ line: i + 1, text: ln.slice(oi + open.length, ci) });
|
|
1729
|
+
else { out.push({ line: i + 1, text: ln.slice(oi + open.length) }); inBlock = true; close = cl; }
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
return out;
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
function visExtractRationale(content, language, rel) {
|
|
1737
|
+
const out = [];
|
|
1738
|
+
for (const c of visExtractComments(content, language)) {
|
|
1739
|
+
const m = RATIONALE_TAG_RE.exec(c.text);
|
|
1740
|
+
if (m && m[2].trim()) { out.push({ file: rel, line: c.line, tag: m[1], text: m[2].trim().slice(0, 120) }); if (out.length >= 30) break; }
|
|
1741
|
+
}
|
|
1742
|
+
return out;
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// Symbol-level nodes: exported symbols (already have line) + best-effort non-exported top-level decls.
|
|
1746
|
+
function visBuildSymbols(exportsArr, content, language) {
|
|
1747
|
+
const syms = [];
|
|
1748
|
+
const seen = new Set();
|
|
1749
|
+
for (const e of exportsArr) {
|
|
1750
|
+
if (seen.has(e.name)) continue;
|
|
1751
|
+
seen.add(e.name);
|
|
1752
|
+
syms.push({ name: e.name, kind: e.kind, line: e.line, exported: true });
|
|
1753
|
+
if (syms.length >= 60) return syms;
|
|
1754
|
+
}
|
|
1755
|
+
const lines = content.split("\n");
|
|
1756
|
+
const addDecl = (re, kindOf) => {
|
|
1757
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1758
|
+
const m = re.exec(lines[i]);
|
|
1759
|
+
if (m) { const name = m[1] || m[2]; if (name && !seen.has(name)) { seen.add(name); syms.push({ name, kind: kindOf(lines[i]), line: i + 1, exported: false }); if (syms.length >= 60) return true; } }
|
|
1760
|
+
}
|
|
1761
|
+
return false;
|
|
1762
|
+
};
|
|
1763
|
+
if (language === "typescript" || language === "javascript") {
|
|
1764
|
+
addDecl(/^(?:async\s+)?(?:function|class)\s+([A-Za-z_$][\w$]*)|^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/, (l) => /^\s*(?:async\s+)?class\b/.test(l) ? "class" : /^\s*(?:async\s+)?function\b/.test(l) ? "function" : "const");
|
|
1765
|
+
} else if (language === "python") {
|
|
1766
|
+
addDecl(/^(?:class|def)\s+([A-Za-z_][\w]*)/, (l) => /^class\b/.test(l) ? "class" : "def");
|
|
1767
|
+
} else if (language === "go") {
|
|
1768
|
+
addDecl(/^func\s+(?:\([^)]*\)\s+)?([a-z][\w]*)|^type\s+([a-z][\w]*)/, (l) => /^func\b/.test(l) ? "func" : "type");
|
|
1769
|
+
} else if (language === "rust") {
|
|
1770
|
+
addDecl(/^\s*(?:fn|struct|enum|trait)\s+([A-Za-z_][\w]*)/, () => "rust-item");
|
|
1771
|
+
}
|
|
1772
|
+
return syms;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
// Deterministic structural clusters via async label propagation over the undirected import graph.
|
|
1776
|
+
function visComputeClusters(modules, edges, moduleByRel, containerOf) {
|
|
1777
|
+
const adj = new Map();
|
|
1778
|
+
const link = (a, b) => { if (a === b) return; if (!adj.has(a)) adj.set(a, new Set()); adj.get(a).add(b); };
|
|
1779
|
+
for (const e of edges) {
|
|
1780
|
+
if (e.kind !== "import") continue;
|
|
1781
|
+
if (!moduleByRel.has(e.from) || !moduleByRel.has(e.to)) continue;
|
|
1782
|
+
link(e.from, e.to); link(e.to, e.from);
|
|
1783
|
+
}
|
|
1784
|
+
const ids = modules.map((m) => m.id).sort();
|
|
1785
|
+
const label = new Map(ids.map((id) => [id, id]));
|
|
1786
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1787
|
+
let changed = false;
|
|
1788
|
+
for (const id of ids) { // async: later nodes this pass see earlier updates
|
|
1789
|
+
const nbrs = adj.get(id);
|
|
1790
|
+
if (!nbrs || nbrs.size === 0) continue;
|
|
1791
|
+
const freq = new Map();
|
|
1792
|
+
for (const n of nbrs) { const l = label.get(n); freq.set(l, (freq.get(l) || 0) + 1); }
|
|
1793
|
+
let best = label.get(id), bestC = -1;
|
|
1794
|
+
for (const [l, c] of freq) { if (c > bestC || (c === bestC && l < best)) { best = l; bestC = c; } }
|
|
1795
|
+
if (best !== label.get(id)) { label.set(id, best); changed = true; }
|
|
1796
|
+
}
|
|
1797
|
+
if (!changed) break;
|
|
1798
|
+
}
|
|
1799
|
+
const byLabel = new Map();
|
|
1800
|
+
for (const id of ids) {
|
|
1801
|
+
const m = moduleByRel.get(id);
|
|
1802
|
+
const hasEdges = adj.has(id) && adj.get(id).size > 0;
|
|
1803
|
+
const key = hasEdges ? label.get(id) : containerOf(m); // unlinked modules → package cluster
|
|
1804
|
+
if (!byLabel.has(key)) byLabel.set(key, []);
|
|
1805
|
+
byLabel.get(key).push(id);
|
|
1806
|
+
}
|
|
1807
|
+
// Monster-community guard: if one cluster swallows >50% of non-test modules, fall back to packages.
|
|
1808
|
+
const nonTest = modules.filter((m) => !m.isTest).length || 1;
|
|
1809
|
+
const maxSize = Math.max(0, ...[...byLabel.values()].map((v) => v.length));
|
|
1810
|
+
let groupsMap = byLabel;
|
|
1811
|
+
if (maxSize > nonTest * 0.5) {
|
|
1812
|
+
groupsMap = new Map();
|
|
1813
|
+
for (const m of modules) { const k = containerOf(m); if (!groupsMap.has(k)) groupsMap.set(k, []); groupsMap.get(k).push(m.id); }
|
|
1814
|
+
}
|
|
1815
|
+
const clusters = [];
|
|
1816
|
+
const clusterOf = new Map();
|
|
1817
|
+
for (const members of groupsMap.values()) {
|
|
1818
|
+
const sorted = members.slice().sort();
|
|
1819
|
+
const cid = "cluster:" + sorted[0];
|
|
1820
|
+
const pkgCount = {}, layerCount = {};
|
|
1821
|
+
for (const id of sorted) { const m = moduleByRel.get(id); const p = m.package || containerOf(m).replace(/^dir:/, ""); pkgCount[p] = (pkgCount[p] || 0) + 1; layerCount[m.layer] = (layerCount[m.layer] || 0) + 1; }
|
|
1822
|
+
const dominantPackage = Object.keys(pkgCount).sort((a, b) => pkgCount[b] - pkgCount[a] || (a < b ? -1 : 1))[0] || null;
|
|
1823
|
+
const dominantLayer = Object.keys(layerCount).sort((a, b) => layerCount[b] - layerCount[a] || (a < b ? -1 : 1))[0] || "support";
|
|
1824
|
+
const packages = Object.keys(pkgCount).sort();
|
|
1825
|
+
const clabel = packages.length === 1 ? String(dominantPackage).replace(/^@[^/]+\//, "") : (sorted[0].split("/")[0] + " · " + dominantLayer);
|
|
1826
|
+
for (const id of sorted) clusterOf.set(id, cid);
|
|
1827
|
+
clusters.push({ id: cid, label: clabel, size: sorted.length, members: sorted, dominantPackage, dominantLayer, packages });
|
|
1828
|
+
}
|
|
1829
|
+
clusters.sort((a, b) => b.size - a.size || (a.id < b.id ? -1 : 1));
|
|
1830
|
+
return { clusters, clusterOf };
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
// Surprising connections: import edges that bridge distant clusters / violate layering / cross groups.
|
|
1834
|
+
const LAYER_RANK_INWARD = { presentation: 0, application: 1, domain: 2, infrastructure: 3 };
|
|
1835
|
+
function visComputeSurprising(edges, callEdges, moduleByRel, clusterOf, groupOfContainer, containerOf) {
|
|
1836
|
+
const pairCount = new Map(); // O(E) cluster-pair index → O(1) bridge test
|
|
1837
|
+
for (const e of edges) {
|
|
1838
|
+
if (e.kind !== "import") continue;
|
|
1839
|
+
const ca = clusterOf.get(e.from), cb = clusterOf.get(e.to);
|
|
1840
|
+
if (!ca || !cb || ca === cb) continue;
|
|
1841
|
+
const k = ca + "|" + cb; pairCount.set(k, (pairCount.get(k) || 0) + 1);
|
|
1842
|
+
}
|
|
1843
|
+
const callSym = new Map();
|
|
1844
|
+
for (const ce of callEdges) { const k = ce.from + "|" + ce.to; if (!callSym.has(k)) callSym.set(k, []); if (callSym.get(k).length < 4 && !callSym.get(k).includes(ce.symbol)) callSym.get(k).push(ce.symbol); }
|
|
1845
|
+
const out = [];
|
|
1846
|
+
const seen = new Set();
|
|
1847
|
+
for (const e of edges) {
|
|
1848
|
+
if (e.kind !== "import") continue;
|
|
1849
|
+
const a = moduleByRel.get(e.from), b = moduleByRel.get(e.to);
|
|
1850
|
+
if (!a || !b) continue;
|
|
1851
|
+
const ca = clusterOf.get(e.from), cb = clusterOf.get(e.to);
|
|
1852
|
+
if (!ca || !cb || ca === cb) continue;
|
|
1853
|
+
const pk = e.from + "→" + e.to;
|
|
1854
|
+
if (seen.has(pk)) continue;
|
|
1855
|
+
seen.add(pk);
|
|
1856
|
+
let score = 0; const reasons = [];
|
|
1857
|
+
const la = LAYER_RANK_INWARD[a.layer], lb = LAYER_RANK_INWARD[b.layer];
|
|
1858
|
+
if (la != null && lb != null && la > lb) { score += 2; reasons.push(a.layer + "→" + b.layer + " (outward)"); }
|
|
1859
|
+
if ((pairCount.get(ca + "|" + cb) || 0) <= 1) { score += 2; reasons.push("bridge"); }
|
|
1860
|
+
const ga = groupOfContainer.get(containerOf(a)), gb = groupOfContainer.get(containerOf(b));
|
|
1861
|
+
if (ga && gb && ga !== gb) { score += 1; reasons.push("cross-group"); }
|
|
1862
|
+
if (score <= 0) continue;
|
|
1863
|
+
out.push({ from: e.from, to: e.to, score, reason: reasons.join(", "), sampleSymbols: callSym.get(e.from + "|" + e.to) || [] });
|
|
1864
|
+
}
|
|
1865
|
+
out.sort((x, y) => y.score - x.score || (x.from < y.from ? -1 : x.from > y.from ? 1 : 0));
|
|
1866
|
+
return out.slice(0, 20);
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
function visBuildMap(root) {
|
|
1870
|
+
const startedAt = Date.now();
|
|
1871
|
+
const files = visWalk(root);
|
|
1872
|
+
const pkgs = visScanPackages(root);
|
|
1873
|
+
const planning = visReadPlanning(root);
|
|
1874
|
+
|
|
1875
|
+
// Build bin-file set: package.json `bin` entries → CLI entry points.
|
|
1876
|
+
// Bin / main paths often point to compiled output (dist/X.js) that's filtered out of the
|
|
1877
|
+
// scanned tree. Register source-tree fallbacks (src/X.{ts,tsx,js,mjs,cjs}) so the actual
|
|
1878
|
+
// source file gets recognized as the entry point at scan time.
|
|
1879
|
+
const binFiles = new Map(); // rel path → cli name
|
|
1880
|
+
const COMPILED_SEGMENT_RE = /(?:^|\/)(?:dist|build|lib|out)\//;
|
|
1881
|
+
const SOURCE_EXTS = [".ts", ".tsx", ".js", ".mjs", ".cjs"];
|
|
1882
|
+
const registerBinPath = (rel, name, prefix) => {
|
|
1883
|
+
const fullKey = (prefix || "") + rel;
|
|
1884
|
+
binFiles.set(fullKey, name);
|
|
1885
|
+
// Source-tree fallback: dist/<stem>.{js,mjs,cjs} → src/<stem>.{ts,tsx,js,mjs,cjs}
|
|
1886
|
+
if (COMPILED_SEGMENT_RE.test(rel)) {
|
|
1887
|
+
const srcStem = rel.replace(COMPILED_SEGMENT_RE, (s) => s.replace(/(?<=\/|^)(dist|build|lib|out)\//, "src/")).replace(/\.(js|mjs|cjs)$/, "");
|
|
1888
|
+
for (const ext of SOURCE_EXTS) {
|
|
1889
|
+
const altRel = srcStem + ext;
|
|
1890
|
+
if (!binFiles.has((prefix || "") + altRel)) {
|
|
1891
|
+
binFiles.set((prefix || "") + altRel, name);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
};
|
|
1896
|
+
for (const p of pkgs) {
|
|
1897
|
+
const pkgDir = p.path === "." ? "" : p.path;
|
|
1898
|
+
const pkgJsonPath = path.join(root, pkgDir, "package.json");
|
|
1899
|
+
try {
|
|
1900
|
+
const pj = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
1901
|
+
const bin = pj.bin;
|
|
1902
|
+
if (typeof bin === "string") {
|
|
1903
|
+
const rel = path.posix.join(pkgDir, bin).replace(/^\.\//, "");
|
|
1904
|
+
registerBinPath(rel, pj.name);
|
|
1905
|
+
} else if (bin && typeof bin === "object") {
|
|
1906
|
+
for (const [name, file] of Object.entries(bin)) {
|
|
1907
|
+
if (typeof file !== "string") continue;
|
|
1908
|
+
const rel = path.posix.join(pkgDir, file).replace(/^\.\//, "");
|
|
1909
|
+
registerBinPath(rel, name);
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
if (pj.main) {
|
|
1913
|
+
const rel = path.posix.join(pkgDir, pj.main).replace(/^\.\//, "");
|
|
1914
|
+
registerBinPath(rel, "main:" + pj.name, "__main__:");
|
|
1915
|
+
}
|
|
1916
|
+
} catch { /* empty */ }
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
const langCounts = {};
|
|
1920
|
+
const modules = [];
|
|
1921
|
+
const moduleByRel = new Map();
|
|
1922
|
+
const totalLoc = { value: 0 };
|
|
1923
|
+
// Per-module rich data
|
|
1924
|
+
const perFile = new Map();
|
|
1925
|
+
const rationaleAll = []; // graphify-style inline rationale (NOTE/WHY/HACK/…) across all files
|
|
1926
|
+
|
|
1927
|
+
for (const abs of files) {
|
|
1928
|
+
const rel = path.relative(root, abs).split(path.sep).join("/");
|
|
1929
|
+
const lang = visLangFor(abs);
|
|
1930
|
+
langCounts[lang] = (langCounts[lang] || 0) + 1;
|
|
1931
|
+
let size = 0, loc = 0;
|
|
1932
|
+
let parsedImports = [], exports = [], sinks = [], routes = [], sinkSites = [], symbols = [];
|
|
1933
|
+
let content = "";
|
|
1934
|
+
try {
|
|
1935
|
+
const stat = fs.statSync(abs);
|
|
1936
|
+
size = stat.size;
|
|
1937
|
+
if (size < 1024 * 1024 && lang !== "other") {
|
|
1938
|
+
content = fs.readFileSync(abs, "utf-8");
|
|
1939
|
+
loc = content.split("\n").length;
|
|
1940
|
+
totalLoc.value += loc;
|
|
1941
|
+
if (VIS_CODE_LANGS.has(lang)) {
|
|
1942
|
+
// Use raw content for export/JSDoc extraction (need comments) and stripped for sink/import detection
|
|
1943
|
+
const stripped = content
|
|
1944
|
+
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
1945
|
+
.replace(/(^|[^:])\/\/.*$/gm, "$1");
|
|
1946
|
+
parsedImports = visParseImports(stripped, lang);
|
|
1947
|
+
exports = visExtractExports(content, lang);
|
|
1948
|
+
sinks = visDetectSinks(stripped);
|
|
1949
|
+
sinkSites = visFindSinkSites(content, lang);
|
|
1950
|
+
routes = visDetectRoutes(stripped);
|
|
1951
|
+
symbols = visBuildSymbols(exports, content, lang); // symbol-level nodes (from untruncated exports + decls)
|
|
1952
|
+
}
|
|
1953
|
+
// Inline rationale works for any commented language (incl. markdown), not just code langs.
|
|
1954
|
+
for (const r of visExtractRationale(content, lang, rel)) rationaleAll.push(r);
|
|
1955
|
+
}
|
|
1956
|
+
} catch { /* empty */ }
|
|
1957
|
+
|
|
1958
|
+
const isTest = visIsTest(rel);
|
|
1959
|
+
const pkg = pkgs.find((p) => p.path !== "." && rel.startsWith(p.path + "/"))?.name
|
|
1960
|
+
|| (pkgs[0]?.path === "." ? pkgs[0].name : null);
|
|
1961
|
+
const isBin = binFiles.has(rel);
|
|
1962
|
+
|
|
1963
|
+
const m = {
|
|
1964
|
+
id: rel,
|
|
1965
|
+
path: rel,
|
|
1966
|
+
language: lang,
|
|
1967
|
+
size,
|
|
1968
|
+
loc,
|
|
1969
|
+
isTest,
|
|
1970
|
+
package: pkg,
|
|
1971
|
+
exports: exports.slice(0, 30),
|
|
1972
|
+
symbols,
|
|
1973
|
+
sinks,
|
|
1974
|
+
sinkSites: sinkSites.slice(0, 10),
|
|
1975
|
+
routes: routes.slice(0, 20),
|
|
1976
|
+
entryPoint: null,
|
|
1977
|
+
};
|
|
1978
|
+
if (isBin) {
|
|
1979
|
+
m.entryPoint = { kind: "cli", name: binFiles.get(rel) };
|
|
1980
|
+
} else if (routes.length > 0 && !isTest) {
|
|
1981
|
+
m.entryPoint = { kind: "http", routes: routes.slice(0, 8) };
|
|
1982
|
+
}
|
|
1983
|
+
// Mark package main exports as library entry points
|
|
1984
|
+
const mainKey = "__main__:" + rel;
|
|
1985
|
+
if (binFiles.has(mainKey)) {
|
|
1986
|
+
m.entryPoint = m.entryPoint || { kind: "library", name: binFiles.get(mainKey).replace(/^main:/, "") };
|
|
1987
|
+
}
|
|
1988
|
+
m.layer = visClassifyLayer(rel, sinks, routes.length > 0, isBin, exports.length > 0);
|
|
1989
|
+
modules.push(m);
|
|
1990
|
+
moduleByRel.set(rel, m);
|
|
1991
|
+
perFile.set(rel, { parsedImports, content, stripped: content });
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
// Resolve local imports → edges with symbol-level dataflow
|
|
1995
|
+
const tsLikeExts = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
|
|
1996
|
+
const tsxIndexExts = tsLikeExts;
|
|
1997
|
+
const edges = [];
|
|
1998
|
+
const callEdges = []; // { from, to, symbol }
|
|
1999
|
+
|
|
2000
|
+
// Build workspace-package → entry-file lookup so cross-package imports become real edges
|
|
2001
|
+
const workspaceEntryByName = new Map();
|
|
2002
|
+
for (const p of pkgs) {
|
|
2003
|
+
const pkgDir = p.path === "." ? "" : p.path;
|
|
2004
|
+
const pkgJsonPath = path.join(root, pkgDir, "package.json");
|
|
2005
|
+
try {
|
|
2006
|
+
const pj = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
2007
|
+
const candidates = [];
|
|
2008
|
+
if (pj.main) candidates.push(pj.main);
|
|
2009
|
+
if (pj.module) candidates.push(pj.module);
|
|
2010
|
+
if (pj.exports) {
|
|
2011
|
+
const collect = (v) => {
|
|
2012
|
+
if (typeof v === "string") candidates.push(v);
|
|
2013
|
+
else if (v && typeof v === "object") for (const k of Object.values(v)) collect(k);
|
|
2014
|
+
};
|
|
2015
|
+
collect(pj.exports);
|
|
2016
|
+
}
|
|
2017
|
+
// Also try src/index.{ts,js}
|
|
2018
|
+
candidates.push("src/index.ts", "src/index.js", "index.ts", "index.js");
|
|
2019
|
+
let entry = null;
|
|
2020
|
+
for (const c of candidates) {
|
|
2021
|
+
if (typeof c !== "string") continue;
|
|
2022
|
+
const rel = path.posix.normalize(path.posix.join(pkgDir, c.replace(/^\.\//, ""))).replace(/\.\.\//g, "");
|
|
2023
|
+
for (const ext of ["", ...tsLikeExts]) {
|
|
2024
|
+
const r = ext ? rel.replace(/\.[^/.]+$/, "") + ext : rel;
|
|
2025
|
+
if (moduleByRel.has(r)) { entry = r; break; }
|
|
2026
|
+
}
|
|
2027
|
+
if (entry) break;
|
|
2028
|
+
// Try as-is
|
|
2029
|
+
if (moduleByRel.has(rel)) { entry = rel; break; }
|
|
2030
|
+
}
|
|
2031
|
+
if (entry) workspaceEntryByName.set(pj.name, entry);
|
|
2032
|
+
} catch { /* empty */ }
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
const resolveSpec = (fromDir, spec) => {
|
|
2036
|
+
// Relative path
|
|
2037
|
+
if (spec.startsWith(".") || spec.startsWith("/")) {
|
|
2038
|
+
const base = path.posix.normalize(path.posix.join(fromDir, spec));
|
|
2039
|
+
// Build stem candidates: original, plus extension-stripped (NodeNext: ./foo.js → ./foo.ts on disk)
|
|
2040
|
+
const stems = [base];
|
|
2041
|
+
if (/\.(js|mjs|cjs|jsx)$/.test(base)) {
|
|
2042
|
+
stems.push(base.replace(/\.(js|mjs|cjs|jsx)$/, ""));
|
|
2043
|
+
}
|
|
2044
|
+
for (const stem of stems) {
|
|
2045
|
+
for (const ext of ["", ...tsLikeExts]) {
|
|
2046
|
+
const c = ext ? stem + ext : stem;
|
|
2047
|
+
if (moduleByRel.has(c)) return c;
|
|
2048
|
+
}
|
|
2049
|
+
for (const ext of tsxIndexExts) {
|
|
2050
|
+
const c = path.posix.join(stem, "index" + ext);
|
|
2051
|
+
if (moduleByRel.has(c)) return c;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
return null;
|
|
2055
|
+
}
|
|
2056
|
+
// Workspace package: try exact match, then with subpath
|
|
2057
|
+
if (workspaceEntryByName.has(spec)) return workspaceEntryByName.get(spec);
|
|
2058
|
+
const slash = spec.indexOf("/", spec.startsWith("@") ? spec.indexOf("/") + 1 : 0);
|
|
2059
|
+
if (slash > 0) {
|
|
2060
|
+
const pkgName = spec.slice(0, slash);
|
|
2061
|
+
if (workspaceEntryByName.has(pkgName)) return workspaceEntryByName.get(pkgName);
|
|
2062
|
+
}
|
|
2063
|
+
return null;
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
for (const m of modules) {
|
|
2067
|
+
if (m.language !== "typescript" && m.language !== "javascript") continue;
|
|
2068
|
+
const fromDir = path.posix.dirname(m.path);
|
|
2069
|
+
const file = perFile.get(m.path);
|
|
2070
|
+
if (!file) continue;
|
|
2071
|
+
const usedLocals = new Map(); // local name -> { resolved, importedName }
|
|
2072
|
+
for (const imp of file.parsedImports) {
|
|
2073
|
+
const resolved = resolveSpec(fromDir, imp.specifier);
|
|
2074
|
+
if (!resolved) {
|
|
2075
|
+
edges.push({ from: m.id, to: imp.specifier, kind: "external", confidence: "EXTRACTED", resolved: false });
|
|
2076
|
+
continue;
|
|
2077
|
+
}
|
|
2078
|
+
edges.push({ from: m.id, to: resolved, kind: imp.reExport ? "re-export" : "import", confidence: "EXTRACTED" });
|
|
2079
|
+
// Re-exports don't introduce local usage — they pass the symbol through to the
|
|
2080
|
+
// importer of THIS module. We capture them separately for re-export traversal in flow BFS.
|
|
2081
|
+
if (imp.reExport) continue;
|
|
2082
|
+
if (imp.default) usedLocals.set(imp.default, { resolved, importedName: "default" });
|
|
2083
|
+
if (imp.namespace) usedLocals.set(imp.namespace, { resolved, importedName: "*" });
|
|
2084
|
+
for (const n of imp.names || []) {
|
|
2085
|
+
usedLocals.set(n.local, { resolved, importedName: n.imported });
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
// For each imported local, scan for call sites: `localName(` or `localName.x(` (member call)
|
|
2089
|
+
if (usedLocals.size > 0) {
|
|
2090
|
+
const text = file.content || "";
|
|
2091
|
+
for (const [local, ref] of usedLocals) {
|
|
2092
|
+
const safe = local.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2093
|
+
const callRe = new RegExp("\\b" + safe + "\\s*(?:\\.[A-Za-z_$][\\w$]*\\s*)?\\(", "g");
|
|
2094
|
+
let count = 0;
|
|
2095
|
+
while (callRe.exec(text)) { count++; if (count > 100) break; }
|
|
2096
|
+
if (count > 0) {
|
|
2097
|
+
// INFERRED: regex call-site heuristic. AMBIGUOUS when only ever member-called (x.y()) —
|
|
2098
|
+
// the called member is not necessarily the imported symbol.
|
|
2099
|
+
const directRe = new RegExp("\\b" + safe + "\\s*\\(", "g");
|
|
2100
|
+
const confidence = directRe.test(text) ? "INFERRED" : "AMBIGUOUS";
|
|
2101
|
+
callEdges.push({ from: m.id, to: ref.resolved, symbol: ref.importedName, count, confidence });
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
// Containers: prefer packages; fall back to top-level dirs
|
|
2108
|
+
const containers = [];
|
|
2109
|
+
if (pkgs.length > 1) {
|
|
2110
|
+
for (const p of pkgs) {
|
|
2111
|
+
if (p.path === ".") continue;
|
|
2112
|
+
containers.push({
|
|
2113
|
+
id: "pkg:" + p.name,
|
|
2114
|
+
name: p.name,
|
|
2115
|
+
path: p.path,
|
|
2116
|
+
kind: "package",
|
|
2117
|
+
description: p.description,
|
|
2118
|
+
moduleCount: modules.filter((m) => m.path.startsWith(p.path + "/")).length,
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
} else {
|
|
2122
|
+
const topDirs = new Set();
|
|
2123
|
+
for (const m of modules) {
|
|
2124
|
+
const first = m.path.split("/")[0];
|
|
2125
|
+
if (first && !first.includes(".")) topDirs.add(first);
|
|
2126
|
+
}
|
|
2127
|
+
for (const d of topDirs) {
|
|
2128
|
+
containers.push({
|
|
2129
|
+
id: "dir:" + d, name: d, path: d, kind: "directory", description: null,
|
|
2130
|
+
moduleCount: modules.filter((m) => m.path.startsWith(d + "/")).length,
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
const containerOf = (m) => {
|
|
2135
|
+
if (m.package) return "pkg:" + m.package;
|
|
2136
|
+
const first = m.path.split("/")[0];
|
|
2137
|
+
return "dir:" + first;
|
|
2138
|
+
};
|
|
2139
|
+
|
|
2140
|
+
// Functional groups (CodeViz-style nested containers)
|
|
2141
|
+
const groups = applyGroupsCuration(deriveGroups(containers, pkgs, root), root);
|
|
2142
|
+
|
|
2143
|
+
// In-degree / out-degree maps from import edges — used for "top files" ranking.
|
|
2144
|
+
const inDeg = new Map();
|
|
2145
|
+
const outDeg = new Map();
|
|
2146
|
+
for (const e of edges) {
|
|
2147
|
+
if (e.kind !== "import") continue;
|
|
2148
|
+
outDeg.set(e.from, (outDeg.get(e.from) || 0) + 1);
|
|
2149
|
+
inDeg.set(e.to, (inDeg.get(e.to) || 0) + 1);
|
|
2150
|
+
}
|
|
2151
|
+
// Non-test degree (excludes test-originated edges) — for god-node / hotspot ranking, so test
|
|
2152
|
+
// fixtures don't inflate "most depended-on".
|
|
2153
|
+
const inDegNT = new Map();
|
|
2154
|
+
const outDegNT = new Map();
|
|
2155
|
+
for (const e of edges) {
|
|
2156
|
+
if (e.kind !== "import") continue;
|
|
2157
|
+
const fm = moduleByRel.get(e.from);
|
|
2158
|
+
if (fm && fm.isTest) continue;
|
|
2159
|
+
outDegNT.set(e.from, (outDegNT.get(e.from) || 0) + 1);
|
|
2160
|
+
inDegNT.set(e.to, (inDegNT.get(e.to) || 0) + 1);
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
function computeTopFiles(container) {
|
|
2164
|
+
const mods = modules.filter((m) => containerOf(m) === container.id && !m.isTest);
|
|
2165
|
+
if (mods.length === 0) return [];
|
|
2166
|
+
const medianLoc = (() => {
|
|
2167
|
+
const arr = mods.map((m) => m.loc || 0).sort((a, b) => a - b);
|
|
2168
|
+
return arr[Math.floor(arr.length / 2)] || 0;
|
|
2169
|
+
})();
|
|
2170
|
+
const scored = mods.map((m) => {
|
|
2171
|
+
let score = 0;
|
|
2172
|
+
if (m.entryPoint) score += 6;
|
|
2173
|
+
if (m.routes && m.routes.length > 0) score += 3;
|
|
2174
|
+
score += Math.log2(1 + (m.loc || 0));
|
|
2175
|
+
score += Math.log2(1 + (outDeg.get(m.id) || 0));
|
|
2176
|
+
score += Math.log2(1 + (inDeg.get(m.id) || 0));
|
|
2177
|
+
if (/\/index\.(?:ts|tsx|js|mjs|cjs)$/.test(m.path)) score += 4;
|
|
2178
|
+
if ((m.exports || []).some((e) => e.doc)) score += 2;
|
|
2179
|
+
// Reason label
|
|
2180
|
+
let reason = "core file";
|
|
2181
|
+
if (m.entryPoint) {
|
|
2182
|
+
reason = m.entryPoint.kind === "cli" ? "CLI entry"
|
|
2183
|
+
: m.entryPoint.kind === "http" ? "HTTP handler"
|
|
2184
|
+
: "library entry";
|
|
2185
|
+
} else if (m.routes && m.routes.length > 0) reason = "HTTP handler";
|
|
2186
|
+
else if (/\/index\.(?:ts|tsx|js|mjs|cjs)$/.test(m.path)) reason = "package index";
|
|
2187
|
+
else if ((inDeg.get(m.id) || 0) >= 3) reason = "most depended-on";
|
|
2188
|
+
else if ((outDeg.get(m.id) || 0) >= 8) reason = "orchestrator";
|
|
2189
|
+
else if ((m.loc || 0) > medianLoc * 1.5) reason = "largest";
|
|
2190
|
+
return { path: m.path, reason, score: +score.toFixed(2), loc: m.loc || 0 };
|
|
2191
|
+
});
|
|
2192
|
+
scored.sort((a, b) => b.score - a.score || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
2193
|
+
const cap = mods.length < 6 ? 3 : 5;
|
|
2194
|
+
return scored.slice(0, cap);
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
for (const c of containers) {
|
|
2198
|
+
c.topFiles = computeTopFiles(c);
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
// Cross-container edges (collapsed dataflow at the architecture level)
|
|
2202
|
+
const containerEdgeMap = new Map(); // "from→to" -> { from, to, count, symbolFreq }
|
|
2203
|
+
for (const e of edges) {
|
|
2204
|
+
if (e.kind !== "import") continue;
|
|
2205
|
+
const a = moduleByRel.get(e.from), b = moduleByRel.get(e.to);
|
|
2206
|
+
if (!a || !b) continue;
|
|
2207
|
+
const ca = containerOf(a), cb = containerOf(b);
|
|
2208
|
+
if (ca === cb) continue;
|
|
2209
|
+
const key = ca + "→" + cb;
|
|
2210
|
+
if (!containerEdgeMap.has(key)) containerEdgeMap.set(key, { from: ca, to: cb, count: 0, symbolFreq: new Map(), callCount: 0 });
|
|
2211
|
+
containerEdgeMap.get(key).count++;
|
|
2212
|
+
}
|
|
2213
|
+
// Layer in symbol-level call data
|
|
2214
|
+
for (const ce of callEdges) {
|
|
2215
|
+
const a = moduleByRel.get(ce.from), b = moduleByRel.get(ce.to);
|
|
2216
|
+
if (!a || !b) continue;
|
|
2217
|
+
const ca = containerOf(a), cb = containerOf(b);
|
|
2218
|
+
if (ca === cb) continue;
|
|
2219
|
+
const key = ca + "→" + cb;
|
|
2220
|
+
const agg = containerEdgeMap.get(key);
|
|
2221
|
+
if (!agg) continue;
|
|
2222
|
+
agg.callCount += ce.count || 1;
|
|
2223
|
+
agg.symbolFreq.set(ce.symbol, (agg.symbolFreq.get(ce.symbol) || 0) + (ce.count || 1));
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// Classify each container edge with a relationship verb (CodeViz-style labels)
|
|
2227
|
+
const pkgHasReactDep = (pkgName) => {
|
|
2228
|
+
const p = pkgs.find((x) => x.name === pkgName);
|
|
2229
|
+
if (!p) return false;
|
|
2230
|
+
const deps = (p.dependencies || []).concat(p.peerDependencies || []);
|
|
2231
|
+
return deps.some((d) => /^(react|preact|solid-js|svelte)$/.test(d));
|
|
2232
|
+
};
|
|
2233
|
+
function classifyContainerEdge(edge) {
|
|
2234
|
+
const symbols = [...edge.symbolFreq.keys()];
|
|
2235
|
+
const symbolSamples = [...edge.symbolFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([s]) => s);
|
|
2236
|
+
const toPkgName = edge.to.replace(/^pkg:/, "");
|
|
2237
|
+
const labels = [];
|
|
2238
|
+
const matchesAny = (re) => symbols.some((s) => re.test(s));
|
|
2239
|
+
const matchesAll = (re) => symbols.length > 0 && symbols.every((s) => re.test(s));
|
|
2240
|
+
|
|
2241
|
+
// Priority-ordered detection
|
|
2242
|
+
// 1. Renders — uppercase exports + React-ish callee
|
|
2243
|
+
if (pkgHasReactDep(toPkgName) && symbols.some((s) => /^[A-Z]/.test(s))) labels.push("Renders");
|
|
2244
|
+
// 2. Sends Events
|
|
2245
|
+
if (matchesAny(/^(emit|dispatch|publish|broadcast|notify|fire|trigger)|sendEvent|EventBus|EventEmitter|MessageBus|^bus$|^events?$|subscribe|onEvent/i)) labels.push("Sends Events");
|
|
2246
|
+
// 3. Persists — callee has FS-write/db sinks
|
|
2247
|
+
const toMods = modules.filter((m) => containerOf(m) === edge.to);
|
|
2248
|
+
const toSinks = new Set();
|
|
2249
|
+
for (const m of toMods) for (const s of (m.sinks || [])) toSinks.add(s);
|
|
2250
|
+
if (toSinks.has("fs:write") || toSinks.has("db:sql") || toSinks.has("db:orm")) labels.push("Persists");
|
|
2251
|
+
// 4. Updates
|
|
2252
|
+
if (matchesAny(/^(set|update|mutate|patch|put|replace|remove|delete)[A-Z]|^use[A-Z]\w*State$/)) labels.push("Updates");
|
|
2253
|
+
// 5. Reads State (excluded if Updates already matched)
|
|
2254
|
+
if (!labels.includes("Updates") && matchesAny(/^(get|read|fetch|load|find|list|query|select)[A-Z]/)) labels.push("Reads State");
|
|
2255
|
+
// 6. Configures
|
|
2256
|
+
if (matchesAny(/^(config|configure|setup|init|initialize|register|bootstrap|provide|wire)/i)) labels.push("Configures");
|
|
2257
|
+
// 7. Analyzes
|
|
2258
|
+
if (matchesAny(/^(analyz|inspect|check|validat|verify|audit|lint|scan)/i)) labels.push("Analyzes");
|
|
2259
|
+
// 8. Executes Actions
|
|
2260
|
+
if (matchesAny(/^(run|exec|execute|invoke|perform|do[A-Z])/i)) labels.push("Executes Actions");
|
|
2261
|
+
// 9. Uses — type-only or sparse
|
|
2262
|
+
if (edge.callCount === 0 || symbols.length < 3) labels.push("Uses");
|
|
2263
|
+
// 10. Calls — fallback
|
|
2264
|
+
if (labels.length === 0) labels.push("Calls");
|
|
2265
|
+
return { label: labels[0], labels, symbolSamples };
|
|
2266
|
+
}
|
|
2267
|
+
for (const edge of containerEdgeMap.values()) {
|
|
2268
|
+
const classification = classifyContainerEdge(edge);
|
|
2269
|
+
edge.label = classification.label;
|
|
2270
|
+
edge.labels = classification.labels;
|
|
2271
|
+
edge.symbolSamples = classification.symbolSamples;
|
|
2272
|
+
delete edge.symbolFreq; // not serialized
|
|
2273
|
+
}
|
|
2274
|
+
const containerEdges = [...containerEdgeMap.values()];
|
|
2275
|
+
|
|
2276
|
+
// Entry points & sinks summary
|
|
2277
|
+
const entryPoints = modules
|
|
2278
|
+
.filter((m) => m.entryPoint)
|
|
2279
|
+
.map((m) => ({
|
|
2280
|
+
id: m.id,
|
|
2281
|
+
path: m.path,
|
|
2282
|
+
package: m.package,
|
|
2283
|
+
kind: m.entryPoint.kind,
|
|
2284
|
+
name: m.entryPoint.name || null,
|
|
2285
|
+
routes: m.entryPoint.routes || null,
|
|
2286
|
+
}));
|
|
2287
|
+
|
|
2288
|
+
const sinkNodes = modules
|
|
2289
|
+
.filter((m) => m.sinks && m.sinks.length > 0)
|
|
2290
|
+
.map((m) => ({ id: m.id, path: m.path, package: m.package, sinks: m.sinks }));
|
|
2291
|
+
|
|
2292
|
+
// Compute depth from entry points (BFS over dependency edges).
|
|
2293
|
+
// Re-export edges (`export { x } from "./x"`, common in package index.ts hubs) are real
|
|
2294
|
+
// reachability edges — include them so index hubs connect to their implementations instead
|
|
2295
|
+
// of registering as zero-out-degree dead-ends.
|
|
2296
|
+
const adj = new Map();
|
|
2297
|
+
for (const e of edges) {
|
|
2298
|
+
if (e.kind !== "import" && e.kind !== "re-export") continue;
|
|
2299
|
+
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
2300
|
+
adj.get(e.from).push(e.to);
|
|
2301
|
+
}
|
|
2302
|
+
const depth = new Map();
|
|
2303
|
+
const queue = [];
|
|
2304
|
+
for (const ep of entryPoints) { depth.set(ep.id, 0); queue.push(ep.id); }
|
|
2305
|
+
while (queue.length) {
|
|
2306
|
+
const id = queue.shift();
|
|
2307
|
+
const d = depth.get(id);
|
|
2308
|
+
for (const next of (adj.get(id) || [])) {
|
|
2309
|
+
if (!depth.has(next)) { depth.set(next, d + 1); queue.push(next); }
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
for (const m of modules) m.depth = depth.has(m.id) ? depth.get(m.id) : null;
|
|
2313
|
+
|
|
2314
|
+
// ====================== Flow extraction (swim-lane sequences) ======================
|
|
2315
|
+
// For each entry point, walk cross-container edges + collect sinks reached.
|
|
2316
|
+
// Each cross-package hop and each sink touched is a numbered step.
|
|
2317
|
+
const SINK_LABEL = {
|
|
2318
|
+
"fs:write": "Filesystem", "fs:read": "Filesystem",
|
|
2319
|
+
"net:fetch": "Network", "net:http": "Network",
|
|
2320
|
+
"db:sql": "Database", "db:orm": "Database",
|
|
2321
|
+
"cli:io": "Stdout", "process:exec": "Subprocess",
|
|
2322
|
+
"process:exit": "Process", "ai:call": "AI provider", "env:read": "Environment",
|
|
2323
|
+
};
|
|
2324
|
+
const sinkBoxId = (kind) => "sink:" + (SINK_LABEL[kind] || kind);
|
|
2325
|
+
const containerOf2 = (mod) => mod ? (mod.package ? "pkg:" + mod.package : "dir:" + mod.path.split("/")[0]) : null;
|
|
2326
|
+
const containerAdj = new Map();
|
|
2327
|
+
for (const e of containerEdges) {
|
|
2328
|
+
if (!containerAdj.has(e.from)) containerAdj.set(e.from, []);
|
|
2329
|
+
containerAdj.get(e.from).push({ to: e.to, count: e.count });
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
// Build a per-module callEdge index so we can walk concrete symbol-level edges.
|
|
2333
|
+
const callOutByModule = new Map();
|
|
2334
|
+
for (const ce of callEdges) {
|
|
2335
|
+
if (!callOutByModule.has(ce.from)) callOutByModule.set(ce.from, []);
|
|
2336
|
+
callOutByModule.get(ce.from).push(ce);
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
// Re-export adjacency: when a module is a re-export hub (only `export * from`/`export { } from`),
|
|
2340
|
+
// its public surface lives in the targets. The flow BFS treats these as transparent hops so
|
|
2341
|
+
// library entries trace through index.ts into actual implementations.
|
|
2342
|
+
const reExportTargetsByModule = new Map();
|
|
2343
|
+
for (const m of modules) {
|
|
2344
|
+
const file = perFile.get(m.path);
|
|
2345
|
+
if (!file) continue;
|
|
2346
|
+
const targets = [];
|
|
2347
|
+
const fromDir = path.posix.dirname(m.path);
|
|
2348
|
+
for (const imp of file.parsedImports) {
|
|
2349
|
+
if (!imp.reExport) continue;
|
|
2350
|
+
const resolved = resolveSpec(fromDir, imp.specifier);
|
|
2351
|
+
if (resolved && resolved !== m.id) targets.push(resolved);
|
|
2352
|
+
}
|
|
2353
|
+
if (targets.length > 0) reExportTargetsByModule.set(m.id, targets);
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// SINK_LABEL_PHRASE provides natural-language phrasing for each sink kind
|
|
2357
|
+
const SINK_PHRASE = {
|
|
2358
|
+
"fs:write": "writes to the filesystem",
|
|
2359
|
+
"fs:read": "reads from the filesystem",
|
|
2360
|
+
"net:fetch": "calls an external HTTP API",
|
|
2361
|
+
"net:http": "issues an HTTP request",
|
|
2362
|
+
"db:sql": "runs a SQL query",
|
|
2363
|
+
"db:orm": "issues an ORM database call",
|
|
2364
|
+
"cli:io": "writes to stdout/stderr",
|
|
2365
|
+
"process:exec": "spawns a subprocess",
|
|
2366
|
+
"process:exit": "terminates the process",
|
|
2367
|
+
"ai:call": "calls an AI provider",
|
|
2368
|
+
"env:read": "reads environment variables",
|
|
2369
|
+
};
|
|
2370
|
+
|
|
2371
|
+
function relShort(p) { return (p || "").split("/").slice(-2).join("/"); }
|
|
2372
|
+
function docFor(mod, symbol) {
|
|
2373
|
+
if (!mod || !mod.exports) return null;
|
|
2374
|
+
const e = mod.exports.find((x) => x.name === symbol);
|
|
2375
|
+
return e ? e.doc : null;
|
|
2376
|
+
}
|
|
2377
|
+
function describeEntry(ep, mod) {
|
|
2378
|
+
const exportSummary = mod && mod.exports && mod.exports.length
|
|
2379
|
+
? mod.exports.slice(0, 3).map((e) => e.kind + " `" + e.name + "`").join(", ")
|
|
2380
|
+
: null;
|
|
2381
|
+
if (ep.kind === "cli") {
|
|
2382
|
+
const commands = (mod?.exports || []).filter((e) => e.kind === "command");
|
|
2383
|
+
const cmdList = commands.length ? " Dispatches commands: " + commands.slice(0, 6).map((c) => "`" + c.name + "`").join(", ") + (commands.length > 6 ? ", …" : "") + "." : "";
|
|
2384
|
+
return "User runs `" + (ep.name || "cli") + "` from the shell. Entry is " + ep.path + "." + cmdList;
|
|
2385
|
+
}
|
|
2386
|
+
if (ep.kind === "http") {
|
|
2387
|
+
const r = (ep.routes && ep.routes[0]) ? (ep.routes[0].method + " " + ep.routes[0].path) : "";
|
|
2388
|
+
return "Incoming HTTP request " + r + " hits the handler in " + ep.path + ".";
|
|
2389
|
+
}
|
|
2390
|
+
return "Library consumer imports from " + ep.path + (exportSummary ? ". Exposes " + exportSummary + "." : ".");
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
const flows = [];
|
|
2394
|
+
const maxModulesPerFlow = 32;
|
|
2395
|
+
const maxStepsPerFlow = 18;
|
|
2396
|
+
const maxReExportFanout = 6; // how many re-export targets we expand at a dead-end
|
|
2397
|
+
for (const ep of entryPoints) {
|
|
2398
|
+
const startMod = moduleByRel.get(ep.id);
|
|
2399
|
+
const startContainer = containerOf2(startMod);
|
|
2400
|
+
if (!startContainer) continue;
|
|
2401
|
+
|
|
2402
|
+
const steps = [];
|
|
2403
|
+
let stepN = 1;
|
|
2404
|
+
// Step 1: actor → entry container, with natural-language entry description
|
|
2405
|
+
steps.push({
|
|
2406
|
+
n: stepN++,
|
|
2407
|
+
from: "actor:user",
|
|
2408
|
+
to: startContainer,
|
|
2409
|
+
title: ep.kind === "cli" ? "invoke `" + (ep.name || "cli") + "`"
|
|
2410
|
+
: ep.kind === "http" ? (ep.routes && ep.routes[0] ? (ep.routes[0].method + " " + ep.routes[0].path) : "HTTP request")
|
|
2411
|
+
: "call " + (ep.name || "library"),
|
|
2412
|
+
description: describeEntry(ep, startMod),
|
|
2413
|
+
fromFile: null,
|
|
2414
|
+
toFile: ep.path,
|
|
2415
|
+
boxFrom: "actor:user",
|
|
2416
|
+
boxTo: startContainer,
|
|
2417
|
+
});
|
|
2418
|
+
|
|
2419
|
+
// Module-level BFS. Re-exports are TRANSPARENT: when a module has no callEdges out,
|
|
2420
|
+
// we lazily expand its re-export targets at the same depth so library traces descend
|
|
2421
|
+
// from index.ts into the actual implementation modules without flooding the queue.
|
|
2422
|
+
const visitedModules = new Set([ep.id]);
|
|
2423
|
+
const visitedContainers = new Set([startContainer]);
|
|
2424
|
+
const emittedHopKeys = new Set();
|
|
2425
|
+
// enqueued = BFS queue dedup (traverse each module once); visitedModules = every module the
|
|
2426
|
+
// flow touches (drives sink-step emission + the per-flow cap). Kept separate so re-export
|
|
2427
|
+
// siblings can still emit their own intra-package call steps instead of being pre-consumed.
|
|
2428
|
+
const enqueued = new Set([ep.id]);
|
|
2429
|
+
const queue = [{ moduleId: ep.id, depth: 0 }];
|
|
2430
|
+
|
|
2431
|
+
while (queue.length && stepN <= maxStepsPerFlow && visitedModules.size < maxModulesPerFlow) {
|
|
2432
|
+
const cur = queue.shift();
|
|
2433
|
+
if (cur.depth > 6) continue;
|
|
2434
|
+
const fromMod = moduleByRel.get(cur.moduleId);
|
|
2435
|
+
const fromContainer = containerOf2(fromMod);
|
|
2436
|
+
let calls = (callOutByModule.get(cur.moduleId) || []).slice().sort((a, b) => (b.count || 0) - (a.count || 0));
|
|
2437
|
+
|
|
2438
|
+
// No resolved call edges out of this module. Symbol resolution is best-effort, but
|
|
2439
|
+
// import edges are exact — so we still descend the dependency graph instead of
|
|
2440
|
+
// dead-ending at the entry (the root cause of 2-step flows):
|
|
2441
|
+
// 1. transparent re-export hub → expand its targets at the same depth;
|
|
2442
|
+
// 2. otherwise → synthesize hops from this module's import edges, ranked so the
|
|
2443
|
+
// most informative neighbours (cross-package, sink-bearing, exported) come first.
|
|
2444
|
+
if (calls.length === 0) {
|
|
2445
|
+
const reTargets = reExportTargetsByModule.get(cur.moduleId) || [];
|
|
2446
|
+
if (reTargets.length > 0) {
|
|
2447
|
+
for (const t of reTargets.slice(0, maxReExportFanout)) {
|
|
2448
|
+
if (enqueued.has(t)) continue;
|
|
2449
|
+
enqueued.add(t);
|
|
2450
|
+
visitedModules.add(t);
|
|
2451
|
+
queue.push({ moduleId: t, depth: cur.depth });
|
|
2452
|
+
}
|
|
2453
|
+
continue;
|
|
2454
|
+
}
|
|
2455
|
+
const importRank = (to) => {
|
|
2456
|
+
const tm = moduleByRel.get(to);
|
|
2457
|
+
if (!tm) return 0;
|
|
2458
|
+
return (containerOf2(tm) !== fromContainer ? 3 : 0)
|
|
2459
|
+
+ (tm.sinks && tm.sinks.length ? 2 : 0)
|
|
2460
|
+
+ (tm.exports && tm.exports.length ? 1 : 0);
|
|
2461
|
+
};
|
|
2462
|
+
calls = (adj.get(cur.moduleId) || [])
|
|
2463
|
+
.filter((to) => !enqueued.has(to))
|
|
2464
|
+
.sort((a, b) => importRank(b) - importRank(a) || (a < b ? -1 : a > b ? 1 : 0))
|
|
2465
|
+
.slice(0, 8)
|
|
2466
|
+
.map((to) => ({ from: cur.moduleId, to, symbol: "(imports)", count: 0 }));
|
|
2467
|
+
if (calls.length === 0) continue;
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
for (const ce of calls.slice(0, 8)) {
|
|
2471
|
+
const toMod = moduleByRel.get(ce.to);
|
|
2472
|
+
const toContainer = containerOf2(toMod);
|
|
2473
|
+
|
|
2474
|
+
const isCrossContainer = fromContainer !== toContainer;
|
|
2475
|
+
const callDoc = docFor(toMod, ce.symbol);
|
|
2476
|
+
const calleeExported = toMod?.exports?.some((e) => e.name === ce.symbol);
|
|
2477
|
+
const calleeHasSinks = !!(toMod?.sinks?.length);
|
|
2478
|
+
|
|
2479
|
+
// Emit a step when: cross-container OR symbol-has-doc OR exported public API
|
|
2480
|
+
// OR target has sinks OR we're shallow (depth ≤ 1) so the trace stays useful near entry.
|
|
2481
|
+
const shouldEmit = isCrossContainer || callDoc || calleeExported || calleeHasSinks || cur.depth <= 1;
|
|
2482
|
+
|
|
2483
|
+
if (shouldEmit) {
|
|
2484
|
+
if (isCrossContainer) visitedContainers.add(toContainer);
|
|
2485
|
+
|
|
2486
|
+
const hopKey = (isCrossContainer ? fromContainer + "→" + toContainer : ce.from + "→" + ce.to) + "#" + ce.symbol;
|
|
2487
|
+
if (!emittedHopKeys.has(hopKey)) {
|
|
2488
|
+
emittedHopKeys.add(hopKey);
|
|
2489
|
+
|
|
2490
|
+
const symbolPhrase = ce.symbol === "default" ? "the default export"
|
|
2491
|
+
: ce.symbol === "*" ? "the namespace import"
|
|
2492
|
+
: ce.symbol === "(imports)" ? "into its imports"
|
|
2493
|
+
: "`" + ce.symbol + "()`";
|
|
2494
|
+
const docPhrase = callDoc ? " — " + callDoc : (calleeHasSinks ? " (which performs " + toMod.sinks.slice(0,2).join(", ") + ")" : "");
|
|
2495
|
+
const baseDesc = relShort(ce.from) + " calls " + symbolPhrase + " in " + relShort(ce.to) + docPhrase;
|
|
2496
|
+
|
|
2497
|
+
steps.push({
|
|
2498
|
+
n: stepN++,
|
|
2499
|
+
from: isCrossContainer ? fromContainer : ce.from,
|
|
2500
|
+
to: isCrossContainer ? toContainer : ce.to,
|
|
2501
|
+
boxFrom: fromContainer,
|
|
2502
|
+
boxTo: toContainer,
|
|
2503
|
+
title: symbolPhrase.replace(/`/g, "") + " in " + (toMod?.path?.split("/").pop() || ce.to),
|
|
2504
|
+
description: baseDesc + ".",
|
|
2505
|
+
symbol: ce.symbol,
|
|
2506
|
+
fromFile: ce.from,
|
|
2507
|
+
toFile: ce.to,
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
visitedModules.add(ce.to);
|
|
2513
|
+
if (!enqueued.has(ce.to)) {
|
|
2514
|
+
enqueued.add(ce.to);
|
|
2515
|
+
queue.push({ moduleId: ce.to, depth: cur.depth + 1 });
|
|
2516
|
+
}
|
|
2517
|
+
if (stepN > maxStepsPerFlow) break;
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
// Sink steps: for each visited module that has sinkSites, emit a step per sink kind with the concrete callsite
|
|
2522
|
+
const emittedSinkKinds = new Set();
|
|
2523
|
+
for (const modId of visitedModules) {
|
|
2524
|
+
const mod = moduleByRel.get(modId);
|
|
2525
|
+
if (!mod || !mod.sinkSites || !mod.sinkSites.length) continue;
|
|
2526
|
+
const fromContainer = containerOf2(mod);
|
|
2527
|
+
// Group sinkSites by kind so we pick the most informative one per kind for this module
|
|
2528
|
+
const byKind = new Map();
|
|
2529
|
+
for (const s of mod.sinkSites) {
|
|
2530
|
+
if (!byKind.has(s.kind)) byKind.set(s.kind, s);
|
|
2531
|
+
}
|
|
2532
|
+
for (const [kind, site] of byKind) {
|
|
2533
|
+
if (emittedSinkKinds.has(kind)) continue;
|
|
2534
|
+
emittedSinkKinds.add(kind);
|
|
2535
|
+
const fnPart = site.inFunction ? "`" + site.inFunction + "()`" : "top-level code";
|
|
2536
|
+
const phrase = SINK_PHRASE[kind] || ("performs " + kind);
|
|
2537
|
+
const description = mod.path + ":" + site.line + " — " + fnPart + " " + phrase + ". `" + site.snippet + "`";
|
|
2538
|
+
steps.push({
|
|
2539
|
+
n: stepN++,
|
|
2540
|
+
from: fromContainer,
|
|
2541
|
+
to: sinkBoxId(kind),
|
|
2542
|
+
boxFrom: fromContainer,
|
|
2543
|
+
boxTo: sinkBoxId(kind),
|
|
2544
|
+
title: SINK_LABEL[kind] || kind,
|
|
2545
|
+
description,
|
|
2546
|
+
sinkKind: kind,
|
|
2547
|
+
sinkSite: { file: mod.path, line: site.line, fn: site.inFunction, snippet: site.snippet },
|
|
2548
|
+
});
|
|
2549
|
+
if (stepN > maxStepsPerFlow + 8) break;
|
|
2550
|
+
}
|
|
2551
|
+
if (stepN > maxStepsPerFlow + 8) break;
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
// Fallback: if no sinkSites found via callEdges traversal, emit aggregated sink steps per visited container.
|
|
2555
|
+
if (emittedSinkKinds.size === 0) {
|
|
2556
|
+
for (const c of visitedContainers) {
|
|
2557
|
+
const cMods = modules.filter((m) => containerOf2(m) === c);
|
|
2558
|
+
const cSinks = new Set();
|
|
2559
|
+
for (const m of cMods) for (const s of (m.sinks || [])) cSinks.add(s);
|
|
2560
|
+
for (const s of cSinks) {
|
|
2561
|
+
if (emittedSinkKinds.has(s)) continue;
|
|
2562
|
+
emittedSinkKinds.add(s);
|
|
2563
|
+
steps.push({
|
|
2564
|
+
n: stepN++,
|
|
2565
|
+
from: c,
|
|
2566
|
+
to: sinkBoxId(s),
|
|
2567
|
+
boxFrom: c,
|
|
2568
|
+
boxTo: sinkBoxId(s),
|
|
2569
|
+
title: SINK_LABEL[s] || s,
|
|
2570
|
+
description: c.replace(/^pkg:/, "") + " " + (SINK_PHRASE[s] || ("performs `" + s + "`")) + ".",
|
|
2571
|
+
sinkKind: s,
|
|
2572
|
+
});
|
|
2573
|
+
if (stepN > maxStepsPerFlow + 8) break;
|
|
2574
|
+
}
|
|
2575
|
+
if (stepN > maxStepsPerFlow + 8) break;
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
const flowDescription = ep.kind === "cli"
|
|
2580
|
+
? "User invokes the `" + (ep.name || "cli") + "` CLI command. The trace below shows which files run, what symbols they call, and what side effects they produce."
|
|
2581
|
+
: ep.kind === "http"
|
|
2582
|
+
? "An incoming HTTP request flows through the handler, calls dependent services, and reaches downstream side effects."
|
|
2583
|
+
: "Library consumer imports from this entry. The trace shows what the entry exposes and which downstream side effects it can produce.";
|
|
2584
|
+
|
|
2585
|
+
flows.push({
|
|
2586
|
+
id: "flow:" + ep.id,
|
|
2587
|
+
name: ep.kind === "cli" ? (ep.name || ep.path.split("/").pop()) + " (CLI)"
|
|
2588
|
+
: ep.kind === "http" ? (ep.routes && ep.routes[0] ? (ep.routes[0].method + " " + ep.routes[0].path) : ep.path)
|
|
2589
|
+
: (ep.name || ep.path.split("/").pop()) + " (library)",
|
|
2590
|
+
description: flowDescription,
|
|
2591
|
+
entry: ep.id,
|
|
2592
|
+
entryKind: ep.kind,
|
|
2593
|
+
entryContainer: startContainer,
|
|
2594
|
+
steps,
|
|
2595
|
+
});
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
// User-curated FLOWS overrides — read .planning/codebase/FLOWS.json if present.
|
|
2599
|
+
// Schema: { flows: [{ id, name, description, steps: [{ n, from, to, title, description }] }] }
|
|
2600
|
+
// Entries with matching `id` replace auto-generated flows; new ids are appended.
|
|
2601
|
+
try {
|
|
2602
|
+
const flowsFile = path.join(root, PLANNING_DIR, "codebase", "FLOWS.json");
|
|
2603
|
+
if (fs.existsSync(flowsFile)) {
|
|
2604
|
+
const user = JSON.parse(fs.readFileSync(flowsFile, "utf-8"));
|
|
2605
|
+
if (Array.isArray(user.flows)) {
|
|
2606
|
+
const byId = new Map(flows.map((f) => [f.id, f]));
|
|
2607
|
+
for (const uf of user.flows) {
|
|
2608
|
+
if (!uf.id) continue;
|
|
2609
|
+
byId.set(uf.id, Object.assign({}, byId.get(uf.id) || {}, uf, { curated: true }));
|
|
2610
|
+
}
|
|
2611
|
+
flows.length = 0;
|
|
2612
|
+
for (const f of byId.values()) flows.push(f);
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
} catch { /* empty */ }
|
|
2616
|
+
|
|
2617
|
+
// Build the swim-lane "flow graph" — lanes (architectural categories),
|
|
2618
|
+
// boxes (packages + sink kinds + actor), so the HTML can lay it out directly.
|
|
2619
|
+
const lanes = [
|
|
2620
|
+
{ id: "actor", name: "Actors", color: "#ff9bd4" },
|
|
2621
|
+
{ id: "presentation", name: "Presentation", color: "#79c0ff" },
|
|
2622
|
+
{ id: "application", name: "Application", color: "#7ee787" },
|
|
2623
|
+
{ id: "domain", name: "Domain", color: "#d2a8ff" },
|
|
2624
|
+
{ id: "infrastructure", name: "Infrastructure", color: "#f0883e" },
|
|
2625
|
+
{ id: "sinks", name: "Sinks", color: "#ff7b72" },
|
|
2626
|
+
];
|
|
2627
|
+
const boxes = [];
|
|
2628
|
+
boxes.push({ id: "actor:user", lane: "actor", title: "User", sublabel: "CLI / HTTP / library caller", color: "#ff9bd4" });
|
|
2629
|
+
// Determine each container's dominant layer
|
|
2630
|
+
for (const c of containers) {
|
|
2631
|
+
const mods = modules.filter((m) => containerOf2(m) === c.id);
|
|
2632
|
+
const counts = {};
|
|
2633
|
+
for (const m of mods) counts[m.layer] = (counts[m.layer] || 0) + 1;
|
|
2634
|
+
const lane = LAYER_ORDER_INTERNAL.slice().sort((a,b) => (counts[b]||0) - (counts[a]||0))[0] || "support";
|
|
2635
|
+
const sinkSet = new Set();
|
|
2636
|
+
for (const m of mods) for (const s of (m.sinks || [])) sinkSet.add(s);
|
|
2637
|
+
const entryMods = mods.filter((m) => !!m.entryPoint);
|
|
2638
|
+
boxes.push({
|
|
2639
|
+
id: c.id,
|
|
2640
|
+
lane: lane === "support" ? "application" : lane,
|
|
2641
|
+
title: c.name,
|
|
2642
|
+
sublabel: mods.length + " modules" + (entryMods.length ? " · " + entryMods.length + " entry" : "") + (sinkSet.size ? " · " + Array.from(sinkSet).slice(0,3).join(", ") : ""),
|
|
2643
|
+
color: LAYER_COLORS_INTERNAL[lane] || "#8b949e",
|
|
2644
|
+
kind: "package",
|
|
2645
|
+
moduleCount: mods.length,
|
|
2646
|
+
hasEntry: entryMods.length > 0,
|
|
2647
|
+
sinks: Array.from(sinkSet),
|
|
2648
|
+
});
|
|
2649
|
+
}
|
|
2650
|
+
// Sink boxes — one per distinct sink kind that any flow reaches
|
|
2651
|
+
const allSinkKinds = new Set();
|
|
2652
|
+
for (const f of flows) for (const s of f.steps) if (s.sinkKind) allSinkKinds.add(s.sinkKind);
|
|
2653
|
+
for (const kind of allSinkKinds) {
|
|
2654
|
+
boxes.push({
|
|
2655
|
+
id: sinkBoxId(kind),
|
|
2656
|
+
lane: "sinks",
|
|
2657
|
+
title: SINK_LABEL[kind] || kind,
|
|
2658
|
+
sublabel: kind,
|
|
2659
|
+
color: "#ff7b72",
|
|
2660
|
+
kind: "sink",
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
const layerCounts = {};
|
|
2665
|
+
for (const m of modules) layerCounts[m.layer] = (layerCounts[m.layer] || 0) + 1;
|
|
2666
|
+
|
|
2667
|
+
// Symbol index for agents (the searchable identifier glossary)
|
|
2668
|
+
const symbolIndex = [];
|
|
2669
|
+
for (const m of modules) {
|
|
2670
|
+
for (const e of m.exports) {
|
|
2671
|
+
symbolIndex.push({ name: e.name, kind: e.kind, line: e.line, file: m.path, package: m.package, exported: true });
|
|
2672
|
+
if (symbolIndex.length > 1500) break;
|
|
2673
|
+
}
|
|
2674
|
+
if (symbolIndex.length > 1500) break;
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
const tests = { total: modules.filter((m) => m.isTest).length, byContainer: {} };
|
|
2678
|
+
for (const c of containers) {
|
|
2679
|
+
tests.byContainer[c.name] = modules.filter((m) => m.isTest && m.path.startsWith(c.path + "/")).length;
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
// ── Knowledge-graph rollups: hotspots (god-nodes), clusters, surprising connections, rationale ──
|
|
2683
|
+
const rankHotspots = (metric, reason) => {
|
|
2684
|
+
const arr = modules.filter((m) => !m.isTest).map((m) => {
|
|
2685
|
+
const inD = inDegNT.get(m.id) || 0, outD = outDegNT.get(m.id) || 0, l = m.loc || 0;
|
|
2686
|
+
return { id: m.id, path: m.path, package: m.package, inDegree: inD, outDegree: outD, loc: l, score: +metric(inD, outD, l).toFixed(2), reason: reason(inD, outD, l) };
|
|
2687
|
+
});
|
|
2688
|
+
arr.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
2689
|
+
return arr.slice(0, 15);
|
|
2690
|
+
};
|
|
2691
|
+
const hotspots = {
|
|
2692
|
+
godNodes: rankHotspots((i, o, l) => i * 2 + o + Math.log2(1 + l), (i, o) => `${i} dependents · ${o} deps`),
|
|
2693
|
+
mostDependedOn: rankHotspots((i) => i, (i) => `${i} dependents`),
|
|
2694
|
+
orchestrators: rankHotspots((i, o) => o, (i, o) => `imports ${o} modules`),
|
|
2695
|
+
largest: rankHotspots((i, o, l) => l, (i, o, l) => `${l} LOC`),
|
|
2696
|
+
};
|
|
2697
|
+
|
|
2698
|
+
const { clusters, clusterOf } = visComputeClusters(modules, edges, moduleByRel, containerOf);
|
|
2699
|
+
for (const m of modules) m.cluster = clusterOf.get(m.id) || null;
|
|
2700
|
+
|
|
2701
|
+
const groupOfContainer = new Map();
|
|
2702
|
+
for (const g of groups) for (const mid of (g.members || [])) groupOfContainer.set(mid, g.id);
|
|
2703
|
+
const surprisingConnections = visComputeSurprising(edges, callEdges, moduleByRel, clusterOf, groupOfContainer, containerOf);
|
|
2704
|
+
|
|
2705
|
+
const rationaleIndex = rationaleAll
|
|
2706
|
+
.sort((a, b) => (RATIONALE_SEVERITY[a.tag] - RATIONALE_SEVERITY[b.tag]) || (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) || (a.line - b.line))
|
|
2707
|
+
.slice(0, 600);
|
|
2708
|
+
|
|
2709
|
+
return {
|
|
2710
|
+
schemaVersion: 4,
|
|
2711
|
+
generatedAt: new Date().toISOString(),
|
|
2712
|
+
buildMs: Date.now() - startedAt,
|
|
2713
|
+
root: path.basename(root),
|
|
2714
|
+
stats: {
|
|
2715
|
+
files: modules.length,
|
|
2716
|
+
totalLoc: totalLoc.value,
|
|
2717
|
+
languages: langCounts,
|
|
2718
|
+
packages: pkgs.length,
|
|
2719
|
+
containers: containers.length,
|
|
2720
|
+
groups: groups.length,
|
|
2721
|
+
edges: edges.length,
|
|
2722
|
+
callEdges: callEdges.length,
|
|
2723
|
+
containerEdges: containerEdges.length,
|
|
2724
|
+
entryPoints: entryPoints.length,
|
|
2725
|
+
sinkModules: sinkNodes.length,
|
|
2726
|
+
layers: layerCounts,
|
|
2727
|
+
},
|
|
2728
|
+
packages: pkgs,
|
|
2729
|
+
groups,
|
|
2730
|
+
containers,
|
|
2731
|
+
boundedContexts: containers, // alias for back-compat
|
|
2732
|
+
modules,
|
|
2733
|
+
edges,
|
|
2734
|
+
callEdges,
|
|
2735
|
+
containerEdges,
|
|
2736
|
+
entryPoints,
|
|
2737
|
+
sinks: sinkNodes,
|
|
2738
|
+
flows,
|
|
2739
|
+
lanes,
|
|
2740
|
+
boxes,
|
|
2741
|
+
symbolIndex,
|
|
2742
|
+
hotspots,
|
|
2743
|
+
clusters,
|
|
2744
|
+
surprisingConnections,
|
|
2745
|
+
rationaleIndex,
|
|
2746
|
+
tests,
|
|
2747
|
+
planning: {
|
|
2748
|
+
hasProject: !!planning.project,
|
|
2749
|
+
hasRoadmap: !!planning.roadmap,
|
|
2750
|
+
hasDomain: !!planning.domain,
|
|
2751
|
+
currentState: planning.state ? planning.state.slice(0, 2000) : null,
|
|
2752
|
+
},
|
|
2753
|
+
agentHints: {
|
|
2754
|
+
description: "Architecture map of this codebase. Read this BEFORE walking the file tree.",
|
|
2755
|
+
howToUse: [
|
|
2756
|
+
"`groups` partitions packages into functional containers (Frontend, CLI & Runtime, Core, Domain Services, Workflows & Infra). Each group's `members` array lists `pkg:NAME` ids. Overridable via `.planning/codebase/GROUPS.json`.",
|
|
2757
|
+
"`containers[*].groupId` links a package to its functional group; `containers[*].topFiles` is the 3-5 most relevant source files in the package (with a `reason` tag like `CLI entry` / `most depended-on` / `HTTP handler`).",
|
|
2758
|
+
"`containerEdges[*].label` is the relationship verb between two packages (Calls / Uses / Sends Events / Renders / Updates / Reads State / Configures / Analyzes / Executes Actions / Persists). `containerEdges[*].symbolSamples` shows the top imported symbol names.",
|
|
2759
|
+
"`entryPoints` lists every CLI command, HTTP route, and library main — these are where data flows in.",
|
|
2760
|
+
"`sinks` lists modules that hit FS, network, DB, stdout, or run subprocesses — where data flows out.",
|
|
2761
|
+
"`containers` describes packages/bounded contexts. `containerEdges` shows cross-package dataflow.",
|
|
2762
|
+
"`callEdges` is symbol-level: each entry means caller-file uses callee-file's <symbol>.",
|
|
2763
|
+
"`flows` is a list of named scenarios (CLI invocation, HTTP request, library call). Each flow has numbered `steps` going from `from` box → `to` box with a `description`. Boxes are packages (`pkg:NAME`), sinks (`sink:KIND`), or `actor:user`.",
|
|
2764
|
+
"`lanes` + `boxes` give you swim-lane layout coordinates: each box belongs to a lane (presentation / application / domain / infrastructure / sinks / actors).",
|
|
2765
|
+
"To curate flows or groups: write `.planning/codebase/FLOWS.json` or `.planning/codebase/GROUPS.json` — entries with matching `id` override auto-generated ones; new ids are appended.",
|
|
2766
|
+
"`modules[*].layer` classifies each file as presentation / application / domain / infrastructure / support.",
|
|
2767
|
+
"`modules[*].symbols` are symbol-level nodes ({name,kind,line,exported}); `modules[*].cluster` is the structural neighborhood id.",
|
|
2768
|
+
"`hotspots` ranks god-nodes / most-depended-on / orchestrators / largest (non-test import degree).",
|
|
2769
|
+
"`clusters` are STRUCTURAL (import-topology) neighborhoods — not semantic bounded contexts; confirm with a human before equating a cluster with a context. Non-JS/TS packages degenerate to one cluster per package.",
|
|
2770
|
+
"`surprisingConnections` flags import edges that bridge distant clusters, cross functional groups, or violate layer direction — review these.",
|
|
2771
|
+
"`rationaleIndex` collects inline NOTE/WHY/HACK/TODO/FIXME/SECURITY notes ({file,line,tag,text}).",
|
|
2772
|
+
"`edges[*].confidence` / `callEdges[*].confidence` ∈ EXTRACTED (literal in source) / INFERRED (regex call heuristic) / AMBIGUOUS (member-call, imported symbol uncertain).",
|
|
2773
|
+
"Query the map with `draht-tools graph-context|graph-impact|graph-query|graph-callers|graph-callees|graph-path|graph-hotspots|graph-clusters` instead of reading this whole file or grepping.",
|
|
2774
|
+
],
|
|
2775
|
+
},
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2779
|
+
function visRenderHtml(jsonPath) {
|
|
2780
|
+
const jsonName = path.basename(jsonPath);
|
|
2781
|
+
return `<!doctype html>
|
|
2782
|
+
<html lang="en">
|
|
2783
|
+
<head>
|
|
2784
|
+
<meta charset="utf-8" />
|
|
2785
|
+
<title>Draht ▸ Architecture & Flows</title>
|
|
2786
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
2787
|
+
<style>
|
|
2788
|
+
:root {
|
|
2789
|
+
--bg:#0b0d10; --bg-soft:#11151a; --panel:#151b22; --text:#e6edf3;
|
|
2790
|
+
--muted:#8b949e; --border:#262d36;
|
|
2791
|
+
--pres:#79c0ff; --app:#7ee787; --dom:#d2a8ff; --infra:#f0883e; --supp:#8b949e;
|
|
2792
|
+
--sink:#ff7b72; --entry:#ffdf5d; --actor:#ff9bd4;
|
|
2793
|
+
}
|
|
2794
|
+
* { box-sizing:border-box; }
|
|
2795
|
+
html,body { margin:0; height:100%; background:var(--bg); color:var(--text);
|
|
2796
|
+
font:13px/1.45 -apple-system,"SF Pro Text",Segoe UI,system-ui,sans-serif; }
|
|
2797
|
+
|
|
2798
|
+
header { display:flex; align-items:center; gap:14px; padding:10px 16px;
|
|
2799
|
+
border-bottom:1px solid var(--border); background:var(--bg-soft); }
|
|
2800
|
+
header .title { font-weight:700; letter-spacing:.4px; }
|
|
2801
|
+
header .meta { color:var(--muted); font-size:12px; }
|
|
2802
|
+
header .tabs { display:flex; gap:2px; margin-left:8px; }
|
|
2803
|
+
header .tabs button { background:transparent; color:var(--muted); border:1px solid var(--border);
|
|
2804
|
+
padding:4px 10px; cursor:pointer; font-size:12px; border-radius:6px; }
|
|
2805
|
+
header .tabs button.active { color:var(--text); background:#1c2530; border-color:#3a4858; }
|
|
2806
|
+
header .live { margin-left:auto; padding:2px 8px; border-radius:99px;
|
|
2807
|
+
background:#143; color:var(--app); font-size:11px; }
|
|
2808
|
+
header .live.dead { background:#3a1a1a; color:#ff7b72; }
|
|
2809
|
+
|
|
2810
|
+
main { display:grid; grid-template-columns:280px 1fr 380px; height:calc(100vh - 49px); }
|
|
2811
|
+
aside { overflow:auto; background:var(--panel); border-right:1px solid var(--border); }
|
|
2812
|
+
aside.right { border-right:none; border-left:1px solid var(--border); }
|
|
2813
|
+
.section { padding:10px 14px; border-bottom:1px solid var(--border); }
|
|
2814
|
+
.section h2 { margin:0 0 6px; font-size:10.5px; text-transform:uppercase;
|
|
2815
|
+
letter-spacing:1.2px; color:var(--muted); font-weight:700; }
|
|
2816
|
+
.section input { width:100%; background:var(--bg); color:var(--text);
|
|
2817
|
+
border:1px solid var(--border); border-radius:6px; padding:6px 8px; outline:none; font-size:12px; }
|
|
2818
|
+
.list { display:flex; flex-direction:column; }
|
|
2819
|
+
.list .row { display:flex; align-items:center; gap:8px; padding:5px 14px; cursor:pointer; font-size:12px; }
|
|
2820
|
+
.list .row:hover { background:#1c2530; }
|
|
2821
|
+
.list .row.active { background:#1f2a36; border-left:2px solid var(--entry); }
|
|
2822
|
+
.list .row .name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
2823
|
+
.list .row .count { color:var(--muted); font-size:11px; }
|
|
2824
|
+
.dot { width:9px; height:9px; border-radius:50%; flex:0 0 9px; }
|
|
2825
|
+
|
|
2826
|
+
#viz { position:relative; overflow:hidden; background:radial-gradient(circle at 30% 20%, #0f141a 0%, #0b0d10 70%); }
|
|
2827
|
+
svg { display:block; user-select:none; }
|
|
2828
|
+
.controls { position:absolute; top:10px; right:10px; display:flex; gap:6px; z-index: 2; }
|
|
2829
|
+
.controls button { background:var(--panel); color:var(--text); border:1px solid var(--border);
|
|
2830
|
+
border-radius:6px; padding:4px 10px; cursor:pointer; font-size:11px; }
|
|
2831
|
+
.controls button:hover { border-color:var(--pres); }
|
|
2832
|
+
.hud { position:absolute; bottom:10px; left:12px; color:var(--muted); font-size:11px;
|
|
2833
|
+
background:rgba(15,18,22,.6); padding:4px 8px; border-radius:6px; }
|
|
2834
|
+
.legend { position:absolute; top:10px; left:12px; background:rgba(15,18,22,.85);
|
|
2835
|
+
border:1px solid var(--border); border-radius:8px; padding:8px 10px; font-size:11px; z-index: 1; }
|
|
2836
|
+
.legend .row { display:flex; align-items:center; gap:6px; padding:1px 0; }
|
|
2837
|
+
|
|
2838
|
+
.detail h3 { font-size:13px; margin:0 0 6px; word-break:break-all; font-weight:600; }
|
|
2839
|
+
.detail .pill { display:inline-block; padding:2px 8px; border:1px solid var(--border);
|
|
2840
|
+
border-radius:99px; font-size:11px; color:var(--muted); margin:2px 4px 2px 0; }
|
|
2841
|
+
.detail pre { background:var(--bg); border:1px solid var(--border); border-radius:6px;
|
|
2842
|
+
padding:8px; overflow:auto; font-size:11px; line-height:1.4; max-height:220px;
|
|
2843
|
+
margin:6px 0 0; white-space:pre-wrap; }
|
|
2844
|
+
.detail .kv { font-size:11.5px; color:var(--muted); margin:2px 0; }
|
|
2845
|
+
.detail .kv b { color:var(--text); }
|
|
2846
|
+
|
|
2847
|
+
.flow-list { max-height:280px; overflow-y:auto; }
|
|
2848
|
+
.flow-list .flow-item { padding:8px 14px; border-bottom:1px solid var(--border); cursor:pointer; }
|
|
2849
|
+
.flow-list .flow-item:hover { background:#1c2530; }
|
|
2850
|
+
.flow-list .flow-item.active { background:#1f2a36; border-left:3px solid var(--entry); padding-left:11px; }
|
|
2851
|
+
.flow-list .flow-item .name { font-size:12.5px; font-weight:600; }
|
|
2852
|
+
.flow-list .flow-item .desc { font-size:11px; color:var(--muted); margin-top:2px; }
|
|
2853
|
+
.step-list { max-height:calc(100vh - 460px); overflow-y:auto; }
|
|
2854
|
+
|
|
2855
|
+
.step-list .step-item { padding:10px 14px; border-bottom:1px solid var(--border); display:flex; gap:10px;
|
|
2856
|
+
cursor:pointer; align-items:flex-start; }
|
|
2857
|
+
.step-list .step-item:hover { background:#1c2530; }
|
|
2858
|
+
.step-list .step-item.active { background:#1f2a36; }
|
|
2859
|
+
.step-list .step-item .num {
|
|
2860
|
+
flex:0 0 22px; height:22px; border-radius:50%;
|
|
2861
|
+
background:var(--entry); color:#0b0d10; font-weight:700; font-size:12px;
|
|
2862
|
+
display:flex; align-items:center; justify-content:center;
|
|
2863
|
+
}
|
|
2864
|
+
.step-list .step-item .body { flex:1; min-width:0; font-size:11.5px; }
|
|
2865
|
+
.step-list .step-item .title { font-weight:600; color:var(--text); }
|
|
2866
|
+
.step-list .step-item .from-to { color:var(--muted); font-size:10.5px; margin-top:3px; }
|
|
2867
|
+
.step-list .step-item .desc { color:#c9d1d9; font-size:11.5px; margin-top:5px; line-height:1.55; }
|
|
2868
|
+
.step-list .step-item .desc code { background:rgba(28,37,48,0.8); border:1px solid var(--border);
|
|
2869
|
+
border-radius:4px; padding:1px 5px; font-family:ui-monospace,SF Mono,Menlo,monospace; font-size:10.5px; color:#7ee787; }
|
|
2870
|
+
.step-list .step-item .snippet { background:rgba(11,13,16,0.85); border-left:2px solid var(--entry);
|
|
2871
|
+
padding:4px 8px; margin-top:5px; font-family:ui-monospace,SF Mono,Menlo,monospace;
|
|
2872
|
+
font-size:10.5px; color:#c9d1d9; border-radius:0 4px 4px 0; white-space:pre-wrap; word-break:break-word; }
|
|
2873
|
+
.step-list .step-item .file-ref { font-family:ui-monospace,SF Mono,Menlo,monospace; font-size:10px;
|
|
2874
|
+
color:var(--pres); margin-top:2px; word-break:break-all; }
|
|
2875
|
+
.kbd { background:var(--bg); border:1px solid var(--border); padding:1px 5px;
|
|
2876
|
+
border-radius:4px; font-family:ui-monospace,monospace; font-size:10px; }
|
|
2877
|
+
|
|
2878
|
+
.container-rect { fill:rgba(28,37,48,0.55); stroke:#2a3540; stroke-width:1; }
|
|
2879
|
+
.container-rect.hi { stroke:#79c0ff; stroke-width:2; }
|
|
2880
|
+
.container-label { fill:var(--text); font-size:11px; font-weight:600; pointer-events:none; }
|
|
2881
|
+
.module-node { cursor:pointer; }
|
|
2882
|
+
.module-node circle { stroke:#0b0d10; stroke-width:1.2; transition:r .15s, stroke .15s; }
|
|
2883
|
+
.module-node:hover circle { stroke:#fff; }
|
|
2884
|
+
.module-node.selected circle { stroke:#fff; stroke-width:2.4; }
|
|
2885
|
+
.edge { fill:none; stroke:#3a4858; stroke-width:0.8; opacity:.5; }
|
|
2886
|
+
.edge.cross { stroke:#7ee787; stroke-width:1.4; opacity:.65; }
|
|
2887
|
+
.edge.flow { stroke:#ffdf5d; stroke-width:1.5; opacity:.95; }
|
|
2888
|
+
.edge.flow.active { stroke-width:2.5; }
|
|
2889
|
+
.edge.hi { stroke:#ffdf5d; stroke-width:1.6; opacity:1; }
|
|
2890
|
+
.edge.dim { opacity:.05; }
|
|
2891
|
+
.layer-band { stroke:#1a2028; stroke-dasharray:2 4; fill:none; }
|
|
2892
|
+
.layer-label { fill:var(--muted); font-size:11px; font-weight:600; letter-spacing:1.5px; text-transform:uppercase; }
|
|
2893
|
+
.lane-divider { stroke:#1a2028; stroke-dasharray:2 4; }
|
|
2894
|
+
.flow-box { cursor:pointer; }
|
|
2895
|
+
.flow-box:hover rect { stroke-width:1.6; }
|
|
2896
|
+
.step-num { cursor:pointer; }
|
|
2897
|
+
.step-num.active circle { fill:#fff; }
|
|
2898
|
+
|
|
2899
|
+
/* Architecture (CodeViz-style nested) view */
|
|
2900
|
+
.group-rect { fill:rgba(28,37,48,0.32); stroke-width:1.4; rx:12; cursor:default; }
|
|
2901
|
+
.group-rect:hover { filter:brightness(1.15); }
|
|
2902
|
+
.group-rect.focused { stroke-width:2.5; }
|
|
2903
|
+
.group-rect.collapsed { fill:rgba(28,37,48,0.6); }
|
|
2904
|
+
.group-header { fill:rgba(11,13,16,0.65); pointer-events:none; }
|
|
2905
|
+
.group-name { font-size:13px; font-weight:700; letter-spacing:.3px; pointer-events:none; }
|
|
2906
|
+
.group-sub { fill:var(--muted); font-size:10px; pointer-events:none; }
|
|
2907
|
+
.pkg-rect { fill:rgba(15,18,22,0.78); stroke-width:1.2; cursor:pointer;
|
|
2908
|
+
transition:filter .12s, stroke-width .12s; }
|
|
2909
|
+
.pkg-rect:hover { filter:brightness(1.25); stroke-width:1.8; }
|
|
2910
|
+
.pkg-rect.selected { stroke:#fff !important; stroke-width:2.4; }
|
|
2911
|
+
.pkg-rect.dim { opacity:.18; }
|
|
2912
|
+
.pkg-title { fill:var(--text); font-size:12px; font-weight:600; pointer-events:none; }
|
|
2913
|
+
.pkg-sub { fill:var(--muted); font-size:10px; pointer-events:none; }
|
|
2914
|
+
.pkg-topfiles { fill:#8fb8ff; font-size:9.5px; pointer-events:none; font-family:ui-monospace,monospace; }
|
|
2915
|
+
.edge.intra { stroke:#3a4858; stroke-width:0.6; opacity:0.32; }
|
|
2916
|
+
.edge-label-bg { fill:#11151a; stroke:#262d36; stroke-width:1; rx:4; ry:4; }
|
|
2917
|
+
.edge-label-text { fill:#c9d1d9; font-size:10px; font-weight:500; pointer-events:none; }
|
|
2918
|
+
.edge-label-text.persists { fill:#ff7b72; }
|
|
2919
|
+
.edge-label-text.sends-events { fill:#ffdf5d; }
|
|
2920
|
+
.edge-label-text.renders { fill:#79c0ff; }
|
|
2921
|
+
.edge-label-text.configures { fill:#d2a8ff; }
|
|
2922
|
+
.edge-hit { stroke:transparent; stroke-width:14; fill:none; cursor:pointer; }
|
|
2923
|
+
#tooltip { position:absolute; display:none; background:#11151a; color:var(--text);
|
|
2924
|
+
border:1px solid var(--border); border-radius:6px; padding:8px 10px; font-size:11px;
|
|
2925
|
+
max-width:340px; pointer-events:none; z-index:100; box-shadow:0 4px 24px rgba(0,0,0,0.5); }
|
|
2926
|
+
#tooltip .tt-title { font-weight:700; font-size:12px; margin-bottom:2px; }
|
|
2927
|
+
#tooltip .tt-desc { color:var(--muted); font-size:10.5px; margin-bottom:6px; line-height:1.4; }
|
|
2928
|
+
#tooltip .tt-section { color:var(--muted); font-size:9.5px; text-transform:uppercase; letter-spacing:1px;
|
|
2929
|
+
margin:5px 0 2px; }
|
|
2930
|
+
#tooltip ul { margin:0; padding-left:0; list-style:none; }
|
|
2931
|
+
#tooltip ul li { display:flex; gap:6px; font-family:ui-monospace,monospace; font-size:10px; padding:1px 0; }
|
|
2932
|
+
#tooltip .tt-reason { color:var(--entry); flex:0 0 84px; }
|
|
2933
|
+
#tooltip .tt-loc { color:var(--muted); margin-left:auto; }
|
|
2934
|
+
#tooltip code { color:#7ee787; font-family:ui-monospace,monospace; font-size:10px; }
|
|
2935
|
+
.ctrl-checkbox { display:inline-flex; align-items:center; gap:5px; color:var(--muted);
|
|
2936
|
+
font-size:11px; cursor:pointer; padding:4px 8px; border:1px solid var(--border); border-radius:6px; background:var(--panel); }
|
|
2937
|
+
.ctrl-checkbox input { margin:0; cursor:pointer; }
|
|
2938
|
+
</style>
|
|
2939
|
+
</head>
|
|
2940
|
+
<body>
|
|
2941
|
+
<header>
|
|
2942
|
+
<div class="title">DRAHT ▸ <span id="root-name">codebase</span></div>
|
|
2943
|
+
<div class="meta" id="meta">loading…</div>
|
|
2944
|
+
<div class="tabs">
|
|
2945
|
+
<button id="tab-architecture" class="active">Architecture</button>
|
|
2946
|
+
<button id="tab-modules">Modules</button>
|
|
2947
|
+
<button id="tab-flows">Flow Trace</button>
|
|
2948
|
+
<button id="tab-insights">Insights</button>
|
|
2949
|
+
<button id="tab-concepts">Concepts</button>
|
|
2950
|
+
<button id="tab-graph">Knowledge Graph</button>
|
|
2951
|
+
<button id="tab-calls">Calls</button>
|
|
2952
|
+
</div>
|
|
2953
|
+
<div class="live" id="live-indicator">● live</div>
|
|
2954
|
+
</header>
|
|
2955
|
+
<main>
|
|
2956
|
+
<aside id="left-aside">
|
|
2957
|
+
<div class="section">
|
|
2958
|
+
<h2>Search</h2>
|
|
2959
|
+
<input id="q" placeholder="filter…" />
|
|
2960
|
+
</div>
|
|
2961
|
+
<div class="section">
|
|
2962
|
+
<h2>Entry Points</h2>
|
|
2963
|
+
<div class="list" id="entry-list"></div>
|
|
2964
|
+
</div>
|
|
2965
|
+
<div class="section">
|
|
2966
|
+
<h2>Sinks</h2>
|
|
2967
|
+
<div class="list" id="sink-list"></div>
|
|
2968
|
+
</div>
|
|
2969
|
+
<div class="section">
|
|
2970
|
+
<h2>Layers</h2>
|
|
2971
|
+
<div class="list" id="layer-list"></div>
|
|
2972
|
+
</div>
|
|
2973
|
+
<div class="section">
|
|
2974
|
+
<h2>Packages</h2>
|
|
2975
|
+
<div class="list" id="pkg-list"></div>
|
|
2976
|
+
</div>
|
|
2977
|
+
</aside>
|
|
2978
|
+
<div id="viz">
|
|
2979
|
+
<svg id="svg" width="100%" height="100%"></svg>
|
|
2980
|
+
<div class="legend" id="legend"></div>
|
|
2981
|
+
<div class="controls">
|
|
2982
|
+
<label class="ctrl-checkbox"><input type="checkbox" id="overlay-flow-cb"/> overlay flow</label>
|
|
2983
|
+
<button id="fit">fit</button>
|
|
2984
|
+
<button id="clear">clear</button>
|
|
2985
|
+
<button id="reload">reload</button>
|
|
2986
|
+
</div>
|
|
2987
|
+
<div class="hud" id="hud">click a package · hover for details · double-click a group to focus</div>
|
|
2988
|
+
<div id="tooltip"></div>
|
|
2989
|
+
</div>
|
|
2990
|
+
<aside class="right">
|
|
2991
|
+
<div class="section">
|
|
2992
|
+
<h2>Flows</h2>
|
|
2993
|
+
<div class="flow-list" id="flow-list"></div>
|
|
2994
|
+
</div>
|
|
2995
|
+
<div class="section">
|
|
2996
|
+
<h2>Steps</h2>
|
|
2997
|
+
<div class="step-list" id="step-list">
|
|
2998
|
+
<div style="color:var(--muted); padding:8px 0">Select a flow above to see numbered steps.</div>
|
|
2999
|
+
</div>
|
|
3000
|
+
</div>
|
|
3001
|
+
<div class="section detail" id="detail" style="display:none">
|
|
3002
|
+
<h3>Detail</h3>
|
|
3003
|
+
</div>
|
|
3004
|
+
</aside>
|
|
3005
|
+
</main>
|
|
3006
|
+
<script>
|
|
3007
|
+
"use strict";
|
|
3008
|
+
var JSON_PATH = ${JSON.stringify('./' + jsonName)};
|
|
3009
|
+
var LAYER_COLOR = { presentation:"#79c0ff", application:"#7ee787",
|
|
3010
|
+
domain:"#d2a8ff", infrastructure:"#f0883e", support:"#8b949e" };
|
|
3011
|
+
var LAYER_ORDER = ["presentation","application","domain","infrastructure","support"];
|
|
3012
|
+
var SVG_NS = "http://www.w3.org/2000/svg";
|
|
3013
|
+
function $(id) { return document.getElementById(id); }
|
|
3014
|
+
var svg = $("svg");
|
|
3015
|
+
|
|
3016
|
+
var state = {
|
|
3017
|
+
map: null,
|
|
3018
|
+
view: "architecture",
|
|
3019
|
+
zoom: 1,
|
|
3020
|
+
pan: { x:0, y:0 },
|
|
3021
|
+
drag: null,
|
|
3022
|
+
selected: null,
|
|
3023
|
+
selectedFlow: null,
|
|
3024
|
+
selectedStep: null,
|
|
3025
|
+
collapsedGroups: {},
|
|
3026
|
+
overlayFlow: false,
|
|
3027
|
+
focus: null,
|
|
3028
|
+
filter: "",
|
|
3029
|
+
};
|
|
3030
|
+
|
|
3031
|
+
function layerOf(m) { return m.layer || "support"; }
|
|
3032
|
+
function escapeHtml(s) {
|
|
3033
|
+
return String(s).replace(/[&<>"]/g, function (c) {
|
|
3034
|
+
return ({"&":"&","<":"<",">":">","\\"":"""})[c];
|
|
3035
|
+
});
|
|
3036
|
+
}
|
|
3037
|
+
function truncate(s, n) { if (!s) return ""; s = String(s); if (s.length <= n) return s; return s.slice(0, n - 1) + "…"; }
|
|
3038
|
+
function containerIdOf(m) {
|
|
3039
|
+
if (m.package) return "pkg:" + m.package;
|
|
3040
|
+
return "dir:" + m.path.split("/")[0];
|
|
3041
|
+
}
|
|
3042
|
+
function tx(g) {
|
|
3043
|
+
g.setAttribute("transform", "translate(" + state.pan.x + "," + state.pan.y + ") scale(" + state.zoom + ")");
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
async function load(initial) {
|
|
3047
|
+
var res = await fetch(JSON_PATH + "?t=" + Date.now());
|
|
3048
|
+
var map = await res.json();
|
|
3049
|
+
state.map = map;
|
|
3050
|
+
$("root-name").textContent = map.root;
|
|
3051
|
+
$("meta").textContent =
|
|
3052
|
+
map.stats.files + " files · " + map.stats.totalLoc.toLocaleString() + " LOC · " +
|
|
3053
|
+
map.stats.entryPoints + " entries · " + map.stats.sinkModules + " sinks · " +
|
|
3054
|
+
map.stats.containerEdges + " cross-pkg edges · " +
|
|
3055
|
+
new Date(map.generatedAt).toLocaleTimeString();
|
|
3056
|
+
renderSidebar();
|
|
3057
|
+
renderFlowList();
|
|
3058
|
+
render();
|
|
3059
|
+
if (initial) fit();
|
|
3060
|
+
}
|
|
3061
|
+
|
|
3062
|
+
function setView(v) {
|
|
3063
|
+
state.view = v;
|
|
3064
|
+
["tab-architecture","tab-modules","tab-flows","tab-insights","tab-concepts","tab-graph","tab-calls"].forEach(function (id) {
|
|
3065
|
+
$(id).classList.toggle("active", id === "tab-" + v);
|
|
3066
|
+
});
|
|
3067
|
+
// Sidebar layout: flows shows step detail, others show entry inspection
|
|
3068
|
+
render(); fit();
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
function buildAdj(map) {
|
|
3072
|
+
var adj = new Map();
|
|
3073
|
+
for (var i=0; i<map.edges.length; i++) {
|
|
3074
|
+
var e = map.edges[i];
|
|
3075
|
+
if (e.kind !== "import") continue;
|
|
3076
|
+
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
3077
|
+
adj.get(e.from).push(e.to);
|
|
3078
|
+
}
|
|
3079
|
+
return adj;
|
|
3080
|
+
}
|
|
3081
|
+
function buildReverseAdj(map) {
|
|
3082
|
+
var adj = new Map();
|
|
3083
|
+
for (var i=0; i<map.edges.length; i++) {
|
|
3084
|
+
var e = map.edges[i];
|
|
3085
|
+
if (e.kind !== "import") continue;
|
|
3086
|
+
if (!adj.has(e.to)) adj.set(e.to, []);
|
|
3087
|
+
adj.get(e.to).push(e.from);
|
|
3088
|
+
}
|
|
3089
|
+
return adj;
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
function selectFlow(flowId) {
|
|
3093
|
+
state.selectedFlow = flowId;
|
|
3094
|
+
state.selectedStep = null;
|
|
3095
|
+
state.view = "flows";
|
|
3096
|
+
["tab-architecture","tab-modules","tab-flows","tab-insights","tab-concepts","tab-graph","tab-calls"].forEach(function (id) {
|
|
3097
|
+
$(id).classList.toggle("active", id === "tab-flows");
|
|
3098
|
+
});
|
|
3099
|
+
renderFlowList();
|
|
3100
|
+
renderStepList();
|
|
3101
|
+
render();
|
|
3102
|
+
}
|
|
3103
|
+
function selectStep(n) {
|
|
3104
|
+
state.selectedStep = n;
|
|
3105
|
+
renderStepList();
|
|
3106
|
+
render();
|
|
3107
|
+
}
|
|
3108
|
+
function clearFlow() {
|
|
3109
|
+
state.selectedFlow = null;
|
|
3110
|
+
state.selectedStep = null;
|
|
3111
|
+
state.focus = null;
|
|
3112
|
+
state.selected = null;
|
|
3113
|
+
renderFlowList();
|
|
3114
|
+
renderStepList();
|
|
3115
|
+
renderDetail();
|
|
3116
|
+
render();
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
function focusEntry(id) {
|
|
3120
|
+
var adj = buildAdj(state.map);
|
|
3121
|
+
var set = new Set([id]); var stack = [id];
|
|
3122
|
+
while (stack.length) {
|
|
3123
|
+
var x = stack.pop();
|
|
3124
|
+
var ns = adj.get(x) || [];
|
|
3125
|
+
for (var i=0; i<ns.length; i++) if (!set.has(ns[i])) { set.add(ns[i]); stack.push(ns[i]); }
|
|
3126
|
+
}
|
|
3127
|
+
state.focus = { kind: "entry", id: id, set: set };
|
|
3128
|
+
render();
|
|
3129
|
+
}
|
|
3130
|
+
function focusSink(kind) {
|
|
3131
|
+
var map = state.map;
|
|
3132
|
+
var radj = buildReverseAdj(map);
|
|
3133
|
+
var seeds = map.sinks.filter(function (s) { return s.sinks.indexOf(kind) !== -1; }).map(function (s) { return s.id; });
|
|
3134
|
+
var set = new Set(seeds); var stack = seeds.slice();
|
|
3135
|
+
while (stack.length) {
|
|
3136
|
+
var x = stack.pop();
|
|
3137
|
+
var ns = radj.get(x) || [];
|
|
3138
|
+
for (var i=0; i<ns.length; i++) if (!set.has(ns[i])) { set.add(ns[i]); stack.push(ns[i]); }
|
|
3139
|
+
}
|
|
3140
|
+
state.focus = { kind: "sink", id: kind, set: set };
|
|
3141
|
+
render();
|
|
3142
|
+
}
|
|
3143
|
+
function focusPackage(pkgId) {
|
|
3144
|
+
var set = new Set();
|
|
3145
|
+
for (var i=0; i<state.map.modules.length; i++) {
|
|
3146
|
+
var m = state.map.modules[i];
|
|
3147
|
+
if (("pkg:" + (m.package || "")) === pkgId) set.add(m.id);
|
|
3148
|
+
}
|
|
3149
|
+
state.focus = { kind: "package", id: pkgId, set: set };
|
|
3150
|
+
render();
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
// ====================== Swim-lane Flows view ======================
|
|
3154
|
+
|
|
3155
|
+
function layoutSwimlanes(map, W, H) {
|
|
3156
|
+
var lanes = map.lanes || [];
|
|
3157
|
+
if (!lanes.length) return { lanePos: new Map(), boxPos: new Map() };
|
|
3158
|
+
var laneW = W / lanes.length;
|
|
3159
|
+
var lanePos = new Map();
|
|
3160
|
+
lanes.forEach(function (lane, i) {
|
|
3161
|
+
lanePos.set(lane.id, { x: laneW * i, w: laneW, lane: lane });
|
|
3162
|
+
});
|
|
3163
|
+
var boxesByLane = new Map();
|
|
3164
|
+
lanes.forEach(function (l) { boxesByLane.set(l.id, []); });
|
|
3165
|
+
(map.boxes || []).forEach(function (b) {
|
|
3166
|
+
if (boxesByLane.has(b.lane)) boxesByLane.get(b.lane).push(b);
|
|
3167
|
+
});
|
|
3168
|
+
// Sort: entry first, then alphabetical
|
|
3169
|
+
boxesByLane.forEach(function (arr) {
|
|
3170
|
+
arr.sort(function (a,b) {
|
|
3171
|
+
if ((a.hasEntry?1:0) !== (b.hasEntry?1:0)) return (b.hasEntry?1:0) - (a.hasEntry?1:0);
|
|
3172
|
+
return a.title.localeCompare(b.title);
|
|
3173
|
+
});
|
|
3174
|
+
});
|
|
3175
|
+
var headerH = 36;
|
|
3176
|
+
var boxPos = new Map();
|
|
3177
|
+
boxesByLane.forEach(function (arr, laneId) {
|
|
3178
|
+
var lp = lanePos.get(laneId);
|
|
3179
|
+
if (!arr.length) return;
|
|
3180
|
+
var availH = H - headerH - 24;
|
|
3181
|
+
var maxBoxH = Math.min(64, Math.max(46, availH / Math.max(1, arr.length) - 10));
|
|
3182
|
+
var boxPad = 10;
|
|
3183
|
+
var totalH = arr.length * (maxBoxH + boxPad);
|
|
3184
|
+
var startY = headerH + Math.max(8, (availH - totalH) / 2);
|
|
3185
|
+
arr.forEach(function (box, i) {
|
|
3186
|
+
var w = Math.max(140, lp.w - 28);
|
|
3187
|
+
var x = lp.x + (lp.w - w) / 2;
|
|
3188
|
+
boxPos.set(box.id, { x: x, y: startY + i * (maxBoxH + boxPad), w: w, h: maxBoxH, box: box, laneId: laneId });
|
|
3189
|
+
});
|
|
3190
|
+
});
|
|
3191
|
+
return { lanePos: lanePos, boxPos: boxPos };
|
|
3192
|
+
}
|
|
3193
|
+
|
|
3194
|
+
function renderFlowsSwimlane(g, W, H) {
|
|
3195
|
+
var map = state.map;
|
|
3196
|
+
var layout = layoutSwimlanes(map, W, H);
|
|
3197
|
+
// Lane headers + dividers
|
|
3198
|
+
layout.lanePos.forEach(function (lp) {
|
|
3199
|
+
g.appendChild(el("text", { class: "layer-label", x: lp.x + 14, y: 22 }, lp.lane.name));
|
|
3200
|
+
g.appendChild(el("line", { class: "lane-divider", x1: lp.x + lp.w, y1: 0, x2: lp.x + lp.w, y2: H }));
|
|
3201
|
+
});
|
|
3202
|
+
|
|
3203
|
+
var flow = state.selectedFlow ? map.flows.find(function (f) { return f.id === state.selectedFlow; }) : null;
|
|
3204
|
+
var inFlow = new Set();
|
|
3205
|
+
var selectedStepIds = new Set();
|
|
3206
|
+
if (flow) {
|
|
3207
|
+
for (var i=0; i<flow.steps.length; i++) {
|
|
3208
|
+
inFlow.add(flow.steps[i].from); inFlow.add(flow.steps[i].to);
|
|
3209
|
+
if (state.selectedStep && flow.steps[i].n === state.selectedStep) {
|
|
3210
|
+
selectedStepIds.add(flow.steps[i].from); selectedStepIds.add(flow.steps[i].to);
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
// Boxes
|
|
3216
|
+
layout.boxPos.forEach(function (p, id) {
|
|
3217
|
+
var box = p.box;
|
|
3218
|
+
var hi = flow && inFlow.has(id);
|
|
3219
|
+
var dim = flow && !inFlow.has(id);
|
|
3220
|
+
var isSelStep = selectedStepIds.has(id);
|
|
3221
|
+
var node = el("g", { class: "flow-box", transform: "translate(" + p.x + "," + p.y + ")" });
|
|
3222
|
+
var rect = el("rect", {
|
|
3223
|
+
width: p.w, height: p.h, rx: 6, ry: 6,
|
|
3224
|
+
fill: hi ? (isSelStep ? "#3a2c00" : "#1f1900") : "rgba(28,37,48,0.55)",
|
|
3225
|
+
stroke: hi ? "#ffdf5d" : (box.color || "#3a4858"),
|
|
3226
|
+
"stroke-width": hi ? (isSelStep ? 2 : 1.4) : 1,
|
|
3227
|
+
opacity: dim ? 0.12 : 1,
|
|
3228
|
+
});
|
|
3229
|
+
node.appendChild(rect);
|
|
3230
|
+
node.appendChild(el("text", { x: 12, y: 19, fill: hi ? "#ffdf5d" : "#e6edf3",
|
|
3231
|
+
"font-size": 12, "font-weight": 600, opacity: dim ? 0.2 : 1 }, truncate(box.title, 28)));
|
|
3232
|
+
if (box.sublabel) {
|
|
3233
|
+
node.appendChild(el("text", { x: 12, y: 35, fill: "#8b949e", "font-size": 10,
|
|
3234
|
+
opacity: dim ? 0.2 : 1 }, truncate(box.sublabel, 36)));
|
|
3235
|
+
}
|
|
3236
|
+
node.addEventListener("click", function (ev) {
|
|
3237
|
+
ev.stopPropagation();
|
|
3238
|
+
state.selected = { kind: "box", id: id };
|
|
3239
|
+
renderDetail();
|
|
3240
|
+
render();
|
|
3241
|
+
});
|
|
3242
|
+
g.appendChild(node);
|
|
3243
|
+
});
|
|
3244
|
+
|
|
3245
|
+
// Flow arrows + numbered step circles
|
|
3246
|
+
if (flow) {
|
|
3247
|
+
var arrowDefs = el("defs");
|
|
3248
|
+
arrowDefs.innerHTML = '<marker id="arrowhead-flow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#ffdf5d"/></marker>';
|
|
3249
|
+
g.appendChild(arrowDefs);
|
|
3250
|
+
|
|
3251
|
+
// Count intra-package step indices per box so we can stack inline chips
|
|
3252
|
+
var intraStackByBox = new Map();
|
|
3253
|
+
|
|
3254
|
+
function chipAt(boxPos, idx, step, active) {
|
|
3255
|
+
// Position chip inside box, stacked along the right edge near the bottom
|
|
3256
|
+
var px = boxPos.x + boxPos.w - 18;
|
|
3257
|
+
var py = boxPos.y + boxPos.h - 12 - idx * 20;
|
|
3258
|
+
// Wrap if too tall: shift left and reset
|
|
3259
|
+
if (py < boxPos.y + 36) { px = boxPos.x + boxPos.w - 18 - 22; py = boxPos.y + boxPos.h - 12; }
|
|
3260
|
+
var chip = el("g", { class: "step-num" + (active ? " active" : ""), transform: "translate(" + px + "," + py + ")" });
|
|
3261
|
+
chip.appendChild(el("circle", { r: 8, fill: active ? "#fff" : "#ffdf5d", stroke: "#0b0d10", "stroke-width": 1.5 }));
|
|
3262
|
+
chip.appendChild(el("text", { y: 3, "text-anchor": "middle", "font-size": 9, "font-weight": 700, fill: "#0b0d10" }, String(step.n)));
|
|
3263
|
+
chip.addEventListener("click", function (n) { return function (ev) { ev.stopPropagation(); selectStep(n); }; }(step.n));
|
|
3264
|
+
g.appendChild(chip);
|
|
3265
|
+
}
|
|
3266
|
+
|
|
3267
|
+
for (var si=0; si<flow.steps.length; si++) {
|
|
3268
|
+
var step = flow.steps[si];
|
|
3269
|
+
// Resolve box positions, falling back to boxFrom/boxTo for intra-package module-level steps
|
|
3270
|
+
var fromKey = layout.boxPos.has(step.from) ? step.from : step.boxFrom;
|
|
3271
|
+
var toKey = layout.boxPos.has(step.to) ? step.to : step.boxTo;
|
|
3272
|
+
var from = layout.boxPos.get(fromKey);
|
|
3273
|
+
var to = layout.boxPos.get(toKey);
|
|
3274
|
+
if (!from || !to) continue;
|
|
3275
|
+
var active = state.selectedStep === step.n;
|
|
3276
|
+
var intra = fromKey === toKey;
|
|
3277
|
+
|
|
3278
|
+
if (intra) {
|
|
3279
|
+
// Render an inline numbered chip inside the box (no arrow)
|
|
3280
|
+
var idx = intraStackByBox.get(fromKey) || 0;
|
|
3281
|
+
intraStackByBox.set(fromKey, idx + 1);
|
|
3282
|
+
chipAt(from, idx, step, active);
|
|
3283
|
+
continue;
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
var sameLane = from.laneId === to.laneId;
|
|
3287
|
+
var x1, y1, x2, y2;
|
|
3288
|
+
if (sameLane) {
|
|
3289
|
+
if (to.y > from.y) {
|
|
3290
|
+
x1 = from.x + from.w / 2; y1 = from.y + from.h;
|
|
3291
|
+
x2 = to.x + to.w / 2; y2 = to.y;
|
|
3292
|
+
} else {
|
|
3293
|
+
x1 = from.x + from.w / 2; y1 = from.y;
|
|
3294
|
+
x2 = to.x + to.w / 2; y2 = to.y + to.h;
|
|
3295
|
+
}
|
|
3296
|
+
} else if (to.x > from.x) {
|
|
3297
|
+
x1 = from.x + from.w; y1 = from.y + from.h / 2;
|
|
3298
|
+
x2 = to.x; y2 = to.y + to.h / 2;
|
|
3299
|
+
} else {
|
|
3300
|
+
x1 = from.x; y1 = from.y + from.h / 2;
|
|
3301
|
+
x2 = to.x + to.w; y2 = to.y + to.h / 2;
|
|
3302
|
+
}
|
|
3303
|
+
var p = el("path", {
|
|
3304
|
+
class: "edge flow" + (active ? " active" : ""),
|
|
3305
|
+
d: flowPath(x1, y1, x2, y2),
|
|
3306
|
+
"marker-end": "url(#arrowhead-flow)",
|
|
3307
|
+
opacity: active || state.selectedStep == null ? 0.95 : 0.35,
|
|
3308
|
+
});
|
|
3309
|
+
g.appendChild(p);
|
|
3310
|
+
var mx = (x1 + x2) / 2;
|
|
3311
|
+
var my = (y1 + y2) / 2;
|
|
3312
|
+
var circle = el("g", {
|
|
3313
|
+
class: "step-num" + (active ? " active" : ""),
|
|
3314
|
+
transform: "translate(" + mx + "," + my + ")"
|
|
3315
|
+
});
|
|
3316
|
+
circle.appendChild(el("circle", { r: 11, fill: active ? "#fff" : "#ffdf5d", stroke: "#0b0d10", "stroke-width": 2 }));
|
|
3317
|
+
circle.appendChild(el("text", { y: 4, "text-anchor": "middle", "font-size": 11, "font-weight": 700, fill: "#0b0d10" }, String(step.n)));
|
|
3318
|
+
circle.addEventListener("click", function (n) {
|
|
3319
|
+
return function (ev) { ev.stopPropagation(); selectStep(n); };
|
|
3320
|
+
}(step.n));
|
|
3321
|
+
g.appendChild(circle);
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3326
|
+
function flowPath(x1, y1, x2, y2) {
|
|
3327
|
+
// S-curve for cleaner routing
|
|
3328
|
+
var dx = x2 - x1, dy = y2 - y1;
|
|
3329
|
+
if (Math.abs(dx) > Math.abs(dy)) {
|
|
3330
|
+
var c1x = x1 + dx * 0.5, c1y = y1;
|
|
3331
|
+
var c2x = x2 - dx * 0.5, c2y = y2;
|
|
3332
|
+
return "M " + x1 + " " + y1 + " C " + c1x + " " + c1y + ", " + c2x + " " + c2y + ", " + x2 + " " + y2;
|
|
3333
|
+
} else {
|
|
3334
|
+
var c1xv = x1, c1yv = y1 + dy * 0.5;
|
|
3335
|
+
var c2xv = x2, c2yv = y2 - dy * 0.5;
|
|
3336
|
+
return "M " + x1 + " " + y1 + " C " + c1xv + " " + c1yv + ", " + c2xv + " " + c2yv + ", " + x2 + " " + y2;
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
|
|
3340
|
+
function layoutSystem(map, W, H) {
|
|
3341
|
+
var containers = map.containers.map(function (c) {
|
|
3342
|
+
var mods = map.modules.filter(function (m) { return containerIdOf(m) === c.id; });
|
|
3343
|
+
var counts = {};
|
|
3344
|
+
for (var i=0; i<mods.length; i++) {
|
|
3345
|
+
var l = layerOf(mods[i]); counts[l] = (counts[l] || 0) + 1;
|
|
3346
|
+
}
|
|
3347
|
+
var dominant = LAYER_ORDER.slice().sort(function (a,b) { return (counts[b]||0) - (counts[a]||0); })[0] || "support";
|
|
3348
|
+
var sinks = new Set();
|
|
3349
|
+
for (var j=0; j<mods.length; j++) (mods[j].sinks || []).forEach(function (s) { sinks.add(s); });
|
|
3350
|
+
return Object.assign({}, c, { dominant: dominant, moduleCount: mods.length,
|
|
3351
|
+
hasEntry: mods.some(function (m) { return !!m.entryPoint; }), sinks: Array.from(sinks) });
|
|
3352
|
+
});
|
|
3353
|
+
containers.sort(function (a,b) {
|
|
3354
|
+
var d = LAYER_ORDER.indexOf(a.dominant) - LAYER_ORDER.indexOf(b.dominant);
|
|
3355
|
+
return d !== 0 ? d : b.moduleCount - a.moduleCount;
|
|
3356
|
+
});
|
|
3357
|
+
var bandH = H / LAYER_ORDER.length;
|
|
3358
|
+
var positions = new Map();
|
|
3359
|
+
var perLayer = new Map();
|
|
3360
|
+
containers.forEach(function (c) {
|
|
3361
|
+
if (!perLayer.has(c.dominant)) perLayer.set(c.dominant, []);
|
|
3362
|
+
perLayer.get(c.dominant).push(c);
|
|
3363
|
+
});
|
|
3364
|
+
perLayer.forEach(function (cs, layer) {
|
|
3365
|
+
var idx = LAYER_ORDER.indexOf(layer);
|
|
3366
|
+
var y = bandH * idx + bandH / 2;
|
|
3367
|
+
var cols = Math.max(1, cs.length);
|
|
3368
|
+
cs.forEach(function (c, i) {
|
|
3369
|
+
var colW = W / cols;
|
|
3370
|
+
var x = colW * i + colW / 2;
|
|
3371
|
+
var w = Math.max(120, Math.min(colW * 0.85, 80 + Math.sqrt(c.moduleCount) * 26));
|
|
3372
|
+
var h = Math.max(60, Math.min(bandH * 0.8, 50 + Math.sqrt(c.moduleCount) * 14));
|
|
3373
|
+
positions.set(c.id, { x: x - w / 2, y: y - h / 2, w: w, h: h, container: c });
|
|
3374
|
+
});
|
|
3375
|
+
});
|
|
3376
|
+
return { positions: positions, containers: containers };
|
|
3377
|
+
}
|
|
3378
|
+
|
|
3379
|
+
function layoutModules(map, W, H) {
|
|
3380
|
+
var containers = map.containers.slice().sort(function (a,b) { return b.moduleCount - a.moduleCount; });
|
|
3381
|
+
var n = containers.length;
|
|
3382
|
+
var cols = Math.ceil(Math.sqrt(n * (W / H)));
|
|
3383
|
+
var rows = Math.ceil(n / cols);
|
|
3384
|
+
var pad = 16;
|
|
3385
|
+
var cellW = (W - pad) / cols;
|
|
3386
|
+
var cellH = (H - pad) / rows;
|
|
3387
|
+
var containerPos = new Map();
|
|
3388
|
+
containers.forEach(function (c, i) {
|
|
3389
|
+
var cx = i % cols, cy = Math.floor(i / cols);
|
|
3390
|
+
containerPos.set(c.id, { x: pad + cx * cellW, y: pad + cy * cellH, w: cellW - pad, h: cellH - pad, container: c });
|
|
3391
|
+
});
|
|
3392
|
+
var modulePos = new Map();
|
|
3393
|
+
containers.forEach(function (c) {
|
|
3394
|
+
var slot = containerPos.get(c.id); if (!slot) return;
|
|
3395
|
+
var mods = map.modules.filter(function (m) { return containerIdOf(m) === c.id; });
|
|
3396
|
+
mods.sort(function (a,b) {
|
|
3397
|
+
if ((a.entryPoint?1:0) !== (b.entryPoint?1:0)) return (b.entryPoint?1:0) - (a.entryPoint?1:0);
|
|
3398
|
+
var la = LAYER_ORDER.indexOf(layerOf(a)), lb = LAYER_ORDER.indexOf(layerOf(b));
|
|
3399
|
+
if (la !== lb) return la - lb;
|
|
3400
|
+
return b.loc - a.loc;
|
|
3401
|
+
});
|
|
3402
|
+
if (mods.length === 0) return;
|
|
3403
|
+
var innerW = slot.w - 16, innerH = slot.h - 28;
|
|
3404
|
+
var mcols = Math.max(1, Math.ceil(Math.sqrt(mods.length * Math.max(0.001, innerW / Math.max(1, innerH)))));
|
|
3405
|
+
var mw = innerW / mcols, mh = innerH / Math.max(1, Math.ceil(mods.length / mcols));
|
|
3406
|
+
mods.forEach(function (m, i) {
|
|
3407
|
+
var x = slot.x + 8 + (i % mcols) * mw + mw / 2;
|
|
3408
|
+
var y = slot.y + 22 + Math.floor(i / mcols) * mh + mh / 2;
|
|
3409
|
+
modulePos.set(m.id, { x: x, y: y, m: m });
|
|
3410
|
+
});
|
|
3411
|
+
});
|
|
3412
|
+
return { containerPos: containerPos, modulePos: modulePos, containers: containers };
|
|
3413
|
+
}
|
|
3414
|
+
|
|
3415
|
+
function el(tag, attrs, text) {
|
|
3416
|
+
var e = document.createElementNS(SVG_NS, tag);
|
|
3417
|
+
if (attrs) for (var k in attrs) {
|
|
3418
|
+
if (attrs[k] == null) continue;
|
|
3419
|
+
e.setAttribute(k, attrs[k]);
|
|
3420
|
+
}
|
|
3421
|
+
if (text != null) e.textContent = text;
|
|
3422
|
+
return e;
|
|
3423
|
+
}
|
|
3424
|
+
function arrow(x1, y1, x2, y2, attrs) {
|
|
3425
|
+
var dx = x2 - x1, dy = y2 - y1;
|
|
3426
|
+
var c1x = x1 + dx * 0.25, c1y = y1 + dy * 0.5;
|
|
3427
|
+
var c2x = x1 + dx * 0.75, c2y = y2 - dy * 0.1;
|
|
3428
|
+
attrs = attrs || {};
|
|
3429
|
+
var p = el("path", Object.assign({}, attrs, { d: "M" + x1 + " " + y1 + " C " + c1x + " " + c1y + ", " + c2x + " " + c2y + ", " + x2 + " " + y2 }));
|
|
3430
|
+
return p;
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
function render() {
|
|
3434
|
+
var map = state.map; if (!map) return;
|
|
3435
|
+
var W = svg.clientWidth, H = svg.clientHeight;
|
|
3436
|
+
svg.innerHTML = "";
|
|
3437
|
+
var g = el("g", { id: "world" });
|
|
3438
|
+
tx(g);
|
|
3439
|
+
svg.appendChild(g);
|
|
3440
|
+
if (state.view === "architecture") renderArchitecture(g, W, H);
|
|
3441
|
+
else if (state.view === "modules") renderModules(g, W, H);
|
|
3442
|
+
else if (state.view === "insights") renderInsights(g, W, H);
|
|
3443
|
+
else if (state.view === "concepts") renderConcepts(g, W, H);
|
|
3444
|
+
else if (state.view === "graph") renderGraph(g, W, H);
|
|
3445
|
+
else if (state.view === "calls") renderCalls(g, W, H);
|
|
3446
|
+
else renderFlowsSwimlane(g, W, H);
|
|
3447
|
+
$("legend").innerHTML = legendHtml();
|
|
3448
|
+
$("hud").textContent = hudText();
|
|
3449
|
+
}
|
|
3450
|
+
|
|
3451
|
+
function legendHtml() {
|
|
3452
|
+
var s = "";
|
|
3453
|
+
if (state.view === "architecture" && state.map.groups) {
|
|
3454
|
+
state.map.groups.forEach(function (gr) {
|
|
3455
|
+
s += '<div class="row"><div class="dot" style="background:' + gr.color + '"></div>' + escapeHtml(gr.name) + '</div>';
|
|
3456
|
+
});
|
|
3457
|
+
} else if (state.view === "flows" && state.map.lanes) {
|
|
3458
|
+
state.map.lanes.forEach(function (l) {
|
|
3459
|
+
s += '<div class="row"><div class="dot" style="background:' + l.color + '"></div>' + l.name + '</div>';
|
|
3460
|
+
});
|
|
3461
|
+
} else if (state.view === "insights") {
|
|
3462
|
+
(state.map.clusters || []).slice(0, 8).forEach(function (c) {
|
|
3463
|
+
s += '<div class="row"><div class="dot" style="background:' + clusterColor(c.id) + '"></div>' + escapeHtml(c.label) + ' (' + c.size + ')</div>';
|
|
3464
|
+
});
|
|
3465
|
+
s += '<div class="row"><div class="dot" style="background:#fff;border:1px solid #888"></div>god node (larger)</div>';
|
|
3466
|
+
s += '<div class="row"><div class="dot" style="background:#ff5c5c"></div>surprising edge</div>';
|
|
3467
|
+
} else {
|
|
3468
|
+
LAYER_ORDER.forEach(function (l) {
|
|
3469
|
+
s += '<div class="row"><div class="dot" style="background:' + LAYER_COLOR[l] + '"></div>' + l + '</div>';
|
|
3470
|
+
});
|
|
3471
|
+
s += '<div class="row"><div class="dot" style="background:#ffdf5d"></div>entry point</div>';
|
|
3472
|
+
s += '<div class="row"><div class="dot" style="background:#ff7b72"></div>sink</div>';
|
|
3473
|
+
}
|
|
3474
|
+
return s;
|
|
3475
|
+
}
|
|
3476
|
+
function hudText() {
|
|
3477
|
+
if (state.view === "architecture") {
|
|
3478
|
+
var c = (state.map.containers || []).length;
|
|
3479
|
+
var gN = (state.map.groups || []).length;
|
|
3480
|
+
return "Architecture · " + gN + " groups, " + c + " packages · click a package · double-click a group to focus · ESC to clear";
|
|
3481
|
+
}
|
|
3482
|
+
if (state.view === "flows") {
|
|
3483
|
+
if (state.selectedFlow) {
|
|
3484
|
+
var f = state.map.flows.find(function (x) { return x.id === state.selectedFlow; });
|
|
3485
|
+
return f ? "FLOW: " + f.name + " — " + f.steps.length + " steps" : "";
|
|
3486
|
+
}
|
|
3487
|
+
return "Pick a flow on the right to highlight the path through the system";
|
|
3488
|
+
}
|
|
3489
|
+
if (state.view === "insights") {
|
|
3490
|
+
var god = (state.map.hotspots && state.map.hotspots.godNodes) || [];
|
|
3491
|
+
return "Insights · " + ((state.map.clusters || []).length) + " clusters · " + god.length + " god-nodes · " + ((state.map.surprisingConnections || []).length) + " surprising edges · hover a node for detail";
|
|
3492
|
+
}
|
|
3493
|
+
if (state.view === "concepts") {
|
|
3494
|
+
return "Concepts · " + ((state.map.clusters || []).length) + " clusters as nodes · edges = cross-cluster imports · hover for counts";
|
|
3495
|
+
}
|
|
3496
|
+
if (state.view === "graph") {
|
|
3497
|
+
var total = (state.map.modules || []).length;
|
|
3498
|
+
var shown = (state.map.modules || []).filter(function (m) { return !m.isTest; }).length;
|
|
3499
|
+
return "Knowledge graph · " + shown + " of " + total + " modules (tests hidden) · grouped by cluster · edges = imports";
|
|
3500
|
+
}
|
|
3501
|
+
if (state.view === "calls") {
|
|
3502
|
+
return "Calls · symbol-level call graph around one module (god-node by default) · callers ← center → callees · hover a node for its path";
|
|
3503
|
+
}
|
|
3504
|
+
if (state.focus) return "focused on " + state.focus.kind + ":" + state.focus.id + " — " + state.focus.set.size + " module(s) (esc to clear)";
|
|
3505
|
+
return state.view + " view · scroll = zoom · drag = pan · click = focus";
|
|
3506
|
+
}
|
|
3507
|
+
|
|
3508
|
+
// ====================== Architecture (nested-containers) view ======================
|
|
3509
|
+
|
|
3510
|
+
// Slice-and-dice treemap: divides a rect into N sub-rects weighted by item.weight.
|
|
3511
|
+
function slice(rect, items, getWeight) {
|
|
3512
|
+
if (items.length === 0) return [];
|
|
3513
|
+
var total = 0;
|
|
3514
|
+
for (var i=0; i<items.length; i++) total += Math.max(1, getWeight(items[i]));
|
|
3515
|
+
var out = [];
|
|
3516
|
+
var horizontal = rect.w >= rect.h;
|
|
3517
|
+
var cx = rect.x, cy = rect.y;
|
|
3518
|
+
for (var j=0; j<items.length; j++) {
|
|
3519
|
+
var w = Math.max(1, getWeight(items[j]));
|
|
3520
|
+
var frac = w / total;
|
|
3521
|
+
if (horizontal) {
|
|
3522
|
+
var subW = Math.max(1, rect.w * frac);
|
|
3523
|
+
out.push({ x: cx, y: rect.y, w: subW, h: rect.h, item: items[j] });
|
|
3524
|
+
cx += subW;
|
|
3525
|
+
} else {
|
|
3526
|
+
var subH = Math.max(1, rect.h * frac);
|
|
3527
|
+
out.push({ x: rect.x, y: cy, w: rect.w, h: subH, item: items[j] });
|
|
3528
|
+
cy += subH;
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
return out;
|
|
3532
|
+
}
|
|
3533
|
+
|
|
3534
|
+
// Grid layout that always fits N items into a rect, deterministic columns by aspect ratio.
|
|
3535
|
+
function gridLayout(rect, items) {
|
|
3536
|
+
if (items.length === 0) return [];
|
|
3537
|
+
var aspect = rect.w / Math.max(1, rect.h);
|
|
3538
|
+
var cols = Math.max(1, Math.round(Math.sqrt(items.length * aspect)));
|
|
3539
|
+
cols = Math.min(cols, items.length);
|
|
3540
|
+
var rows = Math.ceil(items.length / cols);
|
|
3541
|
+
var cw = rect.w / cols, rh = rect.h / rows;
|
|
3542
|
+
var out = [];
|
|
3543
|
+
for (var i=0; i<items.length; i++) {
|
|
3544
|
+
var col = i % cols, row = Math.floor(i / cols);
|
|
3545
|
+
out.push({ x: rect.x + col * cw, y: rect.y + row * rh, w: cw, h: rh, item: items[i] });
|
|
3546
|
+
}
|
|
3547
|
+
return out;
|
|
3548
|
+
}
|
|
3549
|
+
|
|
3550
|
+
function layoutArchitecture(map, W, H) {
|
|
3551
|
+
var groups = (map.groups || []).slice();
|
|
3552
|
+
if (groups.length === 0) return { groupPos: new Map(), packagePos: new Map() };
|
|
3553
|
+
groups.sort(function (a, b) { return (b.moduleCount || 0) - (a.moduleCount || 0); });
|
|
3554
|
+
var pad = 18, gap = 12;
|
|
3555
|
+
var outerRect = { x: pad, y: pad, w: W - pad * 2, h: H - pad * 2 };
|
|
3556
|
+
// Use slice-and-dice weighted by sqrt(moduleCount) so small groups stay readable.
|
|
3557
|
+
var groupSlots = slice(outerRect, groups, function (g) { return Math.sqrt(Math.max(1, g.moduleCount || 1)); });
|
|
3558
|
+
var groupPos = new Map();
|
|
3559
|
+
var packagePos = new Map();
|
|
3560
|
+
for (var i=0; i<groupSlots.length; i++) {
|
|
3561
|
+
var slot = groupSlots[i];
|
|
3562
|
+
var grp = slot.item;
|
|
3563
|
+
var inset = { x: slot.x + gap/2, y: slot.y + gap/2, w: slot.w - gap, h: slot.h - gap };
|
|
3564
|
+
var collapsed = !!state.collapsedGroups[grp.id];
|
|
3565
|
+
groupPos.set(grp.id, { x: inset.x, y: inset.y, w: inset.w, h: inset.h, group: grp, collapsed: collapsed });
|
|
3566
|
+
if (collapsed) continue;
|
|
3567
|
+
var memberContainers = grp.members.map(function (id) { return map.containers.find(function (c) { return c.id === id; }); }).filter(Boolean);
|
|
3568
|
+
if (memberContainers.length === 0) continue;
|
|
3569
|
+
var headerH = 34;
|
|
3570
|
+
var pkgRect = { x: inset.x + 8, y: inset.y + headerH, w: Math.max(40, inset.w - 16), h: Math.max(40, inset.h - headerH - 8) };
|
|
3571
|
+
// Grid layout — always fits everything inside the group
|
|
3572
|
+
var pkgSlots = gridLayout(pkgRect, memberContainers);
|
|
3573
|
+
for (var k=0; k<pkgSlots.length; k++) {
|
|
3574
|
+
var ps = pkgSlots[k];
|
|
3575
|
+
var ix = ps.x + 3, iy = ps.y + 3, iw = Math.max(40, ps.w - 6), ih = Math.max(34, ps.h - 6);
|
|
3576
|
+
packagePos.set(ps.item.id, { x: ix, y: iy, w: iw, h: ih, container: ps.item, groupId: grp.id });
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
return { groupPos: groupPos, packagePos: packagePos };
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
function hideTooltip() { $("tooltip").style.display = "none"; }
|
|
3583
|
+
function showTooltip(html, ev) {
|
|
3584
|
+
var tt = $("tooltip");
|
|
3585
|
+
tt.innerHTML = html;
|
|
3586
|
+
tt.style.display = "block";
|
|
3587
|
+
// Position relative to viewport, clamped to viz
|
|
3588
|
+
var viz = $("viz").getBoundingClientRect();
|
|
3589
|
+
var x = (ev.clientX - viz.left) + 14;
|
|
3590
|
+
var y = (ev.clientY - viz.top) + 14;
|
|
3591
|
+
var ttW = tt.offsetWidth, ttH = tt.offsetHeight;
|
|
3592
|
+
if (x + ttW > viz.width) x = viz.width - ttW - 6;
|
|
3593
|
+
if (y + ttH > viz.height) y = viz.height - ttH - 6;
|
|
3594
|
+
tt.style.left = x + "px"; tt.style.top = y + "px";
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
function tooltipPackageHtml(container, groupName) {
|
|
3598
|
+
var top = (container.topFiles || []).slice(0, 5);
|
|
3599
|
+
var html = '<div class="tt-title">' + escapeHtml(container.name) + '</div>';
|
|
3600
|
+
if (container.description) html += '<div class="tt-desc">' + escapeHtml(container.description) + '</div>';
|
|
3601
|
+
html += '<div class="tt-section">Group</div><div>' + escapeHtml(groupName || "—") + '</div>';
|
|
3602
|
+
if (top.length) {
|
|
3603
|
+
html += '<div class="tt-section">Top Files (' + top.length + ')</div><ul>';
|
|
3604
|
+
for (var i=0; i<top.length; i++) {
|
|
3605
|
+
html += '<li><span class="tt-reason">' + escapeHtml(top[i].reason) + '</span>' +
|
|
3606
|
+
'<span>' + escapeHtml(top[i].path.split("/").slice(-2).join("/")) + '</span>' +
|
|
3607
|
+
'<span class="tt-loc">' + top[i].loc + '</span></li>';
|
|
3608
|
+
}
|
|
3609
|
+
html += '</ul>';
|
|
3610
|
+
}
|
|
3611
|
+
return html;
|
|
3612
|
+
}
|
|
3613
|
+
|
|
3614
|
+
function tooltipEdgeHtml(edge) {
|
|
3615
|
+
var labels = (edge.labels || [edge.label]).join(", ");
|
|
3616
|
+
var samples = (edge.symbolSamples || []).slice(0, 5).map(function (s) { return '<code>' + escapeHtml(s) + '</code>'; }).join(", ");
|
|
3617
|
+
var html = '<div class="tt-title">' + escapeHtml(edge.from.replace(/^pkg:/, "")) +
|
|
3618
|
+
' <span style="color:var(--muted)">→</span> ' + escapeHtml(edge.to.replace(/^pkg:/, "")) + '</div>';
|
|
3619
|
+
html += '<div class="tt-desc"><b>' + escapeHtml(labels) + '</b> · ' +
|
|
3620
|
+
edge.count + ' imports · ' + (edge.callCount || 0) + ' calls</div>';
|
|
3621
|
+
if (samples) html += '<div class="tt-section">Top symbols</div><div>' + samples + '</div>';
|
|
3622
|
+
return html;
|
|
3623
|
+
}
|
|
3624
|
+
|
|
3625
|
+
function renderArchitecture(g, W, H) {
|
|
3626
|
+
var map = state.map;
|
|
3627
|
+
var layout = layoutArchitecture(map, W, H);
|
|
3628
|
+
state.lastArchLayout = layout;
|
|
3629
|
+
var groups = map.groups || [];
|
|
3630
|
+
var groupById = {}; for (var ig=0; ig<groups.length; ig++) groupById[groups[ig].id] = groups[ig];
|
|
3631
|
+
|
|
3632
|
+
// 1) Group rectangles (containers)
|
|
3633
|
+
layout.groupPos.forEach(function (gp, id) {
|
|
3634
|
+
var grp = gp.group;
|
|
3635
|
+
var color = grp.color || "#8b949e";
|
|
3636
|
+
var focusedGroup = state.focus && state.focus.kind === "group" && state.focus.id === id;
|
|
3637
|
+
var rect = el("rect", {
|
|
3638
|
+
class: "group-rect" + (gp.collapsed ? " collapsed" : "") + (focusedGroup ? " focused" : ""),
|
|
3639
|
+
x: gp.x, y: gp.y, width: gp.w, height: gp.h, rx: 12, ry: 12,
|
|
3640
|
+
stroke: color, fill: "rgba(28,37,48,0.32)",
|
|
3641
|
+
});
|
|
3642
|
+
g.appendChild(rect);
|
|
3643
|
+
// Header strip
|
|
3644
|
+
g.appendChild(el("rect", { class: "group-header",
|
|
3645
|
+
x: gp.x, y: gp.y, width: gp.w, height: 30, rx: 12, ry: 12 }));
|
|
3646
|
+
g.appendChild(el("text", { class: "group-name", x: gp.x + 14, y: gp.y + 20, fill: color }, grp.name));
|
|
3647
|
+
var sub = grp.members.length + " pkgs · " + (grp.moduleCount || 0) + " modules" + (grp.source === "curated" ? " · curated" : "");
|
|
3648
|
+
g.appendChild(el("text", { class: "group-sub", x: gp.x + gp.w - 14, y: gp.y + 20, "text-anchor": "end" }, sub));
|
|
3649
|
+
// Click on header area toggles collapse; double-click sets focus
|
|
3650
|
+
rect.addEventListener("dblclick", function (ev) {
|
|
3651
|
+
ev.stopPropagation();
|
|
3652
|
+
var set = new Set();
|
|
3653
|
+
for (var i=0; i<map.containers.length; i++) {
|
|
3654
|
+
var c = map.containers[i];
|
|
3655
|
+
if (c.groupId === id) {
|
|
3656
|
+
set.add(c.id);
|
|
3657
|
+
var mods = map.modules.filter(function (m) { return containerIdOf(m) === c.id; });
|
|
3658
|
+
for (var k=0; k<mods.length; k++) set.add(mods[k].id);
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
state.focus = { kind: "group", id: id, set: set };
|
|
3662
|
+
render();
|
|
3663
|
+
});
|
|
3664
|
+
// Click on header (top 30px) toggles collapse
|
|
3665
|
+
rect.addEventListener("click", function (ev) {
|
|
3666
|
+
var rectBox = rect.getBoundingClientRect();
|
|
3667
|
+
if (ev.clientY - rectBox.top <= 30) {
|
|
3668
|
+
ev.stopPropagation();
|
|
3669
|
+
state.collapsedGroups[id] = !state.collapsedGroups[id];
|
|
3670
|
+
render();
|
|
3671
|
+
}
|
|
3672
|
+
});
|
|
3673
|
+
});
|
|
3674
|
+
|
|
3675
|
+
// 2) Package rectangles inside expanded groups
|
|
3676
|
+
layout.packagePos.forEach(function (pp, id) {
|
|
3677
|
+
var c = pp.container;
|
|
3678
|
+
var grp = groupById[pp.groupId] || { color: "#3a4858" };
|
|
3679
|
+
var sel = state.selected && state.selected.kind === "box" && state.selected.id === id;
|
|
3680
|
+
var dim = state.focus && !state.focus.set.has(id);
|
|
3681
|
+
var rect = el("rect", {
|
|
3682
|
+
class: "pkg-rect" + (sel ? " selected" : "") + (dim ? " dim" : ""),
|
|
3683
|
+
x: pp.x, y: pp.y, width: pp.w, height: pp.h, rx: 8, ry: 8,
|
|
3684
|
+
stroke: grp.color || "#3a4858",
|
|
3685
|
+
});
|
|
3686
|
+
g.appendChild(rect);
|
|
3687
|
+
g.appendChild(el("text", { class: "pkg-title", x: pp.x + 10, y: pp.y + 18 },
|
|
3688
|
+
truncate(c.name, Math.max(8, Math.floor(pp.w / 7.5)))));
|
|
3689
|
+
var entryCount = (c.topFiles || []).filter(function (t) { return /entry|HTTP/.test(t.reason); }).length;
|
|
3690
|
+
var sub = (c.moduleCount || 0) + " modules" + (entryCount ? " · " + entryCount + " entry" : "");
|
|
3691
|
+
g.appendChild(el("text", { class: "pkg-sub", x: pp.x + 10, y: pp.y + 32 }, sub));
|
|
3692
|
+
// Show 1-3 top file paths inline if there's vertical space
|
|
3693
|
+
if (pp.h >= 76) {
|
|
3694
|
+
var top = (c.topFiles || []).slice(0, Math.min(3, Math.floor((pp.h - 40) / 14)));
|
|
3695
|
+
for (var t=0; t<top.length; t++) {
|
|
3696
|
+
var label = top[t].reason + ": " + top[t].path.split("/").slice(-2).join("/");
|
|
3697
|
+
g.appendChild(el("text", { class: "pkg-topfiles", x: pp.x + 10, y: pp.y + 48 + t * 13 },
|
|
3698
|
+
truncate(label, Math.max(10, Math.floor(pp.w / 6.5)))));
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
rect.addEventListener("click", function (ev) {
|
|
3702
|
+
ev.stopPropagation();
|
|
3703
|
+
state.selected = { kind: "box", id: id };
|
|
3704
|
+
renderDetail();
|
|
3705
|
+
render();
|
|
3706
|
+
});
|
|
3707
|
+
rect.addEventListener("mouseenter", function (ev) {
|
|
3708
|
+
showTooltip(tooltipPackageHtml(c, grp.name), ev);
|
|
3709
|
+
});
|
|
3710
|
+
rect.addEventListener("mousemove", function (ev) {
|
|
3711
|
+
showTooltip(tooltipPackageHtml(c, grp.name), ev);
|
|
3712
|
+
});
|
|
3713
|
+
rect.addEventListener("mouseleave", hideTooltip);
|
|
3714
|
+
});
|
|
3715
|
+
|
|
3716
|
+
// 3) Build collapsed cross-group edges if any group is collapsed
|
|
3717
|
+
var collapsedSet = new Set(Object.keys(state.collapsedGroups).filter(function (k) { return state.collapsedGroups[k]; }));
|
|
3718
|
+
// Build container → group lookup
|
|
3719
|
+
var groupOfContainer = {}; for (var ic=0; ic<map.containers.length; ic++) groupOfContainer[map.containers[ic].id] = map.containers[ic].groupId;
|
|
3720
|
+
|
|
3721
|
+
// 4) Cross-package + cross-group edges with labeled chips
|
|
3722
|
+
var crossGroupAgg = new Map(); // "fromG→toG" -> agg
|
|
3723
|
+
var edges = map.containerEdges || [];
|
|
3724
|
+
var defs = el("defs");
|
|
3725
|
+
defs.innerHTML = '<marker id="arrow-cross" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#7ee787"/></marker>' +
|
|
3726
|
+
'<marker id="arrow-flow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#ffdf5d"/></marker>';
|
|
3727
|
+
g.appendChild(defs);
|
|
3728
|
+
|
|
3729
|
+
for (var ei=0; ei<edges.length; ei++) {
|
|
3730
|
+
var edge = edges[ei];
|
|
3731
|
+
var fromG = groupOfContainer[edge.from];
|
|
3732
|
+
var toG = groupOfContainer[edge.to];
|
|
3733
|
+
var fromCollapsed = collapsedSet.has(fromG);
|
|
3734
|
+
var toCollapsed = collapsedSet.has(toG);
|
|
3735
|
+
if (fromCollapsed || toCollapsed) {
|
|
3736
|
+
var k = fromG + "→" + toG;
|
|
3737
|
+
if (!crossGroupAgg.has(k)) crossGroupAgg.set(k, { from: fromG, to: toG, count: 0, callCount: 0, labels: new Set() });
|
|
3738
|
+
var ag = crossGroupAgg.get(k);
|
|
3739
|
+
ag.count += edge.count;
|
|
3740
|
+
ag.callCount += (edge.callCount || 0);
|
|
3741
|
+
ag.labels.add(edge.label);
|
|
3742
|
+
continue;
|
|
3743
|
+
}
|
|
3744
|
+
var fromPos = layout.packagePos.get(edge.from);
|
|
3745
|
+
var toPos = layout.packagePos.get(edge.to);
|
|
3746
|
+
if (!fromPos || !toPos) continue;
|
|
3747
|
+
var x1, y1, x2, y2;
|
|
3748
|
+
// Pick anchor points on box edges nearest to the other box
|
|
3749
|
+
var fcx = fromPos.x + fromPos.w/2, fcy = fromPos.y + fromPos.h/2;
|
|
3750
|
+
var tcx = toPos.x + toPos.w/2, tcy = toPos.y + toPos.h/2;
|
|
3751
|
+
if (Math.abs(tcx - fcx) >= Math.abs(tcy - fcy)) {
|
|
3752
|
+
// Horizontal-dominant: use right/left edges
|
|
3753
|
+
x1 = tcx > fcx ? fromPos.x + fromPos.w : fromPos.x;
|
|
3754
|
+
y1 = fcy;
|
|
3755
|
+
x2 = tcx > fcx ? toPos.x : toPos.x + toPos.w;
|
|
3756
|
+
y2 = tcy;
|
|
3757
|
+
} else {
|
|
3758
|
+
x1 = fcx;
|
|
3759
|
+
y1 = tcy > fcy ? fromPos.y + fromPos.h : fromPos.y;
|
|
3760
|
+
x2 = tcx;
|
|
3761
|
+
y2 = tcy > fcy ? toPos.y : toPos.y + toPos.h;
|
|
3762
|
+
}
|
|
3763
|
+
var sw = Math.min(4, 0.8 + Math.log2(edge.count + 1));
|
|
3764
|
+
var path = el("path", {
|
|
3765
|
+
class: "edge cross",
|
|
3766
|
+
d: flowPath(x1, y1, x2, y2),
|
|
3767
|
+
"stroke-width": sw,
|
|
3768
|
+
"marker-end": "url(#arrow-cross)",
|
|
3769
|
+
});
|
|
3770
|
+
g.appendChild(path);
|
|
3771
|
+
// Wide invisible hit area for hover
|
|
3772
|
+
var hit = el("path", {
|
|
3773
|
+
class: "edge-hit", d: flowPath(x1, y1, x2, y2),
|
|
3774
|
+
});
|
|
3775
|
+
g.appendChild(hit);
|
|
3776
|
+
hit.addEventListener("mouseenter", function (e) { return function (ev) { showTooltip(tooltipEdgeHtml(e), ev); }; }(edge));
|
|
3777
|
+
hit.addEventListener("mousemove", function (e) { return function (ev) { showTooltip(tooltipEdgeHtml(e), ev); }; }(edge));
|
|
3778
|
+
hit.addEventListener("mouseleave", hideTooltip);
|
|
3779
|
+
// Label chip at midpoint (skip when edge is too short)
|
|
3780
|
+
var dist = Math.hypot(x2 - x1, y2 - y1);
|
|
3781
|
+
if (dist >= 80 && edge.label) {
|
|
3782
|
+
var mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
|
|
3783
|
+
var labelText = edge.label;
|
|
3784
|
+
var chipW = labelText.length * 6.2 + 12;
|
|
3785
|
+
var labelClass = "edge-label-text " + labelText.toLowerCase().replace(/\s+/g, "-");
|
|
3786
|
+
var chip = el("g", { transform: "translate(" + mx + "," + my + ")" });
|
|
3787
|
+
chip.appendChild(el("rect", { class: "edge-label-bg", x: -chipW/2, y: -9, width: chipW, height: 18, rx: 4, ry: 4 }));
|
|
3788
|
+
chip.appendChild(el("text", { class: labelClass, x: 0, y: 3, "text-anchor": "middle" }, labelText));
|
|
3789
|
+
g.appendChild(chip);
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
|
|
3793
|
+
// 5) Collapsed group → group aggregate edges
|
|
3794
|
+
crossGroupAgg.forEach(function (agg) {
|
|
3795
|
+
var fromGP = layout.groupPos.get(agg.from), toGP = layout.groupPos.get(agg.to);
|
|
3796
|
+
if (!fromGP || !toGP) return;
|
|
3797
|
+
var fcx = fromGP.x + fromGP.w/2, fcy = fromGP.y + fromGP.h/2;
|
|
3798
|
+
var tcx = toGP.x + toGP.w/2, tcy = toGP.y + toGP.h/2;
|
|
3799
|
+
var x1, y1, x2, y2;
|
|
3800
|
+
if (Math.abs(tcx - fcx) >= Math.abs(tcy - fcy)) {
|
|
3801
|
+
x1 = tcx > fcx ? fromGP.x + fromGP.w : fromGP.x; y1 = fcy;
|
|
3802
|
+
x2 = tcx > fcx ? toGP.x : toGP.x + toGP.w; y2 = tcy;
|
|
3803
|
+
} else {
|
|
3804
|
+
x1 = fcx; y1 = tcy > fcy ? fromGP.y + fromGP.h : fromGP.y;
|
|
3805
|
+
x2 = tcx; y2 = tcy > fcy ? toGP.y : toGP.y + toGP.h;
|
|
3806
|
+
}
|
|
3807
|
+
g.appendChild(el("path", { class: "edge cross", d: flowPath(x1, y1, x2, y2),
|
|
3808
|
+
"stroke-width": Math.min(6, 1.5 + Math.log2(agg.count + 1)),
|
|
3809
|
+
"marker-end": "url(#arrow-cross)" }));
|
|
3810
|
+
var mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
|
|
3811
|
+
var labelText = (agg.from.replace(/^group:/, "") + " → " + agg.to.replace(/^group:/, "") + " · " + agg.count);
|
|
3812
|
+
var chipW = labelText.length * 6.2 + 12;
|
|
3813
|
+
var chip = el("g", { transform: "translate(" + mx + "," + my + ")" });
|
|
3814
|
+
chip.appendChild(el("rect", { class: "edge-label-bg", x: -chipW/2, y: -9, width: chipW, height: 18, rx: 4, ry: 4 }));
|
|
3815
|
+
chip.appendChild(el("text", { class: "edge-label-text", x: 0, y: 3, "text-anchor": "middle" }, labelText));
|
|
3816
|
+
g.appendChild(chip);
|
|
3817
|
+
});
|
|
3818
|
+
|
|
3819
|
+
// 6) Optional yellow flow overlay
|
|
3820
|
+
if (state.overlayFlow && state.selectedFlow) {
|
|
3821
|
+
overlayFlowOnArchitecture(g, layout);
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
|
|
3825
|
+
function overlayFlowOnArchitecture(g, layout) {
|
|
3826
|
+
var map = state.map;
|
|
3827
|
+
var flow = map.flows.find(function (f) { return f.id === state.selectedFlow; });
|
|
3828
|
+
if (!flow) return;
|
|
3829
|
+
var intraStack = new Map();
|
|
3830
|
+
for (var si=0; si<flow.steps.length; si++) {
|
|
3831
|
+
var step = flow.steps[si];
|
|
3832
|
+
var fromKey = layout.packagePos.has(step.from) ? step.from : step.boxFrom;
|
|
3833
|
+
var toKey = layout.packagePos.has(step.to) ? step.to : step.boxTo;
|
|
3834
|
+
var from = layout.packagePos.get(fromKey);
|
|
3835
|
+
var to = layout.packagePos.get(toKey);
|
|
3836
|
+
if (!from || !to) continue;
|
|
3837
|
+
if (fromKey === toKey) {
|
|
3838
|
+
// Intra-package chip
|
|
3839
|
+
var idx = intraStack.get(fromKey) || 0;
|
|
3840
|
+
intraStack.set(fromKey, idx + 1);
|
|
3841
|
+
var px = from.x + from.w - 16, py = from.y + from.h - 12 - idx * 18;
|
|
3842
|
+
if (py < from.y + 36) { px = from.x + from.w - 16 - 20; py = from.y + from.h - 12; }
|
|
3843
|
+
var chip = el("g", { transform: "translate(" + px + "," + py + ")" });
|
|
3844
|
+
chip.appendChild(el("circle", { r: 7, fill: "#ffdf5d", stroke: "#0b0d10", "stroke-width": 1.5 }));
|
|
3845
|
+
chip.appendChild(el("text", { y: 3, "text-anchor": "middle", "font-size": 9, "font-weight": 700, fill: "#0b0d10" }, String(step.n)));
|
|
3846
|
+
g.appendChild(chip);
|
|
3847
|
+
continue;
|
|
3848
|
+
}
|
|
3849
|
+
var x1 = from.x + from.w / 2, y1 = from.y + from.h / 2;
|
|
3850
|
+
var x2 = to.x + to.w / 2, y2 = to.y + to.h / 2;
|
|
3851
|
+
g.appendChild(el("path", { class: "edge flow", d: flowPath(x1, y1, x2, y2),
|
|
3852
|
+
"stroke-width": 2, "marker-end": "url(#arrow-flow)" }));
|
|
3853
|
+
var mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
|
|
3854
|
+
var chip2 = el("g", { transform: "translate(" + mx + "," + my + ")" });
|
|
3855
|
+
chip2.appendChild(el("circle", { r: 10, fill: "#ffdf5d", stroke: "#0b0d10", "stroke-width": 2 }));
|
|
3856
|
+
chip2.appendChild(el("text", { y: 4, "text-anchor": "middle", "font-size": 10, "font-weight": 700, fill: "#0b0d10" }, String(step.n)));
|
|
3857
|
+
g.appendChild(chip2);
|
|
3858
|
+
}
|
|
3859
|
+
}
|
|
3860
|
+
|
|
3861
|
+
function renderSystem(g, W, H) {
|
|
3862
|
+
var map = state.map;
|
|
3863
|
+
var layout = layoutSystem(map, W, H);
|
|
3864
|
+
var bandH = H / LAYER_ORDER.length;
|
|
3865
|
+
for (var i=0; i<LAYER_ORDER.length; i++) {
|
|
3866
|
+
var l = LAYER_ORDER[i];
|
|
3867
|
+
g.appendChild(el("text", { class:"layer-label", x: 10, y: bandH * i + 14 }, l));
|
|
3868
|
+
g.appendChild(el("line", { class:"layer-band", x1: 0, x2: W, y1: bandH * (i+1), y2: bandH * (i+1) }));
|
|
3869
|
+
}
|
|
3870
|
+
for (var ei=0; ei<map.containerEdges.length; ei++) {
|
|
3871
|
+
var ed = map.containerEdges[ei];
|
|
3872
|
+
var a = layout.positions.get(ed.from), b = layout.positions.get(ed.to);
|
|
3873
|
+
if (!a || !b) continue;
|
|
3874
|
+
var ax = a.x + a.w / 2, ay = a.y + a.h / 2;
|
|
3875
|
+
var bx = b.x + b.w / 2, by = b.y + b.h / 2;
|
|
3876
|
+
var hi = state.focus && state.focus.kind === "package" && (state.focus.id === ed.from || state.focus.id === ed.to);
|
|
3877
|
+
var sw = Math.min(6, 1 + Math.log2(ed.count + 1));
|
|
3878
|
+
g.appendChild(arrow(ax, ay, bx, by, { class: "edge cross" + (hi ? " hi" : ""), "stroke-width": sw }));
|
|
3879
|
+
}
|
|
3880
|
+
layout.positions.forEach(function (p, id) {
|
|
3881
|
+
var c = p.container;
|
|
3882
|
+
var hi = (state.focus && state.focus.kind === "package" && state.focus.id === id);
|
|
3883
|
+
var rect = el("rect", { class: "container-rect" + (hi ? " hi" : ""),
|
|
3884
|
+
x: p.x, y: p.y, width: p.w, height: p.h, rx: 10, ry: 10 });
|
|
3885
|
+
rect.style.cursor = "pointer";
|
|
3886
|
+
rect.addEventListener("click", function (ev) { ev.stopPropagation(); focusPackage(id); });
|
|
3887
|
+
g.appendChild(rect);
|
|
3888
|
+
g.appendChild(el("text", { class: "container-label", x: p.x + 10, y: p.y + 16 }, c.name));
|
|
3889
|
+
g.appendChild(el("text", { class: "container-label", x: p.x + 10, y: p.y + 32, fill: LAYER_COLOR[c.dominant] },
|
|
3890
|
+
c.dominant + " · " + c.moduleCount + "m" + (c.hasEntry ? " · entry" : "") + (c.sinks.length ? " · " + c.sinks.length + " sinks" : "")));
|
|
3891
|
+
});
|
|
3892
|
+
}
|
|
3893
|
+
|
|
3894
|
+
function renderModules(g, W, H) {
|
|
3895
|
+
var map = state.map;
|
|
3896
|
+
var layout = layoutModules(map, W, H);
|
|
3897
|
+
layout.containerPos.forEach(function (p, cid) {
|
|
3898
|
+
var hi = (state.focus && state.focus.kind === "package" && state.focus.id === cid);
|
|
3899
|
+
var r = el("rect", { class: "container-rect" + (hi ? " hi" : ""),
|
|
3900
|
+
x: p.x, y: p.y, width: p.w, height: p.h, rx: 8, ry: 8 });
|
|
3901
|
+
g.appendChild(r);
|
|
3902
|
+
g.appendChild(el("text", { class: "container-label", x: p.x + 8, y: p.y + 14 }, p.container.name));
|
|
3903
|
+
});
|
|
3904
|
+
for (var i=0; i<map.edges.length; i++) {
|
|
3905
|
+
var e = map.edges[i]; if (e.kind !== "import") continue;
|
|
3906
|
+
var a = layout.modulePos.get(e.from), b = layout.modulePos.get(e.to);
|
|
3907
|
+
if (!a || !b) continue;
|
|
3908
|
+
var focused = state.focus && state.focus.set.has(e.from) && state.focus.set.has(e.to);
|
|
3909
|
+
var dim = state.focus && !focused;
|
|
3910
|
+
var cross = containerIdOf(a.m) !== containerIdOf(b.m);
|
|
3911
|
+
g.appendChild(arrow(a.x, a.y, b.x, b.y, { class: "edge" + (cross ? " cross" : "") + (dim ? " dim" : "") + (focused ? " hi" : ""), "stroke-width": cross ? 1.4 : 0.8 }));
|
|
3912
|
+
}
|
|
3913
|
+
layout.modulePos.forEach(function (p, id) {
|
|
3914
|
+
var m = p.m;
|
|
3915
|
+
var dim = state.focus && !state.focus.set.has(id);
|
|
3916
|
+
var color = m.entryPoint ? "#ffdf5d" : (m.sinks && m.sinks.length > 0 ? "#ff7b72" : LAYER_COLOR[layerOf(m)]);
|
|
3917
|
+
var r = Math.max(2.5, Math.min(10, 2 + Math.sqrt(Math.max(1, m.loc / 25))));
|
|
3918
|
+
var node = el("g", { class: "module-node", transform: "translate(" + p.x + "," + p.y + ")" });
|
|
3919
|
+
if (dim) node.style.opacity = 0.15;
|
|
3920
|
+
node.appendChild(el("circle", { r: r, fill: color }));
|
|
3921
|
+
if (m.entryPoint) node.appendChild(el("circle", { r: r + 3, fill: "none", stroke: "#ffdf5d", "stroke-width": 1 }));
|
|
3922
|
+
g.appendChild(node);
|
|
3923
|
+
});
|
|
3924
|
+
}
|
|
3925
|
+
|
|
3926
|
+
// ====================== Insights view (clusters · god-nodes · surprising connections) ======================
|
|
3927
|
+
function clusterColor(cid) {
|
|
3928
|
+
if (!cid) return "#8b949e";
|
|
3929
|
+
var h = 0; for (var i=0; i<cid.length; i++) h = (h * 31 + cid.charCodeAt(i)) % 360;
|
|
3930
|
+
return "hsl(" + h + ",58%,62%)";
|
|
3931
|
+
}
|
|
3932
|
+
function renderInsights(g, W, H) {
|
|
3933
|
+
var map = state.map;
|
|
3934
|
+
var layout = layoutModules(map, W, H);
|
|
3935
|
+
var god = (map.hotspots && map.hotspots.godNodes) || [];
|
|
3936
|
+
var godIds = new Set(god.map(function (x) { return x.id; }));
|
|
3937
|
+
var godBy = {}; god.forEach(function (x) { godBy[x.id] = x; });
|
|
3938
|
+
layout.containerPos.forEach(function (p) {
|
|
3939
|
+
g.appendChild(el("rect", { class: "container-rect", x: p.x, y: p.y, width: p.w, height: p.h, rx: 8, ry: 8 }));
|
|
3940
|
+
g.appendChild(el("text", { class: "container-label", x: p.x + 8, y: p.y + 14 }, p.container.name));
|
|
3941
|
+
});
|
|
3942
|
+
// Surprising connections as hot dashed edges (only these — keeps the view legible).
|
|
3943
|
+
((map.surprisingConnections) || []).forEach(function (x) {
|
|
3944
|
+
var a = layout.modulePos.get(x.from), b = layout.modulePos.get(x.to);
|
|
3945
|
+
if (!a || !b) return;
|
|
3946
|
+
var p = arrow(a.x, a.y, b.x, b.y, { class: "edge", stroke: "#ff5c5c", "stroke-width": 1.6, "stroke-dasharray": "4 3", opacity: 0.85 });
|
|
3947
|
+
p.appendChild(el("title", null, "surprising: " + x.reason + " (score " + x.score + ")"));
|
|
3948
|
+
g.appendChild(p);
|
|
3949
|
+
});
|
|
3950
|
+
// Module nodes colored by cluster; god-nodes enlarged + outlined.
|
|
3951
|
+
layout.modulePos.forEach(function (p, id) {
|
|
3952
|
+
var m = p.m;
|
|
3953
|
+
var isGod = godIds.has(id);
|
|
3954
|
+
var r = isGod ? Math.max(6, Math.min(16, 5 + Math.sqrt((m.loc || 1) / 20))) : Math.max(2, Math.min(8, 1.5 + Math.sqrt(Math.max(1, (m.loc || 1) / 30))));
|
|
3955
|
+
var node = el("g", { class: "module-node", transform: "translate(" + p.x + "," + p.y + ")" });
|
|
3956
|
+
var c = el("circle", { r: r, fill: clusterColor(m.cluster), stroke: isGod ? "#ffffff" : "none", "stroke-width": isGod ? 1.5 : 0 });
|
|
3957
|
+
node.appendChild(c);
|
|
3958
|
+
node.appendChild(el("title", null, m.path + (isGod ? " — god node (in " + godBy[id].inDegree + " · out " + godBy[id].outDegree + ")" : (m.cluster ? " — cluster " + m.cluster : ""))));
|
|
3959
|
+
g.appendChild(node);
|
|
3960
|
+
});
|
|
3961
|
+
}
|
|
3962
|
+
|
|
3963
|
+
// ===================== Knowledge-graph family (Concepts / Graph / Calls) =====================
|
|
3964
|
+
// Deterministic radial placement of clusters around the canvas center (largest first).
|
|
3965
|
+
function clusterCentroids(map, W, H) {
|
|
3966
|
+
var clusters = (map.clusters || []).slice().sort(function (a, b) { return b.size - a.size || (a.id < b.id ? -1 : 1); });
|
|
3967
|
+
var cx = W / 2, cy = H / 2, R = Math.min(W, H) * 0.40;
|
|
3968
|
+
var pos = new Map();
|
|
3969
|
+
var n = clusters.length || 1;
|
|
3970
|
+
clusters.forEach(function (c, i) {
|
|
3971
|
+
var ang = (i / n) * Math.PI * 2 - Math.PI / 2;
|
|
3972
|
+
var ring = R * (0.5 + 0.5 * ((i % 3) / 2));
|
|
3973
|
+
pos.set(c.id, { x: cx + Math.cos(ang) * ring, y: cy + Math.sin(ang) * ring, c: c });
|
|
3974
|
+
});
|
|
3975
|
+
return { clusters: clusters, pos: pos, cx: cx, cy: cy };
|
|
3976
|
+
}
|
|
3977
|
+
// Cross-cluster import/re-export weights — the edges of the concept graph.
|
|
3978
|
+
function crossClusterEdges(map) {
|
|
3979
|
+
var cl = {}; (map.modules || []).forEach(function (m) { cl[m.id] = m.cluster; });
|
|
3980
|
+
var w = {};
|
|
3981
|
+
(map.edges || []).forEach(function (e) {
|
|
3982
|
+
if (e.kind !== "import" && e.kind !== "re-export") return;
|
|
3983
|
+
var a = cl[e.from], b = cl[e.to];
|
|
3984
|
+
if (!a || !b || a === b) return;
|
|
3985
|
+
var key = a < b ? a + "\t" + b : b + "\t" + a;
|
|
3986
|
+
w[key] = (w[key] || 0) + 1;
|
|
3987
|
+
});
|
|
3988
|
+
return Object.keys(w).sort().map(function (k) { var p = k.split("\t"); return { a: p[0], b: p[1], weight: w[k] }; });
|
|
3989
|
+
}
|
|
3990
|
+
|
|
3991
|
+
// Concepts — cluster-level graph: nodes = clusters (sized by member count), edges = cross-cluster imports.
|
|
3992
|
+
function renderConcepts(g, W, H) {
|
|
3993
|
+
var map = state.map;
|
|
3994
|
+
var L = clusterCentroids(map, W, H);
|
|
3995
|
+
var edges = crossClusterEdges(map);
|
|
3996
|
+
var maxW = edges.reduce(function (mx, e) { return Math.max(mx, e.weight); }, 1);
|
|
3997
|
+
edges.forEach(function (e) {
|
|
3998
|
+
var a = L.pos.get(e.a), b = L.pos.get(e.b); if (!a || !b) return;
|
|
3999
|
+
var ln = el("line", { x1: a.x, y1: a.y, x2: b.x, y2: b.y, stroke: "#3a4658", "stroke-width": 0.6 + 3.6 * (e.weight / maxW), opacity: 0.5 });
|
|
4000
|
+
ln.appendChild(el("title", null, e.a + " ↔ " + e.b + " — " + e.weight + " imports"));
|
|
4001
|
+
g.appendChild(ln);
|
|
4002
|
+
});
|
|
4003
|
+
L.clusters.forEach(function (c) {
|
|
4004
|
+
var p = L.pos.get(c.id); if (!p) return;
|
|
4005
|
+
var r = Math.max(9, Math.min(48, 6 + Math.sqrt(c.size) * 3));
|
|
4006
|
+
var node = el("g", { class: "module-node", transform: "translate(" + p.x + "," + p.y + ")" });
|
|
4007
|
+
node.appendChild(el("circle", { r: r, fill: clusterColor(c.id), opacity: 0.85, stroke: "#0d1117", "stroke-width": 1.5 }));
|
|
4008
|
+
node.appendChild(el("text", { "text-anchor": "middle", y: 4, fill: "#0d1117", "font-size": Math.max(9, Math.min(14, r / 2)), "font-weight": 700 }, String(c.size)));
|
|
4009
|
+
node.appendChild(el("text", { "text-anchor": "middle", y: r + 13, fill: "#c9d1d9", "font-size": 11 }, (c.label || c.id).slice(0, 30)));
|
|
4010
|
+
node.appendChild(el("title", null, (c.label || c.id) + " — " + c.size + " modules"));
|
|
4011
|
+
g.appendChild(node);
|
|
4012
|
+
});
|
|
4013
|
+
}
|
|
4014
|
+
|
|
4015
|
+
// Graph — node-link of every (non-test) module, grouped around its cluster centroid, with import edges.
|
|
4016
|
+
function renderGraph(g, W, H) {
|
|
4017
|
+
var map = state.map;
|
|
4018
|
+
var L = clusterCentroids(map, W, H);
|
|
4019
|
+
var fallback = (map.clusters && map.clusters[0] && map.clusters[0].id) || null;
|
|
4020
|
+
var idx = {}, pos = new Map();
|
|
4021
|
+
(map.modules || []).forEach(function (m) {
|
|
4022
|
+
if (m.isTest) return;
|
|
4023
|
+
var c = m.cluster || fallback;
|
|
4024
|
+
var cen = L.pos.get(c) || { x: W / 2, y: H / 2 };
|
|
4025
|
+
var k = idx[c] = (idx[c] || 0); idx[c] = k + 1;
|
|
4026
|
+
var ang = k * 2.399963229; // golden angle — deterministic spiral, no RNG
|
|
4027
|
+
var rad = 5 + Math.sqrt(k) * 7;
|
|
4028
|
+
pos.set(m.id, { x: cen.x + Math.cos(ang) * rad, y: cen.y + Math.sin(ang) * rad, m: m });
|
|
4029
|
+
});
|
|
4030
|
+
(map.edges || []).forEach(function (e) {
|
|
4031
|
+
if (e.kind !== "import" && e.kind !== "re-export") return;
|
|
4032
|
+
var a = pos.get(e.from), b = pos.get(e.to); if (!a || !b) return;
|
|
4033
|
+
g.appendChild(el("line", { x1: a.x, y1: a.y, x2: b.x, y2: b.y, stroke: "#2a3340", "stroke-width": 0.4, opacity: 0.35 }));
|
|
4034
|
+
});
|
|
4035
|
+
pos.forEach(function (p) {
|
|
4036
|
+
var m = p.m;
|
|
4037
|
+
var r = Math.max(1.6, Math.min(7, 1.4 + Math.sqrt((m.loc || 1) / 40)));
|
|
4038
|
+
var node = el("g", { class: "module-node", transform: "translate(" + p.x + "," + p.y + ")" });
|
|
4039
|
+
node.appendChild(el("circle", { r: r, fill: clusterColor(m.cluster), opacity: 0.9 }));
|
|
4040
|
+
node.appendChild(el("title", null, m.path + (m.cluster ? " — " + m.cluster : "")));
|
|
4041
|
+
g.appendChild(node);
|
|
4042
|
+
});
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
// Calls — egocentric symbol call graph: callers on the left, callees on the right, edges labelled by symbol.
|
|
4046
|
+
function renderCalls(g, W, H) {
|
|
4047
|
+
var map = state.map;
|
|
4048
|
+
var ces = map.callEdges || [];
|
|
4049
|
+
var modById = {}; (map.modules || []).forEach(function (m) { modById[m.id] = m; });
|
|
4050
|
+
var center = (state.selected && modById[state.selected]) ? state.selected : null;
|
|
4051
|
+
if (!center) { var god = map.hotspots && map.hotspots.godNodes && map.hotspots.godNodes[0]; center = god ? god.id : (ces[0] && ces[0].from) || null; }
|
|
4052
|
+
if (!center) { g.appendChild(el("text", { x: W / 2, y: H / 2, "text-anchor": "middle", fill: "#8b949e" }, "No call edges — click a module in another view.")); return; }
|
|
4053
|
+
var callees = ces.filter(function (e) { return e.from === center; }).slice(0, 24);
|
|
4054
|
+
var callers = ces.filter(function (e) { return e.to === center; }).slice(0, 24);
|
|
4055
|
+
var cx = W / 2, cy = H / 2;
|
|
4056
|
+
function placeColumn(list, side) {
|
|
4057
|
+
var x = cx + side * Math.min(W * 0.36, 360);
|
|
4058
|
+
var n = list.length || 1;
|
|
4059
|
+
list.forEach(function (e, i) {
|
|
4060
|
+
var y = (H * (i + 1)) / (n + 1);
|
|
4061
|
+
var other = side > 0 ? e.to : e.from;
|
|
4062
|
+
g.appendChild(side > 0
|
|
4063
|
+
? arrow(cx + 9, cy, x - 6, y, { fill: "none", stroke: "#4f8cc9", "stroke-width": 1.1, opacity: 0.8 })
|
|
4064
|
+
: arrow(x + 6, y, cx - 9, cy, { fill: "none", stroke: "#c98a4f", "stroke-width": 1.1, opacity: 0.8 }));
|
|
4065
|
+
g.appendChild(el("text", { x: (x + cx) / 2, y: (y + cy) / 2 - 3, "text-anchor": "middle", fill: "#8b949e", "font-size": 9 }, e.symbol || ""));
|
|
4066
|
+
var node = el("g", { class: "module-node", transform: "translate(" + x + "," + y + ")" });
|
|
4067
|
+
node.appendChild(el("circle", { r: 5, fill: clusterColor((modById[other] || {}).cluster) }));
|
|
4068
|
+
node.appendChild(el("text", { "text-anchor": side > 0 ? "start" : "end", x: side > 0 ? 9 : -9, y: 3, fill: "#c9d1d9", "font-size": 10 }, (other.split("/").pop())));
|
|
4069
|
+
node.appendChild(el("title", null, other));
|
|
4070
|
+
g.appendChild(node);
|
|
4071
|
+
});
|
|
4072
|
+
}
|
|
4073
|
+
placeColumn(callers, -1);
|
|
4074
|
+
placeColumn(callees, 1);
|
|
4075
|
+
var cnode = el("g", { transform: "translate(" + cx + "," + cy + ")" });
|
|
4076
|
+
cnode.appendChild(el("circle", { r: 9, fill: clusterColor((modById[center] || {}).cluster), stroke: "#fff", "stroke-width": 2 }));
|
|
4077
|
+
cnode.appendChild(el("text", { "text-anchor": "middle", y: -14, fill: "#fff", "font-size": 11, "font-weight": 700 }, center.split("/").pop()));
|
|
4078
|
+
g.appendChild(cnode);
|
|
4079
|
+
}
|
|
4080
|
+
|
|
4081
|
+
// ====================== Sidebars ======================
|
|
4082
|
+
|
|
4083
|
+
function renderSidebar() {
|
|
4084
|
+
var map = state.map;
|
|
4085
|
+
var ents = $("entry-list"); ents.innerHTML = "";
|
|
4086
|
+
var groups = { cli:[], http:[], library:[] };
|
|
4087
|
+
for (var i=0; i<map.entryPoints.length; i++) {
|
|
4088
|
+
var e = map.entryPoints[i];
|
|
4089
|
+
(groups[e.kind] = groups[e.kind] || []).push(e);
|
|
4090
|
+
}
|
|
4091
|
+
["cli","http","library"].forEach(function (kind) {
|
|
4092
|
+
if (!groups[kind] || groups[kind].length === 0) return;
|
|
4093
|
+
var head = document.createElement("div");
|
|
4094
|
+
head.style.padding = "4px 14px"; head.style.color = "var(--muted)";
|
|
4095
|
+
head.style.fontSize = "10px"; head.style.textTransform = "uppercase"; head.style.letterSpacing = "1.2px";
|
|
4096
|
+
head.textContent = kind + " (" + groups[kind].length + ")";
|
|
4097
|
+
ents.appendChild(head);
|
|
4098
|
+
groups[kind].forEach(function (e) {
|
|
4099
|
+
var row = document.createElement("div"); row.className = "row";
|
|
4100
|
+
var label = e.name || e.path.split("/").pop();
|
|
4101
|
+
var sub = e.routes ? e.routes.slice(0,2).map(function (r) { return r.method + " " + r.path; }).join(", ") : (e.package || "");
|
|
4102
|
+
row.innerHTML = '<div class="dot" style="background:var(--entry)"></div>' +
|
|
4103
|
+
'<div class="name" title="' + escapeHtml(e.path) + '"><div>' + escapeHtml(label) + '</div>' +
|
|
4104
|
+
'<div style="color:var(--muted); font-size:10px">' + escapeHtml(sub) + '</div></div>';
|
|
4105
|
+
row.onclick = function () { selectFlow("flow:" + e.id); };
|
|
4106
|
+
ents.appendChild(row);
|
|
4107
|
+
});
|
|
4108
|
+
});
|
|
4109
|
+
|
|
4110
|
+
var sinkCounts = {};
|
|
4111
|
+
for (var si=0; si<map.sinks.length; si++) {
|
|
4112
|
+
var s = map.sinks[si];
|
|
4113
|
+
for (var sk=0; sk<s.sinks.length; sk++) sinkCounts[s.sinks[sk]] = (sinkCounts[s.sinks[sk]] || 0) + 1;
|
|
4114
|
+
}
|
|
4115
|
+
var sl = $("sink-list"); sl.innerHTML = "";
|
|
4116
|
+
Object.keys(sinkCounts).sort(function (a,b) { return sinkCounts[b] - sinkCounts[a]; }).forEach(function (k) {
|
|
4117
|
+
var row = document.createElement("div"); row.className = "row";
|
|
4118
|
+
row.innerHTML = '<div class="dot" style="background:var(--sink)"></div><div class="name">' + escapeHtml(k) + '</div><div class="count">' + sinkCounts[k] + '</div>';
|
|
4119
|
+
row.onclick = function () { focusSink(k); };
|
|
4120
|
+
sl.appendChild(row);
|
|
4121
|
+
});
|
|
4122
|
+
|
|
4123
|
+
var ll = $("layer-list"); ll.innerHTML = "";
|
|
4124
|
+
LAYER_ORDER.forEach(function (l) {
|
|
4125
|
+
var n = map.stats.layers[l] || 0; if (!n) return;
|
|
4126
|
+
var row = document.createElement("div"); row.className = "row";
|
|
4127
|
+
row.innerHTML = '<div class="dot" style="background:' + LAYER_COLOR[l] + '"></div><div class="name">' + escapeHtml(l) + '</div><div class="count">' + n + '</div>';
|
|
4128
|
+
ll.appendChild(row);
|
|
4129
|
+
});
|
|
4130
|
+
|
|
4131
|
+
var pl = $("pkg-list"); pl.innerHTML = "";
|
|
4132
|
+
map.containers.slice().sort(function (a,b) { return b.moduleCount - a.moduleCount; }).forEach(function (c) {
|
|
4133
|
+
var row = document.createElement("div"); row.className = "row";
|
|
4134
|
+
row.innerHTML = '<div class="dot" style="background:#3a4858"></div><div class="name">' + escapeHtml(c.name) + '</div><div class="count">' + c.moduleCount + '</div>';
|
|
4135
|
+
row.onclick = function () { focusPackage(c.id); };
|
|
4136
|
+
pl.appendChild(row);
|
|
4137
|
+
});
|
|
4138
|
+
}
|
|
4139
|
+
|
|
4140
|
+
function renderFlowList() {
|
|
4141
|
+
var map = state.map;
|
|
4142
|
+
var list = $("flow-list"); list.innerHTML = "";
|
|
4143
|
+
if (!map.flows || !map.flows.length) {
|
|
4144
|
+
list.innerHTML = '<div style="color:var(--muted); padding:8px 0">No flows detected. Add entry points (bin / HTTP routes) or curate .planning/codebase/FLOWS.json.</div>';
|
|
4145
|
+
return;
|
|
4146
|
+
}
|
|
4147
|
+
// Order: CLI first, then HTTP, then library
|
|
4148
|
+
var kindRank = { cli: 0, http: 1, library: 2 };
|
|
4149
|
+
var sorted = map.flows.slice().sort(function (a,b) {
|
|
4150
|
+
return (kindRank[a.entryKind]||3) - (kindRank[b.entryKind]||3);
|
|
4151
|
+
});
|
|
4152
|
+
sorted.forEach(function (f) {
|
|
4153
|
+
var item = document.createElement("div");
|
|
4154
|
+
item.className = "flow-item" + (state.selectedFlow === f.id ? " active" : "");
|
|
4155
|
+
item.innerHTML = '<div class="name">' + escapeHtml(f.name) + '</div>' +
|
|
4156
|
+
'<div class="desc">' + escapeHtml(f.description || "") + (f.curated ? ' <span style="color:var(--entry)">· curated</span>' : '') + '</div>';
|
|
4157
|
+
item.onclick = function () { selectFlow(f.id); };
|
|
4158
|
+
list.appendChild(item);
|
|
4159
|
+
});
|
|
4160
|
+
}
|
|
4161
|
+
|
|
4162
|
+
function renderStepList() {
|
|
4163
|
+
var map = state.map;
|
|
4164
|
+
var list = $("step-list"); list.innerHTML = "";
|
|
4165
|
+
var f = state.selectedFlow ? map.flows.find(function (x) { return x.id === state.selectedFlow; }) : null;
|
|
4166
|
+
if (!f) {
|
|
4167
|
+
list.innerHTML = '<div style="color:var(--muted); padding:8px 0">Select a flow above to see numbered steps.</div>';
|
|
4168
|
+
return;
|
|
4169
|
+
}
|
|
4170
|
+
f.steps.forEach(function (step) {
|
|
4171
|
+
var item = document.createElement("div");
|
|
4172
|
+
item.className = "step-item" + (state.selectedStep === step.n ? " active" : "");
|
|
4173
|
+
var fromLabel = step.from.replace(/^pkg:/, "").replace(/^sink:/, "").replace(/^actor:/, "");
|
|
4174
|
+
var toLabel = step.to.replace(/^pkg:/, "").replace(/^sink:/, "").replace(/^actor:/, "");
|
|
4175
|
+
// Split off trailing code snippet if present
|
|
4176
|
+
var descHtml = "";
|
|
4177
|
+
if (step.description) {
|
|
4178
|
+
var snippet = null; var desc = step.description;
|
|
4179
|
+
var sm = desc.match(/^(.*?)\\s*\\\`([^\\\`]+)\\\`\\s*$/);
|
|
4180
|
+
if (sm && sm[2].length > 12 && /[(){};=]/.test(sm[2])) { desc = sm[1]; snippet = sm[2]; }
|
|
4181
|
+
descHtml = '<div class="desc">' + escapeHtml(desc).replace(/\\\`([^\\\`]+)\\\`/g, function (_, t) { return '<code>' + t + '</code>'; }) + '</div>';
|
|
4182
|
+
if (snippet) descHtml += '<div class="snippet">' + escapeHtml(snippet) + '</div>';
|
|
4183
|
+
}
|
|
4184
|
+
var fileRef = "";
|
|
4185
|
+
if (step.fromFile && step.toFile) {
|
|
4186
|
+
fileRef = '<div class="file-ref">' + escapeHtml(step.fromFile.split("/").slice(-2).join("/")) + ' → ' + escapeHtml(step.toFile.split("/").slice(-2).join("/")) + '</div>';
|
|
4187
|
+
} else if (step.sinkSite) {
|
|
4188
|
+
fileRef = '<div class="file-ref">' + escapeHtml(step.sinkSite.file) + ':' + step.sinkSite.line + '</div>';
|
|
4189
|
+
} else if (step.toFile) {
|
|
4190
|
+
fileRef = '<div class="file-ref">' + escapeHtml(step.toFile) + '</div>';
|
|
4191
|
+
}
|
|
4192
|
+
item.innerHTML = '<div class="num">' + step.n + '</div>' +
|
|
4193
|
+
'<div class="body">' +
|
|
4194
|
+
'<div class="title">' + escapeHtml(step.title || (fromLabel + " → " + toLabel)) + '</div>' +
|
|
4195
|
+
'<div class="from-to">' + escapeHtml(fromLabel) + ' <span style="color:var(--entry)">→</span> ' + escapeHtml(toLabel) + '</div>' +
|
|
4196
|
+
fileRef + descHtml +
|
|
4197
|
+
'</div>';
|
|
4198
|
+
item.onclick = function () { selectStep(step.n); };
|
|
4199
|
+
list.appendChild(item);
|
|
4200
|
+
});
|
|
4201
|
+
}
|
|
4202
|
+
|
|
4203
|
+
function renderDetail() {
|
|
4204
|
+
var elD = $("detail");
|
|
4205
|
+
if (!state.selected) { elD.style.display = "none"; return; }
|
|
4206
|
+
var map = state.map;
|
|
4207
|
+
elD.style.display = "block";
|
|
4208
|
+
if (state.selected.kind === "box") {
|
|
4209
|
+
var id = state.selected.id;
|
|
4210
|
+
var box = (map.boxes || []).find(function (x) { return x.id === id; });
|
|
4211
|
+
if (!box) { elD.style.display = "none"; return; }
|
|
4212
|
+
var html = '<h3>' + escapeHtml(box.title) + '</h3>' +
|
|
4213
|
+
'<div class="pill">' + escapeHtml(box.lane) + '</div>' +
|
|
4214
|
+
(box.kind ? '<div class="pill">' + escapeHtml(box.kind) + '</div>' : '') +
|
|
4215
|
+
(box.sublabel ? '<div class="kv">' + escapeHtml(box.sublabel) + '</div>' : '');
|
|
4216
|
+
if (box.kind === "package") {
|
|
4217
|
+
var c = map.containers.find(function (x) { return x.id === id; });
|
|
4218
|
+
var mods = map.modules.filter(function (m) { return containerIdOf(m) === id; });
|
|
4219
|
+
var inE = map.containerEdges.filter(function (e) { return e.to === id; });
|
|
4220
|
+
var outE = map.containerEdges.filter(function (e) { return e.from === id; });
|
|
4221
|
+
html += '<h4 style="margin:10px 0 4px;font-size:11px;color:var(--muted)">DEPENDS ON</h4>' +
|
|
4222
|
+
(outE.length ? outE.map(function (e) { return '<div class="kv">→ ' + escapeHtml(e.to.replace(/^pkg:/,"")) + ' <span style="color:var(--muted)">(' + e.count + ')</span></div>'; }).join("") : '<div class="kv" style="color:var(--muted)">nothing</div>') +
|
|
4223
|
+
'<h4 style="margin:10px 0 4px;font-size:11px;color:var(--muted)">DEPENDED ON BY</h4>' +
|
|
4224
|
+
(inE.length ? inE.map(function (e) { return '<div class="kv">← ' + escapeHtml(e.from.replace(/^pkg:/,"")) + ' <span style="color:var(--muted)">(' + e.count + ')</span></div>'; }).join("") : '<div class="kv" style="color:var(--muted)">nothing</div>');
|
|
4225
|
+
var entryMods = mods.filter(function (m) { return !!m.entryPoint; });
|
|
4226
|
+
if (entryMods.length) {
|
|
4227
|
+
html += '<h4 style="margin:10px 0 4px;font-size:11px;color:var(--muted)">ENTRY POINTS</h4>';
|
|
4228
|
+
entryMods.forEach(function (m) {
|
|
4229
|
+
html += '<div class="kv">' + escapeHtml(m.entryPoint.name || m.path) + ' <span style="color:var(--muted)">(' + m.entryPoint.kind + ')</span></div>';
|
|
4230
|
+
});
|
|
4231
|
+
}
|
|
4232
|
+
}
|
|
4233
|
+
elD.innerHTML = html;
|
|
4234
|
+
return;
|
|
4235
|
+
}
|
|
4236
|
+
}
|
|
4237
|
+
|
|
4238
|
+
// ====================== Camera ======================
|
|
4239
|
+
function fit() { state.zoom = 1; state.pan = { x: 0, y: 0 }; render(); }
|
|
4240
|
+
|
|
4241
|
+
svg.addEventListener("mousedown", function (e) {
|
|
4242
|
+
state.drag = { x: e.clientX, y: e.clientY, pan: { x: state.pan.x, y: state.pan.y } };
|
|
4243
|
+
});
|
|
4244
|
+
window.addEventListener("mousemove", function (e) {
|
|
4245
|
+
if (!state.drag) return;
|
|
4246
|
+
state.pan.x = state.drag.pan.x + (e.clientX - state.drag.x);
|
|
4247
|
+
state.pan.y = state.drag.pan.y + (e.clientY - state.drag.y);
|
|
4248
|
+
var g = svg.querySelector("#world"); if (g) tx(g);
|
|
4249
|
+
});
|
|
4250
|
+
window.addEventListener("mouseup", function () { state.drag = null; });
|
|
4251
|
+
svg.addEventListener("wheel", function (e) {
|
|
4252
|
+
e.preventDefault();
|
|
4253
|
+
var factor = Math.exp(-e.deltaY * 0.001);
|
|
4254
|
+
var rect = svg.getBoundingClientRect();
|
|
4255
|
+
var cx = e.clientX - rect.left, cy = e.clientY - rect.top;
|
|
4256
|
+
var newZoom = Math.max(0.15, Math.min(5, state.zoom * factor));
|
|
4257
|
+
state.pan.x = cx - ((cx - state.pan.x) * (newZoom / state.zoom));
|
|
4258
|
+
state.pan.y = cy - ((cy - state.pan.y) * (newZoom / state.zoom));
|
|
4259
|
+
state.zoom = newZoom;
|
|
4260
|
+
var g = svg.querySelector("#world"); if (g) tx(g);
|
|
4261
|
+
}, { passive: false });
|
|
4262
|
+
|
|
4263
|
+
window.addEventListener("keydown", function (e) {
|
|
4264
|
+
if (e.target.tagName === "INPUT") return;
|
|
4265
|
+
if (e.key === "f") fit();
|
|
4266
|
+
if (e.key === "Escape") clearFlow();
|
|
4267
|
+
if (e.key === "a") setView("architecture");
|
|
4268
|
+
if (e.key === "m") setView("modules");
|
|
4269
|
+
if (e.key === "F") setView("flows");
|
|
4270
|
+
if (e.key === "i") setView("insights");
|
|
4271
|
+
if (e.key === "c") setView("concepts");
|
|
4272
|
+
if (e.key === "g") setView("graph");
|
|
4273
|
+
if (e.key === "C") setView("calls");
|
|
4274
|
+
});
|
|
4275
|
+
|
|
4276
|
+
$("tab-architecture").onclick = function () { setView("architecture"); };
|
|
4277
|
+
$("tab-modules").onclick = function () { setView("modules"); };
|
|
4278
|
+
$("tab-flows").onclick = function () { setView("flows"); };
|
|
4279
|
+
$("tab-insights").onclick = function () { setView("insights"); };
|
|
4280
|
+
$("tab-concepts").onclick = function () { setView("concepts"); };
|
|
4281
|
+
$("tab-graph").onclick = function () { setView("graph"); };
|
|
4282
|
+
$("tab-calls").onclick = function () { setView("calls"); };
|
|
4283
|
+
$("fit").onclick = fit;
|
|
4284
|
+
$("clear").onclick = function () { clearFlow(); state.collapsedGroups = {}; state.selected = null; render(); };
|
|
4285
|
+
$("reload").onclick = function () { load(false); };
|
|
4286
|
+
var overlayCb = $("overlay-flow-cb");
|
|
4287
|
+
if (overlayCb) overlayCb.addEventListener("change", function (ev) { state.overlayFlow = ev.target.checked; render(); });
|
|
4288
|
+
|
|
4289
|
+
function connectLive() {
|
|
4290
|
+
try {
|
|
4291
|
+
var es = new EventSource("/events");
|
|
4292
|
+
es.onmessage = function (ev) { if (ev.data === "changed") load(false); };
|
|
4293
|
+
es.onerror = function () {
|
|
4294
|
+
$("live-indicator").classList.add("dead");
|
|
4295
|
+
$("live-indicator").textContent = "● offline";
|
|
4296
|
+
};
|
|
4297
|
+
es.onopen = function () {
|
|
4298
|
+
$("live-indicator").classList.remove("dead");
|
|
4299
|
+
$("live-indicator").textContent = "● live";
|
|
4300
|
+
};
|
|
4301
|
+
} catch (err) {}
|
|
4302
|
+
}
|
|
4303
|
+
|
|
4304
|
+
window.addEventListener("resize", function () { render(); });
|
|
4305
|
+
load(true).then(connectLive);
|
|
4306
|
+
</script>
|
|
4307
|
+
</body>
|
|
4308
|
+
</html>`;
|
|
4309
|
+
}
|
|
4310
|
+
|
|
4311
|
+
// GRAPH_REPORT.md — graphify's signature skimmable narrative. Fully deterministic (no LLM, no Date).
|
|
4312
|
+
function visRenderReport(map) {
|
|
4313
|
+
const L = [];
|
|
4314
|
+
const s = map.stats || {};
|
|
4315
|
+
const langs = Object.entries(s.languages || {}).filter(([k]) => k !== "other").sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 6).map(([k, v]) => `${k} ${v}`).join(", ");
|
|
4316
|
+
L.push(`# ${map.root} — Codebase Graph Report`, "");
|
|
4317
|
+
L.push("_Generated by `draht-tools map-graph`. Do not edit; regenerated each build._", "");
|
|
4318
|
+
L.push("## Overview");
|
|
4319
|
+
L.push(`${s.files} modules · ${(s.totalLoc || 0).toLocaleString()} LOC · ${s.packages} packages · ${s.edges} import edges · ${s.entryPoints} entry points · ${(map.clusters || []).length} clusters.`);
|
|
4320
|
+
L.push(`Languages: ${langs || "n/a"}.`, "");
|
|
4321
|
+
L.push("## Key concepts (structural neighborhoods)", "");
|
|
4322
|
+
L.push("> Clusters are import-topology neighborhoods, not semantic bounded contexts — confirm before treating them as such.", "");
|
|
4323
|
+
for (const c of (map.clusters || []).slice(0, 8)) {
|
|
4324
|
+
const code = (c.members || []).filter((m) => /\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|rb|php|swift|kt|cs|c|cpp)$/.test(m));
|
|
4325
|
+
const members = (code.length ? code : (c.members || [])).slice(0, 4).map((m) => "`" + m.split("/").slice(-2).join("/") + "`").join(", ");
|
|
4326
|
+
L.push(`- **${c.label}** — ${c.size} modules · ${c.dominantLayer}${members ? " · e.g. " + members : ""}`);
|
|
4327
|
+
}
|
|
4328
|
+
L.push("", "## God nodes (most connected)", "");
|
|
4329
|
+
L.push("| File | In | Out | Note |", "| --- | --- | --- | --- |");
|
|
4330
|
+
for (const g of (map.hotspots && map.hotspots.godNodes || []).slice(0, 8)) L.push(`| \`${g.path}\` | ${g.inDegree} | ${g.outDegree} | ${g.reason} |`);
|
|
4331
|
+
const sc = map.surprisingConnections || [];
|
|
4332
|
+
if (sc.length) {
|
|
4333
|
+
L.push("", "## Surprising connections", "");
|
|
4334
|
+
for (const x of sc.slice(0, 10)) {
|
|
4335
|
+
const syms = (x.sampleSymbols || []).slice(0, 3).join(", ");
|
|
4336
|
+
L.push(`- \`${x.from}\` → \`${x.to}\` — ${x.reason} (score ${x.score})${syms ? " · " + syms : ""}`);
|
|
4337
|
+
}
|
|
4338
|
+
}
|
|
4339
|
+
const rh = (map.rationaleIndex || []).filter((r) => ["SECURITY", "BUG", "FIXME", "HACK"].includes(r.tag)).slice(0, 12);
|
|
4340
|
+
if (rh.length) {
|
|
4341
|
+
L.push("", "## Rationale highlights (SECURITY / BUG / FIXME / HACK)", "");
|
|
4342
|
+
for (const r of rh) L.push(`- **${r.tag}** \`${r.file}:${r.line}\` — ${r.text}`);
|
|
4343
|
+
}
|
|
4344
|
+
L.push("", "## Suggested questions", "");
|
|
4345
|
+
const gq = [];
|
|
4346
|
+
const top = (map.hotspots && map.hotspots.godNodes || [])[0];
|
|
4347
|
+
if (top) gq.push(`Why does \`${top.path}\` have ${top.inDegree} dependents — is that coupling intended?`);
|
|
4348
|
+
const br = sc.find((x) => /bridge/.test(x.reason));
|
|
4349
|
+
if (br) gq.push(`Is the bridge \`${br.from}\` → \`${br.to}\` intended, or accidental coupling?`);
|
|
4350
|
+
const hk = (map.rationaleIndex || []).find((r) => r.tag === "HACK" || r.tag === "FIXME");
|
|
4351
|
+
if (hk) gq.push(`Should the ${hk.tag} at \`${hk.file}:${hk.line}\` be addressed? ("${hk.text}")`);
|
|
4352
|
+
const big = (map.clusters || [])[0];
|
|
4353
|
+
if (big) gq.push(`Cluster "${big.label}" holds ${big.size} modules — should it be split?`);
|
|
4354
|
+
if (!gq.length) gq.push("Run `draht-tools graph-hotspots` and `graph-clusters --surprising` to explore.");
|
|
4355
|
+
for (const q of gq) L.push(`- ${q}`);
|
|
4356
|
+
L.push("", "---", "Query the graph: `draht-tools graph-context <file>` · `graph-impact <file>` · `graph-query \"<concept>\"` · `graph-hotspots` · `graph-clusters --surprising`.", "");
|
|
4357
|
+
return L.join("\n");
|
|
4358
|
+
}
|
|
4359
|
+
|
|
4360
|
+
function visWriteOutputs(root, opts = {}) {
|
|
4361
|
+
const outDir = path.join(root, PLANNING_DIR, "codebase");
|
|
4362
|
+
ensureDir(outDir);
|
|
4363
|
+
const map = visBuildMap(root);
|
|
4364
|
+
const jsonPath = path.join(outDir, "MAP.json");
|
|
4365
|
+
const htmlPath = path.join(outDir, "MAP.html");
|
|
4366
|
+
const reportPath = path.join(outDir, "GRAPH_REPORT.md");
|
|
4367
|
+
// Idempotent write: if the new map differs from the committed file ONLY in the volatile
|
|
4368
|
+
// generatedAt/buildMs fields, leave every artifact untouched — so the post-commit hook /
|
|
4369
|
+
// stale rebuild never produces spurious git churn. Graph data is deterministic (see verify gate).
|
|
4370
|
+
let unchanged = false;
|
|
4371
|
+
try {
|
|
4372
|
+
const prev = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
|
|
4373
|
+
unchanged = JSON.stringify(Object.assign({}, prev, { generatedAt: 0, buildMs: 0 }))
|
|
4374
|
+
=== JSON.stringify(Object.assign({}, map, { generatedAt: 0, buildMs: 0 }));
|
|
4375
|
+
} catch { /* no/invalid prior file → write fresh */ }
|
|
4376
|
+
if (!unchanged) {
|
|
4377
|
+
fs.writeFileSync(jsonPath, JSON.stringify(map, null, 2) + "\n", "utf-8");
|
|
4378
|
+
fs.writeFileSync(reportPath, visRenderReport(map), "utf-8"); // a fresh human report is a parity feature
|
|
4379
|
+
}
|
|
4380
|
+
// MAP.html is a derived view artifact (not the git-committed source of truth), so on any full
|
|
4381
|
+
// (non-quiet) build we always refresh it — otherwise template/visualization changes never reach
|
|
4382
|
+
// MAP.html when the underlying graph data is unchanged. The JSON/report stay gated above so the
|
|
4383
|
+
// committed data never churns. The post-commit hook uses --quiet and skips the HTML entirely.
|
|
4384
|
+
if (!opts.quiet) fs.writeFileSync(htmlPath, visRenderHtml(jsonPath), "utf-8");
|
|
4385
|
+
return { jsonPath, htmlPath, reportPath, map, unchanged };
|
|
4386
|
+
}
|
|
4387
|
+
|
|
4388
|
+
// --- map-graph ---
|
|
4389
|
+
commands["map-graph"] = function (...args) {
|
|
4390
|
+
let dir = null, quiet = false;
|
|
4391
|
+
for (const a of args) {
|
|
4392
|
+
if (a === "--quiet" || a === "-q") quiet = true;
|
|
4393
|
+
else if (!String(a).startsWith("-") && !dir) dir = a;
|
|
4394
|
+
}
|
|
4395
|
+
const cwd = dir ? path.resolve(dir) : process.cwd();
|
|
4396
|
+
const { jsonPath, htmlPath, reportPath, map } = visWriteOutputs(cwd, { quiet });
|
|
4397
|
+
if (quiet) { // fast refresh for hooks: MAP.json + GRAPH_REPORT.md, no HTML render
|
|
4398
|
+
console.log(`map-graph: ${map.stats.files} modules · schemaVersion ${map.schemaVersion} · ${map.buildMs}ms → ${path.relative(cwd, jsonPath)}`);
|
|
4399
|
+
return;
|
|
4400
|
+
}
|
|
4401
|
+
console.log(banner("MAP-GRAPH"));
|
|
4402
|
+
console.log(`\nWrote:\n ${jsonPath}\n ${htmlPath}\n ${reportPath}`);
|
|
4403
|
+
console.log(`\nIndexed ${map.stats.files} modules · ${map.stats.totalLoc.toLocaleString()} LOC · ${map.stats.edges} edges · ${map.clusters.length} clusters in ${map.buildMs}ms`);
|
|
4404
|
+
console.log(`\nRead the report: ${path.relative(cwd, reportPath)} · Serve live: draht-tools map-serve`);
|
|
4405
|
+
};
|
|
4406
|
+
|
|
4407
|
+
// --- map-serve ---
|
|
4408
|
+
commands["map-serve"] = function (...args) {
|
|
4409
|
+
const http = require("node:http");
|
|
4410
|
+
const cwd = process.cwd();
|
|
4411
|
+
let port = 4878;
|
|
4412
|
+
let openBrowser = true;
|
|
4413
|
+
for (let i = 0; i < args.length; i++) {
|
|
4414
|
+
const a = args[i];
|
|
4415
|
+
if (a === "--port" || a === "-p") port = parseInt(args[++i], 10) || port;
|
|
4416
|
+
else if (a === "--no-open") openBrowser = false;
|
|
4417
|
+
else if (/^\d+$/.test(a)) port = parseInt(a, 10);
|
|
4418
|
+
}
|
|
4419
|
+
|
|
4420
|
+
const outDir = path.join(cwd, PLANNING_DIR, "codebase");
|
|
4421
|
+
const jsonPath = path.join(outDir, "MAP.json");
|
|
4422
|
+
const htmlPath = path.join(outDir, "MAP.html");
|
|
4423
|
+
|
|
4424
|
+
// Initial generation
|
|
4425
|
+
let lastBuild = visWriteOutputs(cwd);
|
|
4426
|
+
console.log(banner("MAP-SERVE"));
|
|
4427
|
+
console.log(`\nServing ${path.relative(cwd, outDir)}/ on http://localhost:${port}`);
|
|
4428
|
+
console.log(`Indexed ${lastBuild.map.stats.files} modules in ${lastBuild.map.buildMs}ms`);
|
|
4429
|
+
|
|
4430
|
+
const clients = new Set();
|
|
4431
|
+
let regenTimer = null;
|
|
4432
|
+
const regen = () => {
|
|
4433
|
+
clearTimeout(regenTimer);
|
|
4434
|
+
regenTimer = setTimeout(() => {
|
|
4435
|
+
try {
|
|
4436
|
+
lastBuild = visWriteOutputs(cwd);
|
|
4437
|
+
const ts = new Date().toLocaleTimeString();
|
|
4438
|
+
console.log(`[${ts}] regenerated MAP.json (${lastBuild.map.stats.files} modules, ${lastBuild.map.buildMs}ms)`);
|
|
4439
|
+
for (const c of clients) {
|
|
4440
|
+
try { c.write("data: changed\n\n"); } catch { /* empty */ }
|
|
4441
|
+
}
|
|
4442
|
+
} catch (err) {
|
|
4443
|
+
console.error("regen failed:", err.message);
|
|
4444
|
+
}
|
|
4445
|
+
}, 250);
|
|
4446
|
+
};
|
|
4447
|
+
|
|
4448
|
+
// File watcher (recursive — supported on darwin/win32; fallback walks top-level dirs on linux)
|
|
4449
|
+
const watchTargets = [cwd];
|
|
4450
|
+
const watchers = [];
|
|
4451
|
+
const tryWatch = (target) => {
|
|
4452
|
+
try {
|
|
4453
|
+
const w = fs.watch(target, { recursive: true }, (_evt, fname) => {
|
|
4454
|
+
if (!fname) return;
|
|
4455
|
+
const f = fname.toString();
|
|
4456
|
+
if (VIS_DEFAULT_IGNORES.has(f.split(path.sep)[0])) return;
|
|
4457
|
+
if (f.includes("/node_modules/") || f.includes("/.git/")) return;
|
|
4458
|
+
if (f.includes("/.planning/")) return;
|
|
4459
|
+
regen();
|
|
4460
|
+
});
|
|
4461
|
+
watchers.push(w);
|
|
4462
|
+
return true;
|
|
4463
|
+
} catch { return false; }
|
|
4464
|
+
};
|
|
4465
|
+
if (!tryWatch(cwd)) {
|
|
4466
|
+
// Fallback: watch top-level dirs non-recursively
|
|
4467
|
+
for (const e of fs.readdirSync(cwd, { withFileTypes: true })) {
|
|
4468
|
+
if (!e.isDirectory()) continue;
|
|
4469
|
+
if (VIS_DEFAULT_IGNORES.has(e.name)) continue;
|
|
4470
|
+
tryWatch(path.join(cwd, e.name));
|
|
4471
|
+
}
|
|
4472
|
+
}
|
|
4473
|
+
|
|
4474
|
+
const server = http.createServer((req, res) => {
|
|
4475
|
+
const url = req.url.split("?")[0];
|
|
4476
|
+
if (url === "/" || url === "/index.html" || url === "/MAP.html") {
|
|
4477
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
4478
|
+
res.end(fs.readFileSync(htmlPath));
|
|
4479
|
+
} else if (url === "/MAP.json") {
|
|
4480
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8",
|
|
4481
|
+
"cache-control": "no-store" });
|
|
4482
|
+
res.end(fs.readFileSync(jsonPath));
|
|
4483
|
+
} else if (url === "/events") {
|
|
4484
|
+
res.writeHead(200, {
|
|
4485
|
+
"content-type": "text/event-stream",
|
|
4486
|
+
"cache-control": "no-cache",
|
|
4487
|
+
connection: "keep-alive",
|
|
4488
|
+
});
|
|
4489
|
+
res.write("retry: 2000\n\n");
|
|
4490
|
+
clients.add(res);
|
|
4491
|
+
req.on("close", () => clients.delete(res));
|
|
4492
|
+
} else if (url === "/health") {
|
|
4493
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
4494
|
+
res.end(JSON.stringify({ ok: true, stats: lastBuild.map.stats }));
|
|
4495
|
+
} else {
|
|
4496
|
+
res.writeHead(404); res.end("not found");
|
|
4497
|
+
}
|
|
4498
|
+
});
|
|
4499
|
+
|
|
4500
|
+
server.listen(port, () => {
|
|
4501
|
+
const url = `http://localhost:${port}`;
|
|
4502
|
+
console.log(`\n→ Open ${url}`);
|
|
4503
|
+
console.log(` Live updates via SSE; edits to source files regenerate the map.`);
|
|
4504
|
+
console.log(` Ctrl-C to stop.`);
|
|
4505
|
+
if (openBrowser) {
|
|
4506
|
+
const opener = process.platform === "darwin" ? "open"
|
|
4507
|
+
: process.platform === "win32" ? "start" : "xdg-open";
|
|
4508
|
+
try { execSync(`${opener} ${url}`, { stdio: "ignore" }); } catch { /* empty */ }
|
|
4509
|
+
}
|
|
4510
|
+
});
|
|
4511
|
+
|
|
4512
|
+
const shutdown = () => {
|
|
4513
|
+
for (const w of watchers) try { w.close(); } catch { /* empty */ }
|
|
4514
|
+
try { server.close(); } catch { /* empty */ }
|
|
4515
|
+
process.exit(0);
|
|
4516
|
+
};
|
|
4517
|
+
process.on("SIGINT", shutdown);
|
|
4518
|
+
process.on("SIGTERM", shutdown);
|
|
4519
|
+
};
|
|
4520
|
+
|
|
4521
|
+
// ============================================================================
|
|
4522
|
+
// Knowledge-graph queries — answer from MAP.json instead of grepping (read-only)
|
|
4523
|
+
// ============================================================================
|
|
4524
|
+
|
|
4525
|
+
function graphLoadMap() {
|
|
4526
|
+
const jsonPath = path.join(process.cwd(), PLANNING_DIR, "codebase", "MAP.json");
|
|
4527
|
+
try { return { map: JSON.parse(fs.readFileSync(jsonPath, "utf-8")), jsonPath }; }
|
|
4528
|
+
catch { return { map: null, jsonPath }; }
|
|
4529
|
+
}
|
|
4530
|
+
function graphNoMap() { console.log("no map — run `draht-tools map-graph` first."); }
|
|
4531
|
+
|
|
4532
|
+
// Split args into { files, flags }; value-flags (e.g. depth/limit) consume the next token.
|
|
4533
|
+
function graphParseArgs(args, valueFlags = []) {
|
|
4534
|
+
const files = [], flags = {};
|
|
4535
|
+
for (let i = 0; i < args.length; i++) {
|
|
4536
|
+
const a = String(args[i]);
|
|
4537
|
+
const key = a.replace(/^--?/, "");
|
|
4538
|
+
if (!a.startsWith("-")) files.push(a);
|
|
4539
|
+
else if (valueFlags.includes(key)) flags[key] = args[++i];
|
|
4540
|
+
else flags[key] = true;
|
|
4541
|
+
}
|
|
4542
|
+
return { files, flags };
|
|
4543
|
+
}
|
|
4544
|
+
|
|
4545
|
+
// Resolve a user path to a module id: exact, then unique suffix, then unique basename, then substring.
|
|
4546
|
+
function graphResolveFile(map, q) {
|
|
4547
|
+
if (!q) return null;
|
|
4548
|
+
const norm = String(q).replace(/^\.\//, "");
|
|
4549
|
+
const mods = map.modules;
|
|
4550
|
+
let m = mods.find((x) => x.id === norm);
|
|
4551
|
+
if (m) return { id: m.id, exact: true };
|
|
4552
|
+
const suffix = mods.filter((x) => x.id.endsWith("/" + norm));
|
|
4553
|
+
if (suffix.length === 1) return { id: suffix[0].id, exact: false };
|
|
4554
|
+
const base = norm.split("/").pop();
|
|
4555
|
+
const byBase = mods.filter((x) => x.path.split("/").pop() === base);
|
|
4556
|
+
if (byBase.length === 1) return { id: byBase[0].id, exact: false };
|
|
4557
|
+
const contains = mods.filter((x) => x.id.includes(norm)).sort((a, b) => a.id.length - b.id.length);
|
|
4558
|
+
if (contains.length) return { id: contains[0].id, exact: false };
|
|
4559
|
+
return null;
|
|
4560
|
+
}
|
|
4561
|
+
|
|
4562
|
+
function graphImportAdj(map) {
|
|
4563
|
+
// import + re-export are both real structural dependency edges (barrels re-export their internals).
|
|
4564
|
+
const fwd = new Map(), rev = new Map();
|
|
4565
|
+
for (const e of map.edges) {
|
|
4566
|
+
if (e.kind !== "import" && e.kind !== "re-export") continue;
|
|
4567
|
+
if (!fwd.has(e.from)) fwd.set(e.from, []); if (!fwd.get(e.from).includes(e.to)) fwd.get(e.from).push(e.to);
|
|
4568
|
+
if (!rev.has(e.to)) rev.set(e.to, []); if (!rev.get(e.to).includes(e.from)) rev.get(e.to).push(e.from);
|
|
4569
|
+
}
|
|
4570
|
+
return { fwd, rev };
|
|
4571
|
+
}
|
|
4572
|
+
const graphShort = (p) => String(p).split("/").slice(-2).join("/");
|
|
4573
|
+
|
|
4574
|
+
// graph-context — "where am I": package, layer, cluster, importers/imports, exports, sinks, rationale.
|
|
4575
|
+
commands["graph-context"] = function (...args) {
|
|
4576
|
+
const { map } = graphLoadMap();
|
|
4577
|
+
if (!map) return graphNoMap();
|
|
4578
|
+
const { files, flags } = graphParseArgs(args);
|
|
4579
|
+
if (!files.length) { console.log("usage: graph-context <file...> [--json]"); return; }
|
|
4580
|
+
const { fwd: imports, rev: importers } = graphImportAdj(map);
|
|
4581
|
+
const clusterById = new Map((map.clusters || []).map((c) => [c.id, c]));
|
|
4582
|
+
const modById = new Map(map.modules.map((m) => [m.id, m]));
|
|
4583
|
+
const L = [], J = [];
|
|
4584
|
+
for (const f of files) {
|
|
4585
|
+
const r = graphResolveFile(map, f);
|
|
4586
|
+
if (!r) { L.push(`${f}: not found in map`); continue; }
|
|
4587
|
+
const m = modById.get(r.id);
|
|
4588
|
+
if (!r.exact) L.push(`resolved '${f}' → ${m.id}`);
|
|
4589
|
+
const cl = clusterById.get(m.cluster);
|
|
4590
|
+
const exps = (m.symbols && m.symbols.length ? m.symbols.filter((s) => s.exported) : (m.exports || [])).map((s) => s.name);
|
|
4591
|
+
const ins = importers.get(m.id) || [], outs = imports.get(m.id) || [];
|
|
4592
|
+
const rat = (map.rationaleIndex || []).filter((x) => x.file === m.id).slice(0, 4).map((x) => `${x.tag}:${x.line} ${x.text.slice(0, 40)}`);
|
|
4593
|
+
L.push(`${m.path} · pkg:${m.package || "-"} · layer:${m.layer} · cluster:${cl ? cl.label : "-"}(${cl ? cl.size : 0}) · entry:${m.entryPoint ? m.entryPoint.kind : "no"}`);
|
|
4594
|
+
L.push(` exports(${exps.length}): ${exps.slice(0, 8).join(", ") || "-"}${exps.length > 8 ? " …" : ""}`);
|
|
4595
|
+
L.push(` importers(${ins.length}): ${ins.slice(0, 5).map(graphShort).join(", ") || "-"}${ins.length > 5 ? ` (+${ins.length - 5} more)` : ""}`);
|
|
4596
|
+
L.push(` imports(${outs.length}): ${outs.slice(0, 5).map(graphShort).join(", ") || "-"}${outs.length > 5 ? ` (+${outs.length - 5} more)` : ""}`);
|
|
4597
|
+
if (m.sinks && m.sinks.length) L.push(` sinks: ${m.sinks.join(", ")}`);
|
|
4598
|
+
if (rat.length) L.push(` rationale(${rat.length}): ${rat.join(" · ")}`);
|
|
4599
|
+
J.push({ id: m.id, package: m.package, layer: m.layer, cluster: m.cluster, clusterLabel: cl ? cl.label : null, entryPoint: m.entryPoint, exports: exps, importers: ins, imports: outs, sinks: m.sinks, rationale: (map.rationaleIndex || []).filter((x) => x.file === m.id) });
|
|
4600
|
+
}
|
|
4601
|
+
console.log(flags.json ? JSON.stringify(J, null, 2) : L.join("\n"));
|
|
4602
|
+
};
|
|
4603
|
+
|
|
4604
|
+
// graph-impact — blast radius: reverse-transitive importers, entry points reached, sinks, boundary warns.
|
|
4605
|
+
commands["graph-impact"] = function (...args) {
|
|
4606
|
+
const { map } = graphLoadMap();
|
|
4607
|
+
if (!map) return graphNoMap();
|
|
4608
|
+
const { files, flags } = graphParseArgs(args);
|
|
4609
|
+
if (!files.length) { console.log("usage: graph-impact <file...> [--json]"); return; }
|
|
4610
|
+
const { rev } = graphImportAdj(map);
|
|
4611
|
+
const modById = new Map(map.modules.map((m) => [m.id, m]));
|
|
4612
|
+
const targets = [], notes = [];
|
|
4613
|
+
for (const f of files) { const r = graphResolveFile(map, f); if (r) { if (!r.exact) notes.push(`resolved '${f}' → ${r.id}`); targets.push(r.id); } else notes.push(`${f}: not found`); }
|
|
4614
|
+
if (!targets.length) { console.log(notes.join("\n") || "no targets resolved"); return; }
|
|
4615
|
+
const seen = new Set(targets), queue = [...targets];
|
|
4616
|
+
while (queue.length) { const id = queue.shift(); for (const dep of (rev.get(id) || [])) if (!seen.has(dep)) { seen.add(dep); queue.push(dep); } }
|
|
4617
|
+
for (const t of targets) seen.delete(t);
|
|
4618
|
+
const impacted = [...seen].map((id) => modById.get(id)).filter(Boolean);
|
|
4619
|
+
const eps = (map.entryPoints || []).filter((ep) => seen.has(ep.id));
|
|
4620
|
+
const byPkg = {}; for (const m of impacted) { const p = m.package || "(root)"; (byPkg[p] = byPkg[p] || []).push(m.path); }
|
|
4621
|
+
const clusterLabel = new Map((map.clusters || []).map((c) => [c.id, c.label]));
|
|
4622
|
+
const cls = [...new Set(impacted.map((m) => m.cluster).filter(Boolean))];
|
|
4623
|
+
const sinkKinds = new Set(); for (const t of targets) for (const s of (modById.get(t).sinks || [])) sinkKinds.add(s);
|
|
4624
|
+
const warns = (map.surprisingConnections || []).filter((x) => seen.has(x.from) || seen.has(x.to) || targets.includes(x.to)).slice(0, 5);
|
|
4625
|
+
const epLabel = (e) => e.kind === "cli" ? "cli:" + (e.name || "") : e.kind === "http" ? "http:" + ((e.routes && e.routes[0] && (e.routes[0].method + " " + e.routes[0].path)) || "") : "lib:" + (e.name || e.path.split("/").pop());
|
|
4626
|
+
const L = [];
|
|
4627
|
+
if (notes.length) L.push(...notes);
|
|
4628
|
+
L.push(`impact ${targets.map((t) => t.split("/").pop()).join(", ")} — ${impacted.length} modules · ${Object.keys(byPkg).length} packages · ${eps.length} entry points · sinks: ${[...sinkKinds].join(", ") || "none"}`);
|
|
4629
|
+
if (eps.length) L.push(`entry points reaching it (${eps.length}): ${eps.slice(0, 8).map(epLabel).join(", ")}${eps.length > 8 ? " …" : ""}`);
|
|
4630
|
+
const pkgs = Object.entries(byPkg).sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1));
|
|
4631
|
+
if (pkgs.length) L.push("by package:");
|
|
4632
|
+
for (const [p, arr] of pkgs.slice(0, 8)) L.push(` ${p.replace(/^@[^/]+\//, "")}(${arr.length}): ${arr.slice(0, 5).map((x) => x.split("/").pop()).join(" ")}${arr.length > 5 ? ` (+${arr.length - 5})` : ""}`);
|
|
4633
|
+
if (pkgs.length > 8) L.push(` … +${pkgs.length - 8} more packages`);
|
|
4634
|
+
if (cls.length) L.push(`clusters affected: ${cls.map((c) => clusterLabel.get(c) || c).slice(0, 8).join(", ")}`);
|
|
4635
|
+
for (const w of warns) L.push(`⚠ ${w.reason}: ${graphShort(w.from)} → ${graphShort(w.to)}`);
|
|
4636
|
+
console.log(flags.json ? JSON.stringify({ targets, impacted: impacted.map((m) => m.id), entryPoints: eps.map((e) => e.id), byPackage: byPkg, clusters: cls, sinks: [...sinkKinds], warnings: warns }, null, 2) : L.join("\n"));
|
|
4637
|
+
};
|
|
4638
|
+
|
|
4639
|
+
// graph-callers / graph-callees — direct + N-hop neighbours via call + import edges, with symbols.
|
|
4640
|
+
function graphCallDir(args, direction) {
|
|
4641
|
+
const { map } = graphLoadMap();
|
|
4642
|
+
if (!map) return graphNoMap();
|
|
4643
|
+
const { files, flags } = graphParseArgs(args, ["depth"]);
|
|
4644
|
+
if (!files.length) { console.log(`usage: graph-${direction} <file> [--depth N] [--json]`); return; }
|
|
4645
|
+
const depth = Math.max(1, parseInt(flags.depth, 10) || 1);
|
|
4646
|
+
const r = graphResolveFile(map, files[0]);
|
|
4647
|
+
if (!r) { console.log(`${files[0]}: not found in map`); return; }
|
|
4648
|
+
const fwd = new Map(), rev = new Map();
|
|
4649
|
+
const push = (mp, k, v) => { if (!mp.has(k)) mp.set(k, []); if (!mp.get(k).some((x) => x.to === v.to && x.symbol === v.symbol)) mp.get(k).push(v); };
|
|
4650
|
+
for (const ce of map.callEdges) { push(fwd, ce.from, { to: ce.to, symbol: ce.symbol }); push(rev, ce.to, { to: ce.from, symbol: ce.symbol }); }
|
|
4651
|
+
for (const e of map.edges) { if (e.kind !== "import") continue; push(fwd, e.from, { to: e.to, symbol: null }); push(rev, e.to, { to: e.from, symbol: null }); }
|
|
4652
|
+
const adj = direction === "callers" ? rev : fwd;
|
|
4653
|
+
const level = new Map([[r.id, 0]]); const q = [r.id]; const hops = [];
|
|
4654
|
+
while (q.length) { const id = level.get(q[0]) < depth ? q.shift() : (q.shift(), null); if (id == null) continue; for (const nb of (adj.get(id) || [])) { if (!level.has(nb.to)) { level.set(nb.to, level.get(id) + 1); q.push(nb.to); } if (level.get(nb.to) === level.get(id) + 1) hops.push({ from: id, to: nb.to, symbol: nb.symbol, hop: level.get(id) + 1 }); } }
|
|
4655
|
+
const byHop = {}; for (const h of hops) (byHop[h.hop] = byHop[h.hop] || []).push(h);
|
|
4656
|
+
if (flags.json) { console.log(JSON.stringify({ target: r.id, direction, hops }, null, 2)); return; }
|
|
4657
|
+
const total = level.size - 1;
|
|
4658
|
+
console.log(`${direction} of ${r.id} — ${total} within ${depth} hop${depth > 1 ? "s" : ""}`);
|
|
4659
|
+
for (let d = 1; d <= depth; d++) {
|
|
4660
|
+
const arr = byHop[d] || []; if (!arr.length) continue;
|
|
4661
|
+
console.log(` hop ${d}:`);
|
|
4662
|
+
const seen = new Set();
|
|
4663
|
+
for (const h of arr) { const node = direction === "callers" ? h.to : h.to; if (seen.has(node)) continue; seen.add(node); const syms = arr.filter((x) => x.to === node && x.symbol).map((x) => x.symbol); console.log(` ${node}${syms.length ? " [" + [...new Set(syms)].slice(0, 4).join(", ") + "]" : ""}`); }
|
|
4664
|
+
}
|
|
4665
|
+
};
|
|
4666
|
+
commands["graph-callers"] = function (...args) { return graphCallDir(args, "callers"); };
|
|
4667
|
+
commands["graph-callees"] = function (...args) { return graphCallDir(args, "callees"); };
|
|
4668
|
+
|
|
4669
|
+
// graph-path — shortest import path between two files (forward, else reverse "reached-by").
|
|
4670
|
+
commands["graph-path"] = function (...args) {
|
|
4671
|
+
const { map } = graphLoadMap();
|
|
4672
|
+
if (!map) return graphNoMap();
|
|
4673
|
+
const { files } = graphParseArgs(args);
|
|
4674
|
+
const a = graphResolveFile(map, files[0]), b = graphResolveFile(map, files[1]);
|
|
4675
|
+
if (!a || !b) { console.log("usage: graph-path <from> <to> (both files must resolve)"); return; }
|
|
4676
|
+
const { fwd } = graphImportAdj(map);
|
|
4677
|
+
const sym = new Map(); for (const ce of map.callEdges) if (!sym.has(ce.from + "|" + ce.to)) sym.set(ce.from + "|" + ce.to, ce.symbol);
|
|
4678
|
+
const bfs = (src, dst) => { const prev = new Map([[src, null]]); const q = [src]; while (q.length) { const id = q.shift(); if (id === dst) break; for (const n of (fwd.get(id) || [])) if (!prev.has(n)) { prev.set(n, id); q.push(n); } } if (!prev.has(dst)) return null; const c = []; let x = dst; while (x != null) { c.unshift(x); x = prev.get(x); } return c; };
|
|
4679
|
+
let chain = bfs(a.id, b.id), reversed = false;
|
|
4680
|
+
if (!chain) { chain = bfs(b.id, a.id); reversed = true; }
|
|
4681
|
+
if (!chain) { console.log(`no import path between ${a.id} and ${b.id}`); return; }
|
|
4682
|
+
console.log(reversed ? `(no forward path) reverse: ${b.id} is reached-by ${a.id} in ${chain.length - 1} hops` : `path ${a.id} → ${b.id} (${chain.length - 1} hops)`);
|
|
4683
|
+
const render = reversed ? chain.slice().reverse() : chain;
|
|
4684
|
+
const line = render.map((c, i) => { const s = i < render.length - 1 ? sym.get(c + "|" + render[i + 1]) : null; return graphShort(c) + (i < render.length - 1 ? (s ? ` —${s}→ ` : " → ") : ""); }).join("");
|
|
4685
|
+
console.log(" " + line);
|
|
4686
|
+
};
|
|
4687
|
+
|
|
4688
|
+
// graph-query — ranked keyword + doc search over symbol nodes (no embeddings; deterministic).
|
|
4689
|
+
commands["graph-query"] = function (...args) {
|
|
4690
|
+
const { map } = graphLoadMap();
|
|
4691
|
+
if (!map) return graphNoMap();
|
|
4692
|
+
const { files, flags } = graphParseArgs(args);
|
|
4693
|
+
const terms = files.map((t) => t.toLowerCase()).filter((t) => t.length >= 3);
|
|
4694
|
+
if (!terms.length) { console.log("usage: graph-query <term...> [--json] (terms ≥3 chars)"); return; }
|
|
4695
|
+
const stem = (s) => s.replace(/(ing|tion|ed|s)$/, "");
|
|
4696
|
+
const clusterLabel = new Map((map.clusters || []).map((c) => [c.id, (c.label || "").toLowerCase()]));
|
|
4697
|
+
const deg = new Map(); for (const e of map.edges) { if (e.kind !== "import") continue; deg.set(e.from, (deg.get(e.from) || 0) + 1); deg.set(e.to, (deg.get(e.to) || 0) + 1); }
|
|
4698
|
+
const cands = [];
|
|
4699
|
+
for (const m of map.modules) {
|
|
4700
|
+
const expDoc = new Map((m.exports || []).map((e) => [e.name, e.doc || ""]));
|
|
4701
|
+
const baseLow = m.path.split("/").pop().toLowerCase();
|
|
4702
|
+
const clab = clusterLabel.get(m.cluster) || "";
|
|
4703
|
+
for (const s of (m.symbols || [])) {
|
|
4704
|
+
const nameLow = s.name.toLowerCase(), doc = expDoc.get(s.name) || "", docLow = doc.toLowerCase();
|
|
4705
|
+
let total = 0, ok = true;
|
|
4706
|
+
for (const t of terms) {
|
|
4707
|
+
let sc = 0;
|
|
4708
|
+
if (nameLow === t) sc = 400; else if (nameLow.startsWith(t)) sc = 200; else if (nameLow.includes(t)) sc = 100;
|
|
4709
|
+
if (sc < 60 && baseLow.includes(t)) sc = 60;
|
|
4710
|
+
if (sc < 40 && (docLow.includes(t) || docLow.includes(stem(t)))) sc = 40;
|
|
4711
|
+
if (sc < 30 && clab.includes(t)) sc = 30;
|
|
4712
|
+
if (sc === 0) { ok = false; break; }
|
|
4713
|
+
total += sc;
|
|
4714
|
+
}
|
|
4715
|
+
if (!ok) continue;
|
|
4716
|
+
let mult = 1; if (s.exported) mult *= 1.5; if (m.entryPoint) mult *= 1.3;
|
|
4717
|
+
cands.push({ score: +(total * mult).toFixed(1), deg: deg.get(m.id) || 0, path: m.path, line: s.line, kind: s.kind, name: s.name, exported: !!s.exported, doc });
|
|
4718
|
+
}
|
|
4719
|
+
}
|
|
4720
|
+
cands.sort((a, b) => b.score - a.score || b.deg - a.deg || a.path.length - b.path.length || (a.path < b.path ? -1 : 1));
|
|
4721
|
+
const top = cands.slice(0, 15);
|
|
4722
|
+
if (flags.json) { console.log(JSON.stringify(top, null, 2)); return; }
|
|
4723
|
+
console.log(`query "${terms.join(" ")}" — ${top.length}/${cands.length} hits`);
|
|
4724
|
+
for (const c of top) console.log(`${c.path}:${c.line} ${c.kind} ${c.name}${c.doc ? " — " + c.doc.slice(0, 60) : ""}${c.exported ? " [exported]" : ""}`);
|
|
4725
|
+
if (cands.length > 15) console.log(`(${cands.length - 15} more: --json for all)`);
|
|
4726
|
+
};
|
|
4727
|
+
|
|
4728
|
+
// graph-hotspots — god-nodes / most-depended-on / orchestrators / largest.
|
|
4729
|
+
commands["graph-hotspots"] = function (...args) {
|
|
4730
|
+
const { map } = graphLoadMap();
|
|
4731
|
+
if (!map) return graphNoMap();
|
|
4732
|
+
const { flags } = graphParseArgs(args, ["limit"]);
|
|
4733
|
+
const lim = Math.max(1, parseInt(flags.limit, 10) || 10);
|
|
4734
|
+
const h = map.hotspots || {};
|
|
4735
|
+
if (flags.json) { console.log(JSON.stringify(h, null, 2)); return; }
|
|
4736
|
+
const section = (title, arr) => { console.log(`\n${title}`); for (const g of (arr || []).slice(0, lim)) console.log(` ${g.path} [in ${g.inDegree} · out ${g.outDegree} · ${g.loc} LOC] ${g.reason}`); };
|
|
4737
|
+
section("God nodes (most connected):", h.godNodes);
|
|
4738
|
+
section("Most depended-on:", h.mostDependedOn);
|
|
4739
|
+
section("Orchestrators (most deps):", h.orchestrators);
|
|
4740
|
+
section("Largest:", h.largest);
|
|
4741
|
+
};
|
|
4742
|
+
|
|
4743
|
+
// graph-clusters — structural neighborhoods; --surprising appends bridge/boundary edges.
|
|
4744
|
+
commands["graph-clusters"] = function (...args) {
|
|
4745
|
+
const { map } = graphLoadMap();
|
|
4746
|
+
if (!map) return graphNoMap();
|
|
4747
|
+
const { flags } = graphParseArgs(args);
|
|
4748
|
+
if (flags.json) { console.log(JSON.stringify({ clusters: map.clusters, surprisingConnections: flags.surprising ? map.surprisingConnections : undefined }, null, 2)); return; }
|
|
4749
|
+
console.log(`${(map.clusters || []).length} clusters (structural import-topology — not semantic bounded contexts):`);
|
|
4750
|
+
for (const c of (map.clusters || [])) console.log(` ${c.label} · ${c.size} modules · ${c.dominantLayer} · ${(c.packages || []).slice(0, 3).join(", ")}`);
|
|
4751
|
+
if (flags.surprising) {
|
|
4752
|
+
console.log(`\nSurprising connections (${(map.surprisingConnections || []).length}):`);
|
|
4753
|
+
for (const x of (map.surprisingConnections || [])) console.log(` ${graphShort(x.from)} → ${graphShort(x.to)} — ${x.reason} (${x.score})${x.sampleSymbols && x.sampleSymbols.length ? " · " + x.sampleSymbols.slice(0, 3).join(", ") : ""}`);
|
|
4754
|
+
}
|
|
4755
|
+
};
|
|
4756
|
+
|
|
4757
|
+
// graph-hook — install/uninstall a git post-commit hook that refreshes MAP.json (graphify-style).
|
|
4758
|
+
commands["graph-hook"] = function (...args) {
|
|
4759
|
+
const sub = args[0] || "status";
|
|
4760
|
+
const gitDir = path.join(process.cwd(), ".git");
|
|
4761
|
+
if (!fs.existsSync(gitDir)) { console.log("not a git repository (no .git)"); return; }
|
|
4762
|
+
const hookPath = path.join(gitDir, "hooks", "post-commit");
|
|
4763
|
+
const BEGIN = "# >>> draht map-graph >>>", END = "# <<< draht map-graph <<<";
|
|
4764
|
+
const selfPath = __filename;
|
|
4765
|
+
const block = `${BEGIN}\nnode "${selfPath}" map-graph --quiet 2>/dev/null || true\n${END}`;
|
|
4766
|
+
const read = () => { try { return fs.readFileSync(hookPath, "utf-8"); } catch { return ""; } };
|
|
4767
|
+
const stripBlock = (s) => s.replace(new RegExp("\\n*" + BEGIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "[\\s\\S]*?" + END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\n*", "g"), "\n").replace(/^\n+/, "");
|
|
4768
|
+
if (sub === "install") {
|
|
4769
|
+
let cur = read();
|
|
4770
|
+
if (cur.includes(BEGIN)) cur = stripBlock(cur);
|
|
4771
|
+
if (!cur.trim()) cur = "#!/bin/sh\n";
|
|
4772
|
+
const next = cur.replace(/\n*$/, "\n") + "\n" + block + "\n";
|
|
4773
|
+
ensureDir(path.dirname(hookPath));
|
|
4774
|
+
fs.writeFileSync(hookPath, next, "utf-8");
|
|
4775
|
+
try { fs.chmodSync(hookPath, 0o755); } catch { /* empty */ }
|
|
4776
|
+
console.log(`installed post-commit hook → ${path.relative(process.cwd(), hookPath)}\n refreshes .planning/codebase/MAP.json after each commit (lands in the next commit).`);
|
|
4777
|
+
} else if (sub === "uninstall") {
|
|
4778
|
+
const cur = read();
|
|
4779
|
+
if (!cur.includes(BEGIN)) { console.log("draht hook not installed."); return; }
|
|
4780
|
+
const next = stripBlock(cur);
|
|
4781
|
+
if (next.trim() && next.trim() !== "#!/bin/sh") fs.writeFileSync(hookPath, next, "utf-8"); else { try { fs.unlinkSync(hookPath); } catch { /* empty */ } }
|
|
4782
|
+
console.log("removed draht post-commit hook block.");
|
|
4783
|
+
} else {
|
|
4784
|
+
console.log(read().includes(BEGIN) ? "draht post-commit hook: INSTALLED" : "draht post-commit hook: not installed (run `draht-tools graph-hook install`)");
|
|
4785
|
+
}
|
|
4786
|
+
};
|
|
4787
|
+
|
|
1050
4788
|
// ============================================================================
|
|
1051
4789
|
// Help & Dispatch
|
|
1052
4790
|
// ============================================================================
|
|
@@ -1059,7 +4797,24 @@ Usage: draht-tools <command> [args]
|
|
|
1059
4797
|
|
|
1060
4798
|
Project Setup:
|
|
1061
4799
|
init Check preconditions, create .planning/
|
|
1062
|
-
map-codebase [dir] Analyze existing codebase
|
|
4800
|
+
map-codebase [dir] Analyze existing codebase (docs)
|
|
4801
|
+
map-graph [dir] [--quiet] Generate living codebase map (MAP.json + MAP.html + GRAPH_REPORT.md)
|
|
4802
|
+
--quiet: refresh MAP.json + report only (no HTML); for hooks
|
|
4803
|
+
Override functional groups via .planning/codebase/GROUPS.json
|
|
4804
|
+
Override flows via .planning/codebase/FLOWS.json
|
|
4805
|
+
map-serve [port] Serve MAP.html with live reload on file changes
|
|
4806
|
+
|
|
4807
|
+
Knowledge Graph (query MAP.json instead of grepping — run map-graph first):
|
|
4808
|
+
graph-context <file...> Where a file sits: pkg, layer, cluster, importers/imports, sinks, rationale
|
|
4809
|
+
graph-impact <file...> Blast radius: reverse-dependents, entry points reached, sinks, boundary warns
|
|
4810
|
+
graph-callers <file> [--depth N] Modules that call/import the file (N hops)
|
|
4811
|
+
graph-callees <file> [--depth N] Modules the file calls/imports (N hops)
|
|
4812
|
+
graph-path <from> <to> Shortest import path between two files
|
|
4813
|
+
graph-query <term...> Ranked symbol + doc search (replaces grep for "find the X")
|
|
4814
|
+
graph-hotspots [--limit N] God-nodes / most-depended-on / orchestrators / largest
|
|
4815
|
+
graph-clusters [--surprising] Structural neighborhoods (+ surprising/bridge connections)
|
|
4816
|
+
graph-hook install|uninstall|status Git post-commit hook that refreshes MAP.json
|
|
4817
|
+
(all accept --json for machine output)
|
|
1063
4818
|
create-project [name] Create PROJECT.md
|
|
1064
4819
|
create-requirements Create REQUIREMENTS.md
|
|
1065
4820
|
create-domain-model Generate DOMAIN-MODEL.md from PROJECT.md
|