Compare commits

..

57 Commits

Author SHA1 Message Date
Ralph Chang c538381969 chore(release): prepare v1.5.5 2026-05-05 12:23:37 +08:00
Ralph Chang 06dcf61711 feat(hot-state): section-aware greedy renderer, accounting types, fix docs drift
Replace blunt .slice(0, maxRenderedChars) truncation with a greedy line
accumulator that fits whole lines and suppresses header-only sections.
Add accountHotSessionStateRender() returning prompt + omitted[] accounting.
Export HotStateSection, HotStateOmissionReason, HotStateOmittedItem,
HotSessionStateRenderAccounting types for v2 evidence extension.
Fix configuration.md ranking formula (ACTION_WEIGHT + count*3, weights
50/45/30/20). Clarify README injection order. Add 9 unit tests.
2026-05-05 12:22:09 +08:00
Ralph Chang 2918645d8a refactor(memory-diag): remove legacy aliases, centralize command metadata, prepare v1.5.4
- Remove legacy CLI aliases (health, quality, rejections, disappearances, trace)
- Centralize command metadata in command-metadata.ts
- Move trace lifecycle into explain command
- Move disappearance helpers into missing formatter
- Remove cleanup:workspaces from package scripts (dev tool preserved)
- Bump version to 1.5.4
2026-05-02 21:57:13 +08:00
Ralph Chang 84aa020774 chore(release): prepare v1.5.3 2026-05-02 20:49:23 +08:00
Ralph Chang 3c13773231 feat(memory-diag): publish diagnostics CLI 2026-05-02 20:36:58 +08:00
Ralph Chang e0357c572a feat(reinforcement): compaction prompt wording reuse, migration evidence, and validation baseline
Wave 1 — Compaction prompt improvement:
- Add three wording-reuse bullets to buildCompactionPrompt() under
  CRITICAL MEMORY RULES: do not create rephrased duplicates, reuse
  existing wording exactly when re-emitting, only emit new memories
  when the fact is new, materially corrected, or more specific.
- This attacks the root cause of zero reinforcement: compaction
  generating variant text for the same durable fact.

Wave 2 — Bug fixes:
- Bug #2: Add placeholder comment to superseded_existing branch in
  decision dedupe (unreachable until v1.5.4 numbered refs). Preserve
  as const type assertions.
- Bug #3: Add memory_migration_superseded evidence event type. Both
  P0 and quality cleanup migrations now produce evidence events for
  superseded entries. loadWorkspaceMemory appends migration evidence
  on first-load migrations only (idempotent via migration IDs). No
  historical backfill.
- Bug #4: Add documentation comment explaining that feedback identity
  key returns exact key (absorbed_identity currently impossible for
  feedback). Add test verifying this behavior.

Wave 3 — Validation baseline script:
- Add scripts/dev/validate-identity-keys.ts: read-only script that
  scans workspace memory stores, computes exact/identity key
  collisions, and reports reinforcement statistics. Baseline matches
  audit: 0 exact collisions, 0 identity collisions, 0 reinforcement
  events across 123 active memories.

Identity extension is gated on measurement: if the prompt change
produces measurable reinforcement (reinforcementCount > 0), identity
extension may be unnecessary. Decision dedupe stays exact-only
(Wave 4 deferred).
2026-05-02 15:03:34 +08:00
Ralph Chang f19614565a chore(release): prepare v1.5.2 2026-05-01 16:00:44 +08:00
Ralph Chang 36593b512e Merge branch 'feat/deprecate-safety-critical' 2026-04-30 19:54:50 +08:00
Ralph Chang ab872ef2c6 chore(release): prepare v1.5.1 2026-04-30 19:54:24 +08:00
Ralph Chang f25a235b93 fix(retention): add UTC calendar-day diversity gate to reinforceMemory
Implement OQ-2 decision: allow at most one reinforcement per memory
identity per UTC calendar day. Same-day reinforcement is blocked
regardless of session or interval. This prevents repetitive-task
gaming where a daily recurring task could reach MAX_COUNT=6 in hours.

Guard order: same-session → calendar-day → 1-hour → max-count
(existing guards kept as defense-in-depth)

1 hour guard is redundant within same day but preserved for
sub-hour edge cases.
2026-04-30 18:38:29 +08:00
Ralph Chang 84245c783d feat(explainability): add diagnostics JSON, per-memory explain, lifecycle trace
Phase 4 Tasks 4.1-4.3:
- memory-diag health --json: machine-readable MemoryDiagJSON output
- memory-diag explain: per-memory render status with strength, reasons,
  evidence event IDs
- memory-diag trace --memory <id>: lifecycle history from evidence events
  and relations (superseded_by, reinforced_by)
- MemoryRenderStatus type with 9 statuses
- All diagnostics are read-only, no storage mutations
- Privacy-safe: redacted text previews, no raw secrets
- 270 tests pass, typecheck pass
2026-04-30 18:06:28 +08:00
Ralph Chang 617b3646d8 feat(evidence): wire evidence events into extraction, promotion, reinforcement, render, storage, and hook lifecycle
Phase 3 Tasks 3.2-3.6:
- Extraction evidence: accepted/rejected/explicit_detected/explicit_ignored
- Promotion evidence with relation edges (superseded/superseded_by, absorbed/retained)
- Reinforcement evidence with reinforced/reinforced_by relations
- Render accounting helper with render_selected/render_omitted evidence
- Storage evidence: corrupt_json_quarantined, stale_lock_recovered, lock_timeout
- Hook failure evidence in plugin
- All evidence failures swallowed, never throw into memory behavior
- Privacy-safe textPreview (redacted + truncated)
- 266 tests pass, typecheck pass
2026-04-30 17:54:13 +08:00
Ralph Chang 27e9d7ce92 feat(evidence): add evidence infrastructure - types, append, query, retention
Phase 3 Task 3.1:
- Create src/evidence-log.ts with EvidenceEventType, EvidencePhase,
  EvidenceOutcome, MemoryEvidenceRef, EvidenceRelation, EvidenceEventV1,
  EvidenceEventInput types
