Skip to content

Commit c102bec

Browse files
fix(init): read agent-name bindings the way Python does, or decline
Addresses the six blocking review findings on #371. Each was reproduced against the pre-fix code before being fixed, and each fix has a test that fails without it. The ranking shipped in the previous commit read Python name binding with a flattened `ast.walk` and first-write-wins heuristics, which produced misleading `agent.name` values in several statically reproducible cases — including the fail-closed case #324 explicitly requires. **An unresolved application root now blocks selection entirely.** With `root_agent = LlmAgent(name=f"{tier}-coordinator", sub_agents=[worker])`, detection dropped the root and wrote `agent.name: WorkerAgent`. Letting the rest of the field rank looks conservative, but everything remaining is by construction *not* the root, so it silently declares a worker as the reviewed identity. A dynamic name, a factory call such as `App(root_agent=build_root())`, or a symbol no single construction defines now all produce CHANGE_ME plus the reason. The previous test asserted the old behaviour and is replaced — it encoded the bug. The block is deliberately workspace-wide rather than scoped to the file that declares the unresolved root. Scoping it would let a resolved root elsewhere win, which is precisely the class of "assert an identity we cannot justify" this PR exists to remove. **References resolve to the reaching assignment.** For `agent = Agent(name="OldWorker"); agent = Agent(name="ActualRoot"); App(root_agent=agent)`, both constructions were classified as roots and source order picked the overwritten one. Bindings are now matched by nearest scope then latest line before the reference. **Scopes are no longer flattened.** A function-local `root_agent` was promoted to application root and outranked every real module-level agent; the ADK convention is about the *module* symbol `adk run` imports. A helper-local `from other import AGENT_NAME` could likewise supply the value a module-level construction reads from a different module. Imports are now keyed by scope, and `from config import AGENT_NAME as NAME` looks up `AGENT_NAME` in the target module rather than the alias. **Constants require exactly one binding.** `setdefault` made `NAME = "OldAgent"; NAME = "CurrentAgent"` resolve to `OldAgent`, a value Python never passes, and a conditional or computed later write was ignored rather than triggering the promised fail-closed result. A symbol bound more than once anywhere in the file — later, conditional, computed, in another scope, or as a parameter — is now never resolved. That single rule is what makes reading module-level constants safe at all. **Conflicting import roots leave the identity unresolved.** `from config import AGENT_NAME` resolves against the agent directory or the workspace root depending on `sys.path`; when both exist in-workspace and disagree, which one Python picks is not ours to assume. Package `__init__.py` now also precedes the module file, matching Python's own finder. **Child edges require a verified agent constructor.** The `sub_agents=` / `handoffs=` branch ran for any call, so `configure(handoffs=[coordinator])` demoted the coordinator and handed the identity to an unrelated worker. **The zero-install byte-parity claim now holds.** It did not: the script walked the filesystem while canonical detection lists through Git, so a `.gitignore`d module could win a ranking `init` can never produce, and a Python symlink escaping the workspace both contributed a name and leaked its outside absolute path into `path`. Both reproduced. The script now uses the same bounded `git ls-files` inventory when Git can read the workspace, containment-checks every fallback-walk path, and bounds Python *parses* rather than the whole inventory — a global file cap let an asset-heavy repository exhaust its budget before reaching any source. Three parity tests cover the three cases and all three fail on the previous script. Two consistency fixes from the review body: - `cli/detect.py` printed candidate zero rather than calling `select_agent_name`, so with only `Agent(name="t")` the human-readable `detect` reported `t` while `init` wrote CHANGE_ME. It now reports what `init` will write, and prints the rejection reasons when nothing is selectable. That was the fourth copy of the selection rule. - `docs/agent-recipes.md` claimed `project_name_candidates[]` shares the enriched shape; it remains `{value, source}`. Sample selections are unchanged, and both originally reported repositories still resolve correctly (`Strix`, `SmartCloserAgent`). Co-Authored-By: Claude Opus 5 <[email protected]>
1 parent b8b5bac commit c102bec

9 files changed

Lines changed: 1060 additions & 140 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,43 @@
3333
future ordering regression is visible in `detect --json` instead of
3434
silently changing what the manifest claims. The rule itself now exists once
3535
(`select_agent_name`) rather than as a `source in {…}` set literal copied
36-
into the renderer and the JSON summary, and
37-
`tools/shipgate-detect.py` (`script_version` `0.3.0`) is pinned to the
36+
into the renderer, the JSON summary, and `detect`'s human-readable line,
37+
and `tools/shipgate-detect.py` (`script_version` `0.3.0`) is pinned to the
3838
CLI's ranking byte for byte by the parity suite.
3939

40+
Because the ranking reads Python name binding, it reads it the way Python
41+
does or else declines. Scopes are not flattened: a helper's local
42+
`root_agent`, and a helper's local import, belong to that helper and never
43+
stand in for the module's. A reference resolves to the assignment that
44+
actually reaches it — nearest scope, latest line before the reference —
45+
rather than to every assignment sharing the identifier. A symbol bound
46+
more than once anywhere in a file is never resolved, which is what makes
47+
reading module-level constants safe at all: a second write, whether later,
48+
conditional, computed, or in another scope, means the value Python passes
49+
is not the one visible statically. `from config import AGENT_NAME as NAME`
50+
looks up `AGENT_NAME` in the target module, not the alias. And when an
51+
import could resolve to two different in-workspace modules — the agent
52+
directory's `config.py` and the workspace root's — which one Python picks
53+
depends on `sys.path`, so the identity stays unresolved.
54+
55+
**A declared application root that cannot be resolved statically now
56+
blocks selection entirely.** Dropping it and letting the rest of the field
57+
rank looks conservative but is the #324 failure again: everything
58+
remaining is by construction *not* the root, so the manifest would declare
59+
a worker. A dynamic name, a factory call, or a symbol no single
60+
construction defines all produce `CHANGE_ME` plus the reason.
61+
62+
The zero-install detector now takes the same workspace inventory as the
63+
CLI — `git ls-files` when Git can read the workspace, a contained
64+
filesystem walk otherwise — because that is what makes the parity claim
65+
true rather than merely tested on tidy fixtures. A `.gitignore`d module is
66+
invisible to `init`, so walking it anyway let the script name an agent
67+
`init` would never write; a symlink escaping the workspace both
68+
contributed a name and leaked its outside absolute path into the output.
69+
Its file bound also moved from the whole inventory onto Python parses, so
70+
an asset-heavy repository can no longer exhaust the budget before the walk
71+
reaches any source.
72+
4073
- **The recommended next command now runs where it was recommended.** Every
4174
emitted command was written as the console script the wheel installs
4275
(`agents-shipgate …`), so a run started from a source checkout with

‎docs/agent-recipes.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,23 @@ Consume the response to decide whether to proceed. Key fields:
100100
generic scaffolding names (`agent`, `foo`, `test`, …), are ranked last
101101
and marked `selectable: false`.
102102

103+
One rule overrides all four: if the workspace declares an application root
104+
whose name cannot be resolved statically — a dynamic expression, a factory
105+
call, a symbol bound more than once — then **nothing** is selectable, and
106+
the `rationale[]` says why. Anything still ranked is by construction not
107+
the root, so writing it would declare a worker as the reviewed identity.
108+
103109
`rationale[]` states which of those applied, so a ranking change is
104110
visible in the output rather than silently changing what the manifest
105111
claims. `name=` values that come from a module constant or an
106112
`os.environ.get("…", "…")` default in the same package are resolved
107-
statically (one hop, no code executed) and say so in `rationale[]`.
108-
- `project_name_candidates[]` — same shape; `pyproject` source seeds
109-
`project.name` only.
113+
statically (one hop, no code executed) and say so in `rationale[]`. That
114+
resolution is deliberately conservative: a symbol bound more than once
115+
anywhere in the file, or one whose import could resolve to two different
116+
in-workspace modules, is left unresolved rather than guessed.
117+
- `project_name_candidates[]` — `{value, source}` only. Project names have
118+
no hierarchy to rank, so they carry none of the fields above. The
119+
`pyproject` source seeds `project.name`, never `agent.name`.
110120
- `suggested_sources[]` — MCP/OpenAPI files matched by glob AND accepted
111121
by the real input adapters, so `init` never writes a `tool_sources`
112122
entry that `scan` rejects at parse time. These do NOT bump

‎docs/zero-install.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ The script and the canonical CLI are pinned to **structural verdict parity** by
4545

