Skip to content

feat(gemini): optimize context caching and TPM usage#220

Open
psklarkins wants to merge 64 commits intomicrosoft:mainfrom
psklarkins:feature/gemini-optimization
Open

feat(gemini): optimize context caching and TPM usage#220
psklarkins wants to merge 64 commits intomicrosoft:mainfrom
psklarkins:feature/gemini-optimization

Conversation

@psklarkins
Copy link

Summary

This PR implements critical context caching and TPM optimizations for Gemini on OpenCode.

  • Gold Prefix Optimization: Refactored hook_session_start.py to isolate a stable "Frozen Zone" (Identity, Mandates) from dynamic "Churn Zone" (Date, Memory). This ensures the context prefix remains bit-for-bit identical across sessions, maximizing cache hits.
  • Subagent Cache Inheritance: Updated sync-agents-to-opencode.py to bake the Frozen Zone into every generated SKILL.md. Now subagents share the same prefix as the main session, starting with a "Warm Cache" instead of cold.
  • TPM Protection: Forced model: flash for high-volume implementation agents (modular-builder, test-coverage, etc.) in OpenCode generation to prevent "Pro" model rate limit exhaustion during parallel dispatch.

Test Plan

  • Verified hook_session_start.py outputs Frozen Zone first and Churn Zone last.
  • Verified sync-agents-to-opencode.py injects Frozen Zone into generated skills.
  • Verified modular-builder skill maps to flash model.
  • Confirmed dynamic content (Date, Platform) appears only at the end of the prompt.

psklarkins and others added 30 commits February 6, 2026 10:13
Unify the amplifier-claude branch (30 agents, 19 commands, hooks, MCP
servers, design philosophy docs) with v2's improved foundation from main
(recipes, behaviors, context, branding).

Key changes:
- Merge 9 agents with foundation improvements (zen-architect, bug-hunter,
  modular-builder, test-coverage, security-guardian, integration-specialist,
  post-task-cleanup, content-researcher, analysis-engine)
- Strip boilerplate from agent frontmatter, keep model: inherit
- Update .mcp.json: remove deprecated browser-use and unused zen servers
- Enable all 4 MCP servers (playwright, context7, deepwiki, repomix)
- Update .gitignore for Windows reserved names, session artifacts, .data/
- Update README for integrated branch description
- Add amplifier-expert agent to FuseCP project
- Rewrite 5 global agents with ruthless simplicity

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Integrate Claude Code customizations with Amplifier v2
On Windows, .py and .sh files can't be executed directly as commands.
Prefix all hook commands with 'python' or 'bash' so they work on
Windows Server without .cmd wrapper scripts.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
fix: add explicit interpreter to hook commands for Windows
Windows Store python stub intercepts 'python' command and shows install
prompt instead of running scripts. Use 'uv run' which correctly uses
the project's .venv Python managed by uv.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
The $CLAUDE_PROJECT_DIR env var was not being expanded by uv on
Windows, causing all hooks to fail with "path not found". Hooks
run from the project directory so relative paths work correctly.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Syncs local Amplifier-integrated superpowers files into Claude Code's
plugin cache on each session start, ensuring marketplace updates don't
overwrite our modifications.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
All 23 Amplifier agent files had single-line descriptions containing
<example> XML tags that broke Claude Code's YAML frontmatter parser,
causing "Missing required name field" errors on session start.

Converted to block scalar (description: |) format matching the 7
working design agents. Preserved tools and model fields.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Move MEMORY_SYSTEM_ENABLED check and module import before HookLogger
initialization. When modules don't exist (MemoryStore, ClaimValidator),
exit silently without writing to stderr - which Claude Code surfaces
as "PostToolUse:Edit hook error".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Integrate Gemini-developed git-notes memory tools into Claude Code's
hook system for cross-machine state sharing between Claude Code and
Gemini/OpenCode platforms.

- Add SessionStart hook (hook_memory_sync.py) to fetch git notes
- Add PreCompact push to sync notes before context compaction
- Add Python memory wrapper (memory.py) for recall/memorize/snapshot
- Register memory sync hook in settings.json
- Include design doc and implementation plan

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Design to reduce main context consumption from 70-103k tokens (35-52%)
to 25-40k tokens (13-20%) before implementation starts.