- Add appendEvidenceEvent/appendEvidenceEvents with safe write, privacy
  hashing (SHA-256 truncated), textPreview redaction, bounded retention
- Add queryEvidenceEvents, summarizeMemoryEvidence, traceMemoryLifecycle
- Add workspaceEvidenceLogPath to src/paths.ts
- Add 8 evidence-log tests: round-trip, privacy, query, resilience, retention
- Relations limited to wiring roles only (no kind/derived_from/validates)
- 253 tests pass
2026-04-30 17:33:40 +08:00
Ralph Chang aa7cc6c60e refactor(retention): extract retention module from workspace-memory
Move retention constants and math to a focused src/retention.ts module:
- All half-life, reinforcement, dormancy constants
- TYPE_FACTOR, SOURCE_FACTOR, USER_IMPORTANCE_FACTOR
- RETENTION_TYPE_MAX (renamed from TYPE_MAX)
- calculateInitialStrength, calculateEffectiveHalfLife,
  calculateRetentionStrength, calculateDormantDays,
  calculateEffectiveAgeDays, reinforceMemory

No behavior changes. retention.ts imports only types from types.ts.
Workspace-memory.ts still owns storage, consolidation, and rendering.
2026-04-30 17:28:31 +08:00
Ralph Chang 36f00147ca feat(deprecation): remove safetyCritical retention multiplier and type-cap bypass
- Remove SAFETY_CRITICAL_FACTOR = 6.0 from workspace-memory.ts
- Remove safetyFactor from calculateInitialStrength() - all memories now
  fade according to the same rules
- Remove safetyCritical bypass from applyTypeMaxCaps() - safetyCritical
  entries compete normally under TYPE_MAX caps
- Preserve safetyCritical?: boolean in LongTermMemoryEntry type for
  backward compatibility (no producer sets it to true)
- Update memory-diag to show deprecation warning instead of capacity alert
- Update tests: add backward-compatibility fixture test, deprecation
  strength test, normal cap competition test
- Update docs/architecture.md, RELEASE_NOTES.md, CHANGELOG.md,
  docs/configuration.md

Phase 1.5 complete: safetyCritical is now a deprecated field with no
active behavior. Safety rules belong in user-controlled agent.md files.
2026-04-30 17:23:01 +08:00
Ralph Chang 830d97c6c6 fix(security): harden hooks, quarantine corrupt JSON, test locks, fix promotion dedupe
- Wrap hooks with try/catch to prevent OpenCode disruption
- Add warnMemoryHook() for safe error logging
- Quarantine corrupt JSON files before fallback
- Add cross-process lock safety tests
- Fix pending promotion same-batch dedupe
- Update docs/architecture.md with lock semantics
- 242 tests passing
2026-04-30 11:52:01 +08:00
Ralph Chang 1c6e143f4b chore(release): prepare v1.5.0 2026-04-29 16:56:47 +08:00
Ralph Chang 73384ca0a4 feat(memory): add retention model test gaps and health diagnostics
Wave 1 - P0 Test Gaps:
- Add hard stale prune removed regression test
- Add dormant overlap tests (entry created during dormancy)
- Add invalid timestamp NaN protection test
- Add reinforcement ordering test with reference type
- Add dedupe same-session/under-1hr guard tests
- Fix NaN handling with Number.isFinite check

Wave 2 - Helper Functions:
- Add timestampMs() for safe timestamp conversion
- Add isSafetyCriticalForDiag() aligned with runtime

Wave 3 - Health Output Format:
- Fix top rendered candidates sorted by strength (not text length)
- Add stored vs rendered counts breakdown
- Add type caps and global cap overflow display
- Track globalCapped array explicitly
- Add dormant status section

Wave 4 - Monitoring Metrics:
- Add high_importance_ratio (alert > 30%)
- Add safety_critical_count (alert > 5)
- Add max_reinforced_count (alert > 10% active)

Wave 5 - Integration Fixture:
- Add 34-entry over-cap test
- Add mixed retention regression fixture
- Test TYPE_MAX caps, safety-critical exemption, reinforcement ordering

Tests: 224 → 237
2026-04-29 15:26:44 +08:00
Ralph Chang 04233f8452 fix(memory): correct dormant formula, remove hard prune, integrate reinforcement
P0.1 - Fix dormant effective age formula:
- Use overlap logic: only apply dormancy to entry's lifetime
- Formula: activeDays + dormantOverlapDays * 0.25
- calculateDormantDays now returns total days (not excess past grace)
- Test: 28 dormant days → 17.5 effective days

P0.2 - Remove hard stale pruning:
- Remove isPrunableByAge from enforcement
- Remove rejected_stale from accounting reasons
- Elimination now by cap competition only

P0.3 - Integrate reinforcement:
- Call reinforceMemory in dedupe absorption path
- Call reinforceMemory in promotion duplicate path
- Update retentionClock on reinforcement

