packmind 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +136 -0
  3. package/dist/adapters/claude-code.js +67 -0
  4. package/dist/bin/packmind.js +13 -0
  5. package/dist/cli/backup-cmd.js +41 -0
  6. package/dist/cli/ctx.js +14 -0
  7. package/dist/cli/dashboard-cmd.js +34 -0
  8. package/dist/cli/doctor.js +45 -0
  9. package/dist/cli/index-cmd.js +15 -0
  10. package/dist/cli/index.js +68 -0
  11. package/dist/cli/init.js +83 -0
  12. package/dist/cli/insights-cmd.js +28 -0
  13. package/dist/cli/locate.js +15 -0
  14. package/dist/cli/maintain-cmd.js +39 -0
  15. package/dist/cli/mcp-cmd.js +5 -0
  16. package/dist/cli/policy-cmd.js +40 -0
  17. package/dist/cli/recall-cmd.js +18 -0
  18. package/dist/cli/registry.js +32 -0
  19. package/dist/cli/scan.js +18 -0
  20. package/dist/cli/solutions-cmd.js +24 -0
  21. package/dist/cli/status.js +28 -0
  22. package/dist/cli/update.js +73 -0
  23. package/dist/cost/estimator.js +21 -0
  24. package/dist/cost/exact.js +35 -0
  25. package/dist/cost/insights.js +80 -0
  26. package/dist/cost/ledger.js +47 -0
  27. package/dist/cost/pricing.js +27 -0
  28. package/dist/dashboard/server.js +128 -0
  29. package/dist/guard/path-guard.js +26 -0
  30. package/dist/guard/policy.js +0 -0
  31. package/dist/guard/secrets.js +29 -0
  32. package/dist/hooks/post-read.js +80 -0
  33. package/dist/hooks/post-write.js +107 -0
  34. package/dist/hooks/pre-read.js +94 -0
  35. package/dist/hooks/pre-write.js +101 -0
  36. package/dist/hooks/prompt-submit.js +37 -0
  37. package/dist/hooks/runtime.js +471 -0
  38. package/dist/hooks/session-start.js +72 -0
  39. package/dist/hooks/stop.js +69 -0
  40. package/dist/mcp/server.js +112 -0
  41. package/dist/mcp/tools.js +130 -0
  42. package/dist/recall/chunker.js +24 -0
  43. package/dist/recall/embedder.js +51 -0
  44. package/dist/recall/indexer.js +94 -0
  45. package/dist/recall/queue.js +24 -0
  46. package/dist/recall/store.js +48 -0
  47. package/dist/state/describe.js +63 -0
  48. package/dist/state/files.js +45 -0
  49. package/dist/state/formats.js +80 -0
  50. package/dist/state/maintain.js +25 -0
  51. package/dist/state/mapper.js +56 -0
  52. package/dist/state/project.js +33 -0
  53. package/dist/state/schema.js +47 -0
  54. package/dist/state/snapshot.js +69 -0
  55. package/dist/state/walk.js +75 -0
  56. package/dist/util/fs-atomic.js +106 -0
  57. package/dist/util/logger.js +17 -0
  58. package/dist/util/paths.js +20 -0
  59. package/dist/util/platform.js +10 -0
  60. package/package.json +72 -0
  61. package/src/templates/PACKMIND.md +42 -0
  62. package/src/templates/claude-md-snippet.md +9 -0
  63. package/src/templates/config.json +48 -0
  64. package/src/templates/dashboard.html +359 -0
  65. package/src/templates/gitattributes +2 -0
  66. package/src/templates/handoff.md +3 -0
  67. package/src/templates/hooks-package.json +4 -0
  68. package/src/templates/identity.md +5 -0
  69. package/src/templates/journal.md +3 -0
  70. package/src/templates/knowledge.md +12 -0
  71. package/src/templates/logo-dark.svg +23 -0
  72. package/src/templates/logo.svg +23 -0
  73. package/src/templates/map.md +3 -0
  74. package/src/templates/policy.json +11 -0
  75. package/src/templates/solutions.json +1 -0
  76. package/src/templates/usage.json +17 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,136 @@