Three priority tiers:
- P1: Remove always-loaded design @imports, deduplicate AGENTS.md (~17k saved)
- P2: Delegate brainstorming context gathering, writing-plans, and spec
  writing to subagents instead of running in main context (~18-45k saved)
- P3: Add context budget guardrails to all 30 agent definitions, with
  specific limits for 7 high-risk agents

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
12 tasks across 2 repos (amplifier + superpowers), 3 priority tiers:
- P1 (Tasks 1-3): Remove design @imports, deduplicate AGENTS.md, archive DISCOVERIES
- P2 (Tasks 4-7): Context scout subagent, delegate spec/plan writing, output discipline
- P3 (Tasks 8-10): Universal context budget for 30 agents, specific limits for 7 high-risk
- Verification (Tasks 11-12): Token savings, skill changes, agent guardrails, cleanup

Also aligned spec subagent_type references with 449100e pattern (general-purpose).

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Design files (DESIGN-PHILOSOPHY, DESIGN-PRINCIPLES, DESIGN-FRAMEWORK,
DESIGN-VISION) are now loaded on demand by design agents only.
Saves ~14,000 tokens per session for non-design tasks.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Implementation Philosophy and Modular Design Philosophy sections were
duplicated from ai_context/ files already loaded via CLAUDE.md @imports.
Replaced with references. Saves ~2,000 tokens per session.

Reduced file from 757 to 424 lines. All other sections preserved:
- Git commit message guidelines
- Sub-agent strategy
- Incremental processing pattern
- Partial failure handling
- Decision tracking system
- Configuration management
- Response authenticity guidelines
- Zero-BS principle
- Build/test/lint commands
- Code style and formatting
- Dev environment tips
- Testing instructions
- Documentation guidelines

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Moved DevContainer Setup, pnpm Global Bin, and OneDrive/Cloud Sync
entries to DISCOVERIES-archive.md. Kept Tool Generation Patterns and
LLM Response Handling (still actively relevant). Saves ~1,000 tokens.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Every agent now has file read limits (max 15), output size targets
(max 300 lines), stop conditions (10 reads without progress), and
no-replan instructions. Prevents agent context window exhaustion.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
content-researcher: max 20 scan, 5 deep-read
analysis-engine: mode-specific caps (30/3/5)
bug-hunter: 10 reads before hypothesis, 3 cycles max
security-guardian: require explicit scope, no unbounded scans
post-task-cleanup: summary review for >15 file changesets
amplifier-cli-architect: lazy-load references
modular-builder: return paths+summaries for large files

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
…loading

Design agents now read DESIGN-PHILOSOPHY, DESIGN-PRINCIPLES,
DESIGN-FRAMEWORK, and DESIGN-VISION on demand. These files were
removed from the always-loaded @import chain in Task 1 to save
~14,000 tokens per non-design session.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Reviewed: AGENTS.md correctly deduplicated (424 lines), all 30 agents have context budget, 7 high-risk agents have specific limits, 7 design agents have Required Context.
Add max_turns budgets, resume protocol, and task decomposition
guidelines to prevent subagents from exhausting their context
windows. Addresses two observed failure modes: abrupt stops and
summary-mode fallback under token pressure.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Clarify Task tool resume parameter syntax and add context that
referenced skills are from the superpowers plugin.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
…tocol

docs: add subagent resilience protocol
Detects Claude Code (C:/claude/) vs Gemini/OpenCode (C:/Przemek/)
by checking which root directory exists. Exports IS_CLAUDE_CODE,
IS_OPENCODE, AMPLIFIER_ROOT, and SUPERPOWERS_FALLBACK constants
for use by all hooks instead of hardcoded paths.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Replace hardcoded C:/claude/superpowers fallback paths in memory.py,
hook_memory_sync.py, and hook_precompact.py with SUPERPOWERS_FALLBACK
from platform_detect module. Both Claude Code and Gemini machines
now resolve paths correctly from the same codebase.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
…ctor

- Refactor export_transcript() to accept pre-parsed full_entries,
  avoiding double I/O when entries are already parsed
- Extract parse_transcript_entries() as reusable function
- Add GoldPrefixCompactor class for Gemini context cache optimization,
  gated with IS_OPENCODE (inactive on Claude Code)
- Improve summarize_stable() to include user message summaries
  instead of just tool counts
- Preserve TimeoutExpired handler in push_memory_notes()

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Add platform-aware context formatting in session start hook:
- FROZEN ZONE / CHURN ZONE labels only active on OpenCode (Gemini
  context caching optimization)
- Claude Code gets clean "Relevant Context" / "Session Environment"
  headers without zone labels
- Add dynamic session context (date, platform, cwd) for both
  platforms — useful environment info without cache-specific noise

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Creates scripts/sync-agents-to-opencode.py that generates
agents/*/SKILL.md from canonical .claude/agents/*.md definitions.
Adds recommended_model (pro/flash) and tools frontmatter fields
required by OpenCode. Keeps .claude/agents/ as single source of truth.

Run: python scripts/sync-agents-to-opencode.py [--dry-run]

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Documents the Gold Prefix strategy for Gemini context caching,
platform detection architecture, hook changes with gating,
and agent sync approach. Covers both Claude Code and OpenCode
perspectives.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
psklarkins and others added 25 commits February 15, 2026 16:16
…ctor

- Refactor export_transcript() to accept pre-parsed full_entries,
  avoiding double I/O when entries are already parsed
- Extract parse_transcript_entries() as reusable function
- Add GoldPrefixCompactor class for Gemini context cache optimization,
  gated with IS_OPENCODE (inactive on Claude Code)
- Improve summarize_stable() to include user message summaries
  instead of just tool counts
- Preserve TimeoutExpired handler in push_memory_notes()

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Add platform-aware context formatting in session start hook:
- FROZEN ZONE / CHURN ZONE labels only active on OpenCode (Gemini
  context caching optimization)
- Claude Code gets clean "Relevant Context" / "Session Environment"
  headers without zone labels
- Add dynamic session context (date, platform, cwd) for both
  platforms — useful environment info without cache-specific noise

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Creates scripts/sync-agents-to-opencode.py that generates
agents/*/SKILL.md from canonical .claude/agents/*.md definitions.
Adds recommended_model (pro/flash) and tools frontmatter fields
required by OpenCode. Keeps .claude/agents/ as single source of truth.

Run: python scripts/sync-agents-to-opencode.py [--dry-run]

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Documents the Gold Prefix strategy for Gemini context caching,
platform detection architecture, hook changes with gating,
and agent sync approach. Covers both Claude Code and OpenCode
perspectives.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
feat: platform-aware hooks for Claude Code + Gemini dual-machine support
Create .claude/AGENTS_CATALOG.md with all 30 specialized agents organized
by category (Core Development, API & Data, Design, Knowledge & Analysis,
Meta). Includes dispatch keywords, review agent mapping, model tier mapping,
and selection rules.

This file is referenced by AGENTS.md but was previously missing. It serves
as the authoritative catalog for agent selection during task delegation.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Comprehensive design for migrating all 14 Superpowers workflow skills into
native Amplifier commands. Eliminates fork maintenance burden, resolves
command redundancy/confusion, and enables full integration with Amplifier's
30 specialized agents.

Key outcomes:
- 14 skills → 13 commands + 1 embedded config
- 27 total commands → 24 unified commands
- Zero external plugin dependencies
- 100% agent integration (vs 4/14 currently)

Migration organized in 4 phases:
1. Core Pipeline (brainstorm/plan/execute)
2. Development Discipline (debug/tdd/verify)
3. Git & Review Workflow (worktree/branch/review)
4. Meta & Cleanup (write-skill + dependency removal)

Includes detailed transformation rules, agent allocation, test plan,
acceptance criteria, and rollback strategy.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Comprehensive plan for migrating all 14 superpowers workflow skills to native
Amplifier commands:
- 13 new commands (brainstorm, subagent-dev, parallel-agents, debug, tdd,
  verify, worktree, finish-branch, request-review, receive-review, write-skill)
- 2 enriched stubs (create-plan, execute-plan)
- 1 embedded in CLAUDE.md (using-superpowers meta content)

Plan organized into 4 chunks:
- Chunk 1: Core Pipeline (brainstorm → plan → execute)
- Chunk 2: Development Discipline (debug, tdd, verify)
- Chunk 3: Git & Review Workflow (worktree, finish-branch, reviews)
- Chunk 4: Meta & Cleanup (write-skill, infrastructure updates)

Each task includes specific agent assignment, transformation rules, verification
commands, and commit messages. Cross-reference mapping ensures all superpowers:
references are replaced with /command-name format.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
…k 1)

Migrates 5 Superpowers workflow skills to native .claude/commands/:
- brainstorm.md (163 lines) + visual-companion.md (198 lines)
- create-plan.md enriched from 15→228 lines
- execute-plan.md enriched from 23→84 lines
- subagent-dev.md (613 lines, 3 prompt templates inlined)
- parallel-agents.md (167 lines)

All commands verified: zero superpowers:, CLAUDE_PLUGIN_ROOT, or recall.js
references. Full methodology preserved with native agent dispatch.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…unk 2)

Migrates 3 methodology skills to native .claude/commands/:
- debug.md (369 lines) — systematic debugging with bug-hunter dispatch
- tdd.md (454 lines) — TDD methodology with test-coverage dispatch
- verify.md (142 lines) — verification-before-completion discipline

Supporting techniques (root-cause-tracing, defense-in-depth,
condition-based-waiting) inlined into debug.md. All verified clean.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…nk 3)

Migrates 4 workflow skills to native .claude/commands/:
- worktree.md (201 lines) — git worktree isolation practices
- finish-branch.md (203 lines) — branch completion with post-task-cleanup
- request-review.md (205 lines) — formal review with zen-architect dispatch
- receive-review.md (222 lines) — review feedback handling

All verified clean: zero banned references, methodology preserved.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Migrate writing-skills → /write-skill (626 lines, command authoring with TDD)
- Add Amplifier Commands section to CLAUDE.md (usage guidance, priority order)
- Update AGENTS.md cross-references to native /command-name format
- Fix stale "finishing-a-development-branch skill" reference in execute-plan.md

Migration summary:
- 14 command files created (3,875 total lines)
- 2 existing commands enriched (create-plan, execute-plan)
- 1 meta skill embedded in CLAUDE.md (using-superpowers)
- 0 superpowers: references in commands, CLAUDE.md, or AGENTS.md

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Three minor wording fixes caught by final review:
- brainstorm.md: "the /create-plan skill comes first" → simplified
- create-plan.md: "from this skill" → "from this command"
- execute-plan.md: "this skill executes" → "this command executes"

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Migrate Superpowers skills to native Amplifier commands
The superpowers plugin sync hook is no longer needed now that all
14 skills have been migrated to native Amplifier commands. The sync
script copied modified skills into the plugin cache, which is
unnecessary with native .claude/commands/ files.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
7 of 8 agent-dispatching commands were missing max_turns parameters,
risking the context exhaustion failures documented in DISCOVERIES.md.
Added turn budgets from AGENTS.md and resume protocol guidance.

Commands updated: brainstorm, subagent-dev, parallel-agents,
ultrathink-task, write-skill

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Strip GoldPrefixCompactor class, Frozen/Churn zone labels, and
platform_detect.py from main branch. This code is preserved on
feature/gemini-opencode branch for future Gemini deployments.

Changes:
- Remove GoldPrefixCompactor class from hook_precompact.py (~125 lines)
- Remove IS_OPENCODE zone labels from hook_session_start.py
- Remove Gold Prefix analysis block from hook_precompact.py main()
- Replace platform_detect imports with inline SUPERPOWERS_FALLBACK constant

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Reverting the Gemini code separation (6080795). Since both platforms
are used daily, maintaining a separate branch creates unacceptable
drift. All Gemini-specific code is gated by IS_OPENCODE and never
executes on the Claude Code machine.

Restored:
- platform_detect.py — runtime Claude Code vs OpenCode detection
- GoldPrefixCompactor — Gemini context caching optimization
- FROZEN ZONE/CHURN ZONE labels — gated by IS_OPENCODE
- sync-agents-to-opencode.py — agent format converter
- Context caching design spec

Architecture decision: one codebase, runtime-gated platform features.

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
Comprehensive documentation for the Claude Code + OpenCode/Gemini
runtime-gated architecture. Covers platform detection, Gold Prefix
caching, agent sync, maintenance guidelines, and the architectural
decision rationale.

Updated: design spec → full dual-platform reference
Added: DISCOVERIES.md entry for branch vs runtime gating decision

🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
…ion control and ignore it. Remove orphan amplifier-expert agent.
@microsoft-github-policy-service

@psklarkins please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@psklarkins
Copy link
Author

Review: feat(gemini): optimize context caching and TPM usage

Verdict: Request Changes — Good concept, needs cleanup before merge.

What Works Well

  • Frozen/Churn Zone separation is architecturally sound for Gemini prefix caching
  • Defensive error handling improvements (stdin read, JSON parse, empty input) benefit both platforms
  • seen_ids refactoring — DRY improvement, calculated once instead of twice
  • memories_loaded simplification — cleaner calculation
  • No Claude Code regressions — the else: branch is functionally equivalent to current main

Issues to Address

1. Memory rendering logic duplicated (High)
The identical ~24-line block (search_results iteration + unique_recent iteration) is copy-pasted into both the if IS_OPENCODE: and else: branches of hook_session_start.py. The only differences are heading levels and section titles. This violates DRY and creates a maintenance liability — any future change to memory formatting must be applied in two places.

Fix: Extract a shared helper function:

def format_memories(search_results, unique_recent, heading_level="###"):
    parts = []
    if search_results:
        parts.append(f"{heading_level} Relevant Memories")
        for result in search_results[:3]:
            parts.append(f"- **{result.memory.category}** (relevance: {result.score:.2f}): {result.memory.content}")
    if unique_recent:
        parts.append(f"\n{heading_level} Recent Context")
        for mem in unique_recent[:2]:
            parts.append(f"- {mem.category}: {mem.content}")
    return parts

Both branches call this with different heading levels. Single source of truth.

2. Session environment block also duplicated (Low)
The 3 lines formatting date/platform/cwd appear identically in both branches. Same fix pattern — extract or share.

3. frozen_header.md needs purpose comment (Medium)
The file contains OpenCode-specific identity text ("You are opencode...") in the shared repo. It's functionally gated (only read inside if IS_OPENCODE:), but should include a comment header explaining this:

<!-- OpenCode/Gemini only: Stable prefix for context caching.
     Read by hook_session_start.py inside IS_OPENCODE guard.
     Not used on Claude Code. -->

4. Plan doc references machine-specific paths (Low)
docs/superpowers/plans/2026-02-16-gemini-optimization-plan.md references C:/Przemek/ and C:/Users/biuro/ throughout. For an upstream PR, these should be relative paths or clearly noted as OpenCode-machine-specific.

Summary

The Frozen Zone / Churn Zone architecture is well-motivated. The defensive improvements are welcome. Fix the code duplication (extract shared helpers) and add context comments to the Gemini-only files, and this is good to merge.


🤖 Generated with Amplifier

@psklarkins
Copy link
Author

Changes Implemented

Addressed all review feedback:

  1. DRY Fix in hook_session_start.py: Extracted format_memories and format_session_env helpers to eliminate duplication between branches.
  2. Context Comment: Added purpose comment to .claude/context/frozen_header.md explaining it's only used for OpenCode caching.
  3. Path Fixes: Updated plan document to use relative paths instead of hardcoded machine paths.

Ready for re-review.

@psklarkins
Copy link
Author

Re-Review: commit 9281231 addresses all feedback

All 4 findings from the initial review have been addressed:

# Finding Status
1 Memory rendering duplicated Fixed — extracted format_memories() helper with base_heading_level param. Both branches now call it (Gemini: level 3, Claude Code: level 2). Single source of truth.
2 Session environment duplicated Fixed — extracted format_session_env() helper. Both branches use context_parts.extend(format_session_env()).
3 frozen_header.md needs purpose comment Fixed — HTML comment added: "OpenCode/Gemini only: Stable prefix for context caching. Read by hook_session_start.py inside IS_OPENCODE guard. Not used on Claude Code."
4 Plan doc machine-specific paths FixedC:/Przemek/ paths replaced with relative ./ paths, C:/Users/biuro/ replaced with ${OPENCODE_SKILLS_DIR}.

Verification

  • Python AST parse: compiles cleanly
  • Claude Code path: memories first (h2/h3), then "Session Environment" — unchanged behavior
  • Gemini path: Frozen Zone header, then Churn Zone with session env + memories (h3/h4) — correct structure
  • Helper functions are clean, minimal, and well-parameterized

Verdict: APPROVE — Ready to merge.


🤖 Generated with Amplifier

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments