T3 Code's local state is under ~/.t3/ . Runtime data such as sessions, commands, and messages is stored in SQLite; when reviewing or troubleshooting, query the database directly—it is more efficient than digging through logs.
Status database
- Current database:
~/.t3/userdata/statev2.sqlite;state.sqliteis the old database. - The v2 projection tables (
orchestration_v2_projection_*) have been the authoritative data since 2025-10-03; the v1projection_*tables are no longer written and are only queried when looking at earlier history. - Key tables:
orchestration_v2_projection_threads: threads. Columns includethread_id、project_id、title、default_provider、runtime_mode、created_at、updated_at、archived_at。orchestration_v2_projection_turn_items: event stream within a thread, the primary table for analysis. Columns includethread_id、run_id、ordinal、type、status、updated_at、payload_json。orchestration_v2_projection_subagents/runs/run_attempts/provider_sessions: delegation and run details.scheduled_tasks、projection_thread_pull_requests: scheduled tasks, PRs associated with threads.
turn_items.typeCommon values:assistant_message、command_execution、reasoning、dynamic_tool(MCP calls),user_message、file_change、file_search、subagent、error。payload_jsonvaries by type:command_executioncontainsinput/output/exitCode/startedAt/completedAt;assistant_message/reasoningcontains the body text.- Retention limitation: about 87% of
command_executiononly store a single line "Exited with code N" inoutput, theexitCodefield is often missing, and the full stdout/stderr is not persisted—judge success or failure mainly by the exit code in the output text. - Subagents for delegated tasks are independent threads (named like
thread:delegated-task:*); to query subagent activity, just filter bythread_id. - There is no sqlite3 CLI on Windows; use Python's built-in sqlite3 module to query the database. If a query is at all long, write a temporary .py file and run that; inline
python -cquoting in cmd goes wrong easily (exec is cmd,&&connection rather than;)。
Common queries
DB=~/.t3/userdata/statev2.sqlite
# 最近活跃线程
sqlite3 $DB "SELECT thread_id, title, updated_at FROM orchestration_v2_projection_threads
WHERE deleted_at IS NULL ORDER BY updated_at DESC LIMIT 20;"
# 某线程的命令执行(含退出码)
sqlite3 $DB "SELECT json_extract(payload_json,'$.input'), json_extract(payload_json,'$.exitCode')
FROM orchestration_v2_projection_turn_items
WHERE thread_id='<id>' AND type='command_execution' ORDER BY ordinal;"
# 失败的命令(全库)
sqlite3 $DB "SELECT thread_id, json_extract(payload_json,'$.input')
FROM orchestration_v2_projection_turn_items
WHERE type='command_execution' AND payload_json LIKE '%Exited with code%'
AND payload_json NOT LIKE '%Exited with code 0%';"
# 事件类型分布
sqlite3 $DB "SELECT type, COUNT(*) FROM orchestration_v2_projection_turn_items GROUP BY 1 ORDER BY 2 DESC;"
Orchestration tool surface (mechanism facts)
The strategy and operating procedure for delegating work (choosing models, writing task templates, switching routes, acceptance) are the responsibility of the $t3-orchestrator skill; only tool-level mechanism facts are recorded here.
orchestrator_capabilitiesreturns the live provider/model catalog (including custom models); the harness's built-in model list is not exhaustive.delegate_taskparameter surface:task、target:{providerInstanceId, model}、mode、clientRequestId. ReturnstaskId(configured withtask_status/task_cancelmanagement) andchildThreadId(subagent storage thread, cant3_thread_read). The actual delegation rules—targetmodel selection,runtimeMode/interactionModehandling—are in the "Delegating work" section of$t3-orchestrator; read it before calling.- Thread-to-workspace binding can only be set in
t3_thread_launch'sworkspaceStrategy(worktree/existing_worktree/root); having the agent rungit worktree additself does not change the binding. - ACP channel fallback: when the T3 MCP tools are absent and the environment has
T3_ACP_MCP_NODE, use the terminalELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" ${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call <tool> '<json>'。 schedule_taskpass a structured object toschedule({"type":"interval","everyMs":N}/{"type":"fixed_time","timeOfDay":"HH:MM","weekdays":[...]}), not a JSON string.
Watching and waking
T3 wakes this thread when an event arrives. When waiting for external results, register a watch and then end this round—ending the round returns control to T3, and the event will bring you back into the original flow; the task is not over.
- PR reviews, CI, conflicts:
watch_pull_request(usage in the PR instructions injected by T3); subtasks:delegate_taskasync completion events. - Some harnesses (e.g. pi) lazily load MCP tools:
watch_pull_requestwhen not in the tool list, first usetool_searchto search once; if not found, fall back to the ACP fallback described in the previous section. watch_pull_requestwill not wake the thread on "comments posted by its own GitHub account" (confirmed by actual testing: watch registration succeeds, and even after the conclusion arrives there is still no wake-up). Cloud reviewers now each speak under their own identity, so their conclusions will wake normally; only accounts that "speak using the user's token" will miss wake-ups. For such scenarios, attachschedule_task({"type":"interval","everyMs":1800000}, return to the current thread) as a fallback: when the time comes, press$pr-review-loop"review opinions attributed by identity" to re-read all comments, and delete it after this round's reviewers have all arrived or after giving up waiting per the no-response rule.
Sub-thread evidence gathering (t3_thread_read)
- The default view returns only message items; tool calls and file writes require
view:"activity". To find sub-agent reports or a particular write, page backward from the tail position, not from 0. - For cross-environment retrospectives, first run
node <技能目录>/scripts/t3-activity-scan.mjs --hours 24 --self <本线程 id> > scan.json: via the T3 MCP endpoint, collect threads active during the window on this machine and all connected environments, each with the readskillReads、$技能名mentions and user messages. Activity is judged by the most recent run or creation time:t3_thread_list'supdatedAtis refreshed in synchronized batches; filtering with it would count hundreds of old threads. Then uset3_thread_readto read details for the threads you care about. file_changeitem'soriginalFilecarries a full pre-edit snapshot: when an untracked file is corrupted, take the last file_change of that file'soriginalFileto reconstruct it—this is the last recovery path for such incidents.
Worktree reclamation (t3-worktree-gc)
Worktrees bound to T3 threads (~/.t3/worktrees/<项目分组>/<名>) are not automatically cleaned up after the thread ends. The same bound worktree may be equivalently reachable via multiple paths through junctions/symlinks (common after data directory migration): if you see the worktree path "changed", first confirm whether it is the same directory (Windows dir /al/fsutil reparsepoint query,POSIX readlink/stat), and do not treat it as a directory migration. At wrap-up, use scripts/t3-worktree-gc.mjs to reclaim only the worktrees of "other terminated threads"—leave the tree you are in for subsequent sessions, and never touch a tree that is still bound (deleting a bound directory will permanently invalidate that thread's terminal).
node <技能目录>/scripts/t3-worktree-gc.mjs # dry-run:逐目录打印结论
node <技能目录>/scripts/t3-worktree-gc.mjs --apply # 真正执行回收
node <技能目录>/scripts/t3-worktree-gc.mjs --root <dir> # 单独指定扫描根
node <技能目录>/scripts/t3-worktree-gc.mjs --purge-build [--apply] # 附带清理保留树的构建产物
node <技能目录>/scripts/t3-worktree-gc.mjs --purge-build --measure-size # 显式统计候选产物大小
node <技能目录>/scripts/t3-worktree-gc.mjs --diagnose # 对已阻断的树也收集 git 原因
Scan roots and per-tree conclusions are written to stdout in real time; phase start/end, command durations, and timeout failures are written to stderr; when you need the full log, use > gc.log 2>&1, and do not pipe-truncate the exit code. By default, when self, thread/in-use, or database blocking is encountered, the git re-check is skipped; to investigate all causes, use --diagnose(this increases traversal and network costs).
--purge-build: when a worktree is retained for git reasons (dirty tree, unpushed, precious files, unbound half-deleted residue) but has no unterminated threads, active runs, or unattributable process usage, delete only the rebuildable build artifacts within it: cargo target(with .rustc_info.json/CACHEDIR.TAG/.fingerprint)、.build、node_modules、.gradle, Xcode derived data (DerivedData, or directories containing ModuleCache.noindex/Build/Intermediates.noindex , searching down at most two levels inside ignored directories). Only recognized ignored directories are touched; tracked files, uncommitted files, and other ignored content are left alone. When multiple worktrees run in parallel and disk is tight, use this instead of deleting trees to reclaim space. By default only targets are listed; duis not run; add it only when a space estimate is needed --measure-size(Per-target traversal may be slow; failures show as "unknown" and do not affect cleanup eligibility). Each tree re-takes a process-occupancy snapshot once when entering the artifact-deletion phase, to avoid repeated full-machine scans per artifact; before deleting each target, refresh the binding and check against that occupancy snapshot, then verify the ignored rules, tracked and non-ignored files, artifact markers, and path boundaries; if the target or an ancestor within the tree is a symlink/junction, keep it. The recheck narrows the concurrency window but is not an atomic lock; do not manually rewrite a directory that is being cleaned at the same time.
Delete only if all conditions are met; if any is not met, skip and note the reason:
- the caller's cwd is not inside that worktree (self is never deleted);
- it is a git linked worktree (independent clone is skipped). Among non-git/gitfile invalid leftovers, a placeholder directory whose entire tree contains only placeholder/system junk files (left after the T3 merged PR, such as
.keep/.worktree-placeholder、.DS_Storeetc.) is likewise deleted after passing the binding/occupancy checks; if it contains other content, mark it not-a-worktree and only report it.--applycleanup also rmdir's the two-level grouping directories emptied in this round; - all bound threads are terminated (any of settled / archived / deleted; the settledOverride of delegated child threads is never written, so instead look at the subagents table's child_thread_id/provider_thread_id associated rows—all in a terminal state counts as terminated, and no associated rows still counts as not terminated; zero bindings is marked unbound and may be deleted), and non-terminated threads have no run in queued/preparing/starting/running/waiting state—a running row on an already-terminated thread is a projection lag (see "Observed pitfalls"), downgraded to a note and allowed through;
git status --porcelain -uallis empty (-ualloverrides thestatus.showUntrackedFilesconfiguration; all calls that read worktree state carry-c core.fsmonitor=false -c core.untrackedCache=false, to prevent fsmonitor hooks/untracked cache false reports from hiding local edits); in the per-file expansion of ignored, no entry matches a "precious pattern"—precious pattern = credential-type file types (.env, keys/certificates/keystores,*.properties、kubeconfig、.kube/.docker/.azureand other cloud credential directories,.config/gh/gcloud(project-localGH_CONFIG_DIRand other CLI credential areas),*.tfstate*/local.settings.json、hosts.yml、.git-crypt, credential naming, local databases, etc.; the full set is in the script underPRECIOUS_PATTERNS/PRECIOUS_SUBSTRINGS); before matching, filter out artifact/dependency directories via theBENIGN_DIR_SEGMENTSbenign directory segments (including.build/.tmp/Pods/Carthage/SourcePackagesand other SwiftPM, CocoaPods checkouts and derived data); matches list the files, and the remaining ignored entries are collapsed to top-level names for the report, truncated beyond 8.*.propertiesmatches then pass a content-level exemption: files whose keys are all in the toolchain whitelist (sdk.dir/ndk.dir/cmake.dir/flutter.*) are IDE-generated SDK pointers rather than credentials (local.propertiesis normal), allowed through to the report; other keys, unparseable lines, and read failures remain blocking;- there are no directories that ls-files cannot descend into (trailing-slash entries such as nested git repositories; exemptions within benign directory segments—
.build/checkoutssuch dependency checkouts do not count as user repositories), no git submodules (no mode 160000 gitlinks in the index), and no assume-unchanged/skip-worktree marked files (ls-files -vlowercase orStag; the two are merged into a singlels-files -s -v)—the internal state of these paths is invisible to all checks, so they are never deleted; - HEAD changes are already on the remote: HEAD is an ancestor of some
refs/remotes/origin/*, orgit cherryis patch-equivalent commit by commit (rebase/single-commit squash merge), or the patch-id of the entire branchdiff(base..HEAD)matchesbase..refa certain commit (multiple commits squashed together, comparison with upstream capped at 400 commits), or no net change to base. Patch equivalence allows through the change content—the commit object is still discarded, which is exactly how the squash workflow works; orphan commits whose content does not match are still blocked. Before deciding, run once against that repositoryfetch origin --pruneto refresh the local tracking refs—a stale tracking ref left behind after the remote deleted a branch does not mean it has been pushed; if the remote is unreachable, skip. Note that dry-run also performs this step: fetch requires network access and updates localrefs/remotes/origin/*(interactive credential prompts are disabled; missing credentials are judged unreachable directly without blocking the terminal). Branches with patch equivalence are, after--apply, force-deleted withbranch -D(from git's perspective an unmerged branch, but the content is already on the remote); - no process has it as its cwd (on POSIX use lsof; when absent, Linux falls back to /proc; if the check is unavailable it is still a block—without visibility into occupancy there is no attribution. Exception: when all bound threads have terminated, the only possible occupiers are residual processes of terminated threads—orphan agents/emulators/daemons—downgraded to a note and allowed through; deleting a clean, already-pushed directory only invalidates the residual process's cwd; occupancy that cannot be attributed to a directory—possibly a live thread that wandered in—remains a block. On Windows this is not checked, relying on deletion failure as a fallback).
--apply Before actually deleting, re-capture the thread binding/active run/process occupancy snapshot for that directory and re-check all git-side conditions, narrowing the concurrency window between scan and execution. The summary line at the end of the report includes the "in-use worktrees" count (the number of directories with unterminated bound threads or in-progress runs).
database userdata/statev2.sqlite opened read-only (node:sqlite preferred, falling back to the sqlite3 CLI); if absent or unopenable, everything under this root is skipped and no deletion is done.--apply under rmSync after deleting the directory git worktree prune deregister (do not use worktree remove: a spawn timeout would cut the recursive deletion of tens of thousands of files halfway, leaving a half-deleted remnant), then use git branch -d as a fallback to delete the local branch (for a branch whose changes are verified to be on the remote, when -d refuses deletion, switch to -D—both patch equivalence and pushed-but-not-merged-into-current-HEAD count; on failure keep it and note it); if any step fails, mark failed and continue with the next, setting the exit code to non-zero; never terminate processes and never retry with a more forceful command.
Testing:node <技能目录>/scripts/t3-worktree-gc.test.mjs—create fixtures in a temporary directory (a git repository + a fake origin + a minimal statev2.sqlite) covering every skip reason; do not touch the real ~/.t3。
External dependencies: T3 currently cannot unbind a thread from a worktree, nor does it have a "return to root" interface (t3_worktree_handoff can only move into a new worktree); a bound worktree can only be reclaimed by gc after the thread terminates, and the unbinding capability depends on a T3 product change.
Pitfalls observed
- A few ACP agents receive the MCP injection but do not expose the tools—first use the above
acp-mcp-callas a fallback to verify once before drawing conclusions. - Delegated sub-agents occasionally go silently missing; the main agent should be prepared for degraded self-review.
subagents/runsprojection is stuck atrunninghas two real causes: the child thread has actually finished (the projection lags); or the sub-agent is stuck waiting for authorization—the tail of the child thread is theapproval_request/waitingevent, and a background sub-agent inapproval-requiredmode is permanently suspended if no one approves authorization, whiletask_statuskeeps running. Do not trust status polling alone; uset3_thread_readto read thechildThreadIdtail to judge real progress; when authorization is suspended, approve it to let it through or, aftertask_cancel, re-dispatch according to the inherited mode.mcp__t3-code__*Occasionally reports "Failed to connect to MCP server 't3-code'"; retrying restores it; if that does not work, fall back to ACP.mcp_list_toolsEvery session re-queries the full directory, which incurs a considerable token cost.command_executionOutput retention is incomplete (see the previous section); when analyzing failed commands, stderr is mostly unavailable, so only the exit code can be checked.