hippo-memory 3.1.1 → 3.2.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/dist/api/context/context-plan.d.ts +2 -0
- package/dist/api/context/context-plan.js +8 -2
- package/dist/api/context/context-pools.d.ts +3 -0
- package/dist/api/context/context-pools.js +12 -0
- package/dist/api/context/context-render.d.ts +6 -0
- package/dist/api/context/context-render.js +24 -9
- package/dist/api/context/context-types.d.ts +6 -3
- package/dist/api/context/context.js +5 -4
- package/dist/api/context/user-rule.d.ts +12 -0
- package/dist/api/context/user-rule.js +24 -0
- package/dist/api/context/user-rules-get.d.ts +10 -0
- package/dist/api/context/user-rules-get.js +25 -0
- package/dist/api/index.d.ts +1 -0
- package/dist/api/index.js +1 -0
- package/dist/api/memories/remember.js +2 -2
- package/dist/api/prompt-hook.d.ts +11 -0
- package/dist/api/prompt-hook.js +26 -10
- package/dist/api/session-end.d.ts +1 -1
- package/dist/api/session-end.js +5 -3
- package/dist/base/memory/entry.d.ts +5 -0
- package/dist/base/memory/entry.js +8 -1
- package/dist/base/ports/store/ledger.d.ts +2 -2
- package/dist/base/util/version.d.ts +1 -1
- package/dist/base/util/version.js +1 -1
- package/dist/store/sqlite/ledger/token-ledger.js +7 -1
- package/dist/surface/capture/command.d.ts +3 -0
- package/dist/surface/capture/command.js +11 -10
- package/dist/surface/capture/extract.d.ts +3 -2
- package/dist/surface/capture/extract.js +56 -11
- package/dist/surface/capture/transcript.js +6 -1
- package/dist/surface/cli/context.d.ts +7 -0
- package/dist/surface/cli/context.js +17 -10
- package/dist/surface/cli/hook.js +3 -0
- package/dist/surface/cli/hooks/session-end-worker.js +5 -3
- package/dist/surface/cli/init.js +3 -0
- package/dist/surface/cli/memory-import.js +2 -1
- package/dist/surface/cli/session-rules.d.ts +3 -0
- package/dist/surface/cli/session-rules.js +45 -0
- package/dist/surface/cli/setup.js +2 -0
- package/dist/surface/cli/verbs/sessions.d.ts +1 -0
- package/dist/surface/cli/verbs/sessions.js +10 -2
- package/dist/surface/cli/verbs.d.ts +1 -0
- package/dist/surface/hooks-install/rules/claude-hooks.js +11 -3
- package/dist/surface/hooks-install/rules/install-plan.js +1 -0
- package/dist/surface/hooks-install/rules/json-hooks.d.ts +2 -0
- package/dist/surface/hooks-install/rules/shared.d.ts +2 -0
- package/dist/surface/hooks-install/rules/shared.js +2 -0
- package/extensions/openclaw-plugin/openclaw.plugin.json +1 -1
- package/extensions/openclaw-plugin/package.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
|
@@ -38,6 +38,8 @@ export interface ContextPlan {
|
|
|
38
38
|
promptRecallPending: boolean;
|
|
39
39
|
cost: ContextCost | undefined;
|
|
40
40
|
price: (entry: MemoryEntry, isGlobal: boolean, promptRecall?: boolean) => number;
|
|
41
|
+
/** Whether a row prints as the person's own rule for this caller. */
|
|
42
|
+
isUserRule: (entry: MemoryEntry, isGlobal: boolean) => boolean;
|
|
41
43
|
obs: DeliveryObserver | undefined;
|
|
42
44
|
/** The instant the whole read scores strength at, by the model its Context runs under. */
|
|
43
45
|
now: Date;
|
|
@@ -5,6 +5,7 @@ import { classifyOriginProject, projectId, projectNames, } from '../../base/scop
|
|
|
5
5
|
import { DEFAULT_CONFIG } from '../../base/config/config.js';
|
|
6
6
|
import { promptSearchTerms } from '../../base/rank/prompt-recall.js';
|
|
7
7
|
import { personalScopeOf } from '../../base/scope/recall-scope.js';
|
|
8
|
+
import { isUserRule } from './user-rule.js';
|
|
8
9
|
import { finiteOr } from '../../domain/context/select-policy.js';
|
|
9
10
|
import { strengthOf } from '../types.js';
|
|
10
11
|
/** The operator's global store, which planContext proved present before it set hasGlobal. */
|
|
@@ -50,7 +51,7 @@ export function globalSource(ctx) {
|
|
|
50
51
|
}
|
|
51
52
|
/** Prices one entry against the budget: the caller's cost model when it gave one, else a token
|
|
52
53
|
* estimate. */
|
|
53
|
-
function entryPricer(cost, currentProject) {
|
|
54
|
+
function entryPricer(cost, currentProject, userRule) {
|
|
54
55
|
return (entry, isGlobal, promptRecall) => cost
|
|
55
56
|
? cost.entry({
|
|
56
57
|
entry,
|
|
@@ -58,6 +59,7 @@ function entryPricer(cost, currentProject) {
|
|
|
58
59
|
promptRecall,
|
|
59
60
|
origin: entry.originProject ?? null,
|
|
60
61
|
category: classifyOriginProject(entry.originProject, currentProject),
|
|
62
|
+
userRule: userRule(entry, isGlobal),
|
|
61
63
|
})
|
|
62
64
|
: estimateTokens(entry.content);
|
|
63
65
|
}
|
|
@@ -97,7 +99,8 @@ export function planContext(ctx, opts, local) {
|
|
|
97
99
|
// connection.
|
|
98
100
|
const promptRecallPending = pinnedOnly && Boolean(opts.prompt?.trim()) && config.pinnedInject.promptRecall === true;
|
|
99
101
|
const cost = opts.cost;
|
|
100
|
-
const
|
|
102
|
+
const userRule = (entry, isGlobal) => isUserRule(entry, { tenantId: ctx.tenantId, project: currentProject, isGlobal });
|
|
103
|
+
const price = entryPricer(cost, currentProject, userRule);
|
|
101
104
|
return {
|
|
102
105
|
local,
|
|
103
106
|
pinnedOnly,
|
|
@@ -117,6 +120,7 @@ export function planContext(ctx, opts, local) {
|
|
|
117
120
|
promptRecallPending,
|
|
118
121
|
cost,
|
|
119
122
|
price,
|
|
123
|
+
isUserRule: userRule,
|
|
120
124
|
obs: opts.deliveryObserver,
|
|
121
125
|
now: ctx.infra.clock(),
|
|
122
126
|
strength: strengthOf(ctx),
|
|
@@ -157,6 +161,8 @@ export function openBlockBudget(plan, opts, budget) {
|
|
|
157
161
|
cross: plan.includeCrossProject,
|
|
158
162
|
promptRecall: promptRecallPending,
|
|
159
163
|
ambient: !pinnedOnly && config.ambient.enabled,
|
|
164
|
+
// Unknown until the rows load; userRuleReserve pays it then.
|
|
165
|
+
userRule: false,
|
|
160
166
|
}))
|
|
161
167
|
: blockBudget;
|
|
162
168
|
}
|
|
@@ -25,5 +25,8 @@ interface LoadPoolsOptions {
|
|
|
25
25
|
readonly left: number;
|
|
26
26
|
}
|
|
27
27
|
export declare function loadPools(ctx: Context, { plan, admission, recallRequest, left }: LoadPoolsOptions): Promise<ContextPools>;
|
|
28
|
+
/** The tokens of the user-rule heading: nothing unless a loaded row prints under it. SHORTCUT: paid
|
|
29
|
+
* when the pool holds a user rule, even if the ranking then leaves it out; one heading of slack. */
|
|
30
|
+
export declare function userRuleReserve(plan: ContextPlan, pools: ContextPools): number;
|
|
28
31
|
export {};
|
|
29
32
|
//# sourceMappingURL=context-pools.d.ts.map
|
|
@@ -110,6 +110,18 @@ export async function loadPools(ctx, { plan, admission, recallRequest, left }) {
|
|
|
110
110
|
: { entries: [] };
|
|
111
111
|
return { local, global };
|
|
112
112
|
}
|
|
113
|
+
/** The tokens of the user-rule heading: nothing unless a loaded row prints under it. SHORTCUT: paid
|
|
114
|
+
* when the pool holds a user rule, even if the ranking then leaves it out; one heading of slack. */
|
|
115
|
+
export function userRuleReserve(plan, pools) {
|
|
116
|
+
const { cost } = plan;
|
|
117
|
+
const held = pools.local.entries.some((e) => plan.isUserRule(e, plan.primaryIsGlobal)) ||
|
|
118
|
+
pools.global.entries.some((e) => plan.isUserRule(e, true));
|
|
119
|
+
if (!cost || !held)
|
|
120
|
+
return 0;
|
|
121
|
+
// The headings are priced apart, so the two totals differ by the user-rule heading alone.
|
|
122
|
+
const can = { cross: false, promptRecall: false, ambient: false };
|
|
123
|
+
return cost.fixed(0, { ...can, userRule: true }) - cost.fixed(0, { ...can, userRule: false });
|
|
124
|
+
}
|
|
113
125
|
// With prompt recall on, eligibility reports a row the quality floor drops.
|
|
114
126
|
function refusalReporter(plan, isGlobal) {
|
|
115
127
|
const { obs } = plan;
|
|
@@ -37,6 +37,12 @@ export declare function contextBlockLines(items: ReadonlyArray<{
|
|
|
37
37
|
heading?: string;
|
|
38
38
|
strength?: StrengthModel;
|
|
39
39
|
}): string[];
|
|
40
|
+
export declare const USER_RULES_HEADING = "## Rules from the user";
|
|
41
|
+
/** The person's own rule as a plain instruction: no confidence, date or tags to read it as an old
|
|
42
|
+
* note. */
|
|
43
|
+
export declare function userRuleLine(e: MemoryEntry): string;
|
|
44
|
+
/** The section that opens a block; no rules print nothing, and the blank line closes it. */
|
|
45
|
+
export declare function userRuleLines(entries: readonly MemoryEntry[]): string[];
|
|
40
46
|
export declare function crossProjectHeading(entries: number): string;
|
|
41
47
|
export declare function crossProjectLine(item: Pick<ContextResultEntry, 'entry' | 'origin'>): string;
|
|
42
48
|
/** An explicit header lets agents and humans tell borrowed context from project memory; no items
|
|
@@ -167,6 +167,18 @@ export function contextBlockLines(items, totalTokens, framing, opts) {
|
|
|
167
167
|
})),
|
|
168
168
|
];
|
|
169
169
|
}
|
|
170
|
+
export const USER_RULES_HEADING = '## Rules from the user';
|
|
171
|
+
// The person's reply lead ("No:", "Yes, keep doing that:") reads as an answer, not as an order.
|
|
172
|
+
const CORRECTION_LEAD = /^(?:No|Yes, keep doing that):\s*/;
|
|
173
|
+
/** The person's own rule as a plain instruction: no confidence, date or tags to read it as an old
|
|
174
|
+
* note. */
|
|
175
|
+
export function userRuleLine(e) {
|
|
176
|
+
return `- ${shownContent({ ...e, content: e.content.replace(CORRECTION_LEAD, '') })}`;
|
|
177
|
+
}
|
|
178
|
+
/** The section that opens a block; no rules print nothing, and the blank line closes it. */
|
|
179
|
+
export function userRuleLines(entries) {
|
|
180
|
+
return entries.length === 0 ? [] : [USER_RULES_HEADING, ...entries.map(userRuleLine), ''];
|
|
181
|
+
}
|
|
170
182
|
export function crossProjectHeading(entries) {
|
|
171
183
|
return `\n## Other-project memory (explicitly requested, ${entries} entries)\n`;
|
|
172
184
|
}
|
|
@@ -262,16 +274,19 @@ export function contextCost(format, framing, now) {
|
|
|
262
274
|
const hook = format === 'additional-context';
|
|
263
275
|
const price = printedTokens;
|
|
264
276
|
return {
|
|
265
|
-
entry: (item) => price(item.
|
|
266
|
-
?
|
|
267
|
-
:
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
277
|
+
entry: (item) => price(item.userRule
|
|
278
|
+
? userRuleLine(item.entry)
|
|
279
|
+
: item.category === 'cross-project' && !(hook && item.promptRecall)
|
|
280
|
+
? crossProjectLine(item)
|
|
281
|
+
: contextLine({
|
|
282
|
+
item: { entry: item.entry, isGlobal: item.isGlobal ?? false },
|
|
283
|
+
framing,
|
|
284
|
+
showStrength: !hook,
|
|
285
|
+
now,
|
|
286
|
+
strengthPct: FULL_STRENGTH_PCT,
|
|
287
|
+
})),
|
|
274
288
|
fixed: (budget, can) => price(contextHeading('Project Memory', budget, budget)) +
|
|
289
|
+
(can.userRule ? price(`${USER_RULES_HEADING}\n`) : 0) +
|
|
275
290
|
(can.cross ? price(crossProjectHeading(budget)) : 0) +
|
|
276
291
|
(hook && can.promptRecall
|
|
277
292
|
? price(contextHeading('Prompt-Relevant Memory', budget, budget))
|
|
@@ -66,14 +66,17 @@ export interface ContextOptions {
|
|
|
66
66
|
}
|
|
67
67
|
/** Budget prices in the text a caller prints, so the budget bounds what reaches the model. */
|
|
68
68
|
export interface ContextCost {
|
|
69
|
-
/** Tokens of one entry as printed. */
|
|
70
|
-
entry: (item: Pick<ContextResultEntry, 'entry' | 'isGlobal' | 'promptRecall' | 'origin' | 'category'>
|
|
69
|
+
/** Tokens of one entry as printed; `userRule` marks a row that prints as the person's own rule. */
|
|
70
|
+
entry: (item: Pick<ContextResultEntry, 'entry' | 'isGlobal' | 'promptRecall' | 'origin' | 'category'> & {
|
|
71
|
+
userRule?: boolean;
|
|
72
|
+
}) => number;
|
|
71
73
|
/** Tokens of the headers and footer the block can print at this budget, reserved before any
|
|
72
|
-
* entry. */
|
|
74
|
+
* entry. `userRule` is true only when the view holds a user rule. */
|
|
73
75
|
fixed: (budget: number, can: {
|
|
74
76
|
cross: boolean;
|
|
75
77
|
promptRecall: boolean;
|
|
76
78
|
ambient: boolean;
|
|
79
|
+
userRule: boolean;
|
|
77
80
|
}) => number;
|
|
78
81
|
/** Tokens of the sections printed ahead of the memories, each as printed. */
|
|
79
82
|
snapshot: (s: TaskSnapshot, mode: ContinuityMode) => number;
|
|
@@ -10,7 +10,7 @@ import { selectBySearch } from './context-search.js';
|
|
|
10
10
|
import { strengthenOf } from '../recall/finish.js';
|
|
11
11
|
import { keepShownIds } from '../recall/last-recalled.js';
|
|
12
12
|
import { NO_QUERY, sourceOf, globalSource, planContext, promptRecallRequest, openBlockBudget, } from './context-plan.js';
|
|
13
|
-
import { ambientAdmission, loadPools } from './context-pools.js';
|
|
13
|
+
import { ambientAdmission, loadPools, userRuleReserve } from './context-pools.js';
|
|
14
14
|
import { loadTaskSections, pointerModes } from './context-task-state.js';
|
|
15
15
|
/** Tokens a context block may use when the caller sets no budget; the hook command and the CLI
|
|
16
16
|
* default match it. */
|
|
@@ -39,11 +39,12 @@ export async function assembleContext(ctx, opts) {
|
|
|
39
39
|
const noSections = !sections.shownSnapshot && !sections.shownHandoff && sections.shownEvents.length === 0;
|
|
40
40
|
if (nothingToInject(plan, pools, noSections))
|
|
41
41
|
return { entries: [], tokens: 0 };
|
|
42
|
+
const left = Math.max(0, sections.left - userRuleReserve(plan, pools));
|
|
42
43
|
const picked = plan.pinnedOnly
|
|
43
|
-
? selectPinned({ opts, plan, left
|
|
44
|
+
? selectPinned({ opts, plan, left, pools, admission })
|
|
44
45
|
: plan.query === NO_QUERY
|
|
45
|
-
? selectStrongest(plan,
|
|
46
|
-
: await selectBySearch(ctx, { plan, left
|
|
46
|
+
? selectStrongest(plan, left, pools)
|
|
47
|
+
: await selectBySearch(ctx, { plan, left, pools, admission });
|
|
47
48
|
if (picked === null)
|
|
48
49
|
return { entries: [], tokens: 0 };
|
|
49
50
|
const { items, tokens } = finalizeSelection(picked, plan);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { USER_RULE_TAG, type MemoryEntry } from '../../base/memory/entry.js';
|
|
2
|
+
import { type ProjectRef } from '../../base/scope/project-identity.js';
|
|
3
|
+
export { USER_RULE_TAG };
|
|
4
|
+
/** Who reads the block, and where the row lives: a row's origin is the project id capture stamped,
|
|
5
|
+
* so it can be any name the project had; '' is no project. */
|
|
6
|
+
export interface UserRuleViewer {
|
|
7
|
+
readonly tenantId: string;
|
|
8
|
+
readonly project: ProjectRef;
|
|
9
|
+
readonly isGlobal: boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare function isUserRule(e: MemoryEntry, viewer: UserRuleViewer): boolean;
|
|
12
|
+
//# sourceMappingURL=user-rule.d.ts.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Which rows print as the person's own rules: only capture sets the tag, so a row nobody typed
|
|
2
|
+
// cannot pass for one.
|
|
3
|
+
import { USER_RULE_TAG } from '../../base/memory/entry.js';
|
|
4
|
+
import { projectId, projectNames } from '../../base/scope/project-identity.js';
|
|
5
|
+
export { USER_RULE_TAG };
|
|
6
|
+
export function isUserRule(e, viewer) {
|
|
7
|
+
const own = e.pinned &&
|
|
8
|
+
e.source === 'capture' &&
|
|
9
|
+
e.confidence === 'observed' &&
|
|
10
|
+
e.tags.includes(USER_RULE_TAG) &&
|
|
11
|
+
e.supersededBy === null &&
|
|
12
|
+
e.scope === null &&
|
|
13
|
+
e.tenantId === viewer.tenantId;
|
|
14
|
+
if (!own)
|
|
15
|
+
return false;
|
|
16
|
+
// A project store's rows are that project's; capture leaves their origin unset (session-end.ts).
|
|
17
|
+
const origin = e.originProject ?? null;
|
|
18
|
+
const names = projectId(viewer.project) === '' ? [] : projectNames(viewer.project);
|
|
19
|
+
if (!viewer.isGlobal)
|
|
20
|
+
return origin === null || names.includes(origin);
|
|
21
|
+
// A global row is a rule only in the project capture stamped on it; a null origin matches none.
|
|
22
|
+
return origin !== null && names.includes(origin);
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=user-rule.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { MemoryEntry } from '../../base/memory/entry.js';
|
|
2
|
+
import type { Context } from '../types.js';
|
|
3
|
+
import type { ContextOptions } from './context-types.js';
|
|
4
|
+
/** What a user-rules read needs to know of its caller. */
|
|
5
|
+
export type UserRulesOptions = Pick<ContextOptions, 'currentProject' | 'currentSessionId'>;
|
|
6
|
+
/** The tenant's user rules for the current project from the project store and the global store,
|
|
7
|
+
* oldest first, each id once; empty when pinned injection is off. Skips the budgeted selection, so
|
|
8
|
+
* a long list is never cut. */
|
|
9
|
+
export declare function userRulesGet(ctx: Context, opts: UserRulesOptions): Promise<MemoryEntry[]>;
|
|
10
|
+
//# sourceMappingURL=user-rules-get.d.ts.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { compareEntryIdentity } from '../../base/rank/compare.js';
|
|
2
|
+
import { planContext, sourceOf } from './context-plan.js';
|
|
3
|
+
import { ambientAdmission, loadPools } from './context-pools.js';
|
|
4
|
+
/** The tenant's user rules for the current project from the project store and the global store,
|
|
5
|
+
* oldest first, each id once; empty when pinned injection is off. Skips the budgeted selection, so
|
|
6
|
+
* a long list is never cut. */
|
|
7
|
+
export async function userRulesGet(ctx, opts) {
|
|
8
|
+
if (!ctx.config.pinnedInject.enabled)
|
|
9
|
+
return [];
|
|
10
|
+
const pinned = { ...opts, pinnedOnly: true, includeRecent: 0 };
|
|
11
|
+
const plan = planContext(ctx, pinned, sourceOf(ctx.store));
|
|
12
|
+
const admission = ambientAdmission(pinned, plan, null);
|
|
13
|
+
const pools = await loadPools(ctx, { plan, admission, recallRequest: undefined, left: 0 });
|
|
14
|
+
const rules = new Map();
|
|
15
|
+
const keep = (rows, isGlobal) => {
|
|
16
|
+
for (const e of rows) {
|
|
17
|
+
if (plan.isUserRule(e, isGlobal) && !rules.has(e.id))
|
|
18
|
+
rules.set(e.id, e);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
keep(pools.local.entries, plan.primaryIsGlobal);
|
|
22
|
+
keep(pools.global.entries, true);
|
|
23
|
+
return [...rules.values()].sort((a, b) => Date.parse(a.created) - Date.parse(b.created) || compareEntryIdentity(a, b));
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=user-rules-get.js.map
|
package/dist/api/index.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ export { auditList, auditMemoryQuality, computeCutoff, auditPrune, auditRemoveEr
|
|
|
35
35
|
export type { AuditListOptions, AuditPass, PruneAuditOptions, PruneAuditResult, } from './auth/audit.js';
|
|
36
36
|
export type { ContextCost, ContextOptions, ContextResult, ContextResultEntry, ContinuityMode, } from './context/context-types.js';
|
|
37
37
|
export { DEFAULT_CONTEXT_BUDGET, contextGet } from './context/context.js';
|
|
38
|
+
export { userRulesGet, type UserRulesOptions } from './context/user-rules-get.js';
|
|
38
39
|
export { NO_QUERY } from './context/context-plan.js';
|
|
39
40
|
export { contextProjectFor, type ProjectFacts } from './context/context-project.js';
|
|
40
41
|
export { failureSummary, recordTokens, tokenSummary } from './tokens.js';
|
package/dist/api/index.js
CHANGED
|
@@ -24,6 +24,7 @@ export { rawArchive, rawArchiveForEvent, promote, supersede } from './memories/p
|
|
|
24
24
|
export { DEFAULT_KEY_TTL_DAYS, MAX_TTL_DAYS, authCreate, authCreateSelf, authGrant, authKeyTenant, authListAllTenants, authListRows, authRevoke, authUngrant, } from './auth/auth.js';
|
|
25
25
|
export { auditList, auditMemoryQuality, computeCutoff, auditPrune, auditRemoveErrors, memoryQualityRepair, memoryQualityRepairOnce, } from './auth/audit.js';
|
|
26
26
|
export { DEFAULT_CONTEXT_BUDGET, contextGet } from './context/context.js';
|
|
27
|
+
export { userRulesGet } from './context/user-rules-get.js';
|
|
27
28
|
export { NO_QUERY } from './context/context-plan.js';
|
|
28
29
|
export { contextProjectFor } from './context/context-project.js';
|
|
29
30
|
export { failureSummary, recordTokens, tokenSummary } from './tokens.js';
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// instruction check.
|
|
3
3
|
import { detectInstruction, INSTRUCTION_LIKE_TAG, UNTRUSTED_ORIGIN_TAG, } from '../instruction-detect.js';
|
|
4
4
|
import { quarantineScopeFor } from '../../domain/trust/quarantine.js';
|
|
5
|
-
import { createMemory, } from '../../base/memory/entry.js';
|
|
5
|
+
import { createMemory, withoutUserTag, } from '../../base/memory/entry.js';
|
|
6
6
|
import { computeSalience } from '../../base/memory/salience.js';
|
|
7
7
|
import { vetSecrets } from '../../base/util/secret-detect.js';
|
|
8
8
|
import { assertCallerProject } from '../../base/scope/project-identity.js';
|
|
@@ -55,7 +55,7 @@ function prepareRemember(ctx, opts, untrusted) {
|
|
|
55
55
|
? detectInstruction(vetted.content)
|
|
56
56
|
: { flagged: false, reason: null };
|
|
57
57
|
const flagged = !untrusted && memberShares(ctx, opts) && detectInstruction(vetted.content).flagged;
|
|
58
|
-
const tags = trustTagged(opts.tags, untrusted, flagged);
|
|
58
|
+
const tags = trustTagged(opts.tags && withoutUserTag(opts.tags), untrusted, flagged);
|
|
59
59
|
const local = opts.local ?? {};
|
|
60
60
|
const created = createMemory(vetted.content, {
|
|
61
61
|
layer: local.layer,
|
|
@@ -7,10 +7,14 @@ import { type JsonValue } from '../base/util/json.js';
|
|
|
7
7
|
import { type LedgerReach } from './ledger-db.js';
|
|
8
8
|
import type { MemoryEntry } from '../base/memory/entry.js';
|
|
9
9
|
import type { PilotArm } from '../base/session/pilot-arm.js';
|
|
10
|
+
import { type ProjectRef } from '../base/scope/project-identity.js';
|
|
10
11
|
/** What one render needs once api.contextGet has answered. */
|
|
11
12
|
export interface ContextView {
|
|
12
13
|
readonly config: HippoConfig;
|
|
13
14
|
readonly tenantId: string;
|
|
15
|
+
/** The reader's project, with every name capture may have stamped its rows with; a user rule
|
|
16
|
+
* belongs to this project alone. */
|
|
17
|
+
readonly project: ProjectRef;
|
|
14
18
|
readonly ledgerSessionId: string | undefined;
|
|
15
19
|
readonly payloadSessionId: string | undefined;
|
|
16
20
|
readonly pinnedOnly: boolean;
|
|
@@ -47,6 +51,13 @@ export declare function toRenderItems(entries: ContextResultEntry[]): RenderItem
|
|
|
47
51
|
/** The hook format's stdout, '' when nothing is sent: a skippable static block (snapshot,
|
|
48
52
|
* handoff, events, pins, recent-N) and a never-skipped recall block. */
|
|
49
53
|
export declare function additionalContextOutput(view: ContextView): Promise<string>;
|
|
54
|
+
/** The rows that print as the person's own rules, and the rest: a rule prints once, in its own
|
|
55
|
+
* section. */
|
|
56
|
+
export interface UserRuleSplit {
|
|
57
|
+
readonly userRules: MemoryEntry[];
|
|
58
|
+
readonly others: ContextResultEntry[];
|
|
59
|
+
}
|
|
60
|
+
export declare function splitUserRules(view: Pick<ContextView, 'tenantId' | 'project' | 'result'>): UserRuleSplit;
|
|
50
61
|
/**
|
|
51
62
|
* The project a hook caller runs in: its id, the folder name its older rows carry, and any other
|
|
52
63
|
* names it resolves to.
|
package/dist/api/prompt-hook.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { assembleContext } from './context/context.js';
|
|
2
2
|
import { sharedStoreOf, strengthOf } from './types.js';
|
|
3
3
|
import { BadRequestError } from '../base/errors/api-errors.js';
|
|
4
|
-
import { contextBlockLines, contextCost, crossProjectLines, handoffSectionText, sessionTrailText, settleTokens, snapshotSectionText, } from './context/context-render.js';
|
|
4
|
+
import { contextBlockLines, contextCost, crossProjectLines, handoffSectionText, sessionTrailText, settleTokens, snapshotSectionText, userRuleLines, } from './context/context-render.js';
|
|
5
|
+
import { isUserRule } from './context/user-rule.js';
|
|
5
6
|
import { MAX_ID_LEN } from '../base/util/limits.js';
|
|
6
7
|
import { isJsonString } from '../base/util/json.js';
|
|
7
8
|
import { bookLedgerTurn, bookLedgerTurnPerRow, ledgerLastSent, ledgerReachOf, takeDelivery, } from './ledger-db.js';
|
|
8
9
|
import { sessionPilotArm } from './pilot-arm.js';
|
|
9
|
-
import { assertCallerProject, MAX_PROJECT_ALIASES } from '../base/scope/project-identity.js';
|
|
10
|
+
import { assertCallerProject, MAX_PROJECT_ALIASES, } from '../base/scope/project-identity.js';
|
|
10
11
|
import { shouldSkipUnchanged } from '../base/session/skip-unchanged.js';
|
|
11
12
|
import { hookPayloadString, isSubagentPayload } from '../base/util/hook-payload.js';
|
|
12
13
|
import { blockHash, estimateTokens } from '../base/util/token-text.js';
|
|
@@ -44,9 +45,10 @@ export function toRenderItems(entries) {
|
|
|
44
45
|
export async function additionalContextOutput(view) {
|
|
45
46
|
return (await renderAdditionalContext(view)).stdout;
|
|
46
47
|
}
|
|
47
|
-
function renderStaticBlock(view, staticItems, staticCrossEntries) {
|
|
48
|
+
function renderStaticBlock(view, userRules, staticItems, staticCrossEntries) {
|
|
48
49
|
const { result, framing } = view;
|
|
49
50
|
return settleTokens((t) => [
|
|
51
|
+
...userRuleLines(userRules),
|
|
50
52
|
...(result.activeSnapshot
|
|
51
53
|
? [snapshotSectionText(result.activeSnapshot, result.snapshotMode ?? 'full')]
|
|
52
54
|
: []),
|
|
@@ -73,28 +75,41 @@ function renderRecallBlock(recallItems, framing, now) {
|
|
|
73
75
|
heading: 'Prompt-Relevant Memory',
|
|
74
76
|
}).join('\n'));
|
|
75
77
|
}
|
|
78
|
+
export function splitUserRules(view) {
|
|
79
|
+
const isRule = (r) => isUserRule(r.entry, {
|
|
80
|
+
tenantId: view.tenantId,
|
|
81
|
+
project: view.project,
|
|
82
|
+
isGlobal: r.isGlobal ?? false,
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
userRules: view.result.entries.filter(isRule).map((r) => r.entry),
|
|
86
|
+
others: view.result.entries.filter((r) => !isRule(r)),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
76
89
|
function renderBlocks(view) {
|
|
77
|
-
const {
|
|
78
|
-
const
|
|
79
|
-
const
|
|
90
|
+
const { framing } = view;
|
|
91
|
+
const { userRules, others } = splitUserRules(view);
|
|
92
|
+
const staticEntries = others.filter((r) => r.category !== 'cross-project' && !r.promptRecall);
|
|
93
|
+
const staticCrossEntries = others.filter((r) => r.category === 'cross-project' && !r.promptRecall);
|
|
80
94
|
const staticItems = toRenderItems(staticEntries);
|
|
81
|
-
const recallItems = toRenderItems(
|
|
95
|
+
const recallItems = toRenderItems(others.filter((r) => r.promptRecall));
|
|
82
96
|
return {
|
|
97
|
+
userRules,
|
|
83
98
|
staticItems,
|
|
84
99
|
recallItems,
|
|
85
|
-
staticBlock: renderStaticBlock(view, staticItems, staticCrossEntries),
|
|
100
|
+
staticBlock: renderStaticBlock(view, userRules, staticItems, staticCrossEntries),
|
|
86
101
|
recallBlock: renderRecallBlock(recallItems, framing, view.now),
|
|
87
102
|
};
|
|
88
103
|
}
|
|
89
104
|
async function renderAdditionalContext(view) {
|
|
90
105
|
const { rec } = view;
|
|
91
|
-
const { staticItems, recallItems, staticBlock, recallBlock } = renderBlocks(view);
|
|
106
|
+
const { userRules, staticItems, recallItems, staticBlock, recallBlock } = renderBlocks(view);
|
|
92
107
|
if (!staticBlock.trim() && !recallBlock.trim()) {
|
|
93
108
|
rec?.delivered({ state: 'empty' });
|
|
94
109
|
return NOTHING_RENDERED;
|
|
95
110
|
}
|
|
96
111
|
const surface = view.pinnedOnly ? 'hook' : 'context';
|
|
97
|
-
const staticCount = staticItems.length;
|
|
112
|
+
const staticCount = userRules.length + staticItems.length;
|
|
98
113
|
const sendStatic = staticBlock.trim().length > 0 &&
|
|
99
114
|
!(await skipUnchangedStatic({ view, surface, staticBlock, recallBlock, staticCount }));
|
|
100
115
|
const finalStatic = sendStatic ? staticBlock : '';
|
|
@@ -231,6 +246,7 @@ export async function buildPromptHookContext(ctx, req, opts = {}) {
|
|
|
231
246
|
? await renderAdditionalContext({
|
|
232
247
|
config: ctx.config,
|
|
233
248
|
tenantId: ctx.tenantId,
|
|
249
|
+
project: req.project,
|
|
234
250
|
ledgerSessionId,
|
|
235
251
|
payloadSessionId: ledgerSessionId,
|
|
236
252
|
pinnedOnly: true,
|
|
@@ -67,7 +67,7 @@ export interface SessionEndWork<Turn, Scan extends {
|
|
|
67
67
|
currentProject: () => ProjectRef;
|
|
68
68
|
/** Captures `turns`, or the whole transcript when undefined, into `into`; false when it
|
|
69
69
|
* failed, having said why. */
|
|
70
|
-
capture: (into: Context, turns: readonly Turn[] | undefined, originProject: ProjectRef | undefined) => Promise<boolean>;
|
|
70
|
+
capture: (into: Context, turns: readonly Turn[] | undefined, originProject: ProjectRef | undefined, fromStart: boolean) => Promise<boolean>;
|
|
71
71
|
digest: (scan: Scan | null, key: string, log: LineLog) => Promise<void>;
|
|
72
72
|
workingState: (log: LineLog) => ReturnType<SessionClose['workingState']>;
|
|
73
73
|
evidence: () => HandoffEvidence;
|
package/dist/api/session-end.js
CHANGED
|
@@ -197,7 +197,7 @@ async function sleepStep(ctx, w) {
|
|
|
197
197
|
/** Captures the session into `into`; a reply's close takes only the turns after the session's
|
|
198
198
|
* cursor, then moves it, so each reply is extracted once. */
|
|
199
199
|
async function captureStep(ctx, into, scan, w) {
|
|
200
|
-
const capture = async (turns) => {
|
|
200
|
+
const capture = async (turns, fromStart = true) => {
|
|
201
201
|
// With no transcript of its own, capture would read this as a manual run and scan every
|
|
202
202
|
// project.
|
|
203
203
|
if (!w.transcriptPath) {
|
|
@@ -205,7 +205,7 @@ async function captureStep(ctx, into, scan, w) {
|
|
|
205
205
|
return false;
|
|
206
206
|
}
|
|
207
207
|
// In the global store, rows would otherwise read as user-global and show up in every project.
|
|
208
|
-
return w.capture(into, turns, hasOwnStore(ctx) ? undefined : w.currentProject());
|
|
208
|
+
return w.capture(into, turns, hasOwnStore(ctx) ? undefined : w.currentProject(), fromStart);
|
|
209
209
|
};
|
|
210
210
|
if (w.mode !== 'turn') {
|
|
211
211
|
await capture(scan?.turns);
|
|
@@ -220,7 +220,9 @@ async function captureStep(ctx, into, scan, w) {
|
|
|
220
220
|
w.log('skip capture: no new turns since the last reply');
|
|
221
221
|
return;
|
|
222
222
|
}
|
|
223
|
-
|
|
223
|
+
// A slice that starts after the first turn holds only replies to the agent.
|
|
224
|
+
const fromStart = fresh.length === scan.turns.length;
|
|
225
|
+
if (await capture(fresh, fromStart))
|
|
224
226
|
w.cursor.save(w.sessionId, w.transcriptPath, scan.turns);
|
|
225
227
|
}
|
|
226
228
|
/** Books re-reads, sleeps, captures, digests and closes one ended session of the folder `ctx`
|
|
@@ -78,6 +78,11 @@ export declare const ERROR_TAG = "error";
|
|
|
78
78
|
export declare const EXTRACTED_TAG = "extracted";
|
|
79
79
|
export declare const COMPACTION_MEMORY_TAG = "compaction-memory";
|
|
80
80
|
export declare const COMPACTION_SOURCE_PREFIX = "compaction:";
|
|
81
|
+
/** Tag on a rule the person stated, which only capture may set. */
|
|
82
|
+
export declare const USER_RULE_TAG = "from-user";
|
|
83
|
+
/** `tags` without the user-rule tag, for every tag a person types: a typed tag must not make a row
|
|
84
|
+
* print as the person's own rule. */
|
|
85
|
+
export declare function withoutUserTag(tags: readonly string[]): string[];
|
|
81
86
|
/** A memory counts as high schema fit strictly above this. */
|
|
82
87
|
export declare const HIGH_SCHEMA_FIT = 0.7;
|
|
83
88
|
/** The base half-life scaled by the PLAN.md signals: an error tag, and high or low schema fit. */
|
|
@@ -26,6 +26,13 @@ export const ERROR_TAG = 'error';
|
|
|
26
26
|
export const EXTRACTED_TAG = 'extracted';
|
|
27
27
|
export const COMPACTION_MEMORY_TAG = 'compaction-memory';
|
|
28
28
|
export const COMPACTION_SOURCE_PREFIX = 'compaction:';
|
|
29
|
+
/** Tag on a rule the person stated, which only capture may set. */
|
|
30
|
+
export const USER_RULE_TAG = 'from-user';
|
|
31
|
+
/** `tags` without the user-rule tag, for every tag a person types: a typed tag must not make a row
|
|
32
|
+
* print as the person's own rule. */
|
|
33
|
+
export function withoutUserTag(tags) {
|
|
34
|
+
return tags.filter((t) => t !== USER_RULE_TAG);
|
|
35
|
+
}
|
|
29
36
|
/** A memory counts as high schema fit strictly above this. */
|
|
30
37
|
export const HIGH_SCHEMA_FIT = 0.7;
|
|
31
38
|
const HIGH_FIT_HALF_LIFE_FACTOR = 1.5;
|
|
@@ -125,7 +132,7 @@ function assertValidMemoryInput(content, options) {
|
|
|
125
132
|
export function createSuccessor(old, content, opts, now) {
|
|
126
133
|
const fields = {
|
|
127
134
|
layer: opts.layer ?? old.layer,
|
|
128
|
-
tags: opts.tags ??
|
|
135
|
+
tags: withoutUserTag(opts.tags ?? old.tags),
|
|
129
136
|
pinned: opts.pinned ?? old.pinned,
|
|
130
137
|
source: old.source,
|
|
131
138
|
confidence: 'verified',
|
|
@@ -36,10 +36,10 @@ export interface LedgerTurn {
|
|
|
36
36
|
/** Written after the rows, whatever became of them. */
|
|
37
37
|
readonly delivery?: DeliveryEventInput;
|
|
38
38
|
}
|
|
39
|
-
/** Where a block was sent: `hook`/`hook_recall` (per-prompt hook), `compact_resume`,
|
|
39
|
+
/** Where a block was sent: `hook`/`hook_recall` (per-prompt hook), `compact_resume`, `session_start`,
|
|
40
40
|
* `context`/`recall` (CLI), `mcp_*`, `http_*`, and `pilot` (session pilot arm row,
|
|
41
41
|
* src/api/pilot-arm.ts; not a send, so in no surface list). */
|
|
42
|
-
export type TokenSurface = 'hook' | 'hook_recall' | 'compact_resume' | 'context' | 'recall' | 'mcp_recall' | 'mcp_context' | 'http_recall' | 'http_context' | 'http_assemble' | 'pilot';
|
|
42
|
+
export type TokenSurface = 'hook' | 'hook_recall' | 'compact_resume' | 'session_start' | 'context' | 'recall' | 'mcp_recall' | 'mcp_context' | 'http_recall' | 'http_context' | 'http_assemble' | 'pilot';
|
|
43
43
|
/** What happened to a block: `inject` (sent), `skip` (identical to the last injected block),
|
|
44
44
|
* `reset` (host compacted, next must send), `reread` (tokens later calls read again, booked at
|
|
45
45
|
* session end), `arm` (pilot assignment; `block_hash` is `hippo` or `holdout`, `items` the
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Single source of truth for the package version, written by scripts/sync-version.mjs; never
|
|
3
3
|
* edit by hand. Read by the db rollback guard, /health, MCP. A constant, not a runtime
|
|
4
4
|
* package.json read: the published bundle may lack package.json on a path ESM can resolve. */
|
|
5
|
-
export declare const PACKAGE_VERSION = "3.
|
|
5
|
+
export declare const PACKAGE_VERSION = "3.2.0";
|
|
6
6
|
/** The floor a store takes on its first expiring key: the first release with schema v53, set by
|
|
7
7
|
* hand in that release; scripts/checks/check-expiring-keys-floor.mjs gates it. */
|
|
8
8
|
export declare const EXPIRING_KEYS_MIN_BINARY = "1.64.0";
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Single source of truth for the package version, written by scripts/sync-version.mjs; never
|
|
3
3
|
* edit by hand. Read by the db rollback guard, /health, MCP. A constant, not a runtime
|
|
4
4
|
* package.json read: the published bundle may lack package.json on a path ESM can resolve. */
|
|
5
|
-
export const PACKAGE_VERSION = '3.
|
|
5
|
+
export const PACKAGE_VERSION = '3.2.0';
|
|
6
6
|
/** The floor a store takes on its first expiring key: the first release with schema v53, set by
|
|
7
7
|
* hand in that release; scripts/checks/check-expiring-keys-floor.mjs gates it. */
|
|
8
8
|
export const EXPIRING_KEYS_MIN_BINARY = '1.64.0';
|
|
@@ -14,6 +14,7 @@ const TOKEN_SURFACES = [
|
|
|
14
14
|
'hook',
|
|
15
15
|
'hook_recall',
|
|
16
16
|
'compact_resume',
|
|
17
|
+
'session_start',
|
|
17
18
|
'context',
|
|
18
19
|
'recall',
|
|
19
20
|
'mcp_recall',
|
|
@@ -24,7 +25,12 @@ const TOKEN_SURFACES = [
|
|
|
24
25
|
];
|
|
25
26
|
/** Surfaces whose re-reads are counted: only a hook payload tells a sub-agent's block from its
|
|
26
27
|
* parent's, as both carry one session id. */
|
|
27
|
-
const REREAD_SURFACES = [
|
|
28
|
+
const REREAD_SURFACES = [
|
|
29
|
+
'hook',
|
|
30
|
+
'hook_recall',
|
|
31
|
+
'compact_resume',
|
|
32
|
+
'session_start',
|
|
33
|
+
];
|
|
28
34
|
/** Rows older than this are pruned on write. */
|
|
29
35
|
const TOKEN_LEDGER_RETENTION_DAYS = 90;
|
|
30
36
|
/** The stamp a row written at `ts` prunes before: {@link TOKEN_LEDGER_RETENTION_DAYS} earlier. */
|
|
@@ -17,6 +17,9 @@ export interface CaptureOptions {
|
|
|
17
17
|
stdinText?: string;
|
|
18
18
|
stdinTimedOut?: boolean;
|
|
19
19
|
sessionTurns?: readonly SessionTurn[];
|
|
20
|
+
/** False when `sessionTurns` is a later slice of the session (a turn capture), so its first user
|
|
21
|
+
* turn answers the agent. */
|
|
22
|
+
fromStart?: boolean;
|
|
20
23
|
/** Tee stdout/stderr to this log file while capture runs, so SessionEnd output (lost in TUI teardown) shows via
|
|
21
24
|
* `hippo last-sleep`.
|
|
22
25
|
* Appends, because `hippo sleep` writes the same file first. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
2
|
import * as path from 'node:path';
|
|
3
|
-
import { createMemory, Layer } from '../../base/memory/entry.js';
|
|
3
|
+
import { createMemory, Layer, USER_RULE_TAG } from '../../base/memory/entry.js';
|
|
4
4
|
import { duplicateKey, storedTextKeys } from '../../base/util/same-text.js';
|
|
5
5
|
import { isCertainReason, storedDefect } from '../../base/memory/memory-quality.js';
|
|
6
6
|
import { maskEmails, redactSecretsStrict } from '../../base/util/secret-detect.js';
|
|
@@ -67,7 +67,7 @@ async function runCaptureCore(target, options) {
|
|
|
67
67
|
const read = readCaptureTexts(options);
|
|
68
68
|
if (read === null)
|
|
69
69
|
return;
|
|
70
|
-
const { texts, userTexts } = read;
|
|
70
|
+
const { texts, userTexts, firstFollowUp } = read;
|
|
71
71
|
if (texts.every((text) => text.trim().length === 0)) {
|
|
72
72
|
console.log('No text to capture from.');
|
|
73
73
|
return;
|
|
@@ -76,7 +76,7 @@ async function runCaptureCore(target, options) {
|
|
|
76
76
|
// pass could not see (AGENTS.md: no secrets in memories).
|
|
77
77
|
const scrub = (text) => maskEmails(redactSecretsStrict(text));
|
|
78
78
|
const scrubbed = texts.map(scrub);
|
|
79
|
-
const extracted = scrubbedItems(extractFromTexts(scrubbed, userTexts), scrub);
|
|
79
|
+
const extracted = scrubbedItems(extractFromTexts(scrubbed, userTexts, firstFollowUp), scrub);
|
|
80
80
|
if (extracted.length === 0) {
|
|
81
81
|
console.log('No actionable items found in the input.');
|
|
82
82
|
return;
|
|
@@ -149,9 +149,6 @@ function printCaptureTally(options, { captured, skipped, rejected }) {
|
|
|
149
149
|
(rejected > 0 ? `, ${rejected} rejected` : '') +
|
|
150
150
|
')');
|
|
151
151
|
}
|
|
152
|
-
/** The raw texts for the chosen source, one per session turn, the person's turns first; null after printing why a
|
|
153
|
-
* last-session capture has nothing.
|
|
154
|
-
* Only a session says who spoke, so a piped or file capture counts no user texts. */
|
|
155
152
|
function readCaptureTexts(options) {
|
|
156
153
|
switch (options.source) {
|
|
157
154
|
case 'stdin': {
|
|
@@ -199,7 +196,10 @@ function readSessionTexts(options) {
|
|
|
199
196
|
console.log('Transcript had no user/assistant messages to summarise.');
|
|
200
197
|
return null;
|
|
201
198
|
}
|
|
202
|
-
|
|
199
|
+
// The first user turn is the request; a tail that cut it off, or a later slice, holds only replies.
|
|
200
|
+
const allUsers = turns.filter((t) => t.role === 'user').length;
|
|
201
|
+
const opener = options.fromStart !== false && users.length === allUsers ? 1 : 0;
|
|
202
|
+
return { texts: [...users, ...assistants], userTexts: users.length, firstFollowUp: opener };
|
|
203
203
|
}
|
|
204
204
|
/** One entry per new text: building can throw, so a held text or a repeat within the batch is
|
|
205
205
|
* never built. */
|
|
@@ -271,13 +271,14 @@ function captureEntry(item, options, baseHalfLifeDays) {
|
|
|
271
271
|
// The write tenant must match the dedup read's, or scoped dedup passes and the row lands in
|
|
272
272
|
// 'default'. A rule the person stated is pinned, so it injects even when a later prompt shares
|
|
273
273
|
// none of its words. SHORTCUT: every stated rule pins; cap or age these pins if a store's pins
|
|
274
|
-
// outgrow the hook budget.
|
|
274
|
+
// outgrow the hook budget. The from-user tag marks the same pin as the person's rule for the hooks.
|
|
275
|
+
const stated = item.fromUser === true && item.category === 'rule';
|
|
275
276
|
const created = createMemory(item.content, {
|
|
276
277
|
layer: Layer.Episodic,
|
|
277
|
-
tags: item.tags,
|
|
278
|
+
tags: stated ? [...item.tags, USER_RULE_TAG] : item.tags,
|
|
278
279
|
source: 'capture',
|
|
279
280
|
confidence: 'observed',
|
|
280
|
-
pinned:
|
|
281
|
+
pinned: stated,
|
|
281
282
|
tenantId: options.tenantId,
|
|
282
283
|
sourceSessionId: options.sessionId,
|
|
283
284
|
baseHalfLifeDays,
|
|
@@ -6,8 +6,9 @@ export interface ExtractedItem {
|
|
|
6
6
|
fromUser?: boolean;
|
|
7
7
|
}
|
|
8
8
|
/** Captures complete supported statements, each text parsed alone so a fence or heading in one never reaches the next.
|
|
9
|
-
* The first `userTexts` texts are a person's own words; on a repeat their copy wins, so it keeps `fromUser`.
|
|
10
|
-
|
|
9
|
+
* The first `userTexts` texts are a person's own words; on a repeat their copy wins, so it keeps `fromUser`.
|
|
10
|
+
* From `firstFollowUp` on, those words answer the agent's work, so a statement in them can be the person's rule. */
|
|
11
|
+
export declare function extractFromTexts(texts: readonly string[], userTexts?: number, firstFollowUp?: number): ExtractedItem[];
|
|
11
12
|
/** A text an older capture, which kept every bold marker, stored for a line, and what capture
|
|
12
13
|
* extracts from that line now. */
|
|
13
14
|
export interface BoldTwin {
|
|
@@ -279,8 +279,55 @@ function extractSpecSections(prose, cuts) {
|
|
|
279
279
|
to,
|
|
280
280
|
}));
|
|
281
281
|
}
|
|
282
|
+
// A reply to the agent's work states how the person wants it done, rule word or not.
|
|
283
|
+
const ANY_STATEMENT = [/\S/];
|
|
284
|
+
// A kept reply names code or limits a choice; a thanks or a pasted test count does neither.
|
|
285
|
+
const CODE_CUE = /`|\w[\\/]\w|\w\.[A-Za-z]|\w_\w|\w\(|[<>{}[\]=]|(?:^|\s)--?[A-Za-z]/;
|
|
286
|
+
const LIMIT_CUE = /n't\b|\b(?:not|no longer|instead|rather|only|stop|unless|before|after|until|without|except)\b/i;
|
|
287
|
+
// Praise names code too ("Thanks, `src/cache.ts` looks good"); a thanks that goes on to direct is kept.
|
|
288
|
+
// SHORTCUT: word shapes, not meaning; the opt-in model capture is the upgrade path.
|
|
289
|
+
const ACK_LEAD = /^(?:thanks|thank you|ok(?:ay)?|great|nice|perfect|cool|lgtm)\b[\s,.!:-]*/i;
|
|
290
|
+
const NOT_A_DIRECTIVE = /^(?:for|on|to|so|the|a|an|this|that|it|its|you|your|i|we|all|really)\b/i;
|
|
291
|
+
const APPROVAL = /^(?:\S+\s+){0,3}(?:looks?|works?|worked)\s+(?:good|great|fine|right|now)\b/i;
|
|
292
|
+
// Pasted output opens on a file:line, a stack frame or an error word, or holds a file:line:col
|
|
293
|
+
// (a compiler arrow line) or an assertion message.
|
|
294
|
+
const LOG_CUE = new RegExp([
|
|
295
|
+
String.raw `^#\d+\s|^\S*\w\.[A-Za-z]+:\d+|\w\.[A-Za-z]+:\d+:\d+`,
|
|
296
|
+
String.raw `^(?:\w*Error|error(?:\[\w+\])?:|warning:|FAIL|Traceback)`,
|
|
297
|
+
String.raw `\bexpected\b.+\bto (?:be|equal|have)\b`,
|
|
298
|
+
].join('|'));
|
|
299
|
+
/** A thanks with no directive after it, or a short "X looks good". */
|
|
300
|
+
function isPraise(content) {
|
|
301
|
+
const lead = ACK_LEAD.exec(content);
|
|
302
|
+
const rest = lead ? content.slice(lead[0].length) : content;
|
|
303
|
+
if (APPROVAL.test(rest))
|
|
304
|
+
return true;
|
|
305
|
+
if (!lead)
|
|
306
|
+
return false;
|
|
307
|
+
return rest.split(/\s+/).filter(Boolean).length <= 3 || NOT_A_DIRECTIVE.test(rest);
|
|
308
|
+
}
|
|
309
|
+
/** A statement in a reply as the person's rule: 2 words when it names code, 4 with a limiting word. */
|
|
310
|
+
function followUpRule(sentence) {
|
|
311
|
+
const item = extractFromPatterns(sentence, ANY_STATEMENT, 'rule');
|
|
312
|
+
if (!item)
|
|
313
|
+
return null;
|
|
314
|
+
const { content } = item;
|
|
315
|
+
const limits = LIMIT_CUE.test(content);
|
|
316
|
+
if (LOG_CUE.test(content) || (isPraise(content) && !limits))
|
|
317
|
+
return null;
|
|
318
|
+
const words = content.split(/\s+/).length;
|
|
319
|
+
const kept = (words >= 2 && CODE_CUE.test(content)) || (words >= 4 && limits);
|
|
320
|
+
return kept ? { ...item, tags: [...item.tags, 'follow-up'] } : null;
|
|
321
|
+
}
|
|
322
|
+
/** What a sentence holds; in a reply a preference that names code or limits a choice is a rule. */
|
|
323
|
+
function sentenceItem(sentence, followUp) {
|
|
324
|
+
const hit = CATEGORIES.map(([category, patterns]) => extractFromPatterns(sentence, patterns, category)).find((found) => found !== null) ?? null;
|
|
325
|
+
if (!followUp || (hit !== null && hit.category !== 'preference'))
|
|
326
|
+
return hit;
|
|
327
|
+
return followUpRule(sentence) ?? hit;
|
|
328
|
+
}
|
|
282
329
|
// The items of the spec bullets first, then those of each prose block.
|
|
283
|
-
function extractSourced(text, cuts) {
|
|
330
|
+
function extractSourced(text, cuts, followUp = false) {
|
|
284
331
|
const prose = proseOnly(text);
|
|
285
332
|
const found = extractSpecSections(prose, cuts);
|
|
286
333
|
for (const block of proseBlocks(prose, cuts)) {
|
|
@@ -291,24 +338,22 @@ function extractSourced(text, cuts) {
|
|
|
291
338
|
continue;
|
|
292
339
|
if (cutByAside(sentence, at))
|
|
293
340
|
continue;
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
found.push({ item, from, to });
|
|
299
|
-
break;
|
|
300
|
-
}
|
|
341
|
+
const item = sentenceItem(sentence, followUp);
|
|
342
|
+
if (item) {
|
|
343
|
+
const [from, to] = block.sourceOf(at, at + sentence.length);
|
|
344
|
+
found.push({ item, from, to });
|
|
301
345
|
}
|
|
302
346
|
}
|
|
303
347
|
}
|
|
304
348
|
return found;
|
|
305
349
|
}
|
|
306
350
|
/** Captures complete supported statements, each text parsed alone so a fence or heading in one never reaches the next.
|
|
307
|
-
* The first `userTexts` texts are a person's own words; on a repeat their copy wins, so it keeps `fromUser`.
|
|
308
|
-
|
|
351
|
+
* The first `userTexts` texts are a person's own words; on a repeat their copy wins, so it keeps `fromUser`.
|
|
352
|
+
* From `firstFollowUp` on, those words answer the agent's work, so a statement in them can be the person's rule. */
|
|
353
|
+
export function extractFromTexts(texts, userTexts = 0, firstFollowUp = userTexts) {
|
|
309
354
|
const seen = new Set();
|
|
310
355
|
return texts
|
|
311
|
-
.flatMap((text, i) => extractSourced(text, boldPairs).map(({ item }) => i < userTexts ? { ...item, fromUser: true } : item))
|
|
356
|
+
.flatMap((text, i) => extractSourced(text, boldPairs, i >= firstFollowUp && i < userTexts).map(({ item }) => i < userTexts ? { ...item, fromUser: true } : item))
|
|
312
357
|
.filter((item) => {
|
|
313
358
|
const key = duplicateKey(item.content);
|
|
314
359
|
if (seen.has(key) || !assessAutomaticMemory(item.content).accepted)
|
|
@@ -12,12 +12,17 @@ const RECENT_ASSISTANT_TURNS = 10;
|
|
|
12
12
|
* Build a compact text summary from a Claude Code / OpenCode / Copilot JSONL transcript: plain
|
|
13
13
|
* user messages and the final assistant text chunk, without thinking, tool_use and tool_result
|
|
14
14
|
* noise. Exported for tests. */
|
|
15
|
-
/** Leading markers of the
|
|
15
|
+
/** Leading markers of the lines Claude Code writes with type 'user' that no person typed: commands,
|
|
16
|
+
* `!` shell input and output, task notices. */
|
|
16
17
|
const CLAUDE_CODE_COMMAND_PREFIXES = [
|
|
17
18
|
'<local-command-',
|
|
18
19
|
'<command-name>',
|
|
19
20
|
'<command-message>',
|
|
20
21
|
'<command-args>',
|
|
22
|
+
'<bash-input>',
|
|
23
|
+
'<bash-stdout>',
|
|
24
|
+
'<bash-stderr>',
|
|
25
|
+
'<task-notification>',
|
|
21
26
|
];
|
|
22
27
|
function isNonHumanUserLine(entry, content) {
|
|
23
28
|
if (entry.isMeta === true ||
|
|
@@ -1,3 +1,10 @@
|
|
|
1
1
|
import { type CommandContext } from './flag-values.js';
|
|
2
|
+
export interface ContextSession {
|
|
3
|
+
readonly currentSessionId: string | undefined;
|
|
4
|
+
readonly ledgerSessionId: string | undefined;
|
|
5
|
+
readonly payloadSessionId: string | undefined;
|
|
6
|
+
readonly prompt: string | undefined;
|
|
7
|
+
}
|
|
8
|
+
export declare function resolveContextSession(stdinText: string | undefined): ContextSession;
|
|
2
9
|
export declare function handleContext({ hippoRoot, tenantId, args, flags, }: CommandContext): Promise<void>;
|
|
3
10
|
//# sourceMappingURL=context.d.ts.map
|
|
@@ -12,8 +12,8 @@ import { DEFAULT_CONTEXT_BUDGET } from '../../api/context/context.js';
|
|
|
12
12
|
import { cliApiContext, cliHookRequest } from './api-context.js';
|
|
13
13
|
import { renderAmbientSummary } from '../../base/memory/ambient.js';
|
|
14
14
|
import { strengthOf } from '../../api/types.js';
|
|
15
|
-
import { contextBlockLines, contextCost, crossProjectLines, settleTokens, } from '../../api/context/context-render.js';
|
|
16
|
-
import { additionalContextOutput, hasContextData, sessionStartEnvelope, toRenderItems, } from '../../api/prompt-hook.js';
|
|
15
|
+
import { contextBlockLines, contextCost, crossProjectLines, settleTokens, userRuleLines, } from '../../api/context/context-render.js';
|
|
16
|
+
import { additionalContextOutput, hasContextData, sessionStartEnvelope, splitUserRules, toRenderItems, } from '../../api/prompt-hook.js';
|
|
17
17
|
import { flushDeliveryRecorder, startDeliveryRecorder, takeDelivery } from '../../api/ledger-db.js';
|
|
18
18
|
import { boolFlag, parseBudgetFlag, parseCountFlag, parseLimitFlag, stringFlagOrExit, } from './flag-values.js';
|
|
19
19
|
import { requireInit, workingFolder } from './shared.js';
|
|
@@ -92,18 +92,21 @@ async function renderContext(options) {
|
|
|
92
92
|
const framing = stringFlagOrExit(flags, 'framing') ?? 'observe';
|
|
93
93
|
const now = ctx.infra.clock();
|
|
94
94
|
const input = { query, budget, pinnedOnly, format, framing, session, rec, now };
|
|
95
|
-
const
|
|
95
|
+
const opts = buildContextOpts(flags, input, ctx);
|
|
96
|
+
const result = await api.contextGet(ctx, opts);
|
|
96
97
|
if (!hasContextData(result)) {
|
|
97
98
|
rec?.delivered({ state: 'empty' });
|
|
98
99
|
return;
|
|
99
100
|
}
|
|
100
101
|
const envelope = format === 'copilot' ? sessionStartEnvelope(stdinText) : undefined;
|
|
101
|
-
|
|
102
|
+
const view = contextView(ctx, input, result, envelope, opts.currentProject);
|
|
103
|
+
await renderContextView(view, format, query);
|
|
102
104
|
}
|
|
103
|
-
function contextView(ctx, input, result, envelope) {
|
|
105
|
+
function contextView(ctx, input, result, envelope, project) {
|
|
104
106
|
return {
|
|
105
107
|
config: ctx.config,
|
|
106
108
|
tenantId: ctx.tenantId,
|
|
109
|
+
project,
|
|
107
110
|
ledgerSessionId: input.session.ledgerSessionId,
|
|
108
111
|
payloadSessionId: input.session.payloadSessionId,
|
|
109
112
|
pinnedOnly: input.pinnedOnly,
|
|
@@ -133,7 +136,7 @@ async function renderContextView(view, format, query) {
|
|
|
133
136
|
await renderContextMarkdown(view);
|
|
134
137
|
}
|
|
135
138
|
}
|
|
136
|
-
function resolveContextSession(stdinText) {
|
|
139
|
+
export function resolveContextSession(stdinText) {
|
|
137
140
|
// The session id bounds the active-task-snapshot read: the stdin hook payload wins, then
|
|
138
141
|
// hostSessionId(); absent both, api.contextGet applies the pure freshness bound.
|
|
139
142
|
const payload = readHookPayload(stdinText);
|
|
@@ -220,11 +223,15 @@ async function renderContextJson(view, query) {
|
|
|
220
223
|
* ledger does. */
|
|
221
224
|
async function renderContextMarkdown(view) {
|
|
222
225
|
const { result, rec, framing } = view;
|
|
226
|
+
const { userRules, others } = splitUserRules(view);
|
|
223
227
|
// Cross-project inclusions get their own section so they never masquerade as project memory.
|
|
224
|
-
const renderItems = toRenderItems(
|
|
225
|
-
const crossEntries =
|
|
228
|
+
const renderItems = toRenderItems(others.filter((r) => r.category !== 'cross-project'));
|
|
229
|
+
const crossEntries = others.filter((r) => r.category === 'cross-project');
|
|
226
230
|
const text = settleTokens((t) => {
|
|
227
|
-
const lines =
|
|
231
|
+
const lines = [
|
|
232
|
+
...userRuleLines(userRules),
|
|
233
|
+
...continuityTexts(result.activeSnapshot, result.sessionHandoff, result.recentEvents, result),
|
|
234
|
+
];
|
|
228
235
|
if (renderItems.length > 0) {
|
|
229
236
|
lines.push(...contextBlockLines(renderItems, t, framing, { now: view.now, strength: view.strength }));
|
|
230
237
|
}
|
|
@@ -236,7 +243,7 @@ async function renderContextMarkdown(view) {
|
|
|
236
243
|
if (text.length > 0)
|
|
237
244
|
console.log(text);
|
|
238
245
|
rec?.delivered(text.length > 0 ? { state: 'sent', emittedText: `${text}\n` } : { state: 'empty' });
|
|
239
|
-
await bookContextInject(view, renderItems.length, estimateTokens(text));
|
|
246
|
+
await bookContextInject(view, userRules.length + renderItems.length, estimateTokens(text));
|
|
240
247
|
}
|
|
241
248
|
export async function handleContext({ hippoRoot, tenantId, args, flags, }) {
|
|
242
249
|
// Bounded, not a TTY guard: the hot stdin path and a manual run share this one command.
|
package/dist/surface/cli/hook.js
CHANGED
|
@@ -104,6 +104,9 @@ function printClaudeHookInstall(result) {
|
|
|
104
104
|
if (result.installedSessionStart) {
|
|
105
105
|
console.log(`Installed hippo last-sleep SessionStart hook in ${result.target} settings`);
|
|
106
106
|
}
|
|
107
|
+
if (result.installedSessionRules) {
|
|
108
|
+
console.log(`Installed hippo session-rules SessionStart hook in ${result.target} settings`);
|
|
109
|
+
}
|
|
107
110
|
if (result.installedUserPromptSubmit) {
|
|
108
111
|
console.log(`Installed hippo pinned-inject UserPromptSubmit hook in ${result.target} settings`);
|
|
109
112
|
}
|
|
@@ -39,11 +39,12 @@ function runSessionEndWork({ hippoRoot, tenantId, flags, mode, held, }) {
|
|
|
39
39
|
},
|
|
40
40
|
currentProject: () => ctx.infra.machine.projectIdentity(workingFolder(ctx)),
|
|
41
41
|
// The run writes to this folder's own store, else to the global one in its reach.
|
|
42
|
-
capture: async (into, turns, originProject) => {
|
|
42
|
+
capture: async (into, turns, originProject, fromStart) => {
|
|
43
43
|
const root = into === ctx ? hippoRoot : ctx.reach?.global?.root;
|
|
44
44
|
if (root === undefined)
|
|
45
45
|
return false;
|
|
46
|
-
|
|
46
|
+
const ended = { tenantId, flags, transcriptPath, turns, originProject, fromStart };
|
|
47
|
+
return captureEndedSession(root, ended);
|
|
47
48
|
},
|
|
48
49
|
digest: (scan, key, log) => recordSessionDigest(hippoRoot, ctx.store, scan, { key, tenantId, log, config: ctx.config }),
|
|
49
50
|
workingState: (log) => (transcriptPath ? transcriptWorkingState(transcriptPath, log) : null),
|
|
@@ -62,7 +63,7 @@ async function sleepFolderStore(hippoRoot, tenantId, flags, closeLogFile) {
|
|
|
62
63
|
}
|
|
63
64
|
}
|
|
64
65
|
/** True when capture ran to the end, so a turn close may move its cursor past these turns. */
|
|
65
|
-
async function captureEndedSession(store, { tenantId, flags, transcriptPath, turns, originProject }) {
|
|
66
|
+
async function captureEndedSession(store, { tenantId, flags, transcriptPath, turns, originProject, fromStart }) {
|
|
66
67
|
const logFile = stringFlag(flags, 'log-file') ?? null;
|
|
67
68
|
try {
|
|
68
69
|
await runCapture(captureTarget(store), {
|
|
@@ -74,6 +75,7 @@ async function captureEndedSession(store, { tenantId, flags, transcriptPath, tur
|
|
|
74
75
|
tenantId,
|
|
75
76
|
originProject,
|
|
76
77
|
sessionTurns: turns,
|
|
78
|
+
fromStart,
|
|
77
79
|
});
|
|
78
80
|
return true;
|
|
79
81
|
}
|
package/dist/surface/cli/init.js
CHANGED
|
@@ -331,6 +331,9 @@ function installClaudeCodeSettingsHooks(hook) {
|
|
|
331
331
|
if (result.installedSessionStart) {
|
|
332
332
|
console.log(` Auto-installed hippo last-sleep SessionStart hook in ${hook} settings`);
|
|
333
333
|
}
|
|
334
|
+
if (result.installedSessionRules) {
|
|
335
|
+
console.log(` Auto-installed hippo session-rules SessionStart hook in ${hook} settings`);
|
|
336
|
+
}
|
|
334
337
|
if (result.installedUserPromptSubmit) {
|
|
335
338
|
console.log(` Auto-installed hippo pinned-inject UserPromptSubmit hook in ${hook} settings`);
|
|
336
339
|
}
|
|
@@ -6,6 +6,7 @@ import { embedCoverage, memoryEmbedMissing } from '../../api/embeddings.js';
|
|
|
6
6
|
import { importAtSessionEnd, importForStore } from '../../api/agent-memories.js';
|
|
7
7
|
import { currentMachine } from '../../infra/machine.js';
|
|
8
8
|
import { detailLines } from '../../base/memory/agent-memory-report.js';
|
|
9
|
+
import { withoutUserTag } from '../../base/memory/entry.js';
|
|
9
10
|
import { importChatGPTInto, importClaudeInto, importCursorInto, importGenericFileInto, } from '../importers/sources.js';
|
|
10
11
|
import { importMarkdownInto } from '../importers/markdown.js';
|
|
11
12
|
import { importVaultInto } from '../importers/vault.js';
|
|
@@ -50,7 +51,7 @@ function warnRedacted(count) {
|
|
|
50
51
|
export async function handleImport({ hippoRoot, tenantId, args, flags, }) {
|
|
51
52
|
const useGlobal = boolFlag(flags, 'global');
|
|
52
53
|
const dryRun = boolFlag(flags, 'dry-run');
|
|
53
|
-
const extraTags = stringListFlag(flags, 'tag') ?? [];
|
|
54
|
+
const extraTags = withoutUserTag(stringListFlag(flags, 'tag') ?? []);
|
|
54
55
|
const targetRoot = useGlobal ? hippoHomeDir() : hippoRoot;
|
|
55
56
|
if (boolFlag(flags, 'agents')) {
|
|
56
57
|
return await importAgentMemories(hippoRoot, tenantId, { useGlobal, dryRun });
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// `hippo session-rules`: the SessionStart hook that sends the rules the person taught, and nothing
|
|
2
|
+
// else.
|
|
3
|
+
import { estimateTokens } from '../../base/util/token-text.js';
|
|
4
|
+
import { userRulesGet } from '../../api/index.js';
|
|
5
|
+
import { userRuleLines } from '../../api/context/context-render.js';
|
|
6
|
+
import { bookTokenUse } from '../../api/ledger-db.js';
|
|
7
|
+
import { cliApiContext, cliHookRequest, cliLedgerReach } from './api-context.js';
|
|
8
|
+
import { resolveContextSession } from './context.js';
|
|
9
|
+
import { hookStoreRoot, inPilotHoldout } from './hook-runtime.js';
|
|
10
|
+
import { readHookStdin } from './stdin.js';
|
|
11
|
+
import { workingFolder } from './shared.js';
|
|
12
|
+
async function printSessionRules(hippoRoot, tenantId, stdinText) {
|
|
13
|
+
const { currentSessionId, ledgerSessionId, payloadSessionId } = resolveContextSession(stdinText);
|
|
14
|
+
// Booked at the first hook call, as the prompt hook books it, so the holdout sees no rules.
|
|
15
|
+
const held = await inPilotHoldout(hippoRoot, tenantId, currentSessionId, {
|
|
16
|
+
write: payloadSessionId !== undefined,
|
|
17
|
+
});
|
|
18
|
+
if (held)
|
|
19
|
+
return;
|
|
20
|
+
const ctx = cliApiContext(hippoRoot, tenantId);
|
|
21
|
+
const rules = await userRulesGet(ctx, {
|
|
22
|
+
currentProject: ctx.infra.machine.projectIdentity(workingFolder(ctx)),
|
|
23
|
+
currentSessionId,
|
|
24
|
+
});
|
|
25
|
+
const text = userRuleLines(rules).join('\n').trim();
|
|
26
|
+
if (text === '')
|
|
27
|
+
return;
|
|
28
|
+
process.stdout.write(JSON.stringify({
|
|
29
|
+
hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: text },
|
|
30
|
+
}));
|
|
31
|
+
await bookTokenUse({
|
|
32
|
+
tenantId,
|
|
33
|
+
sessionId: ledgerSessionId,
|
|
34
|
+
surface: 'session_start',
|
|
35
|
+
event: 'inject',
|
|
36
|
+
items: rules.length,
|
|
37
|
+
tokens: estimateTokens(text),
|
|
38
|
+
}, cliLedgerReach(hippoRoot));
|
|
39
|
+
}
|
|
40
|
+
export async function handleSessionRules({ hippoRoot, tenantId }) {
|
|
41
|
+
const { text: stdinText } = await readHookStdin();
|
|
42
|
+
// Fires in every folder, so it never requires init: a folder with no store reads the global one.
|
|
43
|
+
await cliHookRequest(() => printSessionRules(hookStoreRoot(hippoRoot), tenantId, stdinText));
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=session-rules.js.map
|
|
@@ -104,6 +104,8 @@ function setupJsonTool(tool, dryRun) {
|
|
|
104
104
|
bits.push('SessionEnd (session-end)');
|
|
105
105
|
if (result.installedSessionStart)
|
|
106
106
|
bits.push('SessionStart');
|
|
107
|
+
if (result.installedSessionRules)
|
|
108
|
+
bits.push('SessionStart (session-rules)');
|
|
107
109
|
if (result.installedUserPromptSubmit)
|
|
108
110
|
bits.push('UserPromptSubmit (pinned-inject)');
|
|
109
111
|
if (result.installedPreCompact)
|
|
@@ -301,7 +301,7 @@ export const SESSION_VERBS = {
|
|
|
301
301
|
usage: [
|
|
302
302
|
`
|
|
303
303
|
setup One-shot: detect installed AI tools and install their hooks:
|
|
304
|
-
claude-code gets
|
|
304
|
+
claude-code gets 8 hooks in $CLAUDE_CONFIG_DIR/settings.json
|
|
305
305
|
(~/.claude by default), opencode a plugin, codex 2 hooks in
|
|
306
306
|
its hooks.json plus a launcher wrapper, copilot 4 hooks, the
|
|
307
307
|
MCP server and an instructions block under $COPILOT_HOME
|
|
@@ -323,6 +323,14 @@ export const SESSION_VERBS = {
|
|
|
323
323
|
--keep Print without clearing`,
|
|
324
324
|
],
|
|
325
325
|
}),
|
|
326
|
+
'session-rules': verb(() => import('../session-rules.js'), 'handleSessionRules', {
|
|
327
|
+
flags: {},
|
|
328
|
+
usage: [
|
|
329
|
+
`
|
|
330
|
+
session-rules SessionStart hook: send every rule you stated to this project as Claude Code
|
|
331
|
+
session context, from the project store and the global one`,
|
|
332
|
+
],
|
|
333
|
+
}),
|
|
326
334
|
'session-end': verb(() => import('../hooks/session-end.js'), 'handleSessionEnd', {
|
|
327
335
|
// Its sleep step reads --dry-run, but the capture after it writes for real.
|
|
328
336
|
dryRun: false,
|
|
@@ -399,7 +407,7 @@ export const SESSION_VERBS = {
|
|
|
399
407
|
hook <sub> [target] Manage framework integrations
|
|
400
408
|
hook list Show available hooks
|
|
401
409
|
hook install <target> Install hook (claude-code|codex|copilot|cursor|openclaw|opencode|pi)
|
|
402
|
-
claude-code adds
|
|
410
|
+
claude-code adds 8 hooks to $CLAUDE_CONFIG_DIR/settings.json
|
|
403
411
|
(~/.claude by default); opencode installs a plugin; codex
|
|
404
412
|
adds 2 hooks to $CODEX_HOME/hooks.json (trust them once in /hooks) and
|
|
405
413
|
wraps the detected launcher in place; copilot writes
|
|
@@ -36,6 +36,7 @@ export declare const COMMANDS: {
|
|
|
36
36
|
capture: import("./verb-row.js").VerbSpec;
|
|
37
37
|
setup: import("./verb-row.js").VerbSpec;
|
|
38
38
|
'last-sleep': import("./verb-row.js").VerbSpec;
|
|
39
|
+
'session-rules': import("./verb-row.js").VerbSpec;
|
|
39
40
|
'session-end': import("./verb-row.js").VerbSpec;
|
|
40
41
|
'__session-end-worker': import("./verb-row.js").VerbSpec;
|
|
41
42
|
'pre-compact': import("./verb-row.js").VerbSpec;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Claude Code's hooks: install, migrate older forms, and remove hippo's handlers.
|
|
2
|
-
import { HIPPO_SLEEP_MARKER, HIPPO_LAST_SLEEP_MARKER, HIPPO_CAPTURE_MARKER, HIPPO_SESSION_END_MARKER, HIPPO_PINNED_INJECT_MARKER, HIPPO_PINNED_INJECT_COMMAND, HIPPO_PRE_COMPACT_MARKER, HIPPO_COMPACT_RESUME_MARKER, HIPPO_CAPTURE_ERROR_MARKER, HIPPO_POST_COMPACT_MARKER, } from './shared.js';
|
|
2
|
+
import { HIPPO_SLEEP_MARKER, HIPPO_LAST_SLEEP_MARKER, HIPPO_SESSION_RULES_MARKER, HIPPO_SESSION_RULES_COMMAND, HIPPO_CAPTURE_MARKER, HIPPO_SESSION_END_MARKER, HIPPO_PINNED_INJECT_MARKER, HIPPO_PINNED_INJECT_COMMAND, HIPPO_PRE_COMPACT_MARKER, HIPPO_COMPACT_RESUME_MARKER, HIPPO_CAPTURE_ERROR_MARKER, HIPPO_POST_COMPACT_MARKER, } from './shared.js';
|
|
3
3
|
import { isJsonString, isJsonObjectLiteral, } from '../../../base/util/json.js';
|
|
4
4
|
import { handlerCommands, hookArrayContains, isHippoCommand, runsHippo, stripHandlers, withoutHandlers, } from './hook-handlers.js';
|
|
5
5
|
import { HOOK_LONG_TIMEOUT_SECONDS, HOOK_MEDIUM_TIMEOUT_SECONDS, HOOK_SHORT_TIMEOUT_SECONDS, ensureHooksObject, nothingInstalled, } from './install-plan.js';
|
|
@@ -74,7 +74,10 @@ function appendHookIfMissing(hooks, event, marker, group) {
|
|
|
74
74
|
* included; uninstall removes only handlers that run one. */
|
|
75
75
|
const CLAUDE_HOOK_MARKERS = [
|
|
76
76
|
['SessionEnd', [HIPPO_SESSION_END_MARKER, HIPPO_SLEEP_MARKER, HIPPO_CAPTURE_MARKER]],
|
|
77
|
-
[
|
|
77
|
+
[
|
|
78
|
+
'SessionStart',
|
|
79
|
+
[HIPPO_LAST_SLEEP_MARKER, HIPPO_SESSION_RULES_MARKER, HIPPO_COMPACT_RESUME_MARKER],
|
|
80
|
+
],
|
|
78
81
|
['UserPromptSubmit', [HIPPO_PINNED_INJECT_MARKER]],
|
|
79
82
|
['PreCompact', [HIPPO_PRE_COMPACT_MARKER]],
|
|
80
83
|
['PostCompact', [HIPPO_POST_COMPACT_MARKER]],
|
|
@@ -87,6 +90,9 @@ const CLAUDE_APPENDED_EVENTS = CLAUDE_HOOK_MARKERS.map(([event]) => event).filte
|
|
|
87
90
|
function appendSessionHooks(hooks, logFile) {
|
|
88
91
|
const installedSessionEnd = appendHookIfMissing(hooks, 'SessionEnd', HIPPO_SESSION_END_MARKER, claudeCommandGroup(`hippo session-end --log-file "${logFile}"`, HOOK_SHORT_TIMEOUT_SECONDS));
|
|
89
92
|
const installedSessionStart = appendHookIfMissing(hooks, 'SessionStart', HIPPO_LAST_SLEEP_MARKER, claudeCommandGroup(`hippo last-sleep --path "${logFile}"`, HOOK_SHORT_TIMEOUT_SECONDS));
|
|
93
|
+
// No matcher: a resumed or cleared session and a compaction lose the rules too, so every source
|
|
94
|
+
// sends them again.
|
|
95
|
+
const installedSessionRules = appendHookIfMissing(hooks, 'SessionStart', HIPPO_SESSION_RULES_MARKER, claudeCommandGroup(HIPPO_SESSION_RULES_COMMAND, HOOK_SHORT_TIMEOUT_SECONDS));
|
|
90
96
|
// Mid-session pinned-rule re-injection: UserPromptSubmit runs every turn, so pinned memories stay
|
|
91
97
|
// in context; the fresh write tail makes lessons saved earlier in the session visible on the next
|
|
92
98
|
// prompt even before they are pinned.
|
|
@@ -95,6 +101,7 @@ function appendSessionHooks(hooks, logFile) {
|
|
|
95
101
|
return {
|
|
96
102
|
installedSessionEnd,
|
|
97
103
|
installedSessionStart,
|
|
104
|
+
installedSessionRules,
|
|
98
105
|
migratedPinnedInjectRecent,
|
|
99
106
|
installedUserPromptSubmit,
|
|
100
107
|
};
|
|
@@ -121,7 +128,7 @@ export function planClaudeCodeHooks(settings, { settingsPath, logFile, compactLo
|
|
|
121
128
|
// SAFETY: ensureHooksObject left every event hippo appends to absent or an array.
|
|
122
129
|
const hooks = merge;
|
|
123
130
|
const migration = migrateLegacyClaudeHooks(hooks);
|
|
124
|
-
const { installedSessionEnd, installedSessionStart, migratedPinnedInjectRecent, installedUserPromptSubmit, } = appendSessionHooks(hooks, logFile);
|
|
131
|
+
const { installedSessionEnd, installedSessionStart, installedSessionRules, migratedPinnedInjectRecent, installedUserPromptSubmit, } = appendSessionHooks(hooks, logFile);
|
|
125
132
|
const { installedPreCompact, installedCompactResume, installedPostCompact } = appendCompactionHooks(hooks, compactLog);
|
|
126
133
|
const installedCaptureError = appendCaptureErrorHook(hooks);
|
|
127
134
|
const result = {
|
|
@@ -129,6 +136,7 @@ export function planClaudeCodeHooks(settings, { settingsPath, logFile, compactLo
|
|
|
129
136
|
settingsPath,
|
|
130
137
|
installedSessionEnd,
|
|
131
138
|
installedSessionStart,
|
|
139
|
+
installedSessionRules,
|
|
132
140
|
installedUserPromptSubmit,
|
|
133
141
|
installedPreCompact,
|
|
134
142
|
installedCompactResume,
|
|
@@ -10,6 +10,7 @@ export function nothingInstalled(target, settingsPath) {
|
|
|
10
10
|
settingsPath,
|
|
11
11
|
installedSessionEnd: false,
|
|
12
12
|
installedSessionStart: false,
|
|
13
|
+
installedSessionRules: false,
|
|
13
14
|
installedUserPromptSubmit: false,
|
|
14
15
|
installedPreCompact: false,
|
|
15
16
|
installedCompactResume: false,
|
|
@@ -18,6 +18,8 @@ export interface InstallResult {
|
|
|
18
18
|
settingsPath: string;
|
|
19
19
|
installedSessionEnd: boolean;
|
|
20
20
|
installedSessionStart: boolean;
|
|
21
|
+
/** SessionStart -> `hippo session-rules` (sends the rules you stated). */
|
|
22
|
+
installedSessionRules: boolean;
|
|
21
23
|
installedUserPromptSubmit: boolean;
|
|
22
24
|
installedPreCompact: boolean;
|
|
23
25
|
installedCompactResume: boolean;
|
|
@@ -9,6 +9,8 @@ export interface ToolDetection {
|
|
|
9
9
|
}
|
|
10
10
|
export declare const HIPPO_SLEEP_MARKER = "hippo sleep";
|
|
11
11
|
export declare const HIPPO_LAST_SLEEP_MARKER = "hippo last-sleep";
|
|
12
|
+
export declare const HIPPO_SESSION_RULES_MARKER = "hippo session-rules";
|
|
13
|
+
export declare const HIPPO_SESSION_RULES_COMMAND = "hippo session-rules";
|
|
12
14
|
export declare const HIPPO_CAPTURE_MARKER = "hippo capture --last-session";
|
|
13
15
|
export declare const HIPPO_SESSION_END_MARKER = "hippo session-end";
|
|
14
16
|
export declare const HIPPO_PINNED_INJECT_MARKER = "hippo context --pinned-only";
|
|
@@ -2,6 +2,8 @@ import * as path from 'node:path';
|
|
|
2
2
|
import { HIPPO_DIR, userHome } from '../../../base/util/agent-homes.js';
|
|
3
3
|
export const HIPPO_SLEEP_MARKER = 'hippo sleep';
|
|
4
4
|
export const HIPPO_LAST_SLEEP_MARKER = 'hippo last-sleep';
|
|
5
|
+
export const HIPPO_SESSION_RULES_MARKER = 'hippo session-rules';
|
|
6
|
+
export const HIPPO_SESSION_RULES_COMMAND = 'hippo session-rules';
|
|
5
7
|
export const HIPPO_CAPTURE_MARKER = 'hippo capture --last-session';
|
|
6
8
|
export const HIPPO_SESSION_END_MARKER = 'hippo session-end';
|
|
7
9
|
export const HIPPO_PINNED_INJECT_MARKER = 'hippo context --pinned-only';
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "hippo-memory",
|
|
3
3
|
"name": "Hippo Memory",
|
|
4
4
|
"description": "Make your agent's memory work like a brain. Hippo is long-term memory for coding agents.",
|
|
5
|
-
"version": "3.
|
|
5
|
+
"version": "3.2.0",
|
|
6
6
|
"configSchema": {
|
|
7
7
|
"type": "object",
|
|
8
8
|
"additionalProperties": false,
|
package/package.json
CHANGED