hippo-memory 3.3.3 → 3.5.1
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 +4 -4
- package/dist/api/callers.d.ts +4 -1
- package/dist/api/context/context-plan.js +3 -0
- package/dist/api/context/context-pools.js +4 -1
- package/dist/api/context/user-rule.js +2 -1
- package/dist/api/dashboard/detail.js +2 -1
- package/dist/api/dashboard/live.d.ts +0 -4
- package/dist/api/dashboard/live.js +0 -8
- package/dist/api/memories/conflicts.d.ts +2 -1
- package/dist/api/memories/conflicts.js +3 -8
- package/dist/api/memories/promote.js +6 -2
- package/dist/api/objects/object-kinds.d.ts +1 -4
- package/dist/api/objects/object-kinds.js +1 -5
- package/dist/api/recall/compose.js +2 -1
- package/dist/api/recall/rank-stages.js +2 -1
- package/dist/api/recall/rows.js +2 -1
- package/dist/api/session-end.d.ts +3 -2
- package/dist/api/session-end.js +8 -4
- package/dist/api/sharing.d.ts +4 -3
- package/dist/api/sharing.js +2 -2
- package/dist/api/sleep/auto-sleep.d.ts +3 -2
- package/dist/api/sleep/auto-sleep.js +16 -3
- package/dist/api/sleep/one-sleep.d.ts +23 -0
- package/dist/api/sleep/one-sleep.js +53 -0
- package/dist/api/sleep/sleep-run.js +2 -1
- package/dist/api/sleep/sleep.d.ts +5 -0
- package/dist/api/sleep/sleep.js +2 -1
- package/dist/api/summary-parents.js +2 -1
- package/dist/base/config/config-keys.js +1 -0
- package/dist/base/config/config.d.ts +2 -0
- package/dist/base/config/config.js +1 -0
- package/dist/base/embeddings/local.d.ts +1 -1
- package/dist/base/embeddings/local.js +2 -3
- package/dist/base/memory/ambient.js +2 -1
- package/dist/base/memory/entry.d.ts +4 -1
- package/dist/base/memory/entry.js +7 -1
- package/dist/base/memory/half-life-plan.js +6 -4
- package/dist/base/memory/keep-rules.js +2 -1
- package/dist/base/memory/liveness.d.ts +7 -0
- package/dist/base/memory/liveness.js +6 -0
- package/dist/base/memory/markdown.js +15 -5
- package/dist/base/memory/memory-audit.js +2 -1
- package/dist/base/memory/memory-facts.d.ts +0 -2
- package/dist/base/memory/memory-facts.js +0 -2
- package/dist/base/memory/merged-row.js +3 -2
- package/dist/base/memory/rule-replaces.js +2 -1
- package/dist/base/memory/stale-mark.d.ts +9 -0
- package/dist/base/memory/stale-mark.js +18 -0
- package/dist/base/ports/store/capture.d.ts +2 -0
- package/dist/base/ports/store/conflicts.d.ts +5 -1
- package/dist/base/ports/store/conflicts.js +2 -0
- package/dist/base/ports/store/consolidation.d.ts +66 -2
- package/dist/base/ports/store/consolidation.js +5 -0
- package/dist/base/ports/store/context-reads.d.ts +2 -0
- package/dist/base/ports/store/objects.d.ts +15 -4
- package/dist/base/ports/store/sessions.d.ts +8 -2
- package/dist/base/ports/store/sessions.js +6 -0
- package/dist/base/ports/store/store-effects.d.ts +5 -0
- package/dist/base/ports/store.d.ts +1 -1
- package/dist/base/scope/live-memory.d.ts +7 -0
- package/dist/base/scope/live-memory.js +10 -0
- package/dist/base/scope/read-admission.d.ts +2 -0
- package/dist/base/scope/read-admission.js +9 -2
- package/dist/base/util/version.d.ts +1 -1
- package/dist/base/util/version.js +1 -1
- package/dist/db/continuity-tables.d.ts +4 -1
- package/dist/db/continuity-tables.js +21 -12
- package/dist/db/migrate.js +2 -2
- package/dist/db/migrations/index.d.ts +1 -1
- package/dist/db/migrations/index.js +5 -1
- package/dist/db/migrations/v61.js +3 -3
- package/dist/db/migrations/v62.d.ts +3 -0
- package/dist/db/migrations/v62.js +43 -0
- package/dist/db/migrations/v63.d.ts +3 -0
- package/dist/db/migrations/v63.js +9 -0
- package/dist/db/required-objects.js +2 -1
- package/dist/db/sql-predicates.d.ts +22 -2
- package/dist/db/sql-predicates.js +27 -2
- package/dist/domain/agent-memories/apply.js +2 -1
- package/dist/domain/agent-memories/container-view.js +2 -1
- package/dist/domain/consolidate/conflicts.js +2 -1
- package/dist/domain/consolidate/dag-summary.d.ts +2 -0
- package/dist/domain/consolidate/dag.d.ts +3 -0
- package/dist/domain/consolidate/dag.js +53 -8
- package/dist/domain/consolidate/dedupe.js +2 -1
- package/dist/domain/consolidate/events.d.ts +2 -0
- package/dist/domain/consolidate/llm-passes.js +94 -20
- package/dist/domain/consolidate/merge.js +11 -10
- package/dist/domain/consolidate/retry-holds.d.ts +14 -0
- package/dist/domain/consolidate/retry-holds.js +26 -0
- package/dist/domain/consolidate/run.d.ts +8 -0
- package/dist/domain/consolidate/run.js +2 -0
- package/dist/domain/consolidate/tombstones.d.ts +3 -4
- package/dist/domain/consolidate/tombstones.js +3 -3
- package/dist/domain/graph/recall.js +3 -2
- package/dist/domain/learn/churn-stale.js +2 -1
- package/dist/domain/learn/extract.d.ts +10 -0
- package/dist/domain/learn/extract.js +10 -5
- package/dist/domain/learn/invalidation.d.ts +1 -1
- package/dist/domain/learn/invalidation.js +4 -11
- package/dist/domain/objects/decisions.d.ts +4 -7
- package/dist/domain/objects/decisions.js +1 -14
- package/dist/domain/objects/descriptor.d.ts +2 -0
- package/dist/domain/objects/lifecycle.js +8 -2
- package/dist/domain/search/as-of.js +3 -2
- package/dist/domain/sharing/share.d.ts +16 -4
- package/dist/domain/sharing/share.js +33 -17
- package/dist/entry/store-kit.js +2 -1
- package/dist/infra/local-embedder.js +14 -2
- package/dist/infra/spool-claims.d.ts +2 -2
- package/dist/infra/spool-claims.js +4 -3
- package/dist/infra/spool-import.js +1 -1
- package/dist/infra/spool-record.d.ts +3 -1
- package/dist/store/sqlite/capture/compaction-hooks.js +14 -6
- package/dist/store/sqlite/capture/compaction-rows.js +9 -2
- package/dist/store/sqlite/capture/spool-request-id.d.ts +3 -0
- package/dist/store/sqlite/capture/spool-request-id.js +12 -0
- package/dist/store/sqlite/connectors/quarantine.js +13 -4
- package/dist/store/sqlite/consolidation/consolidation-summaries.d.ts +4 -5
- package/dist/store/sqlite/consolidation/consolidation-summaries.js +46 -26
- package/dist/store/sqlite/consolidation/consolidation.js +7 -0
- package/dist/store/sqlite/consolidation/empty-extractions.d.ts +14 -0
- package/dist/store/sqlite/consolidation/empty-extractions.js +57 -0
- package/dist/store/sqlite/consolidation/rebuild-holds.d.ts +21 -0
- package/dist/store/sqlite/consolidation/rebuild-holds.js +68 -0
- package/dist/store/sqlite/consolidation/sleep-lock.d.ts +4 -0
- package/dist/store/sqlite/consolidation/sleep-lock.js +69 -0
- package/dist/store/sqlite/entries/entry-filter.js +3 -3
- package/dist/store/sqlite/entries/entry-reads.js +2 -1
- package/dist/store/sqlite/entries/entry-row.js +5 -1
- package/dist/store/sqlite/entries/entry-writes.js +9 -15
- package/dist/store/sqlite/entries/raw-archive.d.ts +2 -1
- package/dist/store/sqlite/entries/raw-archive.js +12 -3
- package/dist/store/sqlite/maintenance/agent-import-steps.js +7 -2
- package/dist/store/sqlite/maintenance/project-tags.js +4 -3
- package/dist/store/sqlite/recall/candidates.js +12 -11
- package/dist/store/sqlite/recall/search-rows.d.ts +3 -0
- package/dist/store/sqlite/recall/search-rows.js +26 -9
- package/dist/store/sqlite/records/object-rows.d.ts +2 -0
- package/dist/store/sqlite/records/object-rows.js +5 -1
- package/dist/store/sqlite/records/object-writes.d.ts +3 -0
- package/dist/store/sqlite/records/object-writes.js +43 -1
- package/dist/store/sqlite/reports/dashboard-lists.js +3 -2
- package/dist/store/sqlite/reports/dashboard-reads.js +5 -3
- package/dist/store/sqlite/reports/dashboard-sql.d.ts +0 -3
- package/dist/store/sqlite/reports/dashboard-sql.js +2 -9
- package/dist/store/sqlite/reports/reports.js +2 -1
- package/dist/store/sqlite/review/conflicts.js +10 -5
- package/dist/store/sqlite/runtime/rule-sql.d.ts +1 -0
- package/dist/store/sqlite/runtime/rule-sql.js +4 -1
- package/dist/store/sqlite/runtime/status-transitions.d.ts +98 -0
- package/dist/store/sqlite/runtime/status-transitions.js +105 -0
- package/dist/store/sqlite/sessions/goals.js +11 -12
- package/dist/store/sqlite/sessions/sessions.d.ts +1 -1
- package/dist/store/sqlite/sessions/sessions.js +20 -8
- package/dist/surface/capture/session-worker.d.ts +3 -2
- package/dist/surface/capture/session-worker.js +36 -10
- package/dist/surface/cli/api-context.js +2 -1
- package/dist/surface/cli/client.d.ts +6 -5
- package/dist/surface/cli/client.js +50 -19
- package/dist/surface/cli/conflicts.js +12 -1
- package/dist/surface/cli/continuity.js +4 -0
- package/dist/surface/cli/decisions.js +16 -17
- package/dist/surface/cli/hooks/session-end-worker.js +3 -2
- package/dist/surface/cli/install-steps.js +99 -13
- package/dist/surface/cli/memory-writes.js +3 -2
- package/dist/surface/cli/print.js +2 -1
- package/dist/surface/cli/sleep-render.js +7 -0
- package/dist/surface/cli/sleep.d.ts +3 -2
- package/dist/surface/cli/sleep.js +10 -4
- package/dist/surface/cli/transfer.js +6 -3
- package/dist/surface/cli/verbs/objects.js +2 -2
- package/dist/surface/dashboard/dashboard-actions.js +1 -1
- package/dist/surface/hooks-install/codex-wrapper.js +52 -11
- package/dist/surface/hooks-install/rules/hook-blocks.js +9 -2
- package/dist/surface/mcp/admin-tools.js +5 -2
- package/dist/surface/render/sleep-events.js +2 -0
- package/dist/surface/server/routes/decisions.js +2 -2
- package/dist/surface/server/sleep-child.js +5 -4
- package/dist/surface/server/sleep-offload.js +36 -25
- package/dist-ui/assets/index-Cst0ubfs.js +1 -0
- package/dist-ui/index.html +1 -1
- 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
- package/dist-ui/assets/index-Q9SY-1Bj.js +0 -1
|
@@ -130,6 +130,8 @@ interface SaveRule<K extends SavableKind> {
|
|
|
130
130
|
readonly createKeys: (fields: ObjectFields[K], version: number) => JsonObject;
|
|
131
131
|
/** Keys the supersede row stores after its own. */
|
|
132
132
|
readonly supersedeKeys?: (fields: ObjectFields[K]) => JsonObject;
|
|
133
|
+
/** The save also weakens the replaced row's mirror and the memory it names. */
|
|
134
|
+
readonly weakensPredecessor?: true;
|
|
133
135
|
}
|
|
134
136
|
export declare const hasText: (text: string | null | undefined) => boolean;
|
|
135
137
|
type SaveRules = {
|
|
@@ -201,7 +201,11 @@ const refreshKeys = (f) => f.receiptCount === undefined
|
|
|
201
201
|
? { refreshed: false }
|
|
202
202
|
: { refreshed: true, receipt_count: f.receiptCount };
|
|
203
203
|
export const SAVE_RULES = {
|
|
204
|
-
decision: {
|
|
204
|
+
decision: {
|
|
205
|
+
versioned: false,
|
|
206
|
+
createKeys: (f) => ({ has_context: hasText(f.context) }),
|
|
207
|
+
weakensPredecessor: true,
|
|
208
|
+
},
|
|
205
209
|
process: {
|
|
206
210
|
versioned: true,
|
|
207
211
|
createKeys: (f, version) => ({
|
|
@@ -14,5 +14,8 @@ export declare function saveAny(on: OnHandle, files: StoreFiles, ...[tenantId, k
|
|
|
14
14
|
} | {
|
|
15
15
|
readonly refused: "unlinked";
|
|
16
16
|
readonly memoryId: string;
|
|
17
|
+
} | {
|
|
18
|
+
readonly refused: "memory_missing";
|
|
19
|
+
readonly memoryId: string;
|
|
17
20
|
} | import("../../../base/ports/store/objects.js").Prediction;
|
|
18
21
|
//# sourceMappingURL=object-writes.d.ts.map
|
|
@@ -5,6 +5,8 @@ import { placeholders } from '../../../db/sql.js';
|
|
|
5
5
|
import { chunked } from '../../../base/util/chunked.js';
|
|
6
6
|
import { calculateStrength, LEGACY_TYPED_HALF_LIFE } from '../../../base/memory/strength.js';
|
|
7
7
|
import { deriveHalfLife } from '../../../base/memory/entry.js';
|
|
8
|
+
import { markStale, SUPERSEDED_TAG } from '../../../base/memory/stale-mark.js';
|
|
9
|
+
import { readEntriesByIds } from '../entries/entry-reads.js';
|
|
8
10
|
import { stampOriginProject, upsertEntryRow } from '../entries/entry-row.js';
|
|
9
11
|
import { auditEntryWrite, writeEntryMirrors, auditingRefusal } from '../entries/entry-writes.js';
|
|
10
12
|
import { markGraphDirty } from '../graph/graph-queue.js';
|
|
@@ -168,6 +170,7 @@ function onStoreHalfLife(db, mirror, rules) {
|
|
|
168
170
|
function withMirror(on, write, writeRow) {
|
|
169
171
|
return on((db, files) => auditingRefusal(db, write.actor, () => {
|
|
170
172
|
let mirror = stampOriginProject(files, write.mirror);
|
|
173
|
+
let also = [];
|
|
171
174
|
const written = withWriteScopeOr(db, 'write_entry', (rollback) => {
|
|
172
175
|
mirror = onStoreHalfLife(db, mirror, files);
|
|
173
176
|
upsertEntryRow(db, mirror);
|
|
@@ -175,6 +178,10 @@ function withMirror(on, write, writeRow) {
|
|
|
175
178
|
if (refusalOf(row))
|
|
176
179
|
return rollback(row);
|
|
177
180
|
auditEntryWrite(db, mirror, write.actor);
|
|
181
|
+
const others = write.alsoWrite?.(db) ?? [];
|
|
182
|
+
if (refusalOf(others))
|
|
183
|
+
return rollback(others);
|
|
184
|
+
also = others;
|
|
178
185
|
return row;
|
|
179
186
|
});
|
|
180
187
|
if (refusalOf(written))
|
|
@@ -183,18 +190,53 @@ function withMirror(on, write, writeRow) {
|
|
|
183
190
|
if (write.graphTenant !== undefined)
|
|
184
191
|
markGraphDirty(db, write.graphTenant, mirror.id);
|
|
185
192
|
writeEntryMirrors(files.hippoRoot, mirror);
|
|
193
|
+
for (const entry of also)
|
|
194
|
+
writeEntryMirrors(files.hippoRoot, entry);
|
|
186
195
|
return written;
|
|
187
196
|
}), openStore);
|
|
188
197
|
}
|
|
198
|
+
/** The memory the replaced row mirrors; none when the save replaces nothing or the mirror is gone. */
|
|
199
|
+
function replacedMirrorId(db, tenantId, kind, replaced) {
|
|
200
|
+
if (replaced === undefined)
|
|
201
|
+
return undefined;
|
|
202
|
+
// SAFETY: the SELECT names memory_id, a column every typed-object table has.
|
|
203
|
+
const row = cachedStatement(db, `SELECT memory_id FROM ${objectTable(kind)} WHERE id = ? AND tenant_id = ?`).get(replaced, tenantId);
|
|
204
|
+
return row?.memory_id ?? undefined;
|
|
205
|
+
}
|
|
206
|
+
/** Weakens the memory the replaced row mirrors, if it has one, and the one the save names, in the
|
|
207
|
+
* save's scope. A named memory the tenant does not hold refuses the save; a gone mirror is skipped. */
|
|
208
|
+
function weakenWithSave(db, tenantId, kind, save) {
|
|
209
|
+
const named = save.weakensMemoryId;
|
|
210
|
+
const derived = replacedMirrorId(db, tenantId, kind, save.supersedesId);
|
|
211
|
+
const ids = [...new Set([derived, named].filter((id) => id !== undefined))];
|
|
212
|
+
const held = readEntriesByIds(db, ids, tenantId);
|
|
213
|
+
if (named !== undefined && !held.has(named)) {
|
|
214
|
+
return { refused: 'memory_missing', memoryId: named };
|
|
215
|
+
}
|
|
216
|
+
const weakened = [];
|
|
217
|
+
for (const id of ids) {
|
|
218
|
+
const entry = held.get(id);
|
|
219
|
+
if (entry === undefined)
|
|
220
|
+
continue;
|
|
221
|
+
const marked = markStale(entry, SUPERSEDED_TAG);
|
|
222
|
+
upsertEntryRow(db, marked);
|
|
223
|
+
auditEntryWrite(db, marked, save.actor);
|
|
224
|
+
weakened.push(marked);
|
|
225
|
+
}
|
|
226
|
+
return weakened;
|
|
227
|
+
}
|
|
189
228
|
function save(on, tenantId, kind, save) {
|
|
190
229
|
const spec = rowSpec(kind);
|
|
191
230
|
const write = {
|
|
192
231
|
mirror: save.mirror,
|
|
193
232
|
actor: save.actor,
|
|
194
233
|
graphTenant: spec.graphType ? tenantId : undefined,
|
|
234
|
+
alsoWrite: SAVE_RULES[kind].weakensPredecessor
|
|
235
|
+
? (db) => weakenWithSave(db, tenantId, kind, save)
|
|
236
|
+
: undefined,
|
|
195
237
|
};
|
|
196
238
|
const written = withMirror(on, write, (db, memoryId) => writeObjectRow(db, { tenantId, kind, memoryId, save }));
|
|
197
|
-
return
|
|
239
|
+
return refusalOf(written) ? written : spec.rowTo(written);
|
|
198
240
|
}
|
|
199
241
|
/** The linked ids are checked once the mirror is in and before the INSERT, so a refusal undoes
|
|
200
242
|
* the mirror with it. */
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { withReadSnapshot } from '../../../db/busy.js';
|
|
2
2
|
import { pragmaDataVersion } from '../../../db/meta.js';
|
|
3
3
|
import { cachedStatement } from '../../../db/statement-cache.js';
|
|
4
|
-
import {
|
|
4
|
+
import { CONFIDENCE_LEVELS } from '../../../base/memory/entry.js';
|
|
5
|
+
import { BAND_AT_RISK, LAYER_ORDER, listHead, memoryFacts, } from '../../../base/memory/memory-facts.js';
|
|
5
6
|
import { DAY_MS } from '../../../base/util/time.js';
|
|
6
7
|
import { FACT_COLUMNS, factInputs, FILTER_SLOTS, textFilter, tallyOf, } from './dashboard-functions.js';
|
|
7
8
|
import { IN_PROJECT, OPEN_PAIRS } from './dashboard-sql.js';
|
|
@@ -24,7 +25,7 @@ const SORT_SQL = {
|
|
|
24
25
|
retrievals: 'COALESCE(retrieval_count, 0)',
|
|
25
26
|
last: 'hippo_days(last_retrieved, :now)',
|
|
26
27
|
age: 'age',
|
|
27
|
-
confidence: rankBy(`COALESCE(confidence, 'observed')`,
|
|
28
|
+
confidence: rankBy(`COALESCE(confidence, 'observed')`, CONFIDENCE_LEVELS),
|
|
28
29
|
scope: `hippo_text_key(COALESCE(scope, ''))`,
|
|
29
30
|
};
|
|
30
31
|
const CHIP_SQL = `(:chip = 'all' OR (:chip = 'risk' AND hippo_band(${FACT_COLUMNS}, :now) = ${BAND_AT_RISK}) ` +
|
|
@@ -12,7 +12,8 @@ import { SCATTER_POINTS_MAX, } from '../../../base/ports/store/dashboard-reads.j
|
|
|
12
12
|
import { openConflictsNaming } from '../review/conflicts.js';
|
|
13
13
|
import { FACT_COLUMNS, GRID_CELLS, textFilter, PROJECT_SLOTS, tallyOf, useDashboardFunctions, } from './dashboard-functions.js';
|
|
14
14
|
import { MemoryLists } from './dashboard-lists.js';
|
|
15
|
-
import { IN_PROJECT,
|
|
15
|
+
import { IN_PROJECT, LIVE, OPEN_PAIRS } from './dashboard-sql.js';
|
|
16
|
+
import { kindIn, quarantinedIn, supersededIn, supersededKindIn, } from '../../../db/sql-predicates.js';
|
|
16
17
|
import { handlesOf, openStore } from '../runtime/handles.js';
|
|
17
18
|
import { answered, bound } from '../runtime/bound.js';
|
|
18
19
|
const EMBEDDED = 'EXISTS (SELECT 1 FROM memory_vectors v WHERE v.memory_id = memories.id)';
|
|
@@ -24,9 +25,10 @@ const noneExcluded = () => ({
|
|
|
24
25
|
quarantined: 0,
|
|
25
26
|
});
|
|
26
27
|
function excluded(db, tenantId) {
|
|
27
|
-
// SAFETY: `why` is one of the three CASE arms or NULL.
|
|
28
|
+
// SAFETY: `why` is one of the three CASE arms or NULL. The kind arm counts a `--kind superseded` row,
|
|
29
|
+
// which hippo remember saves with no successor link.
|
|
28
30
|
const counts = cachedStatement(db, `SELECT CASE WHEN ${quarantinedIn('')} THEN 'quarantined' ` +
|
|
29
|
-
`WHEN ${supersededIn(
|
|
31
|
+
`WHEN ${supersededIn()} OR ${supersededKindIn('')} THEN 'superseded' ` +
|
|
30
32
|
`WHEN ${kindIn('')} = 'archived' THEN 'archived' END AS why, COUNT(*) AS n ` +
|
|
31
33
|
`FROM memories WHERE tenant_id = ? AND NOT (${LIVE}) GROUP BY why`).all(tenantId);
|
|
32
34
|
const excluded = noneExcluded();
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
export declare const quarantinedIn: (t: string) => string;
|
|
2
|
-
export declare const supersededIn: (t: string) => string;
|
|
3
|
-
export declare const kindIn: (t: string) => string;
|
|
4
1
|
export declare const LIVE: string;
|
|
5
2
|
export declare const IN_PROJECT: string;
|
|
6
3
|
export declare const OPEN_PAIRS: string;
|
|
@@ -1,12 +1,5 @@
|
|
|
1
|
-
// The
|
|
2
|
-
|
|
3
|
-
import { QUARANTINE_SCOPE_PREFIX } from '../connectors/quarantine.js';
|
|
4
|
-
// SQL twins of isQuarantineScope and of the two halves of isLiveMemory, for columns under prefix
|
|
5
|
-
// `t`; substr compares bytes, as startsWith does, where LIKE would fold case.
|
|
6
|
-
export const quarantinedIn = (t) => `(${t}scope IS NOT NULL AND substr(${t}scope, 1, ${QUARANTINE_SCOPE_PREFIX.length}) = '${QUARANTINE_SCOPE_PREFIX}')`;
|
|
7
|
-
export const supersededIn = (t) => `(${t}superseded_by IS NOT NULL AND ${t}superseded_by <> '')`;
|
|
8
|
-
export const kindIn = (t) => `COALESCE(${t}kind, 'distilled')`;
|
|
9
|
-
const liveIn = (t) => `NOT ${supersededIn(t)} AND ${kindIn(t)} IN ('raw', 'distilled') AND NOT ${quarantinedIn(t)}`;
|
|
1
|
+
// The dashboard's live-row rules as SQL, which its reads and its sorted memory lists both filter by.
|
|
2
|
+
import { liveIn } from '../../../db/sql-predicates.js';
|
|
10
3
|
export const LIVE = liveIn('');
|
|
11
4
|
// Named parameters bound from one object: Node 22's node:sqlite skips every named slot, ?NNN too,
|
|
12
5
|
// on a positional bind.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// hippo.db's Reports group: the tenant reports, listings and usage reports the status verbs print.
|
|
2
2
|
import { withReadSnapshot } from '../../../db/index.js';
|
|
3
3
|
import { cachedStatement } from '../../../db/statement-cache.js';
|
|
4
|
+
import { supersededIn } from '../../../db/sql-predicates.js';
|
|
4
5
|
import { summarizeTokenUse } from '../ledger/token-ledger.js';
|
|
5
6
|
import { summarizeFailures } from '../capture/failure-log.js';
|
|
6
7
|
import { keysetPage } from '../../../base/util/keyset.js';
|
|
@@ -29,7 +30,7 @@ function correctionLinks(db, page) {
|
|
|
29
30
|
src.created AS source_created
|
|
30
31
|
FROM memories old JOIN memories new ON new.id = old.superseded_by
|
|
31
32
|
LEFT JOIN memories src ON new.extracted_from <> '' AND src.id = new.extracted_from
|
|
32
|
-
WHERE old.
|
|
33
|
+
WHERE ${supersededIn('old.')}${range.sql}
|
|
33
34
|
ORDER BY old.created ASC, old.id ASC LIMIT ?`).all(...range.params, page.limit + 1);
|
|
34
35
|
const kept = keysetPage(rows, page.limit, (r) => ({ created: r.old_created, id: r.old_id }));
|
|
35
36
|
return {
|
|
@@ -3,7 +3,7 @@ import { ALL_TENANTS, DEFAULT_TENANT_ID } from '../../../base/util/tenant.js';
|
|
|
3
3
|
import { withWriteScope } from '../../../db/index.js';
|
|
4
4
|
import { insertRejectedValue } from './rejection.js';
|
|
5
5
|
import { rejectionDigest, normalizeValueForRejection, } from '../../../base/records/rejection-digest.js';
|
|
6
|
-
import { archiveRawMemory } from '../entries/raw-archive.js';
|
|
6
|
+
import { archiveRawMemory, markMirrorCleaned } from '../entries/raw-archive.js';
|
|
7
7
|
import { MEMORY_CONFLICT_COLUMNS, parseJsonArray, rowToMemoryConflict, } from '../runtime/rows.js';
|
|
8
8
|
import { audit } from '../audit/audit-event.js';
|
|
9
9
|
import { syncChangedMirrors, purgeMirrorBestEffort } from '../folder-files/mirrors.js';
|
|
@@ -17,6 +17,7 @@ import { openStore } from '../runtime/handles.js';
|
|
|
17
17
|
import { bound } from '../runtime/bound.js';
|
|
18
18
|
import { READ_PAGE_ROWS } from '../../../base/util/pages.js';
|
|
19
19
|
import { handleStamp } from '../runtime/handle-clock.js';
|
|
20
|
+
import { moveStatus } from '../runtime/status-transitions.js';
|
|
20
21
|
// The JOIN with both members' memories rows needs each conflict column qualified, or `id` would be
|
|
21
22
|
// ambiguous.
|
|
22
23
|
const CONFLICT_COLS_MC = MEMORY_CONFLICT_COLUMNS.split(', ')
|
|
@@ -177,7 +178,12 @@ function resolveStaleOpenConflicts(db, canonicalDetected, sameTenant, detectedAt
|
|
|
177
178
|
const resolved = page.filter((row) => !detectedKeys.has(`${row.memory_a_id}::${row.memory_b_id}`) ||
|
|
178
179
|
!sameTenant(row.memory_a_id, row.memory_b_id));
|
|
179
180
|
if (resolved.length > 0) {
|
|
180
|
-
|
|
181
|
+
moveStatus(db, 'conflictStale', {
|
|
182
|
+
tenantId: ALL_TENANTS,
|
|
183
|
+
ids: resolved.map((row) => row.id),
|
|
184
|
+
to: 'resolved',
|
|
185
|
+
set: { updated_at: detectedAt },
|
|
186
|
+
});
|
|
181
187
|
}
|
|
182
188
|
if (page.length < READ_PAGE_ROWS)
|
|
183
189
|
return;
|
|
@@ -412,9 +418,8 @@ function purgeRemovedLoserMirrors(hippoRoot, db, loserId, removal) {
|
|
|
412
418
|
// which the cleanupArchivedMirrors reaper never scans.
|
|
413
419
|
const purge = { id: removedId, isRaw, logPrefix: 'resolveConflict' };
|
|
414
420
|
const mirrorOk = purgeMirrorBestEffort(hippoRoot, purge);
|
|
415
|
-
if (mirrorOk && isRaw)
|
|
416
|
-
|
|
417
|
-
}
|
|
421
|
+
if (mirrorOk && isRaw)
|
|
422
|
+
markMirrorCleaned(db, removedId, handleStamp(db));
|
|
418
423
|
}
|
|
419
424
|
}
|
|
420
425
|
/** The conflict and loser ids every conflict_resolve audit row names. */
|
|
@@ -23,6 +23,7 @@ export declare function scopeAdmitSql(col: '' | 'm.', ownScope?: string | null):
|
|
|
23
23
|
/** `origin_project IN (?, ...)` with one placeholder per name, the SQL twin of an origin filter;
|
|
24
24
|
* an empty list matches nothing. */
|
|
25
25
|
export declare function originInSql(names: readonly string[], column?: string): string;
|
|
26
|
+
export declare const tagsOf: (column: string) => string;
|
|
26
27
|
/** SQL twin of ownScopeTouches, which is also canReadScope for an admin: every row but another
|
|
27
28
|
* person's personal one. LIKE folds ASCII case as isPersonalScope's /i does. */
|
|
28
29
|
export declare function touchableScopeSql(col: '' | 'm.', ownScope?: string | null): SqlFragment;
|
|
@@ -9,6 +9,7 @@ import { EMOTIONAL_MULTIPLIERS, FALLBACK_HALF_LIFE_DAYS, applyLossAversionRatio,
|
|
|
9
9
|
import { KEEP_PAIRS } from '../../../base/memory/keep-rules.js';
|
|
10
10
|
import { PERSONAL_SCOPE_PREFIX, RECALL_DEFAULT_DENY_SCOPES, } from '../../../base/scope/recall-scope.js';
|
|
11
11
|
import { placeholders } from '../../../db/sql.js';
|
|
12
|
+
import { notSupersededIn } from '../../../db/sql-predicates.js';
|
|
12
13
|
import { rewardFactorAt } from '../../../db/decay-key.js';
|
|
13
14
|
import { SPACE_CODES } from '../../rules/copies.js';
|
|
14
15
|
const UNIX_EPOCH_JULIAN_DAY = 2440587.5;
|
|
@@ -59,7 +60,7 @@ export const julianDayOfMs = (msParam) => `(${msParam} / ${DAY_MS}.0 + ${UNIX_EP
|
|
|
59
60
|
// json_each matches the tag as a whole element; substr, not LIKE, keeps the prefix case-sensitive
|
|
60
61
|
// like startsWith.
|
|
61
62
|
const keepPairSql = (p) => ({
|
|
62
|
-
sql: `(
|
|
63
|
+
sql: `(${notSupersededIn()} AND EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(tags_json) THEN ` +
|
|
63
64
|
`tags_json ELSE '[]' END) WHERE value = ?) AND substr(source, 1, ${p.sourcePrefix.length}) = ?)`,
|
|
64
65
|
params: [p.tag, p.sourcePrefix],
|
|
65
66
|
});
|
|
@@ -88,6 +89,8 @@ export function scopeAdmitSql(col, ownScope) {
|
|
|
88
89
|
export function originInSql(names, column = 'origin_project') {
|
|
89
90
|
return names.length === 0 ? '0' : `${column} IN (${placeholders(names.length)})`;
|
|
90
91
|
}
|
|
92
|
+
// A tags column that is not a JSON array reads as no tags, as parseJsonArray reads it.
|
|
93
|
+
export const tagsOf = (column) => `CASE WHEN NOT json_valid(${column}) THEN '[]' WHEN json_type(${column}) = 'array' THEN ${column} ELSE '[]' END`;
|
|
91
94
|
/** SQL twin of ownScopeTouches, which is also canReadScope for an admin: every row but another
|
|
92
95
|
* person's personal one. LIKE folds ASCII case as isPersonalScope's /i does. */
|
|
93
96
|
export function touchableScopeSql(col, ownScope) {
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { DatabaseSyncLike, SqlResult } from '../../../db/index.js';
|
|
2
|
+
import type { ALL_TENANTS } from '../../../base/util/tenant.js';
|
|
3
|
+
declare const TRANSITIONS: {
|
|
4
|
+
readonly compactionDone: {
|
|
5
|
+
readonly table: "compactions";
|
|
6
|
+
readonly key: "id";
|
|
7
|
+
readonly tenant: true;
|
|
8
|
+
readonly from: readonly ["summarised"];
|
|
9
|
+
readonly to: readonly ["done"];
|
|
10
|
+
readonly set: readonly ["items_written"];
|
|
11
|
+
};
|
|
12
|
+
readonly goalComplete: {
|
|
13
|
+
readonly table: "goal_stack";
|
|
14
|
+
readonly key: "id";
|
|
15
|
+
readonly tenant: true;
|
|
16
|
+
readonly from: readonly ["active", "suspended"];
|
|
17
|
+
readonly to: readonly ["completed"];
|
|
18
|
+
readonly set: readonly ["completed_at", "outcome_score"];
|
|
19
|
+
};
|
|
20
|
+
readonly goalResume: {
|
|
21
|
+
readonly table: "goal_stack";
|
|
22
|
+
readonly key: "id";
|
|
23
|
+
readonly tenant: true;
|
|
24
|
+
readonly from: readonly ["suspended"];
|
|
25
|
+
readonly to: readonly ["active"];
|
|
26
|
+
readonly set: readonly [];
|
|
27
|
+
};
|
|
28
|
+
readonly conflictStale: {
|
|
29
|
+
readonly table: "memory_conflicts";
|
|
30
|
+
readonly key: "id";
|
|
31
|
+
readonly tenant: false;
|
|
32
|
+
readonly from: readonly ["open"];
|
|
33
|
+
readonly to: readonly ["resolved"];
|
|
34
|
+
readonly set: readonly ["updated_at"];
|
|
35
|
+
};
|
|
36
|
+
readonly quarantineApprove: {
|
|
37
|
+
readonly table: "memory_quarantine";
|
|
38
|
+
readonly key: "memory_id";
|
|
39
|
+
readonly tenant: true;
|
|
40
|
+
readonly from: readonly ["pending"];
|
|
41
|
+
readonly to: readonly ["approved"];
|
|
42
|
+
readonly set: readonly ["decided_at", "decided_by"];
|
|
43
|
+
};
|
|
44
|
+
readonly quarantineReject: {
|
|
45
|
+
readonly table: "memory_quarantine";
|
|
46
|
+
readonly key: "memory_id";
|
|
47
|
+
readonly tenant: true;
|
|
48
|
+
readonly from: readonly ["pending"];
|
|
49
|
+
readonly to: readonly ["rejected"];
|
|
50
|
+
readonly set: readonly ["decided_at", "decided_by"];
|
|
51
|
+
};
|
|
52
|
+
readonly snapshotClose: {
|
|
53
|
+
readonly table: "task_snapshots";
|
|
54
|
+
readonly key: "id";
|
|
55
|
+
readonly tenant: true;
|
|
56
|
+
readonly from: readonly ["active"];
|
|
57
|
+
readonly to: readonly ["cleared", "done", "session-ended"];
|
|
58
|
+
readonly set: readonly ["updated_at"];
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
type Transitions = typeof TRANSITIONS;
|
|
62
|
+
/** The name of one guarded status move. */
|
|
63
|
+
export type TransitionName = keyof Transitions;
|
|
64
|
+
type ToOf<N extends TransitionName> = Transitions[N]['to'][number];
|
|
65
|
+
type SetOf<N extends TransitionName> = Transitions[N]['set'][number];
|
|
66
|
+
type TenantPart<N extends TransitionName> = Transitions[N]['tenant'] extends true ? {
|
|
67
|
+
readonly tenantId: string;
|
|
68
|
+
} : {
|
|
69
|
+
readonly tenantId: typeof ALL_TENANTS;
|
|
70
|
+
};
|
|
71
|
+
type SetPart<N extends TransitionName> = [SetOf<N>] extends [never] ? {
|
|
72
|
+
readonly set?: undefined;
|
|
73
|
+
} : {
|
|
74
|
+
readonly set: {
|
|
75
|
+
readonly [C in SetOf<N>]: SqlResult;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
type MoveParts<N extends TransitionName> = {
|
|
79
|
+
readonly to: ToOf<N>;
|
|
80
|
+
} & TenantPart<N> & SetPart<N>;
|
|
81
|
+
/** The rows to move, the status to move them to, and the columns the move sets with it. */
|
|
82
|
+
export type StatusMove<N extends TransitionName> = MoveParts<N> & {
|
|
83
|
+
readonly ids: readonly (string | number)[];
|
|
84
|
+
};
|
|
85
|
+
/** One row to move: `StatusMove` with a single `id`. */
|
|
86
|
+
export type OneStatusMove<N extends TransitionName> = MoveParts<N> & {
|
|
87
|
+
readonly id: string | number;
|
|
88
|
+
};
|
|
89
|
+
/** The error for a target status outside the transition's list, naming the statuses allowed. */
|
|
90
|
+
export declare function badStatusTarget(name: TransitionName, to: string): Error;
|
|
91
|
+
/** Moves the keyed rows that are in one of the transition's from-statuses to `to`, and returns how
|
|
92
|
+
* many it moved: 0 when none was in a from-status. Throws when `to` is not one of its targets. */
|
|
93
|
+
export declare function moveStatus<N extends TransitionName>(db: DatabaseSyncLike, name: N, move: StatusMove<N>): number;
|
|
94
|
+
/** `moveStatus` for one row whose write scope already read its status: a row that left its
|
|
95
|
+
* from-status since then throws, so the scope undoes its writes. */
|
|
96
|
+
export declare function moveOneStatus<N extends TransitionName>(db: DatabaseSyncLike, name: N, move: OneStatusMove<N>): void;
|
|
97
|
+
export {};
|
|
98
|
+
//# sourceMappingURL=status-transitions.d.ts.map
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { placeholders } from '../../../db/sql.js';
|
|
2
|
+
import { cachedStatement } from '../../../db/statement-cache.js';
|
|
3
|
+
import { SNAPSHOT_CLOSE_STATUSES } from '../../../base/ports/store/sessions.js';
|
|
4
|
+
// Table, key and column names reach the SQL only through this map, never from a caller.
|
|
5
|
+
const TRANSITIONS = {
|
|
6
|
+
compactionDone: {
|
|
7
|
+
table: 'compactions',
|
|
8
|
+
key: 'id',
|
|
9
|
+
tenant: true,
|
|
10
|
+
from: ['summarised'],
|
|
11
|
+
to: ['done'],
|
|
12
|
+
set: ['items_written'],
|
|
13
|
+
},
|
|
14
|
+
goalComplete: {
|
|
15
|
+
table: 'goal_stack',
|
|
16
|
+
key: 'id',
|
|
17
|
+
tenant: true,
|
|
18
|
+
from: ['active', 'suspended'],
|
|
19
|
+
to: ['completed'],
|
|
20
|
+
set: ['completed_at', 'outcome_score'],
|
|
21
|
+
},
|
|
22
|
+
goalResume: {
|
|
23
|
+
table: 'goal_stack',
|
|
24
|
+
key: 'id',
|
|
25
|
+
tenant: true,
|
|
26
|
+
from: ['suspended'],
|
|
27
|
+
to: ['active'],
|
|
28
|
+
set: [],
|
|
29
|
+
},
|
|
30
|
+
conflictStale: {
|
|
31
|
+
table: 'memory_conflicts',
|
|
32
|
+
key: 'id',
|
|
33
|
+
tenant: false,
|
|
34
|
+
from: ['open'],
|
|
35
|
+
to: ['resolved'],
|
|
36
|
+
set: ['updated_at'],
|
|
37
|
+
},
|
|
38
|
+
quarantineApprove: {
|
|
39
|
+
table: 'memory_quarantine',
|
|
40
|
+
key: 'memory_id',
|
|
41
|
+
tenant: true,
|
|
42
|
+
from: ['pending'],
|
|
43
|
+
to: ['approved'],
|
|
44
|
+
set: ['decided_at', 'decided_by'],
|
|
45
|
+
},
|
|
46
|
+
quarantineReject: {
|
|
47
|
+
table: 'memory_quarantine',
|
|
48
|
+
key: 'memory_id',
|
|
49
|
+
tenant: true,
|
|
50
|
+
from: ['pending'],
|
|
51
|
+
to: ['rejected'],
|
|
52
|
+
set: ['decided_at', 'decided_by'],
|
|
53
|
+
},
|
|
54
|
+
snapshotClose: {
|
|
55
|
+
table: 'task_snapshots',
|
|
56
|
+
key: 'id',
|
|
57
|
+
tenant: true,
|
|
58
|
+
from: ['active'],
|
|
59
|
+
to: SNAPSHOT_CLOSE_STATUSES,
|
|
60
|
+
set: ['updated_at'],
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
function updateSql(spec) {
|
|
64
|
+
const sets = ['status = ?', ...spec.set.map((column) => `${column} = ?`)].join(', ');
|
|
65
|
+
const tenant = spec.tenant ? ' AND tenant_id = ?' : '';
|
|
66
|
+
return (`UPDATE ${spec.table} SET ${sets} WHERE ${spec.key} IN (SELECT value FROM json_each(?))${tenant} ` +
|
|
67
|
+
`AND status IN (${placeholders(spec.from.length)})`);
|
|
68
|
+
}
|
|
69
|
+
/** The error for a target status outside the transition's list, naming the statuses allowed. */
|
|
70
|
+
export function badStatusTarget(name, to) {
|
|
71
|
+
const spec = TRANSITIONS[name];
|
|
72
|
+
return new Error(`invalid ${spec.table} status "${to}": use ${spec.to.join(' | ')}`);
|
|
73
|
+
}
|
|
74
|
+
function applyMove(db, name, move) {
|
|
75
|
+
const spec = TRANSITIONS[name];
|
|
76
|
+
const { to, ids, tenantId, set = {} } = move;
|
|
77
|
+
if (!spec.to.includes(to))
|
|
78
|
+
throw badStatusTarget(name, to);
|
|
79
|
+
if (ids.length === 0)
|
|
80
|
+
return 0;
|
|
81
|
+
const params = [
|
|
82
|
+
to,
|
|
83
|
+
...spec.set.map((column) => set[column]),
|
|
84
|
+
JSON.stringify(ids),
|
|
85
|
+
...(spec.tenant ? [tenantId] : []),
|
|
86
|
+
...spec.from,
|
|
87
|
+
];
|
|
88
|
+
const result = cachedStatement(db, updateSql(spec)).run(...params);
|
|
89
|
+
return Number(result.changes ?? 0);
|
|
90
|
+
}
|
|
91
|
+
/** Moves the keyed rows that are in one of the transition's from-statuses to `to`, and returns how
|
|
92
|
+
* many it moved: 0 when none was in a from-status. Throws when `to` is not one of its targets. */
|
|
93
|
+
export function moveStatus(db, name, move) {
|
|
94
|
+
return applyMove(db, name, move);
|
|
95
|
+
}
|
|
96
|
+
/** `moveStatus` for one row whose write scope already read its status: a row that left its
|
|
97
|
+
* from-status since then throws, so the scope undoes its writes. */
|
|
98
|
+
export function moveOneStatus(db, name, move) {
|
|
99
|
+
const { id, to, tenantId, set } = move;
|
|
100
|
+
if (applyMove(db, name, { ids: [id], to, tenantId, set }) === 1)
|
|
101
|
+
return;
|
|
102
|
+
const spec = TRANSITIONS[name];
|
|
103
|
+
throw new Error(`${spec.table} row ${id} left ${spec.from.join(' | ')} before its status move`);
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=status-transitions.js.map
|
|
@@ -5,6 +5,7 @@ import { bound } from '../runtime/bound.js';
|
|
|
5
5
|
import { cachedStatement } from '../../../db/statement-cache.js';
|
|
6
6
|
import { generateId } from '../../../base/memory/entry.js';
|
|
7
7
|
import { handleStamp } from '../runtime/handle-clock.js';
|
|
8
|
+
import { moveOneStatus, moveStatus } from '../runtime/status-transitions.js';
|
|
8
9
|
// The goal stack's rules: its ids, its depth cap, the parent check, a new goal and policy, and
|
|
9
10
|
// the strength a completed goal passes to the memories recalled under it.
|
|
10
11
|
// The CLI prints these ids and the sequential-learning adapter reads them back as 16 hex
|
|
@@ -222,19 +223,17 @@ function completeGoal(db, tenantId, goalId, opts) {
|
|
|
222
223
|
const completedAt = handleStamp(db);
|
|
223
224
|
const score = opts.outcomeScore ?? null;
|
|
224
225
|
withWriteScope(db, 'complete_goal', () => {
|
|
225
|
-
const goalRow = cachedStatement(db, `SELECT created_at
|
|
226
|
+
const goalRow = cachedStatement(db, `SELECT created_at FROM goal_stack WHERE id = ? AND tenant_id = ?`).get(goalId, tenantId);
|
|
226
227
|
if (!goalRow)
|
|
227
228
|
return;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
`).run(completedAt, score, goalId, tenantId);
|
|
237
|
-
if (score !== null && !opts.noPropagate) {
|
|
229
|
+
// A goal that is already completed moves no row, so a second call neither restamps nor rescales.
|
|
230
|
+
const moved = moveStatus(db, 'goalComplete', {
|
|
231
|
+
tenantId,
|
|
232
|
+
ids: [goalId],
|
|
233
|
+
to: 'completed',
|
|
234
|
+
set: { completed_at: completedAt, outcome_score: score },
|
|
235
|
+
});
|
|
236
|
+
if (moved === 1 && score !== null && !opts.noPropagate) {
|
|
238
237
|
const multiplier = goalOutcomeMultiplier(score);
|
|
239
238
|
if (multiplier !== 1) {
|
|
240
239
|
const since = goalRow.created_at;
|
|
@@ -266,7 +265,7 @@ function resumeGoal(db, tenantId, goalId) {
|
|
|
266
265
|
if (!row || row.status !== 'suspended')
|
|
267
266
|
return;
|
|
268
267
|
enforceDepthCapWithinTx(db, tenantId, row.session_id);
|
|
269
|
-
|
|
268
|
+
moveOneStatus(db, 'goalResume', { tenantId, id: goalId, to: 'active' });
|
|
270
269
|
});
|
|
271
270
|
}
|
|
272
271
|
const goalsBodies = {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DatabaseSyncLike } from '../../../db/index.js';
|
|
2
|
-
import type
|
|
2
|
+
import { type SessionEvent, type Sessions } from '../../../base/ports/store/sessions.js';
|
|
3
3
|
import type { UntracedSession } from '../../../base/ports/store/consolidation.js';
|
|
4
4
|
import type { Handles } from '../runtime/open.js';
|
|
5
5
|
export declare function listSessionEvents(db: DatabaseSyncLike, tenantId: string, options?: {
|
|
@@ -6,6 +6,7 @@ import { raiseMinBinary } from '../../../db/meta.js';
|
|
|
6
6
|
import { assertTenantId } from '../../../base/scope/tenant-id.js';
|
|
7
7
|
import { TASK_OWNER_MIN_BINARY } from '../../../base/util/version.js';
|
|
8
8
|
import { SESSION_EVENT_COLUMNS, rowToSessionEvent } from '../runtime/rows.js';
|
|
9
|
+
import { isSnapshotCloseStatus, } from '../../../base/ports/store/sessions.js';
|
|
9
10
|
import { removeActiveTaskMirror, writeRecentSessionMirror } from './session-mirrors.js';
|
|
10
11
|
import { continuityStamp } from '../../../base/ports/store/types.js';
|
|
11
12
|
import { parseStoredObject } from '../../../base/util/stored-json.js';
|
|
@@ -17,27 +18,38 @@ import { cachedStatement } from '../../../db/statement-cache.js';
|
|
|
17
18
|
import { RECENT_MIRROR_EVENTS, TRACE_EVENT_ROWS } from '../../rules/windows.js';
|
|
18
19
|
import { SESSION_EVENT_LIMIT, WM_MAX_ENTRIES } from '../../../base/util/limits.js';
|
|
19
20
|
import { handleNow, handleStamp } from '../runtime/handle-clock.js';
|
|
21
|
+
import { badStatusTarget, moveOneStatus } from '../runtime/status-transitions.js';
|
|
22
|
+
/** `status` as a close status, or a throw before any write that names the statuses allowed. */
|
|
23
|
+
function requireSnapshotCloseStatus(status) {
|
|
24
|
+
if (isSnapshotCloseStatus(status))
|
|
25
|
+
return status;
|
|
26
|
+
throw badStatusTarget('snapshotClose', status);
|
|
27
|
+
}
|
|
20
28
|
/** Rows closed: the tenant's newest active snapshot, whoever saved it, or none. */
|
|
21
29
|
function clearActiveTaskSnapshot(db, files, tenantId, clearedStatus) {
|
|
22
30
|
const { hippoRoot } = files;
|
|
23
31
|
assertTenantId('clearActiveTaskSnapshot', tenantId);
|
|
24
32
|
assertKeyedOnSharedStore('clearActiveTaskSnapshot', files, undefined);
|
|
33
|
+
const to = requireSnapshotCloseStatus(clearedStatus);
|
|
25
34
|
const now = handleStamp(db);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
// The read and the move share one write scope, so a second clear finds no active row.
|
|
36
|
+
const closed = withWriteScope(db, 'clear_snapshot', () => {
|
|
37
|
+
const active = cachedStatement(db, `SELECT id FROM task_snapshots WHERE status = 'active' AND tenant_id = ? ORDER BY updated_at DESC, id DESC ` +
|
|
38
|
+
`LIMIT 1`).get(tenantId);
|
|
39
|
+
if (!active?.id)
|
|
40
|
+
return 0;
|
|
41
|
+
moveOneStatus(db, 'snapshotClose', { id: active.id, to, tenantId, set: { updated_at: now } });
|
|
42
|
+
return 1;
|
|
43
|
+
});
|
|
33
44
|
removeActiveTaskMirror(hippoRoot, tenantId);
|
|
34
|
-
return
|
|
45
|
+
return closed;
|
|
35
46
|
}
|
|
36
47
|
/** Close the `active` task snapshot(s) owned by `sessionId` at session end; the WHERE scopes on
|
|
37
48
|
* `session_id` too so an ending session can never close a newer session's snapshot. Returns the
|
|
38
49
|
* number of rows closed. */
|
|
39
50
|
function closeTaskSnapshotsForSession(db, { tenantId, sessionId, status }, key) {
|
|
40
51
|
assertTenantId('closeTaskSnapshotsForSession', tenantId);
|
|
52
|
+
requireSnapshotCloseStatus(status);
|
|
41
53
|
if (key)
|
|
42
54
|
continuityStamp(key);
|
|
43
55
|
// a partial key is a caller bug, so fail loud rather than close nothing
|
|
@@ -4,8 +4,9 @@ import type { SessionTurn } from './transcript.js';
|
|
|
4
4
|
/** A turn close runs after each reply; a full close runs once, when the session ends. */
|
|
5
5
|
export type WorkerMode = 'turn' | 'full';
|
|
6
6
|
/** Runs `work` unless a live worker holds this session, which then runs the request after its
|
|
7
|
-
* own so the last reply is never dropped.
|
|
8
|
-
|
|
7
|
+
* own so the last reply is never dropped. A detached worker's stderr goes nowhere, so `gaveUp`
|
|
8
|
+
* is where it leaves the line saying it stopped with the request still queued. */
|
|
9
|
+
export declare function runSessionWorker(sessionId: string | null, mode: WorkerMode, work: (mode: WorkerMode) => Promise<void>, gaveUp?: LineLog): Promise<void>;
|
|
9
10
|
/** The cursor position after `turns`: how many there were and a hash of the last. */
|
|
10
11
|
export declare function turnPosition(turns: readonly SessionTurn[]): string;
|
|
11
12
|
/** The turns after `position`; all of them when it is null or its last turn is no longer in
|