hippo-memory 1.44.0 → 1.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -24
- package/bin/hippo.js +3 -1
- package/dist/ablation.d.ts +10 -1
- package/dist/ablation.js +17 -1
- package/dist/api.d.ts +81 -22
- package/dist/api.js +258 -49
- package/dist/audit.d.ts +2 -2
- package/dist/audit.js +9 -0
- package/dist/autolearn.d.ts +1 -1
- package/dist/autolearn.js +2 -1
- package/dist/capture-error.d.ts +20 -0
- package/dist/capture-error.js +82 -0
- package/dist/capture.d.ts +25 -8
- package/dist/capture.js +100 -5
- package/dist/cli.d.ts +9 -1
- package/dist/cli.js +531 -119
- package/dist/client.d.ts +4 -21
- package/dist/client.js +3 -112
- package/dist/config.d.ts +20 -0
- package/dist/config.js +37 -1
- package/dist/consolidate.d.ts +9 -0
- package/dist/consolidate.js +133 -46
- package/dist/dag.d.ts +1 -0
- package/dist/dag.js +10 -5
- package/dist/dashboard.js +7 -3
- package/dist/db.js +69 -24
- package/dist/dedupe.d.ts +1 -0
- package/dist/dedupe.js +4 -7
- package/dist/doctor.d.ts +34 -0
- package/dist/doctor.js +174 -0
- package/dist/dormant.d.ts +91 -0
- package/dist/dormant.js +121 -0
- package/dist/embedding-provider.js +2 -1
- package/dist/embeddings.js +81 -8
- package/dist/eval-stats.d.ts +123 -0
- package/dist/eval-stats.js +187 -0
- package/dist/extract.d.ts +2 -0
- package/dist/extract.js +9 -4
- package/dist/half-life-migration.d.ts +55 -0
- package/dist/half-life-migration.js +111 -0
- package/dist/hooks.d.ts +4 -0
- package/dist/hooks.js +47 -0
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +90 -48
- package/dist/memory.d.ts +18 -1
- package/dist/memory.js +33 -5
- package/dist/physics-config.js +5 -1
- package/dist/recall-scope.d.ts +24 -0
- package/dist/recall-scope.js +41 -0
- package/dist/refine-llm.js +3 -2
- package/dist/reject-flow.d.ts +3 -3
- package/dist/reject-flow.js +10 -3
- package/dist/rerankers/jev.js +3 -2
- package/dist/rerankers/llm.js +3 -2
- package/dist/search.d.ts +4 -4
- package/dist/search.js +26 -21
- package/dist/server.d.ts +5 -0
- package/dist/server.js +49 -29
- package/dist/shared.js +1 -1
- package/dist/store.d.ts +29 -11
- package/dist/store.js +197 -70
- package/dist/token-ledger.d.ts +119 -0
- package/dist/token-ledger.js +181 -0
- package/dist/version.d.ts +4 -6
- package/dist/version.js +4 -7
- 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 +7 -3
- package/dist/ablation.d.ts.map +0 -1
- package/dist/ablation.js.map +0 -1
- package/dist/ambient.d.ts.map +0 -1
- package/dist/ambient.js.map +0 -1
- package/dist/api.d.ts.map +0 -1
- package/dist/api.js.map +0 -1
- package/dist/audit-prune.d.ts.map +0 -1
- package/dist/audit-prune.js.map +0 -1
- package/dist/audit.d.ts.map +0 -1
- package/dist/audit.js.map +0 -1
- package/dist/auth.d.ts.map +0 -1
- package/dist/auth.js.map +0 -1
- package/dist/autolearn.d.ts.map +0 -1
- package/dist/autolearn.js.map +0 -1
- package/dist/availability.d.ts.map +0 -1
- package/dist/availability.js.map +0 -1
- package/dist/benchmarks/e1.3/incident-recall-eval.js +0 -78
- package/dist/benchmarks/e1.3/incident-recall-eval.js.map +0 -1
- package/dist/benchmarks/e1.3/slack-1000-event-smoke.js +0 -103
- package/dist/benchmarks/e1.3/slack-1000-event-smoke.js.map +0 -1
- package/dist/capture.d.ts.map +0 -1
- package/dist/capture.js.map +0 -1
- package/dist/card-detail.d.ts.map +0 -1
- package/dist/card-detail.js.map +0 -1
- package/dist/card.d.ts.map +0 -1
- package/dist/card.js.map +0 -1
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/compare.d.ts.map +0 -1
- package/dist/compare.js.map +0 -1
- package/dist/config.d.ts.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/connectors/github/backfill.d.ts.map +0 -1
- package/dist/connectors/github/backfill.js.map +0 -1
- package/dist/connectors/github/cli-impl.d.ts.map +0 -1
- package/dist/connectors/github/cli-impl.js.map +0 -1
- package/dist/connectors/github/deletion.d.ts.map +0 -1
- package/dist/connectors/github/deletion.js.map +0 -1
- package/dist/connectors/github/dlq.d.ts.map +0 -1
- package/dist/connectors/github/dlq.js.map +0 -1
- package/dist/connectors/github/idempotency.d.ts.map +0 -1
- package/dist/connectors/github/idempotency.js.map +0 -1
- package/dist/connectors/github/ingest.d.ts.map +0 -1
- package/dist/connectors/github/ingest.js.map +0 -1
- package/dist/connectors/github/octokit-client.d.ts.map +0 -1
- package/dist/connectors/github/octokit-client.js.map +0 -1
- package/dist/connectors/github/ratelimit.d.ts.map +0 -1
- package/dist/connectors/github/ratelimit.js.map +0 -1
- package/dist/connectors/github/scope.d.ts.map +0 -1
- package/dist/connectors/github/scope.js.map +0 -1
- package/dist/connectors/github/signature.d.ts.map +0 -1
- package/dist/connectors/github/signature.js.map +0 -1
- package/dist/connectors/github/tenant-routing.d.ts.map +0 -1
- package/dist/connectors/github/tenant-routing.js.map +0 -1
- package/dist/connectors/github/transform.d.ts.map +0 -1
- package/dist/connectors/github/transform.js.map +0 -1
- package/dist/connectors/github/types.d.ts.map +0 -1
- package/dist/connectors/github/types.js.map +0 -1
- package/dist/connectors/slack/backfill.d.ts.map +0 -1
- package/dist/connectors/slack/backfill.js.map +0 -1
- package/dist/connectors/slack/deletion.d.ts.map +0 -1
- package/dist/connectors/slack/deletion.js.map +0 -1
- package/dist/connectors/slack/dlq.d.ts.map +0 -1
- package/dist/connectors/slack/dlq.js.map +0 -1
- package/dist/connectors/slack/idempotency.d.ts.map +0 -1
- package/dist/connectors/slack/idempotency.js.map +0 -1
- package/dist/connectors/slack/ingest.d.ts.map +0 -1
- package/dist/connectors/slack/ingest.js.map +0 -1
- package/dist/connectors/slack/ratelimit.d.ts.map +0 -1
- package/dist/connectors/slack/ratelimit.js.map +0 -1
- package/dist/connectors/slack/scope.d.ts.map +0 -1
- package/dist/connectors/slack/scope.js.map +0 -1
- package/dist/connectors/slack/signature.d.ts.map +0 -1
- package/dist/connectors/slack/signature.js.map +0 -1
- package/dist/connectors/slack/tenant-routing.d.ts.map +0 -1
- package/dist/connectors/slack/tenant-routing.js.map +0 -1
- package/dist/connectors/slack/transform.d.ts.map +0 -1
- package/dist/connectors/slack/transform.js.map +0 -1
- package/dist/connectors/slack/types.d.ts.map +0 -1
- package/dist/connectors/slack/types.js.map +0 -1
- package/dist/connectors/slack/web-client.d.ts.map +0 -1
- package/dist/connectors/slack/web-client.js.map +0 -1
- package/dist/connectors/slack/workspaces.d.ts.map +0 -1
- package/dist/connectors/slack/workspaces.js.map +0 -1
- package/dist/consolidate.d.ts.map +0 -1
- package/dist/consolidate.js.map +0 -1
- package/dist/correction-latency.d.ts.map +0 -1
- package/dist/correction-latency.js.map +0 -1
- package/dist/customer-notes.d.ts.map +0 -1
- package/dist/customer-notes.js.map +0 -1
- package/dist/dag.d.ts.map +0 -1
- package/dist/dag.js.map +0 -1
- package/dist/dashboard.d.ts.map +0 -1
- package/dist/dashboard.js.map +0 -1
- package/dist/db.d.ts.map +0 -1
- package/dist/db.js.map +0 -1
- package/dist/decisions.d.ts.map +0 -1
- package/dist/decisions.js.map +0 -1
- package/dist/dedupe.d.ts.map +0 -1
- package/dist/dedupe.js.map +0 -1
- package/dist/embedding-provider.d.ts.map +0 -1
- package/dist/embedding-provider.js.map +0 -1
- package/dist/embeddings.d.ts.map +0 -1
- package/dist/embeddings.js.map +0 -1
- package/dist/eval-suite.d.ts.map +0 -1
- package/dist/eval-suite.js.map +0 -1
- package/dist/eval.d.ts.map +0 -1
- package/dist/eval.js.map +0 -1
- package/dist/extensions/openclaw-plugin/index.js.map +0 -1
- package/dist/extract.d.ts.map +0 -1
- package/dist/extract.js.map +0 -1
- package/dist/forward-claim-detector.d.ts.map +0 -1
- package/dist/forward-claim-detector.js.map +0 -1
- package/dist/goals.d.ts.map +0 -1
- package/dist/goals.js.map +0 -1
- package/dist/graph-extract.d.ts.map +0 -1
- package/dist/graph-extract.js.map +0 -1
- package/dist/graph-recall.d.ts.map +0 -1
- package/dist/graph-recall.js.map +0 -1
- package/dist/graph-stream.d.ts.map +0 -1
- package/dist/graph-stream.js.map +0 -1
- package/dist/graph-view.d.ts.map +0 -1
- package/dist/graph-view.js.map +0 -1
- package/dist/graph.d.ts.map +0 -1
- package/dist/graph.js.map +0 -1
- package/dist/handoff.d.ts.map +0 -1
- package/dist/handoff.js.map +0 -1
- package/dist/hooks.d.ts.map +0 -1
- package/dist/hooks.js.map +0 -1
- package/dist/importers.d.ts.map +0 -1
- package/dist/importers.js.map +0 -1
- package/dist/incidents.d.ts.map +0 -1
- package/dist/incidents.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/invalidation.d.ts.map +0 -1
- package/dist/invalidation.js.map +0 -1
- package/dist/mcp/framing.d.ts.map +0 -1
- package/dist/mcp/framing.js.map +0 -1
- package/dist/mcp/server.d.ts.map +0 -1
- package/dist/mcp/server.js.map +0 -1
- package/dist/memory-value-weights.d.ts.map +0 -1
- package/dist/memory-value-weights.js.map +0 -1
- package/dist/memory-value.d.ts.map +0 -1
- package/dist/memory-value.js.map +0 -1
- package/dist/memory.d.ts.map +0 -1
- package/dist/memory.js.map +0 -1
- package/dist/multihop.d.ts.map +0 -1
- package/dist/multihop.js.map +0 -1
- package/dist/owner-validation.d.ts.map +0 -1
- package/dist/owner-validation.js.map +0 -1
- package/dist/path-context.d.ts.map +0 -1
- package/dist/path-context.js.map +0 -1
- package/dist/physics-config.d.ts.map +0 -1
- package/dist/physics-config.js.map +0 -1
- package/dist/physics-state.d.ts.map +0 -1
- package/dist/physics-state.js.map +0 -1
- package/dist/physics.d.ts.map +0 -1
- package/dist/physics.js.map +0 -1
- package/dist/policies.d.ts.map +0 -1
- package/dist/policies.js.map +0 -1
- package/dist/postinstall.d.ts.map +0 -1
- package/dist/postinstall.js.map +0 -1
- package/dist/predictions.d.ts.map +0 -1
- package/dist/predictions.js.map +0 -1
- package/dist/processes.d.ts.map +0 -1
- package/dist/processes.js.map +0 -1
- package/dist/project-briefs.d.ts.map +0 -1
- package/dist/project-briefs.js.map +0 -1
- package/dist/project-identity.d.ts.map +0 -1
- package/dist/project-identity.js.map +0 -1
- package/dist/provenance-coverage.d.ts.map +0 -1
- package/dist/provenance-coverage.js.map +0 -1
- package/dist/rate-limit.d.ts.map +0 -1
- package/dist/rate-limit.js.map +0 -1
- package/dist/raw-archive-mirror-cleanup.d.ts.map +0 -1
- package/dist/raw-archive-mirror-cleanup.js.map +0 -1
- package/dist/raw-archive.d.ts.map +0 -1
- package/dist/raw-archive.js.map +0 -1
- package/dist/recall-history.d.ts.map +0 -1
- package/dist/recall-history.js.map +0 -1
- package/dist/recall-scope.d.ts.map +0 -1
- package/dist/recall-scope.js.map +0 -1
- package/dist/recall-trace.d.ts.map +0 -1
- package/dist/recall-trace.js.map +0 -1
- package/dist/refine-llm.d.ts.map +0 -1
- package/dist/refine-llm.js.map +0 -1
- package/dist/reject-flow.d.ts.map +0 -1
- package/dist/reject-flow.js.map +0 -1
- package/dist/rejection.d.ts.map +0 -1
- package/dist/rejection.js.map +0 -1
- package/dist/replay.d.ts.map +0 -1
- package/dist/replay.js.map +0 -1
- package/dist/rerankers/cross-encoder.d.ts.map +0 -1
- package/dist/rerankers/cross-encoder.js.map +0 -1
- package/dist/rerankers/index.d.ts.map +0 -1
- package/dist/rerankers/index.js.map +0 -1
- package/dist/rerankers/jev.d.ts.map +0 -1
- package/dist/rerankers/jev.js.map +0 -1
- package/dist/rerankers/llm.d.ts.map +0 -1
- package/dist/rerankers/llm.js.map +0 -1
- package/dist/rerankers/types.d.ts.map +0 -1
- package/dist/rerankers/types.js.map +0 -1
- package/dist/rrf.d.ts.map +0 -1
- package/dist/rrf.js.map +0 -1
- package/dist/salience.d.ts.map +0 -1
- package/dist/salience.js.map +0 -1
- package/dist/scheduler.d.ts.map +0 -1
- package/dist/scheduler.js.map +0 -1
- package/dist/scope.d.ts.map +0 -1
- package/dist/scope.js.map +0 -1
- package/dist/search.d.ts.map +0 -1
- package/dist/search.js.map +0 -1
- package/dist/secret-detect.d.ts.map +0 -1
- package/dist/secret-detect.js.map +0 -1
- package/dist/server-detect.d.ts.map +0 -1
- package/dist/server-detect.js.map +0 -1
- package/dist/server.d.ts.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/shared.d.ts.map +0 -1
- package/dist/shared.js.map +0 -1
- package/dist/skills.d.ts.map +0 -1
- package/dist/skills.js.map +0 -1
- package/dist/sleep-redact.d.ts +0 -58
- package/dist/sleep-redact.d.ts.map +0 -1
- package/dist/sleep-redact.js +0 -80
- package/dist/sleep-redact.js.map +0 -1
- package/dist/src/ablation.js +0 -138
- package/dist/src/ablation.js.map +0 -1
- package/dist/src/ambient.js +0 -148
- package/dist/src/ambient.js.map +0 -1
- package/dist/src/api.js +0 -2109
- package/dist/src/api.js.map +0 -1
- package/dist/src/audit-prune.js +0 -109
- package/dist/src/audit-prune.js.map +0 -1
- package/dist/src/audit.js +0 -213
- package/dist/src/audit.js.map +0 -1
- package/dist/src/auth.js +0 -97
- package/dist/src/auth.js.map +0 -1
- package/dist/src/autolearn.js +0 -174
- package/dist/src/autolearn.js.map +0 -1
- package/dist/src/availability.js +0 -94
- package/dist/src/availability.js.map +0 -1
- package/dist/src/capture.js +0 -1346
- package/dist/src/capture.js.map +0 -1
- package/dist/src/card-detail.js +0 -15
- package/dist/src/card-detail.js.map +0 -1
- package/dist/src/card.js +0 -19
- package/dist/src/card.js.map +0 -1
- package/dist/src/cli.js +0 -9387
- package/dist/src/cli.js.map +0 -1
- package/dist/src/client.js +0 -237
- package/dist/src/client.js.map +0 -1
- package/dist/src/compare.js +0 -122
- package/dist/src/compare.js.map +0 -1
- package/dist/src/config.js +0 -135
- package/dist/src/config.js.map +0 -1
- package/dist/src/connectors/github/backfill.js +0 -281
- package/dist/src/connectors/github/backfill.js.map +0 -1
- package/dist/src/connectors/github/cli-impl.js +0 -234
- package/dist/src/connectors/github/cli-impl.js.map +0 -1
- package/dist/src/connectors/github/deletion.js +0 -85
- package/dist/src/connectors/github/deletion.js.map +0 -1
- package/dist/src/connectors/github/dlq.js +0 -190
- package/dist/src/connectors/github/dlq.js.map +0 -1
- package/dist/src/connectors/github/idempotency.js +0 -27
- package/dist/src/connectors/github/idempotency.js.map +0 -1
- package/dist/src/connectors/github/ingest.js +0 -156
- package/dist/src/connectors/github/ingest.js.map +0 -1
- package/dist/src/connectors/github/octokit-client.js +0 -70
- package/dist/src/connectors/github/octokit-client.js.map +0 -1
- package/dist/src/connectors/github/ratelimit.js +0 -31
- package/dist/src/connectors/github/ratelimit.js.map +0 -1
- package/dist/src/connectors/github/scope.js +0 -13
- package/dist/src/connectors/github/scope.js.map +0 -1
- package/dist/src/connectors/github/signature.js +0 -81
- package/dist/src/connectors/github/signature.js.map +0 -1
- package/dist/src/connectors/github/tenant-routing.js +0 -69
- package/dist/src/connectors/github/tenant-routing.js.map +0 -1
- package/dist/src/connectors/github/transform.js +0 -103
- package/dist/src/connectors/github/transform.js.map +0 -1
- package/dist/src/connectors/github/types.js +0 -100
- package/dist/src/connectors/github/types.js.map +0 -1
- package/dist/src/connectors/slack/backfill.js +0 -78
- package/dist/src/connectors/slack/backfill.js.map +0 -1
- package/dist/src/connectors/slack/deletion.js +0 -59
- package/dist/src/connectors/slack/deletion.js.map +0 -1
- package/dist/src/connectors/slack/dlq.js +0 -224
- package/dist/src/connectors/slack/dlq.js.map +0 -1
- package/dist/src/connectors/slack/idempotency.js +0 -31
- package/dist/src/connectors/slack/idempotency.js.map +0 -1
- package/dist/src/connectors/slack/ingest.js +0 -109
- package/dist/src/connectors/slack/ingest.js.map +0 -1
- package/dist/src/connectors/slack/ratelimit.js +0 -18
- package/dist/src/connectors/slack/ratelimit.js.map +0 -1
- package/dist/src/connectors/slack/scope.js +0 -13
- package/dist/src/connectors/slack/scope.js.map +0 -1
- package/dist/src/connectors/slack/signature.js +0 -27
- package/dist/src/connectors/slack/signature.js.map +0 -1
- package/dist/src/connectors/slack/tenant-routing.js +0 -41
- package/dist/src/connectors/slack/tenant-routing.js.map +0 -1
- package/dist/src/connectors/slack/transform.js +0 -47
- package/dist/src/connectors/slack/transform.js.map +0 -1
- package/dist/src/connectors/slack/types.js +0 -35
- package/dist/src/connectors/slack/types.js.map +0 -1
- package/dist/src/connectors/slack/web-client.js +0 -43
- package/dist/src/connectors/slack/web-client.js.map +0 -1
- package/dist/src/connectors/slack/workspaces.js +0 -62
- package/dist/src/connectors/slack/workspaces.js.map +0 -1
- package/dist/src/consolidate.js +0 -978
- package/dist/src/consolidate.js.map +0 -1
- package/dist/src/correction-latency.js +0 -74
- package/dist/src/correction-latency.js.map +0 -1
- package/dist/src/customer-notes.js +0 -325
- package/dist/src/customer-notes.js.map +0 -1
- package/dist/src/dag.js +0 -352
- package/dist/src/dag.js.map +0 -1
- package/dist/src/dashboard.js +0 -258
- package/dist/src/dashboard.js.map +0 -1
- package/dist/src/db.js +0 -2731
- package/dist/src/db.js.map +0 -1
- package/dist/src/decisions.js +0 -304
- package/dist/src/decisions.js.map +0 -1
- package/dist/src/dedupe.js +0 -141
- package/dist/src/dedupe.js.map +0 -1
- package/dist/src/embedding-provider.js +0 -314
- package/dist/src/embedding-provider.js.map +0 -1
- package/dist/src/embeddings.js +0 -543
- package/dist/src/embeddings.js.map +0 -1
- package/dist/src/eval-suite.js +0 -294
- package/dist/src/eval-suite.js.map +0 -1
- package/dist/src/eval.js +0 -187
- package/dist/src/eval.js.map +0 -1
- package/dist/src/extract.js +0 -117
- package/dist/src/extract.js.map +0 -1
- package/dist/src/forward-claim-detector.js +0 -117
- package/dist/src/forward-claim-detector.js.map +0 -1
- package/dist/src/goals.js +0 -399
- package/dist/src/goals.js.map +0 -1
- package/dist/src/graph-extract.js +0 -314
- package/dist/src/graph-extract.js.map +0 -1
- package/dist/src/graph-recall.js +0 -277
- package/dist/src/graph-recall.js.map +0 -1
- package/dist/src/graph-stream.js +0 -176
- package/dist/src/graph-stream.js.map +0 -1
- package/dist/src/graph-view.js +0 -310
- package/dist/src/graph-view.js.map +0 -1
- package/dist/src/graph.js +0 -762
- package/dist/src/graph.js.map +0 -1
- package/dist/src/handoff.js +0 -65
- package/dist/src/handoff.js.map +0 -1
- package/dist/src/hooks.js +0 -926
- package/dist/src/hooks.js.map +0 -1
- package/dist/src/importers.js +0 -881
- package/dist/src/importers.js.map +0 -1
- package/dist/src/incidents.js +0 -336
- package/dist/src/incidents.js.map +0 -1
- package/dist/src/index.js +0 -32
- package/dist/src/index.js.map +0 -1
- package/dist/src/invalidation.js +0 -129
- package/dist/src/invalidation.js.map +0 -1
- package/dist/src/mcp/framing.js +0 -45
- package/dist/src/mcp/framing.js.map +0 -1
- package/dist/src/mcp/server.js +0 -1298
- package/dist/src/mcp/server.js.map +0 -1
- package/dist/src/memory-value-weights.js +0 -31
- package/dist/src/memory-value-weights.js.map +0 -1
- package/dist/src/memory-value.js +0 -261
- package/dist/src/memory-value.js.map +0 -1
- package/dist/src/memory.js +0 -425
- package/dist/src/memory.js.map +0 -1
- package/dist/src/multihop.js +0 -35
- package/dist/src/multihop.js.map +0 -1
- package/dist/src/owner-validation.js +0 -56
- package/dist/src/owner-validation.js.map +0 -1
- package/dist/src/path-context.js +0 -48
- package/dist/src/path-context.js.map +0 -1
- package/dist/src/physics-config.js +0 -26
- package/dist/src/physics-config.js.map +0 -1
- package/dist/src/physics-state.js +0 -172
- package/dist/src/physics-state.js.map +0 -1
- package/dist/src/physics.js +0 -378
- package/dist/src/physics.js.map +0 -1
- package/dist/src/policies.js +0 -414
- package/dist/src/policies.js.map +0 -1
- package/dist/src/postinstall.js +0 -101
- package/dist/src/postinstall.js.map +0 -1
- package/dist/src/predictions.js +0 -629
- package/dist/src/predictions.js.map +0 -1
- package/dist/src/processes.js +0 -349
- package/dist/src/processes.js.map +0 -1
- package/dist/src/project-briefs.js +0 -492
- package/dist/src/project-briefs.js.map +0 -1
- package/dist/src/project-identity.js +0 -200
- package/dist/src/project-identity.js.map +0 -1
- package/dist/src/provenance-coverage.js +0 -23
- package/dist/src/provenance-coverage.js.map +0 -1
- package/dist/src/rate-limit.js +0 -60
- package/dist/src/rate-limit.js.map +0 -1
- package/dist/src/raw-archive-mirror-cleanup.js +0 -55
- package/dist/src/raw-archive-mirror-cleanup.js.map +0 -1
- package/dist/src/raw-archive.js +0 -91
- package/dist/src/raw-archive.js.map +0 -1
- package/dist/src/recall-history.js +0 -235
- package/dist/src/recall-history.js.map +0 -1
- package/dist/src/recall-scope.js +0 -89
- package/dist/src/recall-scope.js.map +0 -1
- package/dist/src/recall-trace.js +0 -186
- package/dist/src/recall-trace.js.map +0 -1
- package/dist/src/refine-llm.js +0 -156
- package/dist/src/refine-llm.js.map +0 -1
- package/dist/src/reject-flow.js +0 -209
- package/dist/src/reject-flow.js.map +0 -1
- package/dist/src/rejection.js +0 -160
- package/dist/src/rejection.js.map +0 -1
- package/dist/src/replay.js +0 -122
- package/dist/src/replay.js.map +0 -1
- package/dist/src/rerankers/cross-encoder.js +0 -137
- package/dist/src/rerankers/cross-encoder.js.map +0 -1
- package/dist/src/rerankers/index.js +0 -20
- package/dist/src/rerankers/index.js.map +0 -1
- package/dist/src/rerankers/jev.js +0 -119
- package/dist/src/rerankers/jev.js.map +0 -1
- package/dist/src/rerankers/llm.js +0 -80
- package/dist/src/rerankers/llm.js.map +0 -1
- package/dist/src/rerankers/types.js +0 -2
- package/dist/src/rerankers/types.js.map +0 -1
- package/dist/src/rrf.js +0 -61
- package/dist/src/rrf.js.map +0 -1
- package/dist/src/salience.js +0 -74
- package/dist/src/salience.js.map +0 -1
- package/dist/src/scheduler.js +0 -77
- package/dist/src/scheduler.js.map +0 -1
- package/dist/src/scope.js +0 -35
- package/dist/src/scope.js.map +0 -1
- package/dist/src/search.js +0 -1003
- package/dist/src/search.js.map +0 -1
- package/dist/src/secret-detect.js +0 -95
- package/dist/src/secret-detect.js.map +0 -1
- package/dist/src/server-detect.js +0 -231
- package/dist/src/server-detect.js.map +0 -1
- package/dist/src/server.js +0 -3255
- package/dist/src/server.js.map +0 -1
- package/dist/src/shared.js +0 -502
- package/dist/src/shared.js.map +0 -1
- package/dist/src/skills.js +0 -346
- package/dist/src/skills.js.map +0 -1
- package/dist/src/sleep-redact.js +0 -80
- package/dist/src/sleep-redact.js.map +0 -1
- package/dist/src/sso.js +0 -22
- package/dist/src/sso.js.map +0 -1
- package/dist/src/stdin.js +0 -41
- package/dist/src/stdin.js.map +0 -1
- package/dist/src/store.js +0 -3749
- package/dist/src/store.js.map +0 -1
- package/dist/src/tenant.js +0 -17
- package/dist/src/tenant.js.map +0 -1
- package/dist/src/trace.js +0 -72
- package/dist/src/trace.js.map +0 -1
- package/dist/src/version.js +0 -40
- package/dist/src/version.js.map +0 -1
- package/dist/src/working-memory.js +0 -157
- package/dist/src/working-memory.js.map +0 -1
- package/dist/src/yaml.js +0 -107
- package/dist/src/yaml.js.map +0 -1
- package/dist/sso.d.ts +0 -13
- package/dist/sso.d.ts.map +0 -1
- package/dist/sso.js +0 -22
- package/dist/sso.js.map +0 -1
- package/dist/stdin.d.ts.map +0 -1
- package/dist/stdin.js.map +0 -1
- package/dist/store.d.ts.map +0 -1
- package/dist/store.js.map +0 -1
- package/dist/tenant.d.ts.map +0 -1
- package/dist/tenant.js.map +0 -1
- package/dist/trace.d.ts.map +0 -1
- package/dist/trace.js.map +0 -1
- package/dist/version.d.ts.map +0 -1
- package/dist/version.js.map +0 -1
- package/dist/working-memory.d.ts.map +0 -1
- package/dist/working-memory.js.map +0 -1
- package/dist/yaml.d.ts.map +0 -1
- package/dist/yaml.js.map +0 -1
package/dist/src/capture.js
DELETED
|
@@ -1,1346 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Capture actionable items from conversation text.
|
|
3
|
-
*
|
|
4
|
-
* Uses heuristic pattern matching (no LLM) to extract:
|
|
5
|
-
* - Decisions ("we decided", "let's do", "going with")
|
|
6
|
-
* - Specs / requirements (bullet lists after spec/feature/plan headings)
|
|
7
|
-
* - Rules / constraints ("never", "always", "the rule is", "must")
|
|
8
|
-
* - Errors / gotchas ("error:", "bug:", "gotcha:", "watch out")
|
|
9
|
-
* - Preferences ("prefer", "use X instead of Y", "don't use")
|
|
10
|
-
*/
|
|
11
|
-
import * as fs from 'fs';
|
|
12
|
-
import * as path from 'path';
|
|
13
|
-
import { createMemory, Layer } from './memory.js';
|
|
14
|
-
import { isContentWorthStoring } from './audit.js';
|
|
15
|
-
import { isInitialized, writeEntry, loadAllEntries, updateStats, saveActiveTaskSnapshot, loadActiveTaskSnapshot, } from './store.js';
|
|
16
|
-
import { getGlobalRoot, initGlobal } from './shared.js';
|
|
17
|
-
import { embedMemory } from './embeddings.js';
|
|
18
|
-
import { isEmbeddingConfigured } from './embedding-provider.js';
|
|
19
|
-
import { resolveTenantId } from './tenant.js';
|
|
20
|
-
import { defaultPreCompactLogPath } from './hooks.js';
|
|
21
|
-
import { redactSecrets } from './secret-detect.js';
|
|
22
|
-
import { RejectedValueError, checkRejectionGuard } from './rejection.js';
|
|
23
|
-
import { openHippoDb, closeHippoDb } from './db.js';
|
|
24
|
-
// Sentence-level patterns
|
|
25
|
-
//
|
|
26
|
-
// T1 (DF2): each pattern now carries TWO capture groups — group 1 is the
|
|
27
|
-
// discriminating keyword (plus its trailing separator, verbatim), group 2 is
|
|
28
|
-
// the content that follows it. Previously only the after-keyword content was
|
|
29
|
-
// captured, so a negation like "never" / "must not" was discarded and a
|
|
30
|
-
// prohibition inverted into an instruction ("Never use X" stored as "use X").
|
|
31
|
-
// `extractFromPatterns` reassembles group1 + a clause-bounded group2 (T2, via
|
|
32
|
-
// `boundToClause` below) rather than reading a single fixed-width group —
|
|
33
|
-
// group 2's own reach is widened to {1,500} because the true stopping point
|
|
34
|
-
// is now found by content, not counted characters. Keeping the keyword in
|
|
35
|
-
// its own group (rather than folding it into one bigger capture) matters:
|
|
36
|
-
// `boundToClause` must scan for a clause boundary only in group 2, never in
|
|
37
|
-
// group 1 — several keywords end in their own colon ("error:", "rule:",
|
|
38
|
-
// "decision:") which is not a clause boundary in the prose sense and would
|
|
39
|
-
// wrongly truncate the capture down to just the keyword if scanned.
|
|
40
|
-
// `PREFERENCE_PATTERNS[0]` is the one exception — its two-capture-group
|
|
41
|
-
// shape means something different (two content spans either side of
|
|
42
|
-
// "instead of"/"over"/"not") and is a separate, backlogged defect (see
|
|
43
|
-
// docs/plans/2026-08-23-df2-capture-anchoring.md); left as-is.
|
|
44
|
-
const DECISION_PATTERNS = [
|
|
45
|
-
/(?:we(?:'ve| have)?|i(?:'ve| have)?|let's)\s+(decid(?:ed|e)\s+(?:to\s+)?)(.{1,500})/i,
|
|
46
|
-
/(?:let's|we(?:'ll| will| should)?)\s+((?:go with|do|use|try|build|implement|switch to)\s+)(.{1,500})/i,
|
|
47
|
-
/((?:going|went)\s+with\s+)(.{1,500})/i,
|
|
48
|
-
/((?:the plan is|plan:)\s+)(.{1,500})/i,
|
|
49
|
-
/(decision:\s*)(.{1,500})/i,
|
|
50
|
-
];
|
|
51
|
-
const RULE_PATTERNS = [
|
|
52
|
-
/((?:never|always|must(?:\s+not)?|do(?:n't| not)\s+ever)\s+)(.{1,500})/i,
|
|
53
|
-
/((?:the rule is|rule:)\s*)(.{1,500})/i,
|
|
54
|
-
/((?:important|critical|remember):\s*)(.{1,500})/i,
|
|
55
|
-
/((?:make sure|ensure)\s+(?:to\s+)?)(.{1,500})/i,
|
|
56
|
-
];
|
|
57
|
-
const ERROR_PATTERNS = [
|
|
58
|
-
/((?:error|bug|gotcha|watch out|careful|warning|caveat|trap):\s*)(.{1,500})/i,
|
|
59
|
-
/((?:this broke|this breaks|this will break|broke because)\s+)(.{1,500})/i,
|
|
60
|
-
/((?:the (?:issue|problem|fix) (?:is|was))\s+)(.{1,500})/i,
|
|
61
|
-
/((?:don't forget|easy to miss):\s*)(.{1,500})/i,
|
|
62
|
-
];
|
|
63
|
-
// PREFERENCE_PATTERNS[0] keeps its pre-DF2 two-capture-group shape
|
|
64
|
-
// (match[1]-only, unbounded) — out of scope here, backlogged. See
|
|
65
|
-
// extractFromPatterns' reference check against this exact array element.
|
|
66
|
-
const PREFERENCE_PATTERNS = [
|
|
67
|
-
/(?:prefer|use)\s+(.{5,100})\s+(?:instead of|over|not)\s+(.{3,100})/i,
|
|
68
|
-
/((?:don't use|avoid|skip)\s+)(.{1,500})/i,
|
|
69
|
-
/((?:we(?:'re| are)\s+using|the stack is|we use)\s+)(.{1,500})/i,
|
|
70
|
-
];
|
|
71
|
-
// Heading patterns that signal a following list of specs/requirements
|
|
72
|
-
const SPEC_HEADING_PATTERNS = [
|
|
73
|
-
/^#+\s*(?:features?|requirements?|specs?|specifications?|plan|design|architecture|interface|api|todo|tasks?|implementation|notes?)(?:\s|:|$)/i,
|
|
74
|
-
/^(?:features?|requirements?|specs?|specifications?|plan|design|tasks?|implementation)(?:\s*:|$)/i,
|
|
75
|
-
];
|
|
76
|
-
// ---------------------------------------------------------------------------
|
|
77
|
-
// Extraction engine
|
|
78
|
-
// ---------------------------------------------------------------------------
|
|
79
|
-
function splitSentences(text) {
|
|
80
|
-
// Split on sentence boundaries, keeping reasonable chunks
|
|
81
|
-
return text
|
|
82
|
-
.split(/(?<=[.!?])\s+|\n/)
|
|
83
|
-
.map((s) => s.trim())
|
|
84
|
-
.filter((s) => s.length > 5);
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* T2 (DF2): bound a keyword+content capture to its clause instead of a fixed
|
|
88
|
-
* character count. `full` is `keywordPrefix + content` (already concatenated
|
|
89
|
-
* so the 200-char ceiling below applies to the whole stored string, not just
|
|
90
|
-
* the part after the keyword); `searchFrom` is `keywordPrefix.length`, so the
|
|
91
|
-
* clause/terminator scan only ever looks INSIDE `content` — several keywords
|
|
92
|
-
* end in their own colon ("error:", "rule:", "decision:") which must never
|
|
93
|
-
* be mistaken for a clause boundary in the prose that follows.
|
|
94
|
-
*
|
|
95
|
-
* Stops at the first `,`/`;`/`:` followed by whitespace, or at a sentence
|
|
96
|
-
* terminator `[.!?]` followed by whitespace or end-of-string — whichever
|
|
97
|
-
* comes first — and never past `maxLen` chars total.
|
|
98
|
-
*
|
|
99
|
-
* The whitespace requirement on the terminator is load-bearing: a bare
|
|
100
|
-
* `[.!?]` would split inside a token like `.env` / `capture.ts` / `v1.35.0`,
|
|
101
|
-
* turning a full clause into a fragment that then fails the write gate and
|
|
102
|
-
* is silently dropped (measured in the plan). The `maxLen` ceiling is also
|
|
103
|
-
* load-bearing: without it, a clause-free span can run past the 500-char
|
|
104
|
-
* gate in `extractFromPatterns` and the whole match is dropped, where today
|
|
105
|
-
* it is truncated and stored.
|
|
106
|
-
*/
|
|
107
|
-
/**
|
|
108
|
-
* Does a plausible CLOSING single quote appear after `from`? Mirror of the
|
|
109
|
-
* opener rule in `boundToClause`: a closer sits tight against the literal it
|
|
110
|
-
* ends (non-whitespace before) and is followed by whitespace, punctuation, or
|
|
111
|
-
* end-of-string - never by a letter, which is what makes "user's" an
|
|
112
|
-
* apostrophe rather than a partner.
|
|
113
|
-
*/
|
|
114
|
-
function isLetterOrDigit(ch) {
|
|
115
|
-
return ch !== undefined && /[\p{L}\p{N}]/u.test(ch);
|
|
116
|
-
}
|
|
117
|
-
function lastCloserIndex(full) {
|
|
118
|
-
// ONE pass, not one per apostrophe. The previous shape rescanned the whole
|
|
119
|
-
// remaining suffix at every boundary apostrophe, so a transcript full of
|
|
120
|
-
// elisions ("keep 'em", "wait 'til", ...) made extraction quadratic and
|
|
121
|
-
// could stall a moderately sized capture. Codex P2, r7.
|
|
122
|
-
//
|
|
123
|
-
// A quote CLOSES THE SIDE IT IS TIGHT AGAINST. The test needs both
|
|
124
|
-
// neighbours, and one round proved that empirically: these two have the
|
|
125
|
-
// same following character and opposite roles -
|
|
126
|
-
// "preserve 'a, b'-style" next '-' -> CLOSER, content on the left
|
|
127
|
-
// "then run '--force," next '-' -> OPENER, content on the right
|
|
128
|
-
// so no forward-only rule can separate them. An earlier revision tried
|
|
129
|
-
// exactly that and broke in both directions at once (codex P1+P2, r10):
|
|
130
|
-
// it missed closers before token-joining punctuation and accepted
|
|
131
|
-
// "'.env" as a closer because a dot happened to be in its class.
|
|
132
|
-
//
|
|
133
|
-
// never a closer next is a letter/digit "user's", "keep 'em"
|
|
134
|
-
// closer prev is non-whitespace "'a, b' to", "'a, b'-style"
|
|
135
|
-
// closer next is whitespace or end "preserve 'a, b ' exactly"
|
|
136
|
-
// closer next is clause punctuation "preserve 'a, b ', then"
|
|
137
|
-
// that itself ends the token
|
|
138
|
-
//
|
|
139
|
-
// The last clause is what separates ", " from ".env": a dot followed by a
|
|
140
|
-
// letter joins a filename, a dot followed by space ends a sentence.
|
|
141
|
-
for (let j = full.length - 1; j >= 0; j--) {
|
|
142
|
-
if (full[j] !== "'")
|
|
143
|
-
continue;
|
|
144
|
-
const prev = full[j - 1];
|
|
145
|
-
const next = full[j + 1];
|
|
146
|
-
if (isLetterOrDigit(next))
|
|
147
|
-
continue;
|
|
148
|
-
// "tight against content" excludes an OPENING delimiter: in
|
|
149
|
-
// "call parse('--force" the paren is non-whitespace but the quote after
|
|
150
|
-
// it is an opener, and treating it as a closer let an earlier elision
|
|
151
|
-
// pair across the clause boundary. Codex P2, r11.
|
|
152
|
-
const tightBefore = prev !== undefined && !/[\s([{]/.test(prev);
|
|
153
|
-
const endsAfter = next === undefined || /\s/.test(next);
|
|
154
|
-
// Punctuation splits in two, and this is the fact the last three
|
|
155
|
-
// revisions kept rediscovering piecemeal:
|
|
156
|
-
// , ; : ! ? ) ] } never join tokens - they end the literal whatever
|
|
157
|
-
// follows, so "'echo a, b ';then" closes at the ;
|
|
158
|
-
// . - _ / @ # DO join tokens - "'.env" and "'--force" continue a
|
|
159
|
-
// filename or flag, so these only close when trailed
|
|
160
|
-
// by whitespace
|
|
161
|
-
const afterNext = full[j + 2];
|
|
162
|
-
const closesRegardless = next !== undefined && /[,;:!?)\]}]/.test(next);
|
|
163
|
-
const joinerThenSpace = next !== undefined && /[.\-_/@#]/.test(next) &&
|
|
164
|
-
(afterNext === undefined || /\s/.test(afterNext));
|
|
165
|
-
if (tightBefore || endsAfter || closesRegardless || joinerThenSpace)
|
|
166
|
-
return j;
|
|
167
|
-
}
|
|
168
|
-
return -1;
|
|
169
|
-
}
|
|
170
|
-
function boundToClause(full, searchFrom, maxLen = 200) {
|
|
171
|
-
// Scan for the first PROSE clause boundary after `searchFrom`.
|
|
172
|
-
//
|
|
173
|
-
// Depth-awareness is not a nicety here: hippo memories are full of code, and
|
|
174
|
-
// a naive scan reintroduces the exact fragment defect this whole change
|
|
175
|
-
// exists to remove. Measured before this guard existed:
|
|
176
|
-
// "Always call build(x, y) before deploy." -> "Always call build(x"
|
|
177
|
-
// "Never pass {a: 1, b: 2} to the writer." -> "Never pass {a"
|
|
178
|
-
// Both then PASS the write gate, because they contain code punctuation and
|
|
179
|
-
// so read as "specific" — a malformed fragment stored with high confidence.
|
|
180
|
-
// Codex review finding (P1) on this branch.
|
|
181
|
-
//
|
|
182
|
-
// So: a separator only ends the clause at bracket depth zero and outside
|
|
183
|
-
// quotes. Unbalanced closers are tolerated (depth floors at 0) because
|
|
184
|
-
// captured text often starts mid-expression.
|
|
185
|
-
const lastCloser = lastCloserIndex(full);
|
|
186
|
-
let depth = 0;
|
|
187
|
-
let quote = null;
|
|
188
|
-
let cutEnd = full.length;
|
|
189
|
-
for (let i = searchFrom; i < full.length; i++) {
|
|
190
|
-
const ch = full[i];
|
|
191
|
-
if (quote) {
|
|
192
|
-
// Closing uses the SAME shape test as opening. This was asymmetric:
|
|
193
|
-
// twelve rounds went into deciding when a quote OPENS a literal, while
|
|
194
|
-
// the close accepted any bare "'" - so the apostrophe in a possessive
|
|
195
|
-
// INSIDE a literal closed it early:
|
|
196
|
-
// "Always pass 'user's a, b list' to the parser."
|
|
197
|
-
// -> "Always pass 'user's a" (master kept the whole literal)
|
|
198
|
-
// a mid-literal fragment that then PASSES the write gate, which is
|
|
199
|
-
// precisely the defect this branch exists to remove. Found by the
|
|
200
|
-
// ship-gate review after every earlier gate missed it.
|
|
201
|
-
if (ch === quote && (quote !== "'" || !isLetterOrDigit(full[i + 1]))) {
|
|
202
|
-
quote = null;
|
|
203
|
-
}
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
206
|
-
// Quote handling has to tell an APOSTROPHE from a single-quoted
|
|
207
|
-
// LITERAL, because getting either wrong reintroduces the fragment
|
|
208
|
-
// defect this change exists to remove, and both fragments PASS the
|
|
209
|
-
// write gate (code punctuation reads as "specific"):
|
|
210
|
-
// treat every ' as a quote -> "Always ensure it's enabled, then
|
|
211
|
-
// restart..." never leaves quote mode, bounding disabled entirely
|
|
212
|
-
// treat no ' as a quote -> "Always pass 'a, b' to the parser."
|
|
213
|
-
// cuts at the comma and stores "Always pass 'a"
|
|
214
|
-
// Both were codex P1s on this branch, in consecutive rounds.
|
|
215
|
-
//
|
|
216
|
-
// Discriminator: a ' OPENS a literal only at a word boundary - preceded
|
|
217
|
-
// by start/whitespace/open-bracket AND followed by non-whitespace. An
|
|
218
|
-
// in-word apostrophe ("it's", "user's") has letters on both sides and is
|
|
219
|
-
// just a character.
|
|
220
|
-
if (ch === '"' || ch === '`') {
|
|
221
|
-
quote = ch;
|
|
222
|
-
continue;
|
|
223
|
-
}
|
|
224
|
-
if (ch === "'") {
|
|
225
|
-
const prev = i > 0 ? full[i - 1] : undefined;
|
|
226
|
-
const next = full[i + 1];
|
|
227
|
-
const atBoundary = (prev === undefined || /[\s([{]/.test(prev)) &&
|
|
228
|
-
next !== undefined && !/\s/.test(next);
|
|
229
|
-
// Pairing is VERIFIED, not assumed. A word-boundary test alone still
|
|
230
|
-
// opens quote mode on elided forms ("keep 'em", "wait 'til"), which
|
|
231
|
-
// have no closer, so the scanner never leaves quote mode and bounding
|
|
232
|
-
// is disabled for the rest of the capture. Requiring an actual closing
|
|
233
|
-
// quote later in the string replaces a guess with a checkable fact -
|
|
234
|
-
// an elided form simply has no partner. Codex P2, this round.
|
|
235
|
-
// ...and the partner must LOOK like a closer, not merely be another
|
|
236
|
-
// apostrophe. Distance cannot separate the two cases - both put a `'`
|
|
237
|
-
// far downstream:
|
|
238
|
-
// "Always pass '<600-char literal>' to the parser" -> the far ' IS
|
|
239
|
-
// the closer, and pairing must succeed
|
|
240
|
-
// "keep 'em enabled, then <520 chars> check user's config" -> the far
|
|
241
|
-
// ' is in-word, and pairing against it re-opens quote mode on the
|
|
242
|
-
// elision, disabling bounding for the rest of the capture
|
|
243
|
-
// So apply the SAME shape rule already used to open a literal, mirrored:
|
|
244
|
-
// a closer has non-whitespace before it and whitespace/punctuation (not
|
|
245
|
-
// a letter) after. "user's" fails it on both counts. Codex P2, r6.
|
|
246
|
-
if (atBoundary && lastCloser > i) {
|
|
247
|
-
quote = ch;
|
|
248
|
-
}
|
|
249
|
-
continue;
|
|
250
|
-
}
|
|
251
|
-
if (ch === '(' || ch === '[' || ch === '{') {
|
|
252
|
-
depth++;
|
|
253
|
-
continue;
|
|
254
|
-
}
|
|
255
|
-
if (ch === ')' || ch === ']' || ch === '}') {
|
|
256
|
-
if (depth > 0)
|
|
257
|
-
depth--;
|
|
258
|
-
continue;
|
|
259
|
-
}
|
|
260
|
-
if (depth > 0)
|
|
261
|
-
continue;
|
|
262
|
-
const next = full[i + 1];
|
|
263
|
-
// Prose clause separator: , ; : followed by whitespace.
|
|
264
|
-
if ((ch === ',' || ch === ';' || ch === ':') && next !== undefined && /\s/.test(next)) {
|
|
265
|
-
cutEnd = i;
|
|
266
|
-
break;
|
|
267
|
-
}
|
|
268
|
-
// Sentence terminator, but only when followed by whitespace or end — a
|
|
269
|
-
// bare [.!?] splits inside .env, capture.ts, v1.35.0.
|
|
270
|
-
if ((ch === '.' || ch === '!' || ch === '?') && (next === undefined || /\s/.test(next))) {
|
|
271
|
-
cutEnd = i + 1;
|
|
272
|
-
break;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
let bounded = full.slice(0, cutEnd);
|
|
276
|
-
if (bounded.length > maxLen)
|
|
277
|
-
bounded = bounded.slice(0, maxLen);
|
|
278
|
-
return bounded;
|
|
279
|
-
}
|
|
280
|
-
function cleanExtract(raw) {
|
|
281
|
-
let content = raw
|
|
282
|
-
.replace(/^[:\s-]+/, '')
|
|
283
|
-
.replace(/[.!?,;:\s]+$/, '')
|
|
284
|
-
.trim();
|
|
285
|
-
// T2 trailing cleanup: clause-bounding can cut inside a parenthetical and
|
|
286
|
-
// leave an unmatched trailing ')' (e.g. "...(two had never got entries),"
|
|
287
|
-
// bounds to "never got entries)"). Strip a trailing ')' ONLY while closes
|
|
288
|
-
// outnumber opens in the string so far — a balanced parenthetical like
|
|
289
|
-
// "always run the suite (twice)" must be left intact.
|
|
290
|
-
while (content.endsWith(')')) {
|
|
291
|
-
const opens = (content.match(/\(/g) ?? []).length;
|
|
292
|
-
const closes = (content.match(/\)/g) ?? []).length;
|
|
293
|
-
if (closes <= opens)
|
|
294
|
-
break;
|
|
295
|
-
content = content
|
|
296
|
-
.slice(0, -1)
|
|
297
|
-
.replace(/[.!?,;:\s]+$/, '')
|
|
298
|
-
.trim();
|
|
299
|
-
}
|
|
300
|
-
return content;
|
|
301
|
-
}
|
|
302
|
-
function extractFromPatterns(sentence, patterns, category, tag) {
|
|
303
|
-
for (const pat of patterns) {
|
|
304
|
-
// `d` gives per-group offsets; see the contentStart comment below.
|
|
305
|
-
const dpat = pat.flags.includes('d') ? pat : new RegExp(pat.source, pat.flags + 'd');
|
|
306
|
-
const match = dpat.exec(sentence);
|
|
307
|
-
if (match) {
|
|
308
|
-
let bounded;
|
|
309
|
-
if (pat === PREFERENCE_PATTERNS[0]) {
|
|
310
|
-
// PREFERENCE_PATTERNS[0] is the one pattern left out of T1/T2 (see
|
|
311
|
-
// comment at its definition) — its match[1] keeps its pre-DF2,
|
|
312
|
-
// unbounded shape rather than going through clause-bounding.
|
|
313
|
-
bounded = match[1] ?? match[0];
|
|
314
|
-
}
|
|
315
|
-
else {
|
|
316
|
-
// group1 = keyword + separator (verbatim, never clause-bounded);
|
|
317
|
-
// group2 = the content that follows it (clause-bounded below).
|
|
318
|
-
//
|
|
319
|
-
// T1 preserves the keyword only when it carries SEMANTIC SIGN — a
|
|
320
|
-
// negation or modality ("never", "must not", "do not ever",
|
|
321
|
-
// "always"). Dropping those inverts the meaning, which is the whole
|
|
322
|
-
// point of T1. A LABEL keyword ("decision:", "rule:", "error:",
|
|
323
|
-
// "important:") carries no sign: it only names the category, which
|
|
324
|
-
// is already recorded in `category`/`tags`, so prefixing it onto the
|
|
325
|
-
// content is duplication that also breaks value-keyed matching
|
|
326
|
-
// (AT1's rejected-value digest hashes the bare content).
|
|
327
|
-
// Discriminator: a label ends in its own colon, or is a "the X is"
|
|
328
|
-
// phrase.
|
|
329
|
-
const rawPrefix = match[1] ?? '';
|
|
330
|
-
// ONLY colon-terminated labels are dropped. Dropping "the X is/was"
|
|
331
|
-
// too left the residue starting with "to ", which isFragment then
|
|
332
|
-
// rejected outright - so "The plan is to ship on Friday" and "The fix
|
|
333
|
-
// was to bump the pool timeout" stored NOTHING, where every prior
|
|
334
|
-
// version stored them. Silent loss on two of the highest-traffic
|
|
335
|
-
// patterns, and invisible: an absent memory leaves no trace. The AT1
|
|
336
|
-
// rejected-value evidence only ever involved colon labels
|
|
337
|
-
// ("decision: "), so the narrower rule keeps that guarantee.
|
|
338
|
-
const isLabelPrefix = /:\s*$/.test(rawPrefix);
|
|
339
|
-
const keywordPrefix = isLabelPrefix ? '' : rawPrefix;
|
|
340
|
-
// Scan the UNTRUNCATED remainder, not match[2]. The patterns cap
|
|
341
|
-
// their content group at 500 chars, so a quoted literal whose closer
|
|
342
|
-
// sits past that point had no visible partner and the pairing check
|
|
343
|
-
// read the opener as prose - cutting inside the literal. That was a
|
|
344
|
-
// blindness built into the scanner's INPUT, not a bad predicate, so
|
|
345
|
-
// no further predicate could have fixed it. boundToClause already
|
|
346
|
-
// caps its OUTPUT at maxLen, so widening the input costs nothing and
|
|
347
|
-
// makes pairing decidable on the whole sentence. Codex P2, round 5.
|
|
348
|
-
// Group 2's REAL offset, read from the regex engine. Deriving it as
|
|
349
|
-
// `match.index + rawPrefix.length` assumes group 1 starts the match,
|
|
350
|
-
// but DECISION_PATTERNS carry an uncaptured subject ("we ", "let's ")
|
|
351
|
-
// ahead of it - so the offset landed inside the keyword and the
|
|
352
|
-
// widened slice duplicated text: "We decided to pin..." stored as
|
|
353
|
-
// "decided to to pin...". Real corruption of the commonest decision
|
|
354
|
-
// capture, shipped in the previous commit. Codex P1, r6.
|
|
355
|
-
const contentStart = match.indices?.[2]?.[0] ?? -1;
|
|
356
|
-
const afterKeyword = contentStart >= 0 ? sentence.slice(contentStart) : (match[2] ?? match[0]);
|
|
357
|
-
bounded = boundToClause(keywordPrefix + afterKeyword, keywordPrefix.length);
|
|
358
|
-
}
|
|
359
|
-
const content = cleanExtract(bounded);
|
|
360
|
-
if (content.length >= 8 && content.length <= 500) {
|
|
361
|
-
return { content, category, tags: [tag, 'captured'] };
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
return null;
|
|
366
|
-
}
|
|
367
|
-
/** Extract spec items from bullet lists that follow spec-like headings. */
|
|
368
|
-
function extractSpecSections(text) {
|
|
369
|
-
const items = [];
|
|
370
|
-
const lines = text.split('\n');
|
|
371
|
-
let inSpecSection = false;
|
|
372
|
-
for (const line of lines) {
|
|
373
|
-
const trimmed = line.trim();
|
|
374
|
-
// Check if this line is a spec heading
|
|
375
|
-
if (SPEC_HEADING_PATTERNS.some((p) => p.test(trimmed))) {
|
|
376
|
-
inSpecSection = true;
|
|
377
|
-
continue;
|
|
378
|
-
}
|
|
379
|
-
// Another heading resets the section
|
|
380
|
-
if (/^#+\s/.test(trimmed) || /^[A-Z][a-z]+:$/.test(trimmed)) {
|
|
381
|
-
inSpecSection = false;
|
|
382
|
-
continue;
|
|
383
|
-
}
|
|
384
|
-
// Blank line after non-bullet content ends section
|
|
385
|
-
if (!trimmed && inSpecSection) {
|
|
386
|
-
// Keep going, blank lines within spec sections are ok
|
|
387
|
-
continue;
|
|
388
|
-
}
|
|
389
|
-
if (inSpecSection) {
|
|
390
|
-
const bulletMatch = trimmed.match(/^[-*]\s+(.+)/) || trimmed.match(/^\d+\.\s+(.+)/);
|
|
391
|
-
if (bulletMatch) {
|
|
392
|
-
const content = bulletMatch[1].trim();
|
|
393
|
-
if (content.length >= 8 && content.length <= 500) {
|
|
394
|
-
items.push({
|
|
395
|
-
content,
|
|
396
|
-
category: 'spec',
|
|
397
|
-
tags: ['spec', 'captured'],
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
return items;
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* Main extraction function. Scans text for actionable items using heuristics.
|
|
407
|
-
*/
|
|
408
|
-
export function extractFromText(text) {
|
|
409
|
-
const items = [];
|
|
410
|
-
const seen = new Set();
|
|
411
|
-
const addIfNew = (item) => {
|
|
412
|
-
const norm = item.content.toLowerCase().replace(/\s+/g, ' ').trim();
|
|
413
|
-
if (seen.has(norm))
|
|
414
|
-
return;
|
|
415
|
-
if (!isContentWorthStoring(item.content))
|
|
416
|
-
return;
|
|
417
|
-
seen.add(norm);
|
|
418
|
-
items.push(item);
|
|
419
|
-
};
|
|
420
|
-
// 1. Extract spec sections (bullet lists under spec headings)
|
|
421
|
-
for (const item of extractSpecSections(text)) {
|
|
422
|
-
addIfNew(item);
|
|
423
|
-
}
|
|
424
|
-
// 2. Pattern-match on individual sentences
|
|
425
|
-
const sentences = splitSentences(text);
|
|
426
|
-
for (const sentence of sentences) {
|
|
427
|
-
// Try each category in priority order
|
|
428
|
-
const decision = extractFromPatterns(sentence, DECISION_PATTERNS, 'decision', 'decision');
|
|
429
|
-
if (decision) {
|
|
430
|
-
addIfNew(decision);
|
|
431
|
-
continue;
|
|
432
|
-
}
|
|
433
|
-
const rule = extractFromPatterns(sentence, RULE_PATTERNS, 'rule', 'rule');
|
|
434
|
-
if (rule) {
|
|
435
|
-
addIfNew(rule);
|
|
436
|
-
continue;
|
|
437
|
-
}
|
|
438
|
-
const error = extractFromPatterns(sentence, ERROR_PATTERNS, 'error', 'error');
|
|
439
|
-
if (error) {
|
|
440
|
-
addIfNew(error);
|
|
441
|
-
continue;
|
|
442
|
-
}
|
|
443
|
-
const preference = extractFromPatterns(sentence, PREFERENCE_PATTERNS, 'preference', 'preference');
|
|
444
|
-
if (preference) {
|
|
445
|
-
addIfNew(preference);
|
|
446
|
-
continue;
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
return items;
|
|
450
|
-
}
|
|
451
|
-
// ---------------------------------------------------------------------------
|
|
452
|
-
// Normalisation for deduplication (mirrors import.ts)
|
|
453
|
-
// ---------------------------------------------------------------------------
|
|
454
|
-
function normalise(text) {
|
|
455
|
-
return text
|
|
456
|
-
.toLowerCase()
|
|
457
|
-
.replace(/[^\w\s]/g, '')
|
|
458
|
-
.replace(/\s+/g, ' ')
|
|
459
|
-
.trim();
|
|
460
|
-
}
|
|
461
|
-
function isDuplicate(content, existing) {
|
|
462
|
-
const norm = normalise(content);
|
|
463
|
-
if (!norm)
|
|
464
|
-
return true;
|
|
465
|
-
for (const e of existing) {
|
|
466
|
-
if (normalise(e.content) === norm)
|
|
467
|
-
return true;
|
|
468
|
-
}
|
|
469
|
-
return false;
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Write already-extracted items to the store, deduped against existing
|
|
473
|
-
* tenant-scoped entries. Shared write path for `cmdCapture` (extracted from
|
|
474
|
-
* raw text inline) and `cmdPreCompact` (extracted from a pre-computed tail
|
|
475
|
-
* summary, no raw-text re-extraction). Mirrors the non-dry-run write loop in
|
|
476
|
-
* `cmdCaptureCore`: same layer/source/confidence, same embed-if-configured,
|
|
477
|
-
* fire-and-forget behaviour.
|
|
478
|
-
*
|
|
479
|
-
* Returns the fire-and-forget `embedMemory` promises alongside the counts
|
|
480
|
-
* (review round X6) so a caller that must not exit before embeddings settle
|
|
481
|
-
* — `cmdPreCompact`, which runs process.exit(0) right after — can await them
|
|
482
|
-
* with a bounded timeout instead of racing a detached write.
|
|
483
|
-
*/
|
|
484
|
-
function writeExtractedItems(hippoRoot, tenantId, extracted) {
|
|
485
|
-
if (extracted.length === 0)
|
|
486
|
-
return { captured: 0, skipped: 0, rejected: 0, embeds: [] };
|
|
487
|
-
const existing = loadAllEntries(hippoRoot, tenantId);
|
|
488
|
-
const embeds = [];
|
|
489
|
-
let captured = 0;
|
|
490
|
-
let skipped = 0;
|
|
491
|
-
let rejected = 0;
|
|
492
|
-
for (const item of extracted) {
|
|
493
|
-
if (isDuplicate(item.content, existing)) {
|
|
494
|
-
skipped++;
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
const entry = createMemory(item.content, {
|
|
498
|
-
layer: Layer.Episodic,
|
|
499
|
-
tags: item.tags,
|
|
500
|
-
source: 'capture',
|
|
501
|
-
confidence: 'observed',
|
|
502
|
-
tenantId,
|
|
503
|
-
});
|
|
504
|
-
// AT1 (plan §3 containment): a refusal is per-VALUE — one rejected
|
|
505
|
-
// extraction must not abort the rest of this transcript's captures.
|
|
506
|
-
try {
|
|
507
|
-
writeEntry(hippoRoot, entry);
|
|
508
|
-
}
|
|
509
|
-
catch (err) {
|
|
510
|
-
if (err instanceof RejectedValueError) {
|
|
511
|
-
rejected++;
|
|
512
|
-
continue;
|
|
513
|
-
}
|
|
514
|
-
throw err;
|
|
515
|
-
}
|
|
516
|
-
updateStats(hippoRoot, { remembered: 1 });
|
|
517
|
-
existing.push(entry); // within-batch dedup
|
|
518
|
-
if (isEmbeddingConfigured(hippoRoot)) {
|
|
519
|
-
embeds.push(embedMemory(hippoRoot, entry).catch(() => { }));
|
|
520
|
-
}
|
|
521
|
-
captured++;
|
|
522
|
-
}
|
|
523
|
-
return { captured, skipped, rejected, embeds };
|
|
524
|
-
}
|
|
525
|
-
/**
|
|
526
|
-
* Runtime shape guards used throughout this file wherever a value arrives
|
|
527
|
-
* unparsed (JSONL transcript records, stdout/stderr write() chunks). Generic
|
|
528
|
-
* over the input so the parameter is never annotated `unknown` directly — TS
|
|
529
|
-
* infers it from the call site — while the check itself avoids `typeof` by
|
|
530
|
-
* testing identity against the coercion (`String(x) === x`) /
|
|
531
|
-
* prototype-chain (`instanceof Object`) instead. Behaviourally equivalent to
|
|
532
|
-
* `typeof x === 'string'` / a truthy `typeof x === 'object'` check for
|
|
533
|
-
* anything `JSON.parse` can produce (the only divergence is boxed
|
|
534
|
-
* primitives, which JSON.parse never yields).
|
|
535
|
-
*/
|
|
536
|
-
function isStringValue(value) {
|
|
537
|
-
return String(value) === value;
|
|
538
|
-
}
|
|
539
|
-
function isObjectLike(value) {
|
|
540
|
-
return value !== null && value instanceof Object;
|
|
541
|
-
}
|
|
542
|
-
/** Message for a caught value of unknown shape. `cause` names the sanctioned unknown-input case (error-cause enrichment). */
|
|
543
|
-
function errorMessage(cause) {
|
|
544
|
-
return cause instanceof Error ? cause.message : String(cause);
|
|
545
|
-
}
|
|
546
|
-
/**
|
|
547
|
-
* Build a compact text summary from a Claude Code / OpenCode JSONL transcript.
|
|
548
|
-
* Keeps plain user messages and the final chunk of assistant text, drops
|
|
549
|
-
* thinking blocks, tool_use, and tool_result noise. Output is fed to the
|
|
550
|
-
* existing `extractFromText` pipeline.
|
|
551
|
-
*
|
|
552
|
-
* Exported for tests.
|
|
553
|
-
*/
|
|
554
|
-
export function summariseTranscript(jsonl) {
|
|
555
|
-
const lines = jsonl.split('\n').filter((l) => l.trim());
|
|
556
|
-
const userMessages = [];
|
|
557
|
-
const assistantTexts = [];
|
|
558
|
-
for (const line of lines) {
|
|
559
|
-
let entry;
|
|
560
|
-
try {
|
|
561
|
-
entry = JSON.parse(line);
|
|
562
|
-
}
|
|
563
|
-
catch {
|
|
564
|
-
continue;
|
|
565
|
-
}
|
|
566
|
-
if (!isObjectLike(entry))
|
|
567
|
-
continue;
|
|
568
|
-
if (('type' in entry) && (entry.type === 'user' || entry.type === 'assistant')) {
|
|
569
|
-
const message = 'message' in entry && isObjectLike(entry.message) ? entry.message : undefined;
|
|
570
|
-
if (!message)
|
|
571
|
-
continue;
|
|
572
|
-
const content = 'content' in message ? message.content : undefined;
|
|
573
|
-
if (entry.type === 'user') {
|
|
574
|
-
// Plain text user messages only (skip tool_result arrays)
|
|
575
|
-
if (isStringValue(content) && content.trim()) {
|
|
576
|
-
userMessages.push(content.trim());
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
else if (Array.isArray(content)) {
|
|
580
|
-
// Keep assistant text blocks; drop thinking + tool_use
|
|
581
|
-
const chunks = [];
|
|
582
|
-
for (const block of content) {
|
|
583
|
-
if (isObjectLike(block)) {
|
|
584
|
-
const blockText = 'type' in block && block.type === 'text' && 'text' in block ? block.text : undefined;
|
|
585
|
-
if (isStringValue(blockText) && blockText.trim()) {
|
|
586
|
-
chunks.push(blockText.trim());
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
if (chunks.length > 0) {
|
|
591
|
-
assistantTexts.push(chunks.join('\n'));
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
continue;
|
|
595
|
-
}
|
|
596
|
-
// Codex rollout transcript shape: response_item -> payload.message
|
|
597
|
-
if ('type' in entry && entry.type === 'response_item') {
|
|
598
|
-
const payload = 'payload' in entry && isObjectLike(entry.payload) ? entry.payload : undefined;
|
|
599
|
-
if (!payload || !('type' in payload) || payload.type !== 'message')
|
|
600
|
-
continue;
|
|
601
|
-
const role = 'role' in payload ? payload.role : undefined;
|
|
602
|
-
const content = 'content' in payload ? payload.content : undefined;
|
|
603
|
-
if (!Array.isArray(content))
|
|
604
|
-
continue;
|
|
605
|
-
const chunks = [];
|
|
606
|
-
for (const block of content) {
|
|
607
|
-
if (!isObjectLike(block))
|
|
608
|
-
continue;
|
|
609
|
-
const blockType = 'type' in block ? block.type : undefined;
|
|
610
|
-
const blockText = 'text' in block ? block.text : undefined;
|
|
611
|
-
if (role === 'user' && blockType === 'input_text' && isStringValue(blockText) && blockText.trim()) {
|
|
612
|
-
chunks.push(blockText.trim());
|
|
613
|
-
}
|
|
614
|
-
if (role === 'assistant' && blockType === 'output_text' && isStringValue(blockText) && blockText.trim()) {
|
|
615
|
-
chunks.push(blockText.trim());
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
if (chunks.length === 0)
|
|
619
|
-
continue;
|
|
620
|
-
if (role === 'user')
|
|
621
|
-
userMessages.push(chunks.join('\n'));
|
|
622
|
-
if (role === 'assistant')
|
|
623
|
-
assistantTexts.push(chunks.join('\n'));
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
if (userMessages.length === 0 && assistantTexts.length === 0)
|
|
627
|
-
return '';
|
|
628
|
-
// Keep the tail: last ~20 user turns and last ~10 assistant replies.
|
|
629
|
-
// Session-end is about what was decided near the end, not at the start.
|
|
630
|
-
const tailUsers = userMessages.slice(-20);
|
|
631
|
-
const tailAssistants = assistantTexts.slice(-10);
|
|
632
|
-
return [
|
|
633
|
-
'# Session Summary',
|
|
634
|
-
'',
|
|
635
|
-
'## User Messages',
|
|
636
|
-
...tailUsers.map((m) => `- ${m.replace(/\s+/g, ' ').slice(0, 500)}`),
|
|
637
|
-
'',
|
|
638
|
-
'## Assistant Responses',
|
|
639
|
-
...tailAssistants.map((t) => t.slice(0, 2000)),
|
|
640
|
-
].join('\n');
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Resolve a transcript path for `--last-session`.
|
|
644
|
-
*
|
|
645
|
-
* Priority, where the first source present is the only one tried:
|
|
646
|
-
* 1. Explicit `transcriptPath` option (from `--transcript <path>`)
|
|
647
|
-
* 2. Stdin JSON payload (Claude Code / OpenCode SessionEnd hook shape)
|
|
648
|
-
* 3. Most recent `.jsonl` under `~/.claude/projects/<any>/`, only on a proven manual run (no path, no stdin text, no timed-out read), because this scan spans every project on the box
|
|
649
|
-
*
|
|
650
|
-
* Returns null when nothing resolves, a named transcript or payload whose file is missing included. Never throws.
|
|
651
|
-
*/
|
|
652
|
-
export function resolveLastSessionTranscript(explicit, stdinText, stdinTimedOut = false) {
|
|
653
|
-
if (explicit)
|
|
654
|
-
return fs.existsSync(explicit) ? explicit : null;
|
|
655
|
-
if (stdinText && stdinText.trim() !== '') {
|
|
656
|
-
try {
|
|
657
|
-
const payload = JSON.parse(stdinText);
|
|
658
|
-
if (isObjectLike(payload) && 'transcript_path' in payload) {
|
|
659
|
-
const tp = payload.transcript_path;
|
|
660
|
-
if (isStringValue(tp) && fs.existsSync(tp))
|
|
661
|
-
return tp;
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
catch {
|
|
665
|
-
// not JSON, but still a payload, so no scan
|
|
666
|
-
}
|
|
667
|
-
return null;
|
|
668
|
-
}
|
|
669
|
-
if (stdinTimedOut)
|
|
670
|
-
return null;
|
|
671
|
-
const home = process.env.HOME || process.env.USERPROFILE;
|
|
672
|
-
if (!home)
|
|
673
|
-
return null;
|
|
674
|
-
const projectsDir = path.join(home, '.claude', 'projects');
|
|
675
|
-
if (!fs.existsSync(projectsDir))
|
|
676
|
-
return null;
|
|
677
|
-
let newest = null;
|
|
678
|
-
try {
|
|
679
|
-
for (const entry of fs.readdirSync(projectsDir)) {
|
|
680
|
-
const subDir = path.join(projectsDir, entry);
|
|
681
|
-
const stat = fs.statSync(subDir);
|
|
682
|
-
if (!stat.isDirectory())
|
|
683
|
-
continue;
|
|
684
|
-
for (const file of fs.readdirSync(subDir)) {
|
|
685
|
-
if (!file.endsWith('.jsonl'))
|
|
686
|
-
continue;
|
|
687
|
-
const full = path.join(subDir, file);
|
|
688
|
-
const m = fs.statSync(full).mtimeMs;
|
|
689
|
-
if (!newest || m > newest.mtime)
|
|
690
|
-
newest = { path: full, mtime: m };
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
catch {
|
|
695
|
-
return null;
|
|
696
|
-
}
|
|
697
|
-
return newest?.path ?? null;
|
|
698
|
-
}
|
|
699
|
-
export function cmdCapture(hippoRoot, options) {
|
|
700
|
-
// Tee stdout/stderr to a log file when --log-file is set. Used by the
|
|
701
|
-
// SessionEnd hook so output (otherwise swallowed by TUI teardown) surfaces
|
|
702
|
-
// on the next session start via `hippo last-sleep`. Runs second in the
|
|
703
|
-
// SessionEnd sequence after `hippo sleep`, so we APPEND rather than
|
|
704
|
-
// truncate — sleep already wrote its own header + body to this file.
|
|
705
|
-
const restoreStdio = options.logFile ? beginLogTee(options.logFile) : null;
|
|
706
|
-
try {
|
|
707
|
-
cmdCaptureCore(hippoRoot, options);
|
|
708
|
-
if (options.logFile)
|
|
709
|
-
console.log('[hippo] capture complete');
|
|
710
|
-
}
|
|
711
|
-
catch (err) {
|
|
712
|
-
if (options.logFile)
|
|
713
|
-
console.log(`[hippo] capture failed: ${errorMessage(err)}`);
|
|
714
|
-
throw err;
|
|
715
|
-
}
|
|
716
|
-
finally {
|
|
717
|
-
if (restoreStdio)
|
|
718
|
-
restoreStdio();
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
/**
|
|
722
|
-
* Append-mode tee: writes a banner line then mirrors every stdout/stderr
|
|
723
|
-
* chunk to `logFile` until the returned restore function is called.
|
|
724
|
-
* Failures to write the log are non-fatal; the real streams still get
|
|
725
|
-
* the data.
|
|
726
|
-
*/
|
|
727
|
-
function beginLogTee(logFile) {
|
|
728
|
-
try {
|
|
729
|
-
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
730
|
-
fs.appendFileSync(logFile, `[hippo] ${new Date().toISOString()} capturing session...\n`, 'utf8');
|
|
731
|
-
}
|
|
732
|
-
catch (err) {
|
|
733
|
-
console.error(`[hippo] warning: could not open log file ${logFile}: ${errorMessage(err)}`);
|
|
734
|
-
return () => { };
|
|
735
|
-
}
|
|
736
|
-
const origStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
737
|
-
const origStderrWrite = process.stderr.write.bind(process.stderr);
|
|
738
|
-
const tee = (chunk) => {
|
|
739
|
-
try {
|
|
740
|
-
const buf = isStringValue(chunk) ? chunk : Buffer.from(chunk).toString('utf8');
|
|
741
|
-
fs.appendFileSync(logFile, buf, 'utf8');
|
|
742
|
-
}
|
|
743
|
-
catch {
|
|
744
|
-
// log failures are non-fatal
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
const wrapWrite = (origWrite) => {
|
|
748
|
-
const wrapped = (...args) => {
|
|
749
|
-
tee(args[0]);
|
|
750
|
-
// SAFETY: forwarding the exact arguments Node's real overloaded
|
|
751
|
-
// `write` received is safe regardless of which overload the call
|
|
752
|
-
// site used — Node dispatches on the actual argument shapes at
|
|
753
|
-
// runtime, and `StreamWriteArgs` is the union of both overloads'
|
|
754
|
-
// parameter lists.
|
|
755
|
-
return origWrite(...args);
|
|
756
|
-
};
|
|
757
|
-
// SAFETY: `wrapped` matches both real `write` overload shapes it's
|
|
758
|
-
// assigned to; TS can't verify a single implementation covers an
|
|
759
|
-
// overloaded type, but this one forwards to the real stream method.
|
|
760
|
-
return wrapped;
|
|
761
|
-
};
|
|
762
|
-
process.stdout.write = wrapWrite(origStdoutWrite);
|
|
763
|
-
process.stderr.write = wrapWrite(origStderrWrite);
|
|
764
|
-
return () => {
|
|
765
|
-
process.stdout.write = origStdoutWrite;
|
|
766
|
-
process.stderr.write = origStderrWrite;
|
|
767
|
-
};
|
|
768
|
-
}
|
|
769
|
-
function cmdCaptureCore(hippoRoot, options) {
|
|
770
|
-
const useGlobal = options.global;
|
|
771
|
-
const targetRoot = useGlobal ? getGlobalRoot() : hippoRoot;
|
|
772
|
-
if (useGlobal) {
|
|
773
|
-
initGlobal();
|
|
774
|
-
}
|
|
775
|
-
else {
|
|
776
|
-
if (!isInitialized(hippoRoot)) {
|
|
777
|
-
console.error(`No hippo store at ${hippoRoot} (searched ${process.cwd()} and its parents up to your home directory). Run \`hippo init\` first.`);
|
|
778
|
-
process.exit(1);
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
// Read input text
|
|
782
|
-
let text;
|
|
783
|
-
switch (options.source) {
|
|
784
|
-
case 'stdin': {
|
|
785
|
-
try {
|
|
786
|
-
text = fs.readFileSync(0, 'utf8');
|
|
787
|
-
}
|
|
788
|
-
catch {
|
|
789
|
-
console.error('No input on stdin. Pipe text in or use --file <path>.');
|
|
790
|
-
process.exit(1);
|
|
791
|
-
}
|
|
792
|
-
break;
|
|
793
|
-
}
|
|
794
|
-
case 'file': {
|
|
795
|
-
if (!options.filePath) {
|
|
796
|
-
console.error('Missing file path. Usage: hippo capture --file <path>');
|
|
797
|
-
process.exit(1);
|
|
798
|
-
}
|
|
799
|
-
if (!fs.existsSync(options.filePath)) {
|
|
800
|
-
console.error(`File not found: ${options.filePath}`);
|
|
801
|
-
process.exit(1);
|
|
802
|
-
}
|
|
803
|
-
text = fs.readFileSync(options.filePath, 'utf8');
|
|
804
|
-
break;
|
|
805
|
-
}
|
|
806
|
-
case 'last-session': {
|
|
807
|
-
const resolved = resolveLastSessionTranscript(options.transcriptPath, options.stdinText, options.stdinTimedOut);
|
|
808
|
-
if (!resolved) {
|
|
809
|
-
console.log('No transcript found. Pass --transcript <path> or run from a SessionEnd hook.');
|
|
810
|
-
return;
|
|
811
|
-
}
|
|
812
|
-
const jsonl = fs.readFileSync(resolved, 'utf8');
|
|
813
|
-
text = summariseTranscript(jsonl);
|
|
814
|
-
if (!text) {
|
|
815
|
-
console.log('Transcript had no user/assistant messages to summarise.');
|
|
816
|
-
return;
|
|
817
|
-
}
|
|
818
|
-
break;
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
if (!text || text.trim().length === 0) {
|
|
822
|
-
console.log('No text to capture from.');
|
|
823
|
-
return;
|
|
824
|
-
}
|
|
825
|
-
// Extract items
|
|
826
|
-
const extracted = extractFromText(text);
|
|
827
|
-
if (extracted.length === 0) {
|
|
828
|
-
console.log('No actionable items found in the input.');
|
|
829
|
-
return;
|
|
830
|
-
}
|
|
831
|
-
// Load existing for dedup. L9: when options.tenantId is set on a non-global
|
|
832
|
-
// capture, scope the dedup read so tenant A's captures don't get suppressed
|
|
833
|
-
// by tenant B's existing content. Undefined preserves host-wide behaviour.
|
|
834
|
-
const existing = loadAllEntries(targetRoot, useGlobal ? undefined : options.tenantId);
|
|
835
|
-
let captured = 0;
|
|
836
|
-
let skipped = 0;
|
|
837
|
-
let rejected = 0;
|
|
838
|
-
// AT1 P2 fix (dry-run parity, docs/plans/2026-08-15-at1-rejected-value-tombstone.md):
|
|
839
|
-
// dry-run used to skip the guarded write branch ENTIRELY, so a tombstoned
|
|
840
|
-
// extraction printed as `[capture]` and counted toward `captured` — the
|
|
841
|
-
// preview lied about what a real run would do. Mirrors importers.ts's
|
|
842
|
-
// importEntries dry-run probe (commit 6146e82): open a read-only handle
|
|
843
|
-
// once, run the same checkRejectionGuard the real write path uses via
|
|
844
|
-
// writeEntry, never write anything.
|
|
845
|
-
const dryRunDb = options.dryRun ? openHippoDb(targetRoot) : null;
|
|
846
|
-
try {
|
|
847
|
-
for (const item of extracted) {
|
|
848
|
-
if (isDuplicate(item.content, existing)) {
|
|
849
|
-
skipped++;
|
|
850
|
-
if (options.dryRun) {
|
|
851
|
-
console.log(` [skip] (${item.category}) ${item.content.slice(0, 80)}`);
|
|
852
|
-
}
|
|
853
|
-
continue;
|
|
854
|
-
}
|
|
855
|
-
// A3: kind defaults to 'distilled'. capture.ts extracts curated items from
|
|
856
|
-
// session output (not raw transcript chunks), so distilled is correct. If a
|
|
857
|
-
// future variant captures full raw session text, it MUST set kind: 'raw'
|
|
858
|
-
// and route deletions through archiveRawMemory(). See MEMORY_ENVELOPE.md.
|
|
859
|
-
// L9: the dedup read above is scoped by options.tenantId — the WRITE
|
|
860
|
-
// must match, or scoped-dedup-passes-then-default-tenant-write breaks
|
|
861
|
-
// the per-tenant contract. Mirror the dedup-read guard: when
|
|
862
|
-
// global: true, the global store is host-wide and tenant is irrelevant
|
|
863
|
-
// (createMemory's default 'default' applies). When global: false,
|
|
864
|
-
// options.tenantId scopes the write to the same tenant as the dedup.
|
|
865
|
-
const entry = createMemory(item.content, {
|
|
866
|
-
layer: Layer.Episodic,
|
|
867
|
-
tags: item.tags,
|
|
868
|
-
source: 'capture',
|
|
869
|
-
confidence: 'observed',
|
|
870
|
-
tenantId: useGlobal ? undefined : options.tenantId,
|
|
871
|
-
});
|
|
872
|
-
if (options.dryRun) {
|
|
873
|
-
if (dryRunDb) {
|
|
874
|
-
try {
|
|
875
|
-
checkRejectionGuard(dryRunDb, entry.tenantId ?? 'default', entry.id, entry.content);
|
|
876
|
-
}
|
|
877
|
-
catch (err) {
|
|
878
|
-
if (err instanceof RejectedValueError) {
|
|
879
|
-
rejected++;
|
|
880
|
-
console.log(` [reject] (${item.category}) ${item.content.slice(0, 80)} - matches a rejected value`);
|
|
881
|
-
continue;
|
|
882
|
-
}
|
|
883
|
-
throw err;
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
console.log(` [capture] (${item.category}) ${item.content}`);
|
|
887
|
-
}
|
|
888
|
-
else {
|
|
889
|
-
// AT1 (plan §3 containment): one rejected item must not abort the
|
|
890
|
-
// rest of this capture's items.
|
|
891
|
-
try {
|
|
892
|
-
writeEntry(targetRoot, entry);
|
|
893
|
-
}
|
|
894
|
-
catch (err) {
|
|
895
|
-
if (err instanceof RejectedValueError) {
|
|
896
|
-
rejected++;
|
|
897
|
-
continue;
|
|
898
|
-
}
|
|
899
|
-
throw err;
|
|
900
|
-
}
|
|
901
|
-
updateStats(targetRoot, { remembered: 1 });
|
|
902
|
-
existing.push(entry); // within-batch dedup
|
|
903
|
-
if (isEmbeddingConfigured(targetRoot)) {
|
|
904
|
-
embedMemory(targetRoot, entry).catch(() => { });
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
captured++;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
finally {
|
|
911
|
-
if (dryRunDb)
|
|
912
|
-
closeHippoDb(dryRunDb);
|
|
913
|
-
}
|
|
914
|
-
const prefix = options.dryRun ? '[dry-run] ' : '';
|
|
915
|
-
const globalPrefix = useGlobal ? '[global] ' : '';
|
|
916
|
-
console.log(`\n${prefix}${globalPrefix}Captured ${captured} items (${skipped} skipped as duplicates` +
|
|
917
|
-
(rejected > 0 ? `, ${rejected} rejected` : '') +
|
|
918
|
-
')');
|
|
919
|
-
}
|
|
920
|
-
// ---------------------------------------------------------------------------
|
|
921
|
-
// `hippo pre-compact` — PreCompact hook producer
|
|
922
|
-
// ---------------------------------------------------------------------------
|
|
923
|
-
/** Never read the whole transcript — PreCompact fires exactly when it's largest. */
|
|
924
|
-
export const PRE_COMPACT_TAIL_BYTES = 256 * 1024;
|
|
925
|
-
export const PRE_COMPACT_TASK_CAP = 200;
|
|
926
|
-
export const PRE_COMPACT_SUMMARY_CAP = 2000;
|
|
927
|
-
export const PRE_COMPACT_NEXT_STEP_CAP = 500;
|
|
928
|
-
/**
|
|
929
|
-
* Truncate `text` to at most `maxChars` UTF-16 code units without splitting
|
|
930
|
-
* a surrogate pair at the boundary. A plain `slice(0, n)` can land between a
|
|
931
|
-
* high and low surrogate, leaving an unpaired surrogate in a stored/
|
|
932
|
-
* re-injected snapshot field. If the code unit at the cut point is a high
|
|
933
|
-
* surrogate (0xD800-0xDBFF), back off one unit so the pair stays whole.
|
|
934
|
-
*/
|
|
935
|
-
export function truncateCodePointSafe(text, maxChars) {
|
|
936
|
-
if (text.length <= maxChars)
|
|
937
|
-
return text;
|
|
938
|
-
let end = maxChars;
|
|
939
|
-
if (end > 0) {
|
|
940
|
-
const code = text.charCodeAt(end - 1);
|
|
941
|
-
if (code >= 0xd800 && code <= 0xdbff)
|
|
942
|
-
end -= 1;
|
|
943
|
-
}
|
|
944
|
-
return text.slice(0, end);
|
|
945
|
-
}
|
|
946
|
-
/**
|
|
947
|
-
* Cap from the RECENT end: summariseTranscript emits user turns oldest-to-
|
|
948
|
-
* newest with assistant responses after them, so a head-first cap keeps
|
|
949
|
-
* stale context and drops exactly the newest working state this feature
|
|
950
|
-
* exists to preserve. Keep the LAST maxChars instead, aligned forward to a
|
|
951
|
-
* nearby line start, with a trim marker (codex round 3).
|
|
952
|
-
*/
|
|
953
|
-
export function truncateKeepNewest(text, maxChars) {
|
|
954
|
-
if (text.length <= maxChars)
|
|
955
|
-
return text;
|
|
956
|
-
let start = text.length - maxChars;
|
|
957
|
-
const code = text.charCodeAt(start);
|
|
958
|
-
if (code >= 0xdc00 && code <= 0xdfff)
|
|
959
|
-
start += 1; // never start on a low surrogate
|
|
960
|
-
const nl = text.indexOf('\n', start);
|
|
961
|
-
if (nl !== -1 && nl + 1 < text.length && nl - start < 200)
|
|
962
|
-
start = nl + 1;
|
|
963
|
-
return '[...earlier turns trimmed]\n' + text.slice(start);
|
|
964
|
-
}
|
|
965
|
-
/**
|
|
966
|
-
* Positional read of the last `capBytes` of `transcriptPath`, aligned
|
|
967
|
-
* forward to the first complete JSONL line. Uses fs.openSync/readSync at a
|
|
968
|
-
* byte offset rather than reading the whole file and slicing — PreCompact
|
|
969
|
-
* fires exactly when transcripts are largest, so a whole-file read is the
|
|
970
|
-
* one thing this path cannot do.
|
|
971
|
-
*
|
|
972
|
-
* Boundary handling (X14): a seek that lands mid-line must drop that
|
|
973
|
-
* partial first line so every remaining line parses as complete JSON. A
|
|
974
|
-
* seek that lands exactly after a '\n' already starts on a complete line
|
|
975
|
-
* and must NOT drop it — doing so would silently discard one whole line on
|
|
976
|
-
* every tail read whose start offset happens to align with a line break.
|
|
977
|
-
* Distinguished by peeking at the single byte immediately before `start`.
|
|
978
|
-
*/
|
|
979
|
-
export function readTranscriptTail(transcriptPath, capBytes = PRE_COMPACT_TAIL_BYTES) {
|
|
980
|
-
const size = fs.statSync(transcriptPath).size;
|
|
981
|
-
const start = Math.max(0, size - capBytes);
|
|
982
|
-
const length = size - start;
|
|
983
|
-
if (length <= 0)
|
|
984
|
-
return '';
|
|
985
|
-
const fd = fs.openSync(transcriptPath, 'r');
|
|
986
|
-
try {
|
|
987
|
-
let onLineBoundary = start === 0;
|
|
988
|
-
if (!onLineBoundary) {
|
|
989
|
-
const prevByte = Buffer.alloc(1);
|
|
990
|
-
fs.readSync(fd, prevByte, 0, 1, start - 1);
|
|
991
|
-
onLineBoundary = prevByte[0] === 0x0a; // '\n'
|
|
992
|
-
}
|
|
993
|
-
const buf = Buffer.alloc(length);
|
|
994
|
-
fs.readSync(fd, buf, 0, length, start);
|
|
995
|
-
let text = buf.toString('utf8');
|
|
996
|
-
if (!onLineBoundary) {
|
|
997
|
-
// Landed mid-line — drop the partial first line so every remaining
|
|
998
|
-
// line parses as complete JSON.
|
|
999
|
-
const nl = text.indexOf('\n');
|
|
1000
|
-
text = nl === -1 ? '' : text.slice(nl + 1);
|
|
1001
|
-
}
|
|
1002
|
-
return text;
|
|
1003
|
-
}
|
|
1004
|
-
finally {
|
|
1005
|
-
fs.closeSync(fd);
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
/** Most recent plain-text user message in a JSONL tail. Claude Code transcript shape only (PreCompact is claude-code-only). */
|
|
1009
|
-
function lastPlainUserMessage(jsonl) {
|
|
1010
|
-
const lines = jsonl.split('\n').filter((l) => l.trim());
|
|
1011
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1012
|
-
let entry;
|
|
1013
|
-
try {
|
|
1014
|
-
entry = JSON.parse(lines[i]);
|
|
1015
|
-
}
|
|
1016
|
-
catch {
|
|
1017
|
-
continue;
|
|
1018
|
-
}
|
|
1019
|
-
if (!isObjectLike(entry))
|
|
1020
|
-
continue;
|
|
1021
|
-
if (!('type' in entry) || entry.type !== 'user')
|
|
1022
|
-
continue;
|
|
1023
|
-
// Meta/sidechain lines carry type:'user' but are not the human: after a
|
|
1024
|
-
// FIRST compaction the transcript holds the compact summary as an isMeta
|
|
1025
|
-
// user line, and sub-agent turns are isSidechain — deriving "task" from
|
|
1026
|
-
// either yields junk on every later compaction.
|
|
1027
|
-
if (('isMeta' in entry && entry.isMeta === true) || ('isSidechain' in entry && entry.isSidechain === true))
|
|
1028
|
-
continue;
|
|
1029
|
-
const message = 'message' in entry && isObjectLike(entry.message) ? entry.message : undefined;
|
|
1030
|
-
if (!message)
|
|
1031
|
-
continue;
|
|
1032
|
-
const content = 'content' in message ? message.content : undefined;
|
|
1033
|
-
if (isStringValue(content) && content.trim())
|
|
1034
|
-
return content.trim();
|
|
1035
|
-
}
|
|
1036
|
-
return '';
|
|
1037
|
-
}
|
|
1038
|
-
/** Last assistant text block in a JSONL tail (skips thinking + tool_use, same as summariseTranscript). */
|
|
1039
|
-
function lastAssistantTextBlock(jsonl) {
|
|
1040
|
-
const lines = jsonl.split('\n').filter((l) => l.trim());
|
|
1041
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1042
|
-
let entry;
|
|
1043
|
-
try {
|
|
1044
|
-
entry = JSON.parse(lines[i]);
|
|
1045
|
-
}
|
|
1046
|
-
catch {
|
|
1047
|
-
continue;
|
|
1048
|
-
}
|
|
1049
|
-
if (!isObjectLike(entry))
|
|
1050
|
-
continue;
|
|
1051
|
-
if (!('type' in entry) || entry.type !== 'assistant')
|
|
1052
|
-
continue;
|
|
1053
|
-
// Same meta/sidechain guard as lastPlainUserMessage: sub-agent turns
|
|
1054
|
-
// (isSidechain) are not this session's next step.
|
|
1055
|
-
if (('isMeta' in entry && entry.isMeta === true) || ('isSidechain' in entry && entry.isSidechain === true))
|
|
1056
|
-
continue;
|
|
1057
|
-
const message = 'message' in entry && isObjectLike(entry.message) ? entry.message : undefined;
|
|
1058
|
-
if (!message)
|
|
1059
|
-
continue;
|
|
1060
|
-
const content = 'content' in message ? message.content : undefined;
|
|
1061
|
-
if (!Array.isArray(content))
|
|
1062
|
-
continue;
|
|
1063
|
-
for (let j = content.length - 1; j >= 0; j--) {
|
|
1064
|
-
const block = content[j];
|
|
1065
|
-
if (isObjectLike(block)) {
|
|
1066
|
-
const blockText = 'type' in block && block.type === 'text' && 'text' in block ? block.text : undefined;
|
|
1067
|
-
if (isStringValue(blockText) && blockText.trim()) {
|
|
1068
|
-
return blockText.trim();
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
return '';
|
|
1074
|
-
}
|
|
1075
|
-
// Diagnostic-only log; a long-lived install must not grow it unbounded.
|
|
1076
|
-
const PRE_COMPACT_LOG_MAX_BYTES = 256 * 1024;
|
|
1077
|
-
/**
|
|
1078
|
-
* Log-forgery guard: messages here interpolate payload-controlled values
|
|
1079
|
-
* (transcript paths, session ids). Strip C0 control chars — newlines above
|
|
1080
|
-
* all — so a crafted value can't inject fake `[hippo] ...` log lines.
|
|
1081
|
-
* Exported for every `[hippo]`-prefixed log writer that interpolates
|
|
1082
|
-
* payload-controlled values (cli.ts appendSessionEndCloseLog) — one shared
|
|
1083
|
-
* guard, not per-file copies.
|
|
1084
|
-
*/
|
|
1085
|
-
export function sanitizeLogMessage(message) {
|
|
1086
|
-
// eslint-disable-next-line no-control-regex
|
|
1087
|
-
return message.replace(/[\x00-\x1f]/g, '');
|
|
1088
|
-
}
|
|
1089
|
-
function appendPreCompactLog(logFile, message) {
|
|
1090
|
-
try {
|
|
1091
|
-
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
1092
|
-
const stat = fs.existsSync(logFile) ? fs.statSync(logFile) : null;
|
|
1093
|
-
if (stat && stat.size > PRE_COMPACT_LOG_MAX_BYTES) {
|
|
1094
|
-
fs.writeFileSync(logFile, '', 'utf8'); // start fresh — dumb cap, no rotation
|
|
1095
|
-
}
|
|
1096
|
-
fs.appendFileSync(logFile, `[hippo] ${new Date().toISOString()} ${sanitizeLogMessage(message)}\n`, 'utf8');
|
|
1097
|
-
}
|
|
1098
|
-
catch {
|
|
1099
|
-
// Diagnostic-only; a log write failure must never affect the exit-0 contract.
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
/** True iff `filePath` exists and is readable — checks both in one call. */
|
|
1103
|
-
function isReadableFile(filePath) {
|
|
1104
|
-
try {
|
|
1105
|
-
fs.accessSync(filePath, fs.constants.R_OK);
|
|
1106
|
-
return true;
|
|
1107
|
-
}
|
|
1108
|
-
catch {
|
|
1109
|
-
return false;
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
/**
|
|
1113
|
-
* Runs the PreCompact producer. Returns any `embedMemory` promises kicked
|
|
1114
|
-
* off along the way (empty on every skip path) so `cmdPreCompact` can await
|
|
1115
|
-
* them, bounded, before it exits (X6).
|
|
1116
|
-
*/
|
|
1117
|
-
function runPreCompact(hippoRoot, stdinText, stdinTimedOut, logFile) {
|
|
1118
|
-
// X3: the PreCompact hook fires in every Claude Code project, including
|
|
1119
|
-
// ones that never ran `hippo init`, so gate before any store-opening call
|
|
1120
|
-
// (saveActiveTaskSnapshot etc. call initStore, which would create one).
|
|
1121
|
-
if (!isInitialized(hippoRoot)) {
|
|
1122
|
-
appendPreCompactLog(logFile, 'skip: store not initialized');
|
|
1123
|
-
return [];
|
|
1124
|
-
}
|
|
1125
|
-
// Same hazard X4 guards below, different trigger: a read that timed out
|
|
1126
|
-
// must not reach auto-discovery either, or it snapshots another session.
|
|
1127
|
-
if (stdinTimedOut && (!stdinText || stdinText.trim() === '')) {
|
|
1128
|
-
appendPreCompactLog(logFile, 'skip: no PreCompact payload arrived before the stdin wait window closed');
|
|
1129
|
-
return [];
|
|
1130
|
-
}
|
|
1131
|
-
// A true manual invocation has no stdin at all (TTY, or a non-TTY pipe
|
|
1132
|
-
// that yielded an empty read) — that's the ONLY case newest-transcript
|
|
1133
|
-
// auto-discovery is allowed to run. Any other non-empty stdin must
|
|
1134
|
-
// JSON-parse to an object carrying a string transcript_path, or it is
|
|
1135
|
-
// treated as malformed input and skipped (X4) rather than silently
|
|
1136
|
-
// falling back to discovery, which could snapshot an unrelated session's
|
|
1137
|
-
// transcript under this payload's session_id.
|
|
1138
|
-
const manualInvocation = !stdinText || stdinText.trim() === '';
|
|
1139
|
-
let sessionId = null;
|
|
1140
|
-
let payloadTranscriptPath = null;
|
|
1141
|
-
if (!manualInvocation) {
|
|
1142
|
-
let payload;
|
|
1143
|
-
try {
|
|
1144
|
-
payload = JSON.parse(stdinText.trim());
|
|
1145
|
-
}
|
|
1146
|
-
catch {
|
|
1147
|
-
// payload stays undefined; the isObjectLike check below rejects it
|
|
1148
|
-
// the same way it would reject an explicit null.
|
|
1149
|
-
}
|
|
1150
|
-
if (!isObjectLike(payload) || !('transcript_path' in payload) || !isStringValue(payload.transcript_path)) {
|
|
1151
|
-
// Covers non-JSON stdin, a JSON value that isn't an object, and
|
|
1152
|
-
// `"transcript_path": null` (or the key missing entirely) — all fail
|
|
1153
|
-
// the string check. Log and skip; never fall through to auto-discovery.
|
|
1154
|
-
appendPreCompactLog(logFile, 'skip: malformed or incomplete PreCompact payload (missing string transcript_path)');
|
|
1155
|
-
return [];
|
|
1156
|
-
}
|
|
1157
|
-
if ('session_id' in payload && isStringValue(payload.session_id))
|
|
1158
|
-
sessionId = payload.session_id;
|
|
1159
|
-
payloadTranscriptPath = payload.transcript_path;
|
|
1160
|
-
}
|
|
1161
|
-
// X11: payload transcript_path must end .jsonl. No directory-containment
|
|
1162
|
-
// check is applied on top of this — CLAUDE_CONFIG_DIR can relocate the
|
|
1163
|
-
// transcript root entirely, so a path-prefix allowlist would just reject
|
|
1164
|
-
// legitimate relocated installs. The trust boundary here is process
|
|
1165
|
-
// identity, not path shape: a local process able to feed this hook
|
|
1166
|
-
// arbitrary stdin already runs as the same user who owns every transcript
|
|
1167
|
-
// this check could gate on, so containment buys no real isolation.
|
|
1168
|
-
if (payloadTranscriptPath !== null && !/\.jsonl$/i.test(payloadTranscriptPath)) {
|
|
1169
|
-
appendPreCompactLog(logFile, `skip: payload transcript_path is not a .jsonl file: ${payloadTranscriptPath}`);
|
|
1170
|
-
return [];
|
|
1171
|
-
}
|
|
1172
|
-
// A payload transcript_path is EXCLUSIVE: never fall back to
|
|
1173
|
-
// newest-transcript auto-discovery when it's missing/unreadable. That
|
|
1174
|
-
// fallback would snapshot a DIFFERENT session's transcript under THIS
|
|
1175
|
-
// payload's session_id — cross-session contamination with wrong linkage
|
|
1176
|
-
// (verify-stage E2E finding, 2026-08-03). Auto-discovery only applies
|
|
1177
|
-
// on a true manual invocation (no payload at all).
|
|
1178
|
-
let transcriptPath;
|
|
1179
|
-
if (payloadTranscriptPath !== null) {
|
|
1180
|
-
if (isReadableFile(payloadTranscriptPath)) {
|
|
1181
|
-
transcriptPath = payloadTranscriptPath;
|
|
1182
|
-
}
|
|
1183
|
-
else {
|
|
1184
|
-
appendPreCompactLog(logFile, `skip: payload transcript_path unreadable: ${payloadTranscriptPath}`);
|
|
1185
|
-
return [];
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
else {
|
|
1189
|
-
transcriptPath = resolveLastSessionTranscript(undefined, stdinText);
|
|
1190
|
-
}
|
|
1191
|
-
if (!transcriptPath) {
|
|
1192
|
-
appendPreCompactLog(logFile, 'skip: no transcript resolved');
|
|
1193
|
-
return [];
|
|
1194
|
-
}
|
|
1195
|
-
let tail;
|
|
1196
|
-
try {
|
|
1197
|
-
// CX7 (codex round 2): a final JSONL record larger than the window
|
|
1198
|
-
// swallows the whole tail — the seek lands inside it and alignment
|
|
1199
|
-
// drops everything up to its terminator, which is exactly the shape of
|
|
1200
|
-
// a huge tool_result that itself triggered compaction. Grow the window
|
|
1201
|
-
// a bounded number of times until at least one complete line survives.
|
|
1202
|
-
tail = readTranscriptTail(transcriptPath, PRE_COMPACT_TAIL_BYTES);
|
|
1203
|
-
let prevCap = PRE_COMPACT_TAIL_BYTES;
|
|
1204
|
-
for (const grownCap of [PRE_COMPACT_TAIL_BYTES * 4, PRE_COMPACT_TAIL_BYTES * 16]) {
|
|
1205
|
-
if (tail.trim() !== '')
|
|
1206
|
-
break;
|
|
1207
|
-
if (fs.statSync(transcriptPath).size <= prevCap)
|
|
1208
|
-
break; // already read the whole file
|
|
1209
|
-
appendPreCompactLog(logFile, `tail window grown to ${grownCap} bytes (oversized final record)`);
|
|
1210
|
-
tail = readTranscriptTail(transcriptPath, grownCap);
|
|
1211
|
-
prevCap = grownCap;
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
catch (err) {
|
|
1215
|
-
appendPreCompactLog(logFile, `skip: could not read transcript tail: ${errorMessage(err)}`);
|
|
1216
|
-
return [];
|
|
1217
|
-
}
|
|
1218
|
-
const summaryFull = summariseTranscript(tail);
|
|
1219
|
-
// CX5 (codex round 2): extraction runs over REDACTED text — extracted
|
|
1220
|
-
// items become durable memories and must never carry raw secrets any more
|
|
1221
|
-
// than the snapshot fields may. (The pre-existing SessionEnd capture path
|
|
1222
|
-
// is deliberately unchanged.)
|
|
1223
|
-
const scrubbedSummary = redactSecrets(summaryFull);
|
|
1224
|
-
const extracted = extractFromText(scrubbedSummary);
|
|
1225
|
-
const rawTask = lastPlainUserMessage(tail);
|
|
1226
|
-
const rawNextStep = lastAssistantTextBlock(tail);
|
|
1227
|
-
// Full skip only when EVERY derived field is empty and nothing was
|
|
1228
|
-
// extracted — never clobber a user-authored active snapshot with junk.
|
|
1229
|
-
if (!rawTask.trim() && !summaryFull.trim() && !rawNextStep.trim() && extracted.length === 0) {
|
|
1230
|
-
appendPreCompactLog(logFile, 'skip: empty summary and no extracted items');
|
|
1231
|
-
return [];
|
|
1232
|
-
}
|
|
1233
|
-
const tenantId = resolveTenantId({});
|
|
1234
|
-
// Per-field merge (X1): a tool-heavy tail whose only user turns are
|
|
1235
|
-
// tool_result arrays derives an empty task even though the summary is
|
|
1236
|
-
// non-empty. Loading the existing snapshot first lets each field fall
|
|
1237
|
-
// back independently instead of the whole write clobbering a
|
|
1238
|
-
// user-authored field with blank text.
|
|
1239
|
-
let existing = null;
|
|
1240
|
-
try {
|
|
1241
|
-
existing = loadActiveTaskSnapshot(hippoRoot, tenantId);
|
|
1242
|
-
}
|
|
1243
|
-
catch {
|
|
1244
|
-
// No existing snapshot to merge against — proceed with derived-only.
|
|
1245
|
-
}
|
|
1246
|
-
// X9: scrub secret-shaped substrings out of freshly-derived text before it
|
|
1247
|
-
// is capped/stored. These fields bypass the normal capture content gate
|
|
1248
|
-
// (they're not extracted items), so this producer is the only place that
|
|
1249
|
-
// ever sees them before they land in task_snapshots. Carried-over
|
|
1250
|
-
// existing field values are NOT re-scrubbed here — they already passed
|
|
1251
|
-
// through this same gate (or were set via `hippo snapshot save`, which is
|
|
1252
|
-
// deliberately untouched, same as the caps below).
|
|
1253
|
-
const scrubbedTask = redactSecrets(rawTask);
|
|
1254
|
-
const scrubbedNextStep = redactSecrets(rawNextStep);
|
|
1255
|
-
// CX6 (codex round 2): field fallback must never move content across
|
|
1256
|
-
// sessions — session A's task carried into a snapshot saved under session
|
|
1257
|
-
// B's id would pass compact-resume's session gate wearing the wrong
|
|
1258
|
-
// badge. Fall back only when the existing snapshot has no session, this
|
|
1259
|
-
// payload has none, or they match.
|
|
1260
|
-
const fallback = existing !== null &&
|
|
1261
|
-
(existing.session_id === null || sessionId === null || existing.session_id === sessionId)
|
|
1262
|
-
? existing
|
|
1263
|
-
: null;
|
|
1264
|
-
// Field caps are enforced HERE ONLY — saveActiveTaskSnapshot and the
|
|
1265
|
-
// `hippo snapshot save` CLI path stay uncapped (AGENTS.md public-API
|
|
1266
|
-
// preservation). Caps protect the re-injection token budget. Code-point
|
|
1267
|
-
// safe (X2): never split a surrogate pair at the cut.
|
|
1268
|
-
const task = scrubbedTask.trim()
|
|
1269
|
-
? truncateCodePointSafe(scrubbedTask, PRE_COMPACT_TASK_CAP)
|
|
1270
|
-
: (fallback?.task ?? '');
|
|
1271
|
-
const summary = scrubbedSummary.trim()
|
|
1272
|
-
? truncateKeepNewest(scrubbedSummary, PRE_COMPACT_SUMMARY_CAP)
|
|
1273
|
-
: (fallback?.summary ?? '');
|
|
1274
|
-
const nextStep = scrubbedNextStep.trim()
|
|
1275
|
-
? truncateCodePointSafe(scrubbedNextStep, PRE_COMPACT_NEXT_STEP_CAP)
|
|
1276
|
-
: (fallback?.next_step ?? '');
|
|
1277
|
-
// Snapshot writes FIRST: a capture-extraction failure below must never
|
|
1278
|
-
// lose the headline artifact. The reverse order would risk it. All-empty
|
|
1279
|
-
// fields (cross-session tail with nothing derivable) skip the write so a
|
|
1280
|
-
// foreign session's junk never displaces the owning session's snapshot.
|
|
1281
|
-
if (!task && !summary && !nextStep) {
|
|
1282
|
-
appendPreCompactLog(logFile, 'skip: no snapshot content for this session (nothing derivable; fallback blocked or empty)');
|
|
1283
|
-
}
|
|
1284
|
-
else {
|
|
1285
|
-
try {
|
|
1286
|
-
saveActiveTaskSnapshot(hippoRoot, tenantId, {
|
|
1287
|
-
task,
|
|
1288
|
-
summary,
|
|
1289
|
-
next_step: nextStep,
|
|
1290
|
-
source: 'pre-compact',
|
|
1291
|
-
session_id: sessionId,
|
|
1292
|
-
});
|
|
1293
|
-
appendPreCompactLog(logFile, 'snapshot saved');
|
|
1294
|
-
}
|
|
1295
|
-
catch (err) {
|
|
1296
|
-
appendPreCompactLog(logFile, `snapshot save failed: ${errorMessage(err)}`);
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
// Capture extraction SECOND, own try/catch: a failure here self-heals at
|
|
1300
|
-
// the next SessionEnd capture (existing dedup absorbs the overlap).
|
|
1301
|
-
try {
|
|
1302
|
-
const { captured, skipped, rejected, embeds } = writeExtractedItems(hippoRoot, tenantId, extracted);
|
|
1303
|
-
appendPreCompactLog(logFile, `capture: ${captured} items captured, ${skipped} skipped` +
|
|
1304
|
-
(rejected > 0 ? `, ${rejected} rejected` : ''));
|
|
1305
|
-
return embeds;
|
|
1306
|
-
}
|
|
1307
|
-
catch (err) {
|
|
1308
|
-
appendPreCompactLog(logFile, `capture failed: ${errorMessage(err)}`);
|
|
1309
|
-
return [];
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
// X6: bound how long cmdPreCompact will wait for fire-and-forget embeddings
|
|
1313
|
-
// to settle before it exits. PreCompact runs under a hook timeout (30s in
|
|
1314
|
-
// the installer) — 3s leaves ample headroom while still giving embeddings a
|
|
1315
|
-
// real chance to finish instead of racing process.exit(0) unconditionally.
|
|
1316
|
-
const EMBED_SETTLE_TIMEOUT_MS = 3000;
|
|
1317
|
-
/**
|
|
1318
|
-
* PreCompact hook entry point. Exit code 2 on PreCompact BLOCKS compaction,
|
|
1319
|
-
* so this verb must exit 0 on every path — malformed stdin, missing
|
|
1320
|
-
* transcript, and store errors all degrade to a logged no-op rather than a
|
|
1321
|
-
* thrown error. Callers (src/cli.ts) must not wrap this in anything that
|
|
1322
|
-
* could turn a caught-and-logged failure back into a non-zero exit.
|
|
1323
|
-
*/
|
|
1324
|
-
export async function cmdPreCompact(hippoRoot, options) {
|
|
1325
|
-
const logFile = options.logFile ?? defaultPreCompactLogPath();
|
|
1326
|
-
let embeds = [];
|
|
1327
|
-
try {
|
|
1328
|
-
embeds = runPreCompact(hippoRoot, options.stdinText, options.stdinTimedOut ?? false, logFile);
|
|
1329
|
-
}
|
|
1330
|
-
catch (err) {
|
|
1331
|
-
appendPreCompactLog(logFile, `pre-compact failed: ${errorMessage(err)}`);
|
|
1332
|
-
}
|
|
1333
|
-
if (embeds.length > 0) {
|
|
1334
|
-
let timer;
|
|
1335
|
-
const timeout = new Promise((resolve) => {
|
|
1336
|
-
timer = setTimeout(() => resolve('timeout'), EMBED_SETTLE_TIMEOUT_MS);
|
|
1337
|
-
timer.unref?.();
|
|
1338
|
-
});
|
|
1339
|
-
const settled = Promise.allSettled(embeds).then(() => 'settled');
|
|
1340
|
-
const outcome = await Promise.race([settled, timeout]);
|
|
1341
|
-
clearTimeout(timer);
|
|
1342
|
-
appendPreCompactLog(logFile, outcome === 'settled' ? 'embeddings settled' : 'embeddings timeout');
|
|
1343
|
-
}
|
|
1344
|
-
process.exit(0);
|
|
1345
|
-
}
|
|
1346
|
-
//# sourceMappingURL=capture.js.map
|