router
GO v2 front door internals — policy resolution, run records, resume dashboard, and PR label correction for src/worktrail/router
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- router
- triggers
- { "files": [ "src/worktrail/router/**" ], "keywords": [ "policy.py", "go-policy.yaml", "worktrail-go-policy.yaml", "run_record", "dashboard", "automerge_eligible", "risk label", "classify", "RISK_SIGNALS", "scope_review", "parse_invocation", "noun-verb grammar", "triage_keep_limit", "triage_max_queue_age_days", "max_parallel_workers", "compile_max_critical_path_over_width", "compile_max_same_file_chain", "review_skip_max_diff_lines", "pre_commit_cmd", "land_pr", "LandRequest", "LandOutcome", "close_stale_openspec", "flip_and_archive", "capacity-gate", "retry_after", "smoke_flakes", "smoke_flake_aggregate", "smoke_flake_selfcheck", "reconcile_pr_labels", "load_run_index", "base_slug", "automerge_preflight", "required_checks_gate", "owner_repo_from_git", "push_remote_name", "remote.pushDefault", "cluster_detect", "focus-overlap", "MIN_FOCUS_TOKENS", "OVERLAP_THRESHOLD", "risk_judgment", "judge_risk", "compose_tier", "parse_answers", "blast_radius", "red line", "TYPESAFE_API_KEY", "risk_judgment_enabled", "typesafe", "JUDGMENT_ERRORS", "relatedness_judgment", "judge_pair", "judge_pairs", "should_edge", "same_work", "should_cluster", "focus-judgment", "JUDGED_MATCH", "JUDGMENT_THRESHOLD", "JUDGMENT_PREFILTER_FLOOR", "MAX_JUDGED_PAIRS", "cluster_telemetry", "log_judged_pairs", "target_branches", "inline flow sequence", "parse_policy_yaml", "POLICY_KEY_TYPES", "_sweep_key_types", "_SWEEP_SKIP", "_TYPE_SWEEP_EXEMPT", "env_profiles", "auth.profile", "resolve_env_profile", "env_profile.py", "resolve_routing", "_CONSUMER_MENTION_J_LABELS", "_CONSUMER_BY_PHRASE_RE" ] }
- description
- GO v2 front door internals — policy resolution, run records, resume dashboard, and PR label correction for src/worktrail/router
03 SKILL.md 正文
You are working on worktrail's GO v2 front door: loading repo policy, classifying free-text requests into routes, tracking run records, and rendering the resume dashboard.
Domain purpose
router/ is what /go-style front doors consume to decide what a repo allows (policy), which
route a request maps to (classify), what already happened (run_record, dashboard), and whether a
spawned agent's own gh pr create came out correctly labeled (pr_labels). Nothing here spawns
agents or writes task files — that is orchestrator/'s job.
Business rules / invariants
- The front-door grammar is code, not prose:
parse_invocation.pyowns it. The shape is<front-door> [<repo>] <noun> <verb> [args]with exactly four nouns (NOUNS:handoff,spec,pr,decision), plus two deliberate bare shortcuts (<brief-id>=handoff start <id>, and<repo>= that repo's dashboard) and the read-onlyhelp/empty invocations. Every pre-noun-verb spelling (auto,drain,new,implement spec <id>,continue,pr,brainstorm,fix,route:<A-J>,handoff:<id>) is permanent, not deprecated —ALIASESlists them and_canonicalizerewrites only a bare leading token, so a spelled-out noun-verb form is never rewritten twice. Add a new form toFORMS/ALIASESand the parser together, never one without the other. decision list/decision answer <decision-id>are their own modes (decision_list,decision_answer), not intents or brief lookups. The parser carries the id in the result'sdecision_idfield and never tries to resolve it againstqueue/(brief_statusstaysNone);decision answerwith no id ismode: helpwithhelp_topic: decision. Theworktrail-goskill skips the dashboard entirely for both and runsworktrail-decision/ theanswer-decision.mdprocedure directly.- A noun with no recognised verb returns
mode: help, never free text. Free text containing the wordhandoffclassifies to Route E at high confidence inclassify.py(joint-highest-weight signal plus a state boost whenever the queue is non-empty), so anything that escapes the parser lands on the wrong route silently.handoff newmust also never reach the intent branch asrepo=handoff, intent=new— the noun-verb match runs above the bare intent words on purpose.pris the one exception: barepr(andpr <text>) still means the oldprintent. RISK_SIGNALS'authzpattern carries a(?<![-@])guard so it cannot fire inside a compound token.\btreats the hyphen in a package name likebetter-auth(or the@in@auth/core) as a word boundary, so merely naming the dependency scoredhigh:authz. Confirmed live 2026-09-10 (rungo-20260910-085556, devops PR #366): a config-only PR classifiedrisk=high, exceeded that repo's policymax_risk=medium, and was labeledgo:no-automerge, forcing a hand merge. This is a word-boundary artifact inside one token, not the diff-blindness theRISK_SIGNALStable comment deliberately fails loud on. Underscore-joined identifiers (require_auth) were already excluded (_is a word character);auth-relatedstill matches, because the guard looks only at what precedes the word.classify_risk()has two backends over oneRISK_ORDERmapping, and the keyword table is both the default and the fallback.classify_risk(text, *, judgment=False)keeps its shape;_classify_risk_by_keyword()is the extractedRISK_SIGNALSbody, andrisk_judgment.judge_risk()is the second backend — one request asking for a 4-level blast-radius score plus four red-line nouls (irreversible_data_loss,weakens_access_control,moves_money,disables_a_safeguard), never for a tier, a label, or a merge decision. The service observes; the pure, offlinecompose_tier()decides: the score sets the baseline tier (rounded and clamped onto_TIERS), a hard red line at or aboveRED_LINE(0.70) forcescritical, the safeguard red line forceshigh, and a red line is a floor — it can only raise a baseline, never lower one, because a change can read "ordinary" on blast radius and still destroy data. Labels keep the<tier>:<label>shape (medium:blast-radius,critical:moves-money), so a judged tier is readable as such with no second field. Why it exists: the keyword table tiers on word presence alone, and measured 2026-09-19 ontests/fixtures/risk_probes.jsonit got 8/24 exact tiers and 10/24 auto-merge gate decisions — rating prod data deletion, an auth fail-open, refund re-submission and "make a required check non-blocking" mergeable, and seven trivial doc/test changes critical — against the judgment's 20/24 and 24/24 with zero of either error.- The judgment fails safe into the keyword table, always.
judge_risk()returnsNone— the "use the keyword table" signal — on a missingTYPESAFE_API_KEY, an HTTP or transport error, a timeout (typesafe.TIMEOUT_S, deliberately short: a tier that arrives after the operator gave up is worth less than the immediate fallback), an unparseable body, or an answer set missing a field.parse_answers()raisesValueErroron any shape it does not recognise rather than reading a missing noul as zero, so a changed or truncated response can never compose a falsely-low tier. The fallback errs toward over-gating, which is the safe direction. CI needs no key and no network: with the key unset the judgment path is never entered and behaviour is exactly the pre-judgment one. - Both judgment backends share one client,
router/typesafe.py, and one failure-mode rule. The endpoint (API_URL),MODEL,API_KEY_ENV,TIMEOUT_S,is_configured(), the single-requestpost(state, questions), the strictnoul(answers, key)reader, and theJUDGMENT_ERRORStuple live there —risk_judgment.pyre-exportsAPI_KEY_ENVso its own readers and tests keep one import. A second copy of the transport would be one more place for the "what counts as unavailable" contract to drift; add a new backend by importing this module, never by re-implementing the POST. cluster_detect's focus signal also has two backends, and the lexical threshold is both the prefilter and the fallback.relatedness_judgment.judge_pairs()asks two Nouls per pair —same_work(one item subsumes the other) andshould_cluster(distinct work that causes rework if done apart) — and the pure, offlineshould_edge()forms an edge when either clearsJUDGMENT_THRESHOLD(0.70). The union is deliberate: requiring both would drop exactly the "different work, must land together" case the second question exists for. Why it exists, measured 2026-09-19 in both directions: three pairs describing identical work in different vocabulary scored 0.00-0.12 token overlap — invisible toOVERLAP_THRESHOLD(0.45) — while the judgment rated them 0.76-0.86 onsame_work; and of the 14 highest-overlap real corpus pairs, 7 were unrelated on inspection (two different epics' decomposition-gap briefs, a reject-UI brief against a vitest-coverage brief).- The lexical stage is demoted to a prefilter, never removed.
_judgment_candidates()picks which pairs are worth a request atJUDGMENT_PREFILTER_FLOOR(0.05 — far below the edge threshold on purpose, because a prefilter near 0.45 would reproduce the blindness being fixed) and ranks them by overlap descending;MAX_JUDGED_PAIRS(40) caps one scan, because pair count grows quadratically with queue size (68 briefs is 2278 pairs before repo scoping) and a dashboard render may not fan out unbounded. Everything past the cap — and every pair at all when the judgment is unavailable — keeps the lexical decision unchanged. The repo-scoping precondition and theMIN_FOCUS_TOKENSthin-brief abstention are unchanged: a cross-repo pair is never offered, and a brief too thin for the coefficient to read is one the judgment cannot read either. - A verdict replaces the focus signal and nothing else.
_apply_relatedness_judgment()swaps a judged pair'sfocus-overlapmatch forJUDGED_MATCH(focus-judgment, so a reader and the telemetry log can tell which rule decided) when the pair belongs together, and for nothing when it does not — that is how a high-overlap-but-unrelated pair loses its edge. Structural matches (duplicate-slug, same-target-spec, related-link) are never touched: they are facts about the briefs, not a reading of their text. The whole candidate batch is handed over in ONE call, already capped and ordered, so the injected side owns concurrency (MAX_CONCURRENCY, 8) andcluster_detectholds no thread pool and no client; verdicts come back positionally aligned and the first unavailable one ends the pass, because applying a later verdict past a gap would make the surfaced clusters depend on which round trip failed. - The judgment client is injected into
cluster_detect, never imported by it.compute_clusters(..., judge_pairs_fn=None, log_judged_fn=None)defaults both toNone, so every existing caller keeps prior behaviour exactly;dashboard.pyis the call site that injectsrelatedness_judgment.judge_pairs(only whenis_configured()) andcluster_telemetry.log_judged_pairs. Same pattern as_parse_fmandtask_candidates_fn—cluster_detect's own guard test rejects any network module in that file, and its contract is read-only and never-crash. - Every judged pair is logged for later tuning.
cluster_telemetry.log_judged_pairs()appends onejudgedrecord per pair (members, the lexical overlap that ranked it, both Noul values, and the verdict) sharing one timestamp, soJUDGMENT_THRESHOLDand the prefilter floor can be retuned against real pairs without paying for inference again. Best-effort like the module's other writers: the edges are already decided by the time it runs, so a failed write costs a tuning datapoint and nothing else. classify()stays pure by default:risk_judgment_enableddefaults toFalse. Onlymain()turns it on, with--no-risk-judgmentto opt out — the same confinementcited_pr_states' liveghlookup already has — soclassifier_coverage's replay and every test stay deterministic, free and offline. Enabling it changes only therisk/risk_signalsoutput; route selection, its confidence, and its reason never consult it.- A J score built entirely from
_MENTION_ONLY_J_LABELS(routing-logic,classify-py) alongside a strong CI/config signal (_CI_CONFIG_RE:.github/workflows,.github/rulesets,required status check,branch protection) is damped to zero — that shape means the routing/classifier file is cited as evidence for unrelated CI/branch-protection work, not the actual change target (live incident 2026-09-10, brief 20260910-143657/run go-20260910-142322). The damp does not fire when the same text also matches_CITED_AS_EXAMPLE_RE(cites,quotes,verbatim,worked example,as an example, …): a genuine self-referential bug report aboutclassify.py's own routing logic that happens to quote another brief's CI-config text as a worked example was itself getting wrongly demoted from J to F (brief 20260910-152514: J=9 undamped vs F=6, confirmed reproducible). A citation cue means the CI/config phrase is quoted evidence, not the report's own change target, so it must not trigger the damp. Scoped narrowly to these two evidence-confirmed labels — do not widen_MENTION_ONLY_J_LABELSwithout its own confirmed false-positive. - A J score built entirely from
_CONSUMER_MENTION_J_LABELS(go-skill,front-door) whose only occurrence is a consumer by-phrase (_CONSUMER_BY_PHRASE_RE: a consumption cue —consumed/used/read/called/drives/… — followed bybyand then the front door) is also damped to zero — that shape names the front door as a consumer of the result under discussion, which cannot be the change target (live incident 2026-10-03, brief 20261003-204443: the bare clause "the machine-readable surface consumed programmatically by drain, queue-triage, and the go front door" scored J=7 at high confidence with every other route at 0). The by-phrase frame is what separates the two shapes, so no citation carve-out is needed: "add a guard to the go front door so it stops misrouting consumer mentions" still routes J. Damping is scoped to a J score built entirely from these two labels — a request that also carries another J signal (e.g.cassette) still wins on it. Do not widen_CONSUMER_MENTION_J_LABELSwithout its own confirmed false-positive. - The parser translates into the executor's vocabulary, not the user's.
worktrail-sdd-workflowstill speakshandoff:<id>,route:<X>, and the v1 intent words (V1_INTENTS); sospec exploreyieldsintent: brainstorm, andspec fixyieldsroute: F(the executor has nofixintent). The result'scanonicalfield carries the noun-verb spelling so the skill can print(reads as: worktrail-go <canonical>)when it differs fromraw; it isNonefor free text. worktrail-help's reference block is generated fromFORMS+ALIASESviarender_forms()and pinned bytests/router/test_parse_invocation.py::test_help_forms_block_matches_the_parser_registry— regenerate it, never hand-edit it. Only<free text>may carryparsed=False.policy.pyuses two YAML parsers on purpose. Most keys go throughparse_policy_yaml, a flat, stdlib-only, one-nesting-level subset.routing:andadd_ons:are re-parsed with realyaml.safe_load(_resolve_routing,_resolve_add_ons) because both need arbitrary nesting the flat parser would flatten into siblings of the wrong key. Adding a new deeply-nested policy key means adding a matching_resolve_*real-YAML path, not extending the flat parser. The one narrow exception inside the flat parser is_parse_scalar: a value that starts with[and ends with]is handed toyaml.safe_loadso an inline flow sequence ([],[main, dev]) loads as a real list; anything that is not a valid flow sequence (an unclosed[, a quoted"[not a list]", a YAML error) stays a plain string. Before this, a documentedtarget_branches: []loaded as the truthy string'[]'.- Policy resolution fails closed. A malformed
add_ons/routing/automergeshape falls back to the safe default ({}/None/ disabled) with a warning appended tometa["warnings"], never widens autonomy.automerge.max_risk,agent_cli,fallback_agent_cli,agent_model,max_workers,pr_pacing_wait_s, andmax_parallel_workersare all validated/clamped the same way inload_policy. routing.env_profilesnames where a target's environment comes from and stores no values._validate_routing_env_profiles(never-raise warn-and-drop, like its sibling_validate_routing_*validators; resolved beforetargetsand returned in the resolved routing dict, because a target'sauth.profileis validated against it) accepts{name: {from, keys, expect?}}—fromis a path to a JSON file with anenvobject,keyslists which of that object's names to copy, andexpectmaps a name to the literal it must equal before a worker may launch.keysandexpectare deliberately independent: a key may be asserted without being copied (provenance checking) or copied without being asserted (so its value is never printable). A malformedexpectdrops the whole profile, not just the assertion — a silently-dropped assertion is indistinguishable from a passing one, which would defeat the only thingexpectexists for.resolve_routing()must carry this table into the resolved{targets, tiers, roles, purposes, default_tier, env_profiles, drain}dict it returns:spawnlibreads the profile table off that dict (never a second policy read, which could diverge from the tableselect_cellserved from), so dropping the key made every profile-bearing cell raiseOperatorConfigError("not declared in routing.env_profiles") at launch even when the profile was declared — confirmed live 2026-10-02, the drain's intake-triage spawn died on aclaude-deepseekcell whosedeepseekprofile was declared inrouting.yamlall along.auth.profileandauth.envare mutually exclusive alternatives for one auth lane, and a profile on asubscriptiontarget is a warning._validate_routing_targetswarns on a non-mappingauth, on bothenvandprofiledeclared together (the spawn hard-fails; the target is still kept so it appears in--check), and onauth.profileon asubscriptiontarget, because that lane stripsANTHROPIC_API_KEYafter profile injection — a profile-supplied key cannot survive there, though the target is still valid for non-key variables.auth.codex_homealongside a profile is not a conflict (it selects a home, not credentials)._warn_undeclared_env_profileswarns when anauth.profilenames a profileenv_profilesdoes not declare; the target is kept (mirroring "pool: apiwithoutapi_opt_inis kept but ineligible") and the authoritative failure is at spawn.worktrail-routing --checkresolves everyauth.profilecell against the real file, marking the cellFAIL, printing the fullOperatorConfigErrorto stderr, and exiting 1 — but deliberately NOT recording anagent_capacitygate. A recorded gate is skipped silently byselect_cellon the next spawn, which would turn a loud configuration error into an invisible fallback to the next rung — precisely the failure class env profiles exist to remove. Gates model provider conditions; this is operator config, and itsauthcooldown would outlive the fix.load_policy()runs a coarse type sweep (_sweep_key_types) before the per-key checks; the two layers are deliberately separate.POLICY_KEY_TYPESdeclares an expected type (or tuple) for every flatDEFAULTSkey, and a wrong-typed value is replaced by itsDEFAULTSentry with onemeta["warnings"]line (<key> must be <type>[ or null]; got <value!r> — using default <default!r>) — e.g.protected_paths: migrations/becomes[],pre_pr_cmd: truebecomesNone. A key whose default isNonealso acceptsNone, and a YAMLtruenever satisfies an integer key (boolis anintsubclass). The per-key checks further download_policystill run last, unchanged, and own value-level rules (allowed literals, integer minimums, per-entry cleaning).routing/add_onsare exempt (_TYPE_SWEEP_EXEMPT; their own resolvers run first), and every key that already has a stricter per-key check is declared inPOLICY_KEY_TYPESbut listed in_SWEEP_SKIPso the sweep never swallows a value before that check's own warning text (which callers assert on) can fire — the sweep effectively covers the keys that had no value-level check at all.run_record_dirrestores its lazily-resolveddefault_run_record_dir(), notNone.- A bare string under
require_human_routesorautomerge.target_branchesis NOT a type error. Both are declared(list, str):automerge_eligible()testsroute in require_human_routes, so a single-routerequire_human_routes: Bis a working gate that sweeping it to[]would silently open, and it already normalizes a baretarget_branches: devto a one-branch list. Only a value that is neither (e.g.target_branches: 7) falls back to[]with a warning namingautomerge.target_branches. The sweep reachesautomerge.target_branchesseparately because it is a flat key living one level down. A policy key added toDEFAULTSwith noPOLICY_KEY_TYPESentry (and not in_TYPE_SWEEP_EXEMPT) failstests/router/test_policy_key_types.py::test_every_defaults_key_has_a_declared_type_or_is_exempt. automerge.target_branchesempty means "base branch only", and a scalar is one branch, not a substring.automerge_eligible()treatstarget_branches: [](and unset) as no filter; a non-empty list rejects any PR whose target branch is not in it (target branch <b> not in [...]). A hand-edited scalartarget_branches: mainis coerced to["main"]before the check, because a bare string would otherwise fall through to a substring test ('ma' in 'main'). Both the[]spelling and the scalar case are pinned intests/router/test_policy.py.max_parallel_workers(default 6, minimum 1) is a ceiling, not a width. It only applies when neither--max-workersnor policymax_workersis set:live._resolve_max_workersthen runsmin(plan width, max_parallel_workers)workers instead of a fixed 3 (a width-7 plan ran as three serial ticks on 2026-09-02). A setmax_workersstill wins outright. Invalid values (non-int, bool,< 1) drop to the default with ameta["warnings"]entry, same as the other integer keys.- Integer policy keys follow the
triage_keep_limitvalidation pattern.triage_keep_limit(default 2) andtriage_max_queue_age_days(default 14) are the intake-triage escalation bounds: a value that is not anint, is abool, or is below 1 is forced back toDEFAULTS[key]with ameta["warnings"]entry naming the key. Their consumer isworkqueue/queue_triage.py's escalation, which reads them with.get(key, default)so the policy side and the consumer side can land in either order — as of 2026-09-02 the keys are inDEFAULTSbut no consumer reads them yet in this checkout. Copy this loop when adding another bounded-int key rather than inventing a new validation shape. - Plan-shape and review-skip keys use that same bounded-int loop.
compile_max_critical_path_over_width(default 2, min 1) andcompile_max_same_file_chain(default 2, min 1) are the plan-shape gatesconductor/compile.pyconsumes: a compiled plan is rejected when its critical path exceedsmax(width, compile_max_critical_path_over_width)or a dependent chain all touching one file exceedscompile_max_same_file_chain.review_skip_max_diff_lines(default 0 = disabled, min 0) is the fast pathorchestrator/live.py'sdrive()consumes beside_review_exempt: when > 0, a task's first review is skipped once the implement report is a verified success under that many added+removed diff lines (test files excluded). Invalid values drop to the default with ameta["warnings"]entry. pre_commit_cmd(defaultNone) is the one optional-string policy key. A non-string, non-Nonevalue is forced toNonewith a warning. Its consumers areorchestrator/dispatch.py(a worker-prompt hard rule for implement/fix and the ci-fix group prompt) andorchestrator/live.py/verify.py(post-commit amend backstop).Nonemeans repos without a wired command see no behavior change.onboarding/repo_init.py'sdetect_pre_commit_cmdseeds it into a fresh.worktrail/policy.yamlby scanning.github/workflows/*.yml|yamlrun:step lines forruff/oxlint/prettier(PRE_COMMIT_CMD_BY_LINTER, joined with&&in that order); an existing policy file is never touched.automerge.enabled: falsedoes not, by itself, block orchestrator-driven merges. Onlyautomerge_eligible()reads that key, and only when an agent follows sdd-workflow's Phase 8 merge-gate instructions —orchestrator's ownauto_merge()is a separate code path that unconditionally callsgh pr mergeonce CI passes and does not consult this key at all.- Run records enforce ten explicit completion states (
run_record.pyfinish, §22) — a run can never end in vague language.finishalso code-enforcesno_implementation_without_approval(a route-A run cannot finish on an implementation-completion state without a recordeddecisionsentry first) andpre_pr_gate.py'sscope_review_failures(), unconditional on route, exactly once per run regardless of how many group PRs the orchestrator created. - Scope-review entries are append-only; the gate judges only the latest entry per
--item.scope_review_failures()collapsesstatus | item | detailentries to the last one per item before checkingblocked/out-of-scope, so re-recording an item supersedes an earlier mis-phrased or blocked entry (and a laterblockedentry can equally regress a priorcomplete). Malformed entries still fail regardless of position. - An
out-of-scopereason must begin with a prefix fromrun_record.OUT_OF_SCOPE_REASON_PREFIXES(different purpose:/user approved:).cmd_scope_reviewrejects any other reason at write time withSystemExit, andscope_review_failures()re-checks the same tuple at gate time so a hand-edited record is still caught. Extend the tuple, never the two call sites separately. set-list PATH KEY [VALUE ...]is the only invocation that writes a list field, and the repair path for a list-typed field left holding a scalar.setstores its VALUE verbatim, soset PATH handoffs_consumed '["a","b"]'writes the string'["a","b"]', and every appender into that field —append,intervention(interventions), andrecord_decision_event(pending_decisions) — then refuses to touch it (brief 20261003-204455, where the documented recovery fromappendwas itself a dead end).cmd_set_listwriteslist(VALUES)(no values produces[], so an emptied field is expressible) and rejectsstatus, which is a phase, not a list, withSystemExitnamingset. All three append refusals share_scalar_list_field_hint(key), which namesset-list— the oldappendmessage said "useset", a command that cannot perform the repair.classifier_coverage.pyreports ahandoffs_consumedshape it cannot read as ids, and never decodes one._consumed_ids()returns(ids, diagnostics): a list of id strings (what every current writer produces) and a single plain id string (the oldersetform, still on disk) are ids, while a JSON-encoded array/object stored as a string (the sameset PATH handoffs_consumed '["a","b"]'footgun the bullet above describes), a comma-joined string, a non-string value, and a non-string list entry are diagnostics. Each malformed shape used to come through as ONE brief id that cannot exist, so the run's real attribution silently vanished from theactualjoin and this audit never surfaced it (brief 20261003-221534). They are reported, never parsed and never split — recovering the real ids is a separate judgment about what those records meant.load_actual_routes_with_diagnostics()is the audit's loader (load_actual_routes()is itsroutesprojection; the newest run id still wins when several consumed one brief), the diagnostics land in the--jsonpayload ascorpus.malformed_consumed_records(record,reason,value), andrender_reportprints amalformed handoffs_consumed: N record(s)line whenever that list is non-empty, so a reader knowsactualis blind rather than complete.capacity-gate --retry-afteris validated as ISO-8601 and stored verbatim, never slug-sanitized.cmd_capacity_gateruns it through_iso_retry_after(adatetime.fromisoformatcheck that raisesSystemExiton a non-ISO value) rather than_safe_provider, which is a slug sanitizer and turned+00:00into_00:00— an offset every downstreamretry_afterconsumer (orchestrator/agent_capacity._parse_time) then failed to parse (fixed 2026-09-06). Only--providerand--failure-classgo through_safe_provider.finishbest-effort-applies thego:risk-*PR label correction (pr_labels. ensure_pr_risk_label) whenever the record carries apull_request— a spawned headless agent's rawgh pr createis never reachable by the interactive Claude Code PreToolUse label-enforcement hook (Codex/OpenCode have no equivalent mechanism at all).- PR label writes use the REST endpoint, not
gh pr edit --add-label.gh pr edit's GraphQL mutation also touches classic-Projects fields and fails outright on a repo/org with a legacy Projects (classic) board still attached (confirmed live 2026-08-07)._current_pr_labels's read-onlygh pr viewcall is unaffected and stays as-is. reconcile_pr_labels.load_run_index()now reads records throughrun_record._load_lenient, not the raising_load— a single unreadable/malformed record (hand-edited outsiderun_record.py's own renderer) is skipped with aWARNING: skipping unreadable run record: ...line on stderr instead of aborting the whole scheduled sweep. Same tolerance policy_load_lenientalready applies toactive-conflictsand the other directory-widerun_record.pyscans (fixed 2026-09-12).check_deferred_work_handoff.load_deferred_work_entries()andcheck_durable_artifact_capture_gate.find_planned_run_records()— the two Stop-hook check scripts — now surface that same_load_lenientwarning too, instead of discarding it. Both previously unpacked_warningand threw it away, so a malformed run record failed silently with no signal that the check had skipped data. Both now printWARNING: skipping unreadable run record: <detail>to stderr and skip the record, matching the tolerance-with-visibility policy above (fixed 2026-09-12).dashboard.pydetects spec artifacts by exclusion + content, never one strict filename pattern. Known auxiliary files (user-request.md,decision-log.md,traceability-matrix.md, etc.) are named explicitly; any other top-level*.mdis a candidate spec doc, with a dated filename winning when several exist. A## Clarificationsheading is NOT the resolution-gate signal — only ~22/46 real specs carry one; the gate keys on unresolved[NEEDS CLARIFICATION: ...]markers in the spec body instead.- The dashboard JSON payload's
smoke_flakeskey is always present, never absent.smoke_flake_aggregate(repos)callssmoke_flake_selfcheck.check_repo()once per in-scope repo (both--rootsingle-repo and--reposmulti-repo mode), tags each entry with its repo name, and merges them into one{"entries": [...]}keeping the detector's ordering (count desc, suite asc), so a consumer can read the key without an existence check. The aggregate is passive: any failure yields{"entries": []}and therenderedsmoke-flake section is simply omitted — it never breaks the dashboard.smoke_flake_selfcheckis imported unconditionally (the detector-not-yet-shippedtry/except ImportErrorfallback is gone now that the module ships). The entry shape and the recency window are documented inskills/worktrail-go/references/dashboard-render.md. skill_dispatch.evaluate_single_brief()/apply_single_brief_verdict()resolve a barerepo:value to an on-disk checkout before using it ascwd. A brief'srepo:frontmatter is almost always a short name (e.g."worktrail"), not a path.evaluate_single_briefruns it throughdashboard._resolve_repo_dir(resolved_repo, repos_root)to buildgroup_cwdwhenever an explicit repo is resolved and nocwdoverride was passed — previously it passed the bare name straight through, whichsubprocess.runthen rejected as a nonexistent relativecwdwhen invoked from outside the target repo (e.g.worktrail-go's normal cwd).apply_single_brief_verdictnow takes and forwards arepos_rootparameter toqueue_triage.apply_verdicts()so apropose-change/fold-into-changeverdict's own_resolve_repo_dir()call can find the repo too — both call sites must resolve consistently, not just the evaluate path (fixed together 2026-09-03).land_pr.pyis the one shared PR-landing pipeline every PR-opening call site composes with, instead of each reimplementing a subset of it.land_pr(LandRequest) -> LandOutcomeruns, in order: commit pending work (refusesdirty_treewithout acommit_message), the compile-marker gate for every OpenSpec change whosetasks.mdchanged, the preflight gate + label read-back, push, find-or-create the PR (shared withorchestrator/integrate.py's group-PR step), CI watch to a terminal outcome (transient-infra reruns, no-checks-yet grace period,code_defectvsceilingclassification viaCI_PATCH_ITERATION_CEILING), the merge-state guard, the review-thread gate, then finish (or, in checkpoint mode, append a decision to) the run record. Refusal (steps 1-4) never touches the remote; a push or PR-create failure past that point is reported asoutcome="ceiling", neverrefused, because the remote is already mutated (an untouched-remote promiserefusedwould misrepresent). Registered asworktrail-land-pr(worktrail.router.land_pr:main). See the module's own docstring for the authoritative ordered step list — it exists because PR #902 shipped 112 gate-verified files that were never committed beforegit push, a gap each prior call site (queue_triage.py,drain.py,orchestrator/integrate.py, and the agent-executed sdd-workflow/worktrail-goprose) closed differently or not at all. As of 2026-09-05drain.py(_land_remediation_pr),close_stale_openspec.py, andworkqueue/queue_triage.pyall compose with it._push()always pushes with an explicitHEAD:<branch>refspec (git push -u <remote> HEAD:<branch>), never a baregit pushto the configured upstream: a branch created viagit worktree add ... -b <branch> origin/devtracksorigin/dev, so a bare push targeted the wrong remote branch (repro 2026-09-05, gracefully-giving-back PR #716). It no longer runs therev-parse @{u}upstream lookup at all. On a genuine"push"refusal it appends git's stderr (falling back to stdout) to an optionaldetail_out: list[str]out-param, andland_pr()surfaces that asLandOutcome.detailinstead ofnull— an out-param rather than a widened return type so existing callers/mocks of_push(repo, branch, remote, runner)keep working. A timeout/OSErrorstill returns"push_ambiguous"with nothing appended. Regression tests live intests/router/test_land_pr_push_refusal.py, deliberately not intest_land_pr.py.worktrail-land-prwrites oneREFUSED at <step>: <detail>line to stderr; stdout stays the machine contract._refusal_line()takes the first non-blank line ofoutcome.detail, truncating past_MAX_REFUSAL_DETAIL_CHARS(200) with a trailing...; an empty/Nonedetail yields the step alone.main()prints it only foroutcome == "refused", alongside the unchanged JSON payload (--jsonis required), so a machine consumer sees exactly what it saw before. It exists because the operator otherwise gets a JSON blob and has to read this module to interpret it — two live refusals in run go-20261003-153531 (PR #1402) each did, and refusal is the single most common landing failure (brief 20261003-204324).- Every post-PR-open
ghcall inland_pr.pyis scoped to the push-target repo viabase_slug, never left togh's bare-number resolution._gh(..., base_slug=)appends-R <base_slug>(the slug_push_target()returns) when set;_watch_ci,_checks_registered,_log_excerpt,_pr_is_merged,_merge_state_guard(including itsgh run rerun), and_review_thread_gateall take and thread it. On aremote.pushDefault=forkcheckoutoriginis the upstream, so a bare PR number or run id resolved against the upstream's same-numbered — and often long-merged — PR, andland_pr()reportedcompleted_and_merged/"merged externally"while the fork PR was still OPEN (live 2026-09-18, behindthedash/aspens PR #15 vs upstreamaspenkit/aspens#15)._review_thread_gatesplits the slug intoowner/nameand passes them tocheck_review_threads.check, which otherwise derives them fromorigin. With nopushDefault,base_slugisNoneand calls are unchanged. Any new PR- or run-scopedghcall added toland_pr.pymust takebase_slugtoo. automerge_preflightreads the remote the PR will actually be opened against, and refuses rather than falling back to another one.required_checks_gate()resolves the target remote once viapush_remote_name()(remote.pushDefault, elseorigin) and threads it intoowner_repo_from_git(..., remote=); both also accept an explicitremoteoverride. A selected remote that does not exist returnsNone— the old fallback tooriginanswered about a different repository, which on a fork layout is the read-only upstream (behindthedash/aspens PR #26, 2026-09-18: the gate readaspenkit/aspens'sallow_auto_merge=falseand putgo:no-automergeon a PR that was never going to be opened there). The refusal reason names the remote it tried, andis_preflight_query_error()stays False for it — an unresolvable remote is a confirmed state, not a transient read failure. The orchestrator's adapter (verify.Verifier._preflight_runner) rewrites everygitcall togit -C <repo> ..., not justgit remote get-url: the verifier's runner executes from its own neutral cwd, so an unpinnedgit config --get remote.pushDefaultread would answer for that directory and silently re-selectorigin.flip_and_archive's default (task_ids=None) targets every task id, not just the pending ones. The whole point of this module is bookkeeping drift, and its purest case is a change whosetasks.mdis already 100%[x]but was never archived. A pending-only default left bothflippedandalready_checkedempty for that change, so the "nothing to flip" guard refused to archive exactly the case it exists to close. Already-checked ids land inalready_checkedrather than being skipped, so the default path still archives a fully-checked change.close_stale_openspec.pynow lands the PR itself.main()requires--baseand--run; after a successfulflip_and_archiveit callsland_pr(LandRequest(route="E", risk="low", title="chore(<change-id>): close stale bookkeeping", commit_message="chore(<change-id>): archive completed change", ...)), mergesasdict(outcome)into the result under"landing", and maps the outcome to the exit code (landed→0,refused→2,code_defect/review_threads_blocking→3,ceiling→4, anything else→1). Aflip_and_archiveerror still exits 1 without ever callingland_pr. Theworktrail-goclose-stale row is one integrated invocation now (worktrail-close-stale-openspec ... --base "$BASE" --run "$RUN" --json), not a separateworktrail-land-prstep. Confirming a task is truly shipped remains the agent's call.cluster_detect.py's brief-to-brief focus-overlap signal abstains when either side carries fewer thanMIN_FOCUS_TOKENS(10) distinct tokens. The overlap coefficient divides by the smaller token set, so a very short focus text is trivially a near-subset of any longer brief and clearsOVERLAP_THRESHOLDon shared boilerplate alone: ontests/fixtures/classifier_corpus.json(as it stood before the 2026-09-19 regeneration) the 5-token focuscanonical checkout drift: <repo>scored 0.60 against five unrelated briefs, and 52 of the 112 pairs the threshold flagged involved an item that thin._focus_overlap()is the guarded wrapper carrying the floor and is what_signal_matchesand_llm_gate_scorecall, so a thin pair also never reaches the LLM verification band and spends a call on noise;_overlap_coefficient()stays the raw mathematical quantity for callers measuring something other than two briefs' focus text (create_handoff's spec-slug labels,_target_task_edges' task lines). A brief below the floor is not excluded from clustering —duplicate-slug,same-target-spec,related-linkandblocked-byall still connect it; only the "these two read alike" signal abstains, and the same floor gates which pairs_judgment_candidates()will offer to the relatedness judgment.
Critical files
router/parse_invocation.py— theworktrail-goPhase 1 grammar (parse,FORMS,ALIASES,NOUNS,MODES,render_forms); never shells out or writes, readsqueue/only when a folder is supplied, and delegates repo names to the caller (--repos) and brief-id resolution towork_queue.resolve()so nothing here becomes a second implementationrouter/classify.py—classify_risk()and theRISK_SIGNALStable (theauthzpattern's(?<![-@])compound-token guard lives here, now inside the extracted_classify_risk_by_keyword()); alsoclassify()'s two J-damping guards (_MENTION_ONLY_J_LABELS,_CI_CONFIG_RE,_CITED_AS_EXAMPLE_RE; and_CONSUMER_MENTION_J_LABELS,_CONSUMER_BY_PHRASE_RE) and the default-offrisk_judgment_enabledflag thatmain()is the only caller to enablerouter/typesafe.py— the one client both judgment backends share:API_URL/MODEL/API_KEY_ENV/TIMEOUT_S,is_configured(),post(state, questions), the strictnoul()reader, and theJUDGMENT_ERRORStuple that defines "unavailable"; knows nothing about either question set, and is where a new backend gets its transport instead of copying onerouter/risk_judgment.py— the secondclassify_riskbackend:QUESTIONS(one blast-radius score plus the four red-line nouls),is_configured(),ask()'s single request,parse_answers()'s strict shape check, the purecompose_tier()mapping ontoclassify.RISK_ORDER, andjudge_risk()'sNone-on-any-failure contract (itsaskerparameter is the injection seam tests use instead of a network fake); the tier policy lives incompose_tier(), never in the service's answerrouter/relatedness_judgment.py— the secondcluster_detectfocus backend: the two-NoulQUESTIONS(same_work,should_cluster), the pureshould_edge()union rule atJUDGMENT_THRESHOLD,judge_pair()'sNone-on-any-failure contract (same injectableaskerseam), andjudge_pairs()'s order-preserving concurrent batch (MAX_CONCURRENCY); the edge rule lives inshould_edge(), never in the service's answerrouter/policy.py—load_policy(); the single source of truth for a repo's resolved GO policy; alsoparse_policy_yaml/_parse_scalar(the flat parser and its inline-flow-sequence handling),POLICY_KEY_TYPES/_SWEEP_SKIP/_TYPE_SWEEP_EXEMPT/_sweep_key_types()(the coarse type sweep that runs ahead of the per-key checks; covered bytests/router/test_policy_key_types.py) andautomerge_eligible()(including thetarget_branchesscalar coercion)router/env_profile.py—resolve_env_profile(): expandsfrom, requires an absolute path (refused rather than resolved relative to the routing file, becauseexplicit_cell_overridepointsWORKTRAIL_ROUTING_FILEat a mkstemp file under /tmp), JSON-parses the file, requires a mappingenvobject, asserts everyexpectentry, then copies everykeysentry; refuses a missing/empty/non-string key. Every failure raisesOperatorConfigErrornaming target, profile, file and key, and no message ever contains a value for a key not named inexpect(the operator declared that key non-secret by asserting on it, and only that key). Deliberately not inspawnlib/routing_cli/policy:routing_cliimports..orchestrator.agent_capacityandspawnlibimports..router.routing_cli, so a module-levelrouting_cli → spawnlibedge would be an import cycle, andpolicy.py's validator must never open a profile file — reads belong at spawn and--checktime.router/run_record.py—finish()'s ten-state enforcement and its two code-enforced gates;cmd_scope_reviewwrite-time reason validation andOUT_OF_SCOPE_REASON_PREFIXES;cmd_capacity_gate's_iso_retry_aftertimestamp validation;cmd_set_list's list write (and itsstatusrefusal) plus_scalar_list_field_hint(), the refusal all three list-appenders raise through;_load_lenient(), the skip-and-warn wrapper around the raising_load()that every directory-wide scan (includingreconcile_pr_labels.load_run_index(),check_deferred_work_handoff.py, andcheck_durable_artifact_capture_gate.py) should use instead of the raising loaderrouter/pre_pr_gate.py—scope_review_failures(), the latest-entry-per-item scope gate thatfinishcallsrouter/pr_labels.py— the one place that issues thego:risk-*REST label correction; bothdrain.pyand sdd-workflow's Phase 8 call into it rather than reimplementing itrouter/reconcile_pr_labels.py—load_run_index(), the scheduled sweep that maps every PR URL under a runs dir to its{risk_level, gates, route}, tolerant of one malformed record viarun_record._load_lenientrouter/check_deferred_work_handoff.py— the Stop-hook deferred-work handoff guard;load_deferred_work_entries()readsdeferred_workentries via_load_lenientand now prints its discarded warning to stderr instead of silently skipping a malformed recordrouter/check_durable_artifact_capture_gate.py— the Stop-hook durable-artifact capture gate;find_planned_run_records()reads run records via_load_lenientand now prints its discarded warning to stderr instead of silently skipping a malformed recordrouter/dashboard.py— pure file inspection (no git, network, or agents); spec lifecycle stage and next-action detection; also the source of_resolve_repo_dir(), whichskill_dispatch.py's single-brief-triage path uses to resolve a barerepo:value to an on-disk checkout, ofsmoke_flake_aggregate(), which builds the always-presentsmoke_flakespayload key, and of thecompute_clusterscall site that injectsrelatedness_judgment.judge_pairs(only when configured) andcluster_telemetry.log_judged_pairsrouter/smoke_flake_selfcheck.py—check_repo(), the per-repo smoke-flake detector that reads recorded flakes out of a repo's run journals (recency-windowed) and thatdashboard.smoke_flake_aggregate()calls once per in-scope reporouter/land_pr.py—land_pr(),LandRequest/LandOutcome; the shared commit/compile-marker/preflight/push/PR/CI-watch/merge-guard/review-thread-gate/finish pipeline every PR-opening call site should compose with instead of reimplementing a subset;_push()'s explicit-refspec +detail_outcontract lives here, as does_gh()'sbase_slug(-R <slug>) scoping of every post-PR-open call, and_refusal_line()'s stderrREFUSED at <step>: <detail>line for the operator (stdout's JSON payload is unchanged)router/automerge_preflight.py—required_checks_gate(),owner_repo_from_git(),push_remote_name(),is_preflight_query_error(); the live GitHub-side half of the automerge gate and the single resolution point for the read side's target remote, so the gate can never inspect a different repository thanland_prpushes the branch and opens the PR againstrouter/close_stale_openspec.py—flip_and_archive()plusmain()'sland_prlanding and outcome→exit-code mapping for theworktrail-close-stale-openspecconsole scriptrouter/cluster_detect.py— the brief-clustering signals (_signal_matches,_llm_gate_score) thatworkqueue/create_handoff.pyconsumes;_focus_overlap()is the guarded focus comparison carryingMIN_FOCUS_TOKENS, while_overlap_coefficient()stays the raw coefficient every non-focus caller keeps reading;_judgment_candidates()/_apply_relatedness_judgment()own which pairs are worth judging and what a verdict does to an edge (JUDGED_MATCH,JUDGMENT_PREFILTER_FLOOR,MAX_JUDGED_PAIRS) while the client and the telemetry writer stay injectedrouter/cluster_telemetry.py— the one append-only cluster log;log_shown,log_outcome, andlog_judged_pairs()'sjudgedrecord kind (members, overlap, both Noul values, verdict), all best-effort writers that never affect what they record
Last Updated: 2026-10-05
04 同仓库更多 Skills
worktrail-sdd-workflow
Internal SDD workflow executor invoked by /go only. Do not call directly. Executes classified routes A–J: feature planning, implementation (parallel orchestration, PR generation), defect repair, refactoring, spec changes, investigation, and workflow evolution.
worktrail-routing-config
Configure Worktrail's agent routing table (`~/.worktrail/routing.yaml`, or a repo-local `routing:` policy block) — which harness/model executes each role and tier, and how fallback between them works. Use when the operator wants to add or remove a harness/adapter (claude/codex/opencode), add a model to an existing harness (e.g. adding a DeepSeek model to opencode), pin or change who does code review, add a new tier or purpose mapping, change the default tier, or is confused about which harness actually served a spawn (e.g. "why did this use Codex when I only configured Claude"). Trigger phrases: "routing.yaml", "add a harness", "disable a harness", "add an adapter", "remove an adapter", "add a model", "add deepseek to opencode", "change the reviewer", "pin the reviewer", "routing tiers", "routing targets", "default_tier", "independent reviewer", "why did codex get called". This skill is about *editing the config file*; it does not cover `/go`'s own dispatch mechanics (see `worktrail-go`'s SKILL.md Phase 7 for how `tier_for()`/`select_cell()` resolve it at runtime).
worktrail-repo-init
Bootstrap a new repo, or migrate an existing single-branch repo, onto the workspace's repo-standards doctrine (~/rules/CLAUDE.repo.md): the AGENTS.md-is-truth/CLAUDE.md-imports-it split, a dev/prd, dev/stg/prd, or main-only (trunk) branch model with matching GitHub rulesets, an OpenSpec scaffold, an auto-merge workflow, and a seeded .worktrail/policy.yaml. Trigger phrases: "onboard this repo", "apply repo standards", "initialize repo standards", "set up this repo like the rest of the fleet", "bring this repo into line with the repo standards doctrine".
worktrail-help
Show the Worktrail front-door commands and accepted positional arguments. Use when the user asks how to invoke worktrail-go, wants the available handoff, spec, pr, repo, or route forms, invokes worktrail-go with help or with a bare noun, or asks how to answer a filed product decision (worktrail-decision).
worktrail-handoff
Capture a discovered problem, gap, tech debt, or deferred work into a local work queue so a future agent session can pick it up cold. Use mid-session whenever you set work aside instead of doing it now — a fix you judge out of scope for this PR, work that belongs in a follow-up or a separate/later PR, an item you're deferring, or something worth fixing you won't tackle now — so the outstanding item isn't lost without derailing current work; can be called multiple times per session. Trigger phrases: "defer this", "item deferred", "out of scope for this PR", "follow-up work", "leave for another PR", "capture for later", "outstanding item". This skill captures only. Picking a brief back up is the front door's job: worktrail-go <brief-id>.
worktrail-go
Use when the user invokes worktrail-go, asks to pick up queued work, resume active specs, implement or fix a spec, route engineering work, or orient across repositories. Renders the orientation dashboard, classifies free-text requests, claims/resumes handoff briefs, and dispatches SDD work without requiring the user to know sdd-workflow. Grammar: worktrail-go [REPO] <noun> <verb>, nouns handoff / spec / pr / decision. Triggers: worktrail-go, worktrail-go help, worktrail-go spec fix, worktrail-go spec implement, worktrail-go spec route F, worktrail-go handoff new, worktrail-go handoff auto, worktrail-go decision answer, worktrail-go BRIEF-ID, bare worktrail-go, multi-repo orientation.