hippo-memory 2.1.0 → 2.3.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/README.md CHANGED
@@ -78,7 +78,7 @@ claim we retracted.
78
78
 
79
79
  ## Quick start
80
80
 
81
- Start in one project. [What hippo init changes](#what-hippo-init-changes) lists everything the second command writes.
81
+ Start in one project. [What hippo init changes](#what-hippo-init-changes) lists everything the second command writes. A step-by-step version is on the website: [hippo-memory.com/quickstart](https://hippo-memory.com/quickstart/).
82
82
 
83
83
  ```bash
84
84
  npm install -g hippo-memory
@@ -223,11 +223,11 @@ hippo context --auto --budget 1500
223
223
  hippo snapshot clear
224
224
  ```
225
225
 
226
- `hippo context --auto` includes the active task snapshot before long-term memories, so agents get both the immediate thread and the deeper lessons.
226
+ `hippo context --auto` prints the active task snapshot before long-term memories when the calling session saved it, so agents get both the immediate thread and the deeper lessons. A snapshot from another session prints as one line that names the command that shows it.
227
227
 
228
228
  ### Session event trails
229
229
 
230
- Manual snapshots are useful, but real work also needs a breadcrumb trail. Hippo can now store short session events and link them to the active snapshot so context output shows the latest steps, not just the last summary.
230
+ Manual snapshots are useful, but real work also needs a breadcrumb trail. Hippo can now store short session events and link them to the active snapshot so context output shows the latest steps, not just the last summary. The trail prints for the calling session's own snapshot; for another session's, the command in the pointer line prints it.
231
231
 
232
232
  ```bash
233
233
  hippo session log \
@@ -810,6 +810,8 @@ On `heartbeat`, `block`, `review` and `complete`, a given `--run` is checked aga
810
810
 
811
811
  Init patches an instruction file only if it already exists. It also sets up a daily run and imports your coding agents' own memories; [What hippo init changes](#what-hippo-init-changes) lists everything.
812
812
 
813
+ Setup guides on the website: [Claude Code](https://hippo-memory.com/claude-code/) · [Codex](https://hippo-memory.com/codex/) · [Cursor](https://hippo-memory.com/cursor/).
814
+
813
815
  ### Manual install
814
816
 
815
817
  If you prefer explicit control:
@@ -823,15 +825,15 @@ hippo hook install opencode # patches AGENTS.md + installs the opencode TS
823
825
  ```
824
826
 
825
827
  This adds a `<!-- hippo:start -->` ... `<!-- hippo:end -->` block that tells the agent to:
826
- 1. Run `hippo context --auto --budget 1500` at session start
827
- 2. Run `hippo remember "<what went wrong and why>" --error` the moment it finds out why something failed, never as a closing step
828
+ 1. Run `hippo context --auto --budget 1500` at the start of a task. In Claude Code and Codex, whose prompt hook already injects pinned rules and matching memories, only if no hippo memory block has appeared in the session
829
+ 2. Everywhere but Claude Code, whose hooks store failed tool calls: run `hippo remember "<description of what went wrong>" --error` the moment it finds out why something failed, never as a closing step
828
830
  3. Everywhere but Claude Code, whose own auto memory does this job: run a plain `hippo remember` the moment it learns something that should outlive the session, leaving out secrets and personal details
829
831
  4. Capture a short summary with `hippo capture --stdin` when the session ends, but only where no hook captures the session: Cursor, OpenClaw, OpenCode, Pi, and Codex without its wrapper
830
832
 
831
833
  The block asks for nothing a hook already does, because each extra tool call re-reads the whole context. Re-running `hippo init` swaps a block an older hippo wrote for the current one, as long as nobody edited it. It leaves an edited block alone and says so, and never touches text outside the markers.
832
834
 
833
835
  For Claude Code, it also adds 7 hook entries to `~/.claude/settings.json`:
834
- - a `SessionEnd` hook that runs `hippo sleep` and then `hippo capture` when the session exits. Capture matches the last 20 user and 10 assistant messages of the transcript against word patterns for decisions, rules, errors and preferences. It uses no model and does not read earlier turns, so record lessons with `hippo remember` as you go.
836
+ - a `SessionEnd` hook that runs `hippo sleep` and then `hippo capture` when the session exits. Capture matches the last 20 user and 10 assistant messages of the transcript against word patterns for decisions, rules, errors and preferences. It uses no model and does not read earlier turns, so a correction older than that window needs a `hippo remember` by hand.
835
837
  - a `SessionStart` hook that prints the previous session's consolidation log on stderr, where `claude --debug` shows it. When the last sleep failed or a compaction summary was set aside, it shows you one line that points to `hippo doctor`.
836
838
  - a `UserPromptSubmit` hook that runs `hippo context --pinned-only --include-recent 5 --format additional-context` every turn. It re-injects pinned memories (`hippo remember <text> --pin`) plus up to 5 memories that share words with your prompt. When nothing matches, it adds only the pinned ones. Since 1.55.0 this replaces the 5 newest memories, which cut the median block from 847 to 533 tokens in our eval. `{"pinnedInject":{"promptRecall":false}}` brings back the 5 newest, so fresh same-session lessons appear on the next prompt whatever you ask. The block is rendered without live strength percentages, so it stays byte-identical while its memories do not change, and it is sent only when it changed since the session's last prompt: an unchanged block is skipped, resent every 10 skips (`pinnedInject.refreshTurns`, `0` never resends) and resent after compaction. The prompt-matched memories go in a separate block that is never skipped, so they are sent on every prompt they match. `{"pinnedInject":{"skipUnchanged":false}}` sends the pinned block every turn as before. Opt out entirely with `{"pinnedInject":{"enabled":false}}` in `.hippo/config.json`.
837
839
  - a `PreCompact` hook that runs `hippo pre-compact` before the transcript gets summarized. It records the compaction in the store, saves a working-state snapshot (task/summary/next step) so mid-session compaction can't drop it, and asks the summariser to end its summary with a "Memories for hippo" list: the lessons, decisions and corrections from the session that should outlive it. The `SessionEnd` hook still owns extracting durable memories from the transcript.
@@ -856,27 +858,21 @@ For GitHub Copilot, when `$COPILOT_HOME` (else `~/.copilot`) or a VS Code User f
856
858
  ````markdown
857
859
  ## Project Memory (Hippo)
858
860
 
859
- Pinned rules and recent writes auto-inject at every prompt via the installed
860
- UserPromptSubmit hook; never re-run that part manually. At the START of a
861
- task (not per prompt), additionally load task-specific context: git-aware
862
- recall over the full store that per-prompt injection does not cover. Also
863
- run it if the hook is not installed:
861
+ The installed UserPromptSubmit hook injects pinned rules and the memories
862
+ that match each prompt, so never load them yourself. If no hippo memory
863
+ block has appeared in this session, run this at the start of a task:
864
864
  ```bash
865
865
  hippo context --auto --budget 1500
866
866
  ```
867
867
 
868
- When you find out why something failed, record it right then, while you
869
- work, never as a closing step:
870
- ```bash
871
- hippo remember "<what went wrong and why>" --error
872
- ```
873
-
874
868
  The installed hooks store failed tool calls and capture the session when it
875
- ends, so there is nothing to run before you finish.
869
+ ends, so there is nothing to record or run by hand.
876
870
  ````
877
871
 
878
872
  ### MCP Server
879
873
 
874
+ Setup for each client: [hippo-memory.com/mcp](https://hippo-memory.com/mcp/).
875
+
880
876
  For any MCP-compatible client (Cursor, Windsurf (now Devin Desktop), Cline, Claude Desktop):
881
877
 
882
878
  ```bash
@@ -991,6 +987,8 @@ The AI-memory category matured fast in 2026. Hippo's specific take (bio-decay, s
991
987
 
992
988
  Different tools answer different questions. Mem0 and Basic Memory implement "save everything, search later." MemPalace implements "store everything, organize spatially for retrieval." gbrain, Zep, and Cognee implement "extract typed entities and relationships into a knowledge graph." Letta implements "the agent edits its own memory blocks." Memoria implements "Git-style version control over the memory state itself." EverMind implements "self-evolving Skill Memory + multi-modal retrieval over hierarchical scopes." Hippo implements "learn what is wrong and stop repeating it." These are complementary takes, not a single-axis ranking: bio-lifecycle (Hippo) + GraphRAG (gbrain/Cognee/Zep) + agent-self-edit (Letta) + memory-VCS (Memoria) + skill-distillation (EverMind) cover different parts of the same problem.
993
989
 
990
+ Side-by-side pages on the website: [hippo vs mem0](https://hippo-memory.com/vs/mem0/) · [hippo vs Zep](https://hippo-memory.com/vs/zep/) · [hippo vs Letta](https://hippo-memory.com/vs/letta/) · [CLAUDE.md vs MEMORY.md](https://hippo-memory.com/vs/claude-memory/).
991
+
994
992
  ---
995
993
 
996
994
  ## Benchmarks
@@ -1097,7 +1095,7 @@ node run.mjs --adapter all
1097
1095
 
1098
1096
  ### How do I give Claude Code memory between sessions?
1099
1097
 
1100
- Run `npm install -g hippo-memory`, then `hippo init` in the project. If the project has a `CLAUDE.md`, init adds a short block telling Claude to run `hippo context --auto` when a session starts. It also adds hooks to Claude Code's settings that keep your pinned memories in context, save a task snapshot before compaction, and run `hippo sleep` when the session ends. `hippo init --scan ~` gives every git repo under your home folder a store and installs the same hooks, but adds no block to any `CLAUDE.md`. The [Claude Code plugin](https://github.com/kitfunso/hippo-memory/tree/master/extensions/claude-code-plugin) is the alternative to these hooks; use one, not both.
1098
+ Run `npm install -g hippo-memory`, then `hippo init` in the project. If the project has a `CLAUDE.md`, init adds a short block saying the prompt hook injects pinned rules and matching memories, and asking Claude to run `hippo context --auto` at the start of a task only if no hippo memory block has appeared. It also adds hooks to Claude Code's settings that keep your pinned memories in context, save a task snapshot before compaction, and run `hippo sleep` when the session ends. `hippo init --scan ~` gives every git repo under your home folder a store and installs the same hooks, but adds no block to any `CLAUDE.md`. The [Claude Code plugin](https://github.com/kitfunso/hippo-memory/tree/master/extensions/claude-code-plugin) is the alternative to these hooks; use one, not both.
1101
1099
 
1102
1100
  ### How do I give Cursor memory between sessions?
1103
1101
 
package/bin/hippo.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from '../dist/cli.js';
2
+ // node:sqlite warns once per process, and an agent reads the lines on each hippo call.
3
+ const emit = process.emitWarning;
4
+ process.emitWarning = (w, ...rest) =>
5
+ rest[0] === 'ExperimentalWarning' && /SQLite/.test(String(w)) ? undefined : emit.call(process, w, ...rest);
6
+ const { runCli } = await import('../dist/cli.js');
3
7
 
4
8
  runCli();
@@ -1,9 +1,11 @@
1
1
  import { type MemoryEntry } from '../core/memory.js';
2
2
  import { type SessionHandoff } from '../core/handoff.js';
3
3
  import type { SessionEvent, TaskSnapshot } from '../store/rows.js';
4
- import type { AssembleCost, AssembleResult, AssembledContextItem, ContextCost, ContextResultEntry, DrillDownChild, DrillDownCost, DrillDownResult } from './index.js';
4
+ import type { AssembleCost, AssembleResult, AssembledContextItem, ContextCost, ContextResultEntry, ContinuityMode, DrillDownChild, DrillDownCost, DrillDownResult } from './index.js';
5
5
  export declare function snapshotText(s: TaskSnapshot): string;
6
6
  export declare function handoffText(h: SessionHandoff): string;
7
+ export declare function snapshotSectionText(s: TaskSnapshot, mode: ContinuityMode): string;
8
+ export declare function handoffSectionText(h: SessionHandoff, mode: ContinuityMode): string;
7
9
  /** Needs at least one event; the header reads the latest. */
8
10
  export declare function sessionTrailText(events: SessionEvent[]): string;
9
11
  export declare const COMPACT_RESUME_EVENT_CONTENT_CAP = 400;
@@ -42,6 +42,28 @@ export function handoffText(h) {
42
42
  lines.push('');
43
43
  return lines.join('\n');
44
44
  }
45
+ // Another session's state rarely bears on this prompt, so a text reader prints where to read it, not the text.
46
+ const pointerTime = (iso) => iso.slice(0, 16).replace('T', ' ');
47
+ // continuityModeFor sends only a pointer-safe id (or a snapshot with none) here, so these only format.
48
+ function snapshotPointerText(s) {
49
+ const at = pointerTime(s.updated_at);
50
+ const line = s.session_id
51
+ ? `- Session ${s.session_id} saved a task snapshot at ${at} UTC. ` +
52
+ `If this task continues it, run \`hippo session latest --id=${s.session_id}\`.`
53
+ : `- A task snapshot from ${at} UTC names no session. If this task continues it, run \`hippo snapshot show\`.`;
54
+ return ['## Active Task Snapshot\n', line, ''].join('\n');
55
+ }
56
+ function handoffPointerText(h) {
57
+ const line = `- Session ${h.sessionId} left a handoff at ${pointerTime(h.updatedAt)} UTC. ` +
58
+ `If this task continues it, run \`hippo handoff latest --session=${h.sessionId}\`.`;
59
+ return ['## Session Handoff\n', line, ''].join('\n');
60
+ }
61
+ export function snapshotSectionText(s, mode) {
62
+ return mode === 'pointer' ? snapshotPointerText(s) : snapshotText(s);
63
+ }
64
+ export function handoffSectionText(h, mode) {
65
+ return mode === 'pointer' ? handoffPointerText(h) : handoffText(h);
66
+ }
45
67
  /** Needs at least one event; the header reads the latest. */
46
68
  export function sessionTrailText(events) {
47
69
  const latest = events[events.length - 1];
@@ -183,8 +205,8 @@ export function contextCost(format, framing) {
183
205
  + (can.cross ? price(crossProjectHeading(budget)) : 0)
184
206
  + (hook && can.promptRecall ? price(contextHeading('Prompt-Relevant Memory', budget, budget)) : 0)
185
207
  + (!hook && can.ambient ? price(`\n${renderAmbientSummary(WIDEST_AMBIENT)}`) : 0),
186
- snapshot: (s) => price(snapshotText(s)),
187
- handoff: (h) => price(handoffText(h)),
208
+ snapshot: (s, mode) => price(snapshotSectionText(s, mode)),
209
+ handoff: (h, mode) => price(handoffSectionText(h, mode)),
188
210
  trail: (events) => price(sessionTrailText(events)),
189
211
  };
190
212
  }
@@ -4,6 +4,8 @@ import type { MemoryEntry } from '../core/memory.js';
4
4
  import type { DeliveryObserver } from '../store/delivery-recorder.js';
5
5
  import type { AmbientState } from '../core/ambient.js';
6
6
  import type { ProjectRef } from '../core/project-identity.js';
7
+ /** How another session's task snapshot and handoff print: whole, or as a continuity pointer. */
8
+ export type ContinuityMode = 'full' | 'pointer';
7
9
  /**
8
10
  * Options for `getContext`: a budget-bounded bundle of recalled memories, active task snapshot, handoff and recent
9
11
  * events.
@@ -49,6 +51,8 @@ export interface ContextOpts {
49
51
  currentSessionId?: string | null;
50
52
  /** Raw hook-payload prompt; only the pinned-only branch reads it, gated on `pinnedInject.promptRecall`. */
51
53
  prompt?: string;
54
+ /** Default 'full'; under 'pointer' the caller's own session, a shared store and an unsafe id still print whole. */
55
+ continuity?: ContinuityMode;
52
56
  /** What the budget pays for, from the caller that renders the block. Absent = the memory text alone. */
53
57
  cost?: ContextCost;
54
58
  /** @internal The CLI's delivery-ledger observer; it only reads, so selection is the same with or without it. */
@@ -66,8 +70,8 @@ export interface ContextCost {
66
70
  ambient: boolean;
67
71
  }) => number;
68
72
  /** Tokens of the sections printed ahead of the memories, each as printed. */
69
- snapshot: (s: TaskSnapshot) => number;
70
- handoff: (h: SessionHandoff) => number;
73
+ snapshot: (s: TaskSnapshot, mode: ContinuityMode) => number;
74
+ handoff: (h: SessionHandoff, mode: ContinuityMode) => number;
71
75
  trail: (events: SessionEvent[]) => number;
72
76
  }
