Skip to content

refactor: CR-002 post-release cleanup — dead features, env vars, auth-skip-local#203

Merged
thebtf merged 8 commits into
mainfrom
feat/cr-002-post-release-cleanup
Apr 24, 2026
Merged

refactor: CR-002 post-release cleanup — dead features, env vars, auth-skip-local#203
thebtf merged 8 commits into
mainfrom
feat/cr-002-post-release-cleanup

Conversation

@thebtf
Copy link
Copy Markdown
Owner

@thebtf thebtf commented Apr 24, 2026

CR-002: Post-Release Cleanup

Removes all residual dead code from v5.0.0 dynamic features + consolidates env vars.

What changed (-8268 lines, 62 files)

Env var consolidation (US15):

  • ENGRAM_API_TOKENENGRAM_AUTH_ADMIN_TOKEN everywhere (Go, JS, scripts, docs, plugin)
  • Fixed BUG in grpcserver/server.go — was reading ENGRAM_API_TOKEN directly instead of config.GetWorkerToken()
  • Removed ENGRAM_URL_LEGACY, ENGRAM_API_TOKEN_LEGACY shims
  • Removed envFirstOf helper (zero callers after embedding removal)

Dead dynamic features removed (US16):

  • Deleted 6 packages: pkg/llmclient/, internal/backfill/, internal/dedup/, internal/pipeline/, internal/palace/, internal/synthesis/
  • Deleted dead models: pattern.go (407 LOC), conflict.go types (12 LOC)
  • Stripped LLM pipeline from sdk/processor.go (~465 lines)
  • Removed all embedding config fields + 6 getter functions
  • Removed all ENGRAM_EMBEDDING_* and ENGRAM_LLM_* env var handling

Dead function sweep (US17):

  • Removed ~400 lines dead functions from 10 worker handler files
  • Deleted floor_fill.go + test

Hook cleanup (US15/US16):

  • Removed 9 dead exports from lib.js (~180 lines)
  • Deleted sync-sessions.js, post-compact.js
  • Updated plugin env mapping, bumped to 5.0.1

New: auth skip-local config fields (US18 prep):

  • Added AuthSkipLocal + AuthTrustedProxy config fields + env loading
  • Implementation in middleware.go pending (T018 in next iteration)

Verification

  • go build ./...
  • go vet ./...
  • go test ./... -count=1 -short
  • node --test plugin/engram/hooks/hook-cli.test.js

Summary by CodeRabbit

  • Chores

    • Переменная окружения для сервера/плагина изменена: теперь используется ENGRAM_AUTH_ADMIN_TOKEN вместо ENGRAM_API_TOKEN
    • Обновлены документация и манифест плагина с новой переменной аутентификации
  • Removed Features

    • Удалены LLM‑опции и связанные функции (извлечение/ретроспективы/генерация вики/синтез)
    • Удалены компоненты поиска/миннинга/детекции паттернов и сопутствующие возможности
  • Simplification

    • Упрощена конфигурация и поведение сервиса; некоторые эндпоинты теперь возвращают упрощённые/устаревшие ответы

thebtf added 2 commits April 24, 2026 09:26
T019: Remove dead exports from lib.js (requestUpload, WorkstationID,
getSessionSignals, getSessionFiles, clearSessionSignals, diffScope,
SCOPE_PATTERNS, deletePendingMarker, formatResolvedIssuesBlock);
remove buildInjectURL and formatProjectBriefingBlock from
session-start.js; remove buildSearchRequest from user-prompt.js;
delete sync-sessions.js and post-compact.js entirely.
Update test files to use local helpers instead of deleted exports.