1
+ <p align="center">
2
+ <img src="packmind-mark.svg" alt="PackMind" width="120" />
3
+ </p>
4
+
5
+ <h1 align="center">PackMind</h1>
6
+
7
+ <p align="center">
8
+ <strong>A second brain for Claude Code.</strong><br />
9
+ Project memory, real token &amp; cost accounting, local semantic recall, and active guardrails — through lifecycle hooks and an MCP server. Zero workflow changes.
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://github.com/mchl-schrdng/packmind/actions/workflows/ci.yml"><img src="https://github.com/mchl-schrdng/packmind/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
14
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache--2.0-blue.svg" alt="License: Apache-2.0" /></a>
15
+ <img src="https://img.shields.io/badge/Node.js-20%2B-green.svg" alt="Node.js 20+" />
16
+ </p>
17
+
18
+ ---
19
+
20
+ ## What PackMind does
21
+
22
+ Claude Code works without persistent project context: it can't tell a 50-token
23
+ config from a 2,000-token module before opening it, re-reads the same files, and
24
+ forgets what it learned last session. PackMind fixes that with a small state
25
+ directory (`.packmind/`) maintained by lifecycle hooks, plus an MCP server that
26
+ exposes the project's memory as tools Claude can query directly.
27
+
28
+ - **Project map** — every file gets a one-line description, a token estimate, and
29
+ an estimated read cost, so Claude reads `map.md` instead of opening files blind.
30
+ - **Real token &amp; cost accounting** — fast local estimates always, reconciled to
31
+ exact counts via Anthropic's count-tokens API when a key is present, priced per
32
+ model into a running **dollar total**.
33
+ - **Local semantic recall** — an on-device embedding index (nothing leaves your
34
+ machine) lets Claude `recall(...)` past decisions, solutions, and code by meaning.
35
+ - **Active guardrails** — a policy engine warns (or hard-blocks, opt-in) before a
36
+ write touches a secret file or violates a project rule.
37
+
38
+ ## Quick start
39
+
40
+ ```bash
41
+ npm install -g packmind # or: pnpm add -g packmind
42
+ cd your-project
43
+ packmind init # sets up .packmind/, hooks, and the MCP server
44
+ packmind index # builds the local semantic index (first run fetches the embed model)
45
+ ```
46
+
47
+ Then use `claude` as normal.
48
+
49
+ ## The MCP tools
50
+
51
+ Registered automatically in `.mcp.json`. Claude can call:
52
+
53
+ | Tool | Purpose |
54
+ |------|---------|
55
+ | `recall(query)` | Semantic search across knowledge, journal, solutions, and source |
56
+ | `remember(note, kind)` | Save a preference, decision, never-do rule, or note |
57
+ | `record_solution(error, cause, fix, tags)` | Log a fix so it's never rediscovered |
58
+ | `project_map(filter?)` | List files with descriptions and token estimates |
59
+ | `usage_report()` | Token usage and dollar cost for the project |
60
+ | `insights()` | Savings, map coverage, heaviest files, and upkeep notes |
61
+ | `handoff(action, content?)` | Read or update the session resume note |
62
+
63
+ ## CLI
64
+
65
+ ```
66
+ packmind init Set up .packmind/, hooks, and the MCP server
67
+ packmind scan [--check] Rebuild the project map (exit 1 on --check if stale)
68
+ packmind index Build the local semantic recall index
69
+ packmind recall <query> Search project memory from the terminal
70
+ packmind solutions <term> Search recorded fixes
71
+ packmind status Token usage, dollar cost, and health
72
+ packmind insights Where tokens go and what PackMind saved
73
+ packmind dashboard Open the local web dashboard (loopback, token-protected)
74
+ packmind maintain One-shot upkeep: scan + reindex + archive + prune (cron-friendly)
75
+ packmind backup [--list] Snapshot .packmind/ to ~/.packmind/backups
76
+ packmind restore [stamp] Restore .packmind/ from a backup (omit to list)
77
+ packmind solutions <term> Search recorded fixes
78
+ packmind policy check Lint guardrail rules
79
+ packmind doctor Diagnose projects, hooks, and MCP registration
80
+ packmind update Update registered projects (snapshots first, preserves config.json)
81
+ packmind mcp Run the MCP server (used by Claude Code)
82
+ ```
83
+
84
+ ## What lives in `.packmind/`
85
+
86
+ | File | Role | Commit? |
87
+ |------|------|---------|
88
+ | `map.md` | File map with tokens &amp; cost | yes |
89
+ | `knowledge.md` | Preferences, decisions, never-do list | yes |
90
+ | `config.json` | Configuration | yes |
91
+ | `policy.json` | Guardrail rules | yes |
92
+ | `PACKMIND.md` | Protocol Claude follows | yes |
93
+ | `journal.md` | Action log + session summaries | optional |
94
+ | `solutions.json` | Recorded fixes | optional |
95
+ | `usage.json` | Token &amp; cost ledger | no (per-dev) |
96
+ | `handoff.md` | Session resume note | no (per-dev) |
97
+ | `recall/` | Local vector index | no (per-dev) |
98
+
99
+ ## Scheduled maintenance (no daemon)
100
+
101
+ Instead of a background daemon, PackMind ships a single `maintain` command you
102
+ schedule yourself — it refreshes the map, rebuilds the recall index, archives an
103
+ overgrown journal, and prunes old backups. Wire it into your own scheduler:
104
+
105
+ ```cron
106
+ # crontab -e — keep a project's brain fresh every night at 2am
107
+ 0 2 * * * cd /path/to/project && packmind maintain --quiet
108
+ ```
109
+
110
+ No persistent process, no open ports, no state to leak.
111
+
112
+ ## Configuration
113
+
114
+ `.packmind/config.json` is deep-merged over defaults, so it survives `packmind
115
+ update` and stays forward-compatible. Notable keys:
116
+
117
+ - `model` — drives cost pricing (`claude-opus-4-8` by default).
118
+ - `cost.exact` — `auto` (exact when `ANTHROPIC_API_KEY` is set) | `never` | `always`.
119
+ - `recall.enabled` / `recall.embedModel` — local embeddings; fully offline.
120
+ - `guard.blockSecrets` — set `true` to hard-block writes to secret files.
121
+ - `map.respectGitignore`, `map.extraSecretGlobs` — control what gets mapped.
122
+
123
+ ## Privacy
124
+
125
+ Embeddings run locally via an on-device model cached under `~/.packmind/models`;
126
+ your code is never sent anywhere for recall. The only optional network call is
127
+ Anthropic's count-tokens endpoint, used solely when you enable exact counting.
128
+
129
+ ## Requirements
130
+
131
+ - Node.js 20+
132
+ - Claude Code
133
+
134
+ ## License
135
+
136
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,67 @@
1
+ import { readJsonOr, writeJson } from "../util/fs-atomic.js";
2
+ import { onWindows } from "../util/platform.js";
3
+ /**
4
+ * Integration with Claude Code. PackMind installs two things into a project:
5
+ * 1. Lifecycle hooks in .claude/settings.json, tagged `_managedBy: "packmind"`
6
+ * so Claude Code preserves them and PackMind can dedupe/remove cleanly.
7
+ * Commands are guarded so a missing hook file no-ops instead of erroring.
8
+ * 2. An MCP server entry in .mcp.json exposing the brain as queryable tools.
9
+ */
10
+ export const MANAGED_BY = "packmind";
11
+ const HOOKS = "$CLAUDE_PROJECT_DIR/.packmind/hooks";
12
+ function cmd(script, timeout) {
13
+ const p = `${HOOKS}/${script}`;
14
+ return {
15
+ type: "command",
16
+ command: onWindows ? `node "${p}"` : `[ -f "${p}" ] && node "${p}" || true`,
17
+ timeout,
18
+ };
19
+ }
20
+ function group(matcher, script, timeout) {
21
+ return { matcher, hooks: [cmd(script, timeout)], _managedBy: MANAGED_BY };
22
+ }
23
+ export function buildHookMap() {
24
+ return {
25
+ SessionStart: [group("", "session-start.js", 5)],
26
+ UserPromptSubmit: [group("", "prompt-submit.js", 5)],
27
+ PreToolUse: [
28
+ group("Read", "pre-read.js", 5),
29
+ group("Write|Edit|MultiEdit", "pre-write.js", 5),
30
+ ],
31
+ PostToolUse: [
32
+ group("Read", "post-read.js", 5),
33
+ group("Write|Edit|MultiEdit", "post-write.js", 10),
34
+ ],
35
+ Stop: [group("", "stop.js", 10)],
36
+ };
37
+ }
38
+ function stripManaged(existing) {
39
+ const out = {};
40
+ for (const [event, groups] of Object.entries(existing)) {
41
+ const kept = (groups ?? []).filter((g) => g?._managedBy !== MANAGED_BY);
42
+ if (kept.length)
43
+ out[event] = kept;
44
+ }
45
+ return out;
46
+ }
47
+ export function registerHooks(settingsPath) {
48
+ const settings = readJsonOr(settingsPath, {});
49
+ const merged = stripManaged(settings.hooks ?? {});
50
+ for (const [event, groups] of Object.entries(buildHookMap())) {
51
+ merged[event] = [...(merged[event] ?? []), ...groups];
52
+ }
53
+ settings.hooks = merged;
54
+ writeJson(settingsPath, settings);
55
+ }
56
+ export function unregisterHooks(settingsPath) {
57
+ const settings = readJsonOr(settingsPath, {});
58
+ settings.hooks = stripManaged(settings.hooks ?? {});
59
+ writeJson(settingsPath, settings);
60
+ }
61
+ /** Register the PackMind MCP server in a project's .mcp.json (preserving others). */
62
+ export function registerMcp(mcpJsonPath) {
63
+ const config = readJsonOr(mcpJsonPath, {});
64
+ config.mcpServers = config.mcpServers ?? {};
65
+ config.mcpServers.packmind = { command: "packmind", args: ["mcp"] };
66
+ writeJson(mcpJsonPath, config);
67
+ }
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { createProgram } from "../cli/index.js";
3
+ const major = Number(process.versions.node.split(".")[0]);
4
+ if (major < 20) {
5
+ console.error(`PackMind requires Node.js 20+. You are running ${process.version}.`);
6
+ process.exit(1);
7
+ }
8
+ createProgram()
9
+ .parseAsync(process.argv)
10
+ .catch((err) => {
11
+ console.error(err instanceof Error ? err.message : String(err));
12
+ process.exit(1);
13
+ });
@@ -0,0 +1,41 @@
1
+ import chalk from "chalk";
2
+ import { requireProject } from "./ctx.js";
3
+ import { createSnapshot, listSnapshots, restoreSnapshot } from "../state/snapshot.js";
4
+ export function runBackup(opts = {}) {
5
+ const { projectRoot } = requireProject();
6
+ if (opts.list) {
7
+ const snaps = listSnapshots(projectRoot);
8
+ if (!snaps.length) {
9
+ console.log(chalk.dim("No backups yet."));
10
+ return;
11
+ }
12
+ console.log(chalk.bold.cyan("\nBackups:\n"));
13
+ for (const s of snaps)
14
+ console.log(" " + s);
15
+ console.log("");
16
+ return;
17
+ }
18
+ console.log(chalk.green(`✓ Backup created: ${createSnapshot(projectRoot)}`));
19
+ }
20
+ export function runRestore(label) {
21
+ const { projectRoot } = requireProject();
22
+ const snaps = listSnapshots(projectRoot);
23
+ if (!label) {
24
+ if (!snaps.length) {
25
+ console.log(chalk.dim("No backups to restore."));
26
+ return;
27
+ }
28
+ console.log(chalk.bold.cyan("\nAvailable backups:\n"));
29
+ for (const s of snaps)
30
+ console.log(" " + s);
31
+ console.log(chalk.dim("\nRun `packmind restore <timestamp>` to restore one.\n"));
32
+ return;
33
+ }
34
+ if (restoreSnapshot(projectRoot, label)) {
35
+ console.log(chalk.green(`✓ Restored .packmind/ from ${label}`));
36
+ }
37
+ else {
38
+ console.error(chalk.red(`✗ No backup "${label}" for this project.`));
39
+ process.exit(1);
40
+ }
41
+ }
@@ -0,0 +1,14 @@
1
+ import * as fs from "node:fs";
2
+ import chalk from "chalk";
3
+ import { findRoot } from "../state/project.js";
4
+ import { brain } from "../state/files.js";
5
+ import { loadConfig } from "../state/schema.js";
6
+ /** Resolve an initialized project or exit with a helpful message. */
7
+ export function requireProject() {
8
+ const projectRoot = findRoot();
9
+ if (!fs.existsSync(brain(projectRoot).config)) {
10
+ console.error(chalk.red("✗ No .packmind/ here. Run `packmind init` first."));
11
+ process.exit(1);
12
+ }
13
+ return { projectRoot, config: loadConfig(brain(projectRoot).config) };
14
+ }
@@ -0,0 +1,34 @@
1
+ import { execFile } from "node:child_process";
2
+ import chalk from "chalk";
3
+ import { requireProject } from "./ctx.js";
4
+ import { startDashboard } from "../dashboard/server.js";
5
+ import { onWindows, onMac } from "../util/platform.js";
6
+ /** Open a URL in the default browser without invoking a shell (no injection). */
7
+ function openBrowser(url) {
8
+ const [cmd, args] = onMac
9
+ ? ["open", [url]]
10
+ : onWindows
11
+ ? ["cmd", ["/c", "start", "", url]]
12
+ : ["xdg-open", [url]];
13
+ execFile(cmd, args, () => {
14
+ /* ignore: user can open the URL manually */
15
+ });
16
+ }
17
+ export async function runDashboard(opts = {}) {
18
+ const { projectRoot } = requireProject();
19
+ const preferred = opts.port ? parseInt(opts.port, 10) : 7878;
20
+ const handle = await startDashboard(projectRoot, preferred);
21
+ console.log("\n" + chalk.bold.cyan("PackMind dashboard") + " running (loopback only)\n" +
22
+ ` ${chalk.bold(handle.url)}\n\n` +
23
+ chalk.dim(" Token-protected · bound to 127.0.0.1 · Ctrl+C to stop\n"));
24
+ if (opts.open !== false)
25
+ openBrowser(handle.url);
26
+ const shutdown = () => {
27
+ handle.close();
28
+ process.exit(0);
29
+ };
30
+ process.on("SIGINT", shutdown);
31
+ process.on("SIGTERM", shutdown);
32
+ // Keep the process alive.
33
+ await new Promise(() => { });
34
+ }
@@ -0,0 +1,45 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import chalk from "chalk";
4
+ import { readJsonOr } from "../util/fs-atomic.js";
5
+ import { loadConfig } from "../state/schema.js";
6
+ import { brain } from "../state/files.js";
7
+ import { MANAGED_BY } from "../adapters/claude-code.js";
8
+ import { pruneRegistry } from "./registry.js";
9
+ const HOOK_SCRIPTS = [
10
+ "runtime.js", "session-start.js", "prompt-submit.js", "pre-read.js",
11
+ "post-read.js", "pre-write.js", "post-write.js", "stop.js",
12
+ ];
13
+ export function runDoctor() {
14
+ console.log(chalk.bold.cyan("\nPackMind doctor\n"));
15
+ const projects = pruneRegistry();
16
+ if (projects.length === 0) {
17
+ console.log(` ${chalk.yellow("!")} No registered projects. Run \`packmind init\`.`);
18
+ return;
19
+ }
20
+ console.log(` ${chalk.green("✓")} ${projects.length} registered project(s).`);
21
+ for (const p of projects) {
22
+ console.log("\n" + chalk.bold(p.name) + chalk.dim(` ${p.root}`));
23
+ const b = brain(p.root);
24
+ const missing = HOOK_SCRIPTS.filter((s) => !fs.existsSync(path.join(b.hooksDir, s)));
25
+ ok(missing.length === 0, missing.length === 0 ? "all hook scripts present" : `missing: ${missing.join(", ")}`);
26
+ const config = loadConfig(b.config);
27
+ const settings = readJsonOr(path.join(p.root, config.claude.settingsPath), {});
28
+ const tagged = Object.values(settings.hooks ?? {}).flat().filter((g) => g?._managedBy === MANAGED_BY);
29
+ ok(tagged.length >= 7, `${tagged.length} tagged hook entries`);
30
+ const mcp = readJsonOr(path.join(p.root, ".mcp.json"), {});
31
+ ok(Boolean(mcp.mcpServers?.packmind), "packmind MCP server registered");
32
+ let validConfig = true;
33
+ try {
34
+ JSON.parse(fs.readFileSync(b.config, "utf8"));
35
+ }
36
+ catch {
37
+ validConfig = false;
38
+ }
39
+ ok(validConfig, "config.json valid");
40
+ }
41
+ console.log("");
42
+ }
43
+ function ok(pass, msg) {
44
+ console.log(` ${pass ? chalk.green("✓") : chalk.yellow("!")} ${msg}`);
45
+ }
@@ -0,0 +1,15 @@
1
+ import chalk from "chalk";
2
+ import { requireProject } from "./ctx.js";
3
+ import { buildIndex } from "../recall/indexer.js";
4
+ import { LocalEmbedder } from "../recall/embedder.js";
5
+ export async function runIndex() {
6
+ const { projectRoot, config } = requireProject();
7
+ if (!config.recall.enabled) {
8
+ console.error(chalk.yellow("Recall is disabled in config (recall.enabled = false)."));
9
+ return;
10
+ }
11
+ console.log(chalk.dim("Building semantic index locally (first run downloads the embedding model)…"));
12
+ const embedder = new LocalEmbedder(config.recall.embedModel);
13
+ const count = await buildIndex(projectRoot, config, embedder);
14
+ console.log(chalk.cyan(`✓ Indexed ${count} chunks into .packmind/recall/`));
15
+ }
@@ -0,0 +1,68 @@
1
+ import { Command } from "commander";
2
+ import { pkgVersion } from "./locate.js";
3
+ import { runInit } from "./init.js";
4
+ import { runScan } from "./scan.js";
5
+ import { runStatus } from "./status.js";
6
+ import { runIndex } from "./index-cmd.js";
7
+ import { runRecall } from "./recall-cmd.js";
8
+ import { runSolutions } from "./solutions-cmd.js";
9
+ import { runPolicyCheck } from "./policy-cmd.js";
10
+ import { runDoctor } from "./doctor.js";
11
+ import { runUpdate } from "./update.js";
12
+ import { runMcp } from "./mcp-cmd.js";
13
+ import { runDashboard } from "./dashboard-cmd.js";
14
+ import { runInsights } from "./insights-cmd.js";
15
+ import { runMaintain } from "./maintain-cmd.js";
16
+ import { runBackup, runRestore } from "./backup-cmd.js";
17
+ export function createProgram() {
18
+ const program = new Command();
19
+ program
20
+ .name("packmind")
21
+ .description("A second brain for Claude Code: project memory, real token & cost accounting, semantic recall, and active guardrails.")
22
+ .version(pkgVersion());
23
+ program.command("init").description("Initialize .packmind/, register hooks and the MCP server").action(runInit);
24
+ program
25
+ .command("scan")
26
+ .description("Rebuild the project map (map.md)")
27
+ .option("--check", "Exit 1 if the map is stale")
28
+ .action((o) => runScan(o));
29
+ program.command("status").description("Token usage, dollar cost, and project health").action(runStatus);
30
+ program.command("insights").description("Where tokens go and what PackMind saved").action(runInsights);
31
+ program
32
+ .command("maintain")
33
+ .description("One-shot upkeep (scan, reindex, archive journal, prune backups) — cron-friendly")
34
+ .option("--quiet", "Suppress output (for unattended/cron runs)")
35
+ .option("--keep-backups <n>", "How many backups to keep (default 10)")
36
+ .action((o) => runMaintain(o));
37
+ program
38
+ .command("backup")
39
+ .description("Snapshot .packmind/ to ~/.packmind/backups")
40
+ .option("--list", "List existing backups")
41
+ .action((o) => runBackup(o));
42
+ program
43
+ .command("restore [timestamp]")
44
+ .description("Restore .packmind/ from a backup (omit timestamp to list)")
45
+ .action((ts) => runRestore(ts));
46
+ program.command("index").description("Build the local semantic recall index").action(() => runIndex());
47
+ program.command("recall <query...>").description("Search project memory semantically")
48
+ .action((q) => runRecall(q.join(" ")));
49
+ program.command("solutions <term>").description("Search recorded bug solutions").action((t) => runSolutions(t));
50
+ const policy = program.command("policy").description("Guardrail policy");
51
+ policy.command("check").description("Lint policy.json").action(runPolicyCheck);
52
+ program
53
+ .command("update")
54
+ .description("Update registered projects (preserves config.json)")
55
+ .option("--dry-run", "Show what would change")
56
+ .option("--list", "List registered projects")
57
+ .option("--project <name>", "Only the matching project")
58
+ .action((o) => runUpdate(o));
59
+ program.command("doctor").description("Diagnose projects, hooks, and MCP registration").action(runDoctor);
60
+ program.command("mcp").description("Run the PackMind MCP server (stdio)").action(() => runMcp());
61
+ program
62
+ .command("dashboard")
63
+ .description("Open the local web dashboard (loopback only, token-protected)")
64
+ .option("--port <port>", "Preferred port (default 7878)")
65
+ .option("--no-open", "Don't auto-open the browser")
66
+ .action((o) => runDashboard(o));
67
+ return program;
68
+ }