73
77
  export interface ContextResultEntry {
@@ -92,6 +96,9 @@ export interface ContextResult {
92
96
  tokens: number;
93
97
  activeSnapshot?: TaskSnapshot | null;
94
98
  sessionHandoff?: SessionHandoff | null;
99
+ /** Set only when the snapshot or the handoff prints as the pointer. */
100
+ snapshotMode?: ContinuityMode;
101
+ handoffMode?: ContinuityMode;
95
102
  recentEvents?: SessionEvent[];
96
103
  /** The ambient landscape summary over every live row the read may see in the local and global stores,
97
104
  * not just the rows loaded. Present only when ambient config is on, the caller is not pinned-only, and an entry was
@@ -2,6 +2,7 @@
2
2
  import { DEFAULT_SEARCH_CANDIDATE_LIMIT } from '../store/rows.js';
3
3
  import { freshActiveSnapshot, SNAPSHOT_AMBIENT_MAX_AGE_MS } from '../store/sessions.js';
4
4
  import { estimateTokens } from '../util/token-text.js';
5
+ import { isPointerSafeId } from '../util/session-id.js';
5
6
  import { markRetrieved, COMPACTION_MEMORY_TAG } from '../core/memory.js';
6
7
  import { isWorthSurfacing } from '../core/memory-quality.js';
7
8
  import { evalNow, strengthAblation } from '../core/ablation.js';
@@ -131,14 +132,7 @@ export async function getContext(ctx, opts = {}) {
131
132
  const recorded = plan.pinnedOnly
132
133
  ? { items, ambientState: undefined }
133
134
  : await recordRetrieval(ctx, opts, plan, items, sections.activeSnapshot);
134
- return {
135
- entries: recorded.items,
136
- tokens,
137
- activeSnapshot: sections.shownSnapshot ?? undefined,
138
- sessionHandoff: sections.shownHandoff ?? undefined,
139
- recentEvents: sections.shownEvents.length > 0 ? sections.shownEvents : undefined,
140
- ambientState: recorded.ambientState,
141
- };
135
+ return contextResult(recorded, tokens, sections);
142
136
  }
143
137
  function nothingToInject(plan, pools, noSections) {
144
138
  return (!plan.promptRecallPending && pools.local.entries.length === 0 && pools.global.entries.length === 0 && noSections);
@@ -305,19 +299,52 @@ async function loadTaskSections(ctx, opts, plan, startLeft) {
305
299
  // The same envelope rule ambientAdmitEntry applies to memory rows.
306
300
  const activeSnapshot = raw.snapshot && passesScopeFilterForRecall(rowScope(raw.snapshot), exactScope, ownScope) ? raw.snapshot : null;
307
301
  const sessionHandoff = raw.handoff && passesScopeFilterForRecall(rowScope(raw.handoff), exactScope, ownScope) ? raw.handoff : null;
308
- const recentSessionEvents = raw.events.filter((e) => passesScopeFilterForRecall(rowScope(e), exactScope, ownScope));
309
- const shownSnapshot = activeSnapshot && (!cost || pays(cost.snapshot(activeSnapshot))) ? activeSnapshot : null;
310
- const shownHandoff = sessionHandoff && (!cost || pays(cost.handoff(sessionHandoff))) ? sessionHandoff : null;
302
+ const snapshotMode = continuityModeFor(opts, plan, activeSnapshot?.session_id, 'pointer');
303
+ const handoffMode = continuityModeFor(opts, plan, sessionHandoff?.sessionId, 'full');
304
+ const shownSnapshot = activeSnapshot && (!cost || pays(cost.snapshot(activeSnapshot, snapshotMode))) ? activeSnapshot : null;
305
+ const shownHandoff = sessionHandoff && (!cost || pays(cost.handoff(sessionHandoff, handoffMode))) ? sessionHandoff : null;
306
+ // The pointer's command prints the snapshot session's events, so they drop only when that pointer is shown.
307
+ const recentSessionEvents = shownSnapshot !== null && snapshotMode === 'pointer'
308
+ ? []
309
+ : raw.events.filter((e) => passesScopeFilterForRecall(rowScope(e), exactScope, ownScope));
311
310
  const shownEvents = recentSessionEvents.length > 0 && (!cost || pays(cost.trail(recentSessionEvents))) ? recentSessionEvents : [];
312
311
  plan.obs?.sections(Number(shownSnapshot !== null) + Number(shownHandoff !== null) + Number(shownEvents.length > 0), Number(activeSnapshot !== shownSnapshot) +
313
312
  Number(sessionHandoff !== shownHandoff) +
314
313
  Number(recentSessionEvents.length !== shownEvents.length));
315
- return { activeSnapshot, shownSnapshot, shownHandoff, shownEvents, left: left() };
314
+ return { activeSnapshot, shownSnapshot, snapshotMode, shownHandoff, handoffMode, shownEvents, left: left() };
315
+ }
316
+ // The command must return this reader's row, so own, shared-store, unsafe-id print whole; no id: `hippo snapshot show`.
317
+ function continuityModeFor(opts, plan, sessionId, noIdMode) {
318
+ if (opts.continuity !== 'pointer' || plan.sharedStore)
319
+ return 'full';
320
+ if (!sessionId)
321
+ return noIdMode;
322
+ return sessionId === opts.currentSessionId || !isPointerSafeId(sessionId) ? 'full' : 'pointer';
323
+ }
324
+ // The mode is left out of a full print, so every reader's result reads as before.
325
+ function pointerModes(s) {
326
+ const modes = {};
327
+ if (s.shownSnapshot && s.snapshotMode === 'pointer')
328
+ modes.snapshotMode = 'pointer';
329
+ if (s.shownHandoff && s.handoffMode === 'pointer')
330
+ modes.handoffMode = 'pointer';
331
+ return modes;
332
+ }
333
+ function contextResult(recorded, tokens, s) {
334
+ return {
335
+ entries: recorded.items,
336
+ tokens,
337
+ activeSnapshot: s.shownSnapshot ?? undefined,
338
+ sessionHandoff: s.shownHandoff ?? undefined,
339
+ ...pointerModes(s),
340
+ recentEvents: s.shownEvents.length > 0 ? s.shownEvents : undefined,
341
+ ambientState: recorded.ambientState,
342
+ };
316
343
  }
317
344
  function ambientAdmission(opts, plan, shownHandoff) {
318
345
  const transcriptHandoffSession = shownHandoff?.evidence?.derivedFrom === 'transcript' ? shownHandoff.sessionId : null;
319
346
  const ambientAdmit = (e) => {
320
- // A printed handoff already carries the session's closing message, which its digest would print a second time.
347
+ // A shown handoff, whole or as a pointer, stands for the session's closing message; its command prints it.
321
348
  if (transcriptHandoffSession !== null &&
322
349
  e.source_session_id === transcriptHandoffSession &&
323
350
  isSessionDigestRow(e)) {
@@ -30,7 +30,7 @@ export { DEFAULT_KEY_TTL_DAYS, MAX_TTL_DAYS, authCreate, authCreateSelf, authGra
30
30
  export type { AuthCreateOpts, AuthCreateResult, AuthCreateSelfOpts, AuthCreateSelfResult, AuthGrantResult, AuthRevokeResult, } from './auth/auth.js';
31
31
  export { auditList, auditMemoryQuality, computeCutoff, pruneAuditLog, removeAuditErrors, repairMemoryQuality, repairMemoryQualityOnce, } from './auth/audit.js';
32
32
  export type { AuditListOpts, AuditPass, PruneAuditOpts, PruneAuditResult } from './auth/audit.js';
33
- export type { ContextCost, ContextOpts, ContextResult, ContextResultEntry } from './context-types.js';
33
+ export type { ContextCost, ContextOpts, ContextResult, ContextResultEntry, ContinuityMode } from './context-types.js';
34
34
  export { DEFAULT_CONTEXT_BUDGET, NO_QUERY, ambientSecretAdmit, getContext, oneCopyPerMemory } from './context.js';
35
35
  export { failureSummary, recordTokens, tokenSummary } from './tokens.js';
36
36
  export { forgetDormant, isDormant, listDormant, restoreDormant } from './sleep/dormant.js';
@@ -1,4 +1,4 @@
1
- import { type Context, type ContextResult, type ContextResultEntry, type ContextWith } from './index.js';
1
+ import { type Context, type ContextResult, type ContextResultEntry, type ContextWith, type ContinuityMode } from './index.js';
2
2
  import { type HippoConfig } from '../core/config.js';
3
3
  import { type DeliveryEventType, type DeliveryFault, type DeliveryRecorder } from '../store/delivery-recorder.js';
4
4
  import type { HookRuntime } from '../core/capture-contract.js';
@@ -82,6 +82,8 @@ export interface PromptHookOpts {
82
82
  /** The store serves many people, so the caller is not its owner: no global store, no user-global recent rows,
83
83
  * task state only for the caller's own owner and project, and no ledger rows outside this store. */
84
84
  readonly sharedStore?: true;
85
+ /** Default 'full': a pointer names a command that cannot reach this store, so the caller opts in. */
86
+ readonly continuity?: ContinuityMode;
85
87
  }
86
88
  /** The caps on a hook caller's session id and project names, so a caller other than an HTTP route is bounded too. */
87
89
  export declare function assertCallerIds(sessionId: string, project: CallerProject): void;
@@ -1,10 +1,10 @@
1
1
  // The per-prompt hook's block and ledger rows, rendered here for `hippo context` and for promptHookContext (a remote
2
- // hook route's call). promptHookContext keeps the server-side copy of the CLI's getContext flags (cli/context.ts); the
3
- // CLI parity case in tests/prompt-hook-context.test.ts is all that ties the two.
4
- import { getContext } from './index.js';
2
+ // hook route's call). promptHookContext copies the CLI's getContext flags (cli/context.ts) bar `continuity`: the CLI
3
+ // points for text formats; this prints whole unless its caller opts in. Parity: tests/prompt-hook-context.test.ts.
4
+ import { getContext, } from './index.js';
5
5
  import { BadRequestError } from '../core/api-errors.js';
6
6
  import { isSharedStore, loadConfig } from '../core/config.js';
7
- import { contextBlockLines, contextCost, crossProjectLines, handoffText, sessionTrailText, settleTokens, snapshotText, } from './context-render.js';
7
+ import { contextBlockLines, contextCost, crossProjectLines, handoffSectionText, sessionTrailText, settleTokens, snapshotSectionText, } from './context-render.js';
8
8
  import { createDeliveryRecorder, } from '../store/delivery-recorder.js';
9
9
  import { realpathOrResolve } from '../util/real-path.js';
10
10
  import { MAX_ID_LEN } from '../util/limits.js';
@@ -99,8 +99,8 @@ export function additionalContextOutput(view) {
99
99
  function renderStaticBlock(view, staticItems, staticCrossEntries) {
100
100
  const { result, framing } = view;
101
101
  return settleTokens((t) => [
102
- ...(result.activeSnapshot ? [snapshotText(result.activeSnapshot)] : []),
103
- ...(result.sessionHandoff ? [handoffText(result.sessionHandoff)] : []),
102
+ ...(result.activeSnapshot ? [snapshotSectionText(result.activeSnapshot, result.snapshotMode ?? 'full')] : []),
103
+ ...(result.sessionHandoff ? [handoffSectionText(result.sessionHandoff, result.handoffMode ?? 'full')] : []),
104
104
  ...(result.recentEvents && result.recentEvents.length > 0 ? [sessionTrailText(result.recentEvents)] : []),
105
105
  // No live strength percentage, so an unchanged set of memories renders byte-identically turn after turn.
106
106
  ...(staticItems.length > 0 ? contextBlockLines(staticItems, t, framing, { showStrength: false }) : []),
@@ -251,6 +251,7 @@ export async function promptHookContext(ctx, req, opts = {}) {
251
251
  prompt: isJsonString(prompt) ? prompt : undefined,
252
252
  cost: contextCost('additional-context', HOOK_FRAMING),
253
253
  sharedStore,
254
+ continuity: opts.continuity ?? 'full',
254
255
  });
255
256
  const rendered = hasContextData(result)
256
257
  ? renderAdditionalContext({
@@ -8,7 +8,6 @@ export interface CopilotTurn {
8
8
  role: 'user' | 'assistant';
9
9
  text: string;
10
10
  }
11
- export declare const SESSION_ID_RE: RegExp;
12
11
  /**
13
12
  * The Copilot CLI log for a session, `<copilotHome>/session-state/<id>/events.jsonl`; null for an unsafe id or a
14
13
  * missing file.
@@ -5,8 +5,7 @@ import * as fs from 'fs';
5
5
  import * as path from 'path';
6
6
  import { copilotHomeDir } from '../hooks/shared.js';
7
7
  import { isObjectLike, isStringValue } from '../core/capture-contract.js';
8
- // A session id becomes a folder name, so anything beyond word characters and hyphens could climb out of session-state.
9
- export const SESSION_ID_RE = /^[\w-]+$/;
8
+ import { SESSION_ID_RE } from '../util/session-id.js';
10
9
  // user.message sources that mark text hippo did not get from the human: a hidden skill injection or another agent's
11
10
  // prompt.
12
11
  const INJECTED_SOURCE_PREFIXES = ['skill-', 'agent-'];
@@ -5,7 +5,7 @@ import * as path from 'path';
5
5
  import { homeDir } from '../util/agent-homes.js';
6
6
  import { errorCode, errorMessage, log as logger, errorFields } from '../util/log.js';
7
7
  import { isObjectLike, isStringValue } from '../core/capture-contract.js';
8
- import { SESSION_ID_RE } from './copilot-transcript.js';
8
+ import { SESSION_ID_RE } from '../util/session-id.js';
9
9
  import { blockHash } from '../util/token-text.js';
10
10
  import { MINUTE_MS } from '../util/time.js';
11
11
  /** Null for a missing id or one that could climb out of the sessions folder. */
@@ -10,12 +10,12 @@ import * as api from '../api/index.js';
10
10
  import { DEFAULT_CONTEXT_BUDGET, NO_QUERY } from '../api/context.js';
11
11
  import { cliApiContext } from './api-context.js';
12
12
  import { renderAmbientSummary } from '../core/ambient.js';
13
- import { contextBlockLines, contextCost, crossProjectLines, settleTokens } from '../api/context-render.js';
13
+ import { contextBlockLines, contextCost, crossProjectLines, handoffSectionText, settleTokens, snapshotSectionText, } from '../api/context-render.js';
14
14
  import { additionalContextOutput, flushDeliveryRecorder, hasContextData, startDeliveryRecorder, sessionStartEnvelope, toRenderItems, } from '../api/prompt-hook.js';
15
15
  import { parseLimitFlag, parseCountFlag, parseBudgetFlag, flagIsTrue, stringFlagOrExit, } from './flag-values.js';
16
16
  import { requireInit } from './shared.js';
17
17
  import { errorFields, errorMessage, log } from '../util/log.js';
18
- import { printActiveTaskSnapshot, printSessionEvents, printHandoff, captureConsole } from './print.js';
18
+ import { printSessionEvents, captureConsole } from './print.js';
19
19
  import { hostSessionId, hookStoreRoot, hookRuntime, payloadCwdRoot, runHookWithStores, inPilotHoldout, } from './hook-runtime.js';
20
20
  async function cmdContext(hippoRoot, tenantId, args, flags, stdinText) {
21
21
  const rec = startDeliveryRecorder(cliApiContext(hippoRoot, tenantId), {
@@ -149,6 +149,8 @@ function buildContextOpts(flags, input) {
149
149
  crossProject,
150
150
  currentSessionId: input.session.currentSessionId,
151
151
  prompt: input.session.prompt,
152
+ // JSON stays whole for the programs that parse it; every text format points to another session's state.
153
+ continuity: input.format === 'json' ? 'full' : 'pointer',
152
154
  // JSON is budgeted as the markdown it stands for, so one budget picks the same memories in every format.
153
155
  cost: contextCost(input.format === 'additional-context' || input.format === 'copilot' ? 'additional-context' : 'markdown', input.framing),
154
156
  deliveryObserver: input.rec ?? undefined,
@@ -193,10 +195,10 @@ function renderContextMarkdown(view) {
193
195
  const crossEntries = result.entries.filter((r) => r.category === 'cross-project');
194
196
  const text = settleTokens((t) => captureConsole(() => {
195
197
  if (result.activeSnapshot) {
196
- printActiveTaskSnapshot(result.activeSnapshot);
198
+ console.log(snapshotSectionText(result.activeSnapshot, result.snapshotMode ?? 'full'));
197
199
  }
198
200
  if (result.sessionHandoff) {
199
- printHandoff(result.sessionHandoff);
201
+ console.log(handoffSectionText(result.sessionHandoff, result.handoffMode ?? 'full'));
200
202
  }
201
203
  if (result.recentEvents && result.recentEvents.length > 0) {
202
204
  printSessionEvents(result.recentEvents);
@@ -15,7 +15,8 @@ import { cmdCapture } from '../capture/command.js';
15
15
  import { cmdPreCompact, cmdPostCompact } from '../capture/compact.js';
16
16
  import { transcriptWorkingState } from '../capture/working-state.js';
17
17
  import { collectHandoffEvidence } from '../capture/handoff-evidence.js';
18
- import { copilotTranscriptFor, SESSION_ID_RE } from '../capture/copilot-transcript.js';
18
+ import { copilotTranscriptFor } from '../capture/copilot-transcript.js';
19
+ import { SESSION_ID_RE } from '../util/session-id.js';
19
20
  import { loadTurnPosition, runSessionWorker, saveTurnPosition, turnsAfter, } from '../capture/session-worker.js';
20
21
  import { isStringValue, readSessionEnd, readVscodeStop, } from '../core/capture-contract.js';
21
22
  import { loadConfig } from '../core/config.js';
@@ -104,14 +104,20 @@ export declare function passHatK(runsByTask: boolean[][], k: number): number;
104
104
  export type Family<T> = readonly T[];
105
105
  /** One repository's families; a task with no lesson is a family of one. */
106
106
  export type Repository<T> = readonly Family<T>[];
107
- /** An {@link Estimate} with a two-sided p-value from the same resamples. */
107
+ /** An {@link Estimate} with a two-sided p-value, from bootstrap resamples or from a t test over repositories. */
108
108
  export interface TestedEstimate extends Estimate {
109
- /** 2 x min(share <= null, share >= null), capped at 1; NaN with fewer than two repositories. */
109
+ /** Bootstrap: 2 x min(share <= null, share >= null) of the resamples, capped at 1. t test: the two-sided Student t p.
110
+ * NaN with fewer than two repositories. */
110
111
  readonly p: number;
111
- /** Non-finite resamples, dropped; `iterations + dropped` is the number requested. */
112
+ /** Non-finite resamples, dropped; `iterations + dropped` is the number requested. Both are 0 for a t test. */
112
113
  readonly dropped: number;
113
114
  /** The null the p-value tested against; {@link verdict} reads its sides from here. */
114
115
  readonly nullValue: number;
116
+ /** Degrees of freedom of a t test (a fixed-repository test gives a fractional Satterthwaite value);
117
+ * absent on a bootstrap. */
118
+ readonly df?: number;
119
+ /** Standard error of a t test; absent on a bootstrap. */
120
+ readonly se?: number;
115
121
  }
116
122
  /** Options for {@link twoLevelBootstrap}. */
117
123
  export interface TwoLevelOpts extends BootstrapOpts {
@@ -119,7 +125,12 @@ export interface TwoLevelOpts extends BootstrapOpts {
119
125
  readonly iterations?: number;
120
126
  /** Value the p-value tests against: 0 for differences, 1 for ratios. Default 0. */
121
127
  readonly nullValue?: number;
128
+ /** Keep every repository in place and resample families inside each: the stratified twin of a
129
+ * fixed-repository t test. Default false. */
130
+ readonly fixedRepositories?: boolean;
122
131
  }
132
+ /** The result with nothing to test: estimate, bounds and p all NaN. */
133
+ export declare function notANumber(nullValue: number, dropped: number): TestedEstimate;
123
134
  /** Resamples repositories, then families inside each; only the repository draw carries a shared-store fault.
124
135
  * The statistic never uses the PRNG, so a second call on one seed draws the same resamples. */
125
136
  export declare function twoLevelBootstrap<T>(repos: readonly Repository<T>[], statistic: (units: readonly T[]) => number, opts?: TwoLevelOpts): TestedEstimate;
@@ -168,14 +168,15 @@ export function passHatK(runsByTask, k) {
168
168
  return Number.NaN;
169
169
  return eligible.filter((r) => r.slice(0, k).every(Boolean)).length / eligible.length;
170
170
  }
171
- function notANumber(nullValue, dropped) {
171
+ /** The result with nothing to test: estimate, bounds and p all NaN. */
172
+ export function notANumber(nullValue, dropped) {
172
173
  const nan = Number.NaN;
173
174
  return { estimate: nan, low: nan, high: nan, p: nan, iterations: 0, dropped, nullValue };
174
175
  }
175
- function resampleUnits(repos, rand) {
176
+ function resampleUnits(repos, rand, fixedRepositories) {
176
177
  const units = [];
177
178
  for (let i = 0; i < repos.length; i++) {
178
- const repo = repos[Math.floor(rand() * repos.length)];
179
+ const repo = fixedRepositories ? repos[i] : repos[Math.floor(rand() * repos.length)];
179
180
  for (let j = 0; j < repo.length; j++) {
180
181
  for (const unit of repo[Math.floor(rand() * repo.length)])
181
182
  units.push(unit);
@@ -209,7 +210,7 @@ export function twoLevelBootstrap(repos, statistic, opts = {}) {
209
210
  const rand = seededRandom(opts.seed ?? 1);
210
211
  const samples = [];
211
212
  for (let b = 0; b < requested; b++) {
212
- const value = statistic(resampleUnits(kept, rand));
213
+ const value = statistic(resampleUnits(kept, rand, opts.fixedRepositories ?? false));
213
214
  if (Number.isFinite(value))
214
215
  samples.push(value);
215
216
  }
@@ -0,0 +1,62 @@
1
+ /** Student t tests for the built-in memory eval. The repositories are fixed and the family is the unit
2
+ * (Amendment 2): a variance-components t over family-by-seed tables with Satterthwaite df, plus the older
3
+ * one-value-per-repository tests (G-1 df).
4
+ * The t distribution is written here because the package carries no statistics library. */
5
+ import { type TestedEstimate } from './eval-stats.js';
6
+ /** log Gamma(z) for z >= 0.5, by the Lanczos series (g 7, nine terms). */
7
+ export declare function lnGamma(z: number): number;
8
+ /** Regularized incomplete beta I_x(a, b). */
9
+ export declare function incompleteBeta(x: number, a: number, b: number): number;
10
+ /** Student t cumulative distribution P(T <= t) with `df` degrees of freedom. */
11
+ export declare function studentTCdf(t: number, df: number): number;
12
+ /** Student t quantile: the t with P(T <= t) = p, found by bisection on the CDF. */
13
+ export declare function studentTQuantile(p: number, df: number): number;
14
+ /** One-sample t test on per-repository values: the mean, se = sd / sqrt(G), G-1 degrees of freedom.
15
+ * Fewer than two repositories give the not-a-number result. */
16
+ export declare function repositoryT(values: readonly number[], nullValue?: number): TestedEstimate;
17
+ /** One unit of a family-by-seed table; units that share a (repo, family, seed) cell are averaged. */
18
+ export interface FamilyUnit {
19
+ readonly repo: string;
20
+ readonly family: string;
21
+ readonly seed: number;
22
+ readonly value: number;
23
+ }
24
+ /** Mean squares pooled over the fitted repositories of a family-by-seed fit, weighted by df, with the mean
25
+ * seeds per family (`sBar`) and families per seed (`kBar`) that turn them into variance components;
26
+ * `repos` lists every repository. */
27
+ export interface PooledComponents {
28
+ readonly repos: readonly {
29
+ readonly k: number;
30
+ readonly s: number;
31
+ readonly n: number;
32
+ }[];
33
+ readonly F: number;
34
+ readonly Q: number;
35
+ readonly E: number;
36
+ readonly dfF: number;
37
+ readonly dfQ: number;
38
+ readonly dfE: number;
39
+ readonly sBar: number;
40
+ readonly kBar: number;
41
+ }
42
+ /** The pooled mean squares the fixed-repository t test reads, for one repository or more; null when none can be fitted.
43
+ * The seed rule and the sizer take their spreads from here, so they cannot drift from the test. */
44
+ export declare function pooledComponents(units: readonly FamilyUnit[]): PooledComponents | null;
45
+ /** Mean of the repository estimates with repositories held fixed: the spread is family and seed variation inside each
46
+ * (additive model y = mu + a_f + b_s), pooled over fitted repositories (two or more families and seeds in
47
+ * one connected block, one residual df); a thinner or split one adds its mean and borrows the pooled spread.
48
+ * Fewer than two repositories or none fitted: NaN. */
49
+ export declare function fixedRepositoryT(units: readonly FamilyUnit[], nullValue?: number): TestedEstimate;
50
+ /** One (repo, family, seed) cell's summed treatment and control values. */
51
+ export interface RatioCell {
52
+ readonly repo: string;
53
+ readonly family: string;
54
+ readonly seed: number;
55
+ readonly t: number;
56
+ readonly c: number;
57
+ }
58
+ /** The pooled ratio sum(t) / sum(c) against 1; its spread is fixedRepositoryT on the residuals (t - R c) / mean(c).
59
+ * The interval is on the log scale (`se` too): with skewed costs the symmetric R +- t se passed 5.2-5.6% at a true
60
+ * 1.10, over the 5% bar, and the log form passed 3.2-4.7%. */
61
+ export declare function fixedRepositoryRatioT(cells: readonly RatioCell[]): TestedEstimate;
62
+ //# sourceMappingURL=repository-t.d.ts.map