4646
**When to use this:** you're a coding agent (Claude Code, Codex, Cursor) deciding *whether* to propose Shipgate. The script tells you in one fetch + one Python invocation. The full flow (`init`, `scan`, `apply-patches`) requires the actual install.
4747

48-
**Constraints:** Python 3.12+ on the runner. No git fast path (uses `os.walk` only). Evidence/reason strings and absolute scores are simplified — the verdict is what's pinned, not the prose.
48+
**Constraints:** Python 3.12+ on the runner. Evidence/reason strings and absolute framework scores are simplified — the verdict is what's pinned, not the prose.
49+
50+
The workspace inventory does match the canonical CLI's — `git ls-files` when Git can read the workspace, a contained filesystem walk otherwise. That is a correctness requirement, not a speed one: a `.gitignore`d module is invisible to `init`, so a script that walked it anyway could name an agent `init` will never write. Paths escaping the workspace through a symlink are dropped for the same reason.
4951

5052
## 2. `uvx` (no permanent install)
5153

‎llms-full.txt‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -843,13 +843,23 @@ Consume the response to decide whether to proceed. Key fields:
843843
generic scaffolding names (`agent`, `foo`, `test`, …), are ranked last
844844
and marked `selectable: false`.
845845

846+
One rule overrides all four: if the workspace declares an application root
847+
whose name cannot be resolved statically — a dynamic expression, a factory
848+
call, a symbol bound more than once — then **nothing** is selectable, and
849+
the `rationale[]` says why. Anything still ranked is by construction not
850+
the root, so writing it would declare a worker as the reviewed identity.
851+
846852
`rationale[]` states which of those applied, so a ranking change is
847853
visible in the output rather than silently changing what the manifest
848854
claims. `name=` values that come from a module constant or an
849855
`os.environ.get("…", "…")` default in the same package are resolved
850-
statically (one hop, no code executed) and say so in `rationale[]`.
851-
- `project_name_candidates[]` — same shape; `pyproject` source seeds
852-
`project.name` only.
856+
statically (one hop, no code executed) and say so in `rationale[]`. That
857+
resolution is deliberately conservative: a symbol bound more than once
858+
anywhere in the file, or one whose import could resolve to two different
859+
in-workspace modules, is left unresolved rather than guessed.
860+
- `project_name_candidates[]` — `{value, source}` only. Project names have
861+
no hierarchy to rank, so they carry none of the fields above. The
862+
`pyproject` source seeds `project.name`, never `agent.name`.
853863
- `suggested_sources[]` — MCP/OpenAPI files matched by glob AND accepted
854864
by the real input adapters, so `init` never writes a `tool_sources`
855865
entry that `scan` rejects at parse time. These do NOT bump

‎src/agents_shipgate/cli/detect.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
diagnose_detect,
2222
top_next_actions,
2323
)
24-
from agents_shipgate.cli.discovery import detect_workspace
24+
from agents_shipgate.cli.discovery import detect_workspace, select_agent_name
2525
from agents_shipgate.core.errors import DiscoveryError
2626
from agents_shipgate.schemas.diagnostics import Diagnostic, NextAction
2727

@@ -117,8 +117,22 @@ def detect(
117117
typer.echo(f" · ... ({len(framework.evidence) - 5} more)")
118118
typer.echo("")
119119
if result.agent_name_candidates:
120-
primary = result.agent_name_candidates[0]
121-
typer.echo(f"Agent name candidate: {primary.value} (source: {primary.source})")
120+
# The same call `init` makes, not "candidate zero" — printing the
121+
# top-ranked entry regardless of selectability would tell a human
122+
# that `t` is the agent name while `init` writes CHANGE_ME.
123+
selected = select_agent_name(result.agent_name_candidates)
124+
if selected is not None:
125+
typer.echo(
126+
f"Agent name candidate: {selected.value} (source: {selected.source})"
127+
)
128+
else:
129+
top = result.agent_name_candidates[0]
130+
typer.echo(
131+
"Agent name candidate: none usable — init will write CHANGE_ME "
132+
f"(highest ranked was {top.value!r})"
133+
)
134+
for reason in top.rationale:
135+
typer.echo(f" · {reason}")
122136
if result.project_name_candidates:
123137
primary = result.project_name_candidates[0]
124138
typer.echo(f"Project name candidate: {primary.value} (source: {primary.source})")

0 commit comments

Comments
 (0)