Working Tree Resolution — agentic methodology

mandatory

Como um agente Koder Stack resolve pendências do working tree do monorepo sem auto-commit-cego. O agente inspeciona, raciocina e age conforme cada finding, usando o modelo de quatro destinos (commit, stash, ticket, delete) definido aqui. Esta policy é a spec do comando `/k-tidy`.

Working Tree Resolution — agentic methodology

How a Koder Stack agent resolves working-tree pendencies in the monorepo without autocommitcego. The agent inspects, reasons, and acts per finding using the four-destination model defined here. This policy is the spec behind /k-tidy.


1. Why agentic, not heuristic

Working-tree pendencies (dirty submodules, untracked dirs, orphan locks, unstaged drafts) accumulate when sessions end without proper closure. Heuristic auto-commit ("if dirty → commit") is dangerous: it ships debug prints, abandoned WIP, partial implementations, and accidental edits.

The agentic approach treats each finding as a context to reason about: read the diff, compare with sibling tracked content, look at recent history, infer intent, then *ecide*rather than apply a fixed rule.

This policy formalizes that reasoning so it is reproducible across sessions.


2. The four destinations

Every finding lands in exactly one of four categories. The agent's job is to decide which.

2.1 Commitasis

The WIP is *oherent, complete, and ready to ship*

Signals:

  • Diff implements one identifiable concern endtoend.
  • Pattern matches the most recent commit's intent (continuation).
  • Other repos/files in the session show the same coherent batch

    (e.g., 4 sibling repos all halfway through the same i18n migration).

  • No debug artifacts (println, panic("DEBUG"), commented-out code

    blocks, .bak files).

  • All affected files compile / parse (when checkable).

Action: commit with a message that:

  • Summarizes the change as the original author would.
  • Explicitly states *Picks up WIP from prior session"*for traceability.
  • Includes the standard Co-Authored-By footer.

