recallnest 2.3.0 → 2.6.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/CHANGELOG.md +187 -0
- package/README.md +49 -38
- package/README_CN.md +46 -31
- package/assets/ui/app.js +1031 -0
- package/assets/ui/index.html +224 -0
- package/assets/ui/styles.css +781 -0
- package/config.json.example +4 -1
- package/docs/api-reference.md +1291 -0
- package/docs/architecture.md +168 -0
- package/docs/connector-spec.md +126 -0
- package/eval/cases-canary.json +58 -0
- package/eval/cases-scope-robustness.json +278 -0
- package/eval/cases.json +117 -20
- package/package.json +25 -4
- package/src/__tests__/access-tracker-novelty.test.ts +304 -0
- package/src/__tests__/activity-counter.test.ts +125 -0
- package/src/__tests__/adaptive-fidelity.test.ts +102 -0
- package/src/__tests__/admission-control.test.ts +206 -0
- package/src/__tests__/anchor-generator.test.ts +67 -0
- package/src/__tests__/api-server-security.test.ts +102 -0
- package/src/__tests__/auto-consolidation.test.ts +168 -0
- package/src/__tests__/auto-recall.test.ts +131 -0
- package/src/__tests__/babel-integration.test.ts +144 -0
- package/src/__tests__/batch-dedup.test.ts +65 -0
- package/src/__tests__/belief-history.test.ts +220 -0
- package/src/__tests__/canary-eval.test.ts +114 -0
- package/src/__tests__/capture-engine.test.ts +1328 -0
- package/src/__tests__/capture-heuristic.test.ts +171 -0
- package/src/__tests__/cascade-forget.test.ts +210 -0
- package/src/__tests__/category-min-scores.test.ts +116 -0
- package/src/__tests__/cc8-cc1-essential-context.test.ts +298 -0
- package/src/__tests__/circuit-breaker.test.ts +99 -0
- package/src/__tests__/cluster-consolidation.test.ts +945 -0
- package/src/__tests__/confidence-metadata.test.ts +125 -0
- package/src/__tests__/confidence-tracker.test.ts +261 -0
- package/src/__tests__/conflict-advisor.test.ts +206 -0
- package/src/__tests__/conflict-escalation.test.ts +149 -0
- package/src/__tests__/conflict-lifecycle.test.ts +83 -0
- package/src/__tests__/conflict-output.test.ts +85 -0
- package/src/__tests__/conflict-store.test.ts +418 -0
- package/src/__tests__/connector-v1.test.ts +181 -0
- package/src/__tests__/consolidation-engine.test.ts +430 -0
- package/src/__tests__/constructive-retrieval.test.ts +509 -0
- package/src/__tests__/context-collapse-renderer.test.ts +214 -0
- package/src/__tests__/context-composer-pins.test.ts +64 -0
- package/src/__tests__/context-composer-task-selection.test.ts +24 -0
- package/src/__tests__/context-reconstructor.test.ts +65 -0
- package/src/__tests__/context-renderer.test.ts +91 -0
- package/src/__tests__/continuity-eval.test.ts +275 -0
- package/src/__tests__/continuity-schema.test.ts +97 -0
- package/src/__tests__/contracts.test.ts +262 -0
- package/src/__tests__/conversation-importer.test.ts +692 -0
- package/src/__tests__/core-recall-eval.test.ts +235 -0
- package/src/__tests__/core-summary.test.ts +109 -0
- package/src/__tests__/data-checkup.test.ts +276 -0
- package/src/__tests__/decay-exemption.test.ts +129 -0
- package/src/__tests__/dedup-actions.test.ts +58 -0
- package/src/__tests__/dedup-guard.test.ts +39 -0
- package/src/__tests__/deterministic-id.test.ts +39 -0
- package/src/__tests__/distill-lock.test.ts +305 -0
- package/src/__tests__/distill-session-argshape.test.ts +79 -0
- package/src/__tests__/doctor.test.ts +319 -0
- package/src/__tests__/dream-pipeline.test.ts +780 -0
- package/src/__tests__/drill-down.test.ts +108 -0
- package/src/__tests__/embedder.test.ts +122 -0
- package/src/__tests__/emotion-decay.test.ts +46 -0
- package/src/__tests__/emotion-detector.test.ts +56 -0
- package/src/__tests__/emotion-phase1-integration.test.ts +153 -0
- package/src/__tests__/emotion-retrieval.test.ts +56 -0
- package/src/__tests__/entity-resolver.test.ts +58 -0
- package/src/__tests__/env-config.test.ts +151 -0
- package/src/__tests__/error-signature-boost.test.ts +87 -0
- package/src/__tests__/error-signature.test.ts +95 -0
- package/src/__tests__/error-taxonomy.test.ts +129 -0
- package/src/__tests__/ethics-layer.test.ts +476 -0
- package/src/__tests__/event-segmenter.test.ts +153 -0
- package/src/__tests__/feature-flags-integration.test.ts +54 -0
- package/src/__tests__/frequency-tracker.test.ts +113 -0
- package/src/__tests__/freshness.test.ts +186 -0
- package/src/__tests__/graph-export.test.ts +489 -0
- package/src/__tests__/hotness-blend.test.ts +283 -0
- package/src/__tests__/ingest-chunking.test.ts +44 -0
- package/src/__tests__/ingest.test.ts +360 -0
- package/src/__tests__/interference-detector.test.ts +203 -0
- package/src/__tests__/kg-extractor.test.ts +192 -0
- package/src/__tests__/kg-store.test.ts +300 -0
- package/src/__tests__/llm-client-pivot.test.ts +628 -0
- package/src/__tests__/llm-consolidation.test.ts +226 -0
- package/src/__tests__/maintenance-locks.test.ts +189 -0
- package/src/__tests__/mcp-efficiency.test.ts +288 -0
- package/src/__tests__/mcp-related-scopes.test.ts +151 -0
- package/src/__tests__/memory-boundaries.test.ts +282 -0
- package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +345 -0
- package/src/__tests__/memory-evolution.test.ts +271 -0
- package/src/__tests__/memory-health-rebalance.test.ts +144 -0
- package/src/__tests__/memory-lint.test.ts +421 -0
- package/src/__tests__/memory-output.test.ts +215 -0
- package/src/__tests__/memory-promotion.test.ts +315 -0
- package/src/__tests__/migrate-dedup-ids.test.ts +65 -0
- package/src/__tests__/multi-vector.test.ts +242 -0
- package/src/__tests__/narrative-architecture.test.ts +456 -0
- package/src/__tests__/noise-filter.test.ts +205 -0
- package/src/__tests__/noise-prototype-bank.test.ts +280 -0
- package/src/__tests__/obsidian-connector.test.ts +363 -0
- package/src/__tests__/omitted-reporting.test.ts +98 -0
- package/src/__tests__/pending-review.test.ts +77 -0
- package/src/__tests__/pii-redact.test.ts +333 -0
- package/src/__tests__/pivot-apply.test.ts +373 -0
- package/src/__tests__/pivot-distill-supervisor.test.ts +457 -0
- package/src/__tests__/pivot-distill.test.ts +1178 -0
- package/src/__tests__/post-retrieval-filter.test.ts +178 -0
- package/src/__tests__/ppr-traversal.test.ts +256 -0
- package/src/__tests__/prediction-engine.test.ts +349 -0
- package/src/__tests__/predictive-prospective-memory.test.ts +416 -0
- package/src/__tests__/preference-guard-smoke.test.ts +211 -0
- package/src/__tests__/preference-matcher.test.ts +282 -0
- package/src/__tests__/preference-slots.test.ts +205 -0
- package/src/__tests__/prospective-memory.test.ts +283 -0
- package/src/__tests__/pull-from-macbook-sync-only.test.ts +679 -0
- package/src/__tests__/query-entity-detector.test.ts +171 -0
- package/src/__tests__/query-expander-alias.test.ts +146 -0
- package/src/__tests__/query-expander.test.ts +34 -0
- package/src/__tests__/recall-gate.test.ts +266 -0
- package/src/__tests__/recall-governor.test.ts +227 -0
- package/src/__tests__/recall-mode.test.ts +64 -0
- package/src/__tests__/resolve-db-path.test.ts +130 -0
- package/src/__tests__/resolve-tier.test.ts +64 -0
- package/src/__tests__/result-synthesizer.test.ts +198 -0
- package/src/__tests__/resume-context.test.ts +4898 -0
- package/src/__tests__/retrieval-eval.test.ts +163 -0
- package/src/__tests__/retrieval-trace.test.ts +213 -0
- package/src/__tests__/retriever-boundary-weight.test.ts +136 -0
- package/src/__tests__/retriever-lazy-init-dispatch.test.ts +123 -0
- package/src/__tests__/retroactive-boost.test.ts +223 -0
- package/src/__tests__/salience-scoring.test.ts +106 -0
- package/src/__tests__/scope-inventory.test.ts +200 -0
- package/src/__tests__/scope-policy.test.ts +69 -0
- package/src/__tests__/scope-suggester.test.ts +80 -0
- package/src/__tests__/session-checkpoint.test.ts +291 -0
- package/src/__tests__/session-distiller.test.ts +640 -0
- package/src/__tests__/session-gc.test.ts +215 -0
- package/src/__tests__/skill-engine.test.ts +552 -0
- package/src/__tests__/skill-promotion.test.ts +654 -0
- package/src/__tests__/skill-verifier.test.ts +122 -0
- package/src/__tests__/source-heartbeat.test.ts +250 -0
- package/src/__tests__/stable-context-length-contract.test.ts +62 -0
- package/src/__tests__/store-patch-metadata.test.ts +205 -0
- package/src/__tests__/store-read-consistency.test.ts +122 -0
- package/src/__tests__/store-schema-migration.test.ts +87 -0
- package/src/__tests__/store-scope-audit.test.ts +81 -0
- package/src/__tests__/store-upsert.test.ts +201 -0
- package/src/__tests__/supersede-chain.test.ts +154 -0
- package/src/__tests__/temporal-parser.test.ts +241 -0
- package/src/__tests__/temporal-validity.test.ts +160 -0
- package/src/__tests__/term-registry-terminal-roster.test.ts +127 -0
- package/src/__tests__/term-registry.test.ts +121 -0
- package/src/__tests__/tool-error-surfacing.test.ts +98 -0
- package/src/__tests__/tool-output-compressor.test.ts +160 -0
- package/src/__tests__/topic-tag.test.ts +113 -0
- package/src/__tests__/trusted-memory.test.ts +839 -0
- package/src/__tests__/ui-server-security.test.ts +93 -0
- package/src/__tests__/usage-tracker.test.ts +287 -0
- package/src/__tests__/version-manager.test.ts +213 -0
- package/src/__tests__/workflow-observation-skill-outcome.test.ts +352 -0
- package/src/__tests__/workflow-observation.test.ts +433 -0
- package/src/__tests__/write-verifier.test.ts +122 -0
- package/src/access-tracker.ts +90 -34
- package/src/activity-counter.ts +46 -18
- package/src/adaptive-retrieval.ts +11 -0
- package/src/aliases.ts +133 -0
- package/src/api-server.ts +36 -9
- package/src/audit-log.ts +4 -2
- package/src/auto-consolidation.ts +8 -3
- package/src/auto-gc.ts +85 -21
- package/src/auto-recall.ts +61 -1
- package/src/belief-history.ts +164 -0
- package/src/capture-engine.ts +142 -32
- package/src/cli.ts +268 -41
- package/src/confidence-tracker.ts +36 -18
- package/src/conflict-engine.ts +24 -3
- package/src/consolidation-engine.ts +255 -23
- package/src/context-composer-stable-selection.ts +7 -1
- package/src/context-composer.ts +8 -1
- package/src/data-checkup.ts +96 -7
- package/src/decay-engine.ts +59 -7
- package/src/distill-lock.ts +194 -15
- package/src/doctor.ts +13 -4
- package/src/dream-pipeline.ts +473 -41
- package/src/env-config.ts +118 -0
- package/src/error-signature.ts +153 -0
- package/src/error-taxonomy.ts +115 -0
- package/src/eval.ts +402 -14
- package/src/freshness.ts +192 -0
- package/src/http-request-policy.ts +148 -0
- package/src/idempotency.ts +8 -0
- package/src/ingest.ts +308 -12
- package/src/kg-extractor.ts +13 -3
- package/src/kg-store.ts +236 -44
- package/src/llm-client.ts +106 -11
- package/src/llm-consolidation.ts +2 -1
- package/src/mcp-server.ts +87 -1800
- package/src/mcp-tool-deps.ts +48 -0
- package/src/mcp-tools-advanced.ts +954 -0
- package/src/mcp-tools-core.ts +637 -0
- package/src/mcp-tools-governance.ts +475 -0
- package/src/memory-boundaries.ts +26 -3
- package/src/memory-evolution.ts +73 -1
- package/src/memory-health-rebalance.ts +4 -0
- package/src/memory-lint.ts +183 -10
- package/src/memory-output.ts +129 -4
- package/src/memory-promotion.ts +246 -0
- package/src/memory-schema.ts +25 -2
- package/src/memory-store-port.ts +46 -0
- package/src/multi-vector.ts +2 -1
- package/src/narrative-schema.ts +2 -1
- package/src/noise-filter.ts +57 -6
- package/src/noise-prototype-bank.ts +408 -0
- package/src/pii-detector.ts +207 -5
- package/src/pivot-apply.ts +399 -0
- package/src/preference-matcher.ts +37 -3
- package/src/query-expander.ts +90 -9
- package/src/recall-gate.ts +305 -0
- package/src/result-synthesizer.ts +2 -1
- package/src/retention-policy.ts +2 -1
- package/src/retrieval-profiles.ts +46 -4
- package/src/retriever.ts +354 -157
- package/src/retroactive-boost.ts +6 -2
- package/src/runtime-config.ts +78 -6
- package/src/scope-suggester.ts +113 -0
- package/src/session-distiller.ts +23 -2
- package/src/session-engine.ts +2 -1
- package/src/session-schema.ts +1 -0
- package/src/session-store.ts +5 -0
- package/src/skill-engine.ts +78 -0
- package/src/skill-promotion.ts +304 -48
- package/src/skill-schema.ts +16 -3
- package/src/skill-verifier.ts +152 -0
- package/src/store.ts +321 -57
- package/src/term-registry.ts +35 -0
- package/src/tool-output-compressor.ts +3 -1
- package/src/ui-server.ts +9 -1
- package/src/usage-tracker.ts +242 -0
- package/src/version-manager.ts +3 -2
- package/src/version.ts +19 -0
- package/src/workflow-observation-engine.ts +2 -1
- package/src/workflow-observation-schema.ts +2 -1
- package/src/workflow-observation-store.ts +6 -2
- package/.env +0 -4
- package/CLAUDE.md +0 -46
- package/config.json +0 -55
- package/daily-recall.sh +0 -110
- package/logs/daily-recall.error.log +0 -0
- package/logs/daily-recall.log +0 -60
- package/logs/ingest-2026-04-11.log +0 -110
- package/logs/ingest-2026-04-12.log +0 -90
- package/logs/ingest-2026-04-13.log +0 -87
- package/logs/launchagent-stderr.log +0 -0
- package/logs/launchagent-stdout.log +0 -0
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
2
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
import { createAuditLogger } from "../audit-log.js";
|
|
8
|
+
import type { AuditEntry } from "../audit-log.js";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_RETENTION_POLICY,
|
|
11
|
+
loadRetentionPolicy,
|
|
12
|
+
saveRetentionPolicy,
|
|
13
|
+
shouldArchiveByPolicy,
|
|
14
|
+
} from "../retention-policy.js";
|
|
15
|
+
import type { RetentionPolicy } from "../retention-policy.js";
|
|
16
|
+
import { scanForPII } from "../pii-detector.js";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Helpers
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
function makeTmpDir(): string {
|
|
23
|
+
const dir = join(tmpdir(), `recallnest-test-${randomUUID()}`);
|
|
24
|
+
mkdirSync(dir, { recursive: true });
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// F-1: Audit Log
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
describe("F-1: audit log", () => {
|
|
33
|
+
let tmpDir: string;
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
tmpDir = makeTmpDir();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
afterEach(() => {
|
|
40
|
+
try {
|
|
41
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
42
|
+
} catch {
|
|
43
|
+
// cleanup best-effort
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("log writes an entry and count returns 1", () => {
|
|
48
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
49
|
+
const logger = createAuditLogger(logPath);
|
|
50
|
+
|
|
51
|
+
logger.log({ operation: "store", actor: "manual", scope: "test" });
|
|
52
|
+
|
|
53
|
+
expect(logger.count()).toBe(1);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("log writes multiple entries", () => {
|
|
57
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
58
|
+
const logger = createAuditLogger(logPath);
|
|
59
|
+
|
|
60
|
+
logger.log({ operation: "store", actor: "manual" });
|
|
61
|
+
logger.log({ operation: "retrieve", actor: "agent" });
|
|
62
|
+
logger.log({ operation: "delete", actor: "system" });
|
|
63
|
+
|
|
64
|
+
expect(logger.count()).toBe(3);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("getRecent returns newest first", () => {
|
|
68
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
69
|
+
const logger = createAuditLogger(logPath);
|
|
70
|
+
|
|
71
|
+
logger.log({ operation: "store", actor: "manual", details: "first" });
|
|
72
|
+
logger.log({ operation: "update", actor: "agent", details: "second" });
|
|
73
|
+
logger.log({ operation: "delete", actor: "system", details: "third" });
|
|
74
|
+
|
|
75
|
+
const recent = logger.getRecent(2);
|
|
76
|
+
expect(recent).toHaveLength(2);
|
|
77
|
+
expect(recent[0].details).toBe("third");
|
|
78
|
+
expect(recent[1].details).toBe("second");
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("getRecent defaults to 20", () => {
|
|
82
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
83
|
+
const logger = createAuditLogger(logPath);
|
|
84
|
+
|
|
85
|
+
for (let i = 0; i < 25; i++) {
|
|
86
|
+
logger.log({ operation: "store", actor: "manual", details: `entry-${i}` });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const recent = logger.getRecent();
|
|
90
|
+
expect(recent).toHaveLength(20);
|
|
91
|
+
expect(recent[0].details).toBe("entry-24");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("exportAll returns all entries in order", () => {
|
|
95
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
96
|
+
const logger = createAuditLogger(logPath);
|
|
97
|
+
|
|
98
|
+
logger.log({ operation: "store", actor: "manual", details: "a" });
|
|
99
|
+
logger.log({ operation: "update", actor: "agent", details: "b" });
|
|
100
|
+
|
|
101
|
+
const all = logger.exportAll();
|
|
102
|
+
expect(all).toHaveLength(2);
|
|
103
|
+
expect(all[0].details).toBe("a");
|
|
104
|
+
expect(all[1].details).toBe("b");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("entries have ISO timestamps", () => {
|
|
108
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
109
|
+
const logger = createAuditLogger(logPath);
|
|
110
|
+
|
|
111
|
+
logger.log({ operation: "store", actor: "manual" });
|
|
112
|
+
|
|
113
|
+
const entries = logger.exportAll();
|
|
114
|
+
expect(entries[0].timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("entries preserve scope and memoryId", () => {
|
|
118
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
119
|
+
const logger = createAuditLogger(logPath);
|
|
120
|
+
|
|
121
|
+
logger.log({
|
|
122
|
+
operation: "store",
|
|
123
|
+
actor: "api",
|
|
124
|
+
scope: "project:x",
|
|
125
|
+
memoryId: "mem-123",
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const entries = logger.exportAll();
|
|
129
|
+
expect(entries[0].scope).toBe("project:x");
|
|
130
|
+
expect(entries[0].memoryId).toBe("mem-123");
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("truncates details to 200 chars", () => {
|
|
134
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
135
|
+
const logger = createAuditLogger(logPath);
|
|
136
|
+
|
|
137
|
+
const longDetails = "x".repeat(300);
|
|
138
|
+
logger.log({ operation: "store", actor: "manual", details: longDetails });
|
|
139
|
+
|
|
140
|
+
const entries = logger.exportAll();
|
|
141
|
+
expect(entries[0].details!.length).toBe(200);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("returns empty arrays / 0 count when file does not exist", () => {
|
|
145
|
+
const logPath = join(tmpDir, "nonexistent.jsonl");
|
|
146
|
+
const logger = createAuditLogger(logPath);
|
|
147
|
+
|
|
148
|
+
expect(logger.getRecent()).toEqual([]);
|
|
149
|
+
expect(logger.exportAll()).toEqual([]);
|
|
150
|
+
expect(logger.count()).toBe(0);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("silently handles write to read-only path", () => {
|
|
154
|
+
// Use a path that cannot be written to (deep nested under /dev/null)
|
|
155
|
+
const logger = createAuditLogger("/dev/null/impossible/audit.jsonl");
|
|
156
|
+
|
|
157
|
+
// Should not throw
|
|
158
|
+
expect(() => {
|
|
159
|
+
logger.log({ operation: "store", actor: "manual" });
|
|
160
|
+
}).not.toThrow();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("creates parent directory if missing", () => {
|
|
164
|
+
const nestedPath = join(tmpDir, "sub", "deep", "audit.jsonl");
|
|
165
|
+
const logger = createAuditLogger(nestedPath);
|
|
166
|
+
|
|
167
|
+
logger.log({ operation: "store", actor: "manual" });
|
|
168
|
+
|
|
169
|
+
expect(existsSync(nestedPath)).toBe(true);
|
|
170
|
+
expect(logger.count()).toBe(1);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("skips malformed lines gracefully", () => {
|
|
174
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
175
|
+
// Write some valid and invalid lines
|
|
176
|
+
writeFileSync(
|
|
177
|
+
logPath,
|
|
178
|
+
'{"timestamp":"2026-01-01T00:00:00Z","operation":"store","actor":"manual"}\nBAD LINE\n{"timestamp":"2026-01-02T00:00:00Z","operation":"update","actor":"agent"}\n',
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
const logger = createAuditLogger(logPath);
|
|
182
|
+
expect(logger.count()).toBe(2);
|
|
183
|
+
expect(logger.exportAll()).toHaveLength(2);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// F-2: Retention Policy
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
describe("F-2: retention policy", () => {
|
|
192
|
+
let tmpDir: string;
|
|
193
|
+
|
|
194
|
+
beforeEach(() => {
|
|
195
|
+
tmpDir = makeTmpDir();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
afterEach(() => {
|
|
199
|
+
try {
|
|
200
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
201
|
+
} catch {
|
|
202
|
+
// cleanup best-effort
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("DEFAULT_RETENTION_POLICY has safe defaults", () => {
|
|
207
|
+
expect(DEFAULT_RETENTION_POLICY.autoArchiveAfterDays).toBe(0);
|
|
208
|
+
expect(DEFAULT_RETENTION_POLICY.maxMemories).toBe(0);
|
|
209
|
+
expect(DEFAULT_RETENTION_POLICY.allowHardDelete).toBe(false);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("loadRetentionPolicy returns defaults for unconfigured scope", () => {
|
|
213
|
+
const policy = loadRetentionPolicy("unknown-scope", tmpDir);
|
|
214
|
+
expect(policy).toEqual(DEFAULT_RETENTION_POLICY);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it("save and load round-trips correctly", () => {
|
|
218
|
+
const custom: Partial<RetentionPolicy> = {
|
|
219
|
+
autoArchiveAfterDays: 30,
|
|
220
|
+
maxMemories: 100,
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
saveRetentionPolicy("my-scope", custom, tmpDir);
|
|
224
|
+
const loaded = loadRetentionPolicy("my-scope", tmpDir);
|
|
225
|
+
|
|
226
|
+
expect(loaded.autoArchiveAfterDays).toBe(30);
|
|
227
|
+
expect(loaded.maxMemories).toBe(100);
|
|
228
|
+
expect(loaded.allowHardDelete).toBe(false); // default preserved
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it("partial save merges with defaults", () => {
|
|
232
|
+
saveRetentionPolicy("scope-a", { allowHardDelete: true }, tmpDir);
|
|
233
|
+
const loaded = loadRetentionPolicy("scope-a", tmpDir);
|
|
234
|
+
|
|
235
|
+
expect(loaded.allowHardDelete).toBe(true);
|
|
236
|
+
expect(loaded.autoArchiveAfterDays).toBe(0);
|
|
237
|
+
expect(loaded.maxMemories).toBe(0);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("different scopes have independent policies", () => {
|
|
241
|
+
saveRetentionPolicy("scope-x", { maxMemories: 50 }, tmpDir);
|
|
242
|
+
saveRetentionPolicy("scope-y", { maxMemories: 200 }, tmpDir);
|
|
243
|
+
|
|
244
|
+
expect(loadRetentionPolicy("scope-x", tmpDir).maxMemories).toBe(50);
|
|
245
|
+
expect(loadRetentionPolicy("scope-y", tmpDir).maxMemories).toBe(200);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("shouldArchiveByPolicy: default policy never archives", () => {
|
|
249
|
+
const result = shouldArchiveByPolicy(DEFAULT_RETENTION_POLICY, 365, 9999);
|
|
250
|
+
expect(result.archive).toBe(false);
|
|
251
|
+
expect(result.reason).toBeUndefined();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("shouldArchiveByPolicy: archives when age exceeds limit", () => {
|
|
255
|
+
const policy: RetentionPolicy = {
|
|
256
|
+
autoArchiveAfterDays: 30,
|
|
257
|
+
maxMemories: 0,
|
|
258
|
+
allowHardDelete: false,
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const result = shouldArchiveByPolicy(policy, 31, 10);
|
|
262
|
+
expect(result.archive).toBe(true);
|
|
263
|
+
expect(result.reason).toContain("31d");
|
|
264
|
+
expect(result.reason).toContain("30d");
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("shouldArchiveByPolicy: does not archive when age is within limit", () => {
|
|
268
|
+
const policy: RetentionPolicy = {
|
|
269
|
+
autoArchiveAfterDays: 30,
|
|
270
|
+
maxMemories: 0,
|
|
271
|
+
allowHardDelete: false,
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
expect(shouldArchiveByPolicy(policy, 29, 10).archive).toBe(false);
|
|
275
|
+
expect(shouldArchiveByPolicy(policy, 30, 10).archive).toBe(false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("shouldArchiveByPolicy: archives when count exceeds limit", () => {
|
|
279
|
+
const policy: RetentionPolicy = {
|
|
280
|
+
autoArchiveAfterDays: 0,
|
|
281
|
+
maxMemories: 100,
|
|
282
|
+
allowHardDelete: false,
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const result = shouldArchiveByPolicy(policy, 5, 101);
|
|
286
|
+
expect(result.archive).toBe(true);
|
|
287
|
+
expect(result.reason).toContain("101");
|
|
288
|
+
expect(result.reason).toContain("100");
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
it("shouldArchiveByPolicy: does not archive when count is within limit", () => {
|
|
292
|
+
const policy: RetentionPolicy = {
|
|
293
|
+
autoArchiveAfterDays: 0,
|
|
294
|
+
maxMemories: 100,
|
|
295
|
+
allowHardDelete: false,
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
expect(shouldArchiveByPolicy(policy, 5, 99).archive).toBe(false);
|
|
299
|
+
expect(shouldArchiveByPolicy(policy, 5, 100).archive).toBe(false);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it("allowHardDelete defaults to false", () => {
|
|
303
|
+
saveRetentionPolicy("scope-del", {}, tmpDir);
|
|
304
|
+
const loaded = loadRetentionPolicy("scope-del", tmpDir);
|
|
305
|
+
expect(loaded.allowHardDelete).toBe(false);
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
// F-3: PII Detector
|
|
311
|
+
// ---------------------------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
describe("F-3: PII detector", () => {
|
|
314
|
+
it("returns clean result for text without PII", () => {
|
|
315
|
+
const result = scanForPII("This is a normal sentence about programming.");
|
|
316
|
+
expect(result.hasPII).toBe(false);
|
|
317
|
+
expect(result.detections).toHaveLength(0);
|
|
318
|
+
expect(result.summary).toBe("No PII detected");
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it("returns clean result for pure Chinese text without PII", () => {
|
|
322
|
+
const result = scanForPII("今天天气不错,我们去公园散步吧。");
|
|
323
|
+
expect(result.hasPII).toBe(false);
|
|
324
|
+
expect(result.detections).toHaveLength(0);
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("detects API keys (high severity)", () => {
|
|
328
|
+
const result = scanForPII("My key is sk-1234567890abcdefghijklmnop");
|
|
329
|
+
expect(result.hasPII).toBe(true);
|
|
330
|
+
const apiKey = result.detections.find((d) => d.type === "api_key");
|
|
331
|
+
expect(apiKey).toBeDefined();
|
|
332
|
+
expect(apiKey!.severity).toBe("high");
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it("detects token patterns (high severity)", () => {
|
|
336
|
+
const result = scanForPII("token=abcdefghij1234567890abcdefghij");
|
|
337
|
+
expect(result.hasPII).toBe(true);
|
|
338
|
+
const detection = result.detections.find((d) => d.type === "api_key");
|
|
339
|
+
expect(detection).toBeDefined();
|
|
340
|
+
expect(detection!.severity).toBe("high");
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("detects passwords (high severity)", () => {
|
|
344
|
+
const result = scanForPII('password="MyS3cretP@ss!"');
|
|
345
|
+
expect(result.hasPII).toBe(true);
|
|
346
|
+
const pwd = result.detections.find((d) => d.type === "password");
|
|
347
|
+
expect(pwd).toBeDefined();
|
|
348
|
+
expect(pwd!.severity).toBe("high");
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
it("detects Chinese ID numbers (high severity)", () => {
|
|
352
|
+
const result = scanForPII("身份证号: 110101199003077891");
|
|
353
|
+
expect(result.hasPII).toBe(true);
|
|
354
|
+
const id = result.detections.find((d) => d.type === "id_number");
|
|
355
|
+
expect(id).toBeDefined();
|
|
356
|
+
expect(id!.severity).toBe("high");
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it("detects email addresses (low severity)", () => {
|
|
360
|
+
const result = scanForPII("Contact me at alice@example.com");
|
|
361
|
+
expect(result.hasPII).toBe(true);
|
|
362
|
+
const email = result.detections.find((d) => d.type === "email");
|
|
363
|
+
expect(email).toBeDefined();
|
|
364
|
+
expect(email!.severity).toBe("low");
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
it("detects phone numbers (medium severity)", () => {
|
|
368
|
+
const result = scanForPII("我的手机号是 13812345678");
|
|
369
|
+
expect(result.hasPII).toBe(true);
|
|
370
|
+
const phone = result.detections.find((d) => d.type === "phone");
|
|
371
|
+
expect(phone).toBeDefined();
|
|
372
|
+
expect(phone!.severity).toBe("medium");
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it("detects credit card numbers (high severity)", () => {
|
|
376
|
+
const result = scanForPII("Card: 4111-1111-1111-1111");
|
|
377
|
+
expect(result.hasPII).toBe(true);
|
|
378
|
+
const cc = result.detections.find((d) => d.type === "credit_card");
|
|
379
|
+
expect(cc).toBeDefined();
|
|
380
|
+
expect(cc!.severity).toBe("high");
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
it("detects credit card without separators", () => {
|
|
384
|
+
const result = scanForPII("Card: 4111111111111111");
|
|
385
|
+
expect(result.hasPII).toBe(true);
|
|
386
|
+
const cc = result.detections.find((d) => d.type === "credit_card");
|
|
387
|
+
expect(cc).toBeDefined();
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
it("detects multiple PII types in mixed text", () => {
|
|
391
|
+
const text =
|
|
392
|
+
"User alice@test.com has password=SuperSecret123 and phone 13900001234. " +
|
|
393
|
+
"API key: sk-abcdefghijklmnopqrstuvwxyz";
|
|
394
|
+
const result = scanForPII(text);
|
|
395
|
+
|
|
396
|
+
expect(result.hasPII).toBe(true);
|
|
397
|
+
const types = new Set(result.detections.map((d) => d.type));
|
|
398
|
+
expect(types.has("email")).toBe(true);
|
|
399
|
+
expect(types.has("password")).toBe(true);
|
|
400
|
+
expect(types.has("phone")).toBe(true);
|
|
401
|
+
expect(types.has("api_key")).toBe(true);
|
|
402
|
+
expect(result.detections.length).toBeGreaterThanOrEqual(4);
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
it("masks sensitive matches (preserves head/tail, masks middle)", () => {
|
|
406
|
+
const result = scanForPII("token=abcdefghijklmnopqrstuvwxyz1234");
|
|
407
|
+
expect(result.hasPII).toBe(true);
|
|
408
|
+
const detection = result.detections[0];
|
|
409
|
+
// Masked value should contain ***
|
|
410
|
+
expect(detection.match).toContain("***");
|
|
411
|
+
// Should not contain the full original value
|
|
412
|
+
expect(detection.match.length).toBeLessThan(
|
|
413
|
+
"token=abcdefghijklmnopqrstuvwxyz1234".length,
|
|
414
|
+
);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it("mask preserves first 4 and last 4 chars for long values", () => {
|
|
418
|
+
// Email is a good test case: alice@example.com (17 chars, > 8)
|
|
419
|
+
const result = scanForPII("email: alice@example.com");
|
|
420
|
+
const email = result.detections.find((d) => d.type === "email");
|
|
421
|
+
expect(email).toBeDefined();
|
|
422
|
+
// "alice@example.com" -> "alic***e.com"
|
|
423
|
+
expect(email!.match.startsWith("alic")).toBe(true);
|
|
424
|
+
expect(email!.match.endsWith(".com")).toBe(true);
|
|
425
|
+
expect(email!.match).toContain("***");
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
it("provides accurate summary counts", () => {
|
|
429
|
+
const text =
|
|
430
|
+
"password=MySecret123 alice@test.com 13812345678";
|
|
431
|
+
const result = scanForPII(text);
|
|
432
|
+
|
|
433
|
+
// Should mention total count and severity breakdown
|
|
434
|
+
expect(result.summary).toContain("Found");
|
|
435
|
+
expect(result.summary).toMatch(/\d+ high/);
|
|
436
|
+
expect(result.summary).toMatch(/\d+ medium/);
|
|
437
|
+
expect(result.summary).toMatch(/\d+ low/);
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
it("records position (char offset) of matches", () => {
|
|
441
|
+
const text = "prefix alice@example.com suffix";
|
|
442
|
+
const result = scanForPII(text);
|
|
443
|
+
const email = result.detections.find((d) => d.type === "email");
|
|
444
|
+
expect(email).toBeDefined();
|
|
445
|
+
expect(email!.position).toBe(text.indexOf("alice@example.com"));
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it("handles empty string", () => {
|
|
449
|
+
const result = scanForPII("");
|
|
450
|
+
expect(result.hasPII).toBe(false);
|
|
451
|
+
expect(result.detections).toHaveLength(0);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
it("can be called multiple times (regex state reset)", () => {
|
|
455
|
+
// Ensures global regex lastIndex is properly reset between calls
|
|
456
|
+
const text = "sk-abcdefghijklmnopqrstuvwxyz";
|
|
457
|
+
const r1 = scanForPII(text);
|
|
458
|
+
const r2 = scanForPII(text);
|
|
459
|
+
expect(r1.detections.length).toBe(r2.detections.length);
|
|
460
|
+
expect(r1.hasPII).toBe(r2.hasPII);
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
// ---------------------------------------------------------------------------
|
|
465
|
+
// F-2 Integration: Retention Policy + Auto-GC
|
|
466
|
+
// ---------------------------------------------------------------------------
|
|
467
|
+
|
|
468
|
+
import {
|
|
469
|
+
maybeRunGc,
|
|
470
|
+
resetGcTimestamp,
|
|
471
|
+
DEFAULT_AUTO_GC_CONFIG,
|
|
472
|
+
} from "../auto-gc.js";
|
|
473
|
+
import { isActiveMemory } from "../memory-evolution.js";
|
|
474
|
+
|
|
475
|
+
describe("F-2 integration: retention policy + auto-gc", () => {
|
|
476
|
+
let tmpDir: string;
|
|
477
|
+
|
|
478
|
+
beforeEach(() => {
|
|
479
|
+
tmpDir = makeTmpDir();
|
|
480
|
+
resetGcTimestamp();
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
afterEach(() => {
|
|
484
|
+
try {
|
|
485
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
486
|
+
} catch {
|
|
487
|
+
// cleanup best-effort
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
/** Build a minimal mock store for auto-gc tests. */
|
|
492
|
+
function makeGcStore(entries: Array<{
|
|
493
|
+
id: string;
|
|
494
|
+
importance: number;
|
|
495
|
+
timestamp: number;
|
|
496
|
+
metadata: string;
|
|
497
|
+
scope: string;
|
|
498
|
+
}>) {
|
|
499
|
+
const data = new Map(entries.map(e => [e.id, {
|
|
500
|
+
...e,
|
|
501
|
+
text: "test",
|
|
502
|
+
vector: [1, 0, 0],
|
|
503
|
+
category: "events" as const,
|
|
504
|
+
}]));
|
|
505
|
+
const updates: Array<{ id: string; metadata: string }> = [];
|
|
506
|
+
return {
|
|
507
|
+
store: {
|
|
508
|
+
stats: async () => ({ totalCount: data.size, scopeCounts: {}, categoryCounts: {} }),
|
|
509
|
+
list: async () => Array.from(data.values()),
|
|
510
|
+
listPage: async (opts: { limit?: number; offset?: number } = {}) => {
|
|
511
|
+
const { limit = 1000, offset = 0 } = opts;
|
|
512
|
+
return Array.from(data.values()).slice(offset, offset + limit);
|
|
513
|
+
},
|
|
514
|
+
update: async (id: string, patch: { metadata: string }) => {
|
|
515
|
+
updates.push({ id, metadata: patch.metadata });
|
|
516
|
+
const entry = data.get(id);
|
|
517
|
+
if (!entry) return null;
|
|
518
|
+
entry.metadata = patch.metadata;
|
|
519
|
+
return entry;
|
|
520
|
+
},
|
|
521
|
+
},
|
|
522
|
+
updates,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
it("archives memories exceeding autoArchiveAfterDays", async () => {
|
|
527
|
+
const now = Date.now();
|
|
528
|
+
const scope = "project:retention-age";
|
|
529
|
+
// Save a retention policy: autoArchiveAfterDays = 30
|
|
530
|
+
saveRetentionPolicy(scope, { autoArchiveAfterDays: 30 }, tmpDir);
|
|
531
|
+
|
|
532
|
+
const activeMeta = JSON.stringify({
|
|
533
|
+
evolution: { status: "active", version: 1 },
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
// One memory aged 45 days (above autoArchiveAfterDays=30)
|
|
537
|
+
// Set importance high enough and decay score high enough that decay alone won't archive
|
|
538
|
+
const { store, updates } = makeGcStore([
|
|
539
|
+
{
|
|
540
|
+
id: "aged-mem",
|
|
541
|
+
importance: 0.5,
|
|
542
|
+
timestamp: now - 45 * 86_400_000,
|
|
543
|
+
metadata: activeMeta,
|
|
544
|
+
scope,
|
|
545
|
+
},
|
|
546
|
+
]);
|
|
547
|
+
|
|
548
|
+
const result = await maybeRunGc(
|
|
549
|
+
store as ReturnType<typeof makeGcStore>["store"] & import("../store.js").MemoryStore,
|
|
550
|
+
{
|
|
551
|
+
...DEFAULT_AUTO_GC_CONFIG,
|
|
552
|
+
minMemoryCount: 1,
|
|
553
|
+
minHoursSinceLastGc: 0,
|
|
554
|
+
// Set a very low decay threshold so decay alone wouldn't trigger
|
|
555
|
+
decayScoreThreshold: 0.001,
|
|
556
|
+
minAgeDays: 60, // Higher than 45 → decay check skipped
|
|
557
|
+
},
|
|
558
|
+
tmpDir,
|
|
559
|
+
);
|
|
560
|
+
|
|
561
|
+
expect(result.triggered).toBe(true);
|
|
562
|
+
expect(result.archivedCount).toBe(1);
|
|
563
|
+
expect(updates.length).toBe(1);
|
|
564
|
+
// Verify the archived metadata marks it as archived
|
|
565
|
+
expect(isActiveMemory(updates[0].metadata)).toBe(false);
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
it("archives memories when scope exceeds maxMemories", async () => {
|
|
569
|
+
const now = Date.now();
|
|
570
|
+
const scope = "project:retention-count";
|
|
571
|
+
// maxMemories = 5 → with 6 active memories, oldest should be archived
|
|
572
|
+
saveRetentionPolicy(scope, { maxMemories: 5 }, tmpDir);
|
|
573
|
+
|
|
574
|
+
const activeMeta = JSON.stringify({
|
|
575
|
+
evolution: { status: "active", version: 1 },
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
// Create 6 memories, all recent (within minAgeDays so decay won't fire)
|
|
579
|
+
const entries = Array.from({ length: 6 }, (_, i) => ({
|
|
580
|
+
id: `mem-${i}`,
|
|
581
|
+
importance: 0.5,
|
|
582
|
+
timestamp: now - (i + 1) * 86_400_000, // 1-6 days old
|
|
583
|
+
metadata: activeMeta,
|
|
584
|
+
scope,
|
|
585
|
+
}));
|
|
586
|
+
|
|
587
|
+
const { store, updates } = makeGcStore(entries);
|
|
588
|
+
|
|
589
|
+
const result = await maybeRunGc(
|
|
590
|
+
store as ReturnType<typeof makeGcStore>["store"] & import("../store.js").MemoryStore,
|
|
591
|
+
{
|
|
592
|
+
...DEFAULT_AUTO_GC_CONFIG,
|
|
593
|
+
minMemoryCount: 1,
|
|
594
|
+
minHoursSinceLastGc: 0,
|
|
595
|
+
decayScoreThreshold: 0.001, // Very low so decay alone won't trigger
|
|
596
|
+
minAgeDays: 365, // Very high so decay check is skipped
|
|
597
|
+
},
|
|
598
|
+
tmpDir,
|
|
599
|
+
);
|
|
600
|
+
|
|
601
|
+
expect(result.triggered).toBe(true);
|
|
602
|
+
// At least one should be archived since activeCount (6) > maxMemories (5)
|
|
603
|
+
expect(result.archivedCount).toBeGreaterThanOrEqual(1);
|
|
604
|
+
expect(updates.length).toBeGreaterThanOrEqual(1);
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
it("does not affect existing behavior when no retention config exists", async () => {
|
|
608
|
+
const now = Date.now();
|
|
609
|
+
const scope = "project:no-retention";
|
|
610
|
+
// No saveRetentionPolicy call → default policy (0/0/false) → no policy archival
|
|
611
|
+
|
|
612
|
+
const activeMeta = JSON.stringify({
|
|
613
|
+
evolution: { status: "active", version: 1 },
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
// Memory aged 10 days, within default minAgeDays (30) → decay skip
|
|
617
|
+
// No retention policy → policy skip
|
|
618
|
+
const { store, updates } = makeGcStore([
|
|
619
|
+
{
|
|
620
|
+
id: "young-mem",
|
|
621
|
+
importance: 0.5,
|
|
622
|
+
timestamp: now - 10 * 86_400_000,
|
|
623
|
+
metadata: activeMeta,
|
|
624
|
+
scope,
|
|
625
|
+
},
|
|
626
|
+
]);
|
|
627
|
+
|
|
628
|
+
const result = await maybeRunGc(
|
|
629
|
+
store as ReturnType<typeof makeGcStore>["store"] & import("../store.js").MemoryStore,
|
|
630
|
+
{
|
|
631
|
+
...DEFAULT_AUTO_GC_CONFIG,
|
|
632
|
+
minMemoryCount: 1,
|
|
633
|
+
minHoursSinceLastGc: 0,
|
|
634
|
+
minAgeDays: 30,
|
|
635
|
+
},
|
|
636
|
+
tmpDir, // Points to empty retention dir
|
|
637
|
+
);
|
|
638
|
+
|
|
639
|
+
expect(result.triggered).toBe(true);
|
|
640
|
+
expect(result.archivedCount).toBe(0);
|
|
641
|
+
expect(updates.length).toBe(0);
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
// ---------------------------------------------------------------------------
|
|
646
|
+
// F-3 Integration: PII Detection + persistMemory
|
|
647
|
+
// ---------------------------------------------------------------------------
|
|
648
|
+
|
|
649
|
+
import { persistMemory } from "../capture-engine.js";
|
|
650
|
+
|
|
651
|
+
describe("F-3 integration: PII detection + persistMemory", () => {
|
|
652
|
+
/** Build minimal deps for persistMemory. */
|
|
653
|
+
function createPiiTestDeps() {
|
|
654
|
+
const storedEntries: Array<Record<string, unknown>> = [];
|
|
655
|
+
let seq = 1;
|
|
656
|
+
return {
|
|
657
|
+
storedEntries,
|
|
658
|
+
deps: {
|
|
659
|
+
embedder: {
|
|
660
|
+
async embedPassage(_text: string) {
|
|
661
|
+
return [1, 0, 0];
|
|
662
|
+
},
|
|
663
|
+
},
|
|
664
|
+
store: {
|
|
665
|
+
async store(entry: Record<string, unknown>) {
|
|
666
|
+
const stored = {
|
|
667
|
+
...entry,
|
|
668
|
+
id: `00000000-0000-0000-0000-${String(seq).padStart(12, "0")}`,
|
|
669
|
+
timestamp: 1_700_000_000_000 + seq,
|
|
670
|
+
};
|
|
671
|
+
seq += 1;
|
|
672
|
+
storedEntries.push(stored);
|
|
673
|
+
return stored;
|
|
674
|
+
},
|
|
675
|
+
async list(
|
|
676
|
+
_scopeFilter?: string[],
|
|
677
|
+
_category?: string,
|
|
678
|
+
limit = 20,
|
|
679
|
+
offset = 0,
|
|
680
|
+
) {
|
|
681
|
+
return storedEntries.slice(offset, offset + limit);
|
|
682
|
+
},
|
|
683
|
+
async update(id: string, updates: Record<string, unknown>) {
|
|
684
|
+
const index = storedEntries.findIndex((e) => e.id === id);
|
|
685
|
+
if (index < 0) return null;
|
|
686
|
+
storedEntries[index] = { ...storedEntries[index], ...updates };
|
|
687
|
+
return storedEntries[index];
|
|
688
|
+
},
|
|
689
|
+
async getById(id: string) {
|
|
690
|
+
return storedEntries.find((e) => e.id === id) ?? null;
|
|
691
|
+
},
|
|
692
|
+
async get(id: string) {
|
|
693
|
+
return storedEntries.find((e) => e.id === id) ?? null;
|
|
694
|
+
},
|
|
695
|
+
},
|
|
696
|
+
},
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
it("adds piiWarning to metadata when text contains API key", async () => {
|
|
701
|
+
const { deps, storedEntries } = createPiiTestDeps();
|
|
702
|
+
const result = await persistMemory(deps as Parameters<typeof persistMemory>[0], {
|
|
703
|
+
text: "My API key is sk-abcdefghijklmnopqrstuvwxyz",
|
|
704
|
+
category: "events",
|
|
705
|
+
importance: 0.7,
|
|
706
|
+
scope: "project:pii-test",
|
|
707
|
+
source: "manual",
|
|
708
|
+
tags: [],
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
expect(result.id).toBeDefined();
|
|
712
|
+
// Check the stored entry's metadata contains piiWarning
|
|
713
|
+
const stored = storedEntries[0];
|
|
714
|
+
const meta = JSON.parse(stored.metadata as string);
|
|
715
|
+
expect(meta.piiWarning).toBeDefined();
|
|
716
|
+
expect(meta.piiWarning.severity).toBe("high");
|
|
717
|
+
expect(meta.piiWarning.detections).toBeGreaterThanOrEqual(1);
|
|
718
|
+
expect(meta.piiWarning.summary).toContain("Found");
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
it("does not add piiWarning to metadata for normal text", async () => {
|
|
722
|
+
const { deps, storedEntries } = createPiiTestDeps();
|
|
723
|
+
const result = await persistMemory(deps as Parameters<typeof persistMemory>[0], {
|
|
724
|
+
text: "User prefers dark mode in all applications",
|
|
725
|
+
category: "preferences",
|
|
726
|
+
importance: 0.7,
|
|
727
|
+
scope: "project:pii-test",
|
|
728
|
+
source: "manual",
|
|
729
|
+
tags: [],
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
expect(result.id).toBeDefined();
|
|
733
|
+
const stored = storedEntries[0];
|
|
734
|
+
const meta = JSON.parse(stored.metadata as string);
|
|
735
|
+
expect(meta.piiWarning).toBeUndefined();
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
it("PII detection does not block write (text with PII is still stored)", async () => {
|
|
739
|
+
const { deps, storedEntries } = createPiiTestDeps();
|
|
740
|
+
const sensitiveText =
|
|
741
|
+
"password=SuperSecret123 and token=abcdefghijklmnopqrstuvwxyz1234";
|
|
742
|
+
const result = await persistMemory(deps as Parameters<typeof persistMemory>[0], {
|
|
743
|
+
text: sensitiveText,
|
|
744
|
+
category: "events",
|
|
745
|
+
importance: 0.7,
|
|
746
|
+
scope: "project:pii-test",
|
|
747
|
+
source: "manual",
|
|
748
|
+
tags: [],
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
// Memory was stored despite PII
|
|
752
|
+
expect(result.id).toBeDefined();
|
|
753
|
+
expect(result.disposition).toBe("stored");
|
|
754
|
+
expect(storedEntries.length).toBe(1);
|
|
755
|
+
// F-3b (2026-07-10): stored text is scrubbed — secrets must not reach
|
|
756
|
+
// storage/embedding/logs. Key names survive for readability.
|
|
757
|
+
expect(storedEntries[0].text).toContain("password=[REDACTED:password]");
|
|
758
|
+
expect(storedEntries[0].text).not.toContain("SuperSecret123");
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
|
|
762
|
+
// ---------------------------------------------------------------------------
|
|
763
|
+
// F-1 integration: audit logger in persistMemory & maybeRunGc
|
|
764
|
+
// ---------------------------------------------------------------------------
|
|
765
|
+
|
|
766
|
+
describe("F-1 integration: audit logger", () => {
|
|
767
|
+
let tmpDir: string;
|
|
768
|
+
beforeEach(() => { tmpDir = join(tmpdir(), `f1-audit-${randomUUID()}`); mkdirSync(tmpDir, { recursive: true }); });
|
|
769
|
+
afterEach(() => { try { rmSync(tmpDir, { recursive: true, force: true }); } catch {} });
|
|
770
|
+
|
|
771
|
+
it("persistMemory records store audit entry", async () => {
|
|
772
|
+
const { persistMemory } = await import("../capture-engine.js");
|
|
773
|
+
const { createAuditLogger } = await import("../audit-log.js");
|
|
774
|
+
const logPath = join(tmpDir, "audit.jsonl");
|
|
775
|
+
const logger = createAuditLogger(logPath);
|
|
776
|
+
|
|
777
|
+
const deps = {
|
|
778
|
+
embedder: { async embedPassage() { return [1, 0, 0]; } },
|
|
779
|
+
store: {
|
|
780
|
+
async store(entry: Record<string, unknown>) { return { ...entry, id: entry.id ?? "test-1", timestamp: Date.now() }; },
|
|
781
|
+
async list() { return []; },
|
|
782
|
+
async update() { return null; },
|
|
783
|
+
async getById() { return null; },
|
|
784
|
+
},
|
|
785
|
+
auditLogger: logger,
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
await persistMemory(deps as Parameters<typeof persistMemory>[0], {
|
|
789
|
+
text: "User prefers dark mode",
|
|
790
|
+
category: "preferences",
|
|
791
|
+
scope: "project:test",
|
|
792
|
+
source: "manual",
|
|
793
|
+
importance: 0.7,
|
|
794
|
+
tags: [],
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
const entries = logger.exportAll();
|
|
798
|
+
const storeEntry = entries.find(e => e.operation === "store");
|
|
799
|
+
expect(storeEntry).toBeDefined();
|
|
800
|
+
expect(storeEntry!.actor).toBe("manual");
|
|
801
|
+
expect(storeEntry!.scope).toBe("project:test");
|
|
802
|
+
});
|
|
803
|
+
|
|
804
|
+
it("maybeRunGc records archive audit entry", async () => {
|
|
805
|
+
const { maybeRunGc, resetGcTimestamp } = await import("../auto-gc.js");
|
|
806
|
+
const { createAuditLogger } = await import("../audit-log.js");
|
|
807
|
+
resetGcTimestamp();
|
|
808
|
+
|
|
809
|
+
const logPath = join(tmpDir, "audit-gc.jsonl");
|
|
810
|
+
const logger = createAuditLogger(logPath);
|
|
811
|
+
const now = Date.now();
|
|
812
|
+
const oldTs = now - 120 * 86_400_000;
|
|
813
|
+
const activeMeta = JSON.stringify({ evolution: { status: "active", version: 1, accessCount: 0, lastAccessedAt: null, validFrom: oldTs, validUntil: null } });
|
|
814
|
+
|
|
815
|
+
const rows = [{ id: "gc-1", text: "old", importance: 0.1, timestamp: oldTs, metadata: activeMeta, category: "events", scope: "project:test" }];
|
|
816
|
+
const store = {
|
|
817
|
+
async stats() { return { totalCount: 100, scopeCounts: {}, categoryCounts: {} }; },
|
|
818
|
+
async list() { return rows; },
|
|
819
|
+
async listPage(opts: { limit?: number; offset?: number } = {}) {
|
|
820
|
+
const { limit = 1000, offset = 0 } = opts;
|
|
821
|
+
return rows.slice(offset, offset + limit);
|
|
822
|
+
},
|
|
823
|
+
async update(id: string, upd: Record<string, unknown>) { return { id, ...upd }; },
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
const result = await maybeRunGc(
|
|
827
|
+
store as Parameters<typeof maybeRunGc>[0],
|
|
828
|
+
{ minMemoryCount: 1, minHoursSinceLastGc: 0, decayScoreThreshold: 0.99, maxArchivePerRun: 10, minAgeDays: 30 },
|
|
829
|
+
undefined, // retentionConfigDir
|
|
830
|
+
logger, // auditLogger (4th param)
|
|
831
|
+
);
|
|
832
|
+
|
|
833
|
+
expect(result.archivedCount).toBe(1);
|
|
834
|
+
const archiveEntry = logger.exportAll().find(e => e.operation === "archive");
|
|
835
|
+
expect(archiveEntry).toBeDefined();
|
|
836
|
+
expect(archiveEntry!.memoryId).toBe("gc-1");
|
|
837
|
+
expect(archiveEntry!.actor).toBe("system");
|
|
838
|
+
});
|
|
839
|
+
});
|