persnally 2.0.3 → 2.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.
package/build/src/cli.js CHANGED
@@ -8,7 +8,7 @@ import { existsSync, rmSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { join } from "node:path";
10
10
  import { applyApiKey, configPath, loadConfig, saveConfig } from "./config.js";
11
- import { CLIENTS, connectAll, connectClient } from "./connect.js";
11
+ import { CLIENTS, connectAll, connectClient, installClaudeCodeHook } from "./connect.js";
12
12
  import { runConsolidation } from "./consolidate.js";
13
13
  import { chooseExtractor } from "./llm.js";
14
14
  import { CATEGORIES, clearScope, loadScopes, setScope } from "./permissions.js";
@@ -19,6 +19,7 @@ import { extractClaudeEvents, parseClaudeExport } from "./importers/claude.js";
19
19
  import { DEFAULT_TRANSCRIPTS_DIR, extractClaudeCodeEvents, parseClaudeCodeTranscripts, } from "./importers/claude-code.js";
20
20
  import { gitEvents, scanRepos } from "./importers/git.js";
21
21
  import { autostartInstalled, installAutostart, LOG_FILE, removeAutostart, removePidFile, runningPid, startDetached, stopDaemon, writePidFile, } from "./lifecycle.js";
22
+ import { newEvent } from "./events.js";
22
23
  import { renderProfile, synthesizeProfile } from "./profile.js";
23
24
  import { DEFAULT_DB_PATH, EventStore } from "./store.js";
24
25
  const USAGE = `persnallyd ${VERSION} — so every AI finally knows you
@@ -36,6 +37,7 @@ Usage:
36
37
  persnallyd profile Synthesize your profile from the store
37
38
  persnallyd consolidate Reflect now: refresh decay, add behavior patterns, re-synthesize
38
39
  persnallyd show [topics|events|profile] Show topics (default), recent events, or the profile
40
+ persnallyd context [--full] Emit profile + interests for AI injection (records a context read)
39
41
  persnallyd forget <topic> Hard-delete a topic and everything derived from it
40
42
  persnallyd forget --all Delete all data
41
43
  persnallyd forget --batch <id> Undo one import batch
@@ -150,9 +152,19 @@ async function main() {
150
152
  }
151
153
  store.close();
152
154
  // 6. AI clients
153
- for (const { client, file } of connectAll()) {
155
+ const connections = connectAll();
156
+ for (const { client, file } of connections) {
154
157
  console.log(file ? `✓ Connected ${client}` : `· ${client} not installed — skipped`);
155
158
  }
159
+ if (connections.some((r) => r.client === "claude-code" && r.file)) {
160
+ try {
161
+ installClaudeCodeHook();
162
+ console.log("✓ Context hook installed (injects on every Claude Code session)");
163
+ }
164
+ catch (e) {
165
+ console.error(`· Context hook skipped: ${e instanceof Error ? e.message : e}`);
166
+ }
167
+ }
156
168
  console.log(`\nDone${imported ? ` — ${imported} events imported` : ""}. Dashboard: http://127.0.0.1:${port}`);
157
169
  if (process.platform === "darwin" && process.stdout.isTTY) {
158
170
  try {
@@ -197,6 +209,15 @@ async function main() {
197
209
  for (const { client, file } of results) {
198
210
  console.log(file ? `Connected ${client} (${file})` : `${client} not installed — skipped`);
199
211
  }
212
+ // Claude Code also gets a SessionStart hook so every session injects context automatically.
213
+ if (results.some((r) => r.client === "claude-code" && r.file)) {
214
+ try {
215
+ console.log(`Installed Claude Code context hook (${installClaudeCodeHook()})`);
216
+ }
217
+ catch (e) {
218
+ console.error(`Context hook not installed: ${e instanceof Error ? e.message : e}`);
219
+ }
220
+ }
200
221
  return;
201
222
  }
202
223
  case "config": {
@@ -304,6 +325,50 @@ async function main() {
304
325
  store.close();
305
326
  return;
306
327
  }
328
+ case "context": {
329
+ // Serving path for the SessionStart hook: emit profile + interests for
330
+ // injection AND record the read, so hook injections count toward the
331
+ // context-reads metric exactly like the MCP persnally_context tool. `show`
332
+ // stays side-effect-free so manual inspection never inflates the metric.
333
+ const full = args.includes("--full");
334
+ const hook = args.includes("--hook");
335
+ const store = new EventStore();
336
+ const profile = store.getProfile();
337
+ const topics = store.topics(full ? 25 : 12);
338
+ if (!profile && !topics.length) {
339
+ store.close();
340
+ return;
341
+ }
342
+ const out = [];
343
+ let items = topics.length;
344
+ if (profile) {
345
+ out.push("# About the user", profile.headline, "");
346
+ const sections = full ? profile.sections : profile.sections.slice(0, 3);
347
+ items += sections.length;
348
+ for (const s of sections)
349
+ out.push(`## ${s.title}`, s.body, "");
350
+ }
351
+ if (topics.length) {
352
+ out.push("# Current interests (decay-weighted)");
353
+ for (const t of topics) {
354
+ out.push(`- ${t.topic} (${t.category}, ${t.dominant_intent}, weight ${t.weight.toFixed(2)})`);
355
+ }
356
+ }
357
+ // Recording must never break the injection itself (mirrors MCP recordRead).
358
+ try {
359
+ store.append([newEvent("context.read", "cli", { scope: full ? "full" : "brief", client_purpose: hook ? "session-start hook" : "cli context read", items }, { kind: "local", surface: "cli" })]);
360
+ }
361
+ catch (e) {
362
+ console.error("persnally: context.read not recorded:", e instanceof Error ? e.message : e);
363
+ }
364
+ store.close();
365
+ const rendered = out.join("\n");
366
+ // --hook emits the SessionStart envelope itself, so the installed hook needs no jq.
367
+ console.log(hook
368
+ ? JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: rendered } })
369
+ : rendered);
370
+ return;
371
+ }
307
372
  case "forget": {
308
373
  const store = new EventStore();
309
374
  if (args[0] === "--all") {
@@ -7,6 +7,13 @@ export type Client = (typeof CLIENTS)[number];
7
7
  export declare function mcpServerPath(): string;
8
8
  /** Returns the config file written, or null when the client isn't installed. */
9
9
  export declare function connectClient(client: Client): string | null;
10
+ /**
11
+ * Installs (or upgrades) the Persnally SessionStart hook in Claude Code's user
12
+ * settings so every session injects the user's context. Merges into existing
13
+ * settings, leaves other tools' hooks untouched, and is idempotent: a prior
14
+ * Persnally entry (including the old `show topics` form) is replaced, not duplicated.
15
+ */
16
+ export declare function installClaudeCodeHook(): string;
10
17
  export declare function connectAll(): {
11
18
  client: Client;
12
19
  file: string | null;
@@ -2,10 +2,17 @@
2
2
  * Writes the Persnally MCP server into AI clients' configs.
3
3
  * Only touches clients that are actually installed; merges, never clobbers.
4
4
  */
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
8
  export const CLIENTS = ["claude-code", "claude-desktop", "cursor"];
9
+ /** Write JSON via temp file + rename: a crash mid-write can't corrupt the user's config. */
10
+ function writeJsonAtomic(file, cfg) {
11
+ mkdirSync(dirname(file), { recursive: true });
12
+ const tmp = `${file}.${process.pid}.tmp`;
13
+ writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n");
14
+ renameSync(tmp, file);
15
+ }
9
16
  function configPathFor(client) {
10
17
  const home = homedir();
11
18
  switch (client) {
@@ -50,8 +57,36 @@ export function connectClient(client) {
50
57
  }
51
58
  const servers = (cfg.mcpServers ??= {});
52
59
  servers.persnally = { command: "node", args: [mcpServerPath()] };
53
- mkdirSync(dirname(file), { recursive: true });
54
- writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
60
+ writeJsonAtomic(file, cfg);
61
+ return file;
62
+ }
63
+ // The hook self-renders the SessionStart envelope (`context --hook`), so no jq dependency.
64
+ const SESSION_START_COMMAND = "persnallyd context --hook 2>/dev/null";
65
+ /**
66
+ * Installs (or upgrades) the Persnally SessionStart hook in Claude Code's user
67
+ * settings so every session injects the user's context. Merges into existing
68
+ * settings, leaves other tools' hooks untouched, and is idempotent: a prior
69
+ * Persnally entry (including the old `show topics` form) is replaced, not duplicated.
70
+ */
71
+ export function installClaudeCodeHook() {
72
+ const file = join(homedir(), ".claude", "settings.json");
73
+ let cfg = {};
74
+ if (existsSync(file)) {
75
+ try {
76
+ cfg = JSON.parse(readFileSync(file, "utf-8"));
77
+ }
78
+ catch {
79
+ throw new Error(`${file} is not valid JSON — fix it, then run \`persnallyd connect claude-code\` again`);
80
+ }
81
+ }
82
+ const hooks = (cfg.hooks ??= {});
83
+ const existing = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : [];
84
+ const others = existing.filter((g) => !g.hooks?.some((h) => /persnall/i.test(h.command ?? "")));
85
+ others.push({
86
+ hooks: [{ type: "command", command: SESSION_START_COMMAND, timeout: 10, statusMessage: "Loading your Persnally context…" }],
87
+ });
88
+ hooks.SessionStart = others;
89
+ writeJsonAtomic(file, cfg);
55
90
  return file;
56
91
  }
57
92
  export function connectAll() {
File without changes
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "persnally",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "license": "FSL-1.1-MIT",
5
- "description": "The context engine for you — local-first, across every AI. So every AI finally knows you.",
5
+ "description": "Your own context engine — local-first, across every AI. So every AI finally knows you.",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "persnally": "build/src/cli.js",