Compare commits

...
Author SHA1 Message Date
Ben 73bbe5f736 Merge branch 'main' into docs-chat-cloud-first 2026-05-22 09:53:48 -04:00
Ben 806fbcd41c docs(nemoclaw): add Cloud API URL to quickstart and config default (#1700)
* docs(nemoclaw): prioritize Hindsight Cloud with callout banners

* feat(nemoclaw): default --api-url to Hindsight Cloud, make it optional
2026-05-22 09:52:58 -04:00
Ben a75c3c85ad docs(paperclip): add Cloud API URL to quickstart and config default (#1699)
* docs(paperclip): prioritize Hindsight Cloud in setup docs and config default

* style(paperclip): align table columns after linter reformat
2026-05-22 09:37:02 -04:00
Ben 0db9f3da19 docs(dify): add Cloud Recommended callout (#1698)
dify already led with Cloud signup — adds the explicit  Recommended
banner for visual consistency.
2026-05-22 09:36:15 -04:00
Ben 8940710c72 docs(n8n): add Cloud Recommended callout (#1697)
n8n already led with Cloud signup — adds the explicit  Recommended
banner to README and docs page Setup sections for visual consistency
with the other cloud-first integrations.
2026-05-22 09:35:29 -04:00
Ben 6252643de0 docs(agno): prioritize Hindsight Cloud in quickstart (#1696)
Lead README + docs Quick Start with Cloud sign-up + Cloud API URL.
Bulk-replace localhost:8888 examples with Cloud URL. Demote
self-hosted to a 'Self-hosting (local development)' section below.
Update docstring examples in __init__.py and tools.py.
2026-05-22 09:33:44 -04:00
Ben 3fce309c0d docs(agentcore): add Cloud Recommended callout in quickstart (#1694)
Adds  Recommended Hindsight Cloud callout to README + docs + guide
Quick Start sections. agentcore already led with Cloud URL in code
examples — this just makes the recommendation explicit.
2026-05-22 09:32:33 -04:00
Ben 3fc361aabd docs(codex): prioritize Hindsight Cloud over local daemon (#1693)
Add Cloud Recommended callouts to README + docs + guide. Reframe the
'Local Daemon' section as the self-hosting alternative rather than a
peer option. No code default changes — codex still defaults to empty
hindsightApiUrl (local daemon) to avoid breaking existing local users.
2026-05-22 09:31:43 -04:00
Ben f559ae1649 docs(smolagents): prioritize Hindsight Cloud in quickstart (#1692)
Lead README/docs/guide Quick Start with Cloud sign-up + Cloud API
URL example; demote self-hosted localhost:8888 to a 'Self-hosting
(local development)' section below. Update docstring example.
2026-05-22 09:17:39 -04:00
Ben 8ed9a4ebb2 docs(pydantic-ai): prioritize Hindsight Cloud in quickstart (#1691)
Lead README/docs/guide Quick Start with Cloud sign-up + Cloud
base_url example; demote self-hosted localhost:8888 to a
'Self-hosting (local development)' section below. Update docstring
example in __init__.py.
2026-05-22 09:17:07 -04:00
Ben 722aa902fb Regenerate hindsight-docs skill references (#1686)
Adds opencode-go to the integration lists in the generated skill
references. Picked up by the generate-docs-skill.sh pre-commit hook
as drift from the hindsight-docs sources on main.
2026-05-22 09:16:27 -04:00
Ben 5c7e783e18 docs(pipecat): prioritize Hindsight Cloud in quickstart (#1695)
Lead README/docs/guide Quick Start with Cloud, demote self-hosted to
its own section. Updates configure() global example to Cloud default.
2026-05-22 09:15:48 -04:00
Ben e779f10fc7 docs(strands): prioritize Hindsight Cloud in quickstart (#1690)
Lead README/docs/guide Quick Start with Hindsight Cloud sign-up and
Cloud API URL example; demote self-hosted localhost:8888 to a
'Self-hosting (local development)' section below. Update docstring
example in __init__.py to show Cloud-first usage.

Includes 2-line incidental skills/hindsight-docs/ regeneration drift.
2026-05-22 09:15:24 -04:00
Ben 1b2c9f63aa docs(crewai): prioritize Hindsight Cloud in quickstart (#1689)
- Lead README/docs/guide Quick Start with Hindsight Cloud sign-up
  and the Cloud API URL example; demote self-hosted localhost:8888
  to a "Self-hosting (local development)" section below.
- Fix unconfigured-fallback inconsistency in HindsightStorage and
  HindsightReflectTool: previously fell back to localhost:8888
  even though the documented default is Cloud. Now both fallbacks
  use DEFAULT_HINDSIGHT_API_URL.
- Update docstring examples in __init__.py and storage.py to reflect
  the Cloud-first default.
- Update fallback assertion in tests/test_storage.py.
2026-05-22 09:14:56 -04:00
Ben 6bdb1a08f5 docs(chat): add Hindsight Cloud setup callout to README and docs 2026-05-21 14:36:48 -04:00
Ben 7ffe6a104b style: apply ruff format to openai_compatible_llm.py (#1703) 2026-05-21 14:36:17 -04:00
Ben 113d7da987 Blog: Agent Memory Consolidation framework (#1672)
* Add blog post: Agent Memory Consolidation framework
2026-05-21 10:42:41 -04:00
Chandler bd86e7ead0 fix(typescript-client): update repository URL to correct repo (#1657) 2026-05-19 16:51:46 -04:00
Ben 795c081d9f fix(api): auto-refresh openai-codex OAuth access_token (#1637) (#1661)
The openai-codex provider was a startup-only credential loader: it read
~/.codex/auth.json once at __init__ and used the cached access_token
forever. ChatGPT OAuth tokens are short-lived (hours), so any
long-running deployment 401d on every request once the cached token
expired. The only recovery was an external cron + container restart.

This change makes the provider refresh tokens itself, mirroring the
canonical @openai/codex CLI (codex-rs/login/src/auth/manager.rs):

- Loads tokens.refresh_token from auth.json (previously discarded).
- Proactive refresh: decodes the access_token JWT's exp claim and
  refreshes ~60s before expiry. Cheap when the token is fresh.
- Reactive refresh: on a 401/403 from the codex backend, refreshes
  once and retries the request without consuming a normal-retry budget
  slot.
- Single-flight: serializes through asyncio.Lock so concurrent callers
  produce one network refresh, not N. Re-checks under the lock by
  comparing the cached token before/after wait to handle the case
  where another coroutine rotated mid-wait.
- Atomic persistence: writes auth.json via tempfile + os.replace with
  mode 0600. The upstream Rust CLI uses truncate-and-overwrite, which
  a concurrent reader can catch mid-write; tempfile+rename is strictly
  safer.
- Terminal error handling: refresh_token_expired/reused/invalidated
  (and any 401 from the refresh endpoint) raise CodexRefreshExpiredError
  with a clear "run codex auth login" remediation, and do not loop.
- No secrets in logs: refresh logs the reason and outcome but not the
  token values themselves.

OAuth request shape (POST https://auth.openai.com/oauth/token, JSON
body with hardcoded client_id app_EMoamEEZ73f0CkXaXp7hrann,
grant_type=refresh_token) matches the upstream Rust CLI exactly. The
endpoint is overridable via the CODEX_REFRESH_TOKEN_URL_OVERRIDE env
var the same way the upstream CLI supports it.

Tests: 23 new in test_codex_oauth_refresh.py covering JWT exp decode,
staleness with skew, refresh_token loading, atomic persistence with
0600 mode, request shape, in-memory + on-disk update, refresh_token
rotation, terminal-error classification, network error wrapping,
no-secrets-in-logs, single-flight under 10 concurrent callers,
proactive refresh before request, reactive 401-then-retry, and the
no-refresh-when-fresh case. Existing test_codex_tool_choice.py still
passes.

Caveat: all tests are mocked. The OAuth request shape has not been
verified against the real auth.openai.com endpoint - it is grounded
in the upstream codex-rs source on github.com/openai/codex.
Reviewers with a ChatGPT Plus subscription should validate the
end-to-end path before merge.
2026-05-19 16:49:03 -04:00
Minghao Xiao 9c161e4e59 fix(api): preserve tag group or triggers (#1655) 2026-05-19 16:35:01 -04:00
Minghao Xiao 9643e66e77 fix(api): lazy load reflect tiktoken encoding (#1654) 2026-05-19 16:34:24 -04:00
Teven Feng c29c76e3fa feat: add opencode-go LLM provider (#1652) 2026-05-19 16:34:11 -04:00
Minghao Xiao c16d9978e8 fix(api): strip Gemma thought tags (#1653) 2026-05-19 16:33:59 -04:00
Ben 943dfee624 docs: add HINDSIGHT_API_WORKER_ID tip to API quickstart (#1617)
* docs: add HINDSIGHT_API_WORKER_ID tip to API quickstart

Mirrors the tip already present in installation.md so users who follow
the API quickstart's Docker tab see the same guidance about pinning a
stable worker ID. Closes #1616.

* docs: mirror WORKER_ID tip to versioned_docs v0.6 (from #1648)

Folding in xmh1011's strict-improvement hunk from #1648: the
versioned snapshot for v0.6 should carry the same production tip
as the live doc. Same prose, same `:::tip` block. Includes the
auto-regenerated skills/ reference.
2026-05-19 16:28:17 -04:00
Ben ab0caa658e docs(changelog): correct openai-agents v0.1.1 entry (#1639)
Replaces the auto-generated entry, which credited #1123 (a core-engine
consolidation config, not openai-agents-specific) to the v0.1.1 release.
The actual openai-agents-specific work in v0.1.1 was #1134 by @DK09876:
docs/test polish — corrected SDK version requirement, added
memory_instructions() to README and API reference, added Production
Patterns section, and added test_config.py.
2026-05-19 16:27:56 -04:00
Chandler 2cb65e09e3 feat(typescript-client): replace Promise<any> with concrete generated types (#1640) 2026-05-19 16:27:14 -04:00
Ben d1903f3c9f blog: What's New in Hindsight Cloud (#1636)
* blog: What's New in Hindsight Cloud — Going Global
2026-05-19 10:50:42 -04:00
Ben 9784f6573a release(openclaw): v0.7.7 2026-05-15 15:11:52 -04:00
Ben f02e037bc7 release(openai-agents): v0.1.1 2026-05-15 14:50:39 -04:00
Ben 87734b3a44 release(litellm): v0.5.3 2026-05-15 14:46:54 -04:00
Ben f613f005a6 release(strands): v0.1.3 2026-05-15 14:22:37 -04:00
Ben 6a5e2d1800 release(claude-code): v0.6.5 2026-05-15 14:21:30 -04:00
Ben 6d495290bc release(paperclip): v0.2.2 2026-05-15 14:12:33 -04:00
Ben f94e840fe8 docs: attribute 0.6.2 release post to benfrank241 (#1635) 2026-05-14 17:07:12 -04:00
Ben 25052a56d0 docs: add 0.6.2 changelog and release blog post (#1633)
Documents the security/maintenance release: dependency CVE bumps,
mental_models.subtype migration repair, embedding-dimension OID
handling, and integration fixes for Claude Code, Agent SDK, CLI,
and Paperclip.
2026-05-14 16:55:48 -04:00
Ben 8b10231b8b Release v0.6.2
- Update version to 0.6.2 in all components
- Regenerate OpenAPI spec and client SDKs
- Python packages: hindsight-api, hindsight-dev, hindsight-all, hindsight-embed
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- hindsight-all npm wrapper: hindsight-all-npm
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
- Sync documentation to version-0.6
2026-05-14 16:00:16 -04:00
Ben 5a7996a649 blog: onboarding a new engineer onto five months of OpenCode memory (#1628)
* blog: add OpenCode onboarding use-case post
2026-05-14 14:57:37 -04:00
dependabot[bot] 059d1c3e94 chore(deps): bump the uv group across 3 directories with 8 updates (#1630) 2026-05-14 10:57:24 -04:00
Derek Bouius b20c0d8f67 fix(ci): set UV_FROZEN=1 on verify-generated-files job (#1629)
Set UV_FROZEN=1 as a job-level env var so all uv commands (sync, run,
lock) respect the committed lockfile without re-resolving. This is the
idiomatic uv approach for CI and prevents spurious uv.lock diffs that
blocked every Dependabot PR.

Reverts the lint.sh CI-specific --frozen logic from #1618 since the
env var covers it globally.
2026-05-14 10:24:47 -04:00
Ben debbd91961 fix(migrations): repair mental_models.subtype at current head (#1553) (#1627)
Three production deployments (issue #1553, plus confirmations from
@4Lienau and @khanhduyvt0101) report `column "subtype" of relation
"mental_models" does not exist` on `create_mental_model`, despite their
alembic_version showing the current head `m3rg3h3ad5f6`.

Both h3c4d5e6f7g8_mental_models_v4 (which uses `CREATE TABLE IF NOT EXISTS`
and is a no-op on databases that came through the reflections rename) and
d5y6z7a8b9c0_backfill_mental_models_subtype were meant to ensure the
column exists, but on these specific deployments neither fired
successfully — likely a casualty of the divergent-heads reorganization
that put d5y6z7a8b9c0 on a branch the affected DBs bypassed.

Add a new migration at the current head so every stuck deployment picks
it up on next container start. Idempotent (`ADD COLUMN IF NOT EXISTS`),
guarded by an existence check on the table, and matches the canonical v4
column set and CHECK allowlist from d5y6z7a8b9c0.

PG-only: Oracle's baseline creates mental_models with a different
topology and constraint shape, so this repair does not apply there.
2026-05-14 10:14:48 -04:00
Evo ed35894f55 docs(cli): document --timestamp flag on memory retain (#1622) (#1623)
* docs(cli): document new --timestamp flag on memory retain (#1622)

* docs(cli): mirror --timestamp flag in skills CLI reference
2026-05-14 09:32:09 -04:00
Evo 190c31f543 docs(claude-code): document requestTimeoutSeconds option from #1591 (#1626) 2026-05-14 09:31:11 -04:00
Chris Latimer 5a2c138779 Updated benchmark scores 2026-05-14 05:30:57 -06:00
Ben 51ea9aa286 fix(cli, control-plane): make retain Event Date / timestamp actually reach the API (#1622)
* fix(cli, control-plane): make Event Date / timestamp actually reach the API

- CLI `hindsight memory retain` now accepts `-t/--timestamp <ISO>`. The
  internal MemoryItem.timestamp was hardcoded to None, so retains from the
  CLI lost any caller-supplied event date even though the Python/Node/Go
  SDKs accept one. Add a flag and pass it through; regression test asserts
  --help advertises the option.
- Control plane "Event Date" inputs in the new-document and per-file flows
  used `<input type="datetime-local">`, which only commits a value when the
  user enters both date AND time. Typing a date alone silently left the
  value empty, so `item.timestamp` was never sent and the resulting
  operation payload had no event_date. Switch to `type="date"` and pad
  with `T00:00:00` before sending, so date-only entries reach the API as
  valid ISO datetimes.

* fix(cli): decode --timestamp into MemoryItemTimestamp enum

MemoryItem.timestamp is generated as Option<MemoryItemTimestamp>
(progenitor's anyOf wrapper), not Option<String>. Round-trip the
flag value through serde_json so the right variant is selected for
both ISO datetimes and the 'unset' sentinel. Fixes CI build break.
2026-05-13 16:51:21 -04:00
Ben f9fbfe55c2 fix(docs): use real GitHub handle for ContextForge integration author (#1621)
The `by` field was set to `omarouldali`, which is not a real GitHub user
(github.com/omarouldali returns 404). As a result the avatar request to
`github.com/omarouldali.png?size=40` failed and the integrations hub card
showed a broken-image placeholder next to the author name. The actual
GitHub handle of the contributor (author of PRs #961 and #1254) is
`ooa-andera`, which resolves cleanly.
2026-05-13 15:50:19 -04:00
Derek Bouius 5c7aea4717 fix(ci): use frozen lockfile in lint.sh during CI (#1618)
lint.sh runs `uv sync` without --frozen at the repo root, which
re-resolves uv.lock. In CI's verify-generated-files job this causes
spurious 1-line diffs on every Dependabot PR, blocking them from
merging.

Use --frozen when $CI is set so the lockfile is never modified by
the lint step. Local development keeps the non-frozen sync to handle
version bumps gracefully.
2026-05-13 13:58:48 -04:00
Derek Bouius 9dfbfb4bd0 fix: handle transient OID errors in embedding dimension migration (#1612)
The DO $$ block that drops vector indexes iterates pg_indexes via a
cursor. When concurrent pytest-xdist workers drop schemas (CASCADE),
the OID references in the cursor become stale, causing
'could not open relation with OID' errors.

Fix the root cause in migrations.py by adding EXCEPTION WHEN
internal_error handling to the PL/pgSQL DO block. Also add
defense-in-depth retry logic to the two test cases that previously
called ensure_embedding_dimension() without the retry wrapper.
2026-05-13 13:05:51 -04:00
Evo b593d40fdf fix(agent-sdk): agent_knowledge_get_page request detail=content (sister of #1543) (#1557)
* fix(agent-sdk): agent_knowledge_get_page request detail=content (sister of #1543)

* fix(agent-sdk): flatten throw to single line for prettier (printWidth 100)
2026-05-13 10:16:36 -04:00
Rogerio Saulo 55ef70679c feat(claude-code): expose configurable MCP request timeout (#1591)
Adds requestTimeoutSeconds (env: HINDSIGHT_REQUEST_TIMEOUT_SECONDS) to
the claude-code plugin config. When set, overrides the hardcoded per-call
HTTP timeouts (10s recall, 15s retain, 10-15s in knowledge MCP tools).
When unset (default), per-call defaults are preserved — fully backward
compatible.

The health check timeout (5s) is intentionally left alone, since bumping
it would degrade UX when the server is genuinely unreachable.

Fixes #1575
2026-05-13 10:08:22 -04:00
Derek Bouius fd05bdab51 security: bump litellm to >=1.83.14 in root lockfile (#1610)
Fixes 4 remaining Dependabot alerts (1 critical, 3 high) for litellm
vulnerabilities including GHSA-pq44-5pcq-4r5g and GHSA-8cjq-wjmh-q42r
that were missed in the #1609 squash merge.
2026-05-13 08:54:53 -04:00
Derek Bouius a6cd28a3b5 security: bump remaining high/critical deps across all lockfiles (#1609)
* security: bump remaining high/critical deps across all lockfiles

Root uv.lock:
- GitPython 3.1.45 → 3.1.50 (HIGH: multiple traversal/RCE fixes)
- langchain-core 1.2.23 → 1.4.0 (HIGH: path traversal)
- lxml 6.0.2 → 6.1.0 (HIGH)
- Mako 1.3.10 → 1.3.12 (HIGH)
- pillow 12.1.1 → 12.2.0 (HIGH: OOB write)
- python-multipart 0.0.22 → 0.0.28 (HIGH: arbitrary file write)
- litellm 1.83.0 → 1.83.14 (CRITICAL: multiple CVEs)

Integration lockfiles (ag2, agentcore, agno, autogen, crewai, dify,
langgraph, litellm, llamaindex, openai-agents, smolagents, strands,
pipecat, pydantic-ai, integration-tests):
- urllib3 2.6.3 → 2.7.0
- python-multipart, pillow, GitPython, langchain-core, banks, litellm
  bumped where present

Rust (hindsight-clients/rust):
- openssl 0.10.75 → 0.10.79 (HIGH: multiple CVEs)
- rustls-webpki 0.103.10 → 0.103.13 (HIGH)

crewai pinned to <1.10 — 1.10+ renamed Storage → StorageBackend;
migration tracked separately.

* fix: pin pipecat-ai <1.0 to avoid breaking module restructure

pipecat-ai 1.0+ restructured modules (removed
pipecat.processors.aggregators.openai_llm_context), breaking all tests.
Pin to <1.0 and track migration separately.
2026-05-13 07:40:10 -04:00
Derek Bouius 9533107612 security: bump urllib3 to 2.7.0 in integration lockfiles (#1603)
Fixes remaining Dependabot alerts for urllib3 decompression-bomb bypass
and sensitive header forwarding across 6 integration lockfiles:
strands, smolagents, pydantic-ai, pipecat, openai-agents, llamaindex.
2026-05-12 22:26:24 -04:00
Derek Bouius 26c5028c94 security: bump vulnerable dependencies across npm and pip (#1600) 2026-05-12 18:34:19 -04:00
Derek Bouius 9b8d8b5632 fix(ci): paperclip lint formatting + openclaw hook test expectations (#1601)
- paperclip: commit trailing whitespace and line-length fixes that the
  lint hook produces, fixing verify-generated-files on every PR
- openclaw: update agent_end hook tests to expect the system-role
  context message prepended by includeSenderContext (default: true)
2026-05-12 16:55:17 -04:00
Evo d9dd14995c fix(agent-sdk): rename agent_knowledge_recall max_results to max_tokens; bump default 10 to 1024 (#1552) 2026-05-12 16:03:08 -04:00
Evo 378097ba3d docs(paperclip): align integration guide + README with #1560 lifecycle (#1596)
* docs(paperclip): align integration guide with #1560 lifecycle (issue.comment.created retain)

* docs(paperclip): mirror integration README lifecycle after #1560
2026-05-12 15:23:15 -04:00
EvoandEvo 69703e5a31 docs(strands): document FastAPI lifecycle pattern from #1547 (#1581)
Co-authored-by: Evo <[email protected]>
2026-05-12 15:22:25 -04:00
Ben 771922cd70 docs: add Windows/China deployment guidance for embeddings config (#1549) 2026-05-12 15:22:03 -04:00
Ben 61730d5924 blog: the case against external vector DBs for agent memory (#1594)
* blog: add post on the case against external vector DBs for agent memory
2026-05-12 15:14:30 -04:00
Amir Moradi be908d5b2c fix(paperclip): align with Paperclip's actual event payloads (#1560)
* fix(paperclip): align with Paperclip's actual event payloads

The plugin's `agent.run.started` and `agent.run.finished` handlers
destructured fields (`issueTitle`, `issueDescription`, `output`, `result`)
that Paperclip's host does not publish. Paperclip emits a thin lifecycle
payload — `{runId, agentId, status, invocationSource, triggerDetail,
error, errorCode, issueId, startedAt, finishedAt}` — so both handlers
silently early-returned and the plugin never recalled or retained
anything despite registering successfully.

Changes:

- `agent.run.started` now uses `payload.issueId` to look up the issue
  via `ctx.issues.get` and builds the recall query from the issue's
  title + description.

- New `issue.comment.created` subscription replaces the
  `agent.run.finished` retain path. Comments are the durable record of
  agent + user output and the existing payload only carries a 120-char
  snippet, so we fetch the full body via `ctx.issues.listComments`.
  Bank attribution falls back to the issue's assignee when a comment
  has no agent author (e.g. user comments).

- `agent.run.finished` is kept as a debug no-op so the subscription
  stays visible and can be reused if Paperclip ever embeds output in
  the lifecycle payload.

- Manifest gains `issues.read` and `issue.comments.read` capabilities,
  required by the new SDK calls.

- Tests updated to seed issues/comments via the harness, exercise the
  new comment-created path, and cover the assignee-fallback for
  unauthored comments.

Verified end-to-end against a local Paperclip + self-hosted Hindsight:
the patched plugin retains real comment bodies to the correct bank
and Hindsight's recall API returns them on subsequent queries.

Related: vectorize-io/hindsight tracking issue (Paperclip ODIAA-84).

* Log skip retain due to missing agent attribution

Add logging for skipping retain when no agent attribution is available.

* Add test for skipping retain with no agent and assignee
2026-05-12 10:23:51 -04:00
Ben 2471f01107 blog: add category filter to blog landing page (#1580)
Replaces the Hindsight Cloud preview section with a pill-strip filter
(All / Hindsight Cloud / Deep Dives / Announcements & Releases /
Tutorials & Integrations) that filters the chronological grid by
canonical category tag via a ?cat=<slug> URL param.

Backfills the canonical category tag (release / tutorial / deep-dive)
onto the 49 existing posts that needed one. The hindsight-cloud tag is
already in use and stays unchanged.

Extends BlogTagsPostsPage with friendly titles for the new category
tags so /blog/tags/{release,tutorial,deep-dive} render like the
existing /blog/tags/hindsight-cloud page.

No existing post permalinks or tag-archive URLs change.
2026-05-11 16:07:13 -04:00
Ben 2bfd77477a fix(strands): close internally owned hindsight clients (#1547) 2026-05-11 15:40:25 -04:00
Nicolò Boschi 6aab6c89dc release(claude-code): v0.6.4 2026-05-08 16:54:53 +02:00
Offending Commit 909a4fd400 fix(claude-code-mcp): rename recall max_results→max_tokens (#1544)
The MCP tool exposed `max_results: int = 10` but piped that value
straight into the server's `max_tokens` budget. The server has no
`max_results` concept — recall returns whatever fits in the token
budget — so 10 tokens truncated every recall to an empty result set,
making the tool look like a connection failure even though the bank
contained thousands of nodes.

Rename the parameter to match server semantics and bump the default
to 1024 (same as `client.recall`'s default), so callers can request
deeper recalls by raising the budget honestly.
2026-05-08 16:54:02 +02:00
Ben 4d486b9262 blog: add cover image for How Hindsight Scales (#1545)
* blog: add cover image for How Hindsight Scales
2026-05-08 10:23:35 -04:00
Nicolò Boschi 43c4015afa docs: add 0.6.1 changelog and release blog post (#1542)
* docs: add 0.6.1 changelog and release blog post

* docs(blog): add bank dropdown memory stats section + screenshot
2026-05-08 16:13:43 +02:00
Chris Bartholomew b2a693ab7a fix(claude-code): get_page detail=content + handle tool-result spillover (#1543)
Two related changes addressing the same class of issue PR #1528 fixed
for list_pages — but on the get_page surface and on the agent prompt.

1. agent_knowledge_get_page now requests detail=content instead of
   detail=full. Measured on real banks, reflect_response is 70-95% of
   the response bytes; the actual `content` field is 1-2%. At realistic
   page sizes (200-280 KB at full) the response overflows the MCP host's
   per-tool-result token cap and spills to disk where the agent cannot
   consume it inline. Switching to detail=content drops every page to
   ~5 KB. Sample measurements:

     page                 total    content   reflect_response
     Pre-push gate        276 KB   2.8 KB    201 KB
     Local test stack     282 KB   4.0 KB    205 KB
     CI failure triage    266 KB   2.8 KB    194 KB

   The docstring promises "full synthesized content" — exactly what the
   `content` projection returns.

2. The create-agent SKILL template now tells the agent how to recover
   when get_page does spill (rare after this fix, but possible on
   genuinely large pages): Read the spill file, parse the JSON wrapper,
   or fall back to agent_knowledge_recall.

Adds a focused regression test pinning the content projection.
2026-05-08 16:12:54 +02:00
Nicolò Boschi 0dcd605751 Update 2026-05-08-how-hindsight-scales.md 2026-05-08 15:59:11 +02:00
Nicolò Boschi 838ddb0f30 blog: How Hindsight Scales (#1539)
* blog: add "How Hindsight Scales" technical deep dive

Covers performance, quality, and cost scaling across all 4 core
operations: retain, recall, consolidation, and reflect.

* blog: finalize "How Hindsight Scales" post + blog styling

Architecture-focused scaling analysis covering retain, recall,
consolidation, reflect, and mental models. Fact-checked against
codebase. Also switches blog body font to Space Grotesk and adds
colored underline treatment for bold text.
2026-05-08 15:48:14 +02:00
Nicolò Boschi 0f7c5e895b Release v0.6.1
- Update version to 0.6.1 in all components
- Regenerate OpenAPI spec and client SDKs
- Python packages: hindsight-api, hindsight-dev, hindsight-all, hindsight-embed
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- hindsight-all npm wrapper: hindsight-all-npm
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
- Sync documentation to version-0.6
2026-05-08 15:00:38 +02:00
Nicolò Boschi 98f33cbf6c feat(api): add litellmrouter provider for LLM fallback chains (#1537)
* feat(api): add litellmrouter provider for LLM fallback chains

Closes #1464.

New "litellmrouter" provider wraps LiteLLM Router with ordered fallback
across a configurable chain of deployments. On transient errors
(rate-limit, timeout, 5xx) the Router falls back to the next deployment
in declared order; auth errors (401/403) are not retried so a
misconfigured key cannot silently cascade through the chain.

Configuration is provider-scoped (one-word LITELLMROUTER namespace to
avoid clashing with the existing LITELLM_* settings used by the
embeddings/reranker layers):

  HINDSIGHT_API_LLM_PROVIDER=litellmrouter
  HINDSIGHT_API_LLM_LITELLMROUTER_CHAIN=<json list of deployments>

Per-operation chains are supported via the same pattern that already
exists for retain/reflect/consolidation:

  HINDSIGHT_API_RETAIN_LLM_LITELLMROUTER_CHAIN=...
  HINDSIGHT_API_REFLECT_LLM_LITELLMROUTER_CHAIN=...
  HINDSIGHT_API_CONSOLIDATION_LLM_LITELLMROUTER_CHAIN=...

Each per-op chain falls back to the default chain when unset, mirroring
the existing per-op provider/model overrides.

Chain entries are tagged as credential fields and are never exposed via
the bank-config API. Batch APIs are intentionally unsupported in router
mode; users that need batch retain should configure a single provider.

* refactor(api): dedup litellmrouter on top of LiteLLMLLM, accept arbitrary chain keys, add CI matrix entry

The retry/parse/metrics loop in LiteLLMRouterLLM was a near-verbatim copy of
LiteLLMLLM. Extract three small hooks on the base class
(_acompletion, _resolve_completion_model, _stage_label) and have the Router
provider inherit + override only what differs.

Drop strict validation of chain entries. The parser now requires only
'provider' and 'model'; everything else passes through to LiteLLM Router
unchanged. Top-level keys (rpm, tpm, weight, model_info, ...) flow to the
deployment record; an optional 'litellm_params' sub-object merges into the
inner params dict. Documented and tested.

Add a litellmrouter row to the LLM acceptance matrix using a single OpenAI
deployment in the chain. The chain JSON is built from secrets in a
dedicated step and masked in logs before being written to GITHUB_ENV.

* refactor(api): pure pass-through to litellm.Router, drop translation layer

Replace the chain-with-Hindsight-shape API with a thin pass-through to
litellm.Router. The HINDSIGHT_API_LLM_LITELLMROUTER_CONFIG env var is now
a JSON object forwarded verbatim to Router(**config). Hindsight's only
imposed rules: model_list is non-empty, each entry has a model_name, and
requests route against the first entry's model_name.

This removes _LITELLM_PROVIDER_PREFIX (provider→prefix translation),
_build_model_list (flat→nested rewrite), and _build_fallbacks (auto-wired
ordered fallback). Users now write LiteLLM-native configs and pick their
own routing strategy — ordered fallback via 'fallbacks', load-balancing
via shared model_name + 'routing_strategy', rate-limit awareness via rpm/
tpm, and so on. The docs link to LiteLLM's reference rather than
recapitulating it.

Renames:
  ENV_LLM_LITELLMROUTER_CHAIN  -> ENV_LLM_LITELLMROUTER_CONFIG
  llm_litellmrouter_chain      -> llm_litellmrouter_config
  _parse_llm_router_chain      -> _parse_llm_router_config
  LLMProvider(litellmrouter_chain=) -> LLMProvider(litellmrouter_config=)

The dataclass fields change shape from list[dict] to dict (JSON object).

Net reduction across the touched files: ~165 lines.

* docs: regenerate hindsight-docs skill from updated configuration.md

* refactor(api): drop all shape validation on litellmrouter config, use fixed 'default' entrypoint

The previous version still inspected the user's config in two places:
the parser checked model_list/model_name shape, and __init__ pulled
primary_model_name out of model_list[0]. Both are gone.

The parser now only verifies the env var is parseable JSON. Whatever the
user supplies — dict, list, missing keys, weird shapes — flows through.
LiteLLM Router is authoritative about the shape and raises its own
errors at construction time if something's wrong.

The provider no longer extracts a 'primary' name from the input. Instead
it always issues completions against model_name='default' — the single
Hindsight-imposed convention. Users put one entry with that name in
their model_list as the entrypoint and use any names they want for
fallback/load-balance/weighted-pool members. This avoids both pre-
validation footguns and any dependence on Router's internal API
(model_names, model_list attributes) that could shift between versions.

Docs and tests updated to match. The CI matrix already used 'default'.

* docs: regenerate hindsight-docs skill

* ci(test): cap retain max_completion_tokens for litellmrouter matrix row

gpt-4.1-nano caps OpenAI completion at 32768 tokens, but Hindsight's
default DEFAULT_RETAIN_MAX_COMPLETION_TOKENS is 64000. The 'openai'
matrix row passes because OpenAICompatibleLLM has model-specific token
capping; LiteLLMLLM (and the new LiteLLMRouterLLM by inheritance) don't.
That's a pre-existing limitation orthogonal to this PR — the cap-aware
behaviour lives in OpenAICompatibleLLM and intentionally doesn't apply
to LiteLLM-routed calls.

Lower retain max_completion_tokens via env in the litellmrouter job so
CI exercises the Router path end-to-end instead of dying on a
provider-side BadRequestError that's not the thing we're testing.

* fix(api): cap LiteLLM-routed max_completion_tokens to model registry limit

Hindsight defaults retain_max_completion_tokens to 64000 — fine for
high-capacity models, but breaks against models with smaller caps
(gpt-4.1-nano: 32768; gpt-4o-mini: 16384). OpenAICompatibleLLM already
caps via a hardcoded string-match table; LiteLLMLLM and the new Router
provider didn't, so a default Hindsight install pointed at a small
model would fail with provider BadRequestError.

Cap pre-emptively using LiteLLM's own per-model registry
(litellm.get_max_tokens). For LiteLLMLLM the cap is self.model. For
LiteLLMRouterLLM the cap is the min across all configured deployments,
computed once at __init__ — this way a single max_completion_tokens
value works no matter which deployment Router picks (primary,
fallback, weighted-pool member). Unknown models contribute no cap.

Reverts the temporary CI workaround that lowered HINDSIGHT_API_RETAIN_
MAX_COMPLETION_TOKENS=32000 for the litellmrouter row — Hindsight
should work out of the box.

* docs: shorten litellmrouter config section, add models.mdx pointer

Move the discoverability pointer into models.mdx alongside the existing
LiteLLM tip, where users browsing for model options will find it. Strip
the configuration page entry to its essentials: env-var table, one
ordered-fallback example, and the three short caveats. Defer routing
details to LiteLLM's docs rather than recapitulating them.
2026-05-08 14:50:18 +02:00
Nicolò Boschi ab8cc3e605 fix(typescript-client): derive CLIENT_VERSION via tsup define (#1540)
The hardcoded `CLIENT_VERSION = "0.5.1"` in src/index.ts has fallen
behind npm releases through 0.5.6 / 0.5.7 / 0.6.0 — every published
release since 0.5.1 ships a stale constant, mis-attributing User-Agent
in server-side telemetry and foreclosing client-side feature gating.

Substitute `__CLIENT_VERSION__` with `pkg.version` via tsup's `define`
at build time. Source has no JSON import, so the fix is uniform across
runtimes (Node CJS/ESM, Deno via npm:, Deno via raw src) — unlike a
direct `import pkg from "../package.json"`, which Deno rejects without
`with { type: "json" }`, and which would in turn cascade into tsconfig
+ ts-jest reconfiguration (see #1535 for that path).

A `typeof` guard with a `0.0.0-dev` sentinel keeps raw-source loads
(jest, `npm run test:deno`) from throwing ReferenceError when the
build-time substitution hasn't run.

Verified locally: build, jest 6/6, Node CJS/ESM, Deno (dist), Deno
(raw src) all report the substituted version (or the dev sentinel
where appropriate). dist no longer inlines the full package.json
(devDependencies, scripts, repository url) — only the version string.

Closes #1535.
2026-05-08 12:51:12 +02:00
Nicolò Boschi da72f5da44 perf(locomo): scope CI to a 3-conversation curated subset (#1536)
The scheduled LoComo job has been failing on most recent runs with
``TimeoutError: Consolidation did not complete within 3000.0s`` from
``benchmark_runner._wait_for_consolidation``. The offender is
``locomo_conv-44``, the largest bank in the dataset (463 unconsolidated
items at ingestion peak), whose per-bank consolidation regularly grazes
or exceeds the hardcoded 50-minute wait budget under CI load. Because
``Publish LoComo to dashboard`` is gated on ``success()``, every such
failure also drops the entire run from the dashboard, so no LoComo
metrics have been published since the dashboard was set up.

Rather than chase the timeout up, narrow what the scheduled run
exercises. Pick three conversations that bracket accuracy on the last
clean full run (May 5):

- ``conv-26`` — best (90.79%)
- ``conv-30`` — middle (86.42%)
- ``conv-43`` — worst (82.02%)

This deliberately omits ``conv-44``: it sits at median accuracy but
carries the largest unconsolidated set in the dataset, and the goal here
is to keep the trend signal (best/median/worst spread, ingest+recall
behavior) without dragging in the bank that has been blowing the
per-bank timeout.

To plumb this through:

- ``--conversation`` becomes ``nargs="+"`` so it accepts a list of IDs
  (single-ID form still works). Help text and runner docstring updated.
- ``BenchmarkRunner.run`` widens ``specific_item`` to
  ``str | Iterable[str]`` and filters via set membership; longmemeval's
  single-string usage is unaffected.
- The workflow swaps ``locomo_max_conversations`` for
  ``locomo_conversations``: a space-separated string of IDs that
  defaults to the curated set but can be overridden at
  ``workflow_dispatch`` time.

Lint clean (``./scripts/hooks/lint.sh``); argparse ``--help`` verified.
2026-05-08 11:45:23 +02:00
Nicolò Boschi 48295b06e0 chore: fix formatting in llm_wrapper.py to pass verify-generated-files (#1534)
* chore: fix formatting in llm_wrapper.py to pass verify-generated-files

* chore: format n8n and openclaw files to pass verify-generated-files

* fix(openclaw): add missing includeSenderContext to plugin configSchema and uiHints
2026-05-08 11:12:35 +02:00
Nicolò Boschi 3f08b115f8 docs(zai): document z.ai provider and add default model (#1532)
* docs(zai): document z.ai provider and add default model

Follow-up to #1529. Adds z.ai (Zhipu GLM series) to the provider list,
example blocks, default-model table, and `.env.example`. Also wires
`zai` into `PROVIDER_DEFAULT_MODELS` so the new docs entry actually
matches what the engine resolves when only the provider is set.

* docs(zai): use glm-4.5-flash as default (free tier)

glm-4.5-air requires a paid balance on z.ai; flash is on the free
tier and works as a sensible default. Air is still listed in the
example as the paid-tier upgrade.
2026-05-08 10:50:40 +02:00
Nicolò Boschi b628716f15 fix(cp): improve access-key auth UX and harden middleware (#1533)
* fix(cp): improve access-key auth UX and harden middleware

- Move logout button from sidebar to header bar (next to GitHub icon),
  shown only when access-key auth is configured
- Remove redundant status bar from dashboard page
- Return 401 JSON for unauthenticated API requests instead of HTML redirect
- Redirect to /login on 401 in the API client (skip if already on /login)
- Allow /logo.png through middleware for the login page
- Replace brain emoji with Hindsight logo on login page
- Fix error message visibility in dark mode
- Add loading spinner for bank selector while banks are fetching
- Expose access_key_auth as a feature flag via version endpoint
- Document HINDSIGHT_CP_ACCESS_KEY in configuration and installation docs

* fix(cp): spread default features to handle unknown fields from API

* fix(cp): wrap login page in Suspense for useSearchParams
2026-05-08 10:40:50 +02:00
Rodolfo Hansen be696b0d38 feat(openclaw): prepend session-context block to retained transcripts (#1439)
When `dynamicBankGranularity` does not include `"user"`, every speaker
in an agent's bank ends up indistinguishable in similarity search --
memories from John look the same as memories from Peter, so recall can
mix them up. Bumping granularity to per-user is one fix, but it forces
fragmented banks and forfeits cross-user shared context (e.g. for an
ops/sprint-driver bot).

Add an opt-out `includeSenderContext` flag (default true) and a new
optional `sessionContext` parameter to `prepareRetentionTranscript`.
When provided, a small `[context] sender / channel / provider [/context]`
block is prepended to the transcript -- as a system-role message in the
JSON formats, or as a literal text block in the legacy text format.

That single header gives vector recall a strong, model-agnostic signal
to attribute and disambiguate memories without changing the bank
scheme. Filtered providers and missing fields collapse cleanly to null,
so the change is invisible when there's nothing useful to say.

Tests cover both formats, opt-out, missing-fields fallback, and the
no-context default.
2026-05-08 10:11:47 +02:00
Burgunthy 4c75cd9e37 feat: add z.ai (智谱) as first-class LLM provider (#1529)
Add z.ai (https://api.z.ai) as a supported provider in OpenAICompatibleLLM,
following the same pattern as deepseek, minimax, and openrouter.

Changes:
- openai_compatible_llm.py: add zai to valid_providers, base_url, api_key validation
- llm_wrapper.py: add zai to create_llm_provider routing, LLMConfig

Verified: retain (3276 in / 922 out tokens) + recall working with glm-4.5-air
2026-05-08 10:00:59 +02:00
Ariel AI c0ff87ea10 feat(cp): add optional access-key login for Control Plane (#1530)
Add HINDSIGHT_CP_ACCESS_KEY env var to enable a lightweight
shared-secret authentication gate for the Control Plane UI.

Features:
- Login page at /login with access key input form
- /api/auth/login endpoint validates key and sets HttpOnly session cookie
- /api/auth/logout endpoint clears session cookie
- Middleware protects all routes except /login, /api/auth/*, /api/health,
  /api/version, static assets, and _next
- returnTo query param preserves redirect after login
- Constant-time comparison for access key to prevent timing attacks
- Logout button in sidebar (when a bank is selected) and dashboard header
- Updated .env.example and docker-compose docs

Security:
- HttpOnly, SameSite=lax, Secure (production only) cookie
- 24-hour session lifetime
- Constant-time string comparison to prevent timing attacks
2026-05-08 09:37:30 +02:00
Chris Bartholomew 6c6ee73c56 fix(claude-code): use detail=metadata for agent_knowledge_list_pages (#1528)
agent_knowledge_list_pages was hitting GET /mental-models with no detail
parameter, so the API returned its default (detail=full) — synthesized
content + reflect_response for every page in the bank. On a bank with
many pages this produces a single JSON-RPC response that exceeds the
Claude Code MCP client's 16 MB without-newline-boundary buffer ceiling
and triggers a deterministic disconnect.

Reproduced locally driving the MCP server end-to-end:
  unpatched: 20,054,285 bytes in one JSON-RPC message → disconnect
  patched:   44,987 bytes, two messages → clean

The tool's docstring already promises "IDs and names only" — this aligns
the wire call with the documented contract. Agents that need the
synthesized content already use agent_knowledge_get_page, which keeps
detail=full and is unaffected.

Adds a focused regression test pinning the metadata projection.
2026-05-08 09:36:04 +02:00
Chris Bartholomew 7b82d05b77 fix(worker): propagate child error_message to failed batch_retain parent (#1527)
When a batch_retain parent transitions to 'failed' because at least one
child sub-batch failed, the parent's error_message was hardcoded to the
generic string "One or more sub-batches failed". Any consumer that
classifies failures by error_message (dashboards, alert filters, log
aggregators) loses signal once a batch grows children -- a class of
failures that all share the same root reason at the child level becomes
indistinguishable at the parent level.

Pull error_message in the siblings query and pick the most-common
non-empty failed-child message as the parent's error_message. When all
siblings failed for the same reason (the common case) the parent
inherits that reason verbatim; when reasons vary the most-common one is
still a useful representative. Falls back to the legacy generic string
only when no failed sibling carries an error_message at all, preserving
backward compat for that edge case.

Same change applied to both the worker poller's fallback path and the
memory engine's in-transaction path so the propagation behavior is
consistent regardless of which surface finalises the parent.

6 new unit tests for the helper plus an inheritance assertion added to
the existing integration test.
2026-05-08 09:35:38 +02:00
Chris f2a2f9fe40 fix(reflect): read document metadata from retain params (#1523) 2026-05-08 09:32:43 +02:00
Ben 8c6be6de6c blog: n8n Workflows Are Stateless. Hindsight Makes Them Compound. (#1511)
* blog: n8n Workflows Are Stateless. Hindsight Makes Them Compound.
2026-05-07 13:10:10 -04:00
Nicolò Boschi 8d77976ae9 fix(daemon): replace os.fork() with subprocess.Popen to fix MPS on macOS (#1519)
On macOS, os.fork() without exec() corrupts Apple framework state
(XPC, Metal/MPS, ObjC runtime). The daemon's double-fork pattern
caused SIGBUS crashes when PyTorch auto-selected the MPS backend
for local embeddings/reranker models.

Replace the double-fork in daemonize() with subprocess.Popen
(which uses posix_spawn on macOS), giving the daemon a clean
process where MPS works correctly. The re-exec'd child is
identified by the _HINDSIGHT_DAEMON_CHILD env var.

This also removes the macOS FORCE_CPU workaround from
hindsight-embed, since MPS now works natively in daemon mode.

Fixes #270, #1394, #1497
2026-05-07 18:58:34 +02:00
Nicolò Boschi 312bde1b4d docs: surface stable worker_id guidance and zombie-operation recovery (#1522)
* docs: surface stable worker_id guidance and zombie-operation recovery

Worker identity defaults to the container hostname, which Docker rotates
on every restart. That stranded several real deployments' consolidation
queues (issue #1470 and the related closed tickets #991 / #696 / #624).
Move the guidance from the configuration reference table — where it
only gets read after the bug bites — into the install path and add a
recovery section next to the decommission commands.

* docs(faq): add zombie-operations entry
2026-05-07 18:31:22 +02:00
Nicolò Boschi a22e8bdd22 fix(engine): remove multiplicative retry layers in fact extraction (#1412) (#1516)
Structured-output extraction had three nested retry loops that
multiplied on deterministic failures, burning up to 36 LLM calls
per chunk (inner 4 × middle 3 × outer 3).

- Remove outermost _extract_chunk_with_retry wrapper: its broad
  except-Exception added a 3× multiplier on top of already-bounded
  inner retries.
- Remove json_validate_failed retry from middle layer: the inner
  provider loop already retries 400 errors; re-entering the full
  LLM call for the same schema failure is wasted quota.
- Fix claude_code_llm.py: ValidationError was caught by a broad
  except-Exception and retried instead of raising immediately.
  Same input produces the same schema-violating output.
2026-05-07 18:26:18 +02:00
Nicolò Boschi 4088af369a fix(openclaw): backfill plugins.allow with hindsight-openclaw in setup wizard (#1521)
OpenClaw 2026.2.19+ logs a startup WARN whenever `plugins.allow` is
empty and non-bundled plugins are discovered:

  [plugins] plugins.allow is empty; discovered non-bundled plugins
            may auto-load: hindsight-openclaw (...). Set plugins.allow
            to explicit trusted ids.

Cosmetic — the plugin still loads — but the warning fires on every
gateway start and is the kind of noise users justifiably ask about.

`ensurePluginConfig` now adds `hindsight-openclaw` to `plugins.allow`
so the warning goes away. Conservative wrt user-curated lists:

- Undefined → set to `["hindsight-openclaw"]`.
- Existing array → append our id only when missing (idempotent).
- Existing array already containing our id → no-op.
- Non-array value (deliberate weirdness) → leave alone.

Four regression tests cover all four cases.
2026-05-07 18:18:52 +02:00
Nicolò Boschi be53972ab2 release(claude-code): v0.6.3 2026-05-07 18:14:38 +02:00
Nicolò Boschi 691c65acf8 feat(claude-code): resolve git worktrees + explicit directory-bank mapping (#1520)
* feat(claude-code): resolve git worktrees + explicit directory→bank mapping

Adds two new bank-resolution features so that working in a git worktree
or across multiple project directories doesn't accidentally fragment
memory across separate banks.

- resolveWorktrees (default true): detects git worktrees via
  `git rev-parse --git-common-dir` and resolves the project field to the
  main repository basename, so all worktrees of the same repo share one
  bank. Falls back to cwd basename if git is unavailable.
- directoryBankMap: explicit cwd → bankId mapping that takes priority
  over both static and dynamic modes, for users who want full control.

20 new tests cover worktree resolution, directory mapping, prefix
interaction, and graceful fallback paths.

* docs(claude-code): declare resolveWorktrees + directoryBankMap settings

Add the two new bank-resolution fields to the plugin's settings.json so
they show up in the canonical defaults, and document them in the
integration docs (Memory Bank table + a "Worktrees and explicit
mapping" subsection with a config example).
2026-05-07 18:14:04 +02:00
Nicolò Boschi bfa3115579 release(openclaw): v0.7.6 2026-05-07 17:48:43 +02:00
Nicolò Boschi ef600683c9 fix(openclaw): reuse existing token + URL when re-running setup wizard (#1518)
The wizard re-prompted for the API token / API key on every run even
when one was already stored in openclaw.json — confusing for users
(re-typing a long secret) and wasteful when running setup just to
backfill new fields like hooks.allowConversationAccess.

Now: if pluginConfig has an inline string secret (cloud token, api
token, llm api key), the wizard offers to reuse it (showing the last
4 chars masked, e.g. "Reuse the existing token (ends in …***1234)?").
Saying yes keeps the existing secret; saying no falls back to the
masked password prompt as before. SecretRef objects (env-var refs)
aren't pasteable so they keep the previous prompt path.

URL handling tightened up too:
- Cloud: prompt label adapts ("Reuse the configured Cloud URL X?" vs
  "Use the default Hindsight Cloud URL?") and reuses the existing URL
  on confirm.
- API: text prompt seeded with the existing URL via initialValue so
  the user can just press enter.
- API token confirm now defaults to "yes, needs token" when one is
  already configured, instead of always defaulting to no.

Adds a pure maskSecret helper in setup-lib.ts (testable without a
TTY) and three regression tests covering long token / very-short
input / surrounding whitespace.
2026-05-07 17:48:17 +02:00
Nicolò Boschi a34c0e7be3 release(openclaw): v0.7.5 2026-05-07 17:02:53 +02:00
Nicolò Boschi abf8487248 fix(openclaw): write hooks.allowConversationAccess in setup wizard (#1514)
* fix(openclaw): write hooks.allowConversationAccess in setup wizard

OpenClaw 2026.4.24 added a security gate (#71221) that silently drops
"conversation hooks" — including `agent_end`, which the plugin uses
to retain the transcript on every turn — for non-bundled plugins
unless `plugins.entries.<id>.hooks.allowConversationAccess` is
explicitly set to `true` in user config.

Symptom: openclaw logs `typed hook "agent_end" blocked because
non-bundled plugins must set ... allowConversationAccess=true`, the
plugin appears registered, retain count stays at 0, banks stay empty.
Affects every user on openclaw ≥ 2026.4.24 who installed via the
standard `hindsight-openclaw-setup` flow.

Fix: ensurePluginConfig (the helper every wizard mode calls before
saveConfig) now backfills `hooks.allowConversationAccess: true` when
the field is unset. Idempotent — re-running the wizard fixes existing
configs that pre-date the gate. We never override an explicit `false`,
since that's a deliberate user override.

Also extends the PluginEntry shape to include `hooks` and adds four
regression tests covering fresh, backfill, explicit-false, and
foreign-hooks-key cases.

* fix(openclaw): declare contracts.tools in plugin manifest

OpenClaw 2026.5.x added a second gate (loader.js:1448-1455): when a
plugin calls api.registerTool, the loader checks `record.contracts.tools`
(populated from the plugin manifest's `contracts.tools` array). If the
manifest doesn't declare the tool names, openclaw logs:

  ERROR [plugins] plugin must declare contracts.tools before registering
        agent tools (plugin=hindsight-openclaw, ...)

…and the registerTool call no-ops. Result on 2026.5.x: even with
enableKnowledgeTools=true, none of the agent_knowledge_* tools are
exposed to agents.

Fix: declare the seven agent_knowledge_* names in
openclaw.plugin.json's `contracts.tools` array so openclaw recognises
them at manifest-load time. Pure manifest change — runtime behavior is
still gated by `enableKnowledgeTools` in user config; this just lets
openclaw allow the registration when the runtime flag is on.

Verified locally on openclaw 2026.5.6 with the patched manifest copied
into the installed extension dir + a fresh gateway start: log goes
from "knowledge tools registered" + ERROR plugin-must-declare-contracts
→ "knowledge tools registered" with no error.

This is a pure manifest update — no code changes, no test changes
required.
2026-05-07 17:02:28 +02:00
Nicolò Boschi 5d867826a1 release(n8n): v0.1.3 2026-05-07 16:57:57 +02:00
BenandClaude Opus 4.7 e18ab10ac4 fix(n8n): drop hindsight-client runtime dep, inline HTTP calls (#1513)
* fix(n8n): drop hindsight-client runtime dep, inline HTTP calls

n8n's verified-node review (`npx @n8n/scan-community-package
@vectorize-io/[email protected]`) auto-rejects packages with
runtime dependencies via @n8n/community-nodes/no-restricted-imports.
The Hindsight node imported @vectorize-io/hindsight-client, which
triggered the rule.

Replaces the SDK calls with direct HTTP via n8n's built-in
`requestWithAuthentication` helper. The Bearer header is applied
automatically from the existing IAuthenticateGeneric credential — no
credential changes needed.

Endpoints used (verified against the SDK source we removed):
- Retain:  POST {apiUrl}/v1/default/banks/{bank_id}/memories
- Recall:  POST {apiUrl}/v1/default/banks/{bank_id}/memories/recall
- Reflect: POST {apiUrl}/v1/default/banks/{bank_id}/reflect

Body shapes match HindsightClient.retain/recall/reflect line-for-line
so server-side behavior is unchanged.

Test changes:
- Swapped the vi.mock() of @vectorize-io/hindsight-client for a mock
  of helpers.requestWithAuthentication on IExecuteFunctions
- All 22 tests still pass (8 in node-execute, 14 elsewhere)
- Added a new test asserting trailing-slash apiUrl is stripped before
  URL concatenation

Package changes:
- Drop @vectorize-io/hindsight-client from dependencies
- Bump 0.1.2 → 0.1.3

After this lands, run ./scripts/release-integration.sh n8n 0.1.3 to
publish 0.1.3 with provenance, then re-run the scan and submit at
creators.n8n.io.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(n8n): use httpRequestWithAuthentication (deprecated rename)

n8n's @n8n/community-nodes ESLint plugin flags requestWithAuthentication
as deprecated in favor of httpRequestWithAuthentication. Caught by
running the full plugin ruleset locally against the dist before publish:

  no-deprecated-workflow-functions errors in Hindsight.node.js at
  lines 217, 241, 258 (the three operation HTTP calls)

Same signature, same auth behavior — just the modern helper name.
After this rename, all 25 community-nodes lint rules pass clean.

All 22 vitest tests still pass with the helper rename.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(n8n): leave version at 0.1.2 — release pipeline owns the bump

Per Nicolo: the release-integration tooling owns version bumps. This
PR should ship the code change only (drop hindsight-client dep, switch
to httpRequestWithAuthentication, retarget tests). Version 0.1.2 →
0.1.3 will happen automatically when release-integration.sh runs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(n8n): match main's package-lock.json version field

main's package-lock.json has version "0.1.0" (out of sync with
package.json's "0.1.2", but that's the state on main). The previous
revert overshot to "0.1.2" — restoring to "0.1.0" so the lockfile
diff vs main no longer touches the version field.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-07 16:56:39 +02:00
Nicolò Boschi 39d31ad259 perf(worker): scope progress-stats fanout to schemas with pending work (#1509)
The progress logger (_log_progress_if_due) previously ran two heavy
COUNT/GROUP BY queries against every tenant schema on every stats cycle
(every 30s). With N tenants and W workers that's 2*N*W queries per cycle.

Reuse _scan_active_schemas() — which already calls the optional
schemas_with_pending_work() routine when installed (O(1) marker-table
read) or falls back to per-schema EXISTS checks — to pre-filter schemas
before the expensive breakdown queries. Union with schemas that have
locally-tracked in-flight tasks so processing worker counts stay accurate.

Also wraps per-schema queries in try/except for partially-provisioned
tenants and caps the schema list in log output to 20 entries.
2026-05-07 16:26:48 +02:00
Nicolò Boschi 0f2499c7cb release(opencode): v0.2.0 2026-05-07 14:41:34 +02:00
Nicolò Boschi 72ff603ff1 release(codex): v0.3.0 2026-05-07 14:41:14 +02:00
Evo 42ad17f679 docs(entity-labels): document type="map" structured entity groups (#1508)
* docs(entity-labels): document type="map" structured entity groups

* docs(entity-labels): mirror type="map" docs into sidecar reference
2026-05-07 14:37:35 +02:00
Nicolò Boschi 0dfbf3fae7 release(openclaw): v0.7.4 2026-05-07 13:47:45 +02:00
Nicolò Boschi c95206e0eb fix(openclaw): pass enableKnowledgeTools through getPluginConfig (#1507)
* fix(claude-code): bootstrap Python deps via venv in CLAUDE_PLUGIN_DATA

Install Python deps into ${CLAUDE_PLUGIN_DATA}/venv on demand, and
launch the MCP server through that venv's interpreter — no global
pip install, isolated to the plugin, survives plugin updates.

How it works:
- requirements.txt declares deps (mcp>=1.0.0)
- scripts/run_mcp.sh creates the venv on first run (or when
  requirements.txt changes vs the cached copy in plugin data),
  pip-installs into it, and execs ${VENV}/bin/python on mcp_server.py
- .mcp.json now points at the wrapper instead of bare 'python3', so
  the MCP server always runs with the plugin's pinned interpreter
  (avoids version mismatches: e.g. system /usr/bin/python3 was 3.9
  but venv was built with 3.11)

Tested locally: cold start ~25s (venv + pip), warm start ~0.4s,
all 9 agent_knowledge_* tools register correctly.

* docs(claude-code): document knowledge tools and subagent skill

The Claude Code integration now ships an MCP server with
agent_knowledge_* tools and a /hindsight-memory:create-agent skill
for scaffolding memory-backed subagents. Document both, plus the
new enableKnowledgeTools config flag and venv bootstrap behavior.

* fix(openclaw): pass enableKnowledgeTools through getPluginConfig

The flag was declared on PluginConfig and read at the
agent_knowledge_* tool registration site, but never copied through
getPluginConfig — so the runtime value was always undefined and the
if-branch never entered, regardless of what users (or the SDA CLI)
wrote into openclaw.json. Live since the feature was added on
Apr 29 2026.

Adds the field to the whitelist (defaulting to false on missing or
non-boolean values, matching the type definition) plus a regression
test in getPluginConfig.
2026-05-07 13:47:14 +02:00
Nicolò Boschi 2b725bc448 feat: add map-type entity labels for structured entity extraction (#1370) (#1505)
Add a new `type="map"` option to entity_labels that lets users define
structured entity types with named fields. Each field is stored as a
flat `key:field:value` entity string (e.g. `person:name:Alice`,
`person:role:Engineer`), reusing the existing entity storage and
co-occurrence mechanisms with no DB changes.

Fields support all types recursively: text, value, multi-values, and
nested map — enabling schemas like `person:address:city:New York`.

Control plane UI updated with a recursive MapFieldsEditor component
that renders all label types (top-level and nested) using the same
shared component with tree-style visual nesting.
2026-05-07 13:32:08 +02:00
Nicolò Boschi b20bcb62c1 follow-up to #1459: AlloyDB ScaNN docs + review-nit cleanups (#1506)
* docs: document AlloyDB ScaNN vector extension

Follow-up to #1459. Adds `scann` to the supported vector-extension
list in installation.md and configuration.md, with installation
hints, the 10k-row deferred-build caveat, AlloyDB Omni compose
pointer, and the relaxed switching rules (switching *to* scann is
allowed with existing data).

* refactor(_vector_index): address review nits from #1459

- Lift `from sqlalchemy import text` (and add `Connection`) to module
  top in `_vector_index.py`; both helpers now have proper type hints.
- Make `pg_diskann` a first-class entry in a new `RESOLVED_EXTENSIONS`
  tuple via `_normalize_resolved`. The configurable boundary stays
  strict (`validate_extension` rejects `pg_diskann`); the resolved
  helpers (`index_using_clause`, `index_type_keyword`,
  `minimum_rows_for_index`, `uses_per_bank_vector_indexes`) accept it
  without per-call special-case branches. Behavior is identical.
- Harden `test_alembic_vector_migrations_freeze_vector_sql_locally`
  to resolve the migrations dir from `__file__` so the test no longer
  depends on cwd.
- Add a one-liner explaining why `_drop_per_bank_vector_indexes`
  inlines identifiers instead of using bound parameters (DDL).

Tests: tests/test_vector_index.py (10), tests/test_migration_shape.py
+ tests/test_migrations_thread_safety.py (64). Lint and ty clean.
2026-05-07 13:12:03 +02:00
Nicolò Boschi 095f397770 docs(installation): bake custom models into image instead of PVC (#1504)
* docs(installation): bake custom models into image instead of PVC

Add a runnable example under `docker/docker-compose/custom-models/` that
extends the slim image and pre-downloads non-default embedder/reranker
models at build time. Document this as the recommended pattern for
production over enabling the Helm `modelCache` PVC: image layers cache
per node for free, while a PVC adds storage cost, pins pods to a node,
and needs lifecycle management on uninstall/upgrade. Add pointers from
the api/worker `modelCache` values in the chart to the new section.

Refs vectorize-io/hindsight#1383

* fix(docker/custom-models): install local-ml deps via uv into the venv

The slim image's venv at /app/api/.venv was created by uv sync and does
not ship its own pip, so a bare `pip install` falls through to the
system pip and lands the packages in /home/hindsight/.local — invisible
to the venv python that runs hindsight-api at runtime. Use
`uv pip install --python /app/api/.venv/bin/python` to install into the
venv directly. Verified the resulting image loads both baked-in models
with HF_HUB_OFFLINE=1.

* docs(installation): trim custom-models section to a tip and pointer

The Dockerfile/compose example in docker/docker-compose/custom-models/
already has its own README explaining when to use it and why it beats
the modelCache PVC. The installation page only needs to point readers
there.
2026-05-07 12:59:19 +02:00
Nicolò Boschi a1c1b7decd fix(worker): probe pg_proc before calling optional schemas_with_pending_work() (#1503)
* fix(worker): probe pg_proc before calling optional schemas_with_pending_work() (#1408)

The poller called the optional PL/pgSQL routine `schemas_with_pending_work()`
unconditionally on every cycle. When the routine isn't installed (the default
for fresh deployments), Postgres logs a server-side `function does not exist`
error every ~30s even though the Python code silently caught the exception.

This adds a small `OptionalRoutines` registry/cache in
`hindsight_api/engine/db/optional_routines.py` that probes `pg_proc` once on
first lookup and memoises the result for the life of the process. The poller
now calls the routine only when it's actually installed and falls back to the
per-schema EXISTS path otherwise — without any spurious server-side errors.

The registry also carries the canonical install SQL for each routine inline,
so anyone touching the optimisation has a single source of truth (the previous
docstring lived only on `_scan_active_schemas`).

Tradeoffs:
- Probe is permanently cached: installing the routine on a running cluster
  requires a worker restart. Acceptable because these routines are expected
  to be installed once at deploy time, and a probe-per-poll would defeat the
  optimisation.
- Non-PG backends short-circuit to False without touching the DB.

* refactor(worker): drop routine body from registry; document contract instead

Hindsight never installs schemas_with_pending_work() — operators do. Keeping
the SQL body in the API repo would drift from whatever is actually deployed
and falsely imply ownership. Replace the install_sql field on OptionalRoutine
with a contract docstring describing the expected signature, return shape,
and semantic constraints, so any operator-supplied implementation is
interchangeable as long as it matches.

The test installs a minimal contract-satisfying stub locally rather than
relying on a registry-supplied body.
2026-05-07 12:46:09 +02:00
Can Bölük e4422a9b40 Add AlloyDB ScaNN vector index support (#1459)
* feat: add AlloyDB ScaNN vector index support

* fix(hindsight_api): resolved SCANN index mismatch by deferring creation

- Added SCANN-aware vector index helpers with a 10k minimum-row threshold.
- Updated bank index generation to skip per-bank clauses and index creation when unsupported.
- Updated vector migrations to validate extension names and skip SCANN-specific index creation or drops.
- Updated migration reconciliation to use row counts and defer SCANN index recreation instead of mismatch errors.
- Added tests for SCANN deferral, per-bank index ineligibility, and migration SQL freeze behavior.

* docs: add AlloyDB Omni compose example
2026-05-07 12:35:35 +02:00
Nicolò Boschi e63100b6a2 ci: cosign-sign release images + document verification (#1502)
* ci: cosign-sign release images + document verification

Folds the now-proven keyless cosign signing flow into the release
workflow so future releases sign automatically alongside the build,
and adds a "Verifying image signatures" subsection to the Docker
installation docs so downstream consumers know how to verify.

The verification regex accepts signatures from both sign-images.yml
(used to backfill 0.6.0) and release.yml (future releases) so a
single documented command covers all signed tags.

Closes #1484

* docs: tighten cosign verification section
2026-05-07 12:08:01 +02:00
Nicolò Boschi 59ffb1d4a3 ci: add manual workflow to cosign-sign published GHCR images (#1495)
Standalone workflow_dispatch path that resolves a published tag to its
manifest digest, signs it with keyless OIDC via cosign, and verifies the
signature in the same job. Decoupled from release.yml so we can backfill
v0.6.0 (and prior) without coupling supply-chain signing to the release
cut. Once proven, the same sign step will fold into release.yml.

Refs #1484
2026-05-07 11:37:21 +02:00
Evo 976a4e54c6 docs(env): document HINDSIGHT_API_READ_DATABASE_URL in .env.example (#1496) 2026-05-07 11:04:16 +02:00
Evo 1af0907d14 docs(cli): document --strategy flag for memory retain-files (#1499)
* docs(cli): document --strategy flag for memory retain-files

* docs(cli/skills): mirror --strategy flag example for memory retain-files
2026-05-07 11:03:59 +02:00
Ben a3465dd1fe blog: Your Claude Code Subagents Don't Share What They Learn (#1456)
* blog: Your Claude Code Subagents Don't Share What They Learn
2026-05-06 15:13:19 -04:00
Nicolò Boschi 375747f516 feat(cli): add --strategy flag to memory retain-files (#1494)
Allows callers to pick a named retain strategy when bulk-importing files,
overriding the bank's default. The API already accepts a per-file strategy
in FileRetainMetadata; this just wires a CLI flag through to the multipart
metadata.

Closes #1492
2026-05-06 17:52:41 +02:00
Nicolò Boschi a5cef602bc fix(docker): chmod 755 /home/hindsight to support --user UID:GID overrides (#1493)
The default 0700 on /home/hindsight blocks traversal when running with
--user UID:GID for bind-mount ownership matching. This adds chmod 755
in both api-only and standalone stages so non-owner UIDs can traverse
the home directory.

Closes #1481
2026-05-06 17:37:06 +02:00
Nicolò Boschi 2161c4e815 chore: stabilize CI — docs-skill pre-commit hook + retain dict-mutation fix (#1490)
* ci: add pre-commit hook to keep skills/hindsight-docs in sync

The CI verify-generated-files job has been failing on ~82% of recent
runs because PRs touch hindsight-docs/src/pages/changelog/ or
hindsight-docs/static/openapi.json without re-running
./scripts/generate-docs-skill.sh, leaving the committed
skills/hindsight-docs/references/ copy stale.

Catch the drift locally instead. The hook regenerates and, if the
working tree diverges from the index after regen, fails the commit
with a clear message pointing the author at `git add skills/hindsight-docs/`.

The pre-commit dispatcher (.githooks/pre-commit) already iterates every
*.sh in scripts/hooks/, so the new file is picked up automatically.

* fix(retain): stop mutating caller-provided content dicts

PR #1398 (memory pressure) added an in-place pop of the "content" key
on contents_dicts after building combined_content, to release per-item
strings the engine no longer needs. Because the engine forwarded the
caller's dict objects all the way through (memory_engine →
_retain_batch_async_internal → orchestrator.retain_batch), the pop
reached back through the same references and stripped the key from
the caller's input. Any code path that holds onto the contents list
after retain_batch_async returns then trips KeyError: 'content'.

This is what was making test_extensions.py::TestOperationHooksParameters::
test_retain_pre_hook_receives_all_parameters fail intermittently on
main (the streaming path triggers the pop; non-streaming paths skip it).

Fix:
- memory_engine.py: take an engine-owned shallow copy of contents
  after the validator hook so the orchestrator can mutate freely
  without leaking to the caller. Strings are shared by reference,
  so the copy adds only ~150 bytes of dict overhead per item —
  negligible vs the multi-MB strings.
- orchestrator.py (_streaming_retain_batch): clear combined_content
  immediately after handle_document_tracking / upsert_document_metadata
  in all three first-batch paths (no-facts skip, mini-batch DB work,
  post-loop fallback). Once tracking persists the document, nothing
  reads combined_content again, so releasing it shrinks the lifetime
  of the per-document text from "until function returns" to "until DB
  write completes" — recovering the bulk of #1398's memory savings
  without the caller-mutation side effect. nonlocal declarations on
  _process_db_batch and _run_mini_batch_db_work are required because
  Python infers combined_content as local once any branch assigns to it.

Memory profile vs PR #1398:
- #1398 benchmark shape (caller releases its reference at call time):
  identical sustained, brief 2x peak during the combined_content +
  per-item-strings overlap window before tracking completes. Other
  PR #1398 savings (chunks, batch lists, sanitized_content) untouched.
- HTTP / FastAPI callers (request body holds strings until the handler
  returns): no observable change — those strings were going to live
  through the request anyway.
2026-05-06 17:18:52 +02:00
Nicolò Boschi 22f5fcf414 release(n8n): v0.1.2 2026-05-06 17:02:45 +02:00
Ben 8ea68bfbc2 ci(release): add --provenance to npm publish for n8n Verified (#1491) 2026-05-06 16:55:11 +02:00
Nicolò Boschi e32c951957 docs(claude-code): document knowledge tools and subagent skill (#1487)
* fix(claude-code): bootstrap Python deps via venv in CLAUDE_PLUGIN_DATA

Install Python deps into ${CLAUDE_PLUGIN_DATA}/venv on demand, and
launch the MCP server through that venv's interpreter — no global
pip install, isolated to the plugin, survives plugin updates.

How it works:
- requirements.txt declares deps (mcp>=1.0.0)
- scripts/run_mcp.sh creates the venv on first run (or when
  requirements.txt changes vs the cached copy in plugin data),
  pip-installs into it, and execs ${VENV}/bin/python on mcp_server.py
- .mcp.json now points at the wrapper instead of bare 'python3', so
  the MCP server always runs with the plugin's pinned interpreter
  (avoids version mismatches: e.g. system /usr/bin/python3 was 3.9
  but venv was built with 3.11)

Tested locally: cold start ~25s (venv + pip), warm start ~0.4s,
all 9 agent_knowledge_* tools register correctly.

* docs(claude-code): document knowledge tools and subagent skill

The Claude Code integration now ships an MCP server with
agent_knowledge_* tools and a /hindsight-memory:create-agent skill
for scaffolding memory-backed subagents. Document both, plus the
new enableKnowledgeTools config flag and venv bootstrap behavior.
2026-05-06 15:51:57 +02:00
Nicolò Boschi a86d5381d5 fix(packaging): hard-pin meta packages to matching hindsight-api-slim (#1486)
The meta packages (hindsight-api, hindsight-all, hindsight-all-slim,
hindsight-dev) are pure entry-point shims — all real code, including
__version__ shown on the startup banner, lives in hindsight-api-slim.
Their dependency on slim was a stale floor (>=0.4.17), so
`pip install -U hindsight-api==0.6.0` left an older slim in place and
the server reported the previous version.

Hard-pin each meta package to the matching slim/api version, and teach
scripts/release.sh to rewrite the pin alongside the existing
`version = "..."` bumps so future releases stay in sync.
2026-05-06 15:27:38 +02:00
Nicolò Boschi efe5ff8494 feat(perf): publish perf-test results to external dashboard (#1474)
* feat(perf): publish perf-test results to external dashboard repo

Adds `--benchmark-output-dir` to perf-test, which emits two JSON files
in github-action-benchmark format: latency.json (smaller-is-better:
durations + recall p50/p95/p99/mean) and throughput.json (bigger-is-
better: items/queries/memories per sec). The Performance Tests workflow
now publishes both to vectorize-io/hindsight-continuous-performance-
monitor's gh-pages branch on each scheduled run.

Iteration mode (TEMP — search "TEMP" to revert before merge):
push trigger on this branch, default scale=small, locomo skipped
unless manually dispatched.

Setup needed (one-time):
- PAT with Contents:write on the dashboard repo, stored as secret
  PERF_DASHBOARD_TOKEN.
- After the first run creates gh-pages there, enable Pages on that
  repo (Settings → Pages → gh-pages branch).

* fix(perf): wipe benchmark working dir between latency and throughput publishes

github-action-benchmark clones the dashboard repo into a fixed
./benchmark-data-repository directory and doesn't clean up, so the
second invocation in the same job fails with 'destination path already
exists'.

* feat(perf): replace github-action-benchmark with custom dashboard publisher

Drops the two benchmark-action steps (and the dead `--benchmark-output-dir`
flag + `_to_benchmark_entries` helper in system_perf.py) in favour of a
single `scripts/benchmarks/publish-perf-results.sh` step. The script:

1. Reads the perf-test JSON output.
2. Enriches it with commit metadata (subject, author, author_date,
   commit URL, PR URL via `gh api commits/<sha>/pulls`).
3. Clones the dashboard repo's gh-pages branch using PERF_DASHBOARD_TOKEN.
4. Writes data/<timestamp>-<short_sha>.json and prepends the run to
   data/index.json (newest first).
5. Commits and pushes (with one rebase-retry on push rejection).

The matching custom static site lives on gh-pages of
vectorize-io/hindsight-continuous-performance-monitor (separate commit
in that repo).

* perf(workflow): publish dashboard on workflow_dispatch too

* feat(perf): publish workflow run URL and LoComo results to dashboard

Perf script now embeds workflow_run.{id,url} in each enriched run JSON
and the manifest entry, sourced from default GitHub Actions env vars
(GITHUB_RUN_ID + GITHUB_REPOSITORY).

LoComo gets its own publish script (publish-locomo-results.sh) and a
new step in the locomo job. The script strips per-question
detailed_results (kept in the workflow artifact) before pushing — keeps
each run small enough for git. Output lands at:
  data/locomo/<timestamp>-<short_sha>.json
  data/locomo-index.json
The matching dashboard page (locomo.html) is in the dashboard repo.

* perf(workflow): revert iteration-mode TEMP markers

Restores the production defaults that were temporarily flipped while
iterating on the dashboard:
- drop the push trigger on feat/perf-dashboard
- default scale: small → large
- default locomo_skip: true → false
- locomo job condition: workflow_dispatch-only → inputs.locomo_skip != true

Scheduled cron now runs the full suite + LoComo daily and publishes
to the dashboard.
2026-05-06 15:12:11 +02:00
Nicolò Boschi a3e20f995f release(claude-code): v0.6.2 2026-05-06 15:02:27 +02:00
Nicolò Boschi 012c100ebf fix(claude-code): bootstrap Python deps via venv in CLAUDE_PLUGIN_DATA (#1485)
Install Python deps into ${CLAUDE_PLUGIN_DATA}/venv on demand, and
launch the MCP server through that venv's interpreter — no global
pip install, isolated to the plugin, survives plugin updates.

How it works:
- requirements.txt declares deps (mcp>=1.0.0)
- scripts/run_mcp.sh creates the venv on first run (or when
  requirements.txt changes vs the cached copy in plugin data),
  pip-installs into it, and execs ${VENV}/bin/python on mcp_server.py
- .mcp.json now points at the wrapper instead of bare 'python3', so
  the MCP server always runs with the plugin's pinned interpreter
  (avoids version mismatches: e.g. system /usr/bin/python3 was 3.9
  but venv was built with 3.11)

Tested locally: cold start ~25s (venv + pip), warm start ~0.4s,
all 9 agent_knowledge_* tools register correctly.
2026-05-06 15:01:41 +02:00
Chris BartholomewandNicolò Boschi cf9b1f59a9 feat(engine): optional read-only backend for recall queries (#1460)
* feat(engine): optional read-only backend for recall queries

Add a second `DatabaseBackend` (`MemoryEngine._read_backend`) that is
populated when the new `HINDSIGHT_API_READ_DATABASE_URL` env var is set.
The recall search path (`_search_with_retries`, which orchestrates the
parallel semantic + BM25 + graph + temporal retrievers) acquires this
backend via the new `_get_read_backend()` accessor, so all of recall's
heavy SELECT traffic flows through it. Reflect benefits transparently
because it composes recall via its agent-loop tools.

When the env var is unset, `_read_backend` is the same object as
`_backend`. All call sites are unconditional and behaviour is
bit-identical to before this change. Verified by
`test_read_backend_aliases_primary_when_url_unset`.

Intended deployment: front the read URL with a pgbouncer-style pooler
that routes to read-only standbys. Operators can then enable read
offload for individual workloads (e.g. async workers where slight
replication lag is acceptable) by setting the env var on those pods,
while keeping API pods on the primary URL for read-after-write
correctness on synchronous user requests.

Constraints:
- PostgreSQL backend only. The Oracle backend's abstraction layer does
  not yet model a second pool, so the engine silently falls back to the
  primary backend when the URL is set with `database_backend=oracle`.
- The read backend MUST NOT be used for writes — there is no guarantee
  the underlying server is the primary. Only the recall retrieval
  pipeline is wired to use it. All other call sites continue to use
  `_backend` / `_get_backend()`.
- Cleanup in `MemoryEngine.close()` shuts down the read backend only
  when it is a distinct object from `_backend`, so the alias case is
  not double-closed.

Tests:
- `test_config_validation.py`: read_database_url defaults to None when
  unset, loads when set, treats empty string as unset, and is masked in
  startup logs alongside the primary URL.
- `test_read_backend.py`: alias semantics when unset, distinct backend
  with separate pool when set, accessor returns the right backend in
  both cases, close() terminates the distinct read backend.

`uv run ruff check` clean. `uv run ruff format` clean. `uv run ty check`
clean. New tests pass; existing config tests still pass.

* refactor: add independent read pool knobs and clean up read backend init

- Add HINDSIGHT_API_READ_DB_POOL_MIN_SIZE / READ_DB_POOL_MAX_SIZE env
  vars so the read pool can be sized independently from the primary.
- Store read_database_url in __init__ from config instead of re-reading
  the global config singleton in initialize().
- Trim redundant comments and docstrings.

* fix: document read-replica env vars and fix test hygiene

- Add READ_DATABASE_URL, READ_DB_POOL_MIN_SIZE, READ_DB_POOL_MAX_SIZE
  to configuration.md.
- Remove unused `import os` from test_read_backend.py.
- Use monkeypatch instead of os.environ in test_log_config_masks_read_database_url.

* chore: regenerate docs skill and openapi spec

---------

Co-authored-by: Nicolò Boschi <[email protected]>
2026-05-06 14:51:25 +02:00
Nicolò Boschi 5a0cb4a517 feat(control-plane): enrich bank dropdown with memory stats (#1479)
* feat(control-plane): enrich bank dropdown with memory stats and activity

Add fact_count and last_document_at to the bank list API response so the
control plane dropdown can show at-a-glance stats for each bank: a
proportional background bar for relative memory volume, compact count
(k/M), and time since last document ingestion. Banks are sorted by most
recently active first. Popover border color softened globally.

* test: assert bank list returns fact_count and last_document_at
2026-05-06 14:46:55 +02:00
Nicolò Boschi 17b4b2f86e release(openclaw): v0.7.3 2026-05-06 14:33:51 +02:00
Nicolò Boschi d37940a9e1 feat(openclaw): drop redundant before_agent_start + add debugPerfTiming (#1477)
* feat(openclaw): drop redundant before_agent_start hook + add debugPerfTiming

Two unrelated-but-tiny openclaw improvements:

- #1354: Stop registering `before_agent_start`. Its body only called
  `resolveAndCacheIdentity()` + emitted a debug log. The same identity
  resolution already happens in `before_dispatch` (earlier in the
  inbound path), `before_prompt_build` (re-resolves before recall, can
  infer senderId from prompt content), and `agent_end` (re-resolves
  before retain). Subscribing here was duplicate work on the hot path.

- #1406: Add `debugPerfTiming?: boolean` plugin config flag (default
  false). When enabled, the plugin emits one info-level perf line per
  recall path and per retain path:

    perf: before_prompt_build hook_total=4200ms recall_main=3800ms source=fresh results=3
    perf: agent_end hook_total=1200ms retain=1100ms outcome=ok bank=main messages=4

  Lets users diagnose latency without patching the dist. The
  `source=fresh|reused` field reflects in-flight recall dedup; the
  `outcome=ok|queued|error` field reflects whether retain succeeded
  inline, was queued for retry, or failed outright.

Also fixes a stale comment that referenced before_agent_start where the
actual lifecycle stage is before_prompt_build.

* fix(openclaw): sync manifest with PluginConfig type + add parity test

OpenClaw's plugin loader runs configSchema validation with
`additionalProperties: false`, so any PluginConfig field not declared
in openclaw.plugin.json is silently rejected at config-set time. The
manifest had drifted from the type:

- retainMission, observationsMission (added in #1473) — never declared
- debugPerfTiming (added earlier in this PR) — never declared
- retainDocumentScope — pre-existing gap, declared now
- enableKnowledgeTools — was in configSchema but missing from uiHints

All five are now in both configSchema.properties and uiHints. Also
fixed the bankMission description to match the corrected README from
#1353 (only affects /reflect, not retain).

Added a manifest.test.ts parity test that compares the type's keys to
the manifest's declared keys and fails on either side of drift. This
is the same class of bug as #1443 (whitelist drift) — having a test
prevents the next round.
2026-05-06 14:31:33 +02:00
Nicolò Boschi d6b7fad43a chore(deps): bump pg0-embedded to >=0.14.0 (#1476)
pg0 0.14.0 bundles libxml2.so.2 + libicu70 inside the binary and
extracts them next to the embedded postgres at first run, so the host
no longer needs libxml2/libicu installed system-wide.

Unblocks embedded mode on:
- Ubuntu 25.10 (Plucky) and the upcoming 26.04 LTS, where libxml2
  bumped to .so.16 and the .so.2 SONAME is gone (#1361)
- Modern Arch / EndeavourOS, where libxml2 was split out into the
  optional `extra/libxml2-legacy` package (#919)
- Other modern glibc distros where the bundled theseus-rs postgres
  failed with "error while loading shared libraries: libxml2.so.2"

The runtime lib bundle ships only on linux-*-gnu builds; macOS,
Windows, and the musl Linux wheel get an empty bundle (their lib
story is unchanged).

Note: this does not fix the second half of #1361 (hindsight-openclaw
strips HINDSIGHT_EMBED_API_DATABASE_URL when regenerating the profile
env file) — that bug lives in hindsight-integrations/openclaw and
needs a separate fix.

Release notes: https://github.com/vectorize-io/pg0/releases/tag/v0.14.0
2026-05-06 14:28:31 +02:00
Nicolò Boschi 64f430bc71 release(claude-code): v0.6.1 2026-05-06 12:51:46 +02:00
Nicolò Boschi 0231094df1 feat(claude-code): create-agent skill understands SDA layout (#1475)
* feat(claude-code): create-agent skill understands SDA directory layout

When invoked as /hindsight-memory:create-agent <name> from <path>, the skill
now knows the directory was prepared by the SDA installer and contains:
- Content files (.md, .txt, etc.) to ingest
- Optional bank-template.json with exact mental model definitions

The skill ingests files via agent_knowledge_ingest_file, then either:
- Creates the exact mental models from bank-template.json, or
- Creates 3 pages that make sense based on content (no template)

* fix(claude-code): retainToolCalls default false, remove agentName empty override

- Default retainToolCalls to false. Tool calls inflate retained content
  significantly and are mostly noise for memory extraction.
- Remove "agentName": "" from settings.json so the Python DEFAULTS value
  ("claude-code") wins. Empty string in settings.json was overriding
  the proper default, producing bank IDs like "::my-project".

* chore: regenerate docs skill
2026-05-06 12:50:47 +02:00
Nicolò Boschi aca03832f8 fix(openclaw): mission semantics + retainQueue config whitelist (#1473)
Addresses three triaged issues against the openclaw plugin:

- #1270: Stop substituting a default `bankMission` when none is configured.
  Previously every gateway restart re-stamped the default text via
  `createBank({reflectMission})`, clobbering per-bank missions written
  out-of-band via `PATCH /banks/{id}`. Empty/unset is now a true opt-out.

- #1353: Expose `retainMission` and `observationsMission` plugin config
  fields. They each map to the matching bank-config column on first use,
  so users can steer retain extraction and observation consolidation
  declaratively in `openclaw.json` instead of patching the bank API
  out-of-band. README clarified that `bankMission` only affects reflect.

- #1443: Add `retainQueuePath`, `retainQueueMaxAgeMs`, and
  `retainQueueFlushIntervalMs` to the `getPluginConfig()` whitelist.
  These keys were declared in the plugin schema and read by queue init,
  but the strict whitelist silently dropped them — so the queue always
  used the hardcoded default path regardless of user config.

Mission stamping is now centralised in `applyConfiguredMissions()` and
gated by `hasConfiguredMissions()`, replacing six ad-hoc `setMission`
call sites with a single helper that no-ops when nothing is configured.
2026-05-06 12:05:39 +02:00
Nicolò Boschi c9145805e2 fix(retain): reduce memory pressure by clearing content references after use (#1455)
The streaming retain pipeline held multiple redundant copies of document
content in memory for the entire duration of processing.

Changes:
- Clear contents[].content after chunking (chunks are the working set)
- Pop contents_dicts["content"] after building combined_content
- Clear sanitized_content after hash computation
- Clear all_pre_chunks[i] after each chunk is extracted and queued
- Clear batch_contents/extracted/processed/chunk_meta after DB commit

Benchmark (50MB document, 16,666 chunks, mock LLM):
                Baseline    With Fix
  Facts:        148,575     148,600   (identical)
  RSS Growth:   1,190MB     61MB      (19.5x reduction)
  Ratio:        24.9x       1.3x content size
2026-05-06 09:26:21 +02:00
Nicolò Boschi c124b0f28b chore: remove self-driving-agents CLI — moved to vectorize-io/self-driving-agents (#1461)
The CLI source, tests, and CI have been moved to
https://github.com/vectorize-io/self-driving-agents and published
as @vectorize-io/[email protected] from that repo.

Removed:
- hindsight-tools/self-driving-agents/ (source + tests)
- CI job test-self-driving-agents from test.yml
- Workspace entry from root package.json
- Tool entry from release-tool.sh
2026-05-06 09:12:30 +02:00
Nicolò Boschi 0b38269a8f docs: add 0.6.0 changelog and release blog post (#1458)
* docs: add 0.6.0 changelog and release blog post

- Generate changelog entry for 0.6.0 (Oracle 23ai, self-driving agents, Dify, n8n, SmolAgents, AgentCore)
- Add "What's new in Hindsight 0.6.0" blog post
- Fix package-lock.json sync for docs workspace

* docs: remove self-driving agents from 0.6.0 changelog and blog post

* docs: remove Claude Code changes from 0.6.0 changelog and blog post
2026-05-05 20:15:30 +02:00
Nicolò Boschi b967e1c8e2 fix: sync package-lock.json for [email protected]
The release script bumped package.json versions but didn't regenerate
the lockfile, causing npm ci to fail in CI for workspaces that depend
on @vectorize-io/hindsight-client.
2026-05-05 18:14:24 +02:00
Nicolò Boschi 05f52b0811 Release v0.6.0
- Update version to 0.6.0 in all components
- Regenerate OpenAPI spec and client SDKs
- Python packages: hindsight-api, hindsight-dev, hindsight-all, hindsight-embed
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- hindsight-all npm wrapper: hindsight-all-npm
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
- Create documentation version-0.6
2026-05-05 17:49:48 +02:00
Nicolò Boschi 23dc07b0d4 fix: regenerate docs skill to sync with removed config (#1454)
* fix: resolve CI failures in verify-generated-files, deno tests, and LLM acceptance

- Format n8n integration files with prettier (out of sync on main)
- Format postgresql.py (ruff reformatting)
- Format self-driving-agents tool files with prettier
- Skip jest.spyOn-based abort signal tests when running under Deno
  (jest global is not available in the Deno test runner)
- Upgrade bedrock LLM acceptance model from nova-2-lite to nova-2-pro
  (lite model too weak for fact extraction quality assertions)

* fix: revert bedrock model back to nova-2-lite for LLM acceptance tests
2026-05-05 17:40:33 +02:00
Nicolò Boschi 0e344a24ff release(claude-code): v0.6.0 2026-05-05 17:21:03 +02:00
Nicolò Boschi 9cf3890e0f docs(claude-code): update README for v0.6.0 (#1457)
* docs(claude-code): update README for v0.6.0 — knowledge tools, MCP server, subagents

* fix(claude-code): cross-platform Python fallback in hooks (#1413)

Hook commands now try python3 first, falling back to python if
python3 is not found (e.g. Windows where python3 is a Microsoft
Store stub that returns "Permission denied").

All hook scripts exit 0 on errors (graceful degradation), so the
|| fallback only triggers on "command not found" (exit 127) or
"permission denied" from the Windows python3 stub.
2026-05-05 17:19:55 +02:00
Nicolò Boschi 1b9d6d9160 feat(claude-code): knowledge tools, subagents, and create-agent skill (#1450)
* refactor(claude-code): simplify subagent — no hardcoded bank_id, no Stop hook

The subagent no longer hardcodes bank_id or has its own Stop hook.
Instead:
- inject_bank_id.py PreToolUse hook derives bank_id at runtime from
  the plugin config (supports dynamicBankId, per-repo via cwd, etc.)
- The main plugin's Stop hook retains the full conversation (including
  user input) to the derived bank

This means:
- Multiple subagents share the same bank (derived from plugin config)
- Per-repo isolation works via dynamicBankGranularity: ["agent", "project"]
- User input from the main thread is retained (not lost in subagent context)
- Subagent template is simpler — just tool instructions, no bank plumbing

* fix(self-driving-agents): don't overwrite plugin config on subsequent installs

If ~/.hindsight/claude-code.json already has a Hindsight connection
configured, use it as-is. Only prompt for Cloud/Self-hosted setup on
first install. This prevents installing a second agent from clobbering
the shared config (agentName, bankId, etc.) that the plugin uses at
runtime.

* feat(self-driving-agents): auto-approve hindsight MCP tools in user settings

* fix(self-driving-agents): use plugin bank derivation for content ingestion

* fix(self-driving-agents): resolve bank with project dimension from cwd

resolveFromClaudeCode now includes all dimensions (agent, project,
session, channel, user) matching the plugin's bank.py logic. The
project dimension uses basename(process.cwd()), so running the
installer from a repo directory ingests content into the correct
per-project bank that the plugin will use at runtime.

* fix(self-driving-agents): use plugin's agentName for bank derivation, not CLI agentId

* fix(self-driving-agents): fail if subagent already exists in claude-code

* feat(claude-code): add /create-agent skill for in-session agent creation

* refactor(claude-code): remove agent-knowledge skill — subagent body is self-contained

* refactor(self-driving-agents): simplify claude-code harness — just save content + print prompt

The CLI no longer writes subagent files, resolves banks, or patches
permissions for --harness claude-code. Instead it:
1. Fetches content from GitHub
2. Saves it to ~/.self-driving-agents/claude-code/<agent-id>/
3. Prints the exact prompt to give Claude Code

Claude handles everything via /hindsight-memory:create-agent skill:
- Creates the subagent
- Ingests the seed docs
- Creates initial knowledge pages based on the content

This eliminates all bank derivation issues (bank resolved at runtime
by the plugin) and keeps one code path for agent creation (the skill).

* feat(claude-code): auto-approve bash for .self-driving-agents dir in create-agent skill

* docs(claude-code): clarify ingest steps in create-agent skill

* feat(claude-code): add ingest_file tool + auto-approve MCP tools in skill

- Add agent_knowledge_ingest_file(file_path) — reads file server-side,
  no need to pass content inline. Avoids permission prompts for large
  content and keeps tool calls clean.
- Add mcp__hindsight__* to create-agent skill's allowed-tools
- Update skill instructions to prefer ingest_file for disk files

* feat(self-driving-agents): auto-approve MCP tools, skill, and bash for claude-code

* refactor(claude-code): remove bank_id from MCP tool params

bank_id is no longer exposed as a parameter on any MCP tool. The
server resolves it once at startup from plugin config (derive_bank_id).
This prevents Claude from trying to override it or getting confused
about which bank to use.

Removed inject_bank_id.py PreToolUse hook — no longer needed since
bank resolution is server-side only.

* feat(self-driving-agents): copy bank-template.json and instruct Claude to create mental models from it

* feat(claude-code): add get_current_bank tool so Claude can tell user which bank is active

* chore: regenerate docs skill

* chore: trigger CI
2026-05-05 14:53:17 +02:00
Ling Li b322b0c5eb fix(search): correct vchord BM25 score direction (#1453)
The `<&>` operator returns a distance metric where lower values mean
higher relevance, but the code was using DESC ordering, causing the
least relevant results to appear first. Negate the distance to get a
proper score (higher = more relevant), matching pg_textsearch behavior.
2026-05-05 14:27:54 +02:00
Nicolò Boschi e06bbf6ba7 chore: LLM minimum acceptance tests with CI-managed model matrix (#1445)
* chore: add LLM minimum acceptance test workflow with CI-managed model matrix

Move LLM provider/model selection from Python-level pytest.mark.parametrize
to a GitHub Actions matrix. Each provider/model combo runs as a separate CI
job for clear per-model failure visibility.

- Rewrite test_llm_provider.py to read LLM_TEST_PROVIDER/LLM_TEST_MODEL
  from env vars instead of hardcoded MODEL_MATRIX
- Mark with pytest.mark.llm, excluded from test-api via -m "not llm"
- Add test-llm-acceptance.yml workflow (daily cron, manual, or 'llm-tests' label)
  with matrix of 14 provider/model combinations

* chore: LLM minimum acceptance tests as CI matrix job in test.yml

Replace the Python-level MODEL_MATRIX in test_llm_provider.py with a
CI-managed matrix job (test-api-llm-acceptance) in test.yml.

- Add hs_llm_mat pytest marker for tests that should run across LLM providers
- Tag 6 tests across 5 files covering all core operations:
  - test_llm_provider.py: API methods + memory operations (fact extraction, reflect)
  - test_retain.py: test_retain_with_chunks (multi-paragraph retain)
  - test_fact_extraction_quality.py: test_comprehensive_multi_dimension
  - test_reflections.py: test_reflect_searches_mental_models_when_available
  - test_consolidation.py: test_consolidation_merges_only_redundant_facts
- test-api excludes hs_llm_mat tests via -m "not hs_llm_mat"
- New test-api-llm-acceptance job runs only -m "hs_llm_mat" with matrix:
  vertexai (gemini-2.5-flash, gemini-2.5-flash-lite), openai (gpt-4.1-mini),
  anthropic (claude-sonnet-4, claude-haiku-4), deepseek (deepseek-chat)

* fix: update LLM acceptance matrix to available CI providers

Matrix: vertexai/gemini-2.5-flash-lite, gemini/gemini-2.5-flash-lite,
openai/gpt-4.1-nano, groq/openai-gpt-oss-20b, bedrock/nova-2-lite.
Set HINDSIGHT_API_LLM_API_KEY from matrix-provided secret name.
2026-05-05 14:19:54 +02:00
Nicolò Boschi ffd6418efc release(dify): v0.1.1 2026-05-05 12:49:02 +02:00
Nicolò Boschi 19ca59f710 chore: add dify to changelog generator and create changelog page 2026-05-05 12:48:12 +02:00
Nicolò Boschi 197fd1c290 fix(dify): rename package to hindsight-dify (#1451)
* fix(dify): rename package from hindsight-dify-plugin to hindsight-dify

Align with the naming convention used by other integrations
(hindsight-crewai, hindsight-litellm, etc.).

* style(dify): apply ruff formatting
2026-05-05 12:47:09 +02:00
Nicolò Boschi 6c55dbde64 feat(claude-code): add knowledge tools via Python MCP server + claude/claude-code harnesses (#1428)
Plugin changes (hindsight-integrations/claude-code/):
- Add scripts/mcp_server.py — Python FastMCP stdio server exposing 7
  agent_knowledge_* tools (list/get/create/update/delete pages, recall,
  ingest). Each tool accepts optional bank_id parameter.
- Add scripts/inject_bank_id.py — PreToolUse hook that intercepts
  mcp__hindsight__agent_knowledge_* calls and injects bank_id from
  session context (cwd, agentName) via updatedInput.
- Add .mcp.json — plugin MCP server config (stdio transport)
- Add skills/agent-knowledge/SKILL.md
- Add enableKnowledgeTools config flag (MCP server exits if disabled)
- Make client.request() public (was _request)
- Bump plugin to v0.5.0

CLI changes (hindsight-tools/self-driving-agents/):
- Re-add --harness claude (Chat/Cowork skill zip generation, lost in
  hermes PR merge)
- Add --harness claude-code (marketplace install, config, knowledge tools)
- Add tests for both harnesses
2026-05-05 10:50:03 +02:00
BenandNicolò Boschi bc23750b29 feat(dify): add Dify integration with Hindsight memory tools (#1434)
* feat(dify): add Dify integration with Hindsight memory tools

Adds a Dify Tool Plugin under hindsight-integrations/dify/ exposing three
tools — Retain, Recall, Reflect — that can drop into any Dify workflow,
chatflow, or agent app alongside other LLM and tool nodes.

- Provider with API URL + optional API key credentials, validated via
  Hindsight /health
- 15 unit tests (pytest + pytest-mock)
- test-dify-integration CI job, dify added to release-integration.sh
- Docs page at /sdks/integrations/dify, integrations.json listing,
  placeholder icon
- Live-tested end-to-end against local Hindsight: Retain → fact extraction
  → Recall → Reflect synthesis all pass via Dify workflow

Distributed via GitHub for now; Dify Marketplace submission to follow.

* chore(dify): use real Dify logo for integrations listing

Replaces the placeholder blue-D SVG with the actual Dify icon on the
integrations listing page.

* docs(dify): add author + contact info to plugin README

Required by the Dify Marketplace submission checklist.

* fix(dify): address review feedback — add tool tests, error handling, cleanup

- Add 14 tests for RetainTool, RecallTool, ReflectTool _invoke() methods
- Add try/except around client calls with user-friendly error messages
- Simplify urljoin to f-string in provider health check
- Remove deprecated Pydantic v1 dict() fallback in _memory_to_dict
- Remove emoji from build_package.sh output
- Add comment explaining reflect's lower default budget

---------

Co-authored-by: Nicolò Boschi <[email protected]>
2026-05-05 10:41:20 +02:00
youchi1 8507095ab8 fix(recall): inherit observation entities through source_memory_ids (#1397)
* fix(recall): inherit observation entities through source_memory_ids

`include_entities=True` returns `entities: null` for every observation in
the recall response, even when those observations are linked through
`source_memory_ids` to facts whose entities are populated. The
per-memory endpoint (`get_memory_unit`) already handles this case: if an
observation has no rows in `unit_entities`, it inherits the union of
entities from its source memories. The recall path queried
`unit_entities` directly and stopped there, so observation results lost
both their per-result `entities` field and their contribution to the
top-level aggregate map.

The asymmetry made observation-only recall hostile to clients that
needed entity context (URL recovery, entity-aware ranking). The
documented workaround was to add `world` and `experience` to the
`types` filter and rely on those facts to carry the entity payload.

Mirror `get_memory_unit`'s fallback inside the recall entity-fetching
block: for observation result IDs that produced no direct
`unit_entities` rows, look up their `source_memory_ids`, fetch entities
for the union of source IDs in a single batched query, and project the
results back onto the original observation IDs (deduped by entity_id,
preserving source-memory order). The downstream code that derives
per-result `entities` and the top-level aggregate map both consume
`fact_entity_map`, so the inheritance flows through both paths
automatically.

Add a regression test that seeds an observation linked via
`source_memory_ids` to a fact carrying two entities, plus a second
observation with its own direct `unit_entities` link, then asserts
recall projects both per-result entity lists and the top-level map.

* refactor(recall): consolidate observation entity inheritance in one SQL helper

The first commit on this branch fixed the recall projection by mirroring
get_memory_unit's procedural fallback in Python: query unit_entities,
detect observations that came back empty, separately fetch
source_memory_ids, separately fetch entities for the union of source
IDs, then dedupe and merge in Python. That worked but had two issues
worth fixing before the PR lands.

First, the inheritance edge ("observation linked through its source
memories") is dialect-shaped: PG stores it on `memory_units.source_memory_ids`,
Oracle keeps it in the `observation_sources` junction table. The
procedural patch reached for `source_memory_ids` directly, which made
recall observation-entity inheritance silently PG-only.

Second, the same fallback already existed inline in get_memory_unit, so
shipping a second copy in recall left two places that had to stay in
sync forever, by hand.

Introduce `_entity_rows_for_units_sql`, a private engine helper that
returns a single dialect-correct UNION SELECT producing
`(unit_id, entity_id, canonical_name)` rows. Direct rows come from
`unit_entities`; observations that have no direct row inherit through
`source_memory_ids` (PG) or `observation_sources` (Oracle), guarded by
NOT EXISTS so the inheritance only fires when the direct path is empty.
This is the same conceptual shape as `_observations_via_source_match_sql`
on the document view fix branch — both are SQL primitives over the
observation-source edge.

Use the helper in two places that previously hand-rolled the same
inheritance logic:

- The recall entity-fetch block collapses from three queries plus a
  Python dedupe loop to one fetch into the same `fact_entity_map`.
- get_memory_unit's two-query "fetch direct, fall back to sources"
  pattern collapses to one fetch, with identical observable behavior.

Add a get_memory_unit assertion to the existing regression test so the
shared helper is exercised through both call sites and any future drift
between recall and the per-memory endpoint trips a test, not a
production report.
2026-05-05 10:40:14 +02:00
DK09876andClaude Opus 4.6 f3b3fa2edb fix: repair 4 broken tests on main (#1437)
* fix: repair 4 broken tests on main

1. Merge divergent alembic heads (9f8e7d6c5b4a + b5d4e3f2a1c9) that
   were created when deferrable FK and cooccurrence backfill migrations
   both targeted the same parent without a merge revision.

2. Fix openrouter null-content mock tests — MagicMock auto-generates
   truthy values for .error and .model_dump().get(), triggering the
   ProviderResponseError path before reaching null-content handling.
   Explicitly set response.error=None and response.model_dump to return
   a clean dict. Also update the expected exception from JSONDecodeError
   to ProviderResponseError to match current behavior.

3. Fix worker test isolation — clean_operations fixture only cleaned
   test-worker-* prefixed operations, but WorkerPoller.claim_batch scans
   all pending operations in the schema. Stale consolidation tasks from
   other xdist workers caused spurious assertion failures.

4. Add retry to custom embedding dimension schema teardown — pg0
   embedded postgres can race with concurrent xdist workers during
   DROP SCHEMA CASCADE, causing 'could not open relation with OID'.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Fix merge migration run_for_dialect and embedding dimension OID race

- Add run_for_dialect pattern to merge migration (required by test_migration_shape)
- Add retry wrapper for ensure_embedding_dimension to handle pg0 OID race
  condition when concurrent xdist workers do DROP SCHEMA CASCADE

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-05-05 10:34:59 +02:00
Nicolò Boschi d9da3f262d ci: stop re-running test workflow on pull_request_review (#1446)
The CI workflow used pull_request_review to re-run secret-requiring jobs
after a maintainer approved a fork PR. But pull_request_review fires on
every review, so approving an internal PR triggered a duplicate CI run on
the same SHA.

Drop the pull_request_review trigger and all the conditional gating it
required. CI now runs once per push on pull_request. Fork PRs run only
the jobs that don't need secrets (gated by has_secrets); to run the full
suite on a fork branch, push it to an internal branch or use
workflow_dispatch.
2026-05-05 10:21:59 +02:00
Nicolò Boschi fd91e3d34e release(n8n): v0.1.1 2026-05-05 10:18:46 +02:00
Nicolò Boschi 62b141318f chore: add n8n to changelog generator and create changelog page 2026-05-05 10:18:24 +02:00
Nicolò Boschi ad4c0e7755 fix(n8n): add missing index.ts, fix auth header, add execution tests (#1444)
- Add index.ts entry point (package.json "main" points to dist/index.js)
- Fix credential auth header: use empty string instead of undefined to
  avoid sending literal "undefined" header for unauthenticated instances
- Use SVG icon instead of PNG for crisper rendering
- Remove unsafe `as IDataObject` casts on client call options, use
  proper Budget type import
- Add node-execute.test.ts with mocked HindsightClient verifying all
  three operations (retain, recall, reflect) are called correctly
2026-05-05 10:16:56 +02:00
Ben c1eaf7110d feat(n8n): add n8n community-node package for Hindsight memory (#1364)
* feat(n8n): add n8n community-node package for Hindsight memory

Adds @vectorize-io/n8n-nodes-hindsight — an n8n community node package
that exposes Hindsight retain / recall / reflect as workflow operations.
Drop the Hindsight node into any workflow alongside Slack, Sheets,
OpenAI, etc. and you have persistent memory across runs.

Package layout (n8n community-node convention):
- credentials/HindsightApi.credentials.ts: credential class
  (apiUrl + optional apiKey, /health test, Bearer auth)
- nodes/Hindsight/Hindsight.node.ts: single node with operation parameter
  exposing retain / recall / reflect (matches Slack-style multi-op nodes)
- nodes/Hindsight/hindsight.svg: node icon
- 14 unit tests (vitest) covering credential metadata, node properties,
  per-operation field gating, budget enums

Wiring:
- detect-changes filter + test-n8n-integration job in test.yml
  (cloned from test-opencode-integration shape)
- Added n8n to VALID_INTEGRATIONS in scripts/release-integration.sh
- New /sdks/integrations/n8n docs page
- Entry in integrations.json so n8n appears on the listing
- n8n.svg icon (placeholder; replace with brand-approved version)

Verified: tsc + vitest both clean (npm run build, npm test).

* feat(n8n): use Hindsight iris logo as node icon

Replaces the placeholder mark with the actual brand logo (PNG).
Updates copy-icons to ship any hindsight.* file with the build, and
ignores npm-pack tarballs.
2026-05-05 10:01:43 +02:00
Ben 7b671f0c1c docs(guides): add framework memory guides batch (#1432) 2026-05-04 14:37:31 -04:00
Ben 0b0f417df8 blog: Your Agent Harness Has Tools. It Still Needs Memory. (#1429)
* blog: Your Agent Harness Has Tools. It Still Needs Memory.
2026-05-04 14:05:15 -04:00
aliu-ronin fc624cbf40 fix(entity-resolver): stamp cooccurrences with event_date, not now() (#1247)
* fix(entity-resolver): stamp cooccurrences with event_date, not now()

`entity_cooccurrences.last_cooccurred` was always set to `datetime.now(UTC)`
at flush time. For real-time retains that's fine — event time ≈ ingest
time — but any corpus **backfilled in a single session** (for example,
migrating from another memory system) collapses every co-occurrence
onto the import moment. The dashboard's entity graph recency heat then
shows a one-or-two-day range regardless of how far the underlying
knowledge actually spans, and downstream consumers of the column lose
the timeline dimension entirely.

The tuples flowing into `_link_units_to_entities_batch_impl` already
carried the per-unit `fact_date` alongside `(unit_id, entity_id)` — it
was just being discarded at the call site (`_fact_date` underscore).
This change wires the event date through:

- `_CooccurrencePair` grows an `event_date` field.
- `link_units_to_entities_batch` accepts both the legacy
  `(unit_id, entity_id)` tuples and the new
  `(unit_id, entity_id, event_date)` form, so external callers aren't
  forced to migrate in lockstep.
- `_link_units_to_entities_batch_impl` builds a per-unit event-date map
  and attaches the unit's date to every co-occurrence pair emitted from
  that unit.
- `flush_pending_stats` aggregates per-pair event dates and INSERTs the
  observed maximum, falling back to `now()` only when no event date was
  carried (preserves the pre-fix semantics for real-time retains).
- Both in-repo callers (`retain/orchestrator.py` and
  `retain/link_utils.py`) pass the `fact_date` they were already
  holding.

A new Alembic migration repairs historical rows by recomputing
`last_cooccurred` from `MAX(COALESCE(mentioned_at, occurred_start,
created_at))` over `unit_entities × memory_units`, so operators don't
have to run a manual backfill to see the fix in their dashboards.
Regression coverage added in `test_entity_resolver.py` asserts a
historical `event_date` survives the link → flush round-trip.

* chore(docs-skill): pick up HINDSIGHT_API_LLM_DEFAULT_HEADERS row from #1389

Incidental docs-skill regen — `generate-docs-skill.sh` produces a 1-line
diff because #1389 (`feat(anthropic): env-driven max_retries +
default_headers knobs`) added the env var to the source documentation
without re-running the skill exporter at merge time.

Has nothing to do with the entity-cooccurrence fix in the previous
commit, but `verify-generated-files` checks the whole tree, so the row
needs to be in this branch for CI to go green.
2026-05-04 18:05:08 +02:00
Nicolò Boschi 7e830f1f99 feat(self-driving-agents): add Hermes Agent harness support (#1431)
- Add --harness hermes to the CLI
- Creates a Hermes profile per agent for isolation
- Installs standalone Python tool plugin (hindsight-sda) that registers
  7 agent_knowledge_* tools via ctx.register_tool
- Plugin coexists with bundled hindsight memory provider: bundled handles
  auto-retain/recall, our plugin adds knowledge page management
- Both read from the same hindsight/config.json in the profile — single
  source of truth, static bank_id with empty bank_id_template
- Prompts for Hindsight credentials (pre-fills from hermes/openclaw config)
- Prompts for agent name (pre-fills from path)
- Adds plugin to plugins.enabled in profile config.yaml
- 43 tests (5 new for hermes)
2026-05-04 17:13:51 +02:00
Nicolò Boschi 73ea0aae75 feat(self-driving-agents): add Claude Chat/Cowork harness (#1427)
* feat(self-driving-agents): add Claude Chat/Cowork harness

Add --harness claude support to the self-driving-agents CLI. Generates
a self-contained skill zip that can be uploaded to Claude Chat or Cowork
via Customize → Skills → Upload.

The generated skill:
- Has the agent's Hindsight API URL, bank ID, and token baked in
- Uses curl to call the Hindsight REST API (no external deps)
- Instructs Claude to load knowledge pages at startup
- Includes commands for creating pages, searching memories, ingesting docs
- Tells Claude to self-retain user preferences/feedback (no hooks in Chat/Cowork)

Setup flow prompts for Cloud vs Self-hosted, warns about public
accessibility for self-hosted servers, and includes allowlist
instructions in the next steps.

* test(self-driving-agents): add unit tests for claude harness

Tests cover skill generation (frontmatter, API URL/bank/token baking,
zip structure), config validation (localhost rejection, cloud URL),
harness validation, and all API operations in the generated skill.
2026-05-04 16:24:24 +02:00
fa4bf70005 feat(anthropic): env-driven max_retries + default_headers knobs (#1389)
* feat(anthropic): env-driven max_retries + default_headers knobs

Add two opt-in env vars to AnthropicLLM.__init__:

- HINDSIGHT_API_LLM_MAX_RETRIES (int): when set, passes through to
  AsyncAnthropic to override the SDK's default retry count. Useful when
  the deployment has its own outer retry layer (Hindsight already does
  2s→300s exponential backoff in call()) and the SDK's auto-retry would
  stack unnecessarily, producing request bursts that compound 429s.

- HINDSIGHT_API_LLM_DEFAULT_HEADERS (JSON string): when set, parsed and
  passed as default_headers to AsyncAnthropic. Useful when routing
  through a proxy that needs custom headers (component attribution,
  client-fingerprint markers, etc).

Both no-op when unset; existing deployments unaffected.

Real-world driver: routing Hindsight through Switchboard (a custom
HTTP proxy that handles retries + needs X-Component-Id for attribution
+ X-SB-Impersonate-CC for fingerprint compat). Without these env knobs,
operators have to volume-mount a patched anthropic_llm.py into the
container, which is fragile across image upgrades.

* refactor(anthropic): route default_headers + max_retries through config.py per reviewer feedback

Addresses @nicoloboschi's review on PR #1389: "can we use the usual
path for using config.py? pls check other providers".

Changes:
- config.py: add ENV_LLM_DEFAULT_HEADERS + DEFAULT_LLM_DEFAULT_HEADERS
  constants and a static llm_default_headers field on HindsightConfig,
  parsed in from_env() the same way llm_extra_body / llm_gemini_safety_settings
  already are. Static (not in _CONFIGURABLE_FIELDS) — infrastructure-level.
- anthropic_llm.py: drop the inline os.environ.get() reads and the new
  import os. Accept default_headers as a typed __init__ kwarg (sourced from
  config). Hardcode max_retries=0 on the SDK client to mirror
  OpenAICompatibleLLM (line 179) — wrapper-level retry loop in `call()` already
  handles backoff, so SDK retries are double work. Drops our custom
  HINDSIGHT_API_LLM_MAX_RETRIES env knob entirely; the existing same-named
  variable still controls Hindsight's wrapper retry count via
  HindsightConfig.llm_max_retries.
- llm_wrapper.py: thread default_headers through create_llm_provider() and
  LLMProvider.__init__/from_env. Falls back to _get_raw_config().llm_default_headers
  when not explicitly passed (mirrors the gemini_safety_settings pattern).
- memory_engine.py: pass config.llm_default_headers to all four LLMConfig
  constructors (memory / retain / reflect / consolidation), parallel to how
  config.llm_extra_body is already passed.
- configuration.md: document HINDSIGHT_API_LLM_DEFAULT_HEADERS in the LLM
  variables table.

Behavior:
- Default behavior with HINDSIGHT_API_LLM_DEFAULT_HEADERS unset is unchanged
  (None → no headers added).
- SDK-level max_retries change: was Anthropic SDK default (2) when the env
  var was unset, now hardcoded 0. Users who relied on SDK retries will get
  the same retry semantics from the wrapper retry loop, which the rest of
  the providers already use.

Verified: ruff check + ruff format both clean on hindsight-api-slim.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: TuftyBruno <[email protected]>
Co-authored-by: cortex <[email protected]>
2026-05-04 15:46:08 +02:00
Nicolò Boschi 0f15f76a41 fix(hindsight-embed): use sysconfig to find scripts dir in daemon start (#1425)
* fix(hindsight-embed): use sysconfig to find scripts dir in _find_api_command (#1401)

`Path(__file__).parent.parent` resolves to site-packages/ in stock pip
venvs, missing the actual scripts dir (<venv>/bin or <venv>/Scripts).
Use `sysconfig.get_path("scripts")` which works across pip venvs, conda,
and --target installs.

* fix(typescript-client): add jest.spyOn/fn shim to deno_setup.ts

The TestAbortSignal tests use jest.spyOn which doesn't exist under Deno.
Add a mock implementation (matching the pattern in the AI SDK's
vitest-compat.ts) so these tests pass with deno test.

* fix(typescript-client): skip TestAbortSignal under Deno

Deno freezes ES module namespace objects, so jest.spyOn cannot patch
sdk exports. Skip these spy-based unit tests under Deno (they're
already covered by the Jest suite).

* fix(hindsight-embed): restore __file__-relative fallback for --target installs

sysconfig.get_path("scripts") correctly fixes stock venv installs
(#1401) but doesn't cover `pip install --target` layouts where the
binary sits alongside site-packages contents. Keep the original
Path(__file__)-based lookup as a second fallback before uvx (#1240).
2026-05-04 15:45:17 +02:00
aliu-ronin 3ec98a4c37 chore(generated): regenerate openapi spec + clients post #1246 (#1426)
#1246 added the `time_field` query parameter to
`/v1/{tenant}/banks/{bank_id}/stats/memories-timeseries` and the
corresponding `MemoriesTimeseriesResponse` field, but the generated
artefacts weren't refreshed at merge time. As a result `verify-generated-files`
fails on every PR opened against `main` until the spec + clients
catch up.

Regenerated by running:
  ./scripts/generate-openapi.sh
  ./scripts/generate-bank-template-schema.sh  (no diff)
  ./scripts/generate-clients.sh               (rust skipped — built at compile time)
  ./scripts/generate-docs-skill.sh            (no diff)
  ./scripts/hooks/lint.sh

The diff is purely the `time_field` query parameter and response field
propagated into the openapi spec and the python / typescript / go clients.
Rust client is auto-generated via `build.rs` (progenitor) so it doesn't
appear in the diff.
2026-05-04 15:44:58 +02:00
Nicolò Boschi b948b574de fix(mcp): expose tag_groups parameter on recall tool (#1396) (#1424)
The MCP recall tool's schema omitted tag_groups, so MCP clients passing
e.g. {"not": {"tags": ["closeout"]}} for negative filtering had it
silently dropped — recall executed without the filter. The REST API
already exposed it; this brings the MCP tool in line.

Validates incoming dicts via TypeAdapter(list[TagGroup]) and enforces
the same tags/tag_groups mutual-exclusivity check as RecallRequest.
2026-05-04 15:22:43 +02:00
Nicolò Boschi 35e06b6f85 fix(self-driving-agents): fail fast when nemoclaw sandbox is missing or destroyed (#1365) 2026-05-04 15:09:36 +02:00
Nicolò Boschi 08b56fdc33 fix(worker): handle NotImplementedError from add_signal_handler on Windows (#1423)
asyncio.AbstractEventLoop.add_signal_handler is Unix-only and raises
NotImplementedError on the Windows ProactorEventLoop. The worker would
crash silently ~30s into startup while the API process kept serving reads,
masking the failure (pending operations accumulate, consolidation never
runs).

Wrap the SIGINT/SIGTERM registration in a helper that swallows the
exception and reports back. On Windows we log a warning that the in-loop
two-stage shutdown is disabled; default Python SIGINT behavior still
terminates the process on Ctrl+C.

Fixes #1411
2026-05-04 13:15:10 +02:00
Nicolò Boschi 178a721ab2 fix(recall): preserve original exception in recall_async error path (#1421)
Closes #1384. The previous handler used `{e}` (which collapses to an empty
string for exceptions whose __str__ is blank) and re-raised as bare
`Exception(...)`, dropping the original class and traceback. Operations
rows ended up with an opaque `Failed to search memories: ` and worker
logs carried no traceback.

- Use `{e!r}` so exceptions with empty __str__ still produce a
  discriminating class+args string.
- `logger.error(..., exc_info=True)` so worker logs carry the full trace.
- `raise RuntimeError(...) from e` preserves the cause chain.
2026-05-04 12:38:41 +02:00
Nicolò Boschi 3d3aa76b1a fix(daemon): honor --host and HINDSIGHT_API_HOST in daemon mode (#1422)
* fix: clean up async batch retain test and add clarifying comments

Follow-up to #1382. Remove duplicate test fixtures that shadowed
conftest session-scoped embeddings/cross_encoder (causing zero-vector
embeddings in tests). Replace flaky asyncio.sleep(0.1) with a polling
loop. Add comments explaining the legacy checkpoint guard and the
jsonb_set checkpoint SQL.

* fix(daemon): honor --host and HINDSIGHT_API_HOST in daemon mode

Previously, --daemon unconditionally overwrote the host to 127.0.0.1,
ignoring both --host flag and HINDSIGHT_API_HOST env var. Now the
localhost default only applies when the user hasn't explicitly set a
host.

Closes #1402
2026-05-04 12:29:06 +02:00
Chris BartholomewandNicolò Boschi 06e45aba4e fix(retain): defer memory_links → memory_units FKs to break cascade deadlock (#1398)
* fix(retain): defer memory_links → memory_units FKs to break cascade deadlock

Concurrent INSERT into memory_links (from retain link generation —
temporal, semantic, entity, causal — via _bulk_insert_links) and any
DELETE that cascades through memory_units → memory_links (e.g.
delta-retain superseding chunks: chunks → memory_units → memory_links)
can deadlock under sustained single-tenant write load.

The cycle:

  Tx A: DELETE FROM chunks WHERE chunk_id = ANY(...)
        → CASCADE acquires row locks on memory_units, then on
          memory_links rows where to_unit_id matches the deleted units.

  Tx B: INSERT INTO memory_links (...) referencing one of the same
        memory_units rows.
        → The immediate FK check takes FOR KEY SHARE on those
          memory_units rows.

The two transactions take row locks on the same memory_units rows in
opposite orders depending on which side started first. PostgreSQL
detects the cycle and aborts one of them; the loser is killed mid-batch
and the worker has to retry. Under sustained write load the pattern
repeats.

The _bulk_insert_links sort by (from_unit_id, to_unit_id) prevents
INSERT-vs-INSERT contention but doesn't help INSERT-vs-cascading-DELETE.

Fix: make both memory_links → memory_units FKs DEFERRABLE INITIALLY
DEFERRED. INSERT no longer takes FOR KEY SHARE on the FK target row at
INSERT time — checked at COMMIT instead. Concurrent DELETE cascades
freely; if it has removed the target row by COMMIT, the INSERT
transaction fails with a clean FK violation (sqlstate 23503) instead of
both transactions getting tangled in a deadlock (sqlstate 40P01). The
WHERE EXISTS filter in _bulk_insert_links continues to handle the
typical "stale unit_id" case at INSERT time; the deferred FK is just
the backstop for the narrow race window between EXISTS and COMMIT.

ON DELETE CASCADE semantics are preserved — only the *timing* of the
constraint check moves. The entity_id FK is left immediate (entities
aren't part of the observed deadlock cycle).

PG-only: Oracle's deferrable-FK semantics differ and the deadlock cycle
was only observed on PostgreSQL.

Tests:
  * test_memory_links_deferred_fk verifies both FKs end up
    condeferrable=true, condeferred=true, confdeltype='c' (CASCADE)
    after the migration runs. Schema-shape invariant — locks in the fix
    so a future migration can't regress it accidentally.
  * test_migration_shape passes — the new migration uses the
    run_for_dialect dispatcher correctly.

A behaviour test (concurrent INSERT + cascading DELETE no longer
deadlocks) is hard to write deterministically because PG's deadlock
detector is racy; the schema-shape test is the durable guard.

* review: fix stale migration ID + simplify FK recreation

Address review feedback on the deferred-FK migration:

* tests/test_memory_links_deferred_fk.py: replace stale migration ID
  references (a2v3w4x5y6z7) with the actual ID (9f8e7d6c5b4a) in the
  module docstring and assertion failure message.
* 9f8e7d6c5b4a_memory_links_deferrable_fk.py: replace _FK_NAMES tuple +
  substring-based column derivation with an explicit _FK_COLUMNS dict.
  Drop the misleading DO $$ ... EXCEPTION WHEN duplicate_object blocks;
  DROP CONSTRAINT IF EXISTS already provides idempotence and the
  EXCEPTION clause was unreachable after a successful drop.

---------

Co-authored-by: Nicolò Boschi <[email protected]>
2026-05-04 12:25:11 +02:00
VosckoandTosko4 206e2cc092 fix(api): recognize Pydantic aliases in unknown param middleware (#1417)
Treat model field aliases as known JSON body fields so valid payloads like retain's async flag do not trigger X-Ignored-Params warnings.

Co-authored-by: Tosko4 <[email protected]>
2026-05-04 12:16:49 +02:00
Nicolò Boschi f327f9182e fix: clean up async batch retain test and add clarifying comments (#1419)
Follow-up to #1382. Remove duplicate test fixtures that shadowed
conftest session-scoped embeddings/cross_encoder (causing zero-vector
embeddings in tests). Replace flaky asyncio.sleep(0.1) with a polling
loop. Add comments explaining the legacy checkpoint guard and the
jsonb_set checkpoint SQL.
2026-05-04 11:59:31 +02:00
Nicolò Boschi 641b39120f fix(typescript-client): expose missing recall/reflect params (#1362)
* fix(typescript-client): expose missing recall/reflect params (tag_groups, responseSchema, factTypes, excludeMentalModels)

Add client-coverage-check tool that validates Python and TypeScript
wrapper clients expose all OpenAPI request body parameters, similar to
the existing cli-coverage-check for the Rust CLI.

The check caught 6 missing fields in the TypeScript wrapper:
- recall: tag_groups
- reflect: tag_groups, response_schema, fact_types, exclude_mental_models, exclude_mental_model_ids

Closes #1348

* refactor(typescript-client): make retain() delegate to retainBatch()

Mirrors the Python client pattern where retain() is a thin wrapper
around retain_batch(). Also exposes observationScopes and strategy
which were previously only available via retainBatch().
2026-05-04 11:54:41 +02:00
Nicolò Boschi c1f977da7e chore(clients): regenerate clients for time_field timeseries param (#1420)
#1246 added the `time_field` query parameter to
GET /banks/{bank_id}/stats/memories-timeseries (and the corresponding
field on `MemoriesTimeseriesResponse`) but didn't run
./scripts/generate-openapi.sh + ./scripts/generate-clients.sh, so the
spec and generated Go/Python/TypeScript clients drifted from the API.
This has been failing the verify-generated-files CI job ever since.

Regenerate the spec and all clients to bring them back in sync. No
behavior change — this is pure codegen output.
2026-05-04 11:51:26 +02:00
vernmic 0ce9f333dc fix(openclaw): add WeakSet registration guard keyed by API instance (#1409)
Adds a WeakSet<MoltbotPluginAPI> guard at the top of the plugin entry function.
If the same api object is passed again (registry churn), the entry function exits
immediately without re-registering hooks or event listeners.

WeakSet is keyed by object identity, not a module-level boolean. A new api object
(e.g. after a registry migration) will have a different reference and pass through
unconditionally -- this does not reintroduce the bug fixed by #1029 where a
module-level boolean blocked new registries from ever getting hooks.

Old api objects that are no longer referenced are garbage-collected by the WeakSet
(no memory leak).

Closes: #1404
Refs: #1029
2026-05-04 11:41:52 +02:00
voarsh2andReese eb76510ab3 codex: add configurable recall timeout (#1399)
Co-authored-by: Reese <[email protected]>
2026-05-04 11:40:57 +02:00
Nicolò Boschi 10210ba9f5 chore(embed): tidy detach-popen helper and close log fds in parent (#1418)
* chore(embed): tidy detach-popen helper and close log fds in parent

Follow-up to #1380. With the POSIX inherit-fd path gone, `log_handle` is
always supplied — drop the dead `None` branch in `_detach_popen_kwargs`,
type the parameter, and refresh the docstring. Wrap the daemon and UI
log opens in `with` blocks so the parent's copy of the fd is released
once Popen has dup'd it into the child. Add a regression test that
locks down POSIX stdout/stderr redirection so future refactors don't
silently re-introduce the TUI-corruption regression.

* chore: apply pending lint formatter and uv.lock sync

- Drop trailing commas in api.ts that the project formatter rewrites.
- Refresh uv.lock to resolve opentelemetry-* against the raised floors
  introduced in #1373 (`1.41.0` / `0.62b1`).

Both fall out of running `./scripts/hooks/lint.sh` on a clean checkout
and are unrelated to the embed-detach cleanup in this PR — bundling
them so the working tree stays clean after lint.
2026-05-04 11:40:31 +02:00
voarsh2andReese 00e45fe15b fix(retain): scope async recovery checkpoints by document (#1382)
Co-authored-by: Reese <[email protected]>
2026-05-04 11:37:12 +02:00
laoli-no1andLi Lao 4c28e66f5e fix: redirect daemon subprocess stdout/stderr on POSIX to prevent TUI corruption (#1380)
On POSIX, the daemon subprocess previously inherited the parent process's
stdout/stderr file descriptors. When running inside a TUI (e.g. Hermes
terminal UI) that uses stdio pipes for JSON-RPC communication, any output
from the daemon subprocess (uvx download progress, Python library init
messages, Rich UI frames) would leak into the parent's terminal, corrupting
the Ink UI rendering.

This change makes POSIX behavior consistent with Windows (which already
redirected to daemon_log) and the existing UI-spawn path, by always passing
a log_handle to _detach_popen_kwargs.

Fixes: daemon output leaking into TUI, causing input bar misalignment
and timer display corruption.

Co-authored-by: Li Lao <[email protected]>
2026-05-04 11:24:14 +02:00
Chris Bartholomew b9069c2841 fix(webhooks): route webhook endpoints through tenant-aware engine methods (#1388)
Webhook create/list/get/update/delete and list-deliveries endpoints in
the HTTP layer were calling pool.fetchrow/pool.fetch directly with
fq_table("webhooks"), bypassing the async-local schema context that
fq_table reads via get_current_schema(). Under deployments that set a
per-request target schema (multi-tenant routing), this caused webhooks
to be written to and read from the default schema while every other
operation on the same bank correctly resolved to the per-target
schema. Webhooks would land in the wrong schema; the fire path
(which uses the bank's resolved schema) would not see them and never
enqueued webhook_delivery operations -- silent failure, no errors.

Move the SQL into MemoryEngine methods that call _authenticate_tenant
first (matching the pattern used by retain/consolidate/mental-models),
so fq_table sees the same schema as the rest of the bank's data.

Add schema-isolation tests covering create/list/get/update/delete and
deliveries.
2026-05-04 11:20:50 +02:00
youchi1 7cc2daf42a fix(api): include observations in per-document graph and counts (#1374)
The control plane's document detail view ships an Observations tab and
a Memory Composition card alongside World and Experience. Both were
permanently empty for every document.

Root cause: get_graph_data and get_document filter memory_units by
document_id (and chunk_id) directly. Observations are consolidated
rows; their document_id and chunk_id columns are always NULL, with
the link back to a document living on source_memory_ids (PG) or in
the observation_sources junction (Oracle). The equality filter
therefore excluded every observation.

Fix:
- Add MemoryEngine._observations_via_source_match_sql, which returns a
  backend-correct predicate matching observations whose source memories
  satisfy a column equality, scoped to a bank.
- get_graph_data: extend the document_id and chunk_id filters with an
  OR branch using the helper, so observations linked through their
  sources are returned. Bank-scope the inner subquery.
- get_document: replace the broken observation_count column with a
  COUNT(*) subquery built on the same helper, so nodes_by_fact_type
  reflects observations for the document.
- Adjust the existing test_get_document_nodes_by_fact_type assertion:
  memory_unit_count covers facts with document_id (world + experience).
  Observations are reported separately in nodes_by_fact_type.
- New regression test seeds a document with one source fact, an
  observation linked via source_memory_ids, and an unrelated observation,
  then verifies the graph endpoint returns only the linked observation
  when filtering by document_id.
2026-05-04 11:18:33 +02:00
DK09876andClaude Opus 4.6 f1b25ae2b4 fix(oracle): update CHECK constraints in baseline to match current PG schema (#1379)
The Oracle baseline migration had stale CHECK constraint values:
- async_operations.status was missing 'cancelled' (added by i4j5k6l7m8n9)
- mental_models.subtype had old values ('structural','emergent','pinned','learned')
  instead of current ('directive','pinned') (changed by o0j1k2l3m4n5)

Both would cause runtime constraint violations on Oracle when cancelling
operations or creating directives.

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-05-04 11:15:59 +02:00
Nikolay Bratanov 9ef64bf762 fix(hindsight-api-slim): bump opentelemetry-{api,sdk,instrumentation,exporter} floors so PrometheusMetricReader 0.62b1 doesn't crash startup (#1373)
opentelemetry-exporter-prometheus 0.62b1 calls
MetricReader.__init__(otel_component_type=…), a kwarg that opentelemetry-sdk
introduced only in v1.41.0 (open-telemetry/opentelemetry-python#4970).

The previous `opentelemetry-{api,sdk}>=1.20.0` /
`opentelemetry-{instrumentation,exporter,semantic-conventions}>=0.41b0` /
`opentelemetry-exporter-otlp-proto-http>=1.20.0` floors let pip resolve a
recent exporter-prometheus against an older sdk (e.g. 1.39.x cached in a
lockfile), so on hindsight-api startup metric initialisation explodes with
"MetricReader.__init__() got an unexpected keyword argument
'otel_component_type'.  Metrics will be disabled (using no-op collector)."
Functionally hindsight stays up but /metrics is silently empty.

Bumping all six otel pins to the matching 1.41.0 / 0.62b1 floor keeps
pip's resolver consistent across the otel ecosystem and removes the
mismatch that produces the warning.

Closes #1372
2026-05-04 11:13:49 +02:00
voarsh2andReese bc14e5c439 Harden OpenAI-compatible JSON response handling (#1368)
Ensure json_object calls include a user-message json hint, and convert
malformed success responses into clear ProviderResponseError failures
instead of crashing on missing choices/content.

This avoids opaque retain extraction TypeErrors and prevents deterministic
provider error payloads from being retried as generic chunk failures.

Co-authored-by: Reese <[email protected]>
2026-05-04 11:08:33 +02:00
Evo 16766d7080 docs(self-driving-agents): document nemoclaw harness + --sandbox flag (#1367) 2026-05-04 11:07:09 +02:00
Byeonghoon YooandClaude Opus 4.7 78e48e5908 feat(opencode): share memory bank across git worktrees of the same repo (#1352)
* feat(opencode): share memory bank across git worktrees of the same repo

When `dynamicBankId` is enabled, the `project` field was derived from
`basename(directory)`. Linked worktrees (`git worktree add`) of the same
repository therefore ended up using different memory banks just because
their filesystem paths differ — even though they are the same project
and teams want their conventions/knowledge to apply across worktrees.

This change makes the `project` field git-aware:
- Inside a git repository, `git rev-parse --path-format=absolute
  --git-common-dir` is used to locate the main worktree's `.git`; its
  parent (the main worktree root) provides the project name.
  `git-common-dir` always points at the main worktree's `.git`, even
  when invoked from a linked worktree, so every worktree of the same
  repo now resolves to the same bank id.
- Bare repos (where common-dir is the bare repo itself, e.g.
  `myrepo.git`) use that path's basename.
- Outside of git, or when git is unavailable / fails, behavior falls
  back to the previous `basename(directory)` — preserving backward
  compatibility.

The `project` resolution is moved to lazy evaluation so `git` is not
spawned for granularities that don't include the `project` field.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* review: rename git-aware project to opt-in gitProject field

Per review on #1352: keep `project` semantics unchanged (directory
basename) for backwards compatibility, and expose the new git-aware
behavior as a separate `gitProject` value of `dynamicBankGranularity`.

Users that want worktrees of the same repo to share a single bank now
opt in by setting:

  "dynamicBankGranularity": ["agent", "gitProject"]

The previous default `["agent", "project"]` continues to mean exactly
what it did before — basename of the working directory — so existing
banks are not silently rebound.

- bank.ts: VALID_FIELDS gains "gitProject"; `project` resolver reverted
  to basename(directory); new `gitProject` resolver wraps the existing
  `getProjectRootFromGit` helper.
- bank.test.ts: split into two describe blocks — one asserting that
  `project` stays directory-only and never spawns git, one covering the
  new `gitProject` behavior across regular clone, linked worktree, bare
  repo, and git-unavailable fallback. Also added a combined-fields test.
- README.md: documents both fields and the recommended opt-in.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-04 11:05:35 +02:00
aliu-ronin cf1a97ab03 feat(stats): add time_field toggle to memories-timeseries chart (#1246)
* feat(stats): add time_field param to /stats/memories-timeseries

`/stats/memories-timeseries` always bucketed by `created_at` (ingest
time). For a bank built up in real time, ingest time ≈ event time and
that's the right default. But when a corpus is backfilled in a single
session — for example migrating from another memory system — every
record's `created_at` collapses to the import moment, so the chart
shows "all knowledge is new" and hides the underlying timeline.

Adds a `time_field` query parameter that lets the caller choose which
timestamp column drives the bucket assignment:

- `created_at` (default, unchanged) — ingest time
- `mentioned_at` — event time (when the fact was mentioned)
- `occurred_start` — event time (when the underlying event started)

For the event-time columns we `COALESCE(<col>, created_at)` per row so
records lacking an event timestamp still show up somewhere instead of
silently disappearing. The field is whitelisted (never interpolated
from untrusted input), unknown values fall back to `created_at`, and
the chosen column is echoed in the response for UI affordance.

Depends on the tz-aware bucket fix in #1245 (kept as a separate commit).

* feat(control-plane): add Ingested / Mentioned / Occurred toggle

Surfaces the new `time_field` backend option as a three-way toggle next
to the period selector on the "Memories ingested" card:

- **Ingested** — bucketed by `created_at` (default, matches old behavior)
- **Mentioned** — bucketed by `mentioned_at` (event time)
- **Occurred** — bucketed by `occurred_start` (event time)

The card title also updates to reflect which dimension is in view so
the chart reads unambiguously.

Propagates `time_field` through the control-plane proxy
(`/api/stats/[agentId]/memories-timeseries`) and the typed SDK
(`client.getMemoriesTimeseries`). Defaults stay `created_at` everywhere
so behavior is backward-compatible.
2026-05-04 11:03:49 +02:00
harryplusplus 8367930c4d feat(typescript-client): add AbortSignal support to all HindsightClient methods (#1198)
* feat(typescript-client): add AbortSignal support to all HindsightClient methods (#1198)

* Add signal?: AbortSignal to every public method's options bag so callers
  can cancel in-flight requests without dropping down to the raw SDK.

* Methods with optional options (retain, recall, reflect, listMemories,
  createDirective, listDirectives, createMentalModel, listMentalModels,
  listDocuments): signal is an optional field inside the existing options.

* Methods with required options (createBank, updateBankConfig,
  updateDirective, updateMentalModel, updateDocument): signal added as
  an optional field alongside the required fields.

* Methods that previously took no options (getBankProfile, getBankConfig,
  resetBankConfig, deleteBank, getDirective, deleteDirective, getMentalModel,
  refreshMentalModel, deleteMentalModel, getMentalModelHistory, getDocument,
  deleteDocument): accept an optional options?: { signal?: AbortSignal }.

* Add TestAbortSignal suite with 3 unit tests that mock the generated SDK
  and verify signal is passed through on retain, recall, and getBankProfile.

* chore(skills): regenerate hindsight-docs skill files

* chore(self-driving-agents): apply prettier formatting
2026-05-04 11:01:23 +02:00
Nicolò Boschi 507ccaed4b fix(embed): drop gpt-4o-mini fallback when hindsight-api import fails (#1363)
* fix(embed): drop hardcoded gpt-4o-mini fallback when hindsight-api import fails

Closes #1360.

`hindsight-embed/pyproject.toml` only depends on httpx + rich, so
`from hindsight_api.config import PROVIDER_DEFAULT_MODELS` always
fails in standalone venvs (uvx, OpenClaw bundles). The `except
ImportError` branch returned `gpt-4o-mini` for every provider, which
flowed into 4 sites and silently broke retain for every non-OpenAI
provider — `success: true` but zero memories stored because the
provider rejected the OpenAI-shaped model id.

The CLI doesn't need its own copy of the table. The daemon process
runs hindsight-api and already resolves the provider-keyed default
itself (config.py:1349). Leave HINDSIGHT_API_LLM_MODEL unset in the
CLI when the user didn't specify one and let the daemon resolve it:

- get_config() returns llm_model=None when env unset; daemon
  forwards env vars only when truthy (daemon_embed_manager.py:333).
- _do_configure_from_env omits the HINDSIGHT_API_LLM_MODEL line in
  the profile .env when the user didn't pass one (otherwise it gets
  re-injected on every daemon start and suppresses the default).
- _do_configure_interactive drops the model default in the prompt
  and labels it "(leave empty for provider default)".
- PROVIDER_DEFAULTS renamed to PROVIDER_API_KEYS (the model field
  is gone; only the API-key env var is still needed).

Adds two regression tests covering get_config() and the env-driven
configure path.

* fix(embed): don't reject providers outside the interactive menu

The 5-entry PROVIDER_API_KEYS dict only describes the interactive
menu (openai, groq, gemini, ollama, vertexai). hindsight-api supports
~18 providers via PROVIDER_DEFAULT_MODELS — anthropic, claude-code,
bedrock, openrouter, openai-codex, and more. Gating CI configuration
on the menu set blocked valid setups: a user setting
HINDSIGHT_API_LLM_PROVIDER=anthropic with a key would hit "Unknown
provider".

Drop the rejection. The daemon already validates providers via its
own dispatch table and will surface a clear error if the provider is
truly unsupported. Validation in the CLI's UX-only menu list was
duplicate work and a permanent drift hazard.
2026-05-04 10:53:22 +02:00
Ben 4986e8ec37 Add AWS AgentCore integration blog post (#1377)
* Add AWS AgentCore integration blog post
2026-05-01 15:06:42 -04:00
Ben 84c33b104d Blog: Agent Memory in SmolAgents with Hindsight Tools (#1329)
Add blog post explaining the SmolAgents integration with Hindsight memory tools.
Covers retain, recall, and reflect tools for agent memory, real-world examples
(code review agent, data analysis, research assistant), setup guide, code examples,
and best practices. ~1,800 words on persistent memory for SmolAgents.
2026-04-30 10:43:25 -04:00
Ben a908ade6d6 docs: add Pydantic Logfire guide for Hindsight tracing (#1339)
* docs: add Pydantic Logfire as an OTel backend for Hindsight

Hindsight already emits OpenTelemetry spans for retain / recall / reflect
(plus their LLM sub-spans) via the existing OTLP HTTP exporter. Logfire
is an OTel-native receiver, so wiring it up is three env vars — no code
changes, no new dependency.

- New /developer/logfire guide page: env-var config, what the trace tree
  looks like, pairing with logfire.instrument_pydantic_ai(), useful
  Logfire queries, and troubleshooting
- Cross-link from the existing Distributed Tracing section in monitoring.md
  so Logfire sits next to Langfuse / DataDog / Honeycomb in the supported
  backends list

* docs: drop dedicated Logfire page per review feedback

Per Nicolò's review on this PR — the dedicated /developer/logfire page
was mostly Logfire setup, not Hindsight. Keeping only the one-line
mention in the existing OTLP-backends list in monitoring.md, with the
link pointing to logfire.pydantic.dev directly.

The setup walkthrough, query examples, and troubleshooting moved into
the companion blog post (hindsight-marketing-content#113).
2026-04-30 16:24:15 +02:00
Nicolò Boschi 6c17531833 feat(self-driving-agents): add nemoclaw harness support (#1335)
* feat(self-driving-agents): add nemoclaw harness support

NemoClaw runs OpenClaw inside an OpenShell sandbox. The CLI:
- Checks nemoclaw is installed and sandbox exists
- Runs hindsight-nemoclaw setup for plugin + network policy config
- Installs skill into sandbox via `nemoclaw <sandbox> skill install`
- Uses the same bank resolution from openclaw plugin config
- Adds --sandbox flag (required for nemoclaw harness)

* fix(self-driving-agents): pass skill dir (not parent) to nemoclaw skill install

* test(self-driving-agents): add tests for nemoclaw support, version checks, arg parsing

* feat(self-driving-agents): auto-detect nemoclaw sandbox, prompt if multiple

* fix(self-driving-agents): always run nemoclaw setup + rebuild sandbox for network policy
2026-04-30 14:15:06 +02:00
voarsh2andReese b41e5e3675 fix(codex): filter synthetic AGENTS startup messages (#1346)
Co-authored-by: Reese <[email protected]>
2026-04-30 14:06:23 +02:00
Nicolò Boschi a81892096a fix(config): default openai-codex model to gpt-5.4 (#1357)
* fix(config): default openai-codex model to gpt-5.4

gpt-5.2-codex was deprecated by OpenAI and is rejected by the Codex API
on current ChatGPT Pro tiers. Switch the default to gpt-5.4, which is
in the active model list.

Closes #1344

* fix(config): use gpt-5.4-mini as openai-codex default
2026-04-30 14:04:44 +02:00
Nicolò Boschi d39a2ca618 feat(oracle): unify migrations under Alembic with dialect dispatcher (#1330)
* feat(oracle): unify migrations under Alembic with dialect dispatcher

Oracle DDL was a 636-line idempotent file (`migrations_oracle.py`) outside
Alembic, which meant no version tracking, no per-tenant version table, and
schema drift every time a PG migration was added without a corresponding
Oracle change. This unifies both backends behind a single Alembic tree.

- New `alembic/_dialect.py::run_for_dialect(pg=, oracle=)` helper. Each
  migration declares `_pg_upgrade` / `_oracle_upgrade` and dispatches based
  on the live connection's dialect.
- `alembic/env.py` is dialect-aware: PG keeps the existing search_path /
  read-write session setup; Oracle uses `ALTER SESSION SET CURRENT_SCHEMA`
  and `DDL_LOCK_TIMEOUT`.
- `alembic/script.py.mako` scaffolds the new pattern by default.
- All 59 existing PG migrations refactored mechanically — bodies moved into
  `_pg_upgrade` / `_pg_downgrade`, top-level dispatchers added.
- New `o1a2b3c4d5e6_oracle_baseline` migration brings a fresh Oracle 23ai
  database to the current schema in one step (PG = no-op). Drops the legacy
  partition-conversion / dedup / `observation_sources` backfill since those
  only existed for pre-baseline Oracle installs we explicitly are not
  supporting.
- `OracleBackend.run_migrations()` now goes through the unified Alembic
  pipeline; `migrations.py` skips the PG-specific advisory lock + pgvector
  setup when the URL is Oracle.
- `migrations_oracle.py` deleted; tests updated to use `run_migrations()`.
- New `tests/test_migration_shape.py` lint fails CI if any migration omits
  `run_for_dialect` — keeps drift from re-emerging.
- CLAUDE.md updated with the new template and dialect-asymmetry guidance.

* ci: run client integration tests against Oracle on oracle-tests label

Adds test-python-client-oracle and test-typescript-client-oracle. These
mirror the existing test-python-client / test-typescript-client jobs but
spin up Oracle 23ai as a service container and point the API server at it
via HINDSIGHT_API_DATABASE_BACKEND=oracle + DATABASE_URL.

Why a new job instead of matrixing the existing one: Oracle Free's image
takes ~2min to start and is network-heavy, so we don't want to pay that
cost on every PR — only when oracle-tests is opted in via the PR label,
matching the existing test-api-oracle gate.

Why client tests, not unit tests: the unit suite already runs against
both backends via the abstraction layer. Only the client tests exercise
full HTTP round-trips with real serialized payloads, so they catch API
changes that work on PG but break on Oracle (or vice versa) in ways the
abstraction can't see.

* refactor(oracle): tighten feature requirements and dedup is_oracle_url

- Move is_oracle_url to db_url.py and import from there in env.py and
  migrations.py — was duplicated in both.
- Type-annotate _configure_pg_session / _configure_oracle_session params
  (Engine, Connection); ty checks pass.
- Update the Oracle baseline comment around vector + text index creation
  to make the hard requirement explicit: VECTOR + CTXSYS must be
  available, the migration fails hard if either is missing. The
  swallow-only-ORA-00955 behavior was already correct; the previous
  comment misleadingly called it "best-effort".

* chore(openclaw): apply pending prettier reformat to keep verify-generated-files green

Three formatting-only changes prettier wants to make. They've been stale
on main; CI's verify-generated-files runs lint with LINT_ALL=1 (vs the
"only changed integrations" local default), which surfaces them on every
unrelated PR. Folding them in here so this PR can land.

* fix(retain): plumb ops through handle_document_tracking

Line 312 of fact_storage.py references ``ops`` without ``handle_document_tracking``
declaring it as a parameter — straight NameError on every retain that walks
the upsert path. Bug landed on main in d8ec2d7f (#1325) when
``delete_stale_observations_for_memories`` started taking a backend-aware
``ops`` to choose between the PG array operator and the Oracle junction
table; the call site was added but the parameter wasn't threaded into the
enclosing function.

Fix: add ``ops=None`` to ``handle_document_tracking`` and pass ``pool.ops``
from each of the three call sites in orchestrator.py.

This is unrelated to the Alembic dialect-dispatcher refactor in this PR but
is what's blocking it — the NameError caused 17 retain tests to fail (and
left a pytest-xdist worker in a state that hung the whole job at 99%).

* test(observation): pass ops to handle_document_tracking in upsert test

The test calls fact_storage.handle_document_tracking directly, which
delegates to delete_stale_observations_for_memories(ops=ops). With ops=None
the helper falls back to the Oracle junction-table query and fails on PG
with "relation public.observation_sources does not exist". Real callers
(orchestrator, _delete_stale_observations_for_memories wrapper) all pass
self._backend.ops; the test just needs to do the same.

* ci: run client-against-oracle on every API change, drop label gate

Reserve the "oracle-tests" label for the heavy test-api-oracle (full unit
suite). The two client integration jobs against Oracle should run on every
API/client change just like their PG counterparts — the whole point is to
catch PG/Oracle drift before merge, which doesn't work if you have to
remember to label every PR. test-api-oracle keeps its label gate because
the full suite is too slow to run on every push.

* fix(oracle): rewrite path-style service to ?service_name= for SQLAlchemy

Oracle Free / Autonomous DB only register a service name with the listener,
but SQLAlchemy's oracle+oracledb dialect interprets the URL path as a SID.
That mismatch crashes alembic migrations on first connect:
  DPY-6003: SID "FREEPDB1" is not registered with the listener

Rewrite ``oracle://user:pass@host:port/SERVICE`` to
``oracle+oracledb://user:pass@host:port/?service_name=SERVICE`` so the
dialect uses the correct connect descriptor. ``?sid=`` and ``?service_name=``
already in the URL are passed through untouched.

Also adds scripts/dev/start-oracle.sh / stop-oracle.sh that spin up the same
Oracle 23ai Free image CI uses (``container-registry.oracle.com/database/free``)
and bootstrap the HINDSIGHT_TEST user, so we can repro this kind of issue
locally without round-tripping through GitHub Actions.

* fix(oracle): commit after migrations so alembic_version persists

On Oracle, alembic runs each migration with transactional_ddl=False
("Will assume non-transactional DDL"). Each CREATE TABLE auto-commits, but
the trailing ``UPDATE alembic_version SET version_num = ...`` is plain DML
that needs an explicit COMMIT. Without it the connection close rolls the
update back, leaving the schema fully created but the version row one
revision behind — so ``run_migrations`` reports success while the head row
sits at the previous revision.

Caught locally with the new scripts/dev/start-oracle.sh harness running the
same Oracle 23ai Free image CI uses; alembic_version was stuck at
``k6l7m8n9o0p1`` even though every table from the ``o1a2b3c4d5e6`` baseline
existed. After the fix it correctly advances to ``o1a2b3c4d5e6``, and a
second run is a no-op as expected.

PG already needs the same commit (Supabase RW-mode SET), so just drop the
``if not is_oracle`` guard.

* ci(oracle): run python client tests sequentially to avoid ORA-00060

The python client pyproject.toml defaults to -n auto (pytest-xdist).
Against Oracle that hits row-level deadlocks during retain cleanup —
ORA-00060 is logged repeatedly in the API server output and most tests
fail with "Internal Server Error" at fixture teardown. Same shape as the
existing test-api-oracle issue, which is already pinned to -n0.

Override to -n0 in the Oracle client job (only). The PG client job stays
parallel since pgvector + advisory locks handle concurrent retain fine.
TS client tests are unaffected — they run via vitest, not pytest.
2026-04-30 13:58:03 +02:00
Nicolò Boschi ee97aea145 fix(llm): guard against null content from OpenAI-compatible providers (#1355)
* fix(llm): guard against null content from OpenAI-compatible providers

OpenRouter free-tier models occasionally return message.content=None
alongside a valid finish_reason. Without a guard, _strip_code_fences and
the reasoning-tag regexes crashed with TypeError, and the retry loop
couldn't recover because every attempt hit the same unhandled error.

Now treat null/empty content as a transient failure: log warning, retry
within budget, raise ValueError if exhausted.

Fixes #1334

* refactor: coerce null content to empty string

Simpler than the explicit guard — empty string flows into the existing
JSON parse error handler, which already logs, retries, and raises.
2026-04-30 13:56:18 +02:00
Nicolò Boschi 7140f991d9 docs: add Oracle Database as supported enterprise storage (#1356)
* docs: add Oracle Database as supported enterprise storage option

PostgreSQL remains the primary and recommended backend. Oracle is
mentioned as a drop-in alternative for enterprise environments with
full feature parity.

* docs: remove untested Oracle managed services list

* docs: specify Oracle AI Database 26ai as the supported version

* docs: use "Oracle AI Database" consistently, drop version suffix
2026-04-30 12:58:33 +02:00
Evo b712f4f935 docs(python-sdk): document retain_async kwarg per #1306 (#1347)
* docs(python-sdk): document retain_async kwarg per #1306

* docs(python-sdk-mirror): document retain_async kwarg per #1306
2026-04-30 12:50:17 +02:00
Chris Bartholomew f4ca303833 fix(async-ops): atomically commit batch_retain parent and child rows (#1343)
* fix(async-ops): atomically commit batch_retain parent and child rows

submit_async_batch_retain inserts a parent row (status='pending',
task_payload=NULL — it's a status aggregator, not directly executable)
and then loops to insert one child row per sub-batch. The parent INSERT
and child INSERTs were not transactionally coupled: the parent's
INSERT ran in its own auto-committing connection, and each child went
through a separate _submit_async_operation call that acquired its own
connection.

Any failure between them (connection drop, asyncpg timeout, schema-
cache invalidation under concurrent load, or any other exception
raised during child setup) leaves a parent row with zero children.
The worker poller skips it forever because of the
"task_payload IS NOT NULL" filter, the status aggregator never fires
because there are no children to complete, and the row sits pending
indefinitely. It also pollutes queue-depth metrics that operators rely
on to size worker pools.

Fix: wrap parent INSERT and all child INSERTs in a single
async transaction so the create-batch operation is atomic — either
all rows become visible to workers or none are. Child INSERT SQL is
inlined for the duration of the transaction; _submit_async_operation
is left untouched so other callers are unaffected. submit_task() is
deferred to after the transaction commits because SyncTaskBackend
(used in tests) executes synchronously and would otherwise read the
not-yet-committed row.

Tests:
- New regression test
  test_submit_async_batch_retain_rolls_back_parent_on_child_failure
  monkeypatches BatchRetainChildMetadata to raise on the second
  sub-batch and asserts zero async_operations rows remain after the
  failure (parent must roll back together with children).
- Mirrors the existing
  test_submit_async_operation_leaves_claimable_row_when_submit_task_fails
  but at the parent-level (the child-level case was already fixed).

* test(async-retain-tags): rewrite for inlined child INSERT

submit_async_batch_retain now inserts children inline inside the
parent's transaction (rather than calling _submit_async_operation per
child) and notifies the task backend after commit. The pre-existing
test mocked _submit_async_operation and asserted on its call args;
that path no longer runs for children.

Replace those assertions with the new equivalent: count the INSERTs on
the connection, inspect the post-commit submit_task payload for
document_tags, and cross-check the JSON serialized into the child's
task_payload column. Same intent (document_tags propagates through to
the worker), aligned with the new code path.

* fix(retain): thread ops through handle_document_tracking

handle_document_tracking calls delete_stale_observations_for_memories
with ops=ops, but ops is not a parameter of handle_document_tracking
itself (introduced in #1325 as part of the backend-aware observation
read split). Every retain that hits the document-tracking path raises
NameError before any actual work happens.

Add ops as a kwarg-only parameter on handle_document_tracking and
forward pool.ops from each of the three call sites in
_streaming_retain_batch. Behaviorally a no-op for the PG path
(uses_observation_sources_table is False, so the existing PG branch
runs) and for the Oracle path (junction table branch already runs
when ops.uses_observation_sources_table is True).

* test(observation-invalidation): pass ops to handle_document_tracking

The test calls handle_document_tracking directly (rather than going
through the retain orchestrator) and didn't pass ops. With the param
defaulting to None, the inner delete_stale_observations_for_memories
call falls through to the Oracle junction-table read path and queries
a non-existent public.observation_sources relation under PG.

The orchestrator's three call sites already pass pool.ops; this test
just needs to mirror that. Pass memory._backend.ops to keep the test
backend-agnostic.
2026-04-30 12:34:01 +02:00
youchi1 e5f5c7ef9d fix(embed): include 'all' extras when spawning hindsight-api from sibling source (#1341)
The dev-mode spawn (when hindsight-api-slim sits next to hindsight-embed)
runs 'uv run --project hindsight-api-slim hindsight-api' without --extra,
so only base deps install. On a fresh customer environment with no
pre-synced workspace .venv, the daemon then crashes on startup with
'pg0-embedded is required' (and would also miss sentence-transformers).

The 'all' extra in hindsight-api-slim/pyproject.toml is defined as
local-ml + embedded-db (deliberately excludes local-llm so we don't drag
in llama-cpp-python). Use it explicitly so a fresh spawn lands with the
right runtime extras.

Local dev hides this because the workspace .venv is typically pre-synced
with --all-extras (or the explicit subset).
2026-04-30 12:25:01 +02:00
youchi1 c4dc8c35dc fix(consolidator): dedupe + ON CONFLICT for observation_sources INSERT (#1340)
Both _execute_update_action and _execute_create_action insert into the
observation_sources junction table. Previously, both:
  - Built INSERT batches without deduping the source_ids list
  - Lacked ON CONFLICT handling

This caused UniqueViolationError on (observation_id, source_id) under
several scenarios:
  1. Same source_id repeated within source_ids (a single batch can have
     duplicates when several memories collapse to the same effective
     source).
  2. Concurrent consolidation of the same observation racing on the
     DELETE-then-INSERT pattern in _execute_update_action.
  3. Residual rows surviving the DELETE (rare but possible at transaction
     boundaries).

Fix:
  - dict.fromkeys() preserves insertion order while deduping the list.
  - ON CONFLICT (observation_id, source_id) DO NOTHING absorbs any
    surviving duplicates without aborting the entire batch.

Both layers are needed: dedupe avoids the round-trip on intra-batch
duplicates, ON CONFLICT handles cross-batch / concurrent races.
2026-04-30 12:24:04 +02:00
Nicolò Boschi c36ebe5cf0 feat(perf): add HTTP mode to recall benchmark (#1315)
Add --api-url flag to recall_perf.py benchmark subcommand, enabling
recall benchmarks against a remote Hindsight API (e.g., Docker container).
This allows comparing query behavior across different Hindsight versions
by pointing the benchmark at different API instances.

Usage:
  uv run python recall_perf.py benchmark \
    --bank-id my-bank --query "database migration" \
    --api-url http://localhost:8080
2026-04-30 12:22:11 +02:00
Evo 4282e8423a docs(models): document litellm-sdk embeddings provider (#1336)
* docs(models): document litellm-sdk embeddings provider

* docs(models): mirror litellm-sdk embeddings provider in sidecar
2026-04-30 12:21:53 +02:00
Nicolò Boschi 89c34c3135 release(self-driving-agents): v0.0.6 2026-04-29 17:25:09 +02:00
Nicolò Boschi 48b23fe9a8 fix(self-driving-agents): require plugin >= 0.7.2 2026-04-29 17:24:51 +02:00
Nicolò Boschi 682ac0d2c1 release(openclaw): v0.7.2 2026-04-29 17:24:26 +02:00
Nicolò Boschi b313869e75 fix(self-driving-agents): fix plugin upgrade flow, surface errors, show plugin version 2026-04-29 17:23:57 +02:00
Nicolò Boschi 8bc6cd4abf fix(openclaw): replace readFileSync with createRequire to avoid security scanner false positive 2026-04-29 17:23:27 +02:00
Nicolò Boschi bbb8e0375e perf: add recall-with-observations & consolidation suites, split CI steps, fix locomo (#1333)
* chore(docs): sync version-0.5 docs from next

* perf: add recall-with-observations suite, split CI steps, fix locomo timeout

- Add new recall-with-observations perf test suite that includes synthetic
  observations in the bank to test recall under realistic data mix
- Split CI perf-test job into separate per-suite steps for clearer reporting
- Fix locomo consolidation timeout by starting a WorkerPoller in the
  BenchmarkRunner when wait_consolidation is enabled — consolidation tasks
  were being queued but never processed

* perf: add consolidation suite with mock LLM

Add a new consolidation perf test suite that measures DB + embedding
overhead of the consolidation pipeline with mock LLM responses.
The mock callback parses fact IDs from the consolidation prompt and
returns create actions, exercising the full DB write + embedding path.

* fix(ci): replace removed gemini-3.1-pro-preview model in locomo

The model was returning 404 NOT_FOUND. Switch answer LLM to
gemini-2.5-flash which is available.
2026-04-29 17:21:26 +02:00
Nicolò Boschi ec9da6a5cd release(openclaw): v0.7.1 2026-04-29 16:56:50 +02:00
Nicolò Boschi 7f63ed0049 style(openclaw): prettier format 2026-04-29 16:56:25 +02:00
Nicolò Boschi 51e8c28aad fix(openclaw): add enableKnowledgeTools to plugin config schema 2026-04-29 16:55:58 +02:00
Nicolò Boschi 81f2f8a8d7 fix(openclaw): regenerate lockfile with npm-resolved agent-sdk 2026-04-29 16:52:21 +02:00
Nicolò Boschi c1924e9d21 fix: switch openclaw agent-sdk dep from file: to npm ^0.1.0, fix plugin upgrade
- openclaw now depends on @vectorize-io/hindsight-agent-sdk@^0.1.0 from npm
  (file: refs don't resolve when installed from npm registry)
- CLI removes old plugin extension dir before reinstalling (openclaw doesn't
  support in-place upgrade)
2026-04-29 16:49:41 +02:00
Nicolò Boschi c6b0cf3bb6 release(self-driving-agents): v0.0.5 2026-04-29 16:37:03 +02:00
Nicolò Boschi 181ba70dcf style: prettier format cli.ts 2026-04-29 16:36:50 +02:00
Nicolò Boschi 4642360d7d fix(self-driving-agents): check plugin version >= 0.7.0 before writing config
The enableKnowledgeTools config flag is only recognized by plugin v0.7.0+.
Older versions reject unknown properties, breaking all openclaw commands.

Now the CLI checks the installed plugin version and auto-upgrades if needed
before writing the flag.
2026-04-29 16:36:22 +02:00
Nicolò Boschi 317841d5af release(self-driving-agents): v0.0.4 2026-04-29 16:33:08 +02:00
Nicolò Boschi 622593c6c0 test(self-driving-agents): add tests for agent name derivation 2026-04-29 16:32:54 +02:00
Nicolò Boschi 75e9b91f35 fix(self-driving-agents): derive agent name from full subpath (marketing/seo → marketing-seo) 2026-04-29 16:31:18 +02:00
Nicolò Boschi 458530b42a release(self-driving-agents): v0.0.3 2026-04-29 16:21:34 +02:00
Nicolò Boschi d5d0570ac9 fix(self-driving-agents): support 2-segment paths like marketing/seo 2026-04-29 16:21:20 +02:00
Nicolò Boschi 1513c8af35 release(self-driving-agents): v0.0.2 2026-04-29 16:14:15 +02:00
Nicolò Boschi 704ceeb4ec fix(self-driving-agents): add picocolors as direct dependency 2026-04-29 16:14:07 +02:00
Nicolò Boschi d8ec2d7f4a perf(db): eliminate ResultRow wrapping and make observation reads backend-aware (#1325)
* perf(db): eliminate ResultRow wrapping overhead for PostgreSQL

Make ResultRow a Protocol instead of a concrete wrapper class. asyncpg.Record
already satisfies the dict-like access pattern (row["key"], .keys(), .get())
natively in C — wrapping it in a Python class added ~570K __getitem__ calls
per 20-recall benchmark, causing a measurable ~24% regression at 10K bank size.

Changes:
- ResultRow is now a Protocol (interface) in result.py
- DictResultRow is the concrete wrapper, used only by Oracle backend
- PostgresConnection.fetch/fetchrow return raw asyncpg.Record directly
- Oracle backend imports DictResultRow as ResultRow (no behavior change)
- Tests updated to use DictResultRow

Benchmark (medium, 10K items, concurrency=4, same pg0 data):
  v0.5.6 baseline:    0.648s mean
  With wrapping:       0.805s mean (+24%)
  Without wrapping:    0.680s mean (+5%, within noise)
  With junction table: 0.680s mean (observation_sources has zero impact)

* perf(db): eliminate ResultRow wrapping and make observation reads backend-aware

Two performance fixes for the Oracle abstraction layer:

1. Make ResultRow a Protocol instead of a concrete wrapper class. asyncpg.Record
   satisfies dict-like access natively in C — wrapping added ~570K __getitem__
   calls per benchmark, causing a ~24% regression at 10K bank size.

2. Make observation source reads backend-dependent: PG uses native array ops
   (source_memory_ids column with &&, unnest), Oracle uses the observation_sources
   junction table. PG also skips junction table writes in the consolidator.
   At 33K scale, junction table reads doubled retrieval_graph latency (0.093s→0.186s).

Changes:
- ResultRow is now a Protocol; DictResultRow is the concrete wrapper (Oracle only)
- PostgresConnection.fetch/fetchrow return raw asyncpg.Record directly
- DataAccessOps.uses_observation_sources_table property (PG=False, Oracle=True)
- Consolidator guards junction table writes behind uses_observation_sources_table
- memory_engine.py and fact_storage.py branch reads by backend type

Benchmark (large, 33K items, concurrency=4, same pg0 data):
  v0.5.6 baseline:       0.853s mean
  Junction table reads:   1.027s mean (+20%)
  Array ops + no wrap:    1.014s mean (+19%, graph=0.091s matches baseline)
2026-04-29 16:09:25 +02:00
Nicolò Boschi 5e428ebf52 ci: add release-tool.yml workflow, fix release-integration.yml for workspace deps
- New release-tool.yml: triggered on tools/** tags, builds workspace deps
  then publishes to npm
- Fix release-integration.yml: build workspace deps (hindsight-client,
  hindsight-all, hindsight-agent-sdk) before building TS integrations
2026-04-29 16:07:51 +02:00
Nicolò Boschi a17b380083 release(self-driving-agents): v0.0.1 2026-04-29 16:04:54 +02:00
Nicolò Boschi cbe7623d85 release(openclaw): v0.7.0 2026-04-29 16:04:44 +02:00
Nicolò Boschi 79ed8a2786 chore(docs): sync version-0.5 docs from next (#1328) 2026-04-29 15:58:34 +02:00
Nicolò Boschi 7f30dcc780 feat: self-driving agents (part1) (#1302)
* feat(claude-code): add wiki script + agent-knowledge skill

wiki.py: CLI for knowledge pages, recall, ingest, documents.
Uses the existing plugin lib/ for bank resolution and API calls.
No separate config — reads from the same settings.json as retain/recall hooks.

agent-knowledge skill: teaches the agent to use wiki.py commands.
Bank resolution is automatic (same as retain hooks).
Pages default to: delta mode, observation-only, exclude mental models.

* feat: hindsight-agent-sdk (Python + TypeScript) + Claude Code wiki integration

* refactor: move skill to SDK, remove harness-specific skill from claude-code

* feat: add trigger params to MCP create_mental_model + MCP-based skill

- MCP create_mental_model now accepts trigger_mode, trigger_exclude_mental_models,
  trigger_fact_types params (both multi-bank and single-bank modes)
- Skill uses mcp__hindsight__* tools directly — no CLI, no scripts
- Bank scoped via MCP URL: /mcp/banks/{bank_id}/

* feat(openclaw): register wiki tools via registerTool API

* feat: standalone hindsight-agent-setup (npx-able) for all harnesses

* fix(openclaw): static import for wiki-tools (ESM compat)

* rename: agent_knowledge_* tools + cleaner skill (no hindsight/wiki/mental_model confusion)

* fix(openclaw): set tools optional=false so they're not filtered by allowlist

* refactor: setup reads directory layout (bank-template.json + content/), agent name from dir

* rename: @vectorize-io/self-driving-agents, setup→install

* cleanup: remove setup backwards compat

* fix: list_pages uses detail=metadata to avoid blowing up context

* chore: publish-ready package.json, README, .gitignore for self-driving-agents

* rename: hindsight-agent-setup → self-driving-agents

* cleanup: remove MCP tool changes, Python/TS SDKs, Claude Code wiki — keep only openclaw tools + skill + CLI

* cleanup: remove Rust CLI + Python CLI (superseded by self-driving-agents TS CLI)

* cleanup: rename wiki→knowledge, add release-tool.sh, interactive cloud setup, remove SDKs

* refactor: CLI does zero API calls, plugin bootstraps template+content on first session

* feat: CLI checks plugin install+config, runs wizard if needed

* feat(self-driving-agents): TUI wizard, TS client, GitHub agent sources

- Replace raw HTTP with @vectorize-io/hindsight-client SDK
- Add @clack/prompts for polished terminal UI (spinners, confirms, notes)
- Support GitHub agent sources: bare name defaults to vectorize-io/self-driving-agents,
  org/repo/path fetches from any public repo, local paths still work
- Remove bootstrap code from openclaw plugin (CLI handles all API calls)
- Fix ANSI-polluted JSON parsing for openclaw agents list
- Run setup wizard inline when user declines current config

* feat(self-driving-agents): recursive content discovery, drop content/ convention

Content files (.md, .txt, etc.) are now found recursively from the
agent directory root. No special content/ subdirectory needed.

This enables nested agent repos where pointing at any level ingests
all files below it:
- install marketing → all 30 files + root bank-template.json
- install marketing/seo → only SEO files + seo/bank-template.json

* cleanup: remove unrelated files (screenshots, PDF, pretext-poc)

* refactor(self-driving-agents): bundle SKILL.md as file, read at runtime

Move the skill from a hardcoded string to a bundled file at skill/SKILL.md.
Each CLI version ships its own skill — re-running install upgrades it.

* cleanup: remove hindsight-agent-sdk/skill, now bundled in self-driving-agents

* feat: knowledge tools opt-in via enableKnowledgeTools config flag

Plugin: agent_knowledge_* tools only register when enableKnowledgeTools
is true in the plugin config (default: false).

CLI: automatically sets enableKnowledgeTools=true in openclaw.json
during install.

* feat: create hindsight-agent-sdk, move tools under hindsight-tools/

- New @vectorize-io/hindsight-agent-sdk package with harness-agnostic
  knowledge tools using @vectorize-io/hindsight-client (no raw HTTP)
- OpenClaw plugin now imports from the SDK instead of inline knowledge-tools.ts
- Move self-driving-agents and hindsight-agent-sdk under hindsight-tools/
- Update release-tool.sh for new paths

* test: add tests for hindsight-agent-sdk and self-driving-agents

Agent SDK (11 tests): tool creation, endpoint routing, request bodies,
auth headers, page defaults (delta mode, observation facts).

Self-driving-agents CLI (23 tests): recursive content discovery,
local/GitHub path detection, ANSI JSON parsing, bank ID resolution
from plugin config.

CI: add test-hindsight-agent-sdk and test-self-driving-agents jobs
with detect-changes filtering.

* refactor: move tests to tests/ dirs, add prettier for hindsight-tools

- Move tests from src/ to tests/ matching repo conventions
- Add hindsight-tools/ prettier block to lint.sh
- Format all files with prettier

* fix(ci): add hindsight-tools to npm workspaces, build agent-sdk before openclaw

- Add hindsight-tools/* to root workspaces so npm resolves the agent-sdk
- Build agent-sdk before openclaw in all 3 openclaw CI jobs
- Use root npm ci + workspace builds for tool CI jobs
- Regenerate lockfiles

* fix(ci): use file: dep for agent-sdk in openclaw, whitelist in lockfile checker

- openclaw depends on @vectorize-io/hindsight-agent-sdk via file: ref
  (matching how control-plane depends on hindsight-client)
- Lockfile checker whitelists hindsight-tools/* workspace deps
- Regenerate openclaw lockfile
2026-04-29 15:53:56 +02:00
Nicolò Boschi 9025115354 fix(deps): cap cryptography <47 — 47.0.0 SIGILLs on some ARM64 Linux VMs (#1324)
cryptography 47.0.0 emits CPU instructions that aren't exposed in the
ARM64 Linux VMs used by Docker Desktop and Podman (AppleHV) on Apple
Silicon. Importing `cryptography.hazmat.bindings._rust` crashes with
SIGILL (exit 132), so v0.5.6 containers fail to start on those hosts.
See pyca/cryptography#14733.

The Dockerfile copies only pyproject.toml (not uv.lock) and runs
`uv sync` without --locked, so each build re-resolves to the latest
matching version. Without an upper bound, that picked up 47.0.0 once
it shipped on 2026-04-24.

Closes #1322
2026-04-29 15:51:10 +02:00
Ben a23e3432ff chore: remove stray files accidentally landed on main (#1326)
Remove two files that were unintentionally included in #1300 (the Pipecat
blog post commit):

- hindsight-integrations/smolagents/examples/interactive_test.py (orphan
  local example, unreferenced anywhere)
- sdk-python (orphan submodule pointer with no .gitmodules entry)
2026-04-29 15:31:35 +02:00
Jervis b837e66ce6 fix(codex): fix encoding with PowerShell (#1185)
* install codex support for Windows

* remove Windows install script
2026-04-29 15:16:03 +02:00
harryplusplus daae8223c3 feat(python-client): expose retain_async in retain() and aretain() (#1306)
Both single-memory convenience wrappers now accept retain_async and
forward it to retain_batch() / aretain_batch() respectively.  Default
is False so existing call sites are unaffected.

The REST API's /v1/default/banks/{bank_id}/memories endpoint accepts
async: bool on every retain request, and both batch methods already
expose this via retain_async: bool = False.  Since the convenience
wrappers simply delegate to the batch methods, there is no technical
reason to omit the parameter — users who want async on a single memory
today must switch to the batch API, which is an unnecessary friction.

This brings the Python SDK in line with the TypeScript SDK where
retain() exposes async?: boolean.  PR #709 fixed aretain_batch() to
actually pass retain_async through to the request model (it was
silently dropped before), but the convenience wrappers were left
without the parameter.

Also adds unit tests verifying the kwarg is forwarded to prevent
silent regressions.
2026-04-29 15:14:45 +02:00
Evo 3455460e0b docs(mental-models): document tags?source=mental_models per #1296 (#1311)
The new mental-models List view in #1296 added a 'source' query parameter
to GET /banks/{bank_id}/tags so the control plane can fetch the mental-model
tag set instead of the memory tag set. The blog post and a guide describe
this, but the API reference (mental-models.mdx + sidecar reference) didn't
mention the parameter. SDK/integration developers who jump straight to the
API docs would not know they can list mental-model tags this way.

Source-of-truth: openapi.json -> GET /v1/default/banks/{bank_id}/tags param
'source' (enum: memories | mental_models, default: memories).

Adds a small 'Listing mental model tags' subsection to the existing
'Tags and Visibility' section, mirrored byte-for-byte across both docs.
2026-04-29 15:03:03 +02:00
Minghao Xiao 2bada2dbec fix: redact database URLs in config logs (#1316) 2026-04-29 15:02:42 +02:00
zwcf5200 324b4b0a59 fix(embeddings): add allowed_openai_params for OpenAI-compatible embedding dimensions (#1320)
When using litellm-sdk with OpenAI-compatible custom models (model name
starts with "openai/"), the "dimensions" parameter is rejected by litellm
unless it is explicitly allow-listed via allowed_openai_params.

This fix adds the allow-listing so that HINDSIGHT_API_EMBEDDINGS_LITELLM_SDK_OUTPUT_DIMENSIONS
works correctly with OpenAI-compatible embedding endpoints.

Fixes: custom embedding models with OpenAI-compatible APIs reject the
dimensions parameter unless allowed_openai_params includes "dimensions".
2026-04-29 15:01:40 +02:00
Nicolò Boschi 9be2e0503a fix(test): remove stale profile auto-create assertion from bank stats test (#1323)
* fix(test): remove stale profile auto-create assertion from bank stats test

GET /banks/{bank_id}/profile no longer auto-creates banks (99a89789),
so the empty-bank timeseries test was failing with 404. The profile
check was unnecessary — the timeseries endpoint handles non-existent
banks by returning zero-filled buckets.

* fix(test): update remaining tests for profile no-auto-create change

Three more tests relied on GET /profile auto-creating banks:
- test_base_path: remove redundant profile GET, retain creates the bank
- test_http_api_integration: same — bank is created by the first retain
- test_bank_templates: export of nonexistent bank now correctly expects 404

* fix(test): replace all GET /profile bank creation with PUT /banks

More tests relied on GET /profile to auto-create banks:
- test_reflections: 6 occurrences used as bank creation step
- test_http_api_integration: 1 occurrence used to ensure bank exists
- test_base_path_deployment: 1 occurrence in integration tests

* fix(test): upgrade gemini-3-pro-preview to gemini-3.1-pro-preview

The older model was timing out in CI.
2026-04-29 15:01:02 +02:00
Nicolò Boschi 526c61a170 fix(oracle): restore exact v0.5.6 PG query shapes (#1321)
Revert the two PG query changes introduced by the Oracle abstraction
PR (#1307) back to the exact v0.5.6 SQL:

1. Semantic dedup: restore GROUP BY + MAX(weight) + ORDER BY score DESC
   instead of DISTINCT ON. The Oracle PR rewrote this for portability,
   but the PG ops layer should emit the identical query shape.

2. Temporal neighbors: restore exact v0.5.6 query shape with
   src.unit_id::text AS from_id, ABS(EXTRACT(...)), combined.*,
   ROW_NUMBER PARTITION BY src.unit_id.

The only accepted query difference vs 0.5.6 is the observation_sources
junction table reads (new table for Oracle portability).
2026-04-29 12:28:09 +02:00
Nicolò Boschi 3ce26866d2 release(smolagents): v0.1.0 2026-04-29 11:38:30 +02:00
BenandNicolò Boschi 8314de5e06 feat: add SmolAgents integration with Hindsight memory tools (#658)
* feat(smolagents): add SmolAgents integration with Hindsight memory tools

Adds hindsight-integrations/smolagents with retain, recall, and reflect tools
for HuggingFace SmolAgents.

- hindsight_smolagents/: config, errors, and tools (retain/recall/reflect, plus
  memory_instructions helper for prompt-time injection)
- 81 unit tests (all passing)
- Docs page at hindsight-docs/docs-integrations/smolagents.md
- Icon at hindsight-docs/static/img/icons/smolagents.png
- Entry in integrations.json so it appears on the listing page
- CI workflow job test-smolagents-integration
- Wired into scripts/release-integration.sh VALID_INTEGRATIONS

Replaces the earlier draft commits (originally opened March 23) with a clean
single commit rebased on latest main, dropping unrelated package-lock.json
changes that had been bundled in by mistake.

* fix(smolagents): add title and description to docs frontmatter

build-docs CI requires every integration page to have both 'title' and
'description' in its frontmatter. Without them, check-integration-seo.mjs
fails the docusaurus build.

* ci: re-trigger CI after flaky test-python-client

* fix(smolagents): wire integration into release + sidebar; lint fixes

- Add smolagents to the INTEGRATIONS table in generate_changelog.py so
  the release script can cut a tag (release-integration.sh already had
  it after the rebase, but the changelog generator needs its own entry).
- Add a sidebar link in hindsight-docs/sidebars.ts so the docs page is
  reachable from navigation, matching the agentcore pattern.
- examples/interactive_test.py: import-order + drop f-prefix on a
  no-placeholder f-string (ruff F541, I001).
- ruff format adjustments in tools.py.

---------

Co-authored-by: Nicolò Boschi <[email protected]>
2026-04-29 11:37:49 +02:00
Nicolò Boschi 1a37ad15d1 docs: add scoring & ranking deep dive to recall docs (#1317)
Explains how the recall pipeline actually scores and ranks results:
RRF fusion formula, cross-encoder reranking, combined scoring boosts
(recency, temporal proximity, proof count), budget-to-pipeline mapping,
and graph scoring detail. Includes design rationale for each algorithm
choice (why RRF, why multiplicative boosts, why tanh for entities).
2026-04-29 11:17:21 +02:00
Nicolò Boschi 300a8c1e81 refactor(release): consolidate integration metadata into one table (#1314)
generate_changelog.py kept three parallel lists (VALID_INTEGRATIONS,
package-name map, display-name map). Adding a new integration meant
remembering to update all three; missing one only surfaced mid-release
when the script aborted.

Replace them with a single INTEGRATIONS dict keyed by slug, holding an
IntegrationMeta(package_name, display_name) per row. VALID_INTEGRATIONS
is derived from the dict's keys so the CLI help still works. The
display_name falls back to the slug when omitted, preserving current
behavior for ag2, cloudflare-oauth-proxy, and openai-agents.
2026-04-29 10:53:42 +02:00
Nicolò Boschi b50a86a87f release(agentcore): v0.1.1 2026-04-29 10:41:13 +02:00
Nicolò Boschi 1d85f5a0d6 fix(release): map agentcore to package + display name in changelog gen
generate_changelog.py keeps three integration tables (allowlist, package
name, display name). The previous fix added agentcore to the allowlist;
add it to the package-name and display-name maps too so the release can
finish.
2026-04-29 10:40:55 +02:00
Nicolò Boschi 2e5ed7f936 fix(release): add agentcore to changelog generator allowlist
scripts/release-integration.sh was updated to recognize the agentcore
integration in #822, but generate_changelog.py keeps its own copy of
VALID_INTEGRATIONS that wasn't kept in sync. Releasing agentcore failed
at the changelog-generation step. Add agentcore to the generator's list.
2026-04-29 10:40:12 +02:00
Nicolò Boschi 76bcd93156 fix(oracle): restore PG query semantics and clean up migration chain (#1312)
The Oracle PR (#1307) introduced subtle behavioral changes to two PG
query patterns during the abstraction refactor:

1. semantic_expanded CTE: the DISTINCT ON rewrite lost the global
   ORDER BY score DESC before LIMIT. When results exceeded the budget,
   the LIMIT applied in mu.id order instead of keeping the highest-
   scored rows. Fix: wrap DISTINCT ON in a subquery that re-sorts by
   score before applying LIMIT.

2. temporal neighbors: the ROW_NUMBER() OVER (PARTITION BY ... ORDER BY
   time_diff_hours) filter was dropped, doubling the returned rows per
   probe (K per direction × 2 instead of K closest overall). Fix:
   restore the ROW_NUMBER filter around the UNION ALL of both scan
   directions, for both PG and Oracle backends.

3. Migration chain: remove two empty merge migrations that were
   artifacts of the Oracle branch being developed in parallel
   (e6f7g8h9i0j1, j5k6l7m8n9o0) and linearize the chain:
   8c6fa6f7230b → d5y6z7a8b9c0 → i4j5k6l7m8n9 → k6l7m8n9o0p1
2026-04-29 10:38:55 +02:00
Nicolò Boschi b153541e27 fix(agentcore): async-native client, task tracking, drop per-package CHANGELOGs (#1313)
* fix(agentcore): switch adapter to async-native client + track retention tasks

Use client.arecall/areflect/aretain directly instead of wrapping the sync
methods in run_in_executor (which spawned a worker thread that itself
created a new event loop per call). Matches the pipecat integration's
pattern.

Track fire-and-forget retention tasks in a set with a done-callback
discard so asyncio cannot GC them mid-flight. Drop the unused
threading.local client cache and the deprecated asyncio.get_event_loop()
calls.

Type _format_memories against RecallResult attributes instead of
getattr fallbacks. Drop the unimplemented 'hybrid' mode from the
RecallPolicy docstring.

* chore(integrations): drop per-package CHANGELOG.md files

The canonical changelog for each integration lives at
hindsight-docs/src/pages/changelog/integrations/<name>.md and is
written by ./scripts/release-integration.sh at release-cut time.
Per-package CHANGELOG.md files duplicate that content and encourage
pre-staging Unreleased entries, which CLAUDE.md disallows.
2026-04-29 10:32:25 +02:00
Ben c91696f53d feat(agentcore): add hindsight-agentcore integration for Bedrock AgentCore Runtime (#822)
* feat(agentcore): add hindsight-agentcore Python integration

Adds durable cross-session memory for Amazon Bedrock AgentCore Runtime
agents. Runtime sessions are ephemeral; this adapter persists memory
across session churn keyed to stable user identity.

- HindsightRuntimeAdapter with before_turn() / after_turn() / run_turn()
- TurnContext: maps AgentCore invocation identity to Hindsight banks
- default_bank_resolver: tenant:user:agent format (session ID never used)
- RecallPolicy: recall (default) or reflect mode with configurable budget
- RetentionPolicy: context label, tags, metadata, user message inclusion
- Async-by-default retention — never delays the turn response
- Graceful degradation throughout — memory failures never surface to user
- 41 unit tests covering adapter, bank resolution, and config

* feat(agentcore): add CI job, release entry, and docs page

* Add AgentCore icon to sidebar

* fix(agentcore): add pytest to dependency-groups, fix paperclip.md diff

* feat(agentcore): add LICENSE, CHANGELOG, example, live test, and listing entry

Brings PR #822 to parity with the Pipecat reference (commit f7cc9ad6):

- LICENSE (MIT) for community distribution readiness
- CHANGELOG.md: initial 0.1.0 release notes
- examples/basic_runtime_handler.py: minimal AgentCore Runtime handler
  showing TurnContext + adapter.run_turn() with a stub agent_callable
- tests/test_live_integration.py: pytest-skipif live test gated on
  HINDSIGHT_API_KEY; verifies retain (turn 1) -> recall (new session, same user)
  surfaces the planted fact via memory_context
- integrations.json: agentcore entry so it appears on the listings page

Verified: 41 unit tests pass (live test skips cleanly without the key);
ruff clean.
2026-04-29 10:13:22 +02:00
DK09876andClaude Opus 4.6 50f559c9e4 Oracle 23ai database backend (#1307)
* feat(oracle): add Oracle 23ai database backend with full abstraction layer

Add Oracle 23ai as a first-class database backend alongside PostgreSQL via
a clean DatabaseBackend / DataAccessOps / SQLDialect abstraction layer.

Key changes:
- DatabaseBackend ABC with PostgreSQL and Oracle implementations
- DataAccessOps for backend-specific multi-statement operations
- SQLDialect for stateless SQL fragment generation
- Oracle SQL rewriter: translates PG syntax at runtime ($N params, ::casts,
  ON CONFLICT, LIMIT/OFFSET, JSON operators, date_trunc, intervals, etc.)
- Multi-tenant schema isolation via ALTER SESSION SET CURRENT_SCHEMA
- Oracle Text CONTAINS with graceful BM25 fallback
- FOR UPDATE SKIP LOCKED task claiming (Oracle-native)
- CLOB/JSON handling with automatic LOB-to-string conversion
- Comprehensive Oracle integration + HTTP E2E test suites (60 tests)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(oracle): resolve rebase conflicts, harden test assertions, add Oracle retry handling

Remove stale causal_weight_threshold parameter from expand_observations
across all backends and link_expansion_retrieval. Add Oracle exception
handling (InterfaceError, OperationalError, IntegrityError) to retry
logic in memory_engine so Oracle connection/integrity errors trigger
proper retry/skip behavior. Strengthen Oracle integration test assertions
to verify non-empty results and handle known ORA-00060 deadlocks.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(oracle): harden Oracle backend for production readiness

- Fix DPY-4008 bind placeholder error in Oracle Text BM25 fallback by
  rebuilding semantic-only query with correct param indices when CONTAINS
  fails (DRG-10599)
- Add Oracle ORA-00060 deadlock detection to retry_with_backoff so Oracle
  deadlocks get the same exponential backoff as PG DeadlockDetectedError
- Use fq_table() for obs_sources_table in both Oracle and PG ops instead
  of fragile string replacement on mu_table
- Fix ResultRow.__bool__ to delegate to underlying data instead of always
  returning True
- Improve Oracle fuzzy entity resolution fallback logging to include the
  actual error message
- Fix OracleDialect.prepare_bm25_text to handle empty token list edge case
  with proper fallback to escaped query text
- Add E2E smoke test script for Oracle pipeline validation

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(test): update ResultRow bool test for delegating behavior

The test_bool_always_true test expected ResultRow({}) to be truthy,
but we changed __bool__ to delegate to the underlying data. Update
the test to verify both truthy (non-empty) and falsy (empty) cases.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* chore: regenerate OpenAPI spec, docs skill, and fix lint formatting

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-29 10:11:45 +02:00
Ben 4ea650f6c4 Fix broken link in CLI ARM64 guide (#1305) 2026-04-28 16:31:41 -04:00
Ben df6662fe04 docs(guides): add Hindsight update guides (#1301)
* docs(guides): add hindsight update guides batch
2026-04-28 16:13:19 -04:00
Ben 75dd70fa8a Add Pipecat voice AI persistent memory blog post (#1300)
* Add Pipecat voice AI persistent memory blog post
2026-04-28 18:17:37 +00:00
Nicolò Boschi 92f3ee4671 docs: add 0.5.6 changelog and warn about 0.5.5 schema regression
Add 0.5.6 changelog entry documenting the reverted JSON schema
simplification. Add warnings to the 0.5.5 blog post and changelog
entry about the regression that caused 0 facts extracted.
2026-04-28 18:21:51 +02:00
Nicolò Boschi e9b187330c Release v0.5.6
- Update version to 0.5.6 in all components
- Regenerate OpenAPI spec and client SDKs
- Python packages: hindsight-api, hindsight-dev, hindsight-all, hindsight-embed
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- hindsight-all npm wrapper: hindsight-all-npm
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
- Sync documentation to version-0.5
2026-04-28 18:20:34 +02:00
Nicolò Boschi 28c9aa6151 Revert "fix(llm): simplify JSON schemas for better Ollama and LLM compliance (#1292)"
This reverts commit 5b1c3486f3.
2026-04-28 18:18:39 +02:00
Minghao Xiao 98593f9a20 ci: include linux arm64 CLI in release assets (#1298) 2026-04-28 14:00:53 +02:00
Nicolò Boschi 868d5e2ffd docs(release): changelog and blog post for v0.5.5 (#1297)
- Add changelog entry generated from commits between v0.5.4..v0.5.5.
- Add blog post highlighting the redesigned Mental Models List view, the
  Pipecat integration, full Windows support for the embedded runtime, the
  LLM-provider compatibility wave, and the one breaking change in this
  release: GET /banks/{bank_id}/profile no longer auto-creates banks.
- Regenerate docs-skill so the skill mirror reflects the new entries.
2026-04-28 13:44:49 +02:00
Nicolò Boschi c308e473a8 Release v0.5.5
- Update version to 0.5.5 in all components
- Regenerate OpenAPI spec and client SDKs
- Python packages: hindsight-api, hindsight-dev, hindsight-all, hindsight-embed
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- hindsight-all npm wrapper: hindsight-all-npm
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
- Sync documentation to version-0.5

scripts/generate-clients.sh: generate the Python client into a tmp dir
then sync into place. The previous direct bind mount of the client dir
worked on Linux CI but failed on macOS Docker Desktop with
NoSuchFileException when openapi-generator wrote api_client.py and
related supporting files; generating into /tmp avoids that.
2026-04-28 13:24:08 +02:00
Nicolò Boschi 8fbe85f0ca feat: mental-models List view + /tags?source=mental_models (#1296)
* feat(api): list mental-model tags via /tags?source=mental_models

Adds a `source` query param to GET /v1/default/banks/{bank_id}/tags so the
same endpoint can list tags from either memory_units (default) or
mental_models. Mental-model tag suggestions previously had no API; the
alternative of a sibling /mental-models/tags route would have shadowed
GET /mental-models/{mental_model_id} for the literal id "tags".

Engine: new list_mental_model_tags method sharing a private
_list_tags_from_table helper with the existing list_tags.

Tests: covers the engine method (basic counts, wildcard) and an HTTP-level
check that source=mental_models reads from mental_models while default
remains memory_units.

* feat(control-plane): mental-models List view with tag filter

Adds a default split-pane "List" view to the Mental Models page (sidebar of
files + content on the right) and a reusable <TagFilterInput> with free-text
entry, debounced suggestions from the server, and chip selection.

Changes:
- Default Mental Models view is "List" (file/folder metaphor); the existing
  card "Dashboard" view stays as a secondary toggle. Old "Table" view removed.
- Sidebar entries show name, source query subtitle, and relative refresh time.
- Tag filtering is server-side via the existing tags/tags_match params on
  /mental-models; suggestions populate from /tags?source=mental_models.
- Memories (data-view) reuse the same TagFilterInput, gaining suggestions
  it didn't have before.
- Adds proxy route for GET /tags (forwards optional source query param).
- TagFilterInput holds the caller's fetchSuggestions in a ref to keep the
  debounce effect from refiring on every render when callers pass an inline
  closure (which would otherwise loop).
2026-04-28 12:31:21 +02:00
Nicolò Boschi e97a5c9a6e test(integration): add Hermes Agent embedded-mode smoke test (#1283)
Drives the HindsightMemoryProvider plugin shipped with Hermes Agent against
a locally-spawned Hindsight Embedded daemon, exercising the full
sync_turn -> retain -> recall roundtrip end-to-end through the plugin's
real code path.

Run on demand only (not part of CI) via the installed Hermes venv, which
already has every dep — no new pyproject changes needed:

    HINDSIGHT_LLM_API_KEY=... \
        ~/.hermes/hermes-agent/venv/bin/python -m pytest \
        hindsight-integration-tests/tests/test_hermes_embedded_smoke.py \
        -v -s -o addopts=""

The test uses a temp HERMES_HOME so it never touches the user's real
~/.hermes profile, and tears down its daemon on exit. Skips automatically
when the LLM key (HINDSIGHT_LLM_API_KEY or OPENAI_API_KEY) isn't set or
when ~/.hermes/hermes-agent isn't installed.
2026-04-28 11:43:18 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> a50567f864 chore(deps): bump actions/upload-artifact from 4 to 7 (#1278)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-28 11:43:08 +02:00
Nicolò Boschi 461b00d4d9 fix(llm): omit tool_choice="auto" and add deepseek as first-class provider (#1294)
* fix(llm): omit tool_choice="auto" and add deepseek as first-class provider

DeepSeek's reasoner pathway (which deepseek-v4-flash enters by default
with thinking mode) returns HTTP 400 for any tool_choice value, including
"auto". Since omitting tool_choice is semantically equivalent to "auto"
per the OpenAI API spec, we now omit it whenever the caller passes "auto",
which fixes reflect for deepseek-v4-flash without changing behaviour for
compliant providers.

Also promotes DeepSeek to a first-class provider: provider="deepseek"
auto-configures base_url=https://api.deepseek.com and the default model
to deepseek-v4-flash. Documented in configuration.md and .env.example.

* docs(deepseek): add to LLMProvidersGrid, default-models table, and config examples

The LLMProvidersGrid component on the Models page is the canonical visual
list of supported LLM providers; it was missing DeepSeek. Also add it to
the provider default-models table and the per-provider configuration
example block in models.mdx so the page is internally consistent.

* docs: single-source-of-truth for LLM providers (data file + table component)

Adds hindsight-docs/src/data/llmProviders.tsx as the canonical list of
supported providers with id, label, icon, and default model. Both
LLMProvidersGrid (icon grid on the Models page) and the new
LLMProvidersTable component (used in models.mdx for the default-models
table) consume it, so adding a provider now means editing one file
instead of three.

While converting, also added the providers that were missing from the
icon grid: Vertex AI, OpenAI Codex, Claude Code, OpenRouter.

* fix(docs-skill): render LLM provider grid + table in agent skill mirror

The agent-facing skill at skills/hindsight-docs/ is plain markdown — the
MDX-to-MD converter in scripts/generate-docs-skill.sh was leaving
<LLMProvidersTable /> and <LLMProvidersGrid /> as literal JSX, breaking
the verify-generated-files CI check and hiding the supported-providers
data from agents that rely on the skill.

Move the provider data out of llmProviders.tsx into llmProviders.json so
both the React components and the Python skill generator read from the
same source. Teach the converter to render <LLMProvidersTable /> as a
markdown table and <LLMProvidersGrid /> as a bullet list, sourced from
that JSON. Adding a provider is still one-file: edit llmProviders.json.

* chore(pipecat): apply ruff format

Files added in f7cc9ad6 (feat(pipecat)) have unformatted whitespace and
line lengths that the shared ruff config rewrites. Local lint.sh only
re-formats integrations with uncommitted changes, so the drift slipped
in; CI runs with LINT_ALL=1 and surfaces it via verify-generated-files.
2026-04-28 11:42:58 +02:00
Nicolò Boschi 4bc772d8f8 fix(retain): drop strength from causal relations to fix Bedrock Converse (#1295)
The Pydantic CausalRelation/FactCausalRelation models emitted strength as a
float with ge=0.0/le=1.0 constraints, which produced minimum/maximum keys in
the JSON schema. AWS Bedrock Converse API rejects those keys on number types,
causing every retain call against Bedrock Claude to silently produce 0 facts
(see #1289).

In practice the LLM-emitted strength was always 1.0, so the 0.3
causal_weight_threshold filter and weight-based ranking in link expansion
never differentiated anything. Drop the field end-to-end:
- Remove strength from both Pydantic schemas and the dataclass
- Hardcode link weight=1.0 in create_causal_links_batch
- Remove causal_weight_threshold and the AND ml.weight >= $N filters

Causal links still carry weight in the DB (column unchanged) so the signal
can be re-introduced later if a real source of weights appears.

Fixes #1289
2026-04-28 11:25:32 +02:00
Chris Bartholomew 99a8978905 fix(api): GET /banks/{bank_id}/profile no longer auto-creates the bank (#1287)
* fix(api): make GET /banks/{bank_id}/profile a true read (no auto-create)

The HTTP GET handler for bank profile was calling
get_or_create_bank_profile, so a request for a non-existent bank would
silently create it as a side effect. This is dangerous for any client
that polls or holds a stale bank_id while the surrounding context
(tenant, schema, user session) changes — the GET would create the
bank in whatever tenant the request was authenticated against, not
the tenant the client originally meant.

Reads must not have create-as-side-effect. Changes:

* Add bank_utils.get_bank_profile_if_exists(pool, bank_id) — pure
  read; returns None when the row is absent.
* memory_engine.get_bank_profile gets a create_if_missing kwarg
  (defaults True for backwards compatibility). When False, uses the
  new pure-read path and returns None on miss; the caller is
  responsible for translating None to a 404.
* Read-only HTTP endpoints pass create_if_missing=False:
  - GET /v1/default/banks/{bank_id}/profile
  - GET /v1/default/banks/{bank_id}/template (export)
  - GET /v1/default/banks/{bank_id}/audit/logs
  - GET /v1/default/banks/{bank_id}/audit/stats
  All four now return 404 for a missing bank instead of silently
  materializing one.
* Write paths (PUT/PATCH bank, import template, MCP retain/recall)
  keep the default create_if_missing=True — they have explicit
  expectations about creating banks on first use.

Test: tests/test_agents_api.py adds
test_get_bank_profile_no_auto_create_returns_none asserting that a
missing bank is not created as a side effect of a read, and that
explicit auto-create still works after.

* chore(api): @overload get_bank_profile so existing callers stay non-Optional

The previous commit added a create_if_missing kwarg to get_bank_profile
and changed the return annotation to dict[str, Any] | None. That made
the type checker treat every existing caller as receiving Optional,
producing 12 not-subscriptable errors in mcp_tools.py where callers
assumed non-None.

Add @overload variants so the precise return type is recovered:
  - create_if_missing=Literal[True] (the default)  -> dict[str, Any]
  - create_if_missing=Literal[False] (explicit)    -> dict[str, Any] | None

The interface.py abstract declaration mirrors the new signature.
ty check hindsight_api/ is clean after this change.
2026-04-28 11:13:22 +02:00
Nicolò Boschi 91106f30ef fix(parsers): LlamaParse follow-up — reuse client, fix error mapping, add tests (#1293)
Follow-up to #1288: reuse httpx client, fix error mapping, add unit tests
2026-04-28 10:45:53 +02:00
Nicolò Boschi 5b1c3486f3 fix(llm): simplify JSON schemas for better Ollama and LLM compliance (#1292)
* fix(llm): simplify JSON schemas for better Ollama and LLM compliance (#1274)

Pydantic v2's model_json_schema() produces schemas with $ref/$defs, anyOf
(for Optional fields), and const — features that Ollama's grammar-based
constrained decoding silently fails on, causing it to fall back to
unconstrained generation. This also confuses weaker models when the schema
is appended as a text hint in the prompt for other providers (Groq, etc.).

Add _simplify_json_schema() that resolves $ref/$defs by inlining,
simplifies anyOf nullable unions, and replaces const with single-element
enum. Applied to both the Ollama native API path and the prompt-text
schema path for all OpenAI-compatible providers.

Controlled by HINDSIGHT_API_LLM_SIMPLIFY_JSON_SCHEMA (default: true).

* docs(configuration): add HINDSIGHT_API_LLM_SIMPLIFY_JSON_SCHEMA env var
2026-04-28 10:27:55 +02:00
Nicolò Boschi 685e4cf0ef release(pipecat): v0.1.1 2026-04-28 10:17:43 +02:00
Nicolò Boschi 73a0ad0cc3 chore(pipecat): register integration in generate-changelog
Adds pipecat to VALID_INTEGRATIONS, package map, and display name map
so ./scripts/release-integration.sh pipecat can generate the docs
changelog. Mirror of the entry in scripts/release-integration.sh added
in #921.
2026-04-28 10:17:20 +02:00
Ben f7cc9ad663 feat(pipecat): add Pipecat voice AI pipeline memory integration (#921)
* feat(pipecat): add Pipecat voice AI pipeline memory integration

* fix(pipecat): make OpenAILLMContextFrame import optional for forward compat

* feat(pipecat): add LICENSE, CHANGELOG, examples, and live integration test

- LICENSE (MIT) + CHANGELOG.md for community distribution readiness
- examples/basic_pipeline.py: full Daily/Deepgram/OpenAI/Cartesia voice pipeline
- examples/interactive_chat.py: text-based REPL for manual memory validation
- tests/test_live_integration.py: pytest-skipped live test, verifies Retain/Recall/Inject/Idempotency against a running Hindsight instance

Verified: 17/17 unit tests pass; live integration test passes all 4 checks against localhost:8888.

* chore(pipecat): add docs page, integrations listing entry, and icon

- hindsight-docs/docs-integrations/pipecat.md: docs page for the integrations site
- hindsight-docs/src/data/integrations.json: entry so Pipecat appears on the listing
- hindsight-docs/static/img/icons/pipecat.png: icon for the listing
2026-04-28 10:07:40 +02:00
Nicolò Boschi 843dcec77b docs(0.5): sync versioned docs to current docs/ 2026-04-27 17:28:11 +02:00
Nicolò Boschi ae0e3cec8d docs(installation): document memory footprint and hardware requirements (#1282)
* docs(installation): document memory footprint and hardware requirements

Add a Hardware subsection under Prerequisites with per-component RAM
guidance (full vs slim image, control plane, worker, postgres) and
extend the Docker Image Variants table with an Idle RAM column so users
know what to provision before deploying.

* docs(installation): leave Docker Image Variants table alone, soften GPU note

- Revert the Idle RAM column on the Docker Image Variants table; the
  Hardware subsection already carries that detail.
- Reword the CPU/GPU line: CPU is fine for dev and basic workloads, but
  the local cross-encoder reranker typically benefits from a GPU under
  production traffic — or offload reranking to an external provider.

* docs(skill): regenerate hindsight-docs skill mirror
2026-04-27 17:16:23 +02:00
Ben a9967627ae docs(integrations): add ChatGPT and Perplexity integration guides (#1280)
* docs(integrations): add ChatGPT and Perplexity integration guides

- Create chatgpt.md with OAuth setup, custom instructions, and best practices
- Create perplexity.md with OAuth setup, custom instructions, and research workflows
- Update sidebar to include both integrations with icons
- Include troubleshooting, data privacy, and architecture sections

* docs(integrations): add ChatGPT and Perplexity to integrations listing

* docs(icons): add ChatGPT and Perplexity integration icons
2026-04-27 17:08:17 +02:00
Chris Bartholomew f6d659c927 fix(mcp): report Hindsight's version in serverInfo, not FastMCP's (#1281)
FastMCP defaults serverInfo.version to its own library version when the
MCP server constructor isn't given an explicit version. As a result,
clients listing the server saw e.g. "3.0.0" / "3.2.4" (the FastMCP
release in use) instead of Hindsight's actual version. Pass
HINDSIGHT_VERSION explicitly so the reported version reflects this
project.
2026-04-27 16:41:39 +02:00
Nicolò Boschi 794b83d839 chore(lint): cover all npm packages with prettier in lint.sh (#1279)
So formatting violations in hindsight-clients/typescript and
hindsight-all-npm now fail CI via verify-generated-files (same
git-status-after-lint pattern Python uses).

- Add prettier-ts-client and prettier-all-npm tasks to lint.sh
- Delete hindsight-clients/typescript/.prettierrc local override so
  openapi-ts auto-discovers the shared root .prettierrc.json (was
  printWidth 80 / trailingComma "all", now 100 / "es5")
- Reformat affected files (mostly mechanical)
2026-04-27 16:23:15 +02:00
Ben dcc2d69d6f Add blog post: Connect ChatGPT and Perplexity to Hindsight for Long-Term Memory (#1255)
* Add blog post: Connect ChatGPT and Perplexity to Hindsight for Long-Term Memory
2026-04-27 09:18:27 -04:00
Nicolò Boschi 4ba2fffe8d fix(consolidation): reduce memory fan-out during consolidation recall (#996)
* fix(consolidation): reduce memory fan-out during consolidation recall (#996)

Three changes to address unbounded RSS growth during consolidation:

1. Default consolidation recall budget to LOW instead of MID, reducing
   hnsw_fetch from 1,500 to 500 rows per recall arm. Configurable via
   HINDSIGHT_API_CONSOLIDATION_RECALL_BUDGET env var.

2. Default consolidation_source_facts_max_tokens to 4096 instead of -1
   (unlimited), bounding the source-fact hydration that was the worst-case
   memory amplifier on large banks.

3. Default FlashRank ONNX cpu_mem_arena to False, preventing the ONNX
   Runtime memory arena from growing monotonically and pinning RSS after
   consolidation batches complete. Configurable via
   HINDSIGHT_API_RERANKER_FLASHRANK_CPU_MEM_ARENA env var.

* docs(configuration): document new consolidation and FlashRank env vars

* chore: fix lint formatting and regenerate docs skill mirror

* fix: revert accidental removal of Deno client patch in client.gen.ts
2026-04-27 14:54:42 +02:00
Nicolò Boschi 0cffa43cbd release(openclaw): v0.6.6 2026-04-27 12:47:11 +02:00
Nicolò Boschi 70677457d9 fix(openclaw): stop silently skipping retention on default agent:main:main sessions (#1276)
The default dynamicBankGranularity is ["agent","channel","user"] in deriveBankId,
but getIdentitySkipReason defaulted to false when the field was unset, causing
agent:main:main sessions to be silently skipped from retention and recall.

Align both paths: default agentBanking to true (matching the runtime default),
normalise dynamicBankGranularity at config-validation time, and extract a shared
DEFAULT_DYNAMIC_BANK_GRANULARITY constant.

Also adds throttled info-level logging for identity skip events so operators can
discover silent skips without enabling debug mode.

Closes #1215
2026-04-27 12:46:09 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> ee2d8f7540 chore(deps): bump actions/github-script from 8 to 9 (#1025)
Bumps [actions/github-script](https://github.com/actions/github-script) from 8 to 9.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v8...v9)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-27 12:44:01 +02:00
Evo b962de50d8 docs(configuration): mirror COHERE_OUTPUT_DIMENSIONS env var (#1249 drift) (#1252) 2026-04-27 12:14:05 +02:00
grimmjoww578andClaude Opus 4.7 130bb2d616 fix(embed): use getattr for Windows-only subprocess attrs to satisfy ty (#1263)
`subprocess.DETACHED_PROCESS` and `subprocess.CREATE_NEW_PROCESS_GROUP` are
Windows-only constants. The existing code is already guarded by
`if platform.system() == "Windows":`, but `ty`'s static analysis doesn't
track platform-conditional branches, so it flags both attributes as
`unresolved-attribute` on the Linux CI runner — failing
`verify-generated-files`.

Switching to `getattr(subprocess, "DETACHED_PROCESS", 0)` keeps the same
runtime behavior on Windows (constant is present, returned as-is) and
avoids the static-analysis false positive on Linux/macOS where the
attribute access would never execute anyway.

Same fix pattern documented in cpython subprocess docs and used widely
in cross-platform Python codebases.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-04-27 12:13:40 +02:00
Evo b0c1afb19f docs(sidecar): mirror HINDSIGHT_API_EMBEDDINGS_GEMINI_FORCE_IPV4 from #1241 (#1265) 2026-04-27 12:13:01 +02:00
Evo 9654a06e22 docs(blog): align retainEveryNTurns default with #1186 (10 → 3) (#1268) 2026-04-27 12:12:40 +02:00
r266-tech e1c6092785 docs(ops): document processing + cancelled statuses from #1231 (#1238)
* docs(ops): document processing + cancelled statuses from #1231

* docs(skills): mirror operations.md status update from #1231
2026-04-24 14:53:10 +02:00
Connor Black 6fb8ac97a0 feat(embeddings): add HINDSIGHT_API_EMBEDDINGS_GEMINI_FORCE_IPV4 opt-in (#1241)
* feat(embeddings): add HINDSIGHT_API_EMBEDDINGS_GEMINI_FORCE_IPV4 opt-in

In environments where AAAA records resolve but IPv6 egress is broken
(some Docker/VPC setups), the Gemini embeddings client hangs on connect.
This adds an opt-in flag that configures the google-genai client with an
httpx transport bound to 0.0.0.0 so it uses IPv4 only.

Defaults to false; treated as a static (server-level) config per the
project's hierarchical-config guidelines since it is an infrastructure
concern rather than per-tenant business logic.

* fix(embeddings): move force_ipv4 after batch_size to preserve positional compat

Addresses Copilot review feedback. Inserting force_ipv4 at position 7
shifted batch_size to position 8 — any external caller passing batch_size
positionally would have silently started setting force_ipv4 instead.
All internal call sites use kwargs so nothing in the repo was affected,
but keeping the new param at the end of the signature is the right API
hygiene for downstream users.
2026-04-24 14:52:51 +02:00
r266-tech ecd0b846ed docs: add nodes_by_fact_type field to Document Response Format example (#1243)
* docs: add nodes_by_fact_type field to Document Response Format example

* docs(skills): mirror nodes_by_fact_type addition in references
2026-04-24 14:52:22 +02:00
M1p0 0bbc058336 fix(llm): handle DeepSeek tool-call quirks (#1253) 2026-04-24 14:50:43 +02:00
Nicolò Boschi 4ba54d8c8f feat(embed): full Windows support + prefer sibling hindsight-api over uvx (#1250)
* fix(embed): prefer locally-installed hindsight-api over uvx

Falling through to `uvx hindsight-api@...` when hindsight-embed is
installed via `uv pip install --target` (e.g. NixOS, hindsight-all)
downloads a standalone Python whose ABI doesn't match the sibling
site-packages' C extensions, causing `ModuleNotFoundError:
asyncpg.protocol.protocol` at daemon startup (closes #1240).

Check for a sibling `hindsight-api` entry point in `bin/` (or
`Scripts/hindsight-api.exe` on Windows) before falling back to uvx.

* ci(embed): add Windows unit-test job for hindsight-embed

Runs pytest on windows-latest to exercise the Windows code paths in
hindsight-embed (msvcrt file locking, .exe binary detection in
_find_api_command, netstat-based PID lookup).

Skips the test.sh smoke test: the daemon uses POSIX-only
subprocess.Popen(start_new_session=True) and signal.SIGTERM, so making
the full lifecycle Windows-safe is a separate effort.

* ci(embed): add Windows --target install test for issue #1240

Exercises the exact install layout from the issue: `uv pip install
--target` hindsight-embed + hindsight-api-slim, then verify the sibling
`Scripts/hindsight-api.exe` is discovered by `_find_api_command()`
instead of falling back to uvx.

Also runs `hindsight-embed --help` from the installed binary as a
basic smoke check. Daemon startup is still out of scope (needs
secrets + POSIX `start_new_session=True` fix).

* feat(embed): full Windows support for daemon + smoke test

Fixes every platform-specific blocker that previously forced the
Windows CI job to skip the smoke test:

- hindsight-api-slim/daemon.py: skip the double-fork on Windows (no
  fork model). The spawning embed process now drives detachment via
  CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS instead.
- hindsight-embed/daemon_embed_manager.py: centralize detach flags in
  _detach_popen_kwargs(). Windows requires creationflags plus explicit
  stdout/stderr redirection (DETACHED_PROCESS leaves the child with no
  console). POSIX keeps start_new_session=True.
- hindsight-embed/cli.py: reconfigure sys.stdout/stderr to UTF-8 on
  Windows so Rich's box-drawing / ✓ glyphs don't crash the default
  cp1252 codec.
- hindsight-embed/profile_manager.py: seek to byte 0 before msvcrt
  lock/unlock. Windows's msvcrt.locking(LK_UNLCK) requires the file
  pointer at the start of the locked region, which wasn't true after
  json.dump moved the position past the data.
- hindsight-embed/test.sh: detect python vs python3 so Git Bash on
  windows-latest (which only ships `python`) can run the smoke test.
- tests: set USERPROFILE alongside HOME because Path.home() on Windows
  consults USERPROFILE, not HOME.
- HINDSIGHT_EMBED_DAEMON_STARTUP_TIMEOUT env var: bump on Windows CI
  since pg0-embedded's initdb on cold runners is slow.

CI: test-embed-windows now mirrors the Linux test-embed job —
vertexai creds, local-ml/embedded-db extras, HF cache, full smoke
test — on top of the --target install-layout check for issue #1240.

* fix(api-slim): gate mlx/mlx-lm off Windows in local-ml extras

mlx only ships wheels for macOS/Linux, so `uv sync --all-extras` on
win_amd64 errors out with "no source distribution or wheel for the
current platform". Constrain both to `sys_platform != 'win32'` so
Windows resolves local-ml without the Apple Silicon pieces.

* fix(embed): use Path.replace for atomic metadata write on Windows

Path.rename refuses to overwrite an existing destination on Windows
(WinError 183); every profile metadata update after the first one
failed with FileExistsError. Path.replace is the cross-platform
atomic rename added in Python 3.3 precisely for this pattern.

* fix(embed): skip configure prompts when CI env vars are set

do_configure previously gated non-interactive mode on
`sys.stdin.isatty()`: if stdin looked interactive, it went to the
prompt path regardless of env. On Windows GHA pwsh runners stdin
looks like a TTY (it doesn't on Linux headless runners), so the
subprocess-invoked `configure` would block on input and exit with
"Configuration cancelled" — even though HINDSIGHT_API_LLM_* env vars
were set.

Fall through to _do_configure_from_env whenever the required
CI inputs are present (API key set, or provider is ollama/vertexai).

* ci(embed): build and stage hindsight Rust CLI on Windows smoke test

hindsight-embed's retain/recall delegate to the Rust `hindsight` CLI.
On POSIX the embed CLI auto-installs via curl|bash, but on Windows
`bash` routes to WSL (not provisioned) and there's no Windows
installer. Build the CLI from source with cargo and copy the .exe
into ~/.local/bin, which is the first location find_cli_binary()
checks.

Also teach find_cli_binary to look for `hindsight.exe` (and drop the
Unix-only os.access X check on Windows) so the staged binary is
actually picked up.

* fix(cli): update get_graph call to match regenerated client signature

hindsight-clients/rust was regenerated when document_id + chunk_id
query params were added to /banks/{id}/graph; progenitor orders query
params alphabetically, so the call-site now needs three leading
Nones (chunk_id, document_id, limit) and type_filter in the 8th slot.
Building the CLI off the current openapi.json was failing with E0061
"this method takes 9 arguments but 7 arguments were supplied",
blocking the Windows smoke-test cargo build.

* chore(api-slim): bump pg0-embedded to 0.13.0 for Windows support

0.13.0 fixes the "IO error: invalid gzip header" crash that blocked
embedded PostgreSQL startup on Windows, which was the final remaining
blocker for the Windows hindsight-embed smoke test.

* ci(embed): install --target outside repo for sibling-binary verify

_find_api_command's first check looks for a sibling
hindsight-api-slim/ dir via Path(__file__).parent.parent.parent. When
the --target install dir lives inside the monorepo checkout, that
branch matches and the test silently exercises the dev-mode path
instead of the sibling-binary path we're trying to validate.

Move the install into $RUNNER_TEMP so the dev-mode probe misses and
the sibling-binary branch is actually hit.
2026-04-24 14:50:32 +02:00
ooa-andera da55dbb694 Update integration author for ContextForge (#1254)
Change company name to dev name
2026-04-24 14:50:04 +02:00
Nicolò Boschi ab5d2b783b fix(tests): repair 9 regressions surfaced on main (#1251)
* fix(tests): repair 9 regressions surfaced on main

Investigation and fixes for test failures on latest main:

1. test_per_operation_llm_config (2 tests): defaults were hardcoded to 10,
   but #1121 reduced DEFAULT_LLM_MAX_RETRIES to 3. Drive assertions from
   the constant so this tracks future changes automatically.

2. test_sql_schema_safety: #1210 added a docstring on task_backend.py:136
   that said "INSERTed into async_operations", which false-positived the
   unqualified-table regex (INTO+INSERT+bare table). Rephrased the prose.

3. test_memory_engine_execute_task_passes_through_defer_operation: #1231
   made execute_task short-circuit when the async_operations row is
   missing (treat as cancelled). The test created a fresh operation_id
   without inserting a row, so the handler never ran. Insert a pending
   row before execute_task.

4. 4 worker claim_batch / scan tests: assertions were counting total
   claims across the whole DB. test_async_batch_retain.py submits
   pending async_operations without sharing an xdist group, so parallel
   xdist workers polluted each other. Put test_async_batch_retain.py in
   the "worker_tests" group and also scope the worker-test assertions
   to the banks each test created, as defense-in-depth.

5. test_refresh_content_respects_max_tokens: observed ~1.9x over cap
   under Gemini's non-determinism; the 1.5x tolerance was too tight.
   Bumped to 2.5x — still well under the ~20x a "cap ignored" regression
   would produce.

* fix(tests): extend bank-scoped claim filters to 3 more worker tests

CI on the first fix commit surfaced the same cross-file isolation
problem in three additional worker tests. Apply the same bank-scoped
filter pattern so each assertion only counts claims for the bank the
test actually created:

- test_claim_batch_claims_pending_tasks
- test_concurrent_workers_claim_different_tasks
- test_worker_slot_limits_enforced (in this one the executor itself
  ignores leaked tasks so its slot-limit gating stays on our tasks)

These flake under parallel xdist because claim_batch() is global
across bank_id; any pending row from another test file gets scooped
up. The per-test filter is defense-in-depth on top of putting
test_async_batch_retain.py in the same xdist_group.

* fix(tests): isolate more slot/executor worker tests from cross-file claims

test-api CI after the previous fix surfaced four more worker tests
flaking the same way: they assert on counts that include tasks the
poller legitimately claims from other test files running in parallel.

Same bank-scoped filter pattern applied in the executor, plus the
poller-internal counter assertions relaxed to >= (our executor
returns immediately for non-our-bank tasks, but the counter may see
them briefly before the slot frees).

Covers:
- test_worker_fire_and_forget_nonblocking
- test_consolidation_slots_reserved_when_retain_saturates
- test_per_operation_slot_reservations (multi-bank variant)
- test_shared_pool_usable_by_reserved_types (preemptive)

* fix(ui): remove unnecessary \- escape in parseBucketIso regexes

ESLint's no-useless-escape flags \- inside a character class when the
dash is not between two chars. Move the dash to the boundary so it's
always a literal without needing an escape.

Pre-existing on main (introduced by #1245); surfaced when verify-
generated-files started exercising this lint path again after #1248.

* chore: sync generated files with committed sources

verify-generated-files was failing because main's committed copies of
two generated/auto-formatted files have drifted from what the scripts
and ruff now produce:

- hindsight-api-slim/hindsight_api/db_url.py: ruff format now collapses
  a 2-line list comprehension to 1 line (long-line threshold).
- skills/hindsight-docs/references/developer/configuration.md: the
  doc-skill generator emits the Cohere output_dimensions entry that
  #1249 added to configuration.md but didn't regenerate the skill copy.

Not functional changes — just aligning the committed outputs with the
generators/formatters.

* fix(tests): isolate test_recall_time_range hardcoded-UUID fixture

This file inserts memory_units with three hardcoded UUIDs
(00000000-…-000{1,2,3}). memory_units.id is a global primary key, so
parallel xdist workers running these tests simultaneously hit
pk_memory_units uniqueness violations (seen intermittently in
test-api CI as fixture-setup ERRORs).

Two defenses:
- Share an xdist_group so the eight tests serialize on the same
  worker — prevents concurrent workers from inserting the same IDs.
- Defensive pre-DELETE at fixture setup so a previous interrupted
  run's leftover rows don't poison the next setup.

Flake, not a regression from this branch, but surfaces here so
fixing it unblocks the PR.

* fix(tests): filter claims in test_poller_without_tenant_extension_uses_public

One more worker test that asserted len(claimed) == 3 without scoping
to its own bank; scope the assertion to bank_id. Keeps the schema-None
invariant on every claim since no tenant extension is configured.
2026-04-24 14:49:31 +02:00
Nicolò Boschi 13b1d92297 fix(docs): escape curly braces in generated changelog entries (#1248)
* fix(docs): escape curly braces in generated changelog entries

LLM-generated changelog summaries occasionally contain literal
`{...}` (e.g. "{user_id}" template variable), which docusaurus MDX v3
tries to evaluate as a JSX expression, breaking SSG with
`ReferenceError: user_id is not defined`.

Escape `{`/`}` in `entry.summary` at render time in the generator, and
hand-fix the two already-landed claude-code changelog files so main's
Deploy Docs workflow goes green again.

* fix(cli): update get_graph call for new chunks API query params

#1236 added chunk_id/document_id/q/tags/tags_match query params to
/banks/{id}/graph but the CLI wrapper was not updated, so a fresh
cargo build fails with an E0061 arity mismatch against the regenerated
progenitor client. Surfaces here because this PR touches hindsight-docs,
which turns on the test-doc-examples (cli) matrix.

Pass None for the new params and keep the existing type_filter/limit
forwarding; argument order matches the alphabetised generated signature.
2026-04-24 11:17:17 +02:00
Nicolò Boschi a7514e1868 feat(embeddings): allow Cohere output dimensions via env var (#1229) (#1249)
Add HINDSIGHT_API_EMBEDDINGS_COHERE_OUTPUT_DIMENSIONS to configure
custom embedding dimensions for Cohere models that support Matryoshka
embeddings (e.g. embed-v4.0). Uses the Cohere v2 API when
output_dimensions is set; falls back to v1 API otherwise.
2026-04-24 11:05:27 +02:00
Nicolò Boschi db7f492103 fix(db): accept asyncpg-style URLs for external PostgreSQL (#1225)
* fix(db): accept asyncpg-style URLs for external PostgreSQL

Fixes #1216. External PostgreSQL deployments (Cloud SQL, RDS, etc.)
configured with a SQLAlchemy-style URL like
`postgresql+asyncpg://user:pass@host/db?ssl=require` failed in two
places:

1. Five sync `create_engine(database_url)` call sites in migrations.py
   — psycopg2 doesn't understand the asyncpg dialect, and it expects
   `sslmode=require` rather than `ssl=require`.
2. `asyncpg.create_pool(self.db_url)` in memory_engine.py — asyncpg
   doesn't parse the `postgresql+asyncpg://` scheme directly.

Adds a single `to_libpq_url()` helper (urllib.parse-based, idempotent,
safe on passwords containing `+`) and applies it at:

- All five `create_engine()` sites in migrations.py (including the
  run_migrations advisory-lock connection)
- `asyncpg.create_pool()` in memory_engine.py
- The ad-hoc scheme rewrite in alembic/env.py (replaced by the helper)

Existing configs (`pg0`, plain `postgresql://`, `sslmode=require`,
`postgresql+psycopg2://`) are returned byte-identical — no behaviour
change for current users.

* test(db): pin current production URL shapes as regression guard
2026-04-24 10:41:50 +02:00
aliu-ronin cd1ab497c5 fix(stats): timeseries buckets should return tz-aware ISO (#1245)
* fix(stats): return tz-aware ISO from memories-timeseries

The `/stats/memories-timeseries` endpoint was serializing bucket
timestamps as naive ISO strings (e.g. `2026-04-18T00:00:00`). Browsers
parse naive date-time strings as local time per ECMA-262, so
`formatBucketLabel` in the control plane was shifting chart buckets by
the browser's timezone offset.

Use `datetime.now(timezone.utc)` so the bucket anchor is tz-aware, and
keep incoming `timestamptz` rows in UTC rather than stripping the
tzinfo. Serialized bucket times now end in `+00:00`, matching the
convention used by every other endpoint (`/memories/list`, etc.).

Adds a regression test that asserts every bucket `time` carries an
explicit UTC offset.

* fix(control-plane): parse bucket ISO as UTC when offset is missing

Defensive parse paired with the backend fix. Older API servers may
still return naive ISO strings for `/stats/memories-timeseries` buckets;
`new Date('2026-04-18T00:00:00')` would then be interpreted as local
time and shift the chart by the browser's timezone.

`parseBucketIso` appends a `Z` when no offset is present so the bucket
always anchors to UTC before `toLocaleString` converts it to the user's
locale.
2026-04-24 10:38:31 +02:00
Nicolò Boschi 6034e5383d release(litellm): v0.5.2 2026-04-24 10:29:53 +02:00
Nicolò Boschi cdc26daa2a release(claude-code): v0.4.0 2026-04-24 10:29:16 +02:00
Nicolò Boschi b67b688635 fix(claude-code): handle list-content tool_results in transcript parsing (#1226)
tool_result blocks can have content as a list of content blocks
(e.g. [{"type": "text", "text": "..."}]) instead of a plain string.
This happens with Agent subagent responses. Previously these were
silently dropped during retention, losing ~1-4% of tool results.

Extract text from list content blocks before applying the existing
string handling and truncation logic.
2026-04-24 10:28:10 +02:00
DK09876andClaude Opus 4.6 ac5181f565 fix(litellm): handle streaming responses in _store_conversation (#1239)
* fix(litellm): handle streaming responses in _store_conversation (#1221)

Streaming responses (CustomStreamWrapper) lack .choices, causing
AttributeError when _format_conversation_for_storage or
_store_conversation_sync tries to access response.choices. Guard
both the monkeypatch wrappers and the callback handler so they
gracefully skip storage for streaming responses.

Also syncs litellm docs with the current configure()/set_defaults()
API, fixes outdated model names, and corrects the litellm version
requirement in README.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat(litellm): add stream wrappers for proper streaming storage

Replace bandaid hasattr guard with proper stream wrappers that collect
chunks during iteration and store the complete conversation when the
stream is exhausted. Adds _LiteLLMStreamWrapper (sync) and
_LiteLLMAsyncStreamWrapper (async) following the same pattern as
the existing _StreamWrapper in wrappers.py.

Also refactors message formatting into _format_messages_for_storage
to share between the stream wrappers and _format_conversation_for_storage.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(litellm): add missing final_messages guard in completion/acompletion

The convenience wrappers completion() and acompletion() were missing
the `if final_messages:` guard before the streaming check, unlike
_wrapped_completion/_wrapped_acompletion which had it. Without this
guard, passing no messages would create a stream wrapper with None
messages, crashing in _format_messages_for_storage.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-24 10:00:38 +02:00
Ben 9f4b3b670f guides: add general agent memory guide batch (#1233) 2026-04-23 16:30:25 -04:00
Ben 42ed681440 blog: Your Agent Is Not Forgetful. It Was Never Given a Memory. (#1235)
* blog: Your Agent Is Not Forgetful. It Was Never Given a Memory.
2026-04-23 14:38:26 -04:00
Ben 06147ef2e9 fix: correct docker command in 10k stars blog post quickstart (#1237)
- Use correct image: ghcr.io/vectorize-io/hindsight:latest (not vectorize/hindsight)
- Correct ports: 8888 (API) and 9999 (Web UI) instead of 8000
- Add required OPENAI_API_KEY environment variable
- Add volume mount for persistent storage
- Add access URLs for API and UI
2026-04-23 12:01:35 -04:00
Nicolò Boschi 8eb6e69a75 feat(api,ui): document chunks API, reprocess, and enhanced document detail (#1236)
* feat(api,ui): document chunks API, reprocess endpoint, and enhanced document detail dialog

- Add GET /banks/{bank_id}/documents/{document_id}/chunks endpoint to list chunks with pagination
- Add POST /banks/{bank_id}/documents/{document_id}/reprocess endpoint to re-run retain pipeline
- Add document_id/chunk_id filters to GET /banks/{bank_id}/graph endpoint
- Add nodes_by_fact_type to get_document response (per-type memory counts, no extra queries)
- Replace document side panel with full-screen dialog (General, Content, Chunks tabs)
- General tab: InfoCard layout with memory composition bar and compact constellation view
- Chunks tab: collapsible rows with side-by-side text/memories split, expandable to full DataView
- Content tab: raw text display with inline edit
- Actions dropdown (reprocess, delete) matching mental model dialog pattern
- DataView compact mode: constellation-only with expand/compact toggle
- Regenerate OpenAPI spec and client SDKs

* fix(ci): add new document endpoints to CLI coverage skip list
2026-04-23 17:32:19 +02:00
Nicolò Boschi 8f6e0e5bec feat(api): add exclude_parents filter to list operations (#1230)
* feat(api): add exclude_parents filter to list operations endpoint

Batch retain operations create parent + child rows, cluttering the
operations list. Add an `exclude_parents` query parameter that filters
out parent operations (is_parent=true in result_metadata). The control
plane UI now passes this by default so users only see leaf operations.

* test: add unit test for exclude_parents filter

* fix: update Rust CLI and docs skill for new exclude_parents param
2026-04-23 15:24:13 +02:00
Nicolò Boschi 80982da577 fix(ops): expose processing/cancelled statuses through API and UI (#1231)
* fix(ops): expose processing/cancelled statuses through API and UI

The API was collapsing 'processing' into 'pending' before returning
operation status to clients. Cancel was deleting the operation row
instead of preserving it with a 'cancelled' status.

- Stop mapping processing→pending in list/get operation responses
- Add 'processing' to OperationStatusResponse Literal type
- Change cancel_operation to set status='cancelled' instead of DELETE
- Guard cancel to only accept pending operations (409 otherwise)
- Extend retry to accept both failed and cancelled operations
- Add _check_op_alive support for cancelled status
- Add DB migration for 'cancelled' in status check constraint
- Add processing/cancelled badges and filters in operations UI
- Add cancel/retry buttons in operation detail dialog
- Align stats card status colors and labels with operations table
- Regenerate OpenAPI spec and all client SDKs

* chore: regenerate docs skill openapi reference

* chore: regenerate clients and openapi spec (full sync)

* fix(cli): handle processing/cancelled status variants in Rust CLI
2026-04-23 15:06:46 +02:00
Nicolò Boschi 90674aef17 fix(mcp): remove delete_memory tool to close authorization-bypass gap (#1228)
MemoryEngine.delete_memory_unit never called validate_bank_write, so any
authenticated MCP client could delete memories in any bank regardless of
the configured OperationValidatorExtension policy (issue #1218).

No REST endpoint exposes single-memory deletion, and the CLI already
errors out on it. Drop the matching MCP tool and remove delete_memory_unit
from the public MemoryEngineInterface. The engine method stays so internal
observation-invalidation tests still cover the stale-observation sweep.

Also updates the control plane bank-config UI, MCP docs, and skill mirrors
to drop references to the tool.
2026-04-23 14:29:09 +02:00
1072 changed files with 91782 additions and 20797 deletions
+38 -2
View File
@@ -2,7 +2,7 @@
# Copy this file to .env and fill in your values
# LLM Configuration (Required)
# Supported providers: openai, groq, ollama, gemini, anthropic, lmstudio, vertexai, minimax, volcano
# Supported providers: openai, groq, ollama, gemini, anthropic, lmstudio, vertexai, minimax, deepseek, zai, volcano
HINDSIGHT_API_LLM_PROVIDER=openai
HINDSIGHT_API_LLM_API_KEY=your-api-key-here
HINDSIGHT_API_LLM_MODEL=gpt-4o-mini
@@ -25,6 +25,16 @@ HINDSIGHT_API_LLM_BASE_URL=https://api.openai.com/v1
# HINDSIGHT_API_LLM_API_KEY=your-minimax-api-key
# HINDSIGHT_API_LLM_MODEL=MiniMax-M2.7
# Example: DeepSeek configuration (https://api.deepseek.com)
# HINDSIGHT_API_LLM_PROVIDER=deepseek
# HINDSIGHT_API_LLM_API_KEY=your-deepseek-api-key
# HINDSIGHT_API_LLM_MODEL=deepseek-v4-flash # or deepseek-v4-pro / deepseek-chat / deepseek-reasoner
# Example: z.ai configuration (Zhipu GLM series, https://z.ai)
# HINDSIGHT_API_LLM_PROVIDER=zai
# HINDSIGHT_API_LLM_API_KEY=your-zai-api-key
# HINDSIGHT_API_LLM_MODEL=glm-4.5-flash # or glm-4.5-air for the paid tier
# Example: LM Studio local configuration (Qwen 2.5 32B recommended)
# HINDSIGHT_API_LLM_PROVIDER=lmstudio
# HINDSIGHT_API_LLM_API_KEY=lmstudio
@@ -44,6 +54,7 @@ HINDSIGHT_API_LOG_LEVEL=info
# Database (Optional - uses embedded pg0 by default)
# HINDSIGHT_API_DATABASE_URL=postgresql://user:pass@host:5432/db
# HINDSIGHT_API_READ_DATABASE_URL= # Optional read-replica URL. When set, recall queries (semantic, BM25, graph, temporal) flow through a separate pool against this URL, offloading the primary. Typically points to a read-only endpoint (CNPG's <cluster>-ro service or Aurora reader endpoint).
# HINDSIGHT_API_MIGRATION_DATABASE_URL= # Direct PostgreSQL URL for migrations (bypasses PgBouncer). Falls back to DATABASE_URL.
# HINDSIGHT_API_DATABASE_SCHEMA=public # PostgreSQL schema name (default: public)
@@ -54,12 +65,25 @@ HINDSIGHT_API_LOG_LEVEL=info
# HINDSIGHT_API_VECTOR_EXTENSION=pgvectorscale # Auto-detects pg_diskann on Azure
# Embeddings Configuration (Optional - uses local by default)
# Provider: "local" (default) or "tei" (HuggingFace Text Embeddings Inference)
# Provider: "local" (default), "tei", "openai", "cohere", "google", "openrouter", "litellm", or "litellm-sdk"
# HINDSIGHT_API_EMBEDDINGS_PROVIDER=local
# For local provider:
# HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL=BAAI/bge-small-en-v1.5
# Optional for China network / restricted HF access:
# HF_ENDPOINT=https://hf-mirror.com
# For TEI provider:
# HINDSIGHT_API_EMBEDDINGS_TEI_URL=http://localhost:8080
# For OpenAI-compatible embeddings:
# HINDSIGHT_API_EMBEDDINGS_OPENAI_API_KEY=sk-xxxx
# HINDSIGHT_API_EMBEDDINGS_OPENAI_MODEL=text-embedding-3-small
# HINDSIGHT_API_EMBEDDINGS_OPENAI_BASE_URL=https://api.openai.com/v1
#
# IMPORTANT: Embedding keys require provider-specific names:
# HINDSIGHT_API_EMBEDDINGS_{PROVIDER}_{PARAMETER}
# (for example, HINDSIGHT_API_EMBEDDINGS_OPENAI_MODEL).
#
# DeepSeek note: DeepSeek is supported for LLM calls, but not for embeddings.
# If using DeepSeek as LLM provider, keep embeddings on local/openai/cohere/google/etc.
# Reranker Configuration (Optional - uses local by default)
# Provider: "local" (default) or "tei" (HuggingFace Text Embeddings Inference)
@@ -83,3 +107,15 @@ HINDSIGHT_API_LOG_LEVEL=info
# Custom service name and environment (optional, defaults: hindsight-api, development)
# HINDSIGHT_API_OTEL_SERVICE_NAME=hindsight-production
# HINDSIGHT_API_OTEL_DEPLOYMENT_ENVIRONMENT=production
# -----------------------------------------------------------------------------
# Control Plane (Optional)
# -----------------------------------------------------------------------------
# Dataplane API URL - where the CP proxies requests to
# HINDSIGHT_CP_DATAPLANE_API_URL=http://localhost:8888
# Optional: Require a shared access key to view the Control Plane UI.
# When set, visitors see a login page and must enter the key before
# accessing the dashboard or any /api/* routes (except /api/health).
# HINDSIGHT_CP_ACCESS_KEY=your-shared-secret-key
+38 -12
View File
@@ -22,11 +22,13 @@ on:
- ""
- retain
- recall
- recall-with-observations
- consolidation
default: ""
locomo_conversations:
description: "LoComo conversation IDs (space-separated). Blank = curated set (conv-26 conv-30 conv-43)."
type: string
default: ""
locomo_max_conversations:
description: "LoComo max conversations (0 = skip, blank = all)"
type: number
default: 0
locomo_skip:
description: "Skip LoComo job"
type: boolean
@@ -81,7 +83,7 @@ jobs:
run: |
cd hindsight-dev && uv sync --frozen --all-extras --index-strategy unsafe-best-match
- name: Run perf tests
- name: Run perf-test
run: |
SUITE_ARG=""
if [ -n "${{ inputs.suite }}" ]; then
@@ -94,12 +96,23 @@ jobs:
- name: Upload perf results
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: perf-results-${{ github.sha }}
path: hindsight-dev/perf-results.json
retention-days: 90
# Publish enriched results (perf JSON + commit metadata) to the dashboard
# repo's gh-pages branch. The static site at
# https://vectorize-io.github.io/hindsight-continuous-performance-monitor/
# reads data/index.json + data/<run>.json and renders charts client-side.
- name: Publish to dashboard
if: github.event_name == 'schedule' || github.event_name == 'push' || github.event_name == 'workflow_dispatch'
env:
PERF_DASHBOARD_TOKEN: ${{ secrets.PERF_DASHBOARD_TOKEN }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: ./scripts/benchmarks/publish-perf-results.sh hindsight-dev/perf-results.json
locomo:
if: inputs.locomo_skip != true
runs-on: ubuntu-latest
@@ -110,7 +123,7 @@ jobs:
HINDSIGHT_API_JUDGE_LLM_PROVIDER: vertexai
HINDSIGHT_API_JUDGE_LLM_MODEL: google/gemini-2.5-flash-lite
HINDSIGHT_API_ANSWER_LLM_PROVIDER: vertexai
HINDSIGHT_API_ANSWER_LLM_MODEL: google/gemini-3.1-pro-preview
HINDSIGHT_API_ANSWER_LLM_MODEL: google/gemini-2.5-flash
steps:
- uses: actions/checkout@v6
with:
@@ -156,19 +169,32 @@ jobs:
cd hindsight-dev && uv sync --frozen --all-extras --index-strategy unsafe-best-match
- name: Run LoComo benchmark
# Curated 3-conversation subset (best/middle/worst by accuracy on the
# last successful full run): conv-26 (best), conv-30 (middle), conv-43
# (worst). Excludes conv-44, the bank with the largest unconsolidated
# set that has been pushing scheduled runs over the per-bank
# _wait_for_consolidation timeout. Override via workflow_dispatch with
# the locomo_conversations input.
run: |
MAX_CONV_ARG=""
if [ "${{ inputs.locomo_max_conversations }}" != "0" ] && [ -n "${{ inputs.locomo_max_conversations }}" ]; then
MAX_CONV_ARG="--max-conversations ${{ inputs.locomo_max_conversations }}"
CONVERSATIONS="${{ inputs.locomo_conversations }}"
if [ -z "$CONVERSATIONS" ]; then
CONVERSATIONS="conv-26 conv-30 conv-43"
fi
uv run python hindsight-dev/benchmarks/locomo/locomo_benchmark.py \
--wait-consolidation \
$MAX_CONV_ARG
--conversation $CONVERSATIONS
- name: Upload LoComo results
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: locomo-results-${{ github.sha }}
path: hindsight-dev/benchmarks/locomo/results/
retention-days: 90
- name: Publish LoComo to dashboard
if: success() && (github.event_name == 'schedule' || github.event_name == 'push' || github.event_name == 'workflow_dispatch')
env:
PERF_DASHBOARD_TOKEN: ${{ secrets.PERF_DASHBOARD_TOKEN }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: ./scripts/benchmarks/publish-locomo-results.sh hindsight-dev/benchmarks/locomo/results/benchmark_results.json
+18 -7
View File
@@ -81,17 +81,28 @@ jobs:
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
cache-dependency-path: package-lock.json
# Guard: fail fast if the integration's lockfile resolves any dep from a
# monorepo workspace (link=true) or a relative file path. The release
# runner has no pre-built workspace `dist/` so `npm run build` would
# later fail at tsc with "Cannot find module". See:
# https://github.com/vectorize-io/hindsight/issues/… (0.6.0 openclaw retry)
- name: Check integration lockfile
if: steps.type.outputs.type == 'typescript'
run: ./scripts/check-integration-lockfiles.sh
- name: Install dependencies
# Some integrations depend on workspace packages (hindsight-client,
# hindsight-all, hindsight-agent-sdk) via file: refs. Install from root
# so npm resolves them, then build the workspace deps before the integration.
- name: Install root workspace dependencies
if: steps.type.outputs.type == 'typescript'
run: npm ci
- name: Build workspace deps (hindsight-client, hindsight-all, hindsight-agent-sdk)
if: steps.type.outputs.type == 'typescript'
run: |
npm run build --workspace=hindsight-clients/typescript
npm run build --workspace=hindsight-all-npm
npm run build --workspace=hindsight-tools/hindsight-agent-sdk
- name: Install integration dependencies
if: steps.type.outputs.type == 'typescript'
working-directory: ./hindsight-integrations/${{ steps.info.outputs.integration }}
run: npm ci
@@ -106,7 +117,7 @@ jobs:
working-directory: ./hindsight-integrations/${{ steps.info.outputs.integration }}
run: |
set +e
OUTPUT=$(npm publish --access public 2>&1)
OUTPUT=$(npm publish --access public --provenance 2>&1)
EXIT_CODE=$?
echo "$OUTPUT"
if [ $EXIT_CODE -ne 0 ]; then
+65
View File
@@ -0,0 +1,65 @@
name: Release Tool
on:
push:
tags:
- 'tools/**'
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Extract tool info
id: info
run: |
# refs/tags/tools/self-driving-agents/v0.0.1 → tool=self-driving-agents, version=0.0.1
TAG="${GITHUB_REF#refs/tags/}"
TOOL=$(echo "$TAG" | cut -d'/' -f2)
VERSION=$(echo "$TAG" | cut -d'/' -f3 | sed 's/^v//')
echo "tool=$TOOL" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "Tool: $TOOL, Version: $VERSION"
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
cache-dependency-path: package-lock.json
# Tools live under hindsight-tools/ and may depend on workspace packages
# (e.g. @vectorize-io/hindsight-client). Install from root so npm resolves
# workspace deps, then build any required workspace packages first.
- name: Install root workspace dependencies
run: npm ci
- name: Build hindsight-client (workspace dep)
run: npm run build --workspace=hindsight-clients/typescript
- name: Build hindsight-agent-sdk (workspace dep)
run: npm run build --workspace=hindsight-tools/hindsight-agent-sdk
- name: Build tool
run: npm run build --workspace=hindsight-tools/${{ steps.info.outputs.tool }}
- name: Publish to npm
working-directory: ./hindsight-tools/${{ steps.info.outputs.tool }}
run: |
set +e
OUTPUT=$(npm publish --access public 2>&1)
EXIT_CODE=$?
echo "$OUTPUT"
if [ $EXIT_CODE -ne 0 ]; then
if echo "$OUTPUT" | grep -q "cannot publish over"; then
echo "Package version already published, skipping..."
exit 0
fi
exit $EXIT_CODE
fi
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+34
View File
@@ -314,6 +314,7 @@ jobs:
permissions:
contents: read
packages: write
id-token: write
strategy:
matrix:
include:
@@ -410,6 +411,7 @@ jobs:
# Build multi-platform and push to release tags
- name: Build and push release images
id: build
uses: docker/build-push-action@v7
with:
context: .
@@ -421,6 +423,31 @@ jobs:
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Install cosign
uses: sigstore/cosign-installer@v3
- name: Sign published images
env:
TAGS: ${{ steps.meta.outputs.tags }}
DIGEST: ${{ steps.build.outputs.digest }}
run: |
set -euo pipefail
refs=()
while IFS= read -r tag; do
[[ -z "${tag}" ]] && continue
refs+=("${tag}@${DIGEST}")
done <<< "${TAGS}"
cosign sign --yes "${refs[@]}"
- name: Verify signature on primary tag
env:
IMAGE: ghcr.io/${{ github.repository_owner }}/${{ matrix.image_name }}
DIGEST: ${{ steps.build.outputs.digest }}
run: |
cosign verify "${IMAGE}@${DIGEST}" \
--certificate-identity-regexp "^https://github\.com/${{ github.repository }}/\.github/workflows/release\.yml@.*" \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
release-helm-chart:
runs-on: ubuntu-latest
permissions:
@@ -497,6 +524,12 @@ jobs:
name: rust-cli-hindsight-linux-amd64
path: ./artifacts/rust-cli-linux
- name: Download Rust CLI (Linux ARM)
uses: actions/download-artifact@v8
with:
name: rust-cli-hindsight-linux-arm64
path: ./artifacts/rust-cli-linux-arm64
- name: Download Rust CLI (macOS Intel)
uses: actions/download-artifact@v8
with:
@@ -533,6 +566,7 @@ jobs:
cp artifacts/control-plane/*.tgz release-assets/ || true
# Rust CLI binaries
cp artifacts/rust-cli-linux/hindsight-linux-amd64 release-assets/ || true
cp artifacts/rust-cli-linux-arm64/hindsight-linux-arm64 release-assets/ || true
cp artifacts/rust-cli-darwin-amd64/hindsight-darwin-amd64 release-assets/ || true
cp artifacts/rust-cli-darwin-arm64/hindsight-darwin-arm64 release-assets/ || true
# Helm chart
+71
View File
@@ -0,0 +1,71 @@
name: Sign published images
on:
workflow_dispatch:
inputs:
version:
description: 'Version to sign (without leading v, e.g. 0.6.0)'
required: true
type: string
default: '0.6.0'
permissions:
contents: read
packages: write
id-token: write
jobs:
sign:
name: Sign ${{ matrix.image }}:${{ inputs.version }}${{ matrix.suffix }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- { image: hindsight-api, suffix: '' }
- { image: hindsight-api, suffix: '-slim' }
- { image: hindsight-control-plane, suffix: '' }
- { image: hindsight, suffix: '' }
- { image: hindsight, suffix: '-slim' }
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Install cosign
uses: sigstore/cosign-installer@v3
- name: Resolve image digest
id: resolve
env:
IMAGE: ghcr.io/${{ github.repository_owner }}/${{ matrix.image }}
TAG: ${{ inputs.version }}${{ matrix.suffix }}
run: |
set -euo pipefail
DIGEST=$(docker buildx imagetools inspect "${IMAGE}:${TAG}" --format '{{json .Manifest.Digest}}' | tr -d '"')
if [[ -z "${DIGEST}" || "${DIGEST}" != sha256:* ]]; then
echo "Failed to resolve digest for ${IMAGE}:${TAG} (got: ${DIGEST})" >&2
exit 1
fi
echo "Resolved ${IMAGE}:${TAG} -> ${DIGEST}"
echo "ref=${IMAGE}@${DIGEST}" >> "$GITHUB_OUTPUT"
- name: Sign image
env:
REF: ${{ steps.resolve.outputs.ref }}
run: cosign sign --yes "${REF}"
- name: Verify signature
env:
REF: ${{ steps.resolve.outputs.ref }}
run: |
cosign verify "${REF}" \
--certificate-identity-regexp "^https://github\.com/${{ github.repository }}/\.github/workflows/sign-images\.yml@.*" \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
+1001 -71
View File
File diff suppressed because it is too large Load Diff
+45 -7
View File
@@ -123,12 +123,17 @@ Key tables: `banks`, `memory_units`, `documents`, `entities`, `entity_links`
### Adding Database Migrations
Hindsight runs the same Alembic tree against PostgreSQL and Oracle 23ai. Each
migration file dispatches through `run_for_dialect`, which calls either
`_pg_upgrade` or `_oracle_upgrade` based on the live connection. A pytest lint
(`tests/test_migration_shape.py`) fails CI if a migration omits the dispatcher.
1. **Create a new migration file** in `hindsight-api-slim/hindsight_api/alembic/versions/`:
- File name format: `<revision_id>_<description>.py` (e.g., `f1a2b3c4d5e6_add_new_index.py`)
- Use a unique hex revision ID (12 chars)
- Set `down_revision` to the previous migration's revision ID
2. **Migration template**:
2. **Migration template** (the `script.py.mako` template scaffolds this; fill in the bodies):
```python
"""Description of the migration
@@ -139,25 +144,58 @@ Key tables: `banks`, `memory_units`, `documents`, `entities`, `entity_links`
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "f1a2b3c4d5e6"
down_revision: str | Sequence[str] | None = "<previous_revision_id>"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_schema_prefix() -> str:
"""Get schema prefix for table names (required for multi-tenant support)."""
def _pg_schema_prefix() -> str:
"""Schema-qualifier for raw SQL on PG (multi-tenant search_path)."""
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def upgrade() -> None:
schema = _get_schema_prefix()
def _pg_upgrade() -> None:
schema = _pg_schema_prefix()
op.execute(f"CREATE INDEX ... ON {schema}table_name(...)")
def downgrade() -> None:
schema = _get_schema_prefix()
def _pg_downgrade() -> None:
schema = _pg_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}index_name")
def _oracle_upgrade() -> None:
# Oracle 23ai equivalent. Use op.get_bind().exec_driver_sql for forms
# that Alembic core does not model (vector/text indexes, partitions).
op.execute("CREATE INDEX ... ON table_name(...)")
def _oracle_downgrade() -> None:
op.execute("DROP INDEX IF EXISTS index_name")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade, oracle=_oracle_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade, oracle=_oracle_downgrade)
```
**Dialect-only migrations.** If a change genuinely doesn't apply to one
dialect (e.g. enabling `pg_trgm` is PG-only), omit the unused slot:
```python
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade) # oracle slot intentionally absent → no-op
```
Make the asymmetry deliberate. Don't leave an Oracle slot empty just because
you didn't think about it — copy-pasting a PG migration without the Oracle
half is exactly how schemas drift.
3. **Run migrations locally**:
```bash
# Set database URL and run migrations for the base schema plus all tenants
+3 -1
View File
@@ -30,7 +30,7 @@ It eliminates the shortcomings of alternative techniques such as RAG and knowled
Hindsight is the most accurate agent memory system ever tested according to benchmark performance. It has achieved state-of-the-art performance on the LongMemEval benchmark, widely used to assess memory system performance across a variety of conversational AI scenarios. The current reported performance of Hindsight and other agent memory solutions as of January 2026 is shown here:
![Overview](./hindsight-docs/static/img/hindsight-bench.jpg)
![Overview](./hindsight-docs/static/img/hindsight-benchmarks.png)
The benchmark performance data for Hindsight has been independently reproduced by research collaborators at the Virginia Tech [Sanghani Center for Artificial Intelligence and Data Analytics](https://sanghani.cs.vt.edu/) and The Washington Post. Other scores are self-reported by software vendors.
@@ -84,6 +84,8 @@ cd docker/docker-compose
docker compose up
```
> Oracle AI Database is also supported for enterprise deployments with full feature parity. See the [storage documentation](https://hindsight.vectorize.io/developer/storage) for details.
>API: http://localhost:8888
>UI: http://localhost:9999
Generated
+33 -1
View File
@@ -42,6 +42,16 @@
},
"workspace": {
"members": {
"hindsight-all-npm": {
"packageJson": {
"dependencies": [
"npm:@types/node@22",
"npm:tsup@^8.5.1",
"npm:typescript@^5.7.0",
"npm:vitest@^4.1.2"
]
}
},
"hindsight-clients/typescript": {
"packageJson": {
"dependencies": [
@@ -58,6 +68,7 @@
"hindsight-control-plane": {
"packageJson": {
"dependencies": [
"npm:@chenglou/pretext@^0.0.3",
"npm:@eslint/eslintrc@^3.3.3",
"npm:@eslint/js@^9.39.2",
"npm:@radix-ui/react-alert-dialog@^1.1.15",
@@ -91,11 +102,12 @@
"npm:eslint@^9.39.1",
"npm:[email protected]",
"npm:next-themes@~0.4.6",
"npm:next@^16.1.6",
"npm:next@^16.1.7",
"npm:postcss@^8.5.6",
"npm:prettier@^3.7.4",
"npm:react-chrono@^2.9.1",
"npm:react-dom@^19.2.0",
"npm:react-is@^19.2.4",
"npm:react-markdown@^10.1.0",
"npm:react18-json-view@~0.2.9",
"npm:react@^19.2.0",
@@ -133,6 +145,26 @@
"npm:typescript@~5.6.2"
]
}
},
"hindsight-tools/hindsight-agent-sdk": {
"packageJson": {
"dependencies": [
"npm:@vectorize-io/hindsight-client@~0.5.6",
"npm:typescript@^5.4.0",
"npm:vitest@^4.1.2"
]
}
},
"hindsight-tools/self-driving-agents": {
"packageJson": {
"dependencies": [
"npm:@clack/prompts@^1.2.0",
"npm:@vectorize-io/hindsight-client@~0.5.6",
"npm:picocolors@^1.1.0",
"npm:typescript@^5.4.0",
"npm:vitest@^4.1.2"
]
}
}
}
}
@@ -0,0 +1,90 @@
name: hindsight
# Docker Compose file for Hindsight with AlloyDB Omni and ScaNN
# Uses Google's free AlloyDB Omni container image: https://hub.docker.com/r/google/alloydbomni
#
# Usage:
# docker compose -f docker/docker-compose/alloydb/docker-compose.yaml up -d
#
# Make sure to set the required environment variables before running:
# - HINDSIGHT_DB_PASSWORD: password for the AlloyDB Omni/PostgreSQL user
# - Configure LLM provider variables as needed (see the hindsight service below)
#
# Optional environment variables with defaults:
# - HINDSIGHT_VERSION: Hindsight application version (default: latest)
# - HINDSIGHT_DB_VERSION: AlloyDB Omni image tag (default: 17)
# - HINDSIGHT_DB_USER: database user (default: hindsight_user)
# - HINDSIGHT_DB_NAME: database name (default: hindsight_db)
services:
db:
image: google/alloydbomni:${HINDSIGHT_DB_VERSION:-17}
container_name: hindsight-db-alloydb
restart: always
ports:
- "5438:5432"
environment:
POSTGRES_USER: ${HINDSIGHT_DB_USER:-hindsight_user}
POSTGRES_PASSWORD: ${HINDSIGHT_DB_PASSWORD:-hindsight_password}
POSTGRES_DB: ${HINDSIGHT_DB_NAME:-hindsight_db}
volumes:
- alloydb_data:/var/lib/postgresql/data
networks:
- hindsight-net
alloydb-init:
image: google/alloydbomni:${HINDSIGHT_DB_VERSION:-17}
depends_on:
- db
environment:
- PGPASSWORD=${HINDSIGHT_DB_PASSWORD:-hindsight_password}
command:
- bash
- -c
- |
echo 'Waiting for AlloyDB Omni to be ready...'
until pg_isready -h hindsight-db-alloydb -p 5432 -U ${HINDSIGHT_DB_USER:-hindsight_user}; do
echo 'AlloyDB Omni is unavailable - sleeping'
sleep 2
done
echo 'AlloyDB Omni is ready - creating ${HINDSIGHT_DB_NAME:-hindsight_db} database'
psql -h hindsight-db-alloydb -p 5432 -U ${HINDSIGHT_DB_USER:-hindsight_user} -c 'CREATE DATABASE ${HINDSIGHT_DB_NAME:-hindsight_db};' 2>/dev/null || echo 'Database already exists'
echo 'Creating vector and alloydb_scann extensions'
psql -h hindsight-db-alloydb -p 5432 -U ${HINDSIGHT_DB_USER:-hindsight_user} -d ${HINDSIGHT_DB_NAME:-hindsight_db} -c 'CREATE EXTENSION IF NOT EXISTS vector;'
psql -h hindsight-db-alloydb -p 5432 -U ${HINDSIGHT_DB_USER:-hindsight_user} -d ${HINDSIGHT_DB_NAME:-hindsight_db} -c 'CREATE EXTENSION IF NOT EXISTS alloydb_scann CASCADE;'
echo 'Database and extensions created successfully'
restart: "no"
networks:
- hindsight-net
hindsight:
image: ghcr.io/vectorize-io/hindsight:${HINDSIGHT_VERSION:-latest}
container_name: hindsight-app
ports:
- "8888:8888"
- "9999:9999"
environment:
# LLM Configuration
HINDSIGHT_API_LLM_PROVIDER: ${HINDSIGHT_API_LLM_PROVIDER:-openai}
HINDSIGHT_API_LLM_API_KEY: ${OPENAI_API_KEY:-your-api-key}
# Database Configuration
HINDSIGHT_API_DATABASE_URL: postgresql://${HINDSIGHT_DB_USER:-hindsight_user}:${HINDSIGHT_DB_PASSWORD:-hindsight_password}@db:5432/${HINDSIGHT_DB_NAME:-hindsight_db}
# Vector and Text Search Extensions
HINDSIGHT_API_VECTOR_EXTENSION: scann
HINDSIGHT_API_TEXT_SEARCH_EXTENSION: native
depends_on:
db:
condition: service_started
alloydb-init:
condition: service_completed_successfully
networks:
- hindsight-net
networks:
hindsight-net:
driver: bridge
volumes:
alloydb_data:
@@ -0,0 +1,34 @@
# Example: custom Hindsight image with non-default local models baked in.
#
# Use this pattern in production when you run a non-default embedder or
# reranker. Baking models into the image removes the runtime dependency on
# HuggingFace and lets the container registry handle caching per node, so
# you don't need a model-cache PVC.
#
# Built on top of the slim image so only the deps and models you actually
# use end up in the final image.
FROM ghcr.io/vectorize-io/hindsight:latest-slim
# Install the local-ml deps required to load sentence-transformers /
# cross-encoder models at runtime. Pinned ranges mirror hindsight-api-slim's
# `local-ml` extra in hindsight-api-slim/pyproject.toml. Use `uv pip
# install` against the image's venv explicitly: the slim image's venv was
# created by `uv sync` and does not ship its own `pip`, so a bare
# `pip install` would fall back to user site-packages and not be visible
# to the runtime python.
RUN uv pip install --python /app/api/.venv/bin/python --no-cache \
'sentence-transformers>=3.3.0' \
'transformers>=4.53.0' \
'torch>=2.6.0'
# Pre-download the models you want to use. Replace these with your own.
# The defaults bundled in the full image are BAAI/bge-small-en-v1.5 and
# cross-encoder/ms-marco-MiniLM-L-6-v2; here we pick multilingual variants
# as a concrete non-default example.
ARG EMBEDDER=sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
ARG RERANKER=cross-encoder/mmarco-mMiniLMv2-L12-H384-v1
ENV HF_HUB_DOWNLOAD_TIMEOUT=600
RUN python -c "\
from sentence_transformers import SentenceTransformer, CrossEncoder; \
SentenceTransformer('${EMBEDDER}'); \
CrossEncoder('${RERANKER}')"
@@ -0,0 +1,81 @@
# Hindsight with Custom Local Models
Example Docker Compose setup that builds a Hindsight image with **non-default
local embedder and reranker models baked in at build time**.
This is the recommended pattern for production when you use a non-default
local model: the container registry caches model layers per node, pod
startup is deterministic, and you don't need a model-cache PVC (or any
runtime dependency on HuggingFace).
## When to use this
- You override `HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL` or
`HINDSIGHT_API_RERANKER_LOCAL_MODEL` to a non-default model.
- You want pod startup to be deterministic and offline-capable.
- You'd otherwise reach for a Helm `modelCache` PVC just to avoid
re-downloading models.
If you're using the **default** local models, the published full image
(`ghcr.io/vectorize-io/hindsight:latest`) already bakes them in — you don't
need this example.
If you're using **external** providers (TEI, OpenAI, Cohere, ...) for
embeddings and reranking, use the slim image directly — no models are
needed in the image.
## Quick start
```bash
export OPENAI_API_KEY=sk-xxx
docker compose -f docker/docker-compose/custom-models/docker-compose.yaml up --build
```
- API: http://localhost:8888
- Control Plane: http://localhost:9999
## Using your own models
Override the build args to bake different models:
```bash
docker compose -f docker/docker-compose/custom-models/docker-compose.yaml build \
--build-arg EMBEDDER=your-org/your-embedder \
--build-arg RERANKER=your-org/your-reranker
```
Then update the matching `HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL` and
`HINDSIGHT_API_RERANKER_LOCAL_MODEL` values in `docker-compose.yaml` so the
runtime points at the same model IDs.
## Verifying the models are baked in
`docker-compose.yaml` sets `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1`
so that any attempt to download a model at runtime fails loudly instead of
silently re-downloading. If the container starts and serves recall queries
with these set, the models are correctly baked in.
You can also inspect the image directly:
```bash
docker run --rm --entrypoint sh hindsight-custom-models-hindsight \
-c 'ls ~/.cache/huggingface/hub/'
```
## Why not a model-cache PVC?
The Helm chart exposes an optional `api.persistence.modelCache` PVC for
caching downloaded models across pod restarts. Compared to baking models
into the image:
- A PVC adds storage cost — one PVC per worker replica with
`volumeClaimTemplates`.
- `ReadWriteOnce` (the default) pins pods to a node.
- The PVC needs lifecycle management on `helm uninstall` / `helm upgrade`
— without `helm.sh/resource-policy: keep` it is deleted on uninstall;
with it, storage keeps billing forever until manually cleaned up.
- Pod startup still depends on HuggingFace being reachable on first run.
Image layers, by contrast, are pulled once per node and cached for free by
the container runtime, with no orphaned-storage cleanup story.
@@ -0,0 +1,44 @@
name: hindsight-custom-models
# Example: run a custom Hindsight image with non-default local models baked
# in at build time, so pod startup does not depend on HuggingFace at runtime.
#
# Quick start:
# export OPENAI_API_KEY=sk-xxx
# docker compose -f docker/docker-compose/custom-models/docker-compose.yaml up --build
#
# Required environment variables:
# - OPENAI_API_KEY (or configure another LLM provider via HINDSIGHT_API_LLM_*)
services:
hindsight:
build:
context: .
dockerfile: Dockerfile
# Override at build time to bake different models:
# docker compose build --build-arg EMBEDDER=your-org/your-embedder
args:
EMBEDDER: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
RERANKER: cross-encoder/mmarco-mMiniLMv2-L12-H384-v1
container_name: hindsight-custom-models
ports:
- "8888:8888"
- "9999:9999"
environment:
HINDSIGHT_API_LLM_PROVIDER: ${HINDSIGHT_API_LLM_PROVIDER:-openai}
HINDSIGHT_API_LLM_API_KEY: ${OPENAI_API_KEY:-your-api-key}
# Point Hindsight at the models baked into the image above.
HINDSIGHT_API_EMBEDDINGS_PROVIDER: local
HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
HINDSIGHT_API_RERANKER_PROVIDER: local
HINDSIGHT_API_RERANKER_LOCAL_MODEL: cross-encoder/mmarco-mMiniLMv2-L12-H384-v1
# Fail fast if a model is missing from the image instead of silently
# falling back to a HuggingFace download at runtime.
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
volumes:
- pg_data:/home/hindsight/.pg0
volumes:
pg_data:
@@ -51,6 +51,8 @@ services:
# Control Plane config
HINDSIGHT_CP_DATAPLANE_API_URL: http://localhost:8888
# Optional: Require a shared access key for Control Plane UI access
# HINDSIGHT_CP_ACCESS_KEY: your-secret-key
volumes:
# Persist embedded pg0 database
- hindsight_data:/app/data
+8
View File
@@ -172,6 +172,10 @@ USER hindsight
# "Permission denied" error when mounting a fresh root-owned volume.
RUN mkdir -p /home/hindsight/.pg0
# Make /home/hindsight traversable when running with --user UID:GID overrides
# (default 0700 blocks traversal by non-owner UIDs needed for bind-mount ownership matching)
RUN chmod 755 /home/hindsight
ENV PATH="/app/api/.venv/bin:${PATH}"
# Pre-download tiktoken encoding (ALWAYS - required for token counting even in air-gapped envs)
@@ -328,6 +332,10 @@ USER hindsight
# "Permission denied" error when mounting a fresh root-owned volume.
RUN mkdir -p /home/hindsight/.pg0
# Make /home/hindsight traversable when running with --user UID:GID overrides
# (default 0700 blocks traversal by non-owner UIDs needed for bind-mount ownership matching)
RUN chmod 755 /home/hindsight
ENV PATH="/app/api/.venv/bin:${PATH}"
# Pre-download tiktoken encoding (ALWAYS - required for token counting even in air-gapped envs)
+2 -2
View File
@@ -2,8 +2,8 @@ apiVersion: v2
name: hindsight
description: Hindsight helm chart
type: application
version: 0.5.4
appVersion: "0.5.4"
version: 0.6.2
appVersion: "0.6.2"
keywords:
- ai
- memory
+10 -1
View File
@@ -70,6 +70,12 @@ api:
# Persistent volume for local model cache (reranker, embeddings)
# Models are downloaded to /home/hindsight/.cache on first use.
# Without persistence, models are re-downloaded on every pod restart.
#
# For production, prefer baking models into a custom image instead of
# enabling this PVC: image layers are pulled once per node and cached
# for free, while a PVC adds storage cost, pins pods to a node
# (ReadWriteOnce), and needs lifecycle management on uninstall/upgrade.
# See docs: developer/installation#bundling-custom-models-in-a-custom-image
persistence:
modelCache:
enabled: false
@@ -168,7 +174,10 @@ worker:
# affinity: {}
# Persistent volume for local model cache (reranker, embeddings)
# Uses volumeClaimTemplates since worker is a StatefulSet.
# Uses volumeClaimTemplates since worker is a StatefulSet — one PVC per
# replica. For production, prefer baking models into a custom image; see
# api.persistence.modelCache above and docs:
# developer/installation#bundling-custom-models-in-a-custom-image
persistence:
modelCache:
enabled: false
+10 -10
View File
@@ -18,17 +18,17 @@ npm install @vectorize-io/hindsight-all @vectorize-io/hindsight-client
## Example
```ts
import { HindsightServer, consoleLogger } from '@vectorize-io/hindsight-all';
import { HindsightClient } from '@vectorize-io/hindsight-client';
import { HindsightServer, consoleLogger } from "@vectorize-io/hindsight-all";
import { HindsightClient } from "@vectorize-io/hindsight-client";
const server = new HindsightServer({
profile: 'my-app',
profile: "my-app",
port: 9077,
env: {
HINDSIGHT_API_LLM_PROVIDER: 'anthropic',
HINDSIGHT_API_LLM_PROVIDER: "anthropic",
HINDSIGHT_API_LLM_API_KEY: process.env.ANTHROPIC_API_KEY,
HINDSIGHT_API_LLM_MODEL: 'claude-sonnet-4-20250514',
HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT: '0',
HINDSIGHT_API_LLM_MODEL: "claude-sonnet-4-20250514",
HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT: "0",
},
logger: consoleLogger,
});
@@ -37,11 +37,11 @@ await server.start();
const client = new HindsightClient({ baseUrl: server.getBaseUrl() });
await client.retain('user-123', 'User prefers dark mode and concise answers.', {
documentId: 'pref-2026-04-01',
await client.retain("user-123", "User prefers dark mode and concise answers.", {
documentId: "pref-2026-04-01",
});
const recall = await client.recall('user-123', 'what are the user preferences?');
const recall = await client.recall("user-123", "what are the user preferences?");
console.log(recall.results);
await server.stop();
@@ -62,7 +62,7 @@ If you're hacking on the Python `hindsight-embed` package in the same monorepo,
```ts
new HindsightServer({
embedPackagePath: '/path/to/hindsight-embed',
embedPackagePath: "/path/to/hindsight-embed",
// ...
});
```
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@vectorize-io/hindsight-all",
"version": "0.5.4",
"version": "0.6.2",
"description": "Node.js programmatic lifecycle manager for Hindsight — embeds a local hindsight daemon in a Node application. Pair with @vectorize-io/hindsight-client for memory operations.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
+24 -20
View File
@@ -1,32 +1,36 @@
import { describe, it, expect } from 'vitest';
import { getEmbedCommand } from './command.js';
import { describe, it, expect } from "vitest";
import { getEmbedCommand } from "./command.js";
describe('getEmbedCommand', () => {
it('defaults to uvx hindsight-embed@latest', () => {
expect(getEmbedCommand()).toEqual(['uvx', 'hindsight-embed@latest']);
describe("getEmbedCommand", () => {
it("defaults to uvx hindsight-embed@latest", () => {
expect(getEmbedCommand()).toEqual(["uvx", "hindsight-embed@latest"]);
});
it('honours an explicit version', () => {
expect(getEmbedCommand({ embedVersion: '0.5.0' })).toEqual(['uvx', '[email protected]']);
it("honours an explicit version", () => {
expect(getEmbedCommand({ embedVersion: "0.5.0" })).toEqual(["uvx", "[email protected]"]);
});
it('treats an empty version as latest', () => {
expect(getEmbedCommand({ embedVersion: '' })).toEqual(['uvx', 'hindsight-embed@latest']);
it("treats an empty version as latest", () => {
expect(getEmbedCommand({ embedVersion: "" })).toEqual(["uvx", "hindsight-embed@latest"]);
});
it('uses uv run --directory when a local path is given', () => {
expect(getEmbedCommand({ embedPackagePath: '/abs/path' })).toEqual([
'uv',
'run',
'--directory',
'/abs/path',
'hindsight-embed',
it("uses uv run --directory when a local path is given", () => {
expect(getEmbedCommand({ embedPackagePath: "/abs/path" })).toEqual([
"uv",
"run",
"--directory",
"/abs/path",
"hindsight-embed",
]);
});
it('local path takes precedence over version', () => {
expect(
getEmbedCommand({ embedPackagePath: '/abs/path', embedVersion: '0.5.0' }),
).toEqual(['uv', 'run', '--directory', '/abs/path', 'hindsight-embed']);
it("local path takes precedence over version", () => {
expect(getEmbedCommand({ embedPackagePath: "/abs/path", embedVersion: "0.5.0" })).toEqual([
"uv",
"run",
"--directory",
"/abs/path",
"hindsight-embed",
]);
});
});
+3 -3
View File
@@ -18,8 +18,8 @@ export interface EmbedCommandOptions {
export function getEmbedCommand(opts: EmbedCommandOptions = {}): string[] {
if (opts.embedPackagePath) {
return ['uv', 'run', '--directory', opts.embedPackagePath, 'hindsight-embed'];
return ["uv", "run", "--directory", opts.embedPackagePath, "hindsight-embed"];
}
const version = opts.embedVersion && opts.embedVersion.length > 0 ? opts.embedVersion : 'latest';
return ['uvx', `hindsight-embed@${version}`];
const version = opts.embedVersion && opts.embedVersion.length > 0 ? opts.embedVersion : "latest";
return ["uvx", `hindsight-embed@${version}`];
}
+6 -6
View File
@@ -1,7 +1,7 @@
export { HindsightServer } from './server.js';
export { getEmbedCommand } from './command.js';
export { silentLogger, consoleLogger } from './logger.js';
export { HindsightServer } from "./server.js";
export { getEmbedCommand } from "./command.js";
export { silentLogger, consoleLogger } from "./logger.js";
export type { Logger } from './logger.js';
export type { EmbedCommandOptions } from './command.js';
export type { HindsightServerOptions } from './types.js';
export type { Logger } from "./logger.js";
export type { EmbedCommandOptions } from "./command.js";
export type { HindsightServerOptions } from "./types.js";
+15 -15
View File
@@ -1,32 +1,32 @@
import { describe, it, expect } from 'vitest';
import { HindsightServer } from './server.js';
import { describe, it, expect } from "vitest";
import { HindsightServer } from "./server.js";
describe('HindsightServer construction', () => {
it('defaults base URL to http://127.0.0.1:8888', () => {
describe("HindsightServer construction", () => {
it("defaults base URL to http://127.0.0.1:8888", () => {
const server = new HindsightServer();
expect(server.getBaseUrl()).toBe('http://127.0.0.1:8888');
expect(server.getProfile()).toBe('default');
expect(server.getBaseUrl()).toBe("http://127.0.0.1:8888");
expect(server.getProfile()).toBe("default");
});
it('honours custom profile, port, and host', () => {
const server = new HindsightServer({ profile: 'app', port: 9077, host: '0.0.0.0' });
expect(server.getProfile()).toBe('app');
expect(server.getBaseUrl()).toBe('http://0.0.0.0:9077');
it("honours custom profile, port, and host", () => {
const server = new HindsightServer({ profile: "app", port: 9077, host: "0.0.0.0" });
expect(server.getProfile()).toBe("app");
expect(server.getBaseUrl()).toBe("http://0.0.0.0:9077");
});
it('accepts open env pass-through without complaining about unknown keys', () => {
it("accepts open env pass-through without complaining about unknown keys", () => {
const server = new HindsightServer({
env: {
HINDSIGHT_API_LLM_PROVIDER: 'openai',
HINDSIGHT_API_LLM_MODEL: 'gpt-4o-mini',
HINDSIGHT_API_LLM_PROVIDER: "openai",
HINDSIGHT_API_LLM_MODEL: "gpt-4o-mini",
// A field that does not exist today — should still be accepted
HINDSIGHT_FUTURE_FLAG: 'enabled',
HINDSIGHT_FUTURE_FLAG: "enabled",
},
});
expect(server).toBeInstanceOf(HindsightServer);
});
it('exposes checkHealth that returns false when no daemon is running', async () => {
it("exposes checkHealth that returns false when no daemon is running", async () => {
// Random high port that nothing is listening on.
const server = new HindsightServer({ port: 1, readyTimeoutMs: 100 });
const healthy = await server.checkHealth();
+43 -43
View File
@@ -1,12 +1,12 @@
import { spawn } from 'child_process';
import { getEmbedCommand } from './command.js';
import { silentLogger } from './logger.js';
import type { Logger } from './logger.js';
import type { HindsightServerOptions } from './types.js';
import { spawn } from "child_process";
import { getEmbedCommand } from "./command.js";
import { silentLogger } from "./logger.js";
import type { Logger } from "./logger.js";
import type { HindsightServerOptions } from "./types.js";
const DEFAULT_PORT = 8888;
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PROFILE = 'default';
const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_PROFILE = "default";
const DEFAULT_READY_TIMEOUT_MS = 30_000;
const DEFAULT_READY_POLL_INTERVAL_MS = 1_000;
@@ -61,7 +61,7 @@ export class HindsightServer {
this.userEnv = opts.env ?? {};
this.extraProfileCreateArgs = opts.extraProfileCreateArgs ?? [];
this.extraDaemonStartArgs = opts.extraDaemonStartArgs ?? [];
this.platformCpuWorkaround = opts.platformCpuWorkaround ?? (process.platform === 'darwin');
this.platformCpuWorkaround = opts.platformCpuWorkaround ?? process.platform === "darwin";
this.readyTimeoutMs = opts.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
this.readyPollIntervalMs = opts.readyPollIntervalMs ?? DEFAULT_READY_POLL_INTERVAL_MS;
this.logger = opts.logger ?? silentLogger;
@@ -100,22 +100,22 @@ export class HindsightServer {
embedVersion: this.embedVersion,
embedPackagePath: this.embedPackagePath,
});
const args = [...baseArgs, 'daemon', '--profile', this.profile, 'stop'];
const args = [...baseArgs, "daemon", "--profile", this.profile, "stop"];
const child = spawn(cmd, args, { stdio: 'pipe' });
this.pipeOutput(child, 'daemon.stop');
const child = spawn(cmd, args, { stdio: "pipe" });
this.pipeOutput(child, "daemon.stop");
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
this.logger.warn(`[hindsight] daemon stop timed out after 5s`);
resolve();
}, 5_000);
child.on('exit', () => {
child.on("exit", () => {
clearTimeout(timeout);
this.logger.info(`[hindsight] daemon stopped`);
resolve();
});
child.on('error', (err) => {
child.on("error", (err) => {
clearTimeout(timeout);
this.logger.warn(`[hindsight] error stopping daemon: ${err.message}`);
resolve();
@@ -147,9 +147,9 @@ export class HindsightServer {
private buildEnv(): NodeJS.ProcessEnv {
const merged: NodeJS.ProcessEnv = { ...process.env };
if (this.platformCpuWorkaround && process.platform === 'darwin') {
merged['HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU'] = '1';
merged['HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU'] = '1';
if (this.platformCpuWorkaround && process.platform === "darwin") {
merged["HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU"] = "1";
merged["HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU"] = "1";
}
for (const [key, value] of Object.entries(this.userEnv)) {
@@ -175,11 +175,11 @@ export class HindsightServer {
});
const createArgs = [
...baseArgs,
'profile',
'create',
"profile",
"create",
this.profile,
'--merge',
'--port',
"--merge",
"--port",
String(this.port),
];
@@ -189,12 +189,12 @@ export class HindsightServer {
// host state into profile config.
const envForProfile = this.collectProfileEnv(env);
for (const [key, value] of Object.entries(envForProfile)) {
createArgs.push('--env', `${key}=${value}`);
createArgs.push("--env", `${key}=${value}`);
}
createArgs.push(...this.extraProfileCreateArgs);
await this.runCommand(cmd, createArgs, env, 'profile.create');
await this.runCommand(cmd, createArgs, env, "profile.create");
}
/** Collect only the env vars that should be written into the profile file. */
@@ -209,10 +209,10 @@ export class HindsightServer {
}
// 2. CPU workaround — only if auto-applied and not already overridden.
if (this.platformCpuWorkaround && process.platform === 'darwin') {
if (this.platformCpuWorkaround && process.platform === "darwin") {
const cpuKeys = [
'HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU',
'HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU',
"HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU",
"HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU",
];
for (const key of cpuKeys) {
if (!(key in out) && env[key] !== undefined) {
@@ -231,14 +231,14 @@ export class HindsightServer {
});
const args = [
...baseArgs,
'daemon',
'--profile',
"daemon",
"--profile",
this.profile,
'start',
"start",
...this.extraDaemonStartArgs,
];
await this.runCommand(cmd, args, env, 'daemon.start');
await this.runCommand(cmd, args, env, "daemon.start");
}
/**
@@ -249,34 +249,34 @@ export class HindsightServer {
cmd: string,
args: string[],
env: NodeJS.ProcessEnv,
label: string,
label: string
): Promise<void> {
const child = spawn(cmd, args, { stdio: 'pipe', env });
let output = '';
child.stdout?.on('data', (data: Buffer) => {
const child = spawn(cmd, args, { stdio: "pipe", env });
let output = "";
child.stdout?.on("data", (data: Buffer) => {
const text = data.toString();
output += text;
for (const line of text.trimEnd().split('\n')) {
for (const line of text.trimEnd().split("\n")) {
if (line) this.logger.info(`[hindsight:${label}] ${line}`);
}
});
child.stderr?.on('data', (data: Buffer) => {
child.stderr?.on("data", (data: Buffer) => {
const text = data.toString();
output += text;
for (const line of text.trimEnd().split('\n')) {
for (const line of text.trimEnd().split("\n")) {
if (line) this.logger.warn(`[hindsight:${label}] ${line}`);
}
});
await new Promise<void>((resolve, reject) => {
child.on('exit', (code) => {
child.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`${label} failed with code ${code}: ${output.trim()}`));
}
});
child.on('error', (err) => {
child.on("error", (err) => {
reject(new Error(`${label} failed to spawn: ${err.message}`, { cause: err }));
});
});
@@ -284,13 +284,13 @@ export class HindsightServer {
/** Stream a spawned child's stdout/stderr through the logger without blocking. */
private pipeOutput(child: ReturnType<typeof spawn>, label: string): void {
child.stdout?.on('data', (data: Buffer) => {
for (const line of data.toString().trimEnd().split('\n')) {
child.stdout?.on("data", (data: Buffer) => {
for (const line of data.toString().trimEnd().split("\n")) {
if (line) this.logger.info(`[hindsight:${label}] ${line}`);
}
});
child.stderr?.on('data', (data: Buffer) => {
for (const line of data.toString().trimEnd().split('\n')) {
child.stderr?.on("data", (data: Buffer) => {
for (const line of data.toString().trimEnd().split("\n")) {
if (line) this.logger.warn(`[hindsight:${label}] ${line}`);
}
});
@@ -316,7 +316,7 @@ export class HindsightServer {
await new Promise((resolve) => setTimeout(resolve, this.readyPollIntervalMs));
}
throw new Error(
`Hindsight daemon did not become ready within ${this.readyTimeoutMs}ms at ${this.baseUrl}`,
`Hindsight daemon did not become ready within ${this.readyTimeoutMs}ms at ${this.baseUrl}`
);
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Logger } from './logger.js';
import type { Logger } from "./logger.js";
/**
* Options for {@link HindsightServer}.
+4 -4
View File
@@ -1,10 +1,10 @@
import { defineConfig } from 'tsup';
import { defineConfig } from "tsup";
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm'],
entry: ["src/index.ts"],
format: ["esm"],
dts: true,
outDir: 'dist',
outDir: "dist",
clean: true,
sourcemap: true,
bundle: true,
+3 -3
View File
@@ -1,8 +1,8 @@
import { defineConfig } from 'vitest/config';
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
environment: 'node',
include: ["src/**/*.test.ts"],
environment: "node",
},
});
+2 -2
View File
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
[project]
name = "hindsight-all-slim"
version = "0.5.4"
version = "0.6.2"
description = "Hindsight: Agent Memory That Works Like Human Memory - Slim All-in-One Bundle"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"hindsight-api-slim>=0.4.17",
"hindsight-api-slim==0.6.2",
"hindsight-client>=0.0.7",
"hindsight-embed>=0.1.0",
]
+3 -3
View File
@@ -4,12 +4,12 @@ build-backend = "hatchling.build"
[project]
name = "hindsight-all"
version = "0.5.4"
version = "0.6.2"
description = "Hindsight: Agent Memory That Works Like Human Memory - All-in-One Bundle"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"hindsight-api-slim[all]>=0.4.17",
"hindsight-api-slim[all]==0.6.2",
"hindsight-client>=0.0.7",
"hindsight-embed>=0.1.0",
]
@@ -21,7 +21,7 @@ hindsight-embed = { workspace = true }
[project.optional-dependencies]
local-llm = [
"hindsight-api-slim[local-llm]>=0.4.17",
"hindsight-api-slim[local-llm]==0.6.2",
]
test = [
"pytest>=7.0.0",
+1 -1
View File
@@ -46,4 +46,4 @@ __all__ = [
"RemoteTEICrossEncoder",
"LLMConfig",
]
__version__ = "0.5.4"
__version__ = "0.6.2"
@@ -0,0 +1,170 @@
"""Shared PostgreSQL vector-extension dispatch helpers."""
from __future__ import annotations
import logging
from sqlalchemy import text
from sqlalchemy.engine import Connection
logger = logging.getLogger(__name__)
# Extensions a user can set via HINDSIGHT_API_VECTOR_EXTENSION.
CONFIGURABLE_EXTENSIONS = ("pgvector", "pgvectorscale", "vchord", "scann")
# Extensions detect_vector_extension() can return. pg_diskann is a runtime-only
# resolution from a configured "pgvectorscale" backend on Azure (uses a different
# WITH clause), never a value the user sets directly.
RESOLVED_EXTENSIONS = (*CONFIGURABLE_EXTENSIONS, "pg_diskann")
# Backwards-compatible alias for older imports.
VALID_EXTENSIONS = CONFIGURABLE_EXTENSIONS
SCANN_MIN_ROWS_FOR_AUTO_INDEX = 10_000
_EXTENSION_NAMES = {
"pgvector": "vector",
"pgvectorscale": "vectorscale",
"vchord": "vchord",
"scann": "alloydb_scann",
}
_INDEX_USING_CLAUSES = {
"pgvector": "USING hnsw (embedding vector_cosine_ops)",
"pgvectorscale": "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)",
"pg_diskann": "USING diskann (embedding vector_cosine_ops) WITH (max_neighbors = 50)",
"vchord": "USING vchordrq (embedding vector_l2_ops)",
"scann": "USING scann (embedding cosine) WITH (mode = 'AUTO')",
}
_INDEX_TYPE_KEYWORDS = {
"pgvector": "hnsw",
"pgvectorscale": "diskann",
"pg_diskann": "diskann",
"vchord": "vchordrq",
"scann": "scann",
}
_EXTENSION_INSTALL_SQL = {
"pgvector": ("CREATE EXTENSION IF NOT EXISTS vector",),
"pgvectorscale": (
"CREATE EXTENSION IF NOT EXISTS vector",
"CREATE EXTENSION IF NOT EXISTS vectorscale CASCADE",
),
"vchord": ("CREATE EXTENSION IF NOT EXISTS vchord CASCADE",),
"scann": (
"CREATE EXTENSION IF NOT EXISTS vector",
"CREATE EXTENSION IF NOT EXISTS alloydb_scann CASCADE",
),
}
_INSTALL_HINTS = {
"pgvector": "CREATE EXTENSION vector;",
"pgvectorscale": "CREATE EXTENSION vector; then CREATE EXTENSION vectorscale CASCADE; (or pg_diskann on Azure)",
"vchord": "CREATE EXTENSION vchord CASCADE;",
"scann": "CREATE EXTENSION vector; then CREATE EXTENSION alloydb_scann CASCADE;",
}
def validate_extension(name: str) -> str:
"""Return a normalized configurable vector extension name or raise.
Used at the user-facing config boundary; pg_diskann is rejected here because
it is a detection-time alias, never a value the user sets directly.
"""
ext = name.lower()
if ext not in CONFIGURABLE_EXTENSIONS:
valid = ", ".join(CONFIGURABLE_EXTENSIONS)
raise ValueError(f"Invalid vector_extension: {name}. Must be one of: {valid}")
return ext
def _normalize_resolved(name: str) -> str:
"""Normalize either a user-configurable or detect-time extension name."""
ext = name.lower()
if ext not in RESOLVED_EXTENSIONS:
valid = ", ".join(RESOLVED_EXTENSIONS)
raise ValueError(f"Unknown vector extension: {name}. Must be one of: {valid}")
return ext
def pg_extension_name(ext: str) -> str:
"""Return the PostgreSQL extension name for a configured vector backend."""
return _EXTENSION_NAMES[validate_extension(ext)]
def index_using_clause(ext: str) -> str:
"""Return the CREATE INDEX USING clause for the vector backend."""
return _INDEX_USING_CLAUSES[_normalize_resolved(ext)]
def index_type_keyword(ext: str) -> str:
"""Return the keyword that identifies this index type in pg_indexes.indexdef."""
return _INDEX_TYPE_KEYWORDS[_normalize_resolved(ext)]
def minimum_rows_for_index(ext: str) -> int:
"""Return the minimum populated embedding rows before creating this index type."""
return SCANN_MIN_ROWS_FOR_AUTO_INDEX if _normalize_resolved(ext) == "scann" else 0
def should_defer_index_creation(ext: str, row_count: int) -> bool:
"""Return True when index creation should wait for more embeddings."""
minimum_rows = minimum_rows_for_index(ext)
return minimum_rows > 0 and row_count < minimum_rows
def uses_per_bank_vector_indexes(ext: str) -> bool:
"""Return whether the backend should create per-bank partial vector indexes."""
return _normalize_resolved(ext) != "scann"
def bootstrap_extension(conn: Connection, ext: str) -> None:
"""Install the configured vector extension and any prerequisites if possible."""
normalized = validate_extension(ext)
for statement in _EXTENSION_INSTALL_SQL[normalized]:
conn.execute(text(statement))
def detect_vector_extension(conn: Connection, vector_extension: str = "pgvector") -> str:
"""Validate the configured vector extension exists and return the index backend."""
configured_ext = validate_extension(vector_extension)
if configured_ext == "pgvectorscale":
pgvector_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vector'")).scalar()
if not pgvector_check:
raise RuntimeError(
"DiskANN (pgvectorscale/pg_diskann) requires pgvector to be installed. "
f"Install it with: {_INSTALL_HINTS['pgvectorscale']}"
)
vectorscale_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vectorscale'")).scalar()
pg_diskann_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'pg_diskann'")).scalar()
if vectorscale_check:
logger.debug("Using vector extension: pgvectorscale (DiskANN)")
return "pgvectorscale"
if pg_diskann_check:
logger.debug("Using vector extension: pg_diskann (Azure DiskANN)")
return "pg_diskann"
raise RuntimeError(
"Configured vector extension 'pgvectorscale' not found. Install either:\n"
" - pgvectorscale (open source): CREATE EXTENSION vectorscale CASCADE;\n"
" - pg_diskann (Azure): CREATE EXTENSION pg_diskann CASCADE;"
)
extension_name = pg_extension_name(configured_ext)
extension_check = conn.execute(
text("SELECT 1 FROM pg_extension WHERE extname = :extension_name"),
{"extension_name": extension_name},
).scalar()
if not extension_check:
raise RuntimeError(
f"Configured vector extension '{configured_ext}' not found. "
f"Install it with: {_INSTALL_HINTS[configured_ext]}"
)
logger.debug("Using configured vector extension: %s", configured_ext)
return configured_ext
@@ -1,5 +1,7 @@
"""
Hindsight Admin CLI - backup and restore operations.
"""PostgreSQL-only admin utilities (backup, restore, migration, worker management).
Not supported on Oracle backends. Uses asyncpg.connect() directly, binary COPY,
TRUNCATE CASCADE, and REFRESH MATERIALIZED VIEW — all inherently PG-specific.
"""
import asyncio
@@ -15,15 +17,10 @@ import asyncpg
import typer
from ..config import DEFAULT_DATABASE_SCHEMA, HindsightConfig
from ..engine.schema import fq_table_explicit as _fq_table
from ..extensions import TenantExtension, load_extension
from ..pg0 import parse_pg0_url, resolve_database_url
def _fq_table(table: str, schema: str) -> str:
"""Get fully-qualified table name with schema prefix."""
return f"{schema}.{table}"
# Setup logging
logging.basicConfig(
level=logging.INFO,
@@ -0,0 +1,42 @@
"""Dialect dispatcher for Alembic migrations.
Each migration file declares a ``_pg_upgrade``/``_oracle_upgrade`` (and matching
downgrades) function and routes ``upgrade()``/``downgrade()`` through
``run_for_dialect``. The helper inspects the live connection's dialect name and
runs the matching function — or no-ops if the migration doesn't apply to the
current backend.
Use ``None`` (or omit the kwarg) when a migration intentionally has no effect
on a dialect; the helper treats it as a no-op.
"""
from __future__ import annotations
from collections.abc import Callable
from alembic import op
DialectFn = Callable[[], None]
_SUPPORTED = ("postgresql", "oracle")
def run_for_dialect(
*,
pg: DialectFn | None = None,
oracle: DialectFn | None = None,
) -> None:
"""Dispatch to the function matching the current bind's dialect.
Args:
pg: Function to run when the active bind is PostgreSQL.
oracle: Function to run when the active bind is Oracle.
Unrecognized dialects raise; an explicit ``None`` for the active dialect
is a no-op (the migration deliberately does nothing here).
"""
name = op.get_bind().dialect.name
if name not in _SUPPORTED:
raise RuntimeError(f"Unsupported dialect for migration dispatch: {name!r}. Expected one of {_SUPPORTED}.")
fn = {"postgresql": pg, "oracle": oracle}[name]
if fn is not None:
fn()
+100 -75
View File
@@ -1,28 +1,37 @@
"""
Alembic environment configuration for SQLAlchemy with pgvector.
Uses synchronous psycopg2 driver for migrations to avoid pgbouncer issues.
Alembic environment for Hindsight.
Supports two dialects:
* PostgreSQL (sync psycopg2 driver) — default; uses ``search_path`` for
multi-tenant schema isolation and forces read-write transactions to work
around Supabase's read-only-by-default sessions.
* Oracle 23ai (``oracledb`` driver) — uses ``CURRENT_SCHEMA`` for tenant
isolation; no equivalent of ``search_path`` or read-only session quirks.
Each migration file dispatches its DDL through ``alembic._dialect.run_for_dialect``
so a single revision tree serves both backends.
"""
import logging
import os
from pathlib import Path
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from alembic import context
from dotenv import load_dotenv
from sqlalchemy import engine_from_config, pool
from sqlalchemy import Connection, engine_from_config, pool
from sqlalchemy.engine import Engine
# Import your models here
from hindsight_api.db_url import is_oracle_url, to_libpq_url
from hindsight_api.models import Base
# Load environment variables based on HINDSIGHT_API_DATABASE_URL env var or default to local
def load_env():
"""Load environment variables from .env"""
# Check if HINDSIGHT_API_DATABASE_URL is already set (e.g., by CI/CD)
def load_env() -> None:
"""Load environment variables from .env (skipped if already configured)."""
if os.getenv("HINDSIGHT_API_DATABASE_URL"):
return
# Look for .env file in the parent directory (root of the workspace)
root_dir = Path(__file__).parent.parent.parent
env_file = root_dir / ".env"
@@ -32,30 +41,45 @@ def load_env():
load_env()
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Note: We don't call fileConfig() here to avoid overriding the application's logging configuration.
# Alembic will use the existing logging configuration from the application.
# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def _normalize_oracle_url(url: str) -> str:
"""Coerce an Oracle URL into the SQLAlchemy form the oracledb dialect expects.
Two issues to handle:
1. Force the ``oracle+oracledb`` driver — bare ``oracle://`` defaults to
cx_Oracle.
2. Map a path-style service to ``?service_name=...``. SQLAlchemy's oracledb
dialect treats the URL path as a *SID* (legacy), but Oracle Free /
Autonomous DB only register a service name. Without this rewrite we get
``DPY-6003: SID "FREEPDB1" is not registered`` even though the listener
is happy to accept the same name as a service.
"""
parts = urlsplit(url)
if not parts.scheme.startswith("oracle"):
return url
new_scheme = "oracle+oracledb" if parts.scheme == "oracle" else parts.scheme
service = parts.path.lstrip("/")
new_query = parts.query
new_path = parts.path
# Promote /SERVICE to ?service_name=SERVICE unless the caller already
# supplied an explicit ?sid= or ?service_name=.
if service and "service_name=" not in new_query and "sid=" not in new_query:
params = [(k, v) for k, v in parse_qsl(new_query, keep_blank_values=True)]
params.append(("service_name", service))
new_query = urlencode(params)
new_path = ""
return urlunsplit((new_scheme, parts.netloc, new_path, new_query, parts.fragment))
def get_database_url() -> str:
"""
Get and process the database URL from config or environment.
Returns the URL with the correct driver (psycopg2) for migrations.
"""
# Get database URL from config (set programmatically) or environment
"""Resolve the migration URL from Alembic config or env, normalizing per-dialect."""
database_url = config.get_main_option("sqlalchemy.url")
if not database_url:
database_url = os.getenv("HINDSIGHT_API_DATABASE_URL")
@@ -65,30 +89,18 @@ def get_database_url() -> str:
"Set HINDSIGHT_API_DATABASE_URL environment variable or pass database_url to run_migrations()."
)
# For migrations, use psycopg2 (sync driver) to avoid pgbouncer prepared statement issues
if database_url.startswith("postgresql+asyncpg://"):
database_url = database_url.replace("postgresql+asyncpg://", "postgresql://", 1)
elif database_url.startswith("postgres+asyncpg://"):
database_url = database_url.replace("postgres+asyncpg://", "postgresql://", 1)
if is_oracle_url(database_url):
database_url = _normalize_oracle_url(database_url)
else:
# PG: convert SQLAlchemy-style asyncpg URLs and ?ssl= params to libpq form
# for the sync engine used during migrations.
database_url = to_libpq_url(database_url)
# Update config with processed URL for engine_from_config to use
config.set_main_option("sqlalchemy.url", database_url)
return database_url
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
logging.info("running offline")
database_url = get_database_url()
@@ -103,14 +115,40 @@ def run_migrations_offline() -> None:
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode with synchronous engine."""
def _configure_pg_session(engine: Engine, connection: Connection, target_schema: str | None) -> None:
"""PG-only: ensure the session is RW (Supabase) and bind ``search_path``."""
from sqlalchemy import event, text
get_database_url() # Process and set the database URL in config
@event.listens_for(engine, "connect")
def set_read_write_mode(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE")
if target_schema:
cursor.execute(f'CREATE SCHEMA IF NOT EXISTS "{target_schema}"')
cursor.execute(f'SET search_path TO "{target_schema}", public')
cursor.close()
# Check if we're targeting a specific schema (for multi-tenant isolation)
connection.execute(text("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE"))
if target_schema:
connection.execute(text(f'CREATE SCHEMA IF NOT EXISTS "{target_schema}"'))
connection.execute(text(f'SET search_path TO "{target_schema}", public'))
connection.commit()
def _configure_oracle_session(connection: Connection, target_schema: str | None) -> None:
"""Oracle: switch the session's default schema; tolerate DDL contention."""
from sqlalchemy import text
# Wait up to 30s for DDL locks instead of failing immediately (ORA-00054).
connection.execute(text("ALTER SESSION SET DDL_LOCK_TIMEOUT = 30"))
if target_schema:
connection.execute(text(f'ALTER SESSION SET CURRENT_SCHEMA = "{target_schema}"'))
def run_migrations_online() -> None:
database_url = get_database_url()
target_schema = config.get_main_option("target_schema")
is_oracle = is_oracle_url(database_url)
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
@@ -118,37 +156,19 @@ def run_migrations_online() -> None:
poolclass=pool.NullPool,
)
# Add event listener to ensure connection is in read-write mode
# This is needed for Supabase which may start connections in read-only mode
@event.listens_for(connectable, "connect")
def set_read_write_mode(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE")
# If targeting a specific schema, set search_path
# Include public in search_path for access to shared extensions (pgvector)
if target_schema:
cursor.execute(f'CREATE SCHEMA IF NOT EXISTS "{target_schema}"')
cursor.execute(f'SET search_path TO "{target_schema}", public')
cursor.close()
with connectable.connect() as connection:
# Also explicitly set read-write mode on this connection
connection.execute(text("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE"))
if is_oracle:
_configure_oracle_session(connection, target_schema)
else:
_configure_pg_session(connectable, connection, target_schema)
# If targeting a specific schema, set search_path
# Include public in search_path for access to shared extensions (pgvector)
if target_schema:
connection.execute(text(f'CREATE SCHEMA IF NOT EXISTS "{target_schema}"'))
connection.execute(text(f'SET search_path TO "{target_schema}", public'))
connection.commit() # Commit the SET command
# Configure context with version_table_schema if using a specific schema
context_opts = {
"connection": connection,
"target_metadata": target_metadata,
}
if target_schema:
if target_schema and not is_oracle:
# Oracle has no equivalent of PG's per-schema version table; the
# ``alembic_version`` table lives in CURRENT_SCHEMA implicitly.
context_opts["version_table_schema"] = target_schema
context.configure(**context_opts)
@@ -156,7 +176,12 @@ def run_migrations_online() -> None:
with context.begin_transaction():
context.run_migrations()
# Explicit commit to ensure changes are persisted (especially for Supabase)
# Always commit. PG needs it for the explicit RW-mode SET to persist;
# Oracle needs it because each DDL auto-commits but the trailing
# ``UPDATE alembic_version`` is plain DML that would otherwise stay in
# an open transaction and roll back when the connection closes —
# producing the "schema is created but the version row is one revision
# behind" failure mode.
connection.commit()
@@ -11,6 +11,8 @@ from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
@@ -18,11 +20,27 @@ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
def _pg_upgrade() -> None:
"""PostgreSQL upgrade. Set to ``None`` below if this migration is Oracle-only."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
def _pg_downgrade() -> None:
${downgrades if downgrades else "pass"}
def _oracle_upgrade() -> None:
"""Oracle upgrade. Set to ``None`` below if this migration is Postgres-only."""
pass
def _oracle_downgrade() -> None:
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade, oracle=_oracle_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade, oracle=_oracle_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "2eee35aa3cfc"
down_revision: str | Sequence[str] | None = "d6e7f8a9b0c1"
branch_labels: str | Sequence[str] | None = None
@@ -24,7 +26,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Drop the old case-sensitive trigram index
op.execute("DROP INDEX IF EXISTS entities_canonical_name_trgm_idx")
@@ -35,7 +37,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
op.execute("DROP INDEX IF EXISTS entities_canonical_name_lower_trgm_idx")
schema = _get_schema_prefix()
# Restore original case-sensitive index
@@ -43,3 +45,11 @@ def downgrade() -> None:
f"CREATE INDEX IF NOT EXISTS entities_canonical_name_trgm_idx "
f"ON {schema}entities USING GIN (canonical_name gin_trgm_ops)"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -15,6 +15,8 @@ from pgvector.sqlalchemy import Vector
from sqlalchemy import text
from sqlalchemy.dialects import postgresql
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "5a366d414dce"
down_revision: str | Sequence[str] | None = None
@@ -24,52 +26,67 @@ depends_on: str | Sequence[str] | None = None
def _detect_vector_extension() -> str:
"""
Detect or validate vector extension: 'pgvector', 'vchord', or 'pgvectorscale'.
Detect or validate vector extension for this immutable migration revision.
Respects HINDSIGHT_API_VECTOR_EXTENSION env var if set.
"""
conn = op.get_bind()
vector_extension = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
# Validate configured extension is installed
if vector_extension == "pgvectorscale":
# pgvectorscale/DiskANN requires pgvector
pgvector_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vector'")).scalar()
if not pgvector_check:
raise RuntimeError(
"DiskANN requires pgvector. Install with: CREATE EXTENSION vector; then vectorscale or pg_diskann CASCADE;"
)
# Check for either vectorscale (open source) or pg_diskann (Azure)
vectorscale_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vectorscale'")).scalar()
pg_diskann_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'pg_diskann'")).scalar()
if vectorscale_check:
return "pgvectorscale"
elif pg_diskann_check:
if pg_diskann_check:
return "pg_diskann"
else:
raise RuntimeError(
"Configured vector extension 'pgvectorscale' not found. Install either:\n"
" - pgvectorscale: CREATE EXTENSION vectorscale CASCADE;\n"
" - pg_diskann (Azure): CREATE EXTENSION pg_diskann CASCADE;"
)
elif vector_extension == "vchord":
raise RuntimeError(
"Configured vector extension 'pgvectorscale' not found. Install either:\n"
" - pgvectorscale: CREATE EXTENSION vectorscale CASCADE;\n"
" - pg_diskann (Azure): CREATE EXTENSION pg_diskann CASCADE;"
)
if vector_extension == "vchord":
vchord_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vchord'")).scalar()
if not vchord_check:
raise RuntimeError(
"Configured vector extension 'vchord' not found. Install it with: CREATE EXTENSION vchord CASCADE;"
)
return "vchord"
elif vector_extension == "pgvector":
if vector_extension == "scann":
scann_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'alloydb_scann'")).scalar()
if not scann_check:
raise RuntimeError(
"Configured vector extension 'scann' not found. Install it with: CREATE EXTENSION alloydb_scann CASCADE;"
)
return "scann"
if vector_extension == "pgvector":
pgvector_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vector'")).scalar()
if not pgvector_check:
raise RuntimeError(
"Configured vector extension 'pgvector' not found. Install it with: CREATE EXTENSION vector;"
)
return "pgvector"
else:
raise ValueError(
f"Invalid HINDSIGHT_API_VECTOR_EXTENSION: {vector_extension}. Must be 'pgvector', 'vchord', or 'pgvectorscale'"
)
raise ValueError(
"Invalid HINDSIGHT_API_VECTOR_EXTENSION: "
f"{vector_extension}. Must be 'pgvector', 'vchord', 'pgvectorscale', or 'scann'"
)
def _vector_index_using_clause(ext: str) -> str:
if ext == "pgvectorscale":
return "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)"
if ext == "pg_diskann":
return "USING diskann (embedding vector_cosine_ops) WITH (max_neighbors = 50)"
if ext == "vchord":
return "USING vchordrq (embedding vector_l2_ops)"
if ext == "scann":
return "USING scann (embedding cosine) WITH (mode = 'AUTO')"
return "USING hnsw (embedding vector_cosine_ops)"
def _detect_text_search_extension() -> str:
@@ -112,7 +129,7 @@ def _detect_text_search_extension() -> str:
)
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Upgrade schema - create all tables from scratch."""
# Note: pgvector extension is installed globally BEFORE migrations run
@@ -311,36 +328,11 @@ def upgrade() -> None:
)
# Create vector index - conditional based on available extension
vector_ext = _detect_vector_extension()
if vector_ext == "pgvectorscale":
# Use DiskANN index for pgvectorscale (disk-based, scalable)
op.execute("""
if vector_ext != "scann":
op.execute(f"""
CREATE INDEX idx_memory_units_embedding ON memory_units
USING diskann (embedding vector_cosine_ops)
WITH (num_neighbors = 50)
{_vector_index_using_clause(vector_ext)}
""")
elif vector_ext == "pg_diskann":
# Use DiskANN index for pg_diskann (Azure)
op.execute("""
CREATE INDEX idx_memory_units_embedding ON memory_units
USING diskann (embedding vector_cosine_ops)
WITH (max_neighbors = 50)
""")
elif vector_ext == "vchord":
# Use vchordrq index for vchord (supports high-dimensional embeddings)
op.execute("""
CREATE INDEX idx_memory_units_embedding ON memory_units
USING vchordrq (embedding vector_l2_ops)
""")
else: # pgvector
# Use HNSW index for pgvector
op.create_index(
"idx_memory_units_embedding",
"memory_units",
["embedding"],
postgresql_using="hnsw",
postgresql_ops={"embedding": "vector_cosine_ops"},
)
# Create full-text search index on search_vector
# Index type depends on text search backend
@@ -463,7 +455,7 @@ def upgrade() -> None:
op.create_index("idx_unit_entities_entity", "unit_entities", ["entity_id"])
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Downgrade schema - drop all tables."""
# Drop tables in reverse dependency order
@@ -523,3 +515,11 @@ def downgrade() -> None:
# Drop extensions (optional - comment out if you want to keep them)
# op.execute('DROP EXTENSION IF EXISTS vector')
# op.execute('DROP EXTENSION IF EXISTS "uuid-ossp"')
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,117 @@
"""Repair mental_models.subtype on databases stuck at m3rg3h3ad5f6
Three production deployments reported `column "subtype" of relation
"mental_models" does not exist` on `create_mental_model` even after their
container reported `Database migrations completed successfully` and
`alembic_version` advanced to `m3rg3h3ad5f6` (see issue #1553, #1553#1
confirmations from @4Lienau and @khanhduyvt0101).
Both `h3c4d5e6f7g8_mental_models_v4` and `d5y6z7a8b9c0_backfill_mental_models_subtype`
were meant to ensure `subtype` exists, but on databases that came through the
`reflections -> mental_models` rename chain *and* whose alembic_version
advanced past `d5y6z7a8b9c0` along an alternate path during the divergent-heads
reorganization, neither column-add actually fired. The result is a head-tagged
database with a v3-shaped `mental_models` table missing six columns:
``subtype``, ``description``, ``entity_id``, ``observations``, ``links``,
``last_updated``.
This migration sits at the current head (`m3rg3h3ad5f6`) so every affected
deployment will pick it up on next container start. It mirrors the column-add
block from `d5y6z7a8b9c0_backfill_mental_models_subtype` using
``ADD COLUMN IF NOT EXISTS`` so it is a no-op on databases where the columns
are already present.
Revision ID: 86f7a033d372
Revises: m3rg3h3ad5f6
Create Date: 2026-05-14
"""
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "86f7a033d372"
down_revision: str | Sequence[str] | None = "m3rg3h3ad5f6"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _pg_schema_prefix() -> str:
"""Schema-qualifier for raw SQL on PG (multi-tenant search_path)."""
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def _pg_upgrade() -> None:
"""Idempotently ensure mental_models has the v4 column set.
Safe to re-apply on databases that already received the columns via
`h3c4d5e6f7g8_mental_models_v4` or `d5y6z7a8b9c0_backfill_mental_models_subtype` —
every column-add uses ``IF NOT EXISTS`` and the constraint is recreated
from scratch with the canonical v4 allowlist.
"""
schema = _pg_schema_prefix()
bare_schema = schema.strip(".").strip('"') if schema else ""
schema_clause = f"AND table_schema = '{bare_schema}'" if bare_schema else ""
# Wrapped in a DO block so the existence check skips databases that
# predate the reflections -> mental_models rename chain (no table to
# repair). On those, every ALTER below would error.
op.execute(
f"""
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'mental_models'
{schema_clause}
) THEN
-- Add the six v4 columns idempotently.
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS subtype VARCHAR(32) NOT NULL DEFAULT 'structural';
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS description TEXT NOT NULL DEFAULT '';
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS entity_id UUID;
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS observations JSONB DEFAULT '{{"observations": []}}'::jsonb;
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS links VARCHAR[];
ALTER TABLE {schema}mental_models
ADD COLUMN IF NOT EXISTS last_updated TIMESTAMP WITH TIME ZONE;
-- Recreate the CHECK constraint with the canonical v4 allowlist.
-- Existing rows with subtype = 'directive' (possible on databases
-- that ran the o0j1k2l3m4n5 directive-only path) are rewritten to
-- 'structural' first so the constraint add succeeds.
UPDATE {schema}mental_models SET subtype = 'structural' WHERE subtype = 'directive';
ALTER TABLE {schema}mental_models DROP CONSTRAINT IF EXISTS ck_mental_models_subtype;
ALTER TABLE {schema}mental_models
ADD CONSTRAINT ck_mental_models_subtype
CHECK (subtype IN ('structural', 'emergent', 'pinned', 'learned'));
CREATE INDEX IF NOT EXISTS idx_mental_models_subtype
ON {schema}mental_models(bank_id, subtype);
END IF;
END$$;
"""
)
def _pg_downgrade() -> None:
"""No-op: dropping these columns would corrupt v4 application code."""
pass
def upgrade() -> None:
# PG-only: Oracle's baseline (o1a2b3c4d5e6) creates mental_models with its
# own subtype shape (chk_mm_subtype IN ('directive', 'pinned')) and a
# different table topology, so this PG-shaped repair does not apply.
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -26,15 +26,25 @@ Create Date: 2026-04-18
from collections.abc import Sequence
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "8c6fa6f7230b"
down_revision: str | Sequence[str] | None = ("c4x5y6z7a8b9", "h3i4j5k6l7m8")
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
def _pg_upgrade() -> None:
pass
def _pg_downgrade() -> None:
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
pass
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,128 @@
"""Make memory_links.from_unit_id and memory_links.to_unit_id FKs deferrable.
Revision ID: 9f8e7d6c5b4a
Revises: o1a2b3c4d5e6
Create Date: 2026-05-03
Background
----------
Concurrent retain (which INSERTs into ``memory_links``) and any code path
that DELETEs a row whose deletion cascades into ``memory_links`` (e.g.
delta-retain superseding chunks, which CASCADEs chunks → memory_units →
memory_links) can deadlock under sustained single-tenant write load.
The deadlock cycle:
* Tx A: ``DELETE FROM chunks WHERE chunk_id = ANY(...)``
→ CASCADE acquires row locks on memory_units, then on memory_links rows
where ``to_unit_id`` matches the deleted units.
* Tx B: ``INSERT INTO memory_links (...)`` referencing one of the same
memory_units rows.
→ The immediate FK check takes ``FOR KEY SHARE`` on those memory_units
rows.
The two transactions take row locks on the same memory_units rows in
opposite orders depending on which side started first. PostgreSQL detects
the cycle and aborts one transaction; the loser is killed mid-batch, the
winner continues. Workers then retry, but under sustained write load the
pattern repeats.
Fix
---
Make both ``memory_links → memory_units`` FKs (``from_unit_id`` and
``to_unit_id``) ``DEFERRABLE INITIALLY DEFERRED``. This pushes the FK
check from INSERT time to COMMIT time:
* INSERT no longer takes ``FOR KEY SHARE`` on the memory_units row → no
contention with the cascading DELETE's row lock.
* At COMMIT the engine validates referential integrity in one shot. If a
cascade-DELETE has since removed the referenced unit, the INSERT
transaction commits OR fails with a clean FK violation (sqlstate
23503) instead of a deadlock (sqlstate 40P01).
The ``WHERE EXISTS`` filter already in ``_bulk_insert_links`` continues to
filter out the typical "stale unit_id" case at INSERT time; the deferred
FK is only the backstop for the narrow race window between the EXISTS
probe and COMMIT. ``ON DELETE CASCADE`` semantics are unchanged — only
the *timing* of the constraint check moves.
The ``entity_id`` FK on ``memory_links`` is not changed; entities are not
involved in the observed deadlock cycle and leaving the constraint
immediate keeps the error message specific when an entity row is missing.
"""
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "9f8e7d6c5b4a"
down_revision: str | Sequence[str] | None = "o1a2b3c4d5e6"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_schema_prefix() -> str:
"""Schema-qualifier for raw SQL on PG (multi-tenant search_path)."""
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
# The two FK constraints installed by the initial schema migration
# (5a366d414dce_initial_schema), mapped to the column they constrain.
# They reference memory_units(id) with ON DELETE CASCADE — that
# semantics is preserved; only the deferral attribute changes.
_FK_COLUMNS: dict[str, str] = {
"fk_memory_links_from_unit_id_memory_units": "from_unit_id",
"fk_memory_links_to_unit_id_memory_units": "to_unit_id",
}
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# PostgreSQL doesn't allow altering the deferrability of an existing
# constraint with ALTER CONSTRAINT — the constraint must be dropped
# and recreated. DROP IF EXISTS makes the migration safe to re-run
# on schemas where the constraint was already recreated.
for fk_name, column in _FK_COLUMNS.items():
op.execute(f"ALTER TABLE {schema}memory_links DROP CONSTRAINT IF EXISTS {fk_name}")
op.execute(
f"""
ALTER TABLE {schema}memory_links
ADD CONSTRAINT {fk_name}
FOREIGN KEY ({column})
REFERENCES {schema}memory_units (id)
ON DELETE CASCADE
DEFERRABLE INITIALLY DEFERRED
"""
)
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
# Revert to the default (NOT DEFERRABLE) form so a downgrade actually
# restores the prior schema state, even though that re-introduces the
# deadlock window.
for fk_name, column in _FK_COLUMNS.items():
op.execute(f"ALTER TABLE {schema}memory_links DROP CONSTRAINT IF EXISTS {fk_name}")
op.execute(
f"""
ALTER TABLE {schema}memory_links
ADD CONSTRAINT {fk_name}
FOREIGN KEY ({column})
REFERENCES {schema}memory_units (id)
ON DELETE CASCADE
"""
)
def upgrade() -> None:
# PG-only: Oracle's deferrable-FK semantics differ and the deadlock
# cycle was only observed on PostgreSQL. Oracle slot intentionally
# absent → no-op there.
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -15,6 +15,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a1b2c3d4e5f6"
down_revision: str | Sequence[str] | None = "y0t1u2v3w4x5"
branch_labels: str | Sequence[str] | None = None
@@ -27,7 +29,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Create file_storage table for BYTEA storage."""
schema = _get_schema_prefix()
@@ -52,7 +54,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove file_storage table and related columns."""
schema = _get_schema_prefix()
@@ -68,3 +70,11 @@ def downgrade() -> None:
# Drop file_storage table
op.execute(f"DROP TABLE IF EXISTS {schema}file_storage")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -18,6 +18,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a2b3c4d5e6f7"
down_revision: str | Sequence[str] | None = "aa2b3c4d5e6f"
branch_labels: str | Sequence[str] | None = None
@@ -33,7 +35,7 @@ def _detect_text_search_extension() -> str:
return os.getenv("HINDSIGHT_API_TEXT_SEARCH_EXTENSION", "native").lower()
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
table = f"{schema}memory_units"
text_search_ext = _detect_text_search_extension()
@@ -65,7 +67,7 @@ def upgrade() -> None:
# pg_textsearch: no change — index operates on the base `text` column only
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
table = f"{schema}memory_units"
text_search_ext = _detect_text_search_extension()
@@ -86,3 +88,11 @@ def downgrade() -> None:
""")
op.execute(f"ALTER TABLE {table} DROP COLUMN IF EXISTS text_signals")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -24,6 +24,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a2b3c4d5e6f8"
down_revision: str | Sequence[str] | None = "f7g8h9i0j1k2"
branch_labels: str | Sequence[str] | None = None
@@ -35,7 +37,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
@@ -48,7 +50,15 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_units_source_memory_ids")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a2v3w4x5y6z7"
down_revision: str | Sequence[str] | None = "z1u2v3w4x5y6"
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"""
ALTER TABLE {schema}mental_models
@@ -33,6 +35,14 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS last_refreshed_source_query")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a3b4c5d6e7f8"
down_revision: str | Sequence[str] | None = "g7h8i9j0k1l2"
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(
@@ -45,8 +47,16 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_memory_units_consolidation_failed")
op.execute(f"ALTER TABLE {schema}memory_units DROP COLUMN IF EXISTS consolidation_failed_at")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -11,7 +11,8 @@ was configured.
This migration detects the mismatch and recreates the affected indexes with
the correct type. Skipped entirely when the configured extension is pgvector
(the default), since those indexes are already correct.
(the default) or scann. ScaNN uses global vector indexes because empty or tiny
per-bank indexes cannot be built safely on AlloyDB.
"""
import os
@@ -20,6 +21,8 @@ from collections.abc import Sequence
from alembic import context, op
from sqlalchemy import text
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "a4b5c6d7e8f9"
down_revision: str | Sequence[str] | None = "2eee35aa3cfc"
branch_labels: str | Sequence[str] | None = None
@@ -37,39 +40,47 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def _target_index_type() -> str | None:
"""Return the target index type, or None if pgvector (no fix needed)."""
ext = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
def _validate_extension(name: str) -> str:
ext = name.lower()
if ext not in {"pgvector", "pgvectorscale", "vchord", "scann"}:
raise ValueError(
f"Invalid HINDSIGHT_API_VECTOR_EXTENSION: {ext}. Must be 'pgvector', 'vchord', 'pgvectorscale', or 'scann'"
)
return ext
def _index_type_keyword(ext: str) -> str:
if ext == "pgvectorscale":
return "diskann"
elif ext == "vchord":
if ext == "vchord":
return "vchordrq"
return None
if ext == "scann":
return "scann"
return "hnsw"
def _vector_index_using_clause() -> str:
"""Return the USING clause based on the configured vector extension."""
ext = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
def _vector_index_using_clause(ext: str) -> str:
if ext == "pgvectorscale":
return "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)"
elif ext == "vchord":
if ext == "vchord":
return "USING vchordrq (embedding vector_l2_ops)"
else:
return "USING hnsw (embedding vector_cosine_ops)"
if ext == "scann":
return "USING scann (embedding cosine) WITH (mode = 'AUTO')"
return "USING hnsw (embedding vector_cosine_ops)"
def upgrade() -> None:
target = _target_index_type()
if target is None:
# pgvector — indexes are already HNSW, nothing to fix
def _pg_upgrade() -> None:
ext = _validate_extension(os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector"))
if ext in {"pgvector", "scann"}:
return
target = _index_type_keyword(ext)
bind = op.get_bind()
schema_name = context.config.get_main_option("target_schema")
schema = _get_schema_prefix()
table_ref = f'"{schema_name}".memory_units' if schema_name else "memory_units"
banks_ref = f'"{schema_name}".banks' if schema_name else "banks"
using_clause = _vector_index_using_clause()
using_clause = _vector_index_using_clause(ext)
pg_schema = schema_name or "public"
rows = bind.execute(text(f"SELECT bank_id, internal_id FROM {banks_ref}")).fetchall() # noqa: S608
@@ -113,10 +124,10 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
# Downgrade recreates indexes as HNSW (the original hardcoded behavior)
target = _target_index_type()
if target is None:
ext = _validate_extension(os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector"))
if ext in {"pgvector", "scann"}:
return
bind = op.get_bind()
@@ -140,3 +151,11 @@ def downgrade() -> None:
f"WHERE fact_type = '{ft}' AND bank_id = '{escaped_bank_id}'"
)
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "aa2b3c4d5e6f"
down_revision: str | Sequence[str] | None = "z1u2v3w4x5y6"
branch_labels: str | Sequence[str] | None = None
@@ -24,13 +26,21 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}memory_units ALTER COLUMN event_date DROP NOT NULL")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
# Backfill NULLs with now() before restoring the NOT NULL constraint
op.execute(f"UPDATE {schema}memory_units SET event_date = now() WHERE event_date IS NULL")
op.execute(f"ALTER TABLE {schema}memory_units ALTER COLUMN event_date SET NOT NULL")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -9,6 +9,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "b3c4d5e6f7a8"
down_revision: str | Sequence[str] | None = "a3b4c5d6e7f8"
branch_labels: str | Sequence[str] | None = None
@@ -21,12 +23,20 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Add content_hash column to chunks table for delta comparison
op.execute(f"ALTER TABLE {schema}chunks ADD COLUMN IF NOT EXISTS content_hash TEXT")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}chunks DROP COLUMN IF EXISTS content_hash")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -22,6 +22,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "b3c4d5e6f7g8"
down_revision: str | Sequence[str] | None = "c1a2b3d4e5f6"
branch_labels: str | Sequence[str] | None = None
@@ -33,7 +35,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Partial index on occurred_start (covers "occurred_start BETWEEN $4 AND $5")
op.execute("COMMIT")
@@ -58,7 +60,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_units_bank_mentioned_at")
@@ -66,3 +68,11 @@ def downgrade() -> None:
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_units_bank_occurred_end")
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_units_bank_occurred_start")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -20,6 +20,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "b3w4x5y6z7a8"
down_revision: str | Sequence[str] | None = "a2v3w4x5y6z7"
branch_labels: str | Sequence[str] | None = None
@@ -31,7 +33,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"""
ALTER TABLE {schema}mental_models
@@ -39,6 +41,14 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS structured_content")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "b4c5d6e7f8a9"
down_revision: str | Sequence[str] | None = "a2b3c4d5e6f7"
branch_labels: str | Sequence[str] | None = None
@@ -25,10 +27,18 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}memory_units ADD COLUMN IF NOT EXISTS observation_scopes JSONB")
def downgrade() -> None:
def _pg_downgrade() -> None:
pass # intentionally no-op — safe to leave the column in place
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,91 @@
"""Backfill entity_cooccurrences.last_cooccurred from memory_units event time
Revision ID: b5d4e3f2a1c9
Revises: o1a2b3c4d5e6
Create Date: 2026-04-24
The writer path in `entity_resolver.link_units_to_entities_batch` historically
stamped `entity_cooccurrences.last_cooccurred` with `datetime.now(UTC)` at
flush time, ignoring the source memory unit's event date. For normal online
retains that's fine (now ≈ event time), but for any corpus that was
backfilled in a single session — migrating from another memory system, for
example — every co-occurrence collapsed to the import moment, which hid the
underlying knowledge timeline from the dashboard's entity graph recency heat
and from any downstream consumer of the column.
The writer is fixed in the same change set to propagate the unit's event_date;
this migration repairs historical rows by reading the true event time off
`unit_entities × memory_units` (falling back to `created_at` when
`mentioned_at` / `occurred_start` are NULL, so rows never regress).
Oracle slot is intentionally absent: the Oracle baseline (`o1a2b3c4d5e6`)
landed days before this fix, so any Oracle deployment runs the corrected
writer against an effectively empty `entity_cooccurrences` — there is no
historical residue on Oracle to repair. PG-only matches the asymmetry of
the data, not negligence.
"""
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "b5d4e3f2a1c9"
down_revision: str | Sequence[str] | None = "o1a2b3c4d5e6"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_schema_prefix() -> str:
"""Get schema prefix for table names (required for multi-tenant support)."""
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Recompute last_cooccurred from the true event time per entity pair.
# COALESCE picks the first non-null of mentioned_at / occurred_start /
# created_at so banks without event-time metadata still see a sane value
# (equivalent to the pre-fix behaviour) instead of NULL.
#
# The self-join on `unit_entities` is O(k²) per memory_unit in the number
# of distinct entities mentioned (k). For typical units k is small (single
# digits), but a bank with units containing hundreds of entities and tens
# of millions of co-occurrence rows may want to run this off-hours — the
# whole UPDATE is one statement, so it locks every targeted ec row for
# the duration. The migration is one-time; subsequent online writes
# already carry event time via the writer fix.
op.execute(
f"""
UPDATE {schema}entity_cooccurrences ec
SET last_cooccurred = sub.event_time
FROM (
SELECT
LEAST(ue1.entity_id, ue2.entity_id) AS e1,
GREATEST(ue1.entity_id, ue2.entity_id) AS e2,
MAX(COALESCE(mu.mentioned_at, mu.occurred_start, mu.created_at)) AS event_time
FROM {schema}memory_units mu
JOIN {schema}unit_entities ue1 ON ue1.unit_id = mu.id
JOIN {schema}unit_entities ue2 ON ue2.unit_id = mu.id AND ue1.entity_id <> ue2.entity_id
GROUP BY 1, 2
) sub
WHERE ec.entity_id_1 = sub.e1 AND ec.entity_id_2 = sub.e2
"""
)
def _pg_downgrade() -> None:
# No-op: the previous column value was `now()` at the time of write and
# isn't recoverable. Rolling back the code is sufficient — new writes will
# revert to the old behaviour for subsequent retains.
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade) # oracle slot intentionally absent — see header
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "b7c4d8e9f1a2"
down_revision: str | Sequence[str] | None = "5a366d414dce"
@@ -19,7 +21,7 @@ branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add chunks table and link memory_units to chunks."""
# Create chunks table with single text PK (bank_id_document_id_chunk_index)
@@ -56,7 +58,7 @@ def upgrade() -> None:
op.create_index("idx_memory_units_chunk_id", "memory_units", ["chunk_id"])
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove chunks table and chunk_id from memory_units."""
# Drop index and foreign key from memory_units
@@ -68,3 +70,11 @@ def downgrade() -> None:
op.drop_index("idx_chunks_bank_id", table_name="chunks")
op.drop_index("idx_chunks_document_id", table_name="chunks")
op.drop_table("chunks")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
import sqlalchemy as sa
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "c1a2b3d4e5f6"
down_revision: str | Sequence[str] | None = "b4c5d6e7f8a9"
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
# pg_trgm ships with most PostgreSQL installations as a contrib module.
# It enables fast similarity lookups via GIN indexes, used for entity name matching.
# On managed services (e.g. Azure Flexible Server), the extension may not be
@@ -52,8 +54,16 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}entities_canonical_name_trgm_idx")
# Note: not dropping pg_trgm extension as other indexes may depend on it
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "c2d3e4f5g6h7"
down_revision: str | Sequence[str] | None = ("a3b4c5d6e7f8", "c8e5f2a3b4d1")
branch_labels: str | Sequence[str] | None = None
@@ -26,7 +28,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(
@@ -52,10 +54,18 @@ def upgrade() -> None:
op.execute(f"CREATE INDEX IF NOT EXISTS idx_audit_log_started ON {schema}audit_log (started_at DESC)")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_audit_log_started")
op.execute(f"DROP INDEX IF EXISTS {schema}idx_audit_log_bank_started")
op.execute(f"DROP INDEX IF EXISTS {schema}idx_audit_log_action_started")
op.execute(f"DROP TABLE IF EXISTS {schema}audit_log")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -9,6 +9,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "c3d4e5f6g7h8"
down_revision: str | Sequence[str] | None = ("a2b3c4d5e6f7", "a2b3c4d5e6f8")
branch_labels: str | Sequence[str] | None = None
@@ -20,11 +22,19 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}mental_models ADD COLUMN IF NOT EXISTS history JSONB DEFAULT '[]'::jsonb")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS history")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -28,6 +28,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "c4x5y6z7a8b9"
down_revision: str | Sequence[str] | None = "b3w4x5y6z7a8"
branch_labels: str | Sequence[str] | None = None
@@ -39,7 +41,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
mu = f"{schema}memory_units"
@@ -61,6 +63,14 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
# Deleted rows cannot be restored.
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "c5d6e7f8a9b0"
down_revision: str | Sequence[str] | None = "b3c4d5e6f7a8"
branch_labels: str | Sequence[str] | None = None
@@ -24,7 +26,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# 1. Add nullable column
@@ -43,6 +45,14 @@ def upgrade() -> None:
op.execute(f"ALTER TABLE {schema}memory_links ALTER COLUMN bank_id SET NOT NULL")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}memory_links DROP COLUMN IF EXISTS bank_id")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "c8e5f2a3b4d1"
down_revision: str | Sequence[str] | None = "b7c4d8e9f1a2"
@@ -19,7 +21,7 @@ branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add retain_params JSONB column to documents table."""
# Add retain_params column to store parameters passed during retain
@@ -29,7 +31,7 @@ def upgrade() -> None:
op.create_index("idx_documents_retain_params", "documents", ["retain_params"], postgresql_using="gin")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove retain_params column from documents table."""
# Drop index
@@ -37,3 +39,11 @@ def downgrade() -> None:
# Drop column
op.drop_column("documents", "retain_params")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -34,6 +34,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "d2e3f4a5b6c7"
down_revision: str | Sequence[str] | None = "b3c4d5e6f7g8"
branch_labels: str | Sequence[str] | None = None
@@ -45,7 +47,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
@@ -75,9 +77,17 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_links_entity_covering")
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_links_to_type_weight")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -18,6 +18,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "d4e5f6g7h8i9"
down_revision: str | Sequence[str] | None = "d5e6f7a8b9c0"
branch_labels: str | Sequence[str] | None = None
@@ -29,7 +31,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# DROP + CREATE CONCURRENTLY must run outside a transaction block.
op.execute("COMMIT")
@@ -42,7 +44,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute("COMMIT")
op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {schema}idx_memory_units_source_memory_ids")
@@ -51,3 +53,11 @@ def downgrade() -> None:
f"ON {schema}memory_units USING GIN (source_memory_ids) "
f"WHERE source_memory_ids IS NOT NULL"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -6,10 +6,11 @@ Create Date: 2026-03-11
This migration:
1. Adds internal_id UUID column to banks (stable identifier for index naming)
2. Drops the global vector index (competes with per-bank partial indexes)
3. Creates per-(bank_id, fact_type) partial vector indexes for all existing banks
using the configured vector extension (HNSW for pgvector, DiskANN for
pgvectorscale, vchordrq for vchord).
2. For non-ScaNN backends, drops the global vector index (competes with
per-bank partial indexes)
3. For non-ScaNN backends, creates per-(bank_id, fact_type) partial vector
indexes for all existing banks using the configured vector extension
(HNSW for pgvector, DiskANN for pgvectorscale, vchordrq for vchord).
(new banks get indexes created at bank-creation time via bank_utils.create_bank_vector_indexes)
Why per-(bank, fact_type) indexes:
@@ -17,6 +18,8 @@ Why per-(bank, fact_type) indexes:
clause, because the idx_memory_units_bank_id B-tree index always wins at planning time.
- Per-(bank, fact_type) partial indexes have both predicates matching → planner selects them.
- The global vector index competes for larger partitions (world, observation) and must be dropped.
- AlloyDB ScaNN uses global vector indexes with filtered vector search instead
because empty or tiny per-bank indexes cannot be built safely.
"""
import os
@@ -25,6 +28,8 @@ from collections.abc import Sequence
from alembic import context, op
from sqlalchemy import text
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "d5e6f7a8b9c0"
down_revision: str | Sequence[str] | None = "c3d4e5f6g7h8"
branch_labels: str | Sequence[str] | None = None
@@ -37,23 +42,31 @@ _FACT_TYPES: dict[str, str] = {
}
def _configured_vector_extension() -> str:
ext = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
if ext not in {"pgvector", "pgvectorscale", "vchord", "scann"}:
raise ValueError(
f"Invalid HINDSIGHT_API_VECTOR_EXTENSION: {ext}. Must be 'pgvector', 'vchord', 'pgvectorscale', or 'scann'"
)
return ext
def _vector_index_using_clause(ext: str) -> str:
if ext == "pgvectorscale":
return "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)"
if ext == "vchord":
return "USING vchordrq (embedding vector_l2_ops)"
if ext == "scann":
return "USING scann (embedding cosine) WITH (mode = 'AUTO')"
return "USING hnsw (embedding vector_cosine_ops)"
def _get_schema_prefix() -> str:
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def _vector_index_using_clause() -> str:
"""Return the USING clause based on the configured vector extension."""
ext = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
if ext == "pgvectorscale":
return "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)"
elif ext == "vchord":
return "USING vchordrq (embedding vector_l2_ops)"
else:
return "USING hnsw (embedding vector_cosine_ops)"
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# 1. Add internal_id column to banks
@@ -62,6 +75,14 @@ def upgrade() -> None:
)
op.execute(f"ALTER TABLE {schema}banks ADD CONSTRAINT banks_internal_id_unique UNIQUE (internal_id)")
ext = _configured_vector_extension()
if ext == "scann":
# ScaNN should keep/use a global vector index. Per-bank partial indexes
# are created while banks are empty and can fail AlloyDB's ScaNN build
# requirements, so this migration leaves vector index reconciliation to
# runtime ensure_vector_extension once enough rows exist.
return
# 2. Drop any fact_type-only partial indexes that may exist from prior migrations
# (bank_id B-tree always wins over them when bank_id is in the WHERE clause)
op.execute(f"DROP INDEX IF EXISTS {schema}idx_mu_emb_world")
@@ -77,7 +98,7 @@ def upgrade() -> None:
schema_name = context.config.get_main_option("target_schema")
table_ref = f'"{schema_name}".memory_units' if schema_name else "memory_units"
banks_ref = f'"{schema_name}".banks' if schema_name else "banks"
using_clause = _vector_index_using_clause()
using_clause = _vector_index_using_clause(ext)
rows = bind.execute(text(f"SELECT bank_id, internal_id FROM {banks_ref}")).fetchall() # noqa: S608
for row in rows:
@@ -96,7 +117,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
# Drop per-bank HNSW indexes (iterate existing banks)
@@ -107,7 +128,7 @@ def downgrade() -> None:
rows = bind.execute(text(f"SELECT internal_id FROM {banks_ref}")).fetchall() # noqa: S608
for row in rows:
internal_id = str(row[0]).replace("-", "")[:16]
for ft_short in _HNSW_FACT_TYPES.values():
for ft_short in _FACT_TYPES.values():
idx_name = f"idx_mu_emb_{ft_short}_{internal_id}"
bind.execute(text(f"DROP INDEX IF EXISTS {schema}{idx_name}"))
@@ -137,3 +158,11 @@ def downgrade() -> None:
# Drop internal_id column
op.execute(f"ALTER TABLE {schema}banks DROP CONSTRAINT IF EXISTS banks_internal_id_unique")
op.execute(f"ALTER TABLE {schema}banks DROP COLUMN IF EXISTS internal_id")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,67 @@
"""Backfill mental_models.subtype for databases that ran h3c4d5e6f7g8 before the fix
Migration h3c4d5e6f7g8 used CREATE TABLE IF NOT EXISTS to create the
mental_models table with a subtype column. But on databases where the table
already existed (from the reflections -> mental_models rename chain), the
CREATE was a no-op and subtype was never added. A fix was later added to
h3c4d5e6f7g8 (Step 4b), but databases that had already run the migration
never re-execute it. This migration adds the missing columns idempotently.
Revision ID: d5y6z7a8b9c0
Revises: 8c6fa6f7230b
Create Date: 2026-04-18
"""
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "d5y6z7a8b9c0"
down_revision: str | Sequence[str] | None = "8c6fa6f7230b"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_schema_prefix() -> str:
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Add columns that h3c4d5e6f7g8 intended to create but missed when
# the table already existed from the reflections rename chain.
for col_ddl in [
"subtype VARCHAR(32) NOT NULL DEFAULT 'structural'",
"description TEXT NOT NULL DEFAULT ''",
"entity_id UUID",
"observations JSONB DEFAULT '{\"observations\": []}'::jsonb",
"links VARCHAR[]",
"last_updated TIMESTAMP WITH TIME ZONE",
]:
op.execute(f"ALTER TABLE {schema}mental_models ADD COLUMN IF NOT EXISTS {col_ddl}")
# Ensure the CHECK constraint exists
op.execute(f"ALTER TABLE {schema}mental_models DROP CONSTRAINT IF EXISTS ck_mental_models_subtype")
op.execute(f"""
ALTER TABLE {schema}mental_models
ADD CONSTRAINT ck_mental_models_subtype CHECK (subtype IN ('structural', 'emergent', 'pinned', 'learned'))
""")
op.execute(f"CREATE INDEX IF NOT EXISTS idx_mental_models_subtype ON {schema}mental_models(bank_id, subtype)")
def _pg_downgrade() -> None:
# No-op: these columns are part of the intended schema
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -17,6 +17,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "d6e7f8a9b0c1"
down_revision: str | Sequence[str] | None = ("c2d3e4f5g6h7", "c5d6e7f8a9b0")
branch_labels: str | Sequence[str] | None = None
@@ -29,11 +31,19 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}documents DROP COLUMN IF EXISTS metadata")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}documents ADD COLUMN IF NOT EXISTS metadata jsonb DEFAULT '{{}}'")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -8,6 +8,8 @@ Create Date: 2024-12-04 15:00:00.000000
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision = "d9f6a3b4c5e2"
down_revision = "c8e5f2a3b4d1"
@@ -21,7 +23,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade():
def _pg_upgrade():
schema = _get_schema_prefix()
# Drop old check constraint FIRST (before updating data)
@@ -38,7 +40,7 @@ def upgrade():
)
def downgrade():
def _pg_downgrade():
schema = _get_schema_prefix()
# Drop new check constraint FIRST
@@ -51,3 +53,11 @@ def downgrade():
op.create_check_constraint(
"memory_units_fact_type_check", "memory_units", "fact_type IN ('world', 'bank', 'opinion', 'observation')"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
import sqlalchemy as sa
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "e0a1b2c3d4e5"
down_revision: str | Sequence[str] | None = "rename_personality"
@@ -33,7 +35,7 @@ def _get_target_schema() -> str:
return schema if schema else "public"
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Convert Big Five disposition to 3-trait disposition."""
conn = op.get_bind()
schema = _get_schema_prefix()
@@ -75,7 +77,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Convert back to Big Five disposition."""
conn = op.get_bind()
schema = _get_schema_prefix()
@@ -109,3 +111,11 @@ def downgrade() -> None:
ALTER COLUMN disposition SET DEFAULT '{{"openness": 0.5, "conscientiousness": 0.5, "extraversion": 0.5, "agreeableness": 0.5, "neuroticism": 0.5, "bias_strength": 0.5}}'::jsonb
""")
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "e4f5a6b7c8d9"
down_revision: str | Sequence[str] | None = "d2e3f4a5b6c7"
branch_labels: str | Sequence[str] | None = None
@@ -23,7 +25,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(
@@ -54,9 +56,17 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_async_operations_status_retry")
op.execute(f"ALTER TABLE {schema}async_operations DROP COLUMN IF EXISTS next_retry_at")
op.execute(f"DROP INDEX IF EXISTS {schema}idx_webhooks_bank_id")
op.execute(f"DROP TABLE IF EXISTS {schema}webhooks")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "e5f6g7h8i9j0"
down_revision: str | Sequence[str] | None = "d4e5f6g7h8i9"
branch_labels: str | Sequence[str] | None = None
@@ -24,7 +26,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Remove orphaned async_operations rows whose bank no longer exists
@@ -67,7 +69,15 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}async_operations DROP CONSTRAINT IF EXISTS fk_async_operations_bank_id")
op.execute(f"ALTER TABLE {schema}webhooks DROP CONSTRAINT IF EXISTS fk_webhooks_bank_id")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "f1a2b3c4d5e6"
down_revision: str | Sequence[str] | None = "e0a1b2c3d4e5"
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add composite index for efficient graph retrieval edge loading."""
schema = _get_schema_prefix()
# Create composite index for efficient top-k per (from_node, link_type) queries
@@ -38,7 +40,15 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove the composite index."""
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_memory_links_from_type_weight")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -10,6 +10,8 @@ from collections.abc import Sequence
from alembic import op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "f6g7h8i9j0k1"
down_revision: str | Sequence[str] | None = "e5f6g7h8i9j0"
@@ -17,7 +19,7 @@ branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Change memory_units.chunk_id FK from SET NULL to CASCADE.
When a document is deleted the CASCADE reaches chunks first; with SET NULL
@@ -49,9 +51,17 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert to SET NULL behaviour."""
op.drop_constraint("memory_units_chunk_fkey", "memory_units", type_="foreignkey")
op.create_foreign_key(
"memory_units_chunk_fkey", "memory_units", "chunks", ["chunk_id"], ["chunk_id"], ondelete="SET NULL"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "f7g8h9i0j1k2"
down_revision: str | Sequence[str] | None = "e4f5a6b7c8d9"
branch_labels: str | Sequence[str] | None = None
@@ -23,11 +25,19 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}webhooks ADD COLUMN IF NOT EXISTS http_config JSONB NOT NULL DEFAULT '{{}}'")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}webhooks DROP COLUMN IF EXISTS http_config")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "g2a3b4c5d6e7"
down_revision: str | Sequence[str] | None = "f1a2b3c4d5e6"
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add tags column to memory_units and documents tables."""
schema = _get_schema_prefix()
@@ -39,10 +41,18 @@ def upgrade() -> None:
op.execute(f"ALTER TABLE {schema}documents ADD COLUMN IF NOT EXISTS tags VARCHAR[] NOT NULL DEFAULT '{{}}'")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove tags columns and index."""
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_memory_units_tags")
op.execute(f"ALTER TABLE {schema}memory_units DROP COLUMN IF EXISTS tags")
op.execute(f"ALTER TABLE {schema}documents DROP COLUMN IF EXISTS tags")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "g2h3i4j5k6l7"
down_revision: str | Sequence[str] | None = "f1a2b3c4d5e6"
@@ -26,7 +28,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# 1. Delete any remaining opinion rows
@@ -49,7 +51,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
# Restore confidence_score column
@@ -81,3 +83,11 @@ def downgrade() -> None:
f"CREATE INDEX idx_memory_units_opinion_date ON {schema}memory_units "
f"(bank_id, event_date DESC) WHERE fact_type = 'opinion'"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -22,6 +22,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "g7h8i9j0k1l2"
down_revision: str | Sequence[str] | None = "f6g7h8i9j0k1"
branch_labels: str | Sequence[str] | None = None
@@ -33,7 +35,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
mu = f"{schema}memory_units"
banks = f"{schema}banks"
@@ -66,6 +68,14 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
# Deleted rows cannot be restored.
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -17,6 +17,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "h3c4d5e6f7g8"
down_revision: str | Sequence[str] | None = "g2a3b4c5d6e7"
@@ -30,7 +32,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Apply mental models v4 changes."""
schema = _get_schema_prefix()
@@ -85,6 +87,26 @@ def upgrade() -> None:
)
""")
# Step 4b: If the table already existed (from reflections rename chain),
# it won't have the v4 columns. Add them idempotently so the migration
# works regardless of whether CREATE TABLE above was a no-op.
for col_ddl in [
"subtype VARCHAR(32) NOT NULL DEFAULT 'directive'",
"description TEXT NOT NULL DEFAULT ''",
"entity_id UUID",
"observations JSONB DEFAULT '{\"observations\": []}'::jsonb",
"links VARCHAR[]",
"last_updated TIMESTAMP WITH TIME ZONE",
]:
op.execute(f"ALTER TABLE {schema}mental_models ADD COLUMN IF NOT EXISTS {col_ddl}")
# Ensure the subtype CHECK constraint exists (may not if table was renamed)
op.execute(f"ALTER TABLE {schema}mental_models DROP CONSTRAINT IF EXISTS ck_mental_models_subtype")
op.execute(f"""
ALTER TABLE {schema}mental_models
ADD CONSTRAINT ck_mental_models_subtype CHECK (subtype IN ('structural', 'emergent', 'pinned', 'learned'))
""")
# Step 5: Create indexes for efficient queries (if not exist)
op.execute(f"CREATE INDEX IF NOT EXISTS idx_mental_models_bank_id ON {schema}mental_models(bank_id)")
op.execute(f"CREATE INDEX IF NOT EXISTS idx_mental_models_subtype ON {schema}mental_models(bank_id, subtype)")
@@ -93,7 +115,7 @@ def upgrade() -> None:
op.execute(f"CREATE INDEX IF NOT EXISTS idx_mental_models_tags ON {schema}mental_models USING GIN(tags)")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert mental models v4 changes."""
schema = _get_schema_prefix()
@@ -110,3 +132,11 @@ def downgrade() -> None:
op.execute(f"ALTER TABLE {schema}banks DROP COLUMN IF EXISTS mission")
# Note: Cannot restore deleted observations - they are lost on downgrade
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "h3i4j5k6l7m8"
down_revision: str | Sequence[str] | None = ("a4b5c6d7e8f9", "g2h3i4j5k6l7")
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Composite index enables index-only scans for entity_id -> unit_id lookups
op.execute(
@@ -35,8 +37,16 @@ def upgrade() -> None:
op.execute(f"DROP INDEX IF EXISTS {schema}idx_unit_entities_entity")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_unit_entities_entity_unit")
# Restore the single-column index
op.execute(f"CREATE INDEX IF NOT EXISTS idx_unit_entities_entity ON {schema}unit_entities (entity_id)")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "i4d5e6f7g8h9"
down_revision: str | Sequence[str] | None = "h3c4d5e6f7g8"
@@ -26,7 +28,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Delete opinion memory_units."""
schema = _get_schema_prefix()
@@ -35,7 +37,15 @@ def upgrade() -> None:
op.execute(f"DELETE FROM {schema}memory_units WHERE fact_type = 'opinion'")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Cannot restore deleted opinions."""
# Note: Cannot restore deleted opinions - they are lost on downgrade
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,49 @@
"""Add 'cancelled' to async_operations status check constraint
Revision ID: i4j5k6l7m8n9
Revises: d5y6z7a8b9c0
Create Date: 2026-04-23
"""
from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "i4j5k6l7m8n9"
down_revision: str | Sequence[str] | None = "d5y6z7a8b9c0"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_schema_prefix() -> str:
"""Get schema prefix for table names (required for multi-tenant support)."""
schema = context.config.get_main_option("target_schema")
return f'"{schema}".' if schema else ""
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}async_operations DROP CONSTRAINT IF EXISTS async_operations_status_check")
op.execute(
f"ALTER TABLE {schema}async_operations ADD CONSTRAINT async_operations_status_check "
f"CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled'))"
)
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}async_operations DROP CONSTRAINT IF EXISTS async_operations_status_check")
op.execute(
f"ALTER TABLE {schema}async_operations ADD CONSTRAINT async_operations_status_check "
f"CHECK (status IN ('pending', 'processing', 'completed', 'failed'))"
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -15,6 +15,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "j5e6f7g8h9i0"
down_revision: str | Sequence[str] | None = "i4d5e6f7g8h9"
@@ -28,7 +30,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Create mental_model_versions table and add version tracking."""
schema = _get_schema_prefix()
@@ -81,7 +83,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove mental_model_versions table and version column."""
schema = _get_schema_prefix()
@@ -93,3 +95,11 @@ def downgrade() -> None:
# Remove version column from mental_models
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS version")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "k6f7g8h9i0j1"
down_revision: str | Sequence[str] | None = "j5e6f7g8h9i0"
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add 'directive' to mental_models subtype constraint."""
schema = _get_schema_prefix()
@@ -40,7 +42,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove 'directive' from mental_models subtype constraint."""
schema = _get_schema_prefix()
@@ -56,3 +58,11 @@ def downgrade() -> None:
ADD CONSTRAINT ck_mental_models_subtype
CHECK (subtype IN ('structural', 'emergent', 'pinned', 'learned'))
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,38 @@
"""No-op: observation_sources table is Oracle-only
Originally created the observation_sources junction table for all backends,
but PG uses native array ops on the source_memory_ids column (faster at scale).
Oracle creates this table in the o1a2b3c4d5e6 baseline migration instead.
Kept as a no-op to preserve the Alembic revision chain.
Revision ID: k6l7m8n9o0p1
Revises: i4j5k6l7m8n9
Create Date: 2026-04-24
"""
from collections.abc import Sequence
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "k6l7m8n9o0p1"
down_revision: str | Sequence[str] | None = "i4j5k6l7m8n9"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _pg_upgrade() -> None:
# PG uses source_memory_ids[] array on memory_units — no junction table.
pass
def _pg_downgrade() -> None:
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -17,6 +17,8 @@ import sqlalchemy as sa
from alembic import context, op
from sqlalchemy.dialects import postgresql
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "l7g8h9i0j1k2"
down_revision: str | Sequence[str] | None = "k6f7g8h9i0j1"
@@ -30,7 +32,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add worker columns to async_operations."""
schema = _get_schema_prefix()
@@ -78,7 +80,7 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove worker columns from async_operations."""
schema = _get_schema_prefix()
@@ -107,3 +109,11 @@ def downgrade() -> None:
"worker_id",
schema=context.config.get_main_option("target_schema") or None,
)
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,31 @@
"""Merge divergent heads from deferrable FK and cooccurrence backfill
Revision ID: m3rg3h3ad5f6
Revises: 9f8e7d6c5b4a, b5d4e3f2a1c9
Create Date: 2026-05-04
"""
from collections.abc import Sequence
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "m3rg3h3ad5f6"
down_revision: tuple[str, ...] = ("9f8e7d6c5b4a", "b5d4e3f2a1c9")
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _pg_upgrade() -> None:
pass
def _pg_downgrade() -> None:
pass
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "m8h9i0j1k2l3"
down_revision: str | Sequence[str] | None = "l7g8h9i0j1k2"
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Change mental_models.id from VARCHAR(64) to TEXT."""
schema = _get_schema_prefix()
@@ -33,9 +35,17 @@ def upgrade() -> None:
op.execute(f"ALTER TABLE {schema}mental_models ALTER COLUMN id TYPE TEXT")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert mental_models.id from TEXT to VARCHAR(64)."""
schema = _get_schema_prefix()
# Note: This may fail if any id values exceed 64 characters
op.execute(f"ALTER TABLE {schema}mental_models ALTER COLUMN id TYPE VARCHAR(64)")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -16,6 +16,8 @@ from collections.abc import Sequence
from alembic import context, op
from sqlalchemy import text
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "n9i0j1k2l3m4"
down_revision: str | Sequence[str] | None = "m8h9i0j1k2l3"
@@ -30,53 +32,65 @@ def _get_schema_prefix() -> str:
def _detect_vector_extension() -> str:
"""
Detect or validate vector extension: 'pgvector', 'vchord', or 'pgvectorscale'.
Respects HINDSIGHT_API_VECTOR_EXTENSION env var if set.
"""
"""Detect or validate vector extension for this immutable migration revision."""
conn = op.get_bind()
vector_extension = os.getenv("HINDSIGHT_API_VECTOR_EXTENSION", "pgvector").lower()
# Validate configured extension is installed
if vector_extension == "pgvectorscale":
# pgvectorscale/DiskANN requires pgvector
pgvector_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vector'")).scalar()
if not pgvector_check:
raise RuntimeError(
"DiskANN requires pgvector. Install with: CREATE EXTENSION vector; then vectorscale or pg_diskann CASCADE;"
)
# Check for either vectorscale (open source) or pg_diskann (Azure)
vectorscale_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vectorscale'")).scalar()
pg_diskann_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'pg_diskann'")).scalar()
if vectorscale_check:
return "pgvectorscale"
elif pg_diskann_check:
if pg_diskann_check:
return "pg_diskann"
else:
raise RuntimeError(
"Configured vector extension 'pgvectorscale' not found. Install either:\n"
" - pgvectorscale: CREATE EXTENSION vectorscale CASCADE;\n"
" - pg_diskann (Azure): CREATE EXTENSION pg_diskann CASCADE;"
)
elif vector_extension == "vchord":
raise RuntimeError(
"Configured vector extension 'pgvectorscale' not found. Install either:\n"
" - pgvectorscale: CREATE EXTENSION vectorscale CASCADE;\n"
" - pg_diskann (Azure): CREATE EXTENSION pg_diskann CASCADE;"
)
if vector_extension == "vchord":
vchord_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vchord'")).scalar()
if not vchord_check:
raise RuntimeError(
"Configured vector extension 'vchord' not found. Install it with: CREATE EXTENSION vchord CASCADE;"
)
return "vchord"
elif vector_extension == "pgvector":
if vector_extension == "scann":
scann_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'alloydb_scann'")).scalar()
if not scann_check:
raise RuntimeError(
"Configured vector extension 'scann' not found. Install it with: CREATE EXTENSION alloydb_scann CASCADE;"
)
return "scann"
if vector_extension == "pgvector":
pgvector_check = conn.execute(text("SELECT 1 FROM pg_extension WHERE extname = 'vector'")).scalar()
if not pgvector_check:
raise RuntimeError(
"Configured vector extension 'pgvector' not found. Install it with: CREATE EXTENSION vector;"
)
return "pgvector"
else:
raise ValueError(
f"Invalid HINDSIGHT_API_VECTOR_EXTENSION: {vector_extension}. Must be 'pgvector', 'vchord', or 'pgvectorscale'"
)
raise ValueError(
"Invalid HINDSIGHT_API_VECTOR_EXTENSION: "
f"{vector_extension}. Must be 'pgvector', 'vchord', 'pgvectorscale', or 'scann'"
)
def _vector_index_using_clause(ext: str) -> str:
if ext == "pgvectorscale":
return "USING diskann (embedding vector_cosine_ops) WITH (num_neighbors = 50)"
if ext == "pg_diskann":
return "USING diskann (embedding vector_cosine_ops) WITH (max_neighbors = 50)"
if ext == "vchord":
return "USING vchordrq (embedding vector_l2_ops)"
if ext == "scann":
return "USING scann (embedding cosine) WITH (mode = 'AUTO')"
return "USING hnsw (embedding vector_cosine_ops)"
def _detect_text_search_extension() -> str:
@@ -119,7 +133,7 @@ def _detect_text_search_extension() -> str:
)
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Create learnings and pinned_reflections tables."""
schema = _get_schema_prefix()
@@ -156,28 +170,12 @@ def upgrade() -> None:
# Indexes for learnings
op.execute(f"CREATE INDEX idx_learnings_bank_id ON {schema}learnings(bank_id)")
# Create vector index based on detected extension
if vector_ext == "pgvectorscale":
# Create vector index based on detected extension. ScaNN is deferred because
# this table is empty during migration and AlloyDB rejects empty ScaNN builds.
if vector_ext != "scann":
op.execute(f"""
CREATE INDEX idx_learnings_embedding ON {schema}learnings
USING diskann (embedding vector_cosine_ops)
WITH (num_neighbors = 50)
""")
elif vector_ext == "pg_diskann":
op.execute(f"""
CREATE INDEX idx_learnings_embedding ON {schema}learnings
USING diskann (embedding vector_cosine_ops)
WITH (max_neighbors = 50)
""")
elif vector_ext == "vchord":
op.execute(f"""
CREATE INDEX idx_learnings_embedding ON {schema}learnings
USING vchordrq (embedding vector_l2_ops)
""")
else: # pgvector
op.execute(f"""
CREATE INDEX idx_learnings_embedding ON {schema}learnings
USING hnsw (embedding vector_cosine_ops)
{_vector_index_using_clause(vector_ext)}
""")
op.execute(f"CREATE INDEX idx_learnings_tags ON {schema}learnings USING GIN(tags)")
@@ -235,28 +233,12 @@ def upgrade() -> None:
# Indexes for pinned_reflections
op.execute(f"CREATE INDEX idx_pinned_reflections_bank_id ON {schema}pinned_reflections(bank_id)")
# Create vector index based on detected extension
if vector_ext == "pgvectorscale":
# Create vector index based on detected extension. ScaNN is deferred because
# this table is empty during migration and AlloyDB rejects empty ScaNN builds.
if vector_ext != "scann":
op.execute(f"""
CREATE INDEX idx_pinned_reflections_embedding ON {schema}pinned_reflections
USING diskann (embedding vector_cosine_ops)
WITH (num_neighbors = 50)
""")
elif vector_ext == "pg_diskann":
op.execute(f"""
CREATE INDEX idx_pinned_reflections_embedding ON {schema}pinned_reflections
USING diskann (embedding vector_cosine_ops)
WITH (max_neighbors = 50)
""")
elif vector_ext == "vchord":
op.execute(f"""
CREATE INDEX idx_pinned_reflections_embedding ON {schema}pinned_reflections
USING vchordrq (embedding vector_l2_ops)
""")
else: # pgvector
op.execute(f"""
CREATE INDEX idx_pinned_reflections_embedding ON {schema}pinned_reflections
USING hnsw (embedding vector_cosine_ops)
{_vector_index_using_clause(vector_ext)}
""")
op.execute(f"CREATE INDEX idx_pinned_reflections_tags ON {schema}pinned_reflections USING GIN(tags)")
@@ -304,7 +286,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Drop learnings and pinned_reflections tables."""
schema = _get_schema_prefix()
@@ -315,3 +297,11 @@ def downgrade() -> None:
# Remove columns from banks
op.execute(f"ALTER TABLE {schema}banks DROP COLUMN IF EXISTS last_consolidated_at")
op.execute(f"ALTER TABLE {schema}banks DROP COLUMN IF EXISTS mission_changed_at")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -16,6 +16,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "o0j1k2l3m4n5"
down_revision: str | Sequence[str] | None = "n9i0j1k2l3m4"
@@ -29,7 +31,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Migrate data and clean up old mental models."""
schema = _get_schema_prefix()
@@ -80,15 +82,17 @@ def upgrade() -> None:
# 4. Drop the mental_model_versions table (no longer used)
op.execute(f"DROP TABLE IF EXISTS {schema}mental_model_versions CASCADE")
# 5. Drop old constraints and add new one that only allows 'directive'
# 5. Drop old constraints and add new one that allows current subtypes.
# 'pinned' is still used by the code for user-created mental models;
# 'directive' is used for system directives.
op.execute(f"ALTER TABLE {schema}mental_models DROP CONSTRAINT IF EXISTS ck_mental_models_subtype")
op.execute(f"""
ALTER TABLE {schema}mental_models
ADD CONSTRAINT ck_mental_models_subtype CHECK (subtype = 'directive')
ADD CONSTRAINT ck_mental_models_subtype CHECK (subtype IN ('directive', 'pinned'))
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Reverse the migration (data migration is one-way, so this just removes constraints)."""
schema = _get_schema_prefix()
@@ -111,3 +115,11 @@ def downgrade() -> None:
)
# Note: Data migration cannot be reversed - pinned_reflections and learnings data remains
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -0,0 +1,445 @@
"""oracle_baseline
Brings a fresh Oracle 23ai database up to the current schema in a single step.
PostgreSQL is a no-op here — the prior 59 revisions already build the PG schema
incrementally; this revision just closes the loop so both dialects share a
single head from this point on.
After this migration ships, *every* new revision must fill both the ``_pg_*``
and ``_oracle_*`` slots (or explicitly leave one ``None``); a CI check enforces
that.
Tables mirror the PostgreSQL schema but use Oracle-native types:
- UUID -> RAW(16) DEFAULT SYS_GUID()
- TEXT / large VARCHAR -> CLOB
- JSONB -> CLOB with IS JSON CHECK
- BOOLEAN -> NUMBER(1)
- FLOAT -> BINARY_DOUBLE
- VARCHAR[] -> CLOB (JSON array stored as string)
- BYTEA -> BLOB
- vector(384) -> VECTOR(384, FLOAT32) (Oracle 23ai native)
Revision ID: o1a2b3c4d5e6
Revises: k6l7m8n9o0p1
Create Date: 2026-04-29
"""
from collections.abc import Sequence
from alembic import op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "o1a2b3c4d5e6"
down_revision: str | Sequence[str] | None = "k6l7m8n9o0p1"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
# ---------------------------------------------------------------------------
# Tables — created in dependency order
# ---------------------------------------------------------------------------
_TABLES: tuple[str, ...] = (
"""
CREATE TABLE IF NOT EXISTS banks (
bank_id VARCHAR2(256) NOT NULL,
internal_id RAW(16) DEFAULT SYS_GUID() NOT NULL,
name VARCHAR2(512),
disposition CLOB DEFAULT '{"skepticism":3,"literalism":3,"empathy":3}' NOT NULL
CONSTRAINT banks_disposition_json CHECK (disposition IS JSON),
mission CLOB,
personality CLOB DEFAULT '{}' NOT NULL
CONSTRAINT banks_personality_json CHECK (personality IS JSON),
config CLOB DEFAULT '{}' NOT NULL
CONSTRAINT banks_config_json CHECK (config IS JSON),
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_banks PRIMARY KEY (bank_id),
CONSTRAINT banks_internal_id_unique UNIQUE (internal_id)
)
""",
"""
CREATE TABLE IF NOT EXISTS documents (
id VARCHAR2(512) NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
original_text CLOB,
content_hash VARCHAR2(128),
metadata CLOB DEFAULT '{}' NOT NULL
CONSTRAINT docs_metadata_json CHECK (metadata IS JSON),
retain_params CLOB CONSTRAINT docs_retain_params_json CHECK (retain_params IS JSON OR retain_params IS NULL),
file_storage_key VARCHAR2(512),
file_original_name VARCHAR2(512),
file_content_type VARCHAR2(256),
tags CLOB DEFAULT '[]' NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_documents PRIMARY KEY (id, bank_id),
CONSTRAINT fk_documents_bank FOREIGN KEY (bank_id) REFERENCES banks(bank_id) ON DELETE CASCADE
)
""",
"""
CREATE TABLE IF NOT EXISTS chunks (
chunk_id VARCHAR2(512) NOT NULL,
document_id VARCHAR2(512) NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
chunk_index NUMBER(10) NOT NULL,
chunk_text CLOB NOT NULL,
content_hash VARCHAR2(128),
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_chunks PRIMARY KEY (chunk_id),
CONSTRAINT fk_chunks_document FOREIGN KEY (document_id, bank_id)
REFERENCES documents(id, bank_id) ON DELETE CASCADE
)
""",
# memory_units uses automatic list partitioning on bank_id at create time —
# no post-create ALTER required (we used to do that for legacy installs).
"""
CREATE TABLE IF NOT EXISTS memory_units (
id RAW(16) DEFAULT SYS_GUID() NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
document_id VARCHAR2(512),
chunk_id VARCHAR2(512),
text CLOB NOT NULL,
embedding VECTOR(384, FLOAT32),
context CLOB,
event_date TIMESTAMP WITH TIME ZONE NOT NULL,
occurred_start TIMESTAMP WITH TIME ZONE,
occurred_end TIMESTAMP WITH TIME ZONE,
mentioned_at TIMESTAMP WITH TIME ZONE,
fact_type VARCHAR2(64) DEFAULT 'world' NOT NULL,
confidence_score BINARY_DOUBLE,
access_count NUMBER(10) DEFAULT 0 NOT NULL,
consolidated_at TIMESTAMP WITH TIME ZONE,
observation_scopes CLOB CONSTRAINT mu_obs_scopes_json CHECK (observation_scopes IS JSON OR observation_scopes IS NULL),
tags CLOB DEFAULT '[]' NOT NULL,
metadata CLOB DEFAULT '{}' NOT NULL
CONSTRAINT mu_metadata_json CHECK (metadata IS JSON),
proof_count NUMBER(10) DEFAULT 1,
source_memory_ids CLOB,
history CLOB DEFAULT '[]'
CONSTRAINT mu_history_json CHECK (history IS JSON OR history IS NULL),
text_signals CLOB,
consolidation_failed_at TIMESTAMP WITH TIME ZONE,
search_vector CLOB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_memory_units PRIMARY KEY (id),
CONSTRAINT fk_mu_document FOREIGN KEY (document_id, bank_id)
REFERENCES documents(id, bank_id) ON DELETE CASCADE,
CONSTRAINT fk_mu_chunk FOREIGN KEY (chunk_id)
REFERENCES chunks(chunk_id) ON DELETE SET NULL,
CONSTRAINT chk_mu_fact_type CHECK (fact_type IN ('world', 'experience', 'observation')),
CONSTRAINT chk_mu_confidence CHECK (
confidence_score IS NULL
OR (confidence_score >= 0.0 AND confidence_score <= 1.0)
)
)
PARTITION BY LIST (bank_id) AUTOMATIC
(PARTITION p_default VALUES ('__default__'))
""",
"""
CREATE TABLE IF NOT EXISTS entities (
id RAW(16) DEFAULT SYS_GUID() NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
canonical_name VARCHAR2(512) NOT NULL,
metadata CLOB DEFAULT '{}' NOT NULL
CONSTRAINT ent_metadata_json CHECK (metadata IS JSON),
first_seen TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
last_seen TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
mention_count NUMBER(10) DEFAULT 1 NOT NULL,
CONSTRAINT pk_entities PRIMARY KEY (id)
)
""",
"""
CREATE TABLE IF NOT EXISTS unit_entities (
unit_id RAW(16) NOT NULL,
entity_id RAW(16) NOT NULL,
CONSTRAINT pk_unit_entities PRIMARY KEY (unit_id, entity_id),
CONSTRAINT fk_ue_unit FOREIGN KEY (unit_id) REFERENCES memory_units(id) ON DELETE CASCADE,
CONSTRAINT fk_ue_entity FOREIGN KEY (entity_id) REFERENCES entities(id) ON DELETE CASCADE
)
""",
"""
CREATE TABLE IF NOT EXISTS entity_cooccurrences (
entity_id_1 RAW(16) NOT NULL,
entity_id_2 RAW(16) NOT NULL,
cooccurrence_count NUMBER(10) DEFAULT 1 NOT NULL,
last_cooccurred TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_entity_cooccurrences PRIMARY KEY (entity_id_1, entity_id_2),
CONSTRAINT fk_ec_entity1 FOREIGN KEY (entity_id_1) REFERENCES entities(id) ON DELETE CASCADE,
CONSTRAINT fk_ec_entity2 FOREIGN KEY (entity_id_2) REFERENCES entities(id) ON DELETE CASCADE
)
""",
"""
CREATE TABLE IF NOT EXISTS memory_links (
from_unit_id RAW(16) NOT NULL,
to_unit_id RAW(16) NOT NULL,
link_type VARCHAR2(64) NOT NULL,
entity_id RAW(16),
bank_id VARCHAR2(256),
weight BINARY_DOUBLE DEFAULT 1.0 NOT NULL,
source_memory_ids CLOB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT fk_ml_from FOREIGN KEY (from_unit_id) REFERENCES memory_units(id) ON DELETE CASCADE,
CONSTRAINT fk_ml_to FOREIGN KEY (to_unit_id) REFERENCES memory_units(id) ON DELETE CASCADE,
CONSTRAINT fk_ml_entity FOREIGN KEY (entity_id) REFERENCES entities(id) ON DELETE CASCADE,
CONSTRAINT chk_ml_link_type CHECK (
link_type IN ('temporal', 'semantic', 'entity', 'causes', 'caused_by', 'enables', 'prevents')
),
CONSTRAINT chk_ml_weight CHECK (weight >= 0.0 AND weight <= 1.0)
)
""",
"""
CREATE TABLE IF NOT EXISTS mental_models (
id VARCHAR2(256) NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
subtype VARCHAR2(32) NOT NULL,
name VARCHAR2(256) NOT NULL,
description CLOB NOT NULL,
source_query CLOB,
content CLOB,
embedding VECTOR(384, FLOAT32),
entity_id RAW(16),
observations CLOB DEFAULT '{"observations":[]}' NOT NULL
CONSTRAINT mm_obs_json CHECK (observations IS JSON),
links CLOB,
tags CLOB DEFAULT '[]' NOT NULL,
max_tokens NUMBER(10) DEFAULT 2048 NOT NULL,
"trigger" CLOB DEFAULT '{"refresh_after_consolidation":false}' NOT NULL
CONSTRAINT mm_trigger_json CHECK ("trigger" IS JSON),
structured_content CLOB CONSTRAINT mm_sc_json CHECK (structured_content IS JSON OR structured_content IS NULL),
last_refreshed_source_query CLOB,
reflect_response CLOB CONSTRAINT mm_reflect_resp_json CHECK (reflect_response IS JSON OR reflect_response IS NULL),
history CLOB DEFAULT '[]' NOT NULL
CONSTRAINT mm_history_json CHECK (history IS JSON),
last_refreshed_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
last_updated TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_mental_models PRIMARY KEY (id, bank_id),
CONSTRAINT fk_mm_bank FOREIGN KEY (bank_id) REFERENCES banks(bank_id) ON DELETE CASCADE,
CONSTRAINT fk_mm_entity FOREIGN KEY (entity_id) REFERENCES entities(id) ON DELETE SET NULL,
CONSTRAINT chk_mm_subtype CHECK (subtype IN ('directive', 'pinned'))
)
""",
"""
CREATE TABLE IF NOT EXISTS directives (
id RAW(16) DEFAULT SYS_GUID() NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
name VARCHAR2(256) NOT NULL,
content CLOB NOT NULL,
priority NUMBER(10) DEFAULT 0 NOT NULL,
is_active NUMBER(1) DEFAULT 1 NOT NULL,
tags CLOB DEFAULT '[]' NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_directives PRIMARY KEY (id),
CONSTRAINT fk_dir_bank FOREIGN KEY (bank_id) REFERENCES banks(bank_id) ON DELETE CASCADE
)
""",
"""
CREATE TABLE IF NOT EXISTS async_operations (
operation_id RAW(16) DEFAULT SYS_GUID() NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
operation_type VARCHAR2(128) NOT NULL,
status VARCHAR2(32) DEFAULT 'pending' NOT NULL,
worker_id VARCHAR2(256),
claimed_at TIMESTAMP WITH TIME ZONE,
retry_count NUMBER(10) DEFAULT 0 NOT NULL,
next_retry_at TIMESTAMP WITH TIME ZONE,
task_payload CLOB CONSTRAINT ao_payload_json CHECK (task_payload IS JSON OR task_payload IS NULL),
result_metadata CLOB DEFAULT '{}' NOT NULL
CONSTRAINT ao_result_json CHECK (result_metadata IS JSON),
error_message CLOB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
completed_at TIMESTAMP WITH TIME ZONE,
CONSTRAINT pk_async_operations PRIMARY KEY (operation_id),
CONSTRAINT fk_ao_bank FOREIGN KEY (bank_id) REFERENCES banks(bank_id) ON DELETE CASCADE,
CONSTRAINT chk_ao_status CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled'))
)
""",
"""
CREATE TABLE IF NOT EXISTS webhooks (
id RAW(16) DEFAULT SYS_GUID() NOT NULL,
bank_id VARCHAR2(256) NOT NULL,
url VARCHAR2(2048) NOT NULL,
secret VARCHAR2(512),
event_types CLOB DEFAULT '[]' NOT NULL,
http_config CLOB DEFAULT '{}' NOT NULL
CONSTRAINT wh_http_config_json CHECK (http_config IS JSON),
enabled NUMBER(1) DEFAULT 1 NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
CONSTRAINT pk_webhooks PRIMARY KEY (id),
CONSTRAINT fk_wh_bank FOREIGN KEY (bank_id) REFERENCES banks(bank_id) ON DELETE CASCADE
)
""",
"""
CREATE TABLE IF NOT EXISTS file_storage (
storage_key VARCHAR2(512) NOT NULL,
data BLOB NOT NULL,
CONSTRAINT pk_file_storage PRIMARY KEY (storage_key)
)
""",
"""
CREATE TABLE IF NOT EXISTS audit_log (
id RAW(16) DEFAULT SYS_GUID() NOT NULL,
action VARCHAR2(128) NOT NULL,
transport VARCHAR2(64) NOT NULL,
bank_id VARCHAR2(256),
started_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
ended_at TIMESTAMP WITH TIME ZONE,
request CLOB CONSTRAINT al_request_json CHECK (request IS JSON OR request IS NULL),
response CLOB CONSTRAINT al_response_json CHECK (response IS JSON OR response IS NULL),
metadata CLOB DEFAULT '{}' NOT NULL
CONSTRAINT al_metadata_json CHECK (metadata IS JSON),
CONSTRAINT pk_audit_log PRIMARY KEY (id)
)
""",
"""
CREATE TABLE IF NOT EXISTS observation_sources (
observation_id RAW(16) NOT NULL,
source_id RAW(16) NOT NULL,
CONSTRAINT pk_observation_sources PRIMARY KEY (observation_id, source_id),
CONSTRAINT fk_obs_src_observation FOREIGN KEY (observation_id)
REFERENCES memory_units(id) ON DELETE CASCADE
)
""",
)
# ---------------------------------------------------------------------------
# B-tree indexes
# ---------------------------------------------------------------------------
_INDEXES: tuple[str, ...] = (
# documents
"CREATE INDEX idx_docs_bank_id ON documents(bank_id)",
"CREATE INDEX idx_docs_content_hash ON documents(content_hash)",
# chunks
"CREATE INDEX idx_chunks_document_id ON chunks(document_id)",
"CREATE INDEX idx_chunks_bank_id ON chunks(bank_id)",
# memory_units
"CREATE INDEX idx_mu_bank_id ON memory_units(bank_id)",
"CREATE INDEX idx_mu_document_id ON memory_units(document_id)",
"CREATE INDEX idx_mu_chunk_id ON memory_units(chunk_id)",
"CREATE INDEX idx_mu_event_date ON memory_units(event_date DESC)",
"CREATE INDEX idx_mu_bank_date ON memory_units(bank_id, event_date DESC)",
"CREATE INDEX idx_mu_access_count ON memory_units(access_count DESC)",
"CREATE INDEX idx_mu_fact_type ON memory_units(fact_type)",
"CREATE INDEX idx_mu_bank_fact_type ON memory_units(bank_id, fact_type)",
"CREATE INDEX idx_mu_bank_type_date ON memory_units(bank_id, fact_type, event_date DESC)",
# entities
"CREATE INDEX idx_ent_bank_id ON entities(bank_id)",
"CREATE INDEX idx_ent_canonical_name ON entities(canonical_name)",
"CREATE INDEX idx_ent_bank_name ON entities(bank_id, canonical_name)",
"CREATE UNIQUE INDEX idx_ent_bank_lower_name ON entities(bank_id, LOWER(canonical_name))",
# unit_entities
"CREATE INDEX idx_ue_unit ON unit_entities(unit_id)",
"CREATE INDEX idx_ue_entity ON unit_entities(entity_id)",
# entity_cooccurrences
"CREATE INDEX idx_ec_entity1 ON entity_cooccurrences(entity_id_1)",
"CREATE INDEX idx_ec_entity2 ON entity_cooccurrences(entity_id_2)",
"CREATE INDEX idx_ec_count ON entity_cooccurrences(cooccurrence_count DESC)",
# memory_links — function-based unique index uses NVL with the nil UUID raw
# to handle nullable entity_id (matches PG idx_memory_links_unique).
"CREATE UNIQUE INDEX idx_memory_links_unique ON memory_links("
"from_unit_id, to_unit_id, link_type, "
"NVL(entity_id, HEXTORAW('00000000000000000000000000000000')))",
"CREATE INDEX idx_ml_from_unit ON memory_links(from_unit_id)",
"CREATE INDEX idx_ml_to_unit ON memory_links(to_unit_id)",
"CREATE INDEX idx_ml_entity ON memory_links(entity_id)",
"CREATE INDEX idx_ml_link_type ON memory_links(link_type)",
"CREATE INDEX idx_ml_bank_id ON memory_links(bank_id)",
# directives
"CREATE INDEX idx_dir_bank_id ON directives(bank_id)",
"CREATE INDEX idx_dir_bank_active ON directives(bank_id, is_active)",
# mental_models
"CREATE INDEX idx_mm_bank_id ON mental_models(bank_id)",
"CREATE INDEX idx_mm_subtype ON mental_models(bank_id, subtype)",
"CREATE INDEX idx_mm_entity_id ON mental_models(entity_id)",
# async_operations
"CREATE INDEX idx_ao_bank_id ON async_operations(bank_id)",
"CREATE INDEX idx_ao_status ON async_operations(status)",
"CREATE INDEX idx_ao_bank_status ON async_operations(bank_id, status)",
"CREATE INDEX idx_ao_status_retry ON async_operations(status, next_retry_at)",
# webhooks
"CREATE INDEX idx_wh_bank_id ON webhooks(bank_id)",
# audit_log
"CREATE INDEX idx_al_action_started ON audit_log(action, started_at DESC)",
"CREATE INDEX idx_al_bank_started ON audit_log(bank_id, started_at DESC)",
"CREATE INDEX idx_al_started ON audit_log(started_at DESC)",
# observation_sources
"CREATE INDEX idx_obs_sources_source_id ON observation_sources(source_id, observation_id)",
)
_VECTOR_INDEX = (
"CREATE VECTOR INDEX idx_mu_embedding_hnsw ON memory_units(embedding) "
"ORGANIZATION NEIGHBOR PARTITIONS "
"DISTANCE COSINE "
"WITH TARGET ACCURACY 95"
)
# Oracle Text (CTXSYS.CONTEXT) — ``SYNC (ON COMMIT)`` makes it auto-update
# without a maintenance job. Doubled single quotes for the embedded literal.
_TEXT_INDEX = (
"BEGIN "
"EXECUTE IMMEDIATE '"
"CREATE INDEX idx_mu_content_text ON memory_units(text) "
"INDEXTYPE IS CTXSYS.CONTEXT "
"PARAMETERS (''SYNC (ON COMMIT)'')"
"'; "
"EXCEPTION WHEN OTHERS THEN "
"IF SQLCODE = -955 THEN NULL; ELSE RAISE; END IF; "
"END;"
)
def _execute_ignoring_955(sql: str) -> None:
"""Run a CREATE statement and swallow ORA-00955 (object already exists).
Wraps the statement in PL/SQL so the exception handler runs server-side —
no round-trip cost for the common case.
"""
block = (
"BEGIN "
"EXECUTE IMMEDIATE :stmt; "
"EXCEPTION WHEN OTHERS THEN "
"IF SQLCODE = -955 THEN NULL; ELSE RAISE; END IF; "
"END;"
)
op.get_bind().exec_driver_sql(block, {"stmt": sql.strip()})
def _oracle_upgrade() -> None:
bind = op.get_bind()
# Tolerate concurrent DDL instead of failing immediately (ORA-00054).
bind.exec_driver_sql("ALTER SESSION SET DDL_LOCK_TIMEOUT = 30")
for ddl in _TABLES:
_execute_ignoring_955(ddl)
for idx in _INDEXES:
_execute_ignoring_955(idx)
# Hindsight on Oracle requires 23ai with VECTOR support (ASSM tablespace)
# and the CTXSYS package for full-text. Both index creations must succeed
# — the migration fails hard if either feature is unavailable, by design.
# We only swallow ORA-00955 (object already exists) so reruns are safe.
_execute_ignoring_955(_VECTOR_INDEX)
bind.exec_driver_sql(_TEXT_INDEX)
def _oracle_downgrade() -> None:
# Baseline downgrades aren't supported — dropping every table here would
# destroy customer data. Use point-in-time recovery instead.
raise NotImplementedError("Cannot downgrade past the Oracle baseline.")
def upgrade() -> None:
run_for_dialect(oracle=_oracle_upgrade)
def downgrade() -> None:
run_for_dialect(oracle=_oracle_downgrade)
@@ -21,6 +21,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "p1k2l3m4n5o6"
down_revision: str | Sequence[str] | None = "o0j1k2l3m4n5"
@@ -34,7 +36,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Implement new knowledge architecture."""
schema = _get_schema_prefix()
@@ -126,7 +128,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Reverse the migration."""
schema = _get_schema_prefix()
@@ -192,3 +194,11 @@ def downgrade() -> None:
""")
# Note: mental_models table recreation is complex and would need separate handling
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "q2l3m4n5o6p7"
down_revision: str | Sequence[str] | None = "p1k2l3m4n5o6"
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add 'mental_model' to the fact_type check constraint."""
schema = _get_schema_prefix()
@@ -38,7 +40,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove 'mental_model' from the fact_type check constraint."""
schema = _get_schema_prefix()
@@ -48,3 +50,11 @@ def downgrade() -> None:
ADD CONSTRAINT memory_units_fact_type_check
CHECK (fact_type IN ('world', 'experience', 'opinion', 'observation'))
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -14,6 +14,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "r3m4n5o6p7q8"
down_revision: str | Sequence[str] | None = "q2l3m4n5o6p7"
branch_labels: str | Sequence[str] | None = None
@@ -26,7 +28,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add reflect_response JSONB column to reflections."""
schema = _get_schema_prefix()
@@ -37,7 +39,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove reflect_response column from reflections."""
schema = _get_schema_prefix()
@@ -45,3 +47,11 @@ def downgrade() -> None:
ALTER TABLE {schema}reflections
DROP COLUMN IF EXISTS reflect_response
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ import sqlalchemy as sa
from alembic import context, op
from sqlalchemy.dialects import postgresql
from hindsight_api.alembic._dialect import run_for_dialect
# revision identifiers, used by Alembic.
revision: str = "rename_personality"
down_revision: str | Sequence[str] | None = "d9f6a3b4c5e2"
@@ -25,7 +27,7 @@ def _get_target_schema() -> str:
return schema if schema else "public"
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Rename personality column to disposition in banks table (if it exists)."""
conn = op.get_bind()
target_schema = _get_target_schema()
@@ -69,7 +71,7 @@ def upgrade() -> None:
# else: disposition already exists, nothing to do
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert disposition column back to personality."""
conn = op.get_bind()
target_schema = _get_target_schema()
@@ -83,3 +85,11 @@ def downgrade() -> None:
)
if result.fetchone():
op.alter_column("banks", "disposition", new_column_name="personality")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "s4n5o6p7q8r9"
down_revision: str | Sequence[str] | None = "r3m4n5o6p7q8"
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
# Add consolidated_at column to memory_units
@@ -46,8 +48,16 @@ def upgrade() -> None:
)
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"DROP INDEX IF EXISTS {schema}idx_memory_units_unconsolidated")
op.execute(f"ALTER TABLE {schema}memory_units DROP COLUMN IF EXISTS consolidated_at")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -17,6 +17,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "t5o6p7q8r9s0"
down_revision: str | Sequence[str] | None = "s4n5o6p7q8r9"
branch_labels: str | Sequence[str] | None = None
@@ -29,7 +31,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Rename mental_model -> observation and reflections -> mental_models."""
schema = _get_schema_prefix()
@@ -86,7 +88,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Reverse: observation -> mental_model and mental_models -> reflections."""
schema = _get_schema_prefix()
@@ -132,3 +134,11 @@ def downgrade() -> None:
ON {schema}memory_units(bank_id, fact_type)
WHERE fact_type = 'mental_model'
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -12,6 +12,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "u6p7q8r9s0t1"
down_revision: str | Sequence[str] | None = "t5o6p7q8r9s0"
branch_labels: str | Sequence[str] | None = None
@@ -24,7 +26,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Change mental_models.id from UUID to TEXT."""
schema = _get_schema_prefix()
@@ -33,9 +35,17 @@ def upgrade() -> None:
op.execute(f"ALTER TABLE {schema}mental_models ALTER COLUMN id TYPE TEXT USING id::TEXT")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert mental_models.id from TEXT to UUID."""
schema = _get_schema_prefix()
# Note: This will fail if any id values are not valid UUIDs
op.execute(f"ALTER TABLE {schema}mental_models ALTER COLUMN id TYPE UUID USING id::UUID")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "v7q8r9s0t1u2"
down_revision: str | Sequence[str] | None = "u6p7q8r9s0t1"
branch_labels: str | Sequence[str] | None = None
@@ -25,7 +27,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add max_tokens and trigger columns to mental_models."""
schema = _get_schema_prefix()
@@ -42,9 +44,17 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove max_tokens and trigger columns from mental_models."""
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS max_tokens")
op.execute(f"ALTER TABLE {schema}mental_models DROP COLUMN IF EXISTS trigger")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -15,6 +15,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "w8r9s0t1u2v3"
down_revision: str | Sequence[str] | None = "v7q8r9s0t1u2"
branch_labels: str | Sequence[str] | None = None
@@ -27,7 +29,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Change mental_models primary key from (id) to (bank_id, id) for proper bank isolation."""
schema = _get_schema_prefix()
@@ -45,7 +47,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Revert mental_models primary key from (bank_id, id) to (id)."""
schema = _get_schema_prefix()
@@ -58,3 +60,11 @@ def downgrade() -> None:
ALTER TABLE {schema}mental_models
ADD CONSTRAINT mental_models_pkey PRIMARY KEY (id)
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -20,6 +20,8 @@ import sqlalchemy as sa
from alembic import context, op
from sqlalchemy.dialects.postgresql import JSONB
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "x9s0t1u2v3w4"
down_revision: str | Sequence[str] | None = "w8r9s0t1u2v3"
branch_labels: str | Sequence[str] | None = None
@@ -32,7 +34,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add config JSONB column to banks table with GIN index."""
schema = _get_schema_prefix()
@@ -50,7 +52,7 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove config column and index from banks table."""
schema = _get_schema_prefix()
@@ -62,3 +64,11 @@ def downgrade() -> None:
ALTER TABLE {schema}banks
DROP COLUMN IF EXISTS config
""")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -17,6 +17,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "y0t1u2v3w4x5"
down_revision: str | Sequence[str] | None = "x9s0t1u2v3w4"
branch_labels: str | Sequence[str] | None = None
@@ -29,7 +31,7 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
"""Add GIN index on result_metadata for efficient parent_operation_id queries."""
schema = _get_schema_prefix()
@@ -41,9 +43,17 @@ def upgrade() -> None:
""")
def downgrade() -> None:
def _pg_downgrade() -> None:
"""Remove GIN index on result_metadata."""
schema = _get_schema_prefix()
# Drop index
op.execute(f"DROP INDEX IF EXISTS {schema}idx_async_operations_result_metadata")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)
@@ -13,6 +13,8 @@ from collections.abc import Sequence
from alembic import context, op
from hindsight_api.alembic._dialect import run_for_dialect
revision: str = "z1u2v3w4x5y6"
down_revision: str | Sequence[str] | None = "a1b2c3d4e5f6"
branch_labels: str | Sequence[str] | None = None
@@ -25,11 +27,19 @@ def _get_schema_prefix() -> str:
return f'"{schema}".' if schema else ""
def upgrade() -> None:
def _pg_upgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}memory_units ADD COLUMN IF NOT EXISTS observation_scopes JSONB")
def downgrade() -> None:
def _pg_downgrade() -> None:
schema = _get_schema_prefix()
op.execute(f"ALTER TABLE {schema}memory_units DROP COLUMN IF EXISTS observation_scopes")
def upgrade() -> None:
run_for_dialect(pg=_pg_upgrade)
def downgrade() -> None:
run_for_dialect(pg=_pg_downgrade)

Some files were not shown because too many files have changed in this diff Show More