Then push to the appropriate remote (the submodule's own remote if it is a submodule).

2.2 Finish + commit

The WIP is *oherent but incomplete* and finishing is *echanical replication* not creative work.

Signals:

  • A pattern is established in some files; missing in others.
  • The completion is rule-following, not invention (e.g., "fill in the

    4th language entry mirroring the 3 existing ones").

  • Risk of error is low — no business logic added, just template

    application.

Action:

  • Complete the missing pieces using the established pattern.
  • Verify the result compiles / parses.
  • Commit with a message that says *Finishes WIP from prior session;

    applied established pattern to remaining N files."*

If any of the signals weakens (the "pattern" is actually creative, multiple plausible completions exist), demote to *scalate*

2.3 Discard

The artifact is *rovably stale*and removing it loses no information.

Signals:

  • Untracked dir is bit-identical to a tracked sibling (older mtime).
  • Untracked dir is a subset of a tracked sibling.
  • Untracked dir is a build artifact (node_modules/, .gradle/, dist/,

    build/, target/, compiled binaries, generated .png from .svg).

  • Lock file references a PID that no longer exists.
  • Lock file references a session whose session_progress indicates

    completion.

Action:

  • Create a backup if the artifact is > 100 KB (in ~/temp/k-tidy-backup-<timestamp>/).
  • Delete the artifact (rm -rf for dirs, rm for files).
  • Record in audit trail.

2.4 Escalate

Anything that does *ot*clearly fit one of the above three.

Signals:

  • WIP mixes multiple unrelated concerns (e.g., one Go file has both

    "rename module path" and "add new feature X" — needs human split).

  • WIP includes content that looks accidentally edited (single-character

    edits in unrelated files, suspicious deletions).

  • Untracked dir has unique content not found in any tracked sibling.
  • Author of the WIP is unknown / cannot be inferred from session locks.
  • File looks like a credentials artifact (.env, *.key, *.pem,

    credentials.json) — never auto-commit, never discard, always escalate.

  • Session-active lock exists for the affected component (another

    session may still own this work).

Action:

  • Do *othing*— the artifact stays as-is.
  • Record in audit trail with detailed reason.
  • Surface in the final report so a human can decide.

3. The five guarantees

To make the *pply default*safe, the agent must always:

  1. *ead the diff before commit.*Never commit unseen changes. Run

    git diff (or equivalent for submodules) and parse the content.

  2. *ompare untracked with tracked sibling before discard.*Use

    diff -r or equivalent. Never delete based on filename alone.

  3. *erify authorship.*Check whether the dirty content matches the

    pattern of the most recent commit in the same repo. If the commit author / message indicates a different concern, treat as suspect → Escalate.

  4. *ackup before destructive action.*Anything > 100 KB about to be

    deleted gets targzipped to `~tempktidybackuptimestamp/`.

  5. *scalate on any ambiguity.*When in doubt, the answer is Escalate.

    Better to leave 10 things for human review than to ship one wrong commit.


4. Audit trail

Every /k-tidy execution writes a structured audit record to meta/context/notices/archive/k-tidy-YYYY-MM-DD-HH-MM.md:

---
session: k-tidy
timestamp: 2026-04-29T14:00:00Z
duration_seconds: 142
findings: 12
actions:
  - id: 1
    type: discard
    target: products/horizontal/cine/backend/
    confidence: high
    reason: "Untracked subdir; bit-identical to tracked products/horizontal/cine/engine/ (older mtime)."
    reversible: true
    backup: ~/temp/k-tidy-backup-2026-04-29-14-00-00/cine-backend.tar.gz
  - id: 2
    type: commit
    target: koder-hardware
    confidence: high
    commit_sha: 50d3ad5
    pushed_to: https://flow.koder.dev/Koder/koder-hardware.git (main)
    reason: "Coherent i18n batch matching pattern in koder-learn, koder-logistics, koder-silicon."
    reversible: "via git revert 50d3ad5"
  - id: 3
    type: finish-and-commit
    target: koder-bull
    confidence: medium-high
    commit_sha: abc1234
    reason: "i18n string table 80% complete; remaining 20% replicated from koder-learn template."
    reversible: "via git revert abc1234"
  - id: 4
    type: escalate
    target: products/dev/flow/backend/
    confidence: low
    reason: "42620 extra files including vendored gitea fork — needs human review of intent."
counts:
  commit_as_is: 5
  finish_and_commit: 1
  discard: 4
  escalate: 2
---

The audit trail is the single source of truth for what the agent did. It enables /k-tidy --rollback <session-id> to undo an entire run.


5. Discovery: what /k-tidy looks for

Each invocation scans these surfaces:

  1. *arent monorepo working tree*— git status of the koder repo.
  2. *ach submodule's working tree*— recurse into directories listed

    as gitlinks (git ls-files -s | grep ^160000).

  3. *metacontextnoticesactive`*— locks of dead sessions.
  4. *metacontextsessions/** — orphan *.lock` files.
  5. *metacontextdrafts/`*— uncommitted text drafts older than 24 h.
  6. *oplevel untracked dirs*— anything in `git status -porcelain`

    starting with ?? outside the regular working tree of a Sector.

For each surface, the agent runs the four-destination decision.


6. Cross-cutting safety rules

These rules apply across all destinations:

  • *ever modify*.git/, .gitea/, or any directory starting with .

    (except .gitignore and explicit dotfiles).

  • *ever touch*files under meta/context/credentials/.
  • *ever push*to a branch other than the submodule's default

    (main or master) without explicit authorization.

  • *ever run*destructive git commands like --force, reset --hard,

    clean -f, branch -D — those are reserved for the user.

  • *ever bypass hooks*(--no-verify, --no-gpg-sign).
  • *ever auto-resolve*merge conflicts. Conflicts → always Escalate.
  • *ever commit*files matching credential patterns

    (*.env, *.key, *.pem, credentials.*, secret.*, .aws/, .ssh/).

  • *ever act*on a Sector that has an active session lock

    (meta/context/notices/active/lock-<sector>.md) unless the lock's PID is dead and session_progress indicates completion.


7. Worked examples (from the 20260429 migration session)

7.1 i18n batch across 4 koder* submodules → Commitas-is

*inding:*koderhardware, koderlearn, koderlogistics, kodersilicon all had site/index.html modified, all in the same pattern: i18n EN/PT support added, hover styles wrapped in @media (hover:hover).

*easoning:*

  • 4 sibling repos with identical change pattern → coherent batch.
  • Last commit in each repo was "rewrite landing to comply with Koder

    product template" → continuation.

  • No debug artifacts in diff.
  • HTML + JS only, no business logic.

*ecision:*Commitasis in each submodule, push to its remote, bump parent monorepo pointers in one commit.

*onfidence:*HIGH.

7.2 servicesaizoo with mixed concerns → split into 2 commits

*inding:*zoo submodule had:

  • site/ deleted, landing/ untracked (the agent's own RFC-006 §4 work).
  • Go module path migration flow.koder.dev/koder/koder-ai-zookoder.dev/services/ai/zoo/platform.
  • jwt v5.2.1 → v5.3.1 bump.
  • Flutter app importing koder_kit.

*easoning:*Two distinct concerns. Splitting into two commits keeps the history readable.

*ecision:*Commit 1 = site→landing rename. Commit 2 = module path migration + dep bump + koder_kit adoption. Both pushed.

*onfidence:*HIGH (each commit alone is coherent).

7.3 54 untracked <sector>/backend/ directories → Discard

*inding:*54 untracked backend/ dirs across productserviceinfra Sectors, totaling 3.3 GB.

*easoning:*

  • 41 of 54 were bit-identical to their corresponding tracked engine/

    sibling (older mtime).

  • 13 of 54 had extra content, but in every case the extra was: build

    artifacts (gradle cache, node_modules, flutter build), generated PNGs from SVG sources, abandoned cmd/main.go files, vendored deps. None was unique source code.

  • 100% of cases: tracked engine/ was newer than untracked backend/.

*ecision:*Discard all 54. Audit trail preserved the file lists of the 13 superset cases for posterity.

*onfidence:*HIGH for the 41 identical; MEDIUM-HIGH for the 13 superset (escalated to user before action; user approved).

7.4 Hypothetical: half-finished i18n in a single repo → Finish+commit

*inding:*koder-X has site/index.html modified, with i18n infrastructure added (data-i18n attributes) but the LANG dict is empty {}. Three sibling repos (koder-ABC) have full LANG dicts.

*easoning:*

  • The pattern is established in three other repos.
  • Filling in the LANG dict for koder-X is mechanical: extract strings

    with data-i18n attributes, build the EN entries from existing HTML, derive PT entries by translation (or copy EN as placeholder).

  • No business logic introduced.

*ecision:*Finish — fill in the LANG dict using the established pattern, then Commitasis.

*onfidence:*MEDIUM-HIGH. If translation requires nuance the agent cannot verify, it falls back to Escalate.

7.5 Hypothetical: untracked flag.go in a backend/ → Escalate

*inding:*services/foundation/billing/backend/internal/flag.go is untracked. Contains a single function ToggleNewPricing() with no visible callers.

*easoning:*

  • No sibling tracked file with the same content.
  • Function not called from any tracked file.
  • Could be: (a) workinprogress for a feature, (b) abandoned

    experiment, (c) accidental drop from another branch.

  • Author unknown, no recent commit explains it.

*ecision:*Escalate. Surface to user with the file content and ask: commit / delete / move / rename?

*onfidence:*LOW.


8. Phase calibration

This policy uses *gentic apply default*during the Koder Stack acceleration phase. When the Stack enters official homologation, recalibrate to:

  • Default mode shifts to --plan (preview only).
  • --apply becomes opt-in.
  • Escalate threshold tightens (more findings escalated, fewer

    auto-applied).

This recalibration must be requested explicitly by the user. Do not self-recalibrate based on heuristics.

See policies/hyperscale-first.kmd for the broader phase context.


9. Reversibility

Every action recorded in the audit trail is reversible:

  • *ommit/Finish+commit* git revert <sha> in the affected repo.
  • *iscard* restore from ~/temp/k-tidy-backup-<timestamp>/.
  • *ock archive* move file from archive/ back to active/.

/k-tidy --rollback <session-id> reads the audit trail and reverts all actions of that session in reverse order.

The backup directory under ~/temp/ is retained for 7 days then autopurged. Longterm archival of discarded content is not the responsibility of /k-tidy.


10. Integration with /k-commit

When /k-commit runs in the koder monorepo root, it invokes /k-tidy in apply mode at §14b (after backlog review, before finalization). Findings resolved by /k-tidy appear in the final report as a separate section. Modes:

  • /k-commit (default): runs /k-tidy in apply mode.
  • /k-commit --tidy=plan: runs /k-tidy --plan (report only).
  • /k-commit --tidy=skip: skips /k-tidy entirely.

When /k-commit runs inside a submodule (not in the koder monorepo root), /k-tidy is skipped — the scope of /k-tidy is the parent monorepo plus its submodules, not arbitrary repos.

Source: ../home/koder/dev/koder/meta/docs/stack/policies/working-tree-resolution.kmd