T020: Rename ENGRAM_API_TOKEN -> ENGRAM_AUTH_ADMIN_TOKEN in .mcp.json,
run-engram.js, lib.js, session-start.js, commands/*.md, plugin.json,
skills/memory/SKILL.md. Remove ENGRAM_URL_LEGACY and
ENGRAM_API_TOKEN_LEGACY env entries and legacy fallback blocks.
Bump plugin version 5.0.0 -> 5.0.1.
… consolidate env vars, add auth-skip-local

- Remove ENGRAM_API_TOKEN everywhere, replace with ENGRAM_AUTH_ADMIN_TOKEN
- Fix grpcserver BUG: use config.GetWorkerToken() not direct os.Getenv
- Delete 6 dead packages: llmclient, backfill, dedup, pipeline, palace, synthesis
- Delete dead models: pattern.go (407 LOC), conflict types (12 LOC)
- Strip LLM pipeline from sdk/processor.go (~465 lines)
- Remove ~400 lines dead functions from 10 worker handler files
- Remove embedding config fields, getters, envFirstOf helper
- Add ENGRAM_AUTH_SKIP_LOCAL + ENGRAM_AUTH_TRUSTED_PROXY config fields
- Plugin: remove LEGACY shims, rename token, clean dead hook exports
- Delete sync-sessions.js, post-compact.js (dead hooks)
- Bump plugin version 5.0.0 → 5.0.1
- Build/vet/test all green

62 files changed, -8268 lines net
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 24, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fad74d6f-047f-4bc7-9232-8cf3995b6252

📥 Commits

Reviewing files that changed from the base of the PR and between 965c869 and 1837751.

📒 Files selected for processing (9)
  • docs/docs.go
  • docs/swagger.json
  • docs/swagger.yaml
  • internal/config/config.go
  • internal/handlers/serverevents/bridge.go
  • internal/worker/sdk/processor.go
  • pkg/models/observation.go
  • plugin/engram/hooks/pre-tool-use.test.js
  • plugin/engram/hooks/user-prompt.test.js

Walkthrough

Удаляет большие устаревшие подсистемы: серверный backfill/LLM pipeline, palace/mining/aaak, synthesis/wiki, pattern моделирование, встроенный LLM-клиент и множество вспомогательных hook/ingest/retrieval функций; одновременно переключает источник админ-токена на ENGRAM_AUTH_ADMIN_TOKEN и очищает связанный код и документацию.

Changes

Cohort / File(s) Summary
Backfill
internal/backfill/backfill.go, internal/backfill/chunk/chunk.go, internal/backfill/extract/extract.go, internal/backfill/extract/prompts.go, internal/backfill/extract/retrospective.go, internal/backfill/metrics/metrics.go, internal/backfill/progress.go, internal/backfill/sanitize/sanitize.go
Полное удаление серверного backfill/LLM-пайплайна: оркестрация сессий, чанкинг, prompt/XML-валидация, ретроспективы, метрики и прогресс-перенос.
Palace / AAak / Mining
internal/palace/aaak/*.go, internal/palace/mining/... (chunker.go, classify.go, concepts.go, exchange.go, filter.go, miner.go, mining_test.go, normalize.go), internal/palace/taxonomy/queries.go
Удалены компоненты сжатия AAAK, детекции эмоций/флагов/топиков, майнинга текстов, извлечения обменов и таксономия — вся функциональность обработки/классификации текста.
Synthesis / Wiki
internal/synthesis/entity_extractor.go, internal/synthesis/json_parser.go, internal/synthesis/prompts.go, internal/synthesis/types.go, internal/synthesis/wiki_disk.go, internal/synthesis/wiki_generator.go
Удаление подсистемы синтеза сущностей и wiki: типы, промпты, парсеры, генераторы и запись на диск.
Patterns / Models
pkg/models/pattern.go, pkg/models/pattern_test.go
Полное удаление домена паттернов: модели, вспомогательные типы, логика детекции и тесты.
LLM клиент & конфиг
pkg/llmclient/client.go, internal/config/config.go
Удалён встроенный HTTP LLM-клиент и поля конфигурации для эмбеддингов; добавлены поля AuthSkipLocal/AuthTrustedProxy и изменён GetWorkerToken/поведение прочтения токена.
Worker handlers & ingest
internal/worker/handlers_backfill.go, internal/worker/handlers_context.go, internal/worker/handlers_data.go, internal/worker/handlers_ingest.go, internal/worker/handlers_sessions.go, internal/worker/handlers_system.go, internal/worker/handlers.go, internal/worker/handlers_*_test.go
Упрощение обработчиков: удаление LLM-процессинга backfill/ingest, аналитики hit-rate, отзывов, ряда вспомогательных утилит и связанных тестов; некоторые эндпоинты теперь возвращают 410 или stub-ответы.
SDK Processor
internal/worker/sdk/processor.go, internal/worker/sdk/processor_test.go, internal/worker/sdk/prompts.go
Удалён LLM-ориентированный путь обработки: circuit-breaker, throttling, извлечение рассуждений; NewProcessor упрощён, IsAvailable всегда true, тесты и промпты обновлены/удалены.
Dedup
internal/dedup/checker.go, internal/dedup/checker_test.go
Удаление логики проверки близких дубликатов и тестов, включая пороги и CrossModelPromotion.
Retrieval / floor_fill / trigger matcher
internal/worker/retrieval.go, internal/worker/retrieval_helpers.go, internal/worker/floor_fill.go, internal/worker/trigger_matcher.go
Удалены вспомогательные механизмы ранжирования/ланирования/заполнения пола и части триггерной логики; упрощение retrieval pipeline.
Pipeline deterministic
internal/pipeline/deterministic.go, internal/pipeline/deterministic_test.go
Удалён детерминированный пайплайн извлечения наблюдений и связанные тесты.
Plugin / hooks / docs
plugin/engram/.claude-plugin/plugin.json, plugin/engram/.mcp.json, plugin/engram/commands/*.md, plugin/engram/hooks/*.js, plugin/engram/scripts/run-engram.js, plugin/engram/skills/memory/SKILL.md
Переключение документации и плагинов на ENGRAM_AUTH_ADMIN_TOKEN; удаление/сокращение набора hook-утилит и тестовых вспомогательных функций; манифест версии обновлён.
Misc models / observation
pkg/models/observation.go, pkg/models/conflict.go
Добавлен новый тип JSONInt64Array с Scan/Value для совместимости SQL; удалены или упрощены комментарии в conflict.go.
Прочие утилиты и тесты
internal/palace/aaak/* тесты и реализации, plugin/engram/hooks/* скрипты/тесты
Массовое удаление вспомогательных реализаций и тестов в указанных модулях.

Sequence Diagram(s)

(Пропущено — изменения в основном удаляют подсистемы и не вводят новую многоступенчатую последовательность взаимодействий.)

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Поэма

🐰 Вытянул я вилкой старый код v4,
Ушли промпты, паттерны и LLM-двор.
Админ-токен новый — светит в окне,
v5 идёт — стройней стала тетрадь mine.
Пошевелил усы — и всё летит вперёд.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: post-release cleanup removing dead features, consolidating environment variables, and adding auth configuration fields.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cr-002-post-release-cleanup

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.11.4)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request performs a comprehensive cleanup by removing multiple legacy packages related to backfill, mining, and synthesis, while standardizing the administrative token as ENGRAM_AUTH_ADMIN_TOKEN. It also introduces new configuration options for local authentication and trusted proxies. Review feedback suggests that the configuration reload logic should be updated to track these new fields and that the Scan method for JSONInt64Array must return an error for unsupported types to prevent silent failures.

Comment thread internal/config/config.go
Comment thread pkg/models/observation.go Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/worker/sdk/processor.go (1)

576-717: ⚠️ Potential issue | 🔴 Critical

Функции isSelfReferentialSummary и hasMeaningfulContent являются мёртвым кодом и должны быть удалены.

Поиск показывает, что обе функции используются только в тестах (ProcessorTest lines 74, 742 для isSelfReferentialSummary и lines 125, 808 для hasMeaningfulContent), но не вызываются ни из одного кода в продакшене. После удаления ProcessSummary эти функции остались неиспользуемыми. Удалите функции вместе с соответствующими тестовыми случаями.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/worker/sdk/processor.go` around lines 576 - 717, The two helper
functions isSelfReferentialSummary and hasMeaningfulContent are dead code left
after removing ProcessSummary; delete both function definitions from
processor.go and remove the corresponding test cases in ProcessorTest that
reference isSelfReferentialSummary and hasMeaningfulContent (and any test
helpers/assertions that only exercise them); also clean up any now-unused
imports or variables introduced solely for these functions so the build and
tests remain clean.
🧹 Nitpick comments (4)
plugin/engram/hooks/user-prompt.test.js (1)

1-4: Рекомендуется удалить пустой тестовый файл.

Файл содержит только комментарии и не имеет реальных тестов. Вместо сохранения пустого файла-заглушки рекомендуется полностью удалить его — история git сохранит информацию о том, что тесты были удалены и почему.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/engram/hooks/user-prompt.test.js` around lines 1 - 4, Удалите пустой
файл user-prompt.test.js which contains only comments and no tests: remove the
file from the repository (git rm) so it no longer appears in the codebase; rely
on git history to preserve the prior content and rationale and ensure there are
no imports or references to user-prompt.test.js elsewhere (e.g., test runners or
index files) before committing the deletion.
internal/worker/sdk/processor.go (1)

206-258: Удалить неиспользуемые функции и константу.

Функции unionStrings, mergeNarrative и mergeFileMtimes, а также константа writeMergeSimilarityThreshold не вызываются в коде и могут быть удалены.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/worker/sdk/processor.go` around lines 206 - 258, Remove the unused
constant and functions to clean up dead code: delete
writeMergeSimilarityThreshold and the functions unionStrings, mergeNarrative,
and mergeFileMtimes from the file; also remove any now-unused imports (e.g.,
"strings") and any references or tests that expect these symbols so the build
stays clean. Ensure no other code calls unionStrings, mergeNarrative,
mergeFileMtimes or relies on writeMergeSimilarityThreshold before committing.
plugin/engram/hooks/pre-tool-use.test.js (1)

38-38: Незначительная несогласованность: использование require('fs') вместо импортированного fs.

На строке 4 уже импортирован fs, но здесь используется require('fs'). Рекомендуется использовать уже импортированную переменную для единообразия.

♻️ Предлагаемое исправление
-  require('fs').writeFileSync(signalPath, JSON.stringify({ read_counts: { 'internal/auth.go': 3 } }), 'utf8');
+  fs.writeFileSync(signalPath, JSON.stringify({ read_counts: { 'internal/auth.go': 3 } }), 'utf8');
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/engram/hooks/pre-tool-use.test.js` at line 38, The test uses
require('fs') inline instead of the already-imported fs variable; locate the
writeFileSync call that writes to signalPath (the line with
require('fs').writeFileSync(...)) and replace the require call with the existing
fs identifier so the code uses the imported fs (i.e., change
require('fs').writeFileSync(...) to fs.writeFileSync(...)) to keep imports
consistent.
internal/config/config.go (1)

431-434: Несоответствие паттернов доступа к конфигурации.

GetWorkerToken() читает только из переменной окружения, игнорируя cfg.WorkerToken, который загружается в Load() (строки 259-261). Это отличается от паттерна GetWorkerHost(), который проверяет env, затем fallback на Get().WorkerHost.

Такой подход может быть намеренным (не кэшировать токены в памяти), но тогда:

  1. Загрузка cfg.WorkerToken в Load() становится избыточной
  2. Отслеживание изменений WorkerToken в Reload() (строки 400-402) теряет смысл
♻️ Опция 1: Убрать загрузку cfg.WorkerToken (если env-only)

Удалить строки 259-261 в Load() и строки 400-402 в Reload(), а также поле WorkerToken из структуры.

♻️ Опция 2: Использовать cfg.WorkerToken (консистентный паттерн)
 // GetWorkerToken returns the admin authentication token from ENGRAM_AUTH_ADMIN_TOKEN.
 func GetWorkerToken() string {
-	return strings.TrimSpace(os.Getenv("ENGRAM_AUTH_ADMIN_TOKEN"))
+	if token := strings.TrimSpace(os.Getenv("ENGRAM_AUTH_ADMIN_TOKEN")); token != "" {
+		return token
+	}
+	return Get().WorkerToken
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/config/config.go` around lines 431 - 434, GetWorkerToken currently
reads only the environment and ignores the loaded cfg.WorkerToken, causing
inconsistency with GetWorkerHost and making Load/Reload token handling
pointless; to fix, change GetWorkerToken to first check ENGRAM_AUTH_ADMIN_TOKEN
env (trimmed) and if empty return Get().WorkerToken so the existing Load() and
Reload() assignments to cfg.WorkerToken remain meaningful (leave Load, Reload
and the WorkerToken field as-is).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/handlers/serverevents/bridge.go`:
- Around line 107-108: Код в bridge.go записывает serverURL :=
os.Getenv("ENGRAM_SERVER_URL") но документация и другие плагины используют
ENGRAM_URL, из‑за чего возникает несовместимость; исправьте это, добавив в ту же
функцию/блок чтения переменных окружения fallback: если ENGRAM_SERVER_URL
пустой, прочитать os.Getenv("ENGRAM_URL") в ту же переменную serverURL и
залогировать предупреждение о deprecated/несоответствии (чтобы пользователи
знали о несоответствии), сохранив при этом чтение токена через
ENGRAM_AUTH_ADMIN_TOKEN как есть.

In `@internal/worker/handlers_backfill.go`:
- Around line 181-186: The handler now returns a simple JSON via writeJSON with
keys stored, skipped, errors, and deprecated, but the OpenAPI definitions still
reference the removed BackfillSessionResponse structure (with metrics_report and
observations_extracted). Update the API docs to match the handler: remove or
replace the BackfillSessionResponse schema in docs/swagger.yaml and
docs/swagger.json and instead define the response schema to include integer
fields stored, skipped, errors and a string deprecated (or update the endpoint
response reference to an inline schema returning those four keys); ensure the
paths that reference BackfillSessionResponse are updated so the documented
response matches the writeJSON output.

In `@pkg/models/observation.go`:
- Around line 233-240: In JSONInt64Array.Scan(), the default case currently
returns nil which hides unsupported input types; change the default branch to
return a descriptive error (e.g., using fmt.Errorf) similar to
JSONStringArray.Scan() and JSONInt64Map.Scan(), referencing the function name
JSONInt64Array.Scan and include the actual received type in the error message so
callers can detect and handle invalid input.

---

Outside diff comments:
In `@internal/worker/sdk/processor.go`:
- Around line 576-717: The two helper functions isSelfReferentialSummary and
hasMeaningfulContent are dead code left after removing ProcessSummary; delete
both function definitions from processor.go and remove the corresponding test
cases in ProcessorTest that reference isSelfReferentialSummary and
hasMeaningfulContent (and any test helpers/assertions that only exercise them);
also clean up any now-unused imports or variables introduced solely for these
functions so the build and tests remain clean.

---

Nitpick comments:
In `@internal/config/config.go`:
- Around line 431-434: GetWorkerToken currently reads only the environment and
ignores the loaded cfg.WorkerToken, causing inconsistency with GetWorkerHost and
making Load/Reload token handling pointless; to fix, change GetWorkerToken to
first check ENGRAM_AUTH_ADMIN_TOKEN env (trimmed) and if empty return
Get().WorkerToken so the existing Load() and Reload() assignments to
cfg.WorkerToken remain meaningful (leave Load, Reload and the WorkerToken field
as-is).

In `@internal/worker/sdk/processor.go`:
- Around line 206-258: Remove the unused constant and functions to clean up dead
code: delete writeMergeSimilarityThreshold and the functions unionStrings,
mergeNarrative, and mergeFileMtimes from the file; also remove any now-unused
imports (e.g., "strings") and any references or tests that expect these symbols
so the build stays clean. Ensure no other code calls unionStrings,
mergeNarrative, mergeFileMtimes or relies on writeMergeSimilarityThreshold
before committing.

In `@plugin/engram/hooks/pre-tool-use.test.js`:
- Line 38: The test uses require('fs') inline instead of the already-imported fs
variable; locate the writeFileSync call that writes to signalPath (the line with
require('fs').writeFileSync(...)) and replace the require call with the existing
fs identifier so the code uses the imported fs (i.e., change
require('fs').writeFileSync(...) to fs.writeFileSync(...)) to keep imports
consistent.

In `@plugin/engram/hooks/user-prompt.test.js`:
- Around line 1-4: Удалите пустой файл user-prompt.test.js which contains only
comments and no tests: remove the file from the repository (git rm) so it no
longer appears in the codebase; rely on git history to preserve the prior
content and rationale and ensure there are no imports or references to
user-prompt.test.js elsewhere (e.g., test runners or index files) before
committing the deletion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 71cc8ed1-cc78-4b90-b0ba-00fd9fa03901

📥 Commits

Reviewing files that changed from the base of the PR and between dafc3b0 and 965c869.

📒 Files selected for processing (81)
  • internal/backfill/backfill.go
  • internal/backfill/chunk/chunk.go
  • internal/backfill/extract/extract.go
  • internal/backfill/extract/prompts.go
  • internal/backfill/extract/retrospective.go
  • internal/backfill/metrics/metrics.go
  • internal/backfill/progress.go
  • internal/backfill/sanitize/sanitize.go
  • internal/config/config.go
  • internal/dedup/checker.go
  • internal/dedup/checker_test.go
  • internal/grpcserver/server.go
  • internal/handlers/engramcore/tools.go
  • internal/handlers/serverevents/bridge.go
  • internal/handlers/serverevents/doc.go
  • internal/palace/aaak/aaak_test.go
  • internal/palace/aaak/compress.go
  • internal/palace/aaak/decode.go
  • internal/palace/aaak/emotions.go
  • internal/palace/aaak/entities.go
  • internal/palace/aaak/flags.go
  • internal/palace/aaak/tokens_test.go
  • internal/palace/aaak/topics.go
  • internal/palace/mining/chunker.go
  • internal/palace/mining/classify.go
  • internal/palace/mining/concepts.go
  • internal/palace/mining/exchange.go
  • internal/palace/mining/filter.go
  • internal/palace/mining/miner.go
  • internal/palace/mining/mining_test.go
  • internal/palace/mining/normalize.go
  • internal/palace/taxonomy/queries.go
  • internal/pipeline/deterministic.go
  • internal/pipeline/deterministic_test.go
  • internal/synthesis/entity_extractor.go
  • internal/synthesis/json_parser.go
  • internal/synthesis/prompts.go
  • internal/synthesis/types.go
  • internal/synthesis/wiki_disk.go
  • internal/synthesis/wiki_generator.go
  • internal/worker/floor_fill.go
  • internal/worker/handlers.go
  • internal/worker/handlers_backfill.go
  • internal/worker/handlers_context.go
  • internal/worker/handlers_context_floor_test.go
  • internal/worker/handlers_data.go
  • internal/worker/handlers_data_test.go
  • internal/worker/handlers_ingest.go
  • internal/worker/handlers_sessions.go
  • internal/worker/handlers_system.go
  • internal/worker/retrieval.go
  • internal/worker/retrieval_helpers.go
  • internal/worker/sdk/processor.go
  • internal/worker/sdk/processor_test.go
  • internal/worker/sdk/prompts.go
  • internal/worker/service.go
  • internal/worker/trigger_matcher.go
  • pkg/llmclient/client.go
  • pkg/models/conflict.go
  • pkg/models/observation.go
  • pkg/models/pattern.go
  • pkg/models/pattern_test.go
  • plugin/engram/.claude-plugin/plugin.json
  • plugin/engram/.mcp.json
  • plugin/engram/commands/doctor.md
  • plugin/engram/commands/issue.md
  • plugin/engram/commands/restart.md
  • plugin/engram/commands/retro.md
  • plugin/engram/commands/setup.md
  • plugin/engram/commands/stats.md
  • plugin/engram/hooks/lib.js
  • plugin/engram/hooks/lib.test.js
  • plugin/engram/hooks/post-compact.js
  • plugin/engram/hooks/pre-tool-use.test.js
  • plugin/engram/hooks/session-start.js
  • plugin/engram/hooks/session-start.test.js
  • plugin/engram/hooks/sync-sessions.js
  • plugin/engram/hooks/user-prompt.js
  • plugin/engram/hooks/user-prompt.test.js
  • plugin/engram/scripts/run-engram.js
  • plugin/engram/skills/memory/SKILL.md
💤 Files with no reviewable changes (55)
  • plugin/engram/hooks/sync-sessions.js
  • internal/palace/aaak/emotions.go
  • internal/palace/aaak/entities.go
  • internal/backfill/extract/retrospective.go
  • internal/palace/aaak/tokens_test.go
  • internal/worker/handlers_system.go
  • internal/synthesis/prompts.go
  • internal/worker/handlers.go
  • internal/palace/mining/classify.go
  • internal/palace/aaak/decode.go
  • internal/palace/mining/filter.go
  • internal/palace/mining/concepts.go
  • plugin/engram/hooks/user-prompt.js
  • internal/worker/handlers_context.go
  • internal/dedup/checker_test.go
  • internal/worker/sdk/prompts.go
  • internal/palace/aaak/topics.go
  • plugin/engram/hooks/session-start.test.js
  • internal/palace/taxonomy/queries.go
  • internal/worker/handlers_context_floor_test.go
  • internal/palace/aaak/flags.go
  • internal/palace/mining/exchange.go
  • internal/backfill/metrics/metrics.go
  • internal/palace/aaak/compress.go
  • internal/worker/handlers_data_test.go
  • internal/worker/trigger_matcher.go
  • internal/palace/mining/chunker.go
  • internal/worker/floor_fill.go
  • internal/backfill/chunk/chunk.go
  • internal/pipeline/deterministic_test.go
  • internal/synthesis/wiki_generator.go
  • internal/synthesis/types.go
  • internal/worker/retrieval_helpers.go
  • internal/worker/handlers_ingest.go
  • internal/synthesis/wiki_disk.go
  • internal/worker/retrieval.go
  • internal/backfill/progress.go
  • internal/backfill/sanitize/sanitize.go
  • pkg/llmclient/client.go
  • internal/backfill/extract/prompts.go
  • internal/worker/handlers_data.go
  • internal/palace/aaak/aaak_test.go
  • internal/synthesis/json_parser.go
  • internal/palace/mining/mining_test.go
  • internal/palace/mining/miner.go
  • internal/palace/mining/normalize.go
  • plugin/engram/hooks/post-compact.js
  • pkg/models/conflict.go
  • internal/backfill/backfill.go
  • pkg/models/pattern.go
  • internal/backfill/extract/extract.go
  • internal/dedup/checker.go
  • internal/pipeline/deterministic.go
  • internal/synthesis/entity_extractor.go
  • pkg/models/pattern_test.go

Comment thread internal/handlers/serverevents/bridge.go
Comment thread internal/worker/handlers_backfill.go
Comment thread pkg/models/observation.go
thebtf added 6 commits April 24, 2026 15:57
Default case returned nil instead of fmt.Errorf, silently ignoring
scan failures. Now returns a descriptive error for unsupported src types.

Resolves CodeRabbit MAJOR review comment.
Plugin hooks and documentation use ENGRAM_URL universally. Bridge was
reading only ENGRAM_SERVER_URL, causing silent misconfiguration when
users follow the documented env var. Added deprecation warning on fallback.
Removed unused constant writeMergeSimilarityThreshold and three
unreferenced functions: unionStrings, mergeNarrative, mergeFileMtimes.
None were called anywhere in the codebase.
Line 38 used require('fs').writeFileSync instead of the fs variable
imported at the top of the file. Use the existing import.
…elds

1. GetWorkerToken now mirrors GetWorkerHost pattern: checks
   ENGRAM_AUTH_ADMIN_TOKEN env var first, falls back to cfg.WorkerToken.

2. Reload() now tracks changes to AuthSkipLocal and AuthTrustedProxy,
   which were added to the config struct but not diffed in the changed-
   fields detection block.
Handler now returns {stored, skipped, errors, deprecated} since
observation/session-summary persistence was removed in v5. Remove stale
metrics_report and observations_extracted fields; add deprecated string.
@thebtf thebtf merged commit 45c4f67 into main Apr 24, 2026
7 of 8 checks passed
@thebtf thebtf deleted the feat/cr-002-post-release-cleanup branch April 24, 2026 12:59
thebtf added a commit that referenced this pull request Apr 24, 2026
Bump daemon version v5.0.0 → v5.1.0, plugin 5.0.1 → 5.1.0.

Since v5.0.1:
- PR #202: dead-code sweep — removed Go references to dropped tables (-2861 lines)
- PR #203: env var cleanup, auth-skip-local, dead features removal (-5862 lines)
- PR #204: dead UI views and API functions removal (-4065 lines)
- PR #205: Activity Timeline + observation UI cleanup (-2784 lines)

Total: ~15,500 lines of dead code removed post-v5.0.0.
thebtf added a commit that referenced this pull request Apr 26, 2026
…d test

Adds tests/critical/auth_two_tier_test.go (//go:build critical) — the first
@critical end-to-end test in this repo. Resolves the MISSING_SUITE verdict
from the critical-suite skill before v6.0.0 release.

The test exercises the v6 auth boundary across BOTH transports (gRPC + HTTP)
using the SAME validator chain — which is precisely the surface PR #203
silently broke. With this test in place, a future regression where gRPC and
HTTP diverge on validator wiring fails CI before the release tag is cut.

Sub-tests:
- gRPC bufconn server accepts operator key (FR-1 tier 1)
- gRPC bufconn server accepts dashboard-issued keycard (FR-2 symmetry — the
  assertion PR #203 would have flipped to FAIL)
- gRPC rejects garbage / missing bearer with Unauthenticated
- HTTP httptest server bearer arm: master + keycard accepted, garbage rejected
- Anti-stub mutation guard: replacing the keycard store with always-fail
  flips the keycard-success assertion, proving the test exercises the store
  path and is not a tautology

Run via: go test -tags=critical ./tests/critical/...
Build tag gates the suite away from default `go test ./...`.
thebtf added a commit that referenced this pull request Apr 26, 2026
BREAKING CHANGES — v6.0.0 auth model.

* Two-tier token model. Daemon and plugin no longer accept the operator
  key on workstations. Each workstation reads `ENGRAM_TOKEN` — a
  per-workstation API token (worker keycard) issued via the dashboard
  `/tokens` page. Operator key (`ENGRAM_AUTH_ADMIN_TOKEN`) lives ONLY
  on the server host.
* Plugin `.mcp.json` env rename: `ENGRAM_AUTH_ADMIN_TOKEN` → `ENGRAM_TOKEN`.
  No legacy fallback chain.
* Daemon fail-fast on missing token (FR-4): clean exit 1 instead of silent
  graceful-degrade to `loom_*-only` (PR #203 regression class).
* Issuance hardening: `POST/GET/DELETE /api/auth/tokens` and
  `/api/auth/tokens/{id}/stats` require an admin browser session cookie;
  bearer-token authentication (operator key OR worker keycard) → 403.
* Single `auth.Validator` shared by HTTP middleware + gRPC interceptor —
  the symmetric validation contract that PR #203's regression broke.
* Strict token shape gate: `engram_` + exactly 32 hex chars; fails closed
  before any DB / bcrypt work.
* Whitelisted scope mapping: only `read-write` / `read-only` are accepted
  from the api_tokens.scope column; anything else is treated as data
  corruption.
* Connection pool keys credential AND TLS CA: rotating ENGRAM_TLS_CA or
  switching keycards cannot ride a stale pooled connection.
* Bootstrap: 1 critical test (`tests/critical/auth_two_tier_test.go`)
  proves gRPC + HTTP both accept the same valid keycard via the same
  validator chain. Resolves the project-wide MISSING_SUITE gate.
* Production playbook (`docs/PRODUCTION-TESTING-PLAYBOOK.md`) bootstraps
  the customer-mode walkthrough required by rule #11. Three scenarios
  (S2.full, S3, S4) require live-stand validation before v6.0.0 tag.

17/17 review threads resolved. Critical suite verdict: PASS.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant