Category: AI Coding

AI-assisted software development, coding agents, AI coding tools, coding LLMs, context engineering, vibe coding, and automated workflows for building software faster.

  • Kimi K3 Context Engineering for Coding Agents

    Kimi K3 Context Engineering for Coding Agents


    Kimi K3 context engineering means giving a coding agent a small, current, reviewable evidence packet before it edits a repository. Start with a bounded task, add the architecture, dependencies, decisions, and tests that govern it, let the agent inspect the current revision, and keep a human accountable for the final change. A one-million-token model window can hold more material; it does not turn an old chat or a broad prompt into durable repository memory.

    Kimi exposes K3 as the kimi-k3 API model and as k3 or k3-256k in Kimi Code. Its official documentation describes tool calling, long context, and coding clients, but it does not describe a native, persistent repository-memory feature. Treat repository memory as a team-maintained context layer, not an ability the model automatically acquires. For a K3-specific evaluation protocol, see Kimi K3 Codebase Understanding Tests.

    Before You Use Kimi K3 on a Repo

    Confirm the actual surface before you design the workflow. On the Kimi API platform, kimi-k3 is documented with a one-million-token context window, automatic prefix caching, custom tools, and top-level reasoning_effort. Kimi Code documents a separate membership-based client surface: k3 can reach up to 1M for eligible plans, while k3-256k is fixed at 256K. A third-party agent can also impose a smaller context setting or compact the session before K3 receives it.

    That distinction changes the first operational question. Do not ask “Does K3 have 1M?” Ask “Which model ID, client, account tier, client-side context cap, compaction policy, and reasoning setting will this task actually use?” Record them with the repository revision. A result from a 256K compacted session and one from a 1M API request are different runs, even if both say “K3.”

    Use this preflight before granting edit permissions:

    Check Why it belongs in the task record Owner
    Repository commit and working-tree state Makes source claims reproducible and exposes local changes Task owner
    Model ID, surface, and effective window Separates kimi-k3, k3, and k3-256k behavior Agent operator
    Task boundary and non-goals Prevents a broad request from becoming an unreviewed redesign Tech lead
    Permissions and network policy Limits what the agent can change or disclose Repository owner
    Required tests and acceptance criteria Gives the agent a verifiable stopping condition Reviewer

    Kimi's API guidance also says that multi-turn and tool workflows must return the full assistant message, not only its visible text. Preserve that protocol in the harness. If a tool wrapper silently drops tool-call history, the next turn has less evidence than the operator assumes.

    Prepare Architecture and Dependency Context

    An AI coding context should begin with the task, not with a repository dump. Write a one-page task contract: the user-visible behavior to change, the interface that must remain compatible, relevant paths, prohibited areas, expected tests, and the definition of done. Then attach the smallest current evidence set that can prove or disprove the plan.

    For a multi-file change, that packet often includes:

    • an architecture note that identifies entry points, ownership boundaries, and runtime flow;
    • dependency evidence for imports, calls, schemas, configuration, generated artifacts, and external consumers;
    • a recent test or fixture that demonstrates the contract;
    • current build, lint, and focused-test commands; and
    • a short list of unknowns the agent must investigate before editing.

    Abstract workflow showing task scope, architecture evidence, dependency paths, and verification feeding a Kimi K3 coding task

    Keep evidence distinguishable. A design document states intended behavior; source and tests show implemented behavior; an issue explains a requested change; a tool result reports what was observed at a particular revision. Labeling these roles helps the agent avoid treating an outdated diagram as a runtime fact.

    K3 can use custom tools and dynamic tool definitions, but tool availability is not repository understanding. Expose narrow queries such as “find references for this symbol,” “read this lockfile,” or “run this focused test.” Return file paths, revisions, command output, and uncertainty with every result. A giant “repository search” tool that produces untraceable summaries makes later review harder.

    Add Repository Memory and Historical Decisions

    Repository memory is a maintained record of decisions and durable facts that are expensive to rediscover. It is not the agent's conversation transcript. Keep the two separate.

    Useful memory candidates include an architecture decision record, supported deployment targets, compatibility rules, migration status, package ownership, and an explanation of an intentionally unusual dependency. Each entry should identify an owner, source links, the affected paths, a revision or date, and an expiry or review trigger. A note without a source or freshness rule is a hint, not an authority.

    Use a simple lifecycle table:

    Context item Refresh trigger First person to verify
    Generated dependency map Lockfile, build graph, or public API changes Maintainer of the affected module
    Architecture decision A proposed change challenges its assumptions Decision owner or tech lead
    Task-specific issue summary Ticket scope, priority, or acceptance criteria changes Task owner
    Test and environment instructions Toolchain, fixture, or CI image changes Build owner

    This makes “repository memory” accountable. If the entry conflicts with current source, the agent should surface the conflict, inspect the revision, and ask for a decision rather than reconcile it by guessing. For workflows that must share evidence across more than one agent or model, Share Repo Context Across Coding Agents explains why source-linked packets travel better than copied chat histories.

    Query Context Before Multi-File Tasks

    Require an evidence pass before any multi-file edit. The agent should first name the likely entry point, trace one relevant dependency path, identify tests and configuration, and list assumptions. Only then should it propose an edit plan. This sequence is slower than immediate code generation, but it exposes a wrong model of the repository before a patch spreads it across files.

    An effective Kimi K3 coding-agent workflow has four gates:

    1. Scope: Restate the change, compatibility constraints, permissions, and non-goals.
    2. Evidence: Query current source, dependency paths, tests, and approved decision records; cite paths and symbols.
    3. Plan: Separate observed facts from inferences, identify unknowns, and request approval for a risky boundary crossing.
    4. Verification: Run the agreed checks, inspect the diff, and report every remaining uncertainty.

    Kimi's documented tool protocol supports this shape: the client can provide tools, process returned tool calls, append the full assistant message and tool results, and call again. The protocol is a transport mechanism, however. Your team still decides which tool results count as evidence and which changes need approval.

    For larger projects, expose structural queries through a revision-bound index or graph when repeated relationship discovery is costly. That layer should return the source files and indexed revision behind a result. It is complementary to the model window, not a replacement for source inspection. The companion guide Kimi K3 Knowledge Graph for AI Developers covers that boundary.

    Limits, Drift, and Human Review

    Long context has predictable failure modes. It can contain stale design notes, hide the few files that determine behavior, retain an earlier mistaken plan, or be compacted by the client. Kimi Code explicitly notes that changing model IDs can invalidate built context caching and recommends a new session; its model page also warns that a session over 256K may be compacted when moving from k3 to k3-256k. These are workflow facts, not proof of code correctness.

    Counter drift with three controls. First, make every nontrivial conclusion cite a path, symbol, test, command, or decision record. Second, attach a revision and freshness condition to every derived summary. Third, require a human reviewer for authentication, authorization, data migrations, public contracts, destructive commands, and unbounded refactors.

    Do not treat a successful tool call as approval. A tool can read the wrong environment, a test can omit a consumer, and a model can turn a plausible inference into a confident sentence. The reviewer should check the evidence trail as well as the diff. If the task depends on how a specific terminal agent supplies files and tools, retain its own configuration boundary; for example, Context Engineering for OpenCode covers OpenCode rather than assuming that its behavior transfers to Kimi Code.

    Abstract governance loop for task boundary, evidence, planning, review, and revision-bound repository context

    FAQ

    What repository context should expire first?

    Expire derived summaries, generated dependency maps, CI logs, and ticket summaries first because they change with code, configuration, and scope. Keep an architecture decision longer only when it has an owner and a clear review trigger. Source-linked facts do not become permanently true merely because they were once placed in a prompt.

    Who should review generated project notes?

    The maintainer responsible for the affected boundary should review technical claims; a task owner should review scope and acceptance criteria. For cross-cutting notes, assign one accountable owner rather than asking an agent to merge disagreements. The reviewer should be able to trace each important statement to a current source or explicitly mark it as an assumption.

    How much context is too much?

    It is too much when the agent cannot distinguish task-critical evidence from background, when stale material conflicts with current source, or when the client will compact it before the decision is made. Start with a small packet, let the agent retrieve evidence as needed, and retain a stable task contract and provenance trail instead of maximizing token use.

    Conclusion

    Kimi K3 can support a rigorous coding-agent workflow through its hosted API and Kimi Code surfaces, long-context options, and tool-calling protocol. Reliable repository work still comes from the context system around it: bounded tasks, current architecture and dependency evidence, expiring memory, explicit queries, tests, and human approval.

    Use the effective context window as capacity, not as a repository-memory guarantee. Before a multi-file edit, require the agent to show what it observed, what it inferred, what it could not verify, and how the proposed patch will be tested.

  • Switching Codex Providers: Configuration, Session History, and Repository Evidence

    Switching Codex Providers: Configuration, Session History, and Repository Evidence


    To switch Codex provider context safely, change provider and authentication at user scope, treat old sessions as provider-bound records, and rehydrate the task from revision-bound repository evidence. A working route proves connectivity. It does not transfer the previous model’s architecture judgments, file selection, dependency understanding, or private reasoning.

    This guide separates the official Codex configuration model from third-party routing features and from the evidence a model needs to continue a large repository task.

    Quick Verdict

    The correct switch procedure depends on which layer changed.

    Layer What can move What does not move automatically Safe response
    Provider configuration Model provider ID, base URL, wire API, headers, and credential source Repository conclusions Configure at user scope and verify with a new process
    Third-party route Active CC Switch profile, local proxy, protocol conversion, model mapping Equivalent provider behavior Confirm provider, protocol, route, and model separately
    Session history Visibility, record classification, readable plain-text history Backend-specific encrypted reasoning or reliable continuation Resume on the original backend or start a fresh session
    Repository evidence Commit-pinned paths, symbols, dependencies, tests, owners, decisions Private chain of thought Build a reviewed, provider-neutral task packet

    OpenAI’s Codex documentation defines custom model providers in config.toml: a provider can specify its base URL, wire API, authentication, and headers, and model_provider selects it. Provider switching therefore changes the connection contract. It does not define an automatic migration of task state.

    What a Codex Provider Switch Changes

    Official Codex supports custom providers and profiles. The advanced configuration guide shows model_provider and [model_providers.<id>] entries for user configuration, including environment-key and command-backed authentication. It also documents one-run overrides and named profile files under ~/.codex/.

    Provider and authentication configuration has an important security boundary: project .codex/config.toml files cannot override keys that redirect credentials or change provider authentication. Codex ignores project-local model_provider, model_providers, openai_base_url, and related protected keys. Put provider and authentication settings in user-level ~/.codex/config.toml or a user profile, not in repository configuration.

    A third-party manager can edit or route those settings, but it does not become an official Codex capability. CC Switch is a community project that manages provider profiles and can put a local protocol-conversion route between Codex and an upstream. Its Kimi guide converts Codex Responses requests to Chat Completions and back. Its Claude guide converts between Codex Responses and Anthropic Messages. Both recommend restarting Codex after switching so the running process reloads configuration and model-catalog state.

    Codex++ has a different boundary. Its own repository calls it an unofficial tweak loader for the Codex desktop app. It patches the local app to load UI and main-process tweaks; it says it does not replace Codex or proxy the user’s account. Codex++ is not a provider switcher and should not be cited as a way to transfer codebase context.

    After any provider change, verify:

    • the effective user-level model_provider;
    • the selected model and provider-specific model ID;
    • direct connection versus local proxy;
    • wire protocol and conversion path;
    • credential source without printing the credential;
    • whether the active CLI process loaded the new configuration;
    • tool availability, sandbox, and approval behavior.

    Session History Is Not Repository Understanding

    Session history preserves records, not a portable mental model. CC Switch’s unified Codex session-history feature illustrates the difference precisely. Its guide says unification changes only the session’s model_provider classification tag, optionally migrating existing records after making backups. Official and third-party sessions can then appear in one history list.

    That normalization does not make reasoning provider-neutral. The guide warns that cross-provider resume may fail because encrypted_content can be decrypted only by the backend that created it. A session can be visible and readable but not continuable through the new provider.

    Even when resume works, the transcript may contain:

    • conclusions tied to an older commit or dirty worktree;
    • tool output that no longer reflects current files;
    • model-specific interpretations presented without provenance;
    • rejected paths that look like recommendations when excerpted;
    • an incomplete list of consumers, tests, or generated artifacts;
    • assumptions about tool calling, context capacity, or output format.

    Therefore, do not equate “CC Switch repository memory” with repository understanding. CC Switch can expose session records, provider configuration, MCP, and Skills. Its public materials do not describe a native, provider-neutral code graph that transfers verified system relationships into a new model.

    For cross-provider work, use old history to recover task chronology and unresolved questions. Rebuild important claims from source and tests.

    Build a Model-Independent Repository Evidence Layer

    A model-independent layer stores facts that another provider can inspect without relying on the old backend’s private reasoning. It should combine source-controlled instructions, architecture decisions, generated structural evidence, task boundaries, and verification output.

    Repository source flowing into a revision-bound evidence graph and a provider-neutral Codex task packet

    Build it in five parts:

    1. Identity: repository, branch or worktree, commit, dirty-file list, and task owner.
    2. Scope: requested outcome, non-goals, protected paths, acceptance criteria, and allowed external systems.
    3. Structure: relevant packages, files, symbols, imports, calls, schemas, generated artifacts, tests, owners, and decision records.
    4. Provenance: source location, graph revision, extractor version, deterministic or inferred status, and freshness timestamp.
    5. Verification: commands already run, exact results, known failures, remaining risks, and required approvals.

    The graph is a retrieval aid, not the final authority. Dynamic registration, reflection, configuration, generated code, and out-of-repository consumers can be absent. Make the destination model open source behind high-impact edges and rerun tests before it edits.

    Keep the artifact provider-neutral. Do not store opaque reasoning ciphertext, vendor-specific token traces, or unsupported summaries as repository facts. Label a statement as one of:

    • Verified fact: confirmed in source, an authoritative document, or a reproducible command.
    • Model-specific hypothesis: a useful interpretation that still needs evidence.
    • Human decision: an approved constraint, exception, or trade-off with an owner.
    • Stale or disproved: retained only for audit history and excluded from the active plan.

    The generic shared-context guide remains the canonical owner for cross-tool repository context. The CC Switch codebase-context guide covers CC Switch-specific failure modes.

    Provider Switch Checklist

    Use the switch as a controlled handoff, not a mid-sentence backend substitution.

    Checklist for Codex user configuration, routing, session provenance, repository evidence, and retesting

    Prepare

    • Pin the commit and capture uncommitted changes.
    • Save the goal, non-goals, acceptance criteria, and current plan.
    • Export task-relevant graph evidence with source locations.
    • Mark model-specific assumptions and unresolved failures.
    • Record the old provider, model, route, and session ID.
    • Remove secrets and sensitive data from the handoff.

    Switch

    • Change provider/auth only in user-level configuration or an authorized third-party manager.
    • If CC Switch routing is involved, confirm the provider card, local route, app-level toggle, protocol, and model mapping.
    • Restart Codex when the process must reload configuration or model catalogs.
    • Do not use Codex++ as evidence that provider routing changed.

    Validate

    • Confirm effective provider and model without exposing credentials.
    • Start a new session when cross-provider resume fails or provenance is ambiguous.
    • Load the provider-neutral task packet.
    • Reopen source behind high-impact relationships.
    • Restate the plan and compare it with the saved constraints.
    • Rerun focused tests, then broader repository-required checks.
    • Review the final diff for assumptions introduced after the switch.

    If the new model cannot reproduce the old plan from current evidence, stop and plan again. Continuing from an unverifiable summary is faster only until it produces the wrong change.

    FAQ

    What should be retested after switching providers?

    Retest the behavior the task changes, protocol-sensitive tool calls, structured outputs, patch application, and every repository-required build, type, lint, contract, integration, or security check relevant to the diff. Also repeat discovery checks for callers, generated artifacts, schemas, and tests if the old list was model-derived rather than source-linked.

    How should model-specific assumptions be marked?

    Label them explicitly as hypotheses with the originating provider, model, session, repository revision, evidence inspected, and required confirmation. Promote an assumption to a verified fact only after current source, authoritative documentation, or a reproducible test supports it. Keep human decisions separate and name their owner.

    When should a task restart from planning?

    Restart from planning when the session cannot resume, the repository revision changed, the new provider disputes a high-impact assumption, graph evidence is stale, required tools differ, acceptance criteria are unclear, or focused tests contradict the inherited plan. Planning should also restart when the old task packet lacks provenance for files, dependencies, or safety constraints.

    Conclusion

    Switching Codex providers changes configuration and routing, not repository understanding. Official Codex protects provider and authentication settings at user scope; CC Switch can manage third-party routes and session visibility; Codex++ loads desktop tweaks. These are separate tools with separate boundaries.

    Carry the task through a model-independent evidence layer: pin the revision, preserve source-linked structure, label assumptions, and record tests. Then let the new provider verify that packet in a fresh session. If it cannot reproduce the plan, restart planning before changing code.

  • CC Switch Knowledge Graph Workflow

    CC Switch Knowledge Graph Workflow


    A reliable CC Switch knowledge graph workflow uses two separate layers: CC Switch selects and connects the provider; an external, revision-bound graph supplies repository relationships. The first layer answers “which model can this agent call?” The second answers “which files, symbols, contracts, tests, and owners are relevant to this task?”

    Keeping those responsibilities separate makes Claude, Kimi, Codex, and other providers replaceable without pretending that session reasoning or repository understanding moves between them automatically.

    The Two-Layer Workflow

    The workflow starts with a hard boundary between access state and evidence state.

    Layer Owned data Refresh trigger Primary failure
    CC Switch access layer Provider profiles, active route, protocol format, selected model, MCP and Skills configuration Provider, credential, model, or routing change Requests reach the wrong endpoint or use an incompatible protocol
    Repository evidence layer Revision, files, symbols, dependencies, schemas, tests, owners, architecture records, provenance Source or documentation change The agent receives stale, incomplete, or unsupported relationships
    Task packet Goal, non-goals, selected graph results, assumptions, approvals, verification plan Each task or handoff A provider receives too much context or misses a critical constraint

    Repository source becoming revision-bound graph evidence, then a task packet consumed through the selected provider

    Run the layers as a sequence:

    1. Pin the repository revision and define the task boundary.
    2. Query the graph for the smallest useful evidence set.
    3. Inspect current source behind high-impact relationships.
    4. Select the provider and verify the CC Switch route.
    5. Start a new agent session with the reviewed task packet.
    6. Edit only after the agent restates scope and unresolved assumptions.
    7. Run tests, review the diff, and refresh graph artifacts when structure changed.

    This is a model-independent workflow because the durable artifact is not a provider transcript. It is a source-linked evidence packet that another provider can reconstruct and challenge.

    CC Switch for Model Access

    CC Switch is a third-party provider and configuration manager. Its current repository describes profiles for multiple coding tools, one-click switching, provider presets, synchronized MCP and Skills configuration, session management, and a local proxy with format conversion.

    Provider access is not always a direct endpoint substitution. The CC Switch Kimi guide says newer Codex clients use the Responses API while Kimi endpoints can expose Chat Completions. Its local route converts requests and responses between those formats. The Claude routing guide describes a similar bridge between Codex Responses and Anthropic Messages. In both cases, the provider card, local routing service, app-level routing toggle, and restarted Codex process must agree.

    A preflight should therefore record:

    • the coding client and active CC Switch provider;
    • model identifier and provider-specific model mapping;
    • direct versus local-route connection;
    • upstream protocol and any conversion step;
    • credential location and allowed disclosure;
    • MCP and Skills enabled for the target client;
    • whether the client must restart to reload configuration.

    Do not infer model equivalence from a successful route. Protocol conversion can make request shapes interoperable, but it does not make tool behavior, context limits, reasoning, output quality, or provider policies identical.

    Security also belongs at this layer. The v3.18.0 release says current diagnostic logging uses redaction and rotation, but it explicitly warns that logs written by earlier versions are not retroactively cleaned. The routing guides keep real provider keys in CC Switch configuration while the local route injects them during forwarding. Teams must still review provider terms, retention, network path, local file permissions, and the exact repository evidence being disclosed.

    Knowledge Graphs for System Relationships

    The graph layer represents revision-bound system structure. Useful node types include repositories, packages, files, symbols, endpoints, schemas, migrations, tests, owners, and decision records. Useful relationships include imports, calls, implements, generates, validates, owns, and explains.

    Each result needs provenance. At minimum, return:

    • repository and commit;
    • source and target entities;
    • relationship type;
    • file and location supporting the edge;
    • extractor or query version;
    • deterministic versus inferred status;
    • freshness time and known coverage gaps.

    This turns a graph result into inspectable evidence. “Service A depends on schema B” is not enough. “At commit X, symbol A imports generated type B at this path; these contract tests reference the same type” gives the next agent a route to verification.

    The graph must not be presented as a native CC Switch feature. CC Switch’s own scope covers provider, configuration, routing, MCP, Skills, and sessions. The graph is an external context layer, optionally reached through an MCP tool or another project workflow. The CC Switch codebase-context guide explains why that boundary matters after a provider change.

    Query Context Before Running the Agent

    Querying first prevents a new model from spending its opening turns on broad repository scans. It also prevents the opposite failure: pasting an entire repository index into the prompt and burying the task.

    Use a task-shaped query:

    Task: change the public invoice status transition
    Revision: <commit>
    Return:
    - defining schema and implementation symbols
    - direct and two-hop callers
    - generated clients or artifacts
    - contract, integration, and migration tests
    - owners and relevant decision records
    - inferred or missing relationships
    Limit: paths connected to the invoice transition
    

    Then reduce the result to a handoff with four blocks:

    1. Scope: goal, non-goals, revision, allowed paths, acceptance criteria.
    2. Evidence: relevant nodes and paths with source locations.
    3. Uncertainty: inferred edges, dynamic registration, external consumers, missing generated artifacts.
    4. Verification: focused tests, broader required suites, owners, and approval gates.

    The agent should inspect source behind every high-impact edge before changing code. Dynamic imports, reflection, runtime configuration, generated output, and consumers outside the indexed repository can defeat a static graph. Treat a graph as a navigation and impact-analysis aid, not as a substitute for source, tests, or review.

    Keep Providers Replaceable

    A provider is replaceable only when durable knowledge does not depend on its private transcript or proprietary state. Put repository policy in version-controlled instructions, architecture decisions in maintained records, graph evidence in reproducible artifacts, and task conclusions in a reviewed handoff.

    Controls for provider replacement, graph freshness, evidence minimization, human approval, and post-change verification

    Use these controls:

    • Stable schema: keep task packets provider-neutral and avoid vendor-specific reasoning fields.
    • Explicit adapters: isolate provider endpoints, protocol conversion, model mappings, and tool quirks.
    • Least disclosure: query only facts required for the task and filter sensitive paths before retrieval.
    • Provenance: attach revision and source locations to every important relationship.
    • Freshness gates: reject or rebuild graph results when their revision cannot be reconciled with the worktree.
    • Independent verification: make the destination model reopen source and rerun tests.
    • Human ownership: require the responsible team to approve policy, security, and high-impact architectural changes.
    • Transfer record: document what was provided, omitted, inferred, and disproved.

    Avoid using unified history as the portability mechanism. CC Switch’s unified Codex history guide says it normalizes the model_provider tag so sessions share a list. It also says cross-provider resume may fail when encrypted reasoning can only be decrypted by the original backend. A fresh task packet is more portable and easier to audit than an old session whose assumptions may be stale.

    FAQ

    What should the graph expose to each provider?

    Expose only task-relevant entities, relationships, source locations, revision metadata, test paths, and approved decision records. Omit secrets, raw production data, unrelated proprietary modules, private user information, credentials, and full historical transcripts. Give the provider enough evidence to verify the task, not a default copy of the entire repository graph.

    How should sensitive repo facts be filtered?

    Classify graph nodes and fields during ingestion, then enforce provider- and task-specific retrieval policies before results enter the prompt. Redact secrets rather than merely hiding labels, preserve an audit log of returned entity IDs, and require approval for protected areas. Also review local CC Switch logs and configuration backups before sharing them; current redaction does not retroactively sanitize older files.

    When should teams rebuild the graph?

    Rebuild when source, generated artifacts, schemas, dependency manifests, ownership, or relevant architecture documents change. Also rebuild when the task worktree cannot be matched to the graph’s commit, an extractor changes, coverage expands, or verification reveals a missing relationship. For large repositories, incremental refresh is acceptable only when the artifact still records one coherent revision and coverage boundary.

    Conclusion

    The CC Switch knowledge graph workflow is reliable because it does not ask one tool to own two different problems. CC Switch owns provider access, configuration, and protocol routing. A separate graph owns revision-bound repository relationships with provenance and freshness.

    Query that graph before launching the selected agent, reduce results to a task packet, and verify important edges in current source. With those controls, teams can replace Claude, Kimi, Codex, or another provider without claiming that private reasoning or repository comprehension transferred automatically.

  • CC Switch Codebase Context Loss

    CC Switch Codebase Context Loss


    CC Switch can change provider configuration, routing, and related tool settings, but it does not automatically transfer a model’s understanding of your repository. Treat CC Switch codebase context as an access-and-configuration concern. Preserve architecture facts, dependency evidence, task decisions, and verification results in a separate model-independent layer.

    That distinction prevents a dangerous assumption: a successful provider switch proves that requests reach a different backend; it does not prove that the new model knows which files matter, why a boundary exists, or which tests validate the planned change.

    What CC Switch Actually Switches

    CC Switch is a third-party, open-source desktop application, not an official feature of Claude, Kimi, Codex, or OpenAI. Its repository describes one interface for managing provider profiles across supported coding tools, along with MCP and Skills synchronization, session browsing, local proxy routing, and configuration backups.

    The application can therefore affect several operational layers:

    Layer What CC Switch can manage What that does not establish
    Provider profile Endpoint, API format, model choice, credential reference, and active profile That the new model has read the repository
    Local routing Protocol conversion and forwarding for providers that need it Equivalent model behavior or tool semantics
    Shared configuration Selected MCP, Skills, prompts, or common config fields Shared private reasoning or task conclusions
    Session interface Browsing, searching, restoring, or reclassifying supported history Guaranteed cross-provider continuation
    Backup state Copies of configurations or migrated session records A current architecture map

    The v3.18.0 release demonstrates the routing role clearly. It added and refined paths that let Codex communicate with providers using different upstream protocols. The Kimi guide explains a Responses-to-Chat-Completions conversion path; the Claude guide explains a Responses-to-Anthropic-Messages path. Both require local routing, and both recommend restarting the Codex process after switching so it reloads configuration and model-catalog data.

    Those are meaningful capabilities, but they answer where requests go and how protocols connect. They do not answer what the repository means.

    What Happens to Codebase Understanding

    Repository understanding is constructed inside a task from selected files, instructions, search results, tool output, and intermediate judgments. A model may infer that a schema is authoritative, that a generated client must change, or that a failing test is unrelated. None of those conclusions becomes part of another provider merely because the endpoint changes.

    After a Claude-to-Kimi context switch, for example, the new model may receive the same checked-out files and the same committed instructions. It does not automatically inherit:

    • which paths the earlier model inspected and which it skipped;
    • the earlier model’s private reasoning about an architectural trade-off;
    • unresolved hypotheses, rejected alternatives, or confidence levels;
    • an in-memory list of callers, dependencies, owners, and affected tests;
    • tool results that were never written to a durable handoff;
    • permissions or credentials held by the previous process.

    Even shared Skills and MCP configuration should not be confused with coding agent repository memory. A Skill can define a workflow. An MCP server can expose a tool. Neither proves that the new provider has loaded the same evidence, interpreted it the same way, or validated it against the current commit.

    The safe operating assumption is simple: a provider switch starts a new evaluator unless you explicitly supply a reviewed evidence packet. The existing guide to sharing context across coding agents owns the generic cross-tool pattern; this article focuses on the CC Switch boundary.

    Session History vs Repository Knowledge

    CC Switch’s unified Codex session-history feature makes an especially useful boundary test. Its official project guide says the feature only rewrites the model_provider classification tag so official and third-party sessions can appear in one history list. It backs up records before migration, but it does not rewrite the conversation body into a provider-neutral reasoning format.

    The same guide warns that resuming an old session through another backend may fail because the session can contain encrypted_content reasoning that only the backend that created it can decrypt. The record may still be visible and its plain text may still exist on disk, yet provider B may be unable to continue provider A’s session.

    This creates three distinct states:

    1. Visible: the session appears in a history or resume list.
    2. Readable: the stored plain-text messages can be inspected.
    3. Continuable: the active backend can resume the session and generate another turn.

    Unified history improves the first state. It does not guarantee the third. More importantly, even a continuable transcript is not a verified repository model. It can contain old file paths, assumptions from an earlier commit, failed experiments, and conclusions that were never tested.

    Use session history as an audit trail and task clue. Promote only verified facts into durable repository evidence.

    How a Code Graph Reduces Context Loss

    A model-independent code graph can preserve structural evidence that is expensive to rediscover: packages, files, symbols, imports, calls, schemas, routes, tests, owners, and architecture records. The graph should be tied to a repository revision and should link every important relationship back to inspectable source.

    Provider switching through CC Switch with a revision-bound code graph between repository source and the next agent

    The graph reduces context loss when it serves a narrow handoff:

    • Pin the source state. Record the commit or worktree revision that produced the graph.
    • Query for the task. Retrieve only the modules, dependency paths, contracts, owners, and tests relevant to the requested change.
    • Preserve provenance. Include file paths, symbols, edge types, and source locations rather than an unsupported summary.
    • Mark uncertainty. Separate deterministic imports or references from inferred runtime relationships.
    • Verify after switching. Ask the new model to open high-impact source and run the required tests.

    This is not automatic memory transfer. It is a repeatable way to reconstruct the right working set for another model. Graphify can serve as one external evidence layer, while the CC Switch knowledge graph workflow covers the complete two-layer operating model.

    Practical Migration Checklist

    Before changing a provider, create a compact migration packet. After switching, require the new model to validate it before editing.

    Checklist for provider identity, task evidence, freshness, security, and post-switch verification

    Before the switch

    • Record the active provider, model, protocol path, and CC Switch routing state.
    • Pin the repository commit and list any uncommitted changes.
    • Save the task goal, non-goals, acceptance criteria, and protected paths.
    • Export verified file, symbol, dependency, owner, and test evidence.
    • Label model-specific conclusions as hypotheses unless source or tests prove them.
    • Record failed commands, partial migrations, and unresolved risks.
    • Remove secrets, raw credentials, private data, and irrelevant transcript content.

    After the switch

    • Restart the affected CLI when its configuration is read at process startup.
    • Confirm the intended provider, endpoint path, model, and local-routing state.
    • Start a new session if cross-provider resume fails or reasoning provenance is unclear.
    • Reopen the authoritative source behind every high-impact graph edge.
    • Rerun focused tests for the changed surface, then the repository-required suite.
    • Compare the new plan with the saved constraints before allowing writes.

    This checklist makes a failed transfer observable. “The session opened” is not a validation result; “the new model confirmed these paths at this commit and these tests passed” is.

    Keep the first post-switch change deliberately small when the task allows it. Review the new model’s selected files, stated assumptions, patch, and focused test result before assigning a broader refactor. If that short pilot exposes a mismatch between the evidence packet and current checkout, refresh the packet and restart planning instead of compounding uncertain context with more edits.

    FAQ

    What should be checked after switching providers?

    Check provider identity, model, endpoint, protocol conversion, local-routing status, loaded instructions, repository commit, dirty files, and tool permissions. Then verify the task’s important dependency paths against source and rerun focused tests. If the CLI reads configuration only at startup, restart it before trusting the check.

    Can old session notes mislead a new model?

    Yes. Notes can describe a previous commit, preserve an abandoned hypothesis, omit failed tests, or mix facts with model-specific inference. Keep provenance and timestamps, label uncertainty, and require the new model to confirm high-impact claims in current source. Do not treat a visible transcript as repository truth.

    How should teams document failed transfers?

    Record the source and destination providers, session identifier, repository revision, routing state, exact failure, affected evidence, and recovery choice. Distinguish “history not visible,” “history readable but not resumable,” and “task evidence incomplete.” Preserve logs only after checking them for credentials or sensitive content.

    Conclusion

    CC Switch makes provider and configuration changes easier, but a provider switch is not a repository-understanding transfer. Unified session visibility, synchronized Skills, and working protocol conversion remain separate from the model’s current evidence about code.

    Use CC Switch for the access layer. Use a revision-bound repository graph, source-controlled instructions, decision records, and test results for the knowledge layer. When the provider changes, start from a compact evidence packet, verify it against current source, and restart planning whenever the old model’s assumptions cannot be reproduced.

  • CodeWhale Context Optimization Guide

    CodeWhale Context Optimization Guide


    CodeWhale context optimization should reduce repeated repository discovery, not hide evidence from the agent. Build a revision-bound module and dependency map, link tests and entry points, retrieve a small packet for each task, and measure search and startup behavior against a baseline. Keep current source and verification available whenever cached context is stale or incomplete.

    Codewhale v0.9.0 provides model and provider routing, saved sessions, compaction, task-scoped Fleet inputs, and subagents. It does not document a native repository index, code graph, or Fleet-wide shared repository memory. In this guide, indexing is an external Graphify-style evidence layer connected to Codewhale’s documented tools and context inputs.

    Why CodeWhale Agents Re-Read Repos

    Repeated reading is often a rational response to missing or untrusted context. A new worker must discover where the subsystem lives, which symbols matter, what calls them, and which tests establish behavior. If no reusable evidence identifies those paths, searching again is safer than trusting an old summary.

    Codewhale’s subagent behavior makes the boundary explicit. The agent path starts fresh by default with the role prompt and assigned task. Context is carried only when fork_context: true is requested. Fresh sessions are appropriate for independent exploration, but several fresh agents can repeat the same rg, file-open, and dependency-tracing steps.

    Provider switching creates a related cost. Codewhale can select models and providers through a common runtime, and Fleet profiles can pin a route. The incoming model can receive saved transcript text, configured instructions, or an explicit task packet. It does not inherit another provider’s hidden reasoning. Rebuilding repository understanding from current evidence may therefore dominate startup.

    Saved sessions and /compact help with transcript continuity. The user guide describes compaction as a way to recover context budget by summarizing long history. That is useful inside a session, but a compacted transcript is not an automatically refreshed architecture index.

    Optimization begins by classifying repeated work:

    • necessary rereads validate changed or high-risk source;
    • avoidable discovery repeatedly locates stable module boundaries and entry points;
    • stale-context recovery corrects an old map or summary;
    • provider-specific interpretation compares how models reason over the same evidence.

    The target is the second category. Removing the first would make the workflow faster but less trustworthy.

    Build a Module and Dependency Map

    Generate a small, queryable repository map from a pinned commit. Start with information that is expensive to rediscover and likely to be useful across tasks:

    • packages, services, libraries, generated areas, and their owners;
    • public and internal entry points;
    • import, call, registration, schema, event, and configuration relationships;
    • build and deployment boundaries;
    • architecture records linked to affected code;
    • cross-repository contracts and the location of their source of truth.

    Architecture flow from a pinned repository through an external dependency map into task-sized Codewhale context

    Every record should contain provenance. A parsed import can point to a file and line. A generated-client edge should name its generator. An inferred runtime relationship should carry lower confidence and an explanation. The complete map should identify its repository revision and generation method.

    Do not load the whole graph into every prompt. Query it by task. For “change retry behavior in the queue consumer,” retrieve the consumer, its configuration, retry scheduler, error types, telemetry path, owners, and tests. Let Codewhale open those current files and expand only when evidence indicates another dependency.

    Codewhale’s v0.9.0 configuration also documents an optional cache-maximal working-set mode that materializes the full current contents of top active files to stabilize provider prefix caching. That is a prompt-cache optimization for selected files, not a repository map. Use it only after evidence selection; it cannot tell the task which files were missed.

    The CodeWhale Large Codebase Context guide explains the model-independent evidence contract behind this map.

    Index Related Tests and Entry Points

    A module map saves search time only if it leads to behavior-relevant verification. Link each important entry point and relationship path to the tests that exercise it.

    Useful test-index fields include:

    Field Purpose
    test path and command makes verification reproducible
    behavior or contract covered prevents “nearby test” selection
    environment and fixtures exposes database, network, or service dependencies
    source relationship explains why the test belongs to the task
    last successful revision signals possible drift without promising current success
    owner and known limitations routes failures and prevents false confidence

    Entry points require the same care. Record CLI commands, server routes, background jobs, plugin registrations, migrations, and generated interfaces. A symbol search may find a function but miss the configuration that activates it.

    Fleet task specs can carry input_files, additional context, required files, and expected artifacts. Use those fields to give a worker the selected source and test paths, not an unbounded request to “understand the repository.” The worker’s receipt should return the commands and artifact evidence needed to verify the result.

    Rebuild or incrementally update the index when source changes affect mapped relationships. A checksum or commit match is necessary, but high-impact work should still read the relevant current files.

    Retrieve Context by Task

    The smallest useful context packet answers seven questions:

    1. What behavior must change?
    2. Which revision and workspace are authoritative?
    3. Which modules and entry points are in scope?
    4. Which dependency paths justify that scope?
    5. Which rules and decisions apply?
    6. Which tests and reviewers verify the result?
    7. Which relationships remain uncertain?

    Keep temporary state outside the shared map. A worker’s plan, tool output, debugging hypothesis, and provider-specific conclusion belong to its task record. If a finding should become shared knowledge, require source locations, revision, derivation method, and review.

    Codewhale’s opt-in memory is not the place for repository indexing. Its v0.9.0 memory documentation calls the file user-scoped and intended for durable personal preferences across repositories and sessions. Repo conventions belong in project instructions; structural facts belong in a versioned evidence layer.

    For Fleet workflows, the related CodeWhale Fleet Context Sharing guide explains how read-only repo evidence and isolated worker state fit together.

    Validate Savings Without Hiding Risk

    Measure optimization with controlled, repeatable tasks. Do not promise a fixed token reduction: provider token accounting, repository shape, task complexity, caching, and model behavior differ.

    Measurement checklist for Codewhale search actions, context tokens, startup latency, missed dependencies, and verification quality

    Choose several representative tasks and run each with and without the external context layer at the same revision. Record:

    • time until the agent proposes a source-linked plan;
    • search and file-read actions before the first edit;
    • provider-reported input and output tokens when available;
    • repeated reads of unchanged files;
    • number of graph expansions or fallback full-text searches;
    • missed dependencies found during review;
    • relevant test selection and pass/fail results;
    • reviewer corrections and unsupported claims.

    Savings are meaningful only when quality holds. A task that uses fewer tokens but misses a generated consumer is not optimized. Add guardrails: stale context triggers a targeted refresh; disagreement with current source invalidates the cached edge; security, migration, public API, and incident tasks default to broader verification.

    Compare medians across several tasks rather than promoting one successful run. Keep the provider, model, revision, task brief, permissions, and verification commands stable so the comparison measures context retrieval instead of an unrelated route change.

    FAQ

    When should CodeWhale ignore cached context?

    Ignore or bypass it when the commit differs, mapped files changed, generation failed, a live source check contradicts an edge, or the task touches dynamic registration, generated code, migrations, security controls, incident response, or external contracts not represented in the map. A provider change alone does not invalidate source-derived facts, but it does require model-specific conclusions to be reconsidered.

    How should provider-specific notes be labeled?

    Store the provider, model, date, task, revision, and evidence used. Mark the note as observation, hypothesis, or measured result. Do not promote it into shared repository knowledge unless current source or repeatable tests support it. Keep pricing, context-window, and token-accounting notes tied to the concrete route because those attributes can vary by provider.

    What evidence proves optimization helped?

    Use a matched baseline showing fewer redundant searches or reads, lower startup time, or lower provider-reported token use while preserving dependency recall, test selection, reviewer acceptance, and task correctness. Report the task set and measurement method. One fast run or a smaller prompt does not prove safer repository understanding.

    Conclusion

    Codewhale context optimization works best when it removes repeated discovery while retaining current evidence. Build an external revision-bound module, dependency, entry-point, and test index. Retrieve only the slice a task needs, keep worker state separate, and fall back to source inspection whenever freshness or coverage is uncertain.

    Measure search actions, time, tokens, dependency recall, test quality, and reviewer corrections together. If a smaller context packet makes a risk harder to see, it is compression—not optimization.

  • CodeWhale Fleet Context Sharing

    CodeWhale Fleet Context Sharing


    CodeWhale Fleet context sharing should give every worker the same revision-bound repository evidence while keeping instructions, writable scope, hypotheses, and execution state task-specific. Codewhale Fleet supports task-level input_files and extra context, plus durable ledgers, bounded artifacts, and receipts. Its v0.9.0 documentation does not describe a native code graph, repository index, or Fleet-wide shared repository memory.

    The distinction prevents a common multi-agent failure: several workers independently scan the same repository, create incompatible summaries, and return conclusions that cannot be traced to the same source revision. A shared layer should reduce that duplication without merging worker transcripts or turning one agent’s guess into a fleet fact.

    The Fleet Worker Context Problem

    Codewhale describes Agent Fleet as a local-first control plane for durable multi-worker runs. A Fleet worker is a headless codewhale exec run launched and tracked by the fleet, not a separate execution engine. Fleet is designed for work that needs retries, restart survival, receipts, or a ledgered audit trail.

    Durability solves lifecycle problems. It does not solve evidence selection by itself.

    When four workers investigate a large repository without a common map, they may use different terms for the same subsystem, choose different entry points, or rely on different revisions. One worker may infer that a handler is unused after a text search. Another may find it through configuration. A third may examine only the nearby unit tests. Their summaries can all sound reasonable while describing different slices of the system.

    Codewhale gives a Fleet task useful scoping fields. The v0.9.0 task specification can declare a workspace, required files, writable paths, input_files, extra context, budgets, timeouts, expected artifacts, and verification scorers. Those fields let a manager send a compact evidence packet to a worker. They do not automatically build or synchronize repository knowledge.

    Short-lived subagents have another relevant boundary. The agent path starts fresh by default and receives its role prompt plus the assigned task. fork_context: true explicitly carries the parent request prefix when continuation is necessary. Teams should not assume a child has absorbed the parent’s repository analysis unless the task or fork includes it.

    Shared Read-Only Knowledge Layer

    The shared layer should be an external, read-only view of repository facts for a pinned revision. Workers query it; they do not casually rewrite it during task execution.

    Architecture showing a pinned repository feeding an external knowledge layer, task packets, Fleet workers, and receipt verification

    Useful contents include:

    • module, package, service, and entry-point boundaries;
    • symbols, imports, calls, registration paths, and schema flows;
    • related unit, integration, contract, and end-to-end tests;
    • generated-code sources and downstream artifacts;
    • owners, architecture decisions, and external contracts;
    • provenance, confidence, and the commit used to derive each relationship.

    This can be implemented with a versioned repository map, a code graph, a generated report, or a combination. The format matters less than the contract: every load-bearing claim must lead back to current evidence. An inferred call edge should not look identical to a parsed import. A manually documented design intention should name its owner and decision record.

    The manager then builds a task packet from that layer. Fleet’s input_files field can name the relevant source set, while context can state the objective, revision, retrieved relationship paths, acceptance criteria, and unresolved risks. The worker should still read the current source before changing it.

    This design is not a hidden Codewhale feature. It is an external repository-context pattern connected to documented Fleet task inputs. For a broader architecture, Agent Swarm Codebase Context explains how shared evidence, task packets, isolated execution, and controlled fan-in work together.

    Separate Worker State From Repo Facts

    Repository facts and worker state have different lifetimes and approval paths.

    Record Scope Examples Promotion rule
    Shared repository evidence Revision-bound, cross-task imports, callers, owners, test links refreshed from source and reviewed
    Task packet One assignment objective, selected files, constraints, acceptance tests discarded or archived with task
    Worker state One run plan, tool results, hypotheses, partial findings never treated as shared fact automatically
    Fleet evidence One durable run ledger events, artifacts, receipt, scorer result retained for audit and fan-in
    Personal memory User-level, opt-in durable preferences across sessions not a repository fact store

    Codewhale’s user memory is intentionally user-scoped and disabled by default. When enabled, subagents can inherit the user memory file. That does not make it a Fleet repository map. The memory documentation explicitly distinguishes personal preferences from repo-specific project instructions.

    Worktree isolation also needs precise language. Codewhale documents worktree: true for the agent or subagent launch path: it creates a child branch and checkout and runs that child from the isolated path. The Fleet task schema lists workspace, files, and writable paths, but the cited v0.9.0 Fleet guide does not present worktree as a general Fleet task field. Do not promise Fleet worktrees unless the exact launch path and installed release support them.

    The safest rule is that a worker may propose new shared knowledge, but it cannot ratify it. The proposal should include the source revision, evidence locations, derivation method, and confidence. A repository owner or an automated refresh pipeline decides whether the shared layer changes.

    Prevent Conflicting Summaries

    Conflicting summaries become manageable when workers cite evidence instead of copying prose from one another.

    Codewhale Fleet already provides useful audit primitives. Workers write bounded artifact files under .codewhale/fleet/; the ledger stores artifact references with path, checksum, MIME type, and size. Receipts can report pass, fail, partial, skip, or timeout, and deterministic scorers can check exit codes, file existence, regular expressions, or JSON paths.

    Use those primitives to enforce an evidence-rich output contract:

    1. State the revision. Every summary names the commit or immutable workspace snapshot.
    2. Cite source locations. Architecture or impact claims point to files and symbols.
    3. Name the retrieval path. Record the graph query, index lookup, or search command.
    4. Separate observation from inference. “File imports type” is not the same as “runtime uses behavior.”
    5. Attach verification. Include test commands, results, artifact checksums, and scorer status.
    6. Report disagreement. Do not flatten two incompatible findings into a confident compromise.

    Fan-in should belong to a manager or workflow owner. Codewhale’s Fleet documentation makes this explicit: when one combined result is needed, an owner aggregates, verifies, and synthesizes worker receipts. Dispatch is not completion.

    If two workers disagree, re-run the smallest query or test that decides the issue. Prefer live source and tool evidence over old handoffs. The shared map should record the resolved fact only after the supporting source is identified.

    Safe Rollout Pattern

    Adopt shared Fleet context in a narrow subsystem before applying it across a monorepo.

    Rollout checklist for revision pinning, read-only graph access, scoped Fleet tasks, evidence receipts, and refresh approval

    • Choose one subsystem with known owners and reliable tests.
    • Pin the repository revision and generate a minimal module, dependency, and test map.
    • Review graph edges and label parsed, generated, documented, and inferred facts.
    • Define one read-only role and one small change or audit task.
    • Supply only the relevant input_files, relationship paths, constraints, and expected artifacts.
    • Keep each worker’s writable paths and task notes separate.
    • Require receipts to cite source locations and verification artifacts.
    • Let a manager reconcile conflicts and reject unsupported claims.
    • Refresh the map after accepted source changes, then rerun affected queries.
    • Compare search duplication, startup time, missed dependencies, and review corrections against a baseline.

    Do not begin by copying full transcripts into a global memory file. That preserves noise, assumptions, secrets, and stale task state. Start with source-derived relationships that reviewers can reproduce.

    The related CodeWhale Context Optimization Guide focuses on measurement and reducing repeated reads. This article owns the narrower design of what Fleet workers share and what remains isolated.

    FAQ

    How should worker outputs cite shared context?

    Each output should name the repository revision, shared-context version, query or retrieval path, direct source locations, and any low-confidence edges used. The worker’s Fleet artifact should carry a checksum, while the receipt reports verification status. A reviewer should be able to reconstruct the conclusion without trusting the worker transcript.

    Who updates the shared repository map?

    A repository owner or reviewed automation pipeline should update it from accepted source changes. Workers can submit proposed additions with provenance, but they should not silently promote their own summaries. Ownership should follow the affected subsystem, with a maintainer responsible for graph-generation rules and freshness checks.

    What should stay outside shared memory?

    Keep secrets, credentials, raw prompts, private reasoning, speculative diagnoses, transient logs, unreviewed summaries, task-specific write plans, and provider-specific behavior outside the shared repository layer. Codewhale’s opt-in user memory should remain a personal-preference surface, not a substitute for revision-bound repo evidence.

    Conclusion

    Codewhale Fleet provides durable workers, scoped task inputs, ledgers, artifacts, and receipts. Those are strong coordination primitives, but they do not create shared repository understanding automatically.

    Build a read-only, revision-bound evidence layer outside Fleet. Retrieve a small packet into each task, isolate worker state, and require source-linked receipts. When workers disagree, let current source, tests, and a named fan-in owner decide. Shared context is safe only when every worker can cite it and no worker can quietly redefine it.

  • CodeWhale Constitution vs Code Knowledge Graphs

    CodeWhale Constitution vs Code Knowledge Graphs


    A CodeWhale constitution controls how an agent ranks authority, protects selected paths, escalates risk, and verifies completion; a code knowledge graph describes repository entities and relationships for a particular revision. Use .codewhale/constitution.json for governance. Use an external graph for calls, imports, schemas, tests, ownership, and dependency paths. Verify both against current code and live evidence.

    This comparison uses Codewhale for the project’s factual spelling while retaining CodeWhale constitution as the target query. It is based on the v0.9.0 configuration documentation and CodeWhale’s public constitution page as checked on July 23, 2026.

    Quick Verdict

    Do not turn a constitution into a manually maintained architecture map, and do not let a graph decide policy.

    Layer Primary question Appropriate contents Authority and freshness
    .codewhale/constitution.json How should Codewhale decide and verify work in this repo? authority order, protected invariants, branch policy, verification rules, escalation conditions human-reviewed policy; changes when governance changes
    AGENTS.md How should agents work on this project? prose instructions, commands, conventions, contribution workflow human-reviewed instructions; changes with team practice
    External code knowledge graph What repository entities relate at this revision? files, symbols, imports, calls, tests, schemas, documents, owners regenerated or incrementally refreshed from evidence
    Current source and tools Is this claim true for the active task now? checked-out code, configuration, test results, logs, diff highest practical factual check for the active turn
    Opt-in user memory What durable personal preferences follow the user? concise preferences across repositories and sessions user-scoped; not a repo fact database

    The split is operational, not semantic hair-splitting. A constitution may require an agent to trace consumers before changing a public API. The graph can return candidate consumers. Current source and tests determine whether the returned path is accurate and whether the change is acceptable.

    The same pattern applies beyond Codewhale. AGENTS.md vs Knowledge Graph explains why human-authored instructions and generated repository relationships should keep different owners and refresh triggers.

    What a Constitution Controls

    Codewhale v0.9.0 documents several authority layers. The bundled constitution is compiled into the binary. A user-global constitution lives under $CODEWHALE_HOME/constitution.json—normally ~/.codewhale/constitution.json—and expresses standing preferences and stop conditions. A repository can add .codewhale/constitution.json for repo-specific authority and prioritization.

    The repo-local file can contain:

    • an authority order for resolving conflicting sources;
    • protected invariants, optionally scoped to path globs;
    • branch policy;
    • verification requirements before claiming completion;
    • escalation conditions for risky or unclear work.

    These fields govern decisions. For example, an authority list can place live code and tests above an old handoff. A verification policy can require focused tests and a readback of changed files. A protected invariant can require approval or block writes to matched paths when expressed in the supported object form.

    Codewhale’s documentation also establishes limits. Managing the constitution does not alter sandbox, network, trust, shell, MCP, or approval posture. Runtime security controls remain enforced in code. The constitution can tighten behavior or define authority; it cannot grant broader runtime permission.

    Most importantly, constitution entries do not establish repository facts. A rule such as “preserve the billing event schema” tells the agent what matters. It does not enumerate the schema’s producers, consumers, generated clients, migration history, or tests. Those relationships must come from current evidence.

    The public CodeWhale constitution page summarizes the same three-layer model and says the repo law sits above project instructions, memory, and handoffs. It also preserves the honest boundary: current requests and live tool evidence control factual reporting.

    What a Code Knowledge Graph Describes

    A code knowledge graph is a structured, queryable view of repository entities and their relationships. For agent work, useful nodes include files, packages, symbols, endpoints, schemas, tests, owners, configuration keys, and architecture records. Useful edges include imports, calls, implements, generates, publishes, consumes, configures, tests, and owns.

    Architecture separating constitution policy, external revision-bound graph evidence, Codewhale tasks, and source verification

    The graph should be external and revision-bound in this workflow. Codewhale v0.9.0 does not document a native code graph or repository index. An external tool can produce the graph, while Codewhale queries or receives the relevant evidence through its normal task context and tools.

    Revision binding prevents a generated relationship from becoming timeless lore. Every graph view should identify the commit or snapshot from which it was built. It should also preserve provenance:

    • parsed imports and definitions can cite exact locations;
    • generated-code relationships should name the generator and artifact;
    • inferred runtime paths should carry confidence and an explanation;
    • decision links should point to dated records and owners;
    • stale or unresolved edges should be visible, not silently omitted.

    A graph helps answer “what appears connected?” It cannot prove every runtime path, infer every dynamic registration, or decide which behavior a team wants. Source inspection, focused tests, logs, and reviewers remain necessary.

    Why Rules Cannot Replace Repository Facts

    Rules age differently from code relationships. A verification rule may remain valid for years. A caller list can become stale after one refactor.

    Putting repository structure into constitution prose creates three problems. First, changes to the code do not automatically update the rule. Second, reviewers cannot easily distinguish policy from generated observation. Third, an agent may treat a high-authority constitution block as proof even when current source contradicts it.

    The opposite mistake is equally risky. A graph can show that a package imports another package, but it should not decide whether direct dependency is forbidden, whether a migration needs security review, or whether the team permits edits on a release branch. Those are governance decisions.

    Consider a database migration:

    1. The constitution says migrations require rollback steps, focused verification, and owner escalation.
    2. AGENTS.md names the approved commands and contribution flow.
    3. The graph identifies schema consumers, generated clients, migration files, and contract tests.
    4. The task packet selects the relevant evidence for the active revision.
    5. Codewhale reads current files, proposes the change, and runs the required checks.
    6. A reviewer evaluates the diff and evidence.

    Each layer contributes something the others cannot safely replace. Collapsing them into “agent memory” obscures authority and makes stale data harder to detect.

    Codewhale’s optional memory feature reinforces this boundary. It is disabled by default and intentionally user-scoped. The documentation recommends project instructions for repo-specific conventions. Personal memory should not carry an unreviewed architecture summary from one repository into another.

    How Governance and Understanding Work Together

    Connect the layers with explicit gates rather than a single global context dump.

    Checklist linking constitution review, graph freshness, task retrieval, source inspection, tests, and evidence receipts

    1. Ratify governance. Review .codewhale/constitution.json like policy code. Confirm its authority order, protected paths, branch rules, verification requirements, and escalation owners.
    2. Build repository evidence. Generate a module, dependency, test, and ownership graph from a pinned revision.
    3. Retrieve by task. Query only the affected relationships and include source locations, confidence, and unresolved edges.
    4. Apply the rules. Use the constitution to decide which sources outrank old summaries and which gates the work must pass.
    5. Inspect live source. Read the files behind every load-bearing graph path.
    6. Verify behavior. Run the required focused tests and any broader contract or integration checks justified by the impact path.
    7. Record the result. Preserve the revision, graph version, commands, test output, diff, reviewer, and remaining uncertainty.
    8. Refresh separately. Update the graph after code changes; update the constitution only when governance changes.

    This sequence keeps the graph useful without granting it policy authority. It also keeps the constitution authoritative without asking humans to maintain a brittle list of repository relationships.

    For large Codewhale tasks, the CodeWhale Large Codebase Context guide shows how the same evidence layer stays portable when models or providers change.

    FAQ

    Can rules conflict with graph evidence?

    Yes, but the conflict often reveals a category error. A rule might claim a path is protected while the graph shows the component moved; current source should resolve the location, and an owner should update the rule. A graph might expose a forbidden dependency; the constitution determines escalation or remediation. Never edit governance automatically just to make it agree with generated evidence.

    Who reviews constitution changes?

    Repository owners should review them with the people responsible for security, release, and the affected protected paths. Treat changes as policy changes: explain the reason, verify the schema, test any mechanically enforced path globs, and require normal code review. A model may draft text, but Codewhale’s constitution setup distinguishes drafting from ratification.

    How should stale repository facts be flagged?

    Store the source revision, generation time, provenance, and confidence on graph data. Mark the graph stale when the checkout differs, relevant files change, extraction fails, or a current source check contradicts an edge. Block high-impact use until the affected slice is refreshed. Preserve the failed edge and reason so the indexing process can improve.

    Conclusion

    The Codewhale constitution and a code knowledge graph are complementary because they answer different questions. The constitution governs priority, invariants, verification, and escalation. The graph organizes revision-bound repository facts and dependencies. Current source and tests arbitrate factual claims.

    Keep those boundaries visible. Ratify rules with human owners, refresh graphs from code, retrieve only task-relevant evidence, and record verification. If a statement changes when the repository changes, it belongs in the evidence layer—not in constitution prose. If it expresses how the team must decide or verify work, it belongs in governance—not in a generated graph.

  • CodeWhale Large Codebase Context

    CodeWhale Large Codebase Context


    CodeWhale large codebase work needs a repository evidence layer that remains stable when the active model or provider changes. Codewhale can read and edit code, run commands, check results, and route many models through one terminal-agent runtime. Those capabilities do not automatically reveal module boundaries, indirect callers, design intent, related tests, or cross-repository contracts.

    This guide uses Codewhale for the product’s spelling and preserves CodeWhale where it is part of the supplied search language. Facts were checked against the v0.9.0 documentation and release published on July 16, 2026. The repository may move ahead of that release, so unreleased files should not be presented as installed behavior.

    What CodeWhale Brings to Terminal Agents

    Codewhale is an open-source, MIT-licensed coding agent for the terminal. Its official README describes an interactive TUI and a headless codewhale exec path for scripts and CI. The runtime can read code, edit files, execute commands, and inspect results. It also resolves a selected provider and model to a concrete API route.

    The provider layer is valuable for teams that want one operational surface across hosted and local models. Codewhale documents DeepSeek, Claude, GPT, Kimi, GLM, and many other routes. In the TUI, /model selects a provider and model together, while /provider changes the active provider. A team can therefore compare routes or assign different configured models to Fleet profiles without replacing its whole agent harness.

    Large-repository usefulness still depends on how the task is framed. A terminal agent sees the workspace, tools, instructions, and context supplied for a run. It does not gain a complete architecture model simply because the provider supports a large context window or because the runtime can search files.

    The latest public release at the verification cutoff is v0.9.0, published on July 16, 2026. npm also marks 0.9.0 as its latest distribution tag. Do not describe a later repository version as released until both the release channel and the package channel support that claim.

    Codewhale’s own onboarding advice is appropriately conservative: start unfamiliar work in Plan mode, identify sources and critical files, then move to Act for changes. That sequence is useful, but the team must still provide or discover the repository facts on which the plan depends.

    Why Large Repos Need More Than Model Routing

    Model routing answers, “Which provider and model will process this turn?” Repository understanding answers, “Which system relationships must this task preserve?” These questions intersect, but neither resolves the other.

    Consider a change to an authentication claim. The named type may live in one package, while its serializers, middleware, generated clients, deployment flags, database migrations, and contract tests live elsewhere. A model can produce a locally plausible edit after reading the definition and its obvious callers. The edit can still break a consumer reached through registration, configuration, reflection, generated code, or another repository.

    Switching providers can make this gap more visible. The new model receives the current prompt, workspace, and whatever durable instructions the harness loads. It does not inherit private reasoning that another model formed in an earlier turn. A saved session or summary may preserve text, but text is not proof that the underlying relationships remain accurate.

    Three failure patterns are common:

    • Path familiarity masquerades as architecture knowledge. An agent repeatedly opens popular directories and misses a less obvious runtime path.
    • A prior summary becomes authority. A handoff says a module is unused, although current imports or configuration say otherwise.
    • A provider change alters the explanation, not the evidence. Two models produce confident but incompatible impact summaries because neither received a revision-bound dependency map.

    Treat provider choice as an execution decision. Treat repository evidence as a separate, inspectable input that any suitable model can query.

    Repository Knowledge CodeWhale Still Needs

    A useful repository context layer is small enough to retrieve and specific enough to audit. It should not be a giant prose summary of everything the team knows.

    Start with these model-independent facts:

    Evidence Useful contents Verification anchor
    Module map packages, services, entry points, generated areas, ownership repository revision and manifests
    Dependency paths imports, calls, registrations, schema and event flows exact source locations
    Test index unit, integration, contract, migration, and end-to-end coverage current test files and commands
    Decision links architecture records, approved constraints, deprecations dated documents and owners
    External boundaries APIs, queues, databases, clients, sibling repositories contracts plus deployment configuration

    This evidence should identify its source revision. “Service A calls service B” is only reusable when the record says how that relationship was derived and when it was last refreshed. Generated and inferred edges should be labeled differently from directly parsed imports or explicit configuration.

    Codewhale already separates some authority layers. Its documentation places repo instructions in AGENTS.md, repo governance in .codewhale/constitution.json, and optional personal memory in a user-scoped file. None of those should become an improvised dependency database. Instructions explain how an agent should work. A constitution ranks authority and verification expectations. User memory stores durable personal preferences when explicitly enabled.

    For a fuller treatment of portable repository facts, see Share Repo Context Across Coding Agents. The principle is the same for Codewhale: keep structural evidence independent from one provider’s session.

    Code Graphs for Multi-Model Workflows

    An external, revision-bound code graph can make the repository evidence layer queryable. “External” is important: Codewhale v0.9.0 does not document a native code graph, repository index, or automatically shared repository-memory service.

    Architecture flow from a pinned repository revision through an external code graph to Codewhale models and verification

    A graph can represent files, symbols, packages, tests, documents, owners, schemas, and their typed relationships. Before an agent edits a parser, the task can retrieve the parser’s callers, relevant configuration, generated consumers, and tests. The model then reads the selected current files rather than trusting the graph as an oracle.

    A practical query packet contains:

    1. the task objective and acceptance criteria;
    2. the repository revision and allowed write scope;
    3. relevant nodes and relationship paths;
    4. direct source locations for every important edge;
    5. applicable decisions and instructions;
    6. tests that cover the affected behavior;
    7. unresolved or low-confidence relationships.

    This pattern keeps providers replaceable. DeepSeek and Claude may explain a path differently, but they can receive the same versioned evidence. Their model-specific conclusions stay in the task record until source or test results justify promoting a fact into shared repository knowledge.

    Graphify’s broader knowledge graph guide for AI coding assistants explains structural retrieval in more depth. The important operating rule is simpler: use a graph to select and connect evidence, then use current code and tests to verify the claim.

    Verification Checklist

    Before relying on Codewhale for a large-repository change, verify the product surface, the task evidence, and the result separately.

    Checklist for Codewhale release facts, repository context, impact paths, and test verification

    • Confirm the installed package and public release. At this cutoff, both point to v0.9.0.
    • Record the active provider, model, workspace, branch, and commit.
    • Read the applicable AGENTS.md and repo-local constitution without treating either as repository structure.
    • Identify entry points, affected modules, indirect consumers, generated artifacts, and external contracts.
    • Pin graph or index output to the same revision as the checkout.
    • Read the current source behind load-bearing relationship claims.
    • Select behavior-relevant tests, not only tests located beside the edited file.
    • Label model-specific hypotheses and reject unsupported handoff claims.
    • Re-query changed dependency paths after the patch.
    • Preserve commands, test output, diffs, and unresolved risks for review.

    This checklist does not guarantee correctness. It gives a reviewer a reconstructable evidence path and makes provider changes less likely to erase why the task was considered safe.

    FAQ

    Which repo facts should be model-independent?

    Keep stable, verifiable facts model-independent: module ownership, public entry points, imports, calls, schema relationships, deployment boundaries, test coverage, architecture decisions, and source provenance. Store the repository revision and evidence path with each fact. Do not promote an agent’s unverified diagnosis, speculative intent, or private chain of reasoning into the shared layer.

    What should writers verify in CodeWhale docs?

    Verify the product spelling, latest released version, provider and model controls, terminal and headless execution paths, Fleet terminology, constitution location, memory scope, and subagent behavior against the released documentation. At the July 23 cutoff, the relevant public release and npm package are v0.9.0. Also verify negative boundaries: the cited docs do not claim a native code graph or shared repository index.

    When should teams avoid provider switching mid-task?

    Avoid switching during a migration, incident response, release gate, or security-sensitive change when the incoming model cannot reconstruct the plan and evidence. Finish the current verification boundary first, or create a handoff containing the revision, task scope, source paths, graph queries, tests, results, assumptions, and open risks. Restart planning if that evidence cannot be reproduced.

    Conclusion

    Codewhale gives teams a flexible terminal-agent runtime and a practical way to route different models through common tools. For a large codebase, that is the execution layer—not the repository understanding layer.

    Use Codewhale with a pinned task, current source, explicit instructions, and revision-bound relationship evidence. Keep architecture and dependency facts model-independent, label uncertain conclusions, and make tests the final gate. If another provider cannot reproduce the evidence behind a proposed change, the workflow is not ready to switch models or edit the repository.

  • Supacode Agent Context Optimization Guide

    Supacode Agent Context Optimization Guide


    Supacode agent context optimization reduces repeated repository discovery by preparing a revision-bound project map, dependency and test indexes, and a small task-specific evidence packet before each worktree starts. Keep plans and terminal state isolated, verify retrieved facts in current source, and measure correctness alongside tokens and startup time.

    Supacode itself should stay in its documented role. As of July 23, 2026, its official docs cover real Git worktrees, managed local storage, per-worktree terminal state, and configurable run, setup, and archive commands. They do not document a built-in repository index, shared memory, or knowledge graph. The optimization layer described here is a team-owned companion workflow.

    Why Parallel Agents Repeat the Same Search

    Every new coding session begins with uncertainty. An agent needs to find the repository layout, entry points, dependency manifests, relevant symbols, tests, and local instructions. Parallel worktrees isolate those sessions, so they often repeat the same searches independently.

    Repeated scanning has several causes:

    • repository knowledge remains in a previous terminal transcript or model session;
    • onboarding documents describe directories but not current symbol relationships;
    • agents receive a broad task without likely entry points or a write boundary;
    • search failures disappear, so the next agent tries the same weak query;
    • cached summaries lack a commit and cannot be trusted after the branch moves;
    • task-specific conclusions are mixed with stable repository facts.

    The cost shows up as more than input tokens. Agents take longer to produce a defensible plan, open irrelevant files, choose overly broad tests, and sometimes miss indirect dependencies. Reducing reads without improving evidence quality merely hides the problem.

    Supacode’s per-worktree terminal state can preserve tabs, splits, and focused surfaces within that worktree. It does not transfer repository understanding to another worktree. Optimize the evidence supplied to each agent, not just the shell it launches in.

    Map the Repository Before Tasks Start

    Create a compact project map from an approved base commit. The map should help an agent answer where to look, not pretend to summarize the entire system.

    Include:

    1. top-level modules, packages, applications, and deployable units;
    2. public entry points and main configuration files;
    3. generated directories and the commands that produce them;
    4. authoritative architecture and contribution documents;
    5. ownership and review boundaries;
    6. the indexed commit, generator version, exclusions, and failed parses.

    Use stable identifiers such as repository-relative paths and qualified symbols. Avoid copying large file bodies into the map. A short description with a source citation is easier to refresh and audit.

    At task start, retrieve only the relevant slice. The evidence packet should name the goal, branch, base commit, likely modules, cited source paths, permitted write scope, expected tests, and unknowns. The agent must verify those paths in its own checkout before editing.

    Supacode Shared Context Across Worktrees describes how multiple worktrees can query this map without sharing task state.

    Use Dependency and Test Indexes

    A directory map improves orientation, but dependency and test indexes reduce the most expensive repeated reasoning. Build relationships that support impact analysis:

    • symbol definition to direct callers;
    • interface to implementations;
    • package to imports and consumers;
    • schema to producers and readers;
    • generated output to generator;
    • feature, symbol, or endpoint to relevant tests;
    • configuration key to code paths that read it.

    Dependency and test indexes selecting evidence for an isolated worktree

    Every relationship should cite source and revision. Mark whether an edge was parsed, configured, or inferred. Static indexes cannot reliably see every dynamic registry, reflection path, environment-controlled branch, or external consumer. Agents should confirm high-impact edges through current search, focused tests, and responsible reviewers.

    Test indexing should emphasize why a test is relevant. Filename proximity is a weak signal. Record the behavior, public boundary, fixture, or source unit connected to the test. Also distinguish fast focused tests from slower integration or environment-dependent checks.

    When a task changes a public interface, dependency manifest, schema, code generator, or package boundary, refresh the affected index slice before another agent relies on it. A known stale flag is safer than a silently outdated graph.

    The 1M Context vs Knowledge Graph comparison explains why more prompt capacity does not remove the need for fresh relationship selection.

    Keep Task Context Separate

    Optimization fails when shared context becomes a dump of every agent’s activity. Separate neutral repository facts from task-local state.

    Shared context may contain modules, symbols, dependency edges, related tests, approved decisions, owners, source citations, and coverage gaps. Task context should contain the plan, assumptions, terminal output, failed experiments, uncommitted diff, temporary environment settings, and provisional conclusions.

    This separation improves both safety and retrieval quality. Credentials and sensitive logs stay out of the common index. Search results are not polluted by abandoned plans. A task agent cannot silently redefine a repository fact for every other worktree.

    Supacode supports repeatable repository commands. Use a reviewed setup script to prepare dependencies or launch an agent, a run command for the standard development or test process, and an archive command for cleanup. These values may be stored in repository-root supacode.json or Supacode’s local settings. Keep secrets outside command files and keep context generation explicit.

    For a broader worktree boundary, Git Worktree vs Knowledge Graph separates per-worktree Git state from revision-bound structural context.

    Measure Token and Startup Savings

    Measure optimization against a baseline on representative tasks. Do not promise a fixed percentage: repository languages, task type, agent, tool calls, cache state, and context format all affect the result.

    Track:

    • time from worktree creation to an evidence-backed plan;
    • input tokens before the first edit;
    • repeated searches and files reopened across agents;
    • relevant versus irrelevant files inspected;
    • stale-context corrections;
    • missed dependencies found during review;
    • focused and integration test selection;
    • patch rework and integration conflicts.

    A useful trial runs the same class of task under two controlled conditions. The baseline agent uses ordinary repository search. The optimized agent receives a revision-bound map and task evidence packet. Record model, tool configuration, repository commit, prompt, date, and outcome. Compare correctness first, then resource use.

    Token reduction counts only when evidence quality is preserved. If an agent opens fewer files but misses a caller, the workflow is worse. If startup is faster but stale context causes rework, the apparent saving moves downstream.

    Review measurements by task class instead of combining them into one average. A narrow bug fix, cross-module refactor, and unfamiliar-service investigation have different discovery costs and freshness risks. Preserve search traces for representative failures so a shorter startup can be distinguished from a packet that simply omitted the evidence an agent needed.

    Review failed searches as data. Record the query, task, missing entity, expected source, result, and eventual resolution. Repeated failures can reveal missing aliases, unsupported languages, generated-code gaps, or a poor test taxonomy.

    Measurement checklist for baseline, tokens, discovery time, stale context, and correctness

    FAQ

    What signals show context is stale?

    The worktree commit differs materially from the indexed commit; cited paths or symbols no longer exist; dependency manifests, schemas, generators, or public interfaces changed; query results conflict with current search; parser coverage fell; or tests reference relationships absent from the index. Surface these signals with the result rather than hiding them.

    How should failed searches be recorded?

    Record the original query, timestamp, repository and commit, task intent, expected entity, filters used, result, and the source path eventually found. Classify the cause—terminology mismatch, missing parser, generated code, dynamic behavior, stale index, or user error—so maintainers can improve retrieval without storing private task reasoning.

    When is a full rescan still necessary?

    Run a full rescan after a large rebase, package reorganization, parser or schema upgrade, widespread code generation, major dependency migration, or unexplained coverage loss. It is also appropriate when targeted refreshes cannot reconcile the index with current source. Pin the new result to a commit before reuse.

    Conclusion

    Supacode agent context optimization is a repository-evidence workflow around isolated worktrees. Map the project once per meaningful revision, index dependencies and tests, retrieve a small task packet, and keep plans and terminal output local.

    Measure time and tokens, but gate success on correct impact paths, relevant tests, and review outcomes. Supacode can make worktree commands and terminals repeatable. Fresh source citations, explicit coverage gaps, and verification make the context trustworthy.

  • Supacode Shared Context Across Worktrees

    Supacode Shared Context Across Worktrees


    Supacode shared context should be a team-designed, read-only repository knowledge layer that every worktree can query without sharing branch, terminal, plan, or write state. Bind that layer to a Git revision, cite source paths, keep task conclusions separate, and require agents to verify retrieved facts in their own checkout.

    This is an architecture pattern, not a claim that Supacode includes shared memory or a code knowledge graph. Supacode’s official documentation describes real Git worktrees, managed local storage, per-worktree terminal state, and repository run, setup, and archive commands. Those features provide a useful shell for multiple agents. Your team must supply and govern the shared repository context.

    The Multi-Worktree Context Problem

    Each Supacode worktree gives an agent a separate branch and directory. That is valuable because tasks can modify different checkouts without mixing uncommitted files. Yet every agent still enters the same repository with limited knowledge.

    Without a shared context layer, agents repeat the same discovery work:

    • inventorying top-level modules and package manifests;
    • searching for entry points, callers, schemas, and tests;
    • deciding which documentation is current;
    • inferring ownership from filenames or recent commits;
    • producing local summaries that conflict with one another.

    The resulting cost is not only token use. Parallel agents can reach incompatible conclusions about the same architecture. One may treat a generated client as editable source. Another may miss a feature flag. A third may base a change on an obsolete design note. Separate worktrees keep their files apart while their misunderstandings multiply.

    The goal of Supacode shared context is therefore modest: reuse stable, reviewable repository facts so each task begins with a better evidence shortlist. It should not attempt to merge the agents’ reasoning or make every task see every other task’s terminal.

    For the large-repository boundary behind this problem, see Supacode Large Codebase Worktrees.

    What Should Be Shared vs Isolated

    Share repository facts that can be tied to current source. Isolate state that is provisional, sensitive, or specific to one task.

    Share read-only Keep isolated by task
    Module and package boundaries Branch, HEAD, index, and uncommitted files
    Symbol definitions and source citations Agent plan and intermediate reasoning
    Direct imports, calls, and schema references Terminal tabs, output, and notifications
    Test-to-feature and test-to-symbol links Failed experiments and temporary patches
    Approved architecture decisions Task credentials and environment overrides
    Owners and review boundaries Provisional impact conclusions
    Indexed commit and coverage gaps Write permissions and integration authority

    Git worktrees already separate selected Git state. Git documents HEAD and the index as per-worktree while most refs and repository data remain shared. Supacode adds a managed directory and terminal state for each worktree. That means the context design must not assume that “separate directory” equals complete security or environmental isolation.

    External resources need explicit controls. Give worktrees different ports, database names, cache namespaces, disposable credentials, or cloud environments as the task requires. Do not place those secrets into shared repository context.

    The general Share Repo Context Across Coding Agents guide expands this contract beyond a single worktree tool.

    Build a Read-Only Repository Knowledge Layer

    Build the layer from the repository revision agents will actually use. A minimal version can be a generated set of structured files; a richer version can be a queryable graph. The storage technology matters less than provenance and disciplined retrieval.

    Start with high-value entities:

    1. modules, packages, and public entry points;
    2. symbols and their source locations;
    3. direct imports, calls, implementations, and schema references;
    4. tests linked to behaviors or source units;
    5. generated files and their generators;
    6. approved design documents, owners, and review rules.

    Every result should include the indexed commit, source path, symbol or line anchor where practical, extraction method, and confidence or coverage note. Derived summaries should link back to evidence. If a parser fails or a language is unsupported, expose the gap instead of silently presenting an incomplete map.

    Read-only repository facts with revision, source, coverage, and worktree verification

    Give ordinary agents query access, not mutation rights. Agents can submit proposed corrections through a review queue. This prevents a single mistaken task summary from rewriting what every other worktree sees.

    Keep retrieval narrow. A task packet should contain the likely entry points, consumers, tests, and constraints—not a full graph export. Require the receiving agent to confirm critical relationships through source search, file reading, and tests in its current worktree. Static relationships can miss runtime registration, reflection, generated behavior, or external services.

    Version Context With the Codebase

    Context without a revision label is unsafe in an active repository. Record the exact Git commit used to generate it, plus generator version, timestamp, configuration, exclusions, and failed parses.

    When a worktree starts, compare its base commit with the indexed commit. There are three reasonable outcomes:

    • Exact match: use the context as a candidate map and verify important edges.
    • Small known delta: refresh affected modules or mark potentially stale results.
    • Material divergence: rebuild before relying on impact paths.

    Define refresh triggers from repository behavior. Public-interface changes, dependency-manifest edits, schema migrations, code generation, package moves, renames, and test-layout changes usually deserve targeted refresh. Large rebases or parser upgrades may justify a full rebuild.

    Versioning also makes disputes resolvable. If two agents report different callers, reviewers can ask which commit and extraction version each result describes. Without that provenance, “shared context” becomes another undocumented opinion.

    The distinction in Git Worktree vs Knowledge Graph is useful here: the worktree identifies the current source view; the graph identifies the source view from which its relationships were derived.

    Rollout Pattern for Multiple Agents

    Roll out shared context gradually so missing coverage and unsafe assumptions appear before the workflow scales.

    Begin with one repository and two low-risk tasks from the same base commit. Build only a module map, dependency slice, and related-test index. Ask both agents to cite retrieved evidence and record missing or incorrect relationships.

    Next, add explicit task packets. Each packet should state:

    • goal, non-goals, and permitted write paths;
    • branch, base commit, and context revision;
    • candidate entry points and impact paths;
    • relevant tests and required verification;
    • known unknowns and escalation owner;
    • external resources assigned to the worktree.

    Supacode repository commands can support the operational side. A reviewed setup script can prepare dependencies or launch the agent in the new worktree. A run command can start the standard dev or test process. An archive command can stop local services. These commands can live in supacode.json at the repository root or in Supacode’s local settings, according to the official documentation. They do not create or validate the knowledge layer.

    Add metrics after the baseline is stable: time to first defensible plan, repeated searches, stale-context corrections, missed dependencies, irrelevant files opened, test-selection changes, and integration conflicts. Do not claim savings from token totals alone; a shorter run that misses a consumer is not an improvement.

    Finally, separate approval roles. Repository-context maintainers approve shared fact changes. Task owners approve branch decisions. Code owners review affected contracts. An integrator evaluates combined behavior across worktrees.

    The same separation makes handoffs predictable. A new worktree receives the approved evidence packet and its explicit task scope; it does not inherit unreviewed reasoning just because another terminal inspected the repository first. That boundary improves auditability when parallel changes later converge at the merge point.

    Rollout checklist for pilot scope, provenance, access, metrics, and approvals

    FAQ

    How often should shared context refresh?

    Refresh on meaningful repository changes rather than a fixed clock alone. Dependency updates, public API edits, schemas, generated artifacts, package moves, and large rebases are strong triggers. Also run scheduled checks for repositories with steady activity. A query should always reveal its indexed commit so an agent can reject stale results.

    What context should stay private to each task?

    Keep the task plan, intermediate reasoning, terminal transcript, failed experiments, unreviewed conclusions, credentials, environment overrides, and uncommitted diff private to the task. Share an outcome only after review turns it into an approved repository fact, decision record, or source change.

    Who approves shared knowledge changes?

    A named repository-context owner should approve changes, ideally with the relevant code owner for architecture or public-contract facts. Automated updates may publish low-risk structural edges only when validation and rollback are defined. Agent reports should enter a review queue rather than changing shared context directly.

    Conclusion

    Supacode shared context across worktrees works best as a neutral evidence service around Supacode, not as shared agent memory inside it. Supacode isolates Git workspaces and preserves terminal workflows. A separate, revision-bound knowledge layer helps agents locate the same repository facts.

    Share modules, relationships, tests, approved decisions, provenance, and coverage gaps. Isolate branch state, plans, terminal output, credentials, and provisional conclusions. Then require every worktree to verify important claims against current source and tests before editing or integration.