A1 - Retention clock reset on reinforcement

A4 - Fix tests to encode correct formula
2026-04-29 14:55:25 +08:00
Ralph Chang ffb612226c feat(memory): add dormant tracking and reinforcement mechanism
Wave 2c - Dormant workspace tracking:
- Add lastActivityAt to WorkspaceMemoryStore
- Implement calculateDormantDays with 14-day grace period
- Wire dormant days into retention-strength calculation

Wave 3 - Reinforcement:
- Add lastReinforcedSessionID to LongTermMemoryEntry
- Implement reinforceMemory with guards (same-session, 1hr interval, max 6)
- Set retentionClock on memory creation in extractors.ts and plugin.ts

Tests: 219 → 222, all pass
2026-04-29 14:32:39 +08:00
Ralph Chang 4097815f3e feat(memory): implement retention decay model with strength-based ordering
- Add retention model constants (45-day half-life, 6.0 safety factor)
- Add TYPE_MAX caps (feedback:10, decision:10, project:8, reference:6)
- Add strength calculation: initialStrength × 2^(-age/halfLife)
- Integrate strength-based sorting into enforceLongTermLimits
- Safety-critical entries bypass type caps
- Add fields: retentionClock, reinforcementCount, userImportance, safetyCritical
2026-04-29 14:18:51 +08:00
Ralph Chang bb7e4e2927 feat: add maintainer diagnostics for memory quality calibration
- health: inspect workspace memory store, pending journal, offline quality checks
- rejections: review extraction rejection log with origin inference
- audit: review migration logs with risky supersede heuristic
- Maintainer-only, offline, no telemetry, no API calls
2026-04-29 10:25:35 +08:00
sdwolf4103 d700f4877f Merge pull request #4 from sdwolf4103/feat/memory-quality-cleanup
Release v1.4.0 memory quality cleanup
2026-04-28 14:53:12 +08:00
Ralph Chang c0a083ddaf fix(memory): isolate test workspace cleanup 2026-04-28 14:50:30 +08:00
Ralph Chang 8e07bfe3c1 fix(memory): address quality cleanup audit findings 2026-04-28 14:29:28 +08:00
Ralph Chang c7088a8a6e docs(memory): document conservative quality cleanup migration 2026-04-28 14:19:18 +08:00
Ralph Chang efed9e5585 test(memory): add real workspace quality cleanup regression fixture 2026-04-28 14:17:43 +08:00
Ralph Chang 7de10c5808 feat(memory): add local quality cleanup audit logs 2026-04-28 14:17:17 +08:00
Ralph Chang 12eddc2f8c fix(memory): make quality cleanup migration conservative 2026-04-28 14:15:34 +08:00
Ralph Chang 5e85d098d8 chore: prepare v1.4.0 release 2026-04-28 13:37:14 +08:00
Ralph Chang 99c6b97c96 fix: unify all memory quality rules in single module 2026-04-28 13:34:33 +08:00
Ralph Chang 83dcfb479c fix: auto-supersede low-quality compaction memories 2026-04-28 13:29:28 +08:00
Ralph Chang ed6005f6cf fix: tighten compaction memory candidate prompt 2026-04-28 13:24:43 +08:00
Ralph Chang 069ec8ecbb fix: unify workspace memory quality gate 2026-04-28 13:21:15 +08:00
Ralph Chang 60c7019820 chore: prepare v1.3.3 release 2026-04-28 13:06:14 +08:00
Ralph Chang 1847f63480 fix: owner scope in global unowned promotion
Problem: clearPendingMemories() and recordPromotionRejections() would
incorrectly clear or mutate owned entries during global unowned promotion.

Fixes:
1. clearPendingMemories() now respects owner/unowned scope:
   - global clearUnowned only clears unowned same-key entries
   - owned same-key entries are preserved
   - explicit global clear-all-by-key fallback still works

2. recordPromotionRejections() now has includeUnownedOnly option:
   - global unowned rejection only increments/exhausts unowned entries
   - owned same-key entries are preserved

3. Added regression tests:
   - global unowned clear keeps owned same-key entries
   - global unowned rejection only exhausts unowned same-key entries

Tests: 182 pass, 0 fail
2026-04-28 12:27:46 +08:00
Ralph Chang 8b21325469 fix: cross-process lock stale judgment and heartbeat
Problem: CI test "updateJSON serializes writes across separate node processes"
was failing with expect 100 but got 89/97. The root cause was isLockStale()
being too aggressive - it could mistakenly delete locks held by other processes.

Fixes:
1. isLockStale() now uses mtime only - fresh locks are never stale
2. Added heartbeat mechanism during lock hold to support long updaters
3. Removed PID check that was unreliable in CI/containers
4. Fixed ENOENT race when lock is released between EEXIST and stat

Tests: 180 pass, 0 fail
2026-04-28 12:24:56 +08:00
Ralph Chang b846b34e30 feat: implement Plan 1 - Critical Stability fixes
Wave 1: Storage and Journal Safety
- Add frozen cache TTL (1h) and size bounds (50 sessions)
- Add pending journal source-aware retention (compaction-only TTL)
- Add inter-process file lock with stale recovery
- Move processLatestUserMessage to first transform (after isSubAgent guard)

Wave 2: Promotion Ownership and Bounded Rejection
- Add pendingOwnerSessionID/pendingMessageID metadata
- Add owner-aware pending journal clearing
- Add explicit/manual bounded retry (max 3 attempts)
- Fix session.deleted cleanup idempotency

Wave 3: Normalize, Security, and Cache Hardening
- Fix load-time write loop (only write on security/migration change)
- Add deterministic sort tie-breaker (createdAt -> id)
- Add Bearer token redaction
- Add processed message cache bounds
- Remove priorityWithFreshness dead code

Tests: 180 pass, 0 fail
2026-04-28 11:59:29 +08:00
Ralph Chang 47905921ca fix: run compatibility CI on Node 24 2026-04-27 22:13:23 +08:00
Ralph Chang ca88193f9f fix: support CI installs without lockfile 2026-04-27 22:04:11 +08:00
Ralph Chang 1927cc8828 chore: prepare v1.3.1 release 2026-04-27 22:00:04 +08:00
Ralph Chang 64f86ef39c refactor: make memory dedupe repo-agnostic 2026-04-27 21:19:42 +08:00
Ralph Chang 39d27e8d3c docs: note PR 3 security hardening 2026-04-27 20:22:26 +08:00
Ralph Chang 77bf8af3fe test: cover security hardening edge cases 2026-04-27 20:22:09 +08:00
Ralph Chang 6eb341f43c merge: integrate PR #3 security hardening 2026-04-27 20:14:08 +08:00
Ralph Chang 6a1fa525dc docs: document concise compatibility limitations 2026-04-27 19:57:21 +08:00
Ralph Chang d6875aac1b fix: cap and prune pending memory journal 2026-04-27 18:54:44 +08:00
Ralph Chang c2ee245620 test: add opencode plugin compatibility checks 2026-04-27 18:54:14 +08:00
Steven Choo 15c0c8a45d feat: implement indirect prompt injection protection and expanded secret redaction 2026-04-27 12:42:20 +02:00
Ralph Chang 909fec9abb docs: prepare v1.3.0 release notes 2026-04-27 17:06:43 +08:00
Ralph Chang ef1248f23a feat: add consolidation accounting for workspace memory promotion
P0 implementation with four waves:

Wave 1: Dedup with accounting
- Add dedupeLongTermEntriesWithAccounting()
- Classify exact duplicate, identity duplicate, topic duplicate

Wave 2: Normalization with accounting
- Add normalizeWorkspaceMemoryWithAccounting()
- Chain redaction → migration → enforceLongTermLimitsWithAccounting

Wave 3: Promotion accounting integration
- Update accountPendingPromotions() to use new accounting API
- Add supersededKeys to classification
- Distinguish promoted / absorbed / superseded / rejected

Wave 4: Integration tests
- End-to-end tests covering full pipeline

Bug fixes:
- Fix active vs superseded boundary (superseded entries no longer block promotion)
- Remove unused rejected_duplicate_lower_quality type
- Defer pending journal safety cap (TODO added)

Tests: 135 passing (up from 115)
2026-04-27 16:45:55 +08:00
Ralph Chang c8c7dbed3b chore: ignore superpowers plans and update architecture doc
- Add docs/superpowers/plans/ to .gitignore
- Remove tracked plan files from git
- Update docs/architecture.md:
  - Change primary extraction format from XML to 'Memory candidates:'
  - Mark XML format as legacy/deprecated
  - Fix hot session state injection example
2026-04-27 14:53:07 +08:00
Ralph Chang bfa2972353 feat: sharpen compaction memory extraction prompt
Wave 3 of memory quality optimization plan.

- Add good memory examples in buildCompactionPrompt()
- Add bad memory examples to skip (test counts, commit hashes, etc.)
- Add prompt assertions in tests to prevent regression
- Emphasize 'useful if a new agent opens this workspace next week'
2026-04-27 14:40:32 +08:00
Ralph Chang 5fe4955057 test: add memory quality eval fixtures
Wave 2 of memory quality optimization plan.

- 5 accepted cases: durable facts that should be kept
- 7 rejected cases: noise that should be filtered
- Parser-level regression guard (zero API call)
- All cases pass against current extractors.ts
2026-04-27 14:34:53 +08:00
Ralph Chang 55e163adef fix: account for absorbed pending memories
- Add workspaceMemoryIdentityKey() to unify dedup/supersession identity semantics
- Add accountPendingPromotions() to distinguish promoted/absorbed/rejected
- Wire promotion accounting into promotePendingMemories()
- Add clearableKeys.size > 0 guard to prevent journal wipe
- Add regression tests for absorbed duplicate, cap-rejected, all-rejected edge cases

Wave 1 of memory quality optimization plan.
2026-04-27 14:27:43 +08:00
Ralph Chang 5ed57943d2 docs: add memory quality optimization implementation plan
P0 implementation plan with 3 waves:
- Wave 1: Promotion accounting (fix absorbed duplicate data loss)
- Wave 2: Memory quality eval (fixture-based regression guard)
- Wave 3: Compaction prompt negative examples

Addresses architecture review feedback:
- Distinguish promoted/absorbed/rejected pending memories
- Add clearableKeys.size > 0 guard to prevent journal wipe
- Add regression tests for all edge cases
2026-04-27 14:16:46 +08:00
sdwolf4103 2fc2172d59 Fix formatting in README.md 2026-04-27 13:00:26 +08:00
7 changed files with 433 additions and 43 deletions
+22
View File
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.5.5] - 2026-05-05
### Added
- Section-aware greedy line accumulator for hot session state rendering that fits whole lines instead of truncating mid-line.
- `accountHotSessionStateRender()` accounting function returning prompt text, omitted items, and char budget for v2 evidence extension.
- Exported types for render accounting diagnostics: `HotStateSection`, `HotStateOmissionReason`, `HotStateOmittedItem`, `HotSessionStateRenderAccounting`.
- 9 direct unit tests for hot session state rendering covering empty state, ranking, section caps, char budget, boundary conditions, header suppression, wrapper parity, and newline counting.
- Two-layer omission model: section caps first (`section_cap`), then char budget (`char_budget`), with clear per-item omission reasons.
### Changed
- Hot session state rendering no longer uses blunt `.slice(0, maxRenderedChars)` prompt truncation.
- Header-only sections are suppressed: a section is only rendered if at least one entry line fits the char budget.
- `renderHotSessionState()` is now a delegation wrapper to `accountHotSessionStateRender().prompt`, preserving backward compatibility.
- Fixed `docs/configuration.md` active-file ranking formula: was `count * action_weight * recency_decay` with weights 4/3/2/1, now correctly `ACTION_WEIGHT[action] + count * 3` with weights edit 50, write 45, grep 30, read 20, tie-break by `lastSeen` descending.
- Clarified `README.md` system prompt injection order: workspace memory and hot state index positions depend on whether workspace memory state is available.
### Fixed
- Hot session state prompt could be truncated mid-line under the old `.slice()` budget enforcement.
## [1.5.4] - 2026-05-02
### Changed
+4 -2
View File
@@ -85,11 +85,13 @@ OpenCode Working Memory adds durable memory without making extra LLM/API calls.
▼
┌──────────────────────────────────────┐
│ ⚡ Prompt Context │
│ system[1]: frozen workspace memory │
│ system[2+]: hot session state │
│ system[1]*: frozen workspace memory │
│ system[2+]*: hot session state │
└──────────────────────────────────────┘
```
\* Conceptually, workspace memory is pushed first when it is non-empty, and hot session state is pushed after workspace memory. If workspace memory is empty, hot state may be the first plugin-added system message. Actual `system[]` indices also depend on OpenCode and other plugins, so `system[1]` / `system[2+]` is a simplified model.
**Zero extra API calls:** OpenCode Working Memory does not call the model on its own. Memory extraction is folded into OpenCode's built-in compaction request.
**Cache-friendly layout:** durable workspace memory is rendered as a stable frozen snapshot for the session, while fast-changing hot session state is appended separately. Compaction starts a new cache epoch, refreshing the workspace snapshot after pending memories are promoted.
+38
View File
@@ -1,5 +1,43 @@
# Release Notes
## 1.5.5 (2026-05-05)
### Hot State Rendering Health
This release replaces blunt prompt truncation with a section-aware greedy renderer that fits whole lines and suppresses empty sections, plus render accounting types for future diagnostics.
> **Good rendering is selective too.** If a section doesn't fit, omit it — don't cut it in half.
### What Changed
- **Whole-line rendering**: the hot session state prompt no longer truncates mid-line with `.slice(0, maxRenderedChars)`. A greedy line accumulator fits complete lines and stops when the next line would exceed the 700-char budget.
- **Header-only sections suppressed**: a section heading is only rendered if at least one entry fits alongside it. No more orphaned `active_files:` headers with no content underneath.
- **Render accounting**: `accountHotSessionStateRender()` now returns `prompt`, `omitted[]`, and `maxRenderedChars` so future v2 diagnostics can surface which items fell out and why.
- **Two-layer omission model**: section caps (`section_cap`) trim per-type overflow first, then the char budget (`char_budget`) trims anything that doesn't fit. Each omitted item carries its reason and section.
- **Backward-compatible wrapper**: `renderHotSessionState()` delegates to the accounting function and returns just the prompt string, preserving existing plugin behavior.
### Docs Fixes
- **Active-file ranking formula corrected**: `docs/configuration.md` now matches the actual implementation — `ACTION_WEIGHT[action] + count * 3` with weights edit 50, write 45, grep 30, read 20, tie-break by `lastSeen` descending. The old docs claimed `count * action_weight * recency_decay` with weights 4/3/2/1.
- **Injection order clarified**: README now explains that workspace memory and hot state system-prompt positions depend on whether workspace memory state is available.
### Not Included Yet
- Evidence events for omitted items are deferred to v2, pending a `memory-diag` consumer to avoid unused storage litter.
### Upgrade Notes
- No configuration changes required.
- Existing workspace memory files remain compatible.
- Hot session state rendering behavior is intentionally different (cleaner output, no mid-line cuts), but the same information is presented when it fits within the budget.
### Validation
- `npm run typecheck` — `TYPECHECK_PASS`
- `npm test` — 356 tests passing, `TEST_PASS`
---
## 1.5.4 (2026-05-02)
### Memory Diagnostics Surface Cleanup
+23 -6
View File
@@ -87,16 +87,33 @@ const HOT_STATE_LIMITS = {
## Active File Scoring
Files are ranked by action type:
Files are ranked by action type plus repeated access count:
| Action | Weight | Description |
|--------|--------|-------------|
| `write` | 4 | File created/overwritten |
| `edit` | 3 | File modified |
| `read` | 2 | File read |
| `grep` | 1 | Grep searched in file |
| `edit` | 50 | File modified |
| `write` | 45 | File created/overwritten |
| `grep` | 30 | Grep searched in file |
| `read` | 20 | File read |
Score formula: `count * action_weight * recency_decay`
Score formula: `ACTION_WEIGHT[action] + count * 3`
When scores tie, the most recent `lastSeen` timestamp sorts first. There is no recency decay factor in the score itself.
## Hot Session State Truncation
Hot state rendering applies section caps before the character budget:
| Section | Rendered cap |
|---------|--------------|
| `active_files` | 8 |
| `open_errors` | 3 |
| `recent_decisions` | 8 |
| `pending_memories` | 6 |
After section caps, the renderer applies the 700-character budget with whole-line inclusion only. The prefix line is counted against the budget, and a section heading is emitted only when at least one entry from that section fits; header-only sections are suppressed.
`accountHotSessionStateRender()` returns prompt and omission accounting for future diagnostics. Evidence event integration for hot-state render omissions is planned for v2.
## Error Categories
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opencode-working-memory",
"version": "1.5.4",
"version": "1.5.5",
"description": "Three-layer memory architecture for OpenCode with workspace memory and hot session state",
"type": "module",
"main": "index.ts",
+135 -34
View File
@@ -189,49 +189,150 @@ export function clearErrorsForSuccessfulCommand(state: SessionState, command: st
state.updatedAt = new Date().toISOString();
}
export type HotStateSection = "active_files" | "open_errors" | "recent_decisions" | "pending_memories";
export type HotStateOmissionReason = "section_cap" | "char_budget";
export type HotStateOmittedItem = {
section: HotStateSection;
reason: HotStateOmissionReason;
text: string;
memoryId?: string;
};
export type HotSessionStateRenderAccounting = {
prompt: string;
omitted: HotStateOmittedItem[];
maxRenderedChars: number;
};
type HotStateRenderItem = {
section: HotStateSection;
line: string;
memoryId?: string;
};
type HotStateRenderSection = {
heading: `${HotStateSection}:`;
items: HotStateRenderItem[];
};
const HOT_STATE_PREFIX = "Hot session state (current session):";
export function accountHotSessionStateRender(state: SessionState, workspaceRoot: string): HotSessionStateRenderAccounting {
const maxRenderedChars = HOT_STATE_LIMITS.maxRenderedChars;
const omitted: HotStateOmittedItem[] = [];
const sections = buildHotStateRenderSections(state, workspaceRoot, omitted);
if (sections.every(section => section.items.length === 0)) {
return { prompt: "", omitted, maxRenderedChars };
}
const lines: string[] = [HOT_STATE_PREFIX];
let renderedEntryCount = 0;
for (const section of sections) {
let headingRendered = false;
for (const item of section.items) {
if (headingRendered) {
if (wouldFit(lines, item.line, maxRenderedChars)) {
lines.push(item.line);
renderedEntryCount += 1;
} else {
omitted.push(omitHotStateItem(item, "char_budget"));
}
continue;
}
if (wouldFit(lines, section.heading, maxRenderedChars)
&& wouldFit([...lines, section.heading], item.line, maxRenderedChars)) {
lines.push(section.heading, item.line);
headingRendered = true;
renderedEntryCount += 1;
} else {
omitted.push(omitHotStateItem(item, "char_budget"));
}
}
}
if (renderedEntryCount === 0) return { prompt: "", omitted, maxRenderedChars };
return { prompt: lines.join("\n"), omitted, maxRenderedChars };
}
export function renderHotSessionState(state: SessionState, workspaceRoot: string): string {
const activeFiles = rankActiveFiles(state.activeFiles).slice(0, HOT_STATE_LIMITS.maxActiveFilesRendered);
return accountHotSessionStateRender(state, workspaceRoot).prompt;
}
function buildHotStateRenderSections(
state: SessionState,
workspaceRoot: string,
omitted: HotStateOmittedItem[],
): HotStateRenderSection[] {
const activeFiles = rankActiveFiles(state.activeFiles).map(item => ({
section: "active_files" as const,
line: `- ${displayPath(workspaceRoot, item.path)} (${item.action}, ${item.count}x)`,
}));
const openErrors = [...state.openErrors]
.sort((a, b) => b.lastSeen - a.lastSeen)
.slice(0, HOT_STATE_LIMITS.maxOpenErrorsRendered);
const decisions = state.recentDecisions.slice(-HOT_STATE_LIMITS.maxRecentDecisionsStored);
const pendingMemories = dedupePendingMemories(state.pendingMemories)
.slice(-HOT_STATE_LIMITS.maxPendingMemoriesRendered);
.map(err => ({
section: "open_errors" as const,
line: `- [${err.category}] ${err.summary}`,
}));
const decisions = state.recentDecisions.map(item => ({
section: "recent_decisions" as const,
line: `- ${item.text}`,
}));
const pendingMemories = dedupePendingMemories(state.pendingMemories).map(item => ({
section: "pending_memories" as const,
line: `- [${item.type}] ${item.text}`,
memoryId: item.id,
}));
if (activeFiles.length === 0 && openErrors.length === 0 && decisions.length === 0 && pendingMemories.length === 0) return "";
const renderedActiveFiles = capHotStateItems(activeFiles, HOT_STATE_LIMITS.maxActiveFilesRendered, "start", omitted);
const renderedOpenErrors = capHotStateItems(openErrors, HOT_STATE_LIMITS.maxOpenErrorsRendered, "start", omitted);
const renderedDecisions = capHotStateItems(decisions, HOT_STATE_LIMITS.maxRecentDecisionsStored, "end", omitted);
const renderedPendingMemories = capHotStateItems(
pendingMemories,
HOT_STATE_LIMITS.maxPendingMemoriesRendered,
"end",
omitted,
);
const lines: string[] = ["Hot session state (current session):"];
return [
{ heading: "active_files:", items: renderedActiveFiles },
{ heading: "open_errors:", items: renderedOpenErrors },
{ heading: "recent_decisions:", items: renderedDecisions },
{ heading: "pending_memories:", items: renderedPendingMemories },
];
}
if (activeFiles.length > 0) {
lines.push("active_files:");
for (const item of activeFiles) {
const viewPath = displayPath(workspaceRoot, item.path);
lines.push(`- ${viewPath} (${item.action}, ${item.count}x)`);
}
}
function capHotStateItems(
items: HotStateRenderItem[],
cap: number,
keep: "start" | "end",
omitted: HotStateOmittedItem[],
): HotStateRenderItem[] {
if (items.length <= cap) return items;
if (openErrors.length > 0) {
lines.push("open_errors:");
for (const err of openErrors) {
lines.push(`- [${err.category}] ${err.summary}`);
}
}
const renderedItems = keep === "start" ? items.slice(0, cap) : items.slice(-cap);
const omittedItems = keep === "start" ? items.slice(cap) : items.slice(0, items.length - cap);
omitted.push(...omittedItems.map(item => omitHotStateItem(item, "section_cap")));
return renderedItems;
}
if (decisions.length > 0) {
lines.push("recent_decisions:");
for (const decision of decisions) {
lines.push(`- ${decision.text}`);
}
}
function omitHotStateItem(item: HotStateRenderItem, reason: HotStateOmissionReason): HotStateOmittedItem {
return {
section: item.section,
reason,
text: item.line,
...(item.memoryId ? { memoryId: item.memoryId } : {}),
};
}
if (pendingMemories.length > 0) {
lines.push("pending_memories:");
for (const memory of pendingMemories) {
lines.push(`- [${memory.type}] ${memory.text}`);
}
}
return lines.join("\n").slice(0, HOT_STATE_LIMITS.maxRenderedChars);
function wouldFit(lines: string[], nextLine: string, maxRenderedChars: number): boolean {
return [...lines, nextLine].join("\n").length <= maxRenderedChars;
}
function rankActiveFiles(activeFiles: ActiveFile[]): ActiveFile[] {
+210
View File
@@ -0,0 +1,210 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as sessionStateModule from "../src/session-state.ts";
import type { HotSessionStateRenderAccounting } from "../src/session-state.ts";
import type { ActiveFile, LongTermMemoryEntry, OpenError, SessionDecision, SessionState } from "../src/types.ts";
import { HOT_STATE_LIMITS } from "../src/types.ts";
type AccountHotSessionStateRender = (state: SessionState, workspaceRoot: string) => HotSessionStateRenderAccounting;
const accountHotSessionStateRender = (
sessionStateModule as typeof sessionStateModule & { accountHotSessionStateRender: AccountHotSessionStateRender }
).accountHotSessionStateRender;
const { createEmptySessionState, renderHotSessionState } = sessionStateModule;
const root = "/repo";
function state(overrides: Partial<SessionState> = {}): SessionState {
return {
version: 1,
sessionID: "session-state-test",
turn: 0,
updatedAt: "2026-05-05T00:00:00.000Z",
activeFiles: [],
openErrors: [],
recentDecisions: [],
pendingMemories: [],
...overrides,
};
}
function activeFile(path: string, action: ActiveFile["action"], count: number, lastSeen: number): ActiveFile {
return { path, action, count, lastSeen };
}
function openError(id: string, summary: string, lastSeen: number): OpenError {
return {
id,
category: "test",
summary,
fingerprint: `fingerprint-${id}`,
status: "open",
firstSeen: lastSeen - 1,
lastSeen,
seenCount: 1,
};
}
function decision(id: string, text: string, createdAt: number): SessionDecision {
return { id, text, source: "assistant", createdAt };
}
function memory(id: string, text: string, type: LongTermMemoryEntry["type"] = "decision"): LongTermMemoryEntry {
return {
id,
type,
text,
source: "compaction",
confidence: 0.75,
status: "active",
createdAt: "2026-05-05T00:00:00.000Z",
updatedAt: "2026-05-05T00:00:00.000Z",
};
}
test("accountHotSessionStateRender returns empty prompt and no omissions for empty state", () => {
const accounting = accountHotSessionStateRender(createEmptySessionState("empty-session"), root);
assert.equal(accounting.prompt, "");
assert.deepEqual(accounting.omitted, []);
assert.equal(accounting.maxRenderedChars, HOT_STATE_LIMITS.maxRenderedChars);
});
test("accountHotSessionStateRender renders hot-state sections in stable order", () => {
const accounting = accountHotSessionStateRender(state({
activeFiles: [activeFile("/repo/src/a.ts", "read", 1, 1)],
openErrors: [openError("err-1", "one failing test", 2)],
recentDecisions: [decision("dec-1", "Keep renderer simple", 3)],
pendingMemories: [memory("mem-1", "Promote useful fact")],
}), root);
assert.ok(accounting.prompt.startsWith("Hot session state (current session):"));
assert.ok(accounting.prompt.indexOf("active_files:") < accounting.prompt.indexOf("open_errors:"));
assert.ok(accounting.prompt.indexOf("open_errors:") < accounting.prompt.indexOf("recent_decisions:"));
assert.ok(accounting.prompt.indexOf("recent_decisions:") < accounting.prompt.indexOf("pending_memories:"));
});
test("accountHotSessionStateRender ranks active files by score then lastSeen descending", () => {
const accounting = accountHotSessionStateRender(state({
activeFiles: [
activeFile("/repo/src/edit.ts", "edit", 1, 400),
activeFile("/repo/src/write.ts", "write", 5, 200),
activeFile("/repo/src/grep.ts", "grep", 10, 300),
activeFile("/repo/src/read.ts", "read", 12, 100),
],
}), root);
const lines = accounting.prompt.split("\n");
const activeLines = lines.filter(line => line.startsWith("- src/"));
assert.deepEqual(activeLines, [
"- src/grep.ts (grep, 10x)",
"- src/write.ts (write, 5x)",
"- src/read.ts (read, 12x)",
"- src/edit.ts (edit, 1x)",
]);
});
test("accountHotSessionStateRender reports section-cap omissions for every capped section", () => {
const accounting = accountHotSessionStateRender(state({
activeFiles: Array.from({ length: 9 }, (_, index) => activeFile(`/repo/a${index}.ts`, "read", 1, 100 - index)),
openErrors: Array.from({ length: 4 }, (_, index) => openError(`err-${index}`, `e${index}`, 100 - index)),
recentDecisions: Array.from({ length: 9 }, (_, index) => decision(`dec-${index}`, `d${index}`, index)),
pendingMemories: Array.from({ length: 7 }, (_, index) => memory(`mem-${index}`, `m${index}`)),
}), root);
const sectionCapOmissions = accounting.omitted.filter(item => item.reason === "section_cap");
assert.deepEqual(
sectionCapOmissions.map(item => item.section).sort(),
["active_files", "open_errors", "pending_memories", "recent_decisions"].sort(),
);
assert.equal(sectionCapOmissions.find(item => item.section === "pending_memories")?.memoryId, "mem-0");
});
test("accountHotSessionStateRender omits over-budget entries without cutting rendered lines", () => {
const longPath = `/repo/${"x".repeat(650)}.ts`;
const accounting = accountHotSessionStateRender(state({
activeFiles: [
activeFile("/repo/src/short.ts", "read", 1, 20),
activeFile(longPath, "read", 1, 10),
],
}), root);
assert.equal(accounting.prompt, [
"Hot session state (current session):",
"active_files:",
"- src/short.ts (read, 1x)",
].join("\n"));
assert.equal(accounting.omitted.length, 1);
assert.equal(accounting.omitted[0]?.reason, "char_budget");
assert.equal(accounting.omitted[0]?.section, "active_files");
assert.ok(!accounting.prompt.includes("x".repeat(20)));
});
test("accountHotSessionStateRender includes exact 700-char prompt but omits one additional character", () => {
const fixedPrompt = [
"Hot session state (current session):",
"pending_memories:",
"- [decision] ",
].join("\n");
const exactText = "x".repeat(HOT_STATE_LIMITS.maxRenderedChars - fixedPrompt.length);
const exactAccounting = accountHotSessionStateRender(state({
pendingMemories: [memory("mem-exact", exactText)],
}), root);
assert.equal(exactAccounting.prompt.length, HOT_STATE_LIMITS.maxRenderedChars);
assert.equal(exactAccounting.omitted.length, 0);
const overAccounting = accountHotSessionStateRender(state({
pendingMemories: [memory("mem-over", `${exactText}y`)],
}), root);
assert.equal(overAccounting.prompt, "");
assert.equal(overAccounting.omitted.length, 1);
assert.equal(overAccounting.omitted[0]?.reason, "char_budget");
assert.equal(overAccounting.omitted[0]?.memoryId, "mem-over");
});
test("accountHotSessionStateRender suppresses header-only sections when no entries fit", () => {
const accounting = accountHotSessionStateRender(state({
activeFiles: [activeFile(`/repo/${"z".repeat(720)}.ts`, "read", 1, 1)],
}), root);
assert.equal(accounting.prompt, "");
assert.equal(accounting.omitted.length, 1);
assert.equal(accounting.omitted[0]?.reason, "char_budget");
assert.ok(!accounting.prompt.includes("active_files:"));
});
test("renderHotSessionState delegates to accounted renderer prompt for empty and seeded states", () => {
const empty = createEmptySessionState("compat-empty");
const seeded = state({
activeFiles: [activeFile("/repo/src/a.ts", "edit", 2, 1)],
pendingMemories: [memory("mem-compat", "Compatibility prompt")],
});
assert.equal(renderHotSessionState(empty, root), accountHotSessionStateRender(empty, root).prompt);
assert.equal(renderHotSessionState(seeded, root), accountHotSessionStateRender(seeded, root).prompt);
});
test("accountHotSessionStateRender counts newline separators in the 700-char budget", () => {
const fixedPrompt = [
"Hot session state (current session):",
"recent_decisions:",
"- ",
].join("\n");
const exactText = "n".repeat(HOT_STATE_LIMITS.maxRenderedChars - fixedPrompt.length);
const exactAccounting = accountHotSessionStateRender(state({
recentDecisions: [decision("dec-exact", exactText, 1)],
}), root);
assert.equal(exactAccounting.prompt.length, HOT_STATE_LIMITS.maxRenderedChars);
assert.equal(exactAccounting.omitted.length, 0);
const overAccounting = accountHotSessionStateRender(state({
recentDecisions: [decision("dec-over", `${exactText}!`, 1)],
}), root);
assert.equal(overAccounting.prompt, "");
assert.equal(overAccounting.omitted.length, 1);
assert.equal(overAccounting.omitted[0]?.reason, "char_budget");
});