Skip to content

feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107

Closed

Description

@dan-petty

Ready: implementation plan (refined 2026-10-17 at 3dd7fa6)

The plan is in this comment, because the body has no room for it. It supersedes any text below that conflicts with it.


Problem

Lines cited at dcafadf.
At 132ecc5, ai/mcp/server.py:2050 is :2073, and in config/constants.py :2296-2299 is :2297-2300, :2505 is :2539, :2512-2518 is :2546-2552 and :3003 is :3037; every other cited line is unchanged.

Acceptance criteria

Rules

  • .ast-grep/rules/ holds exactly these 12 rules, one file each, with language: python, severity: error and a message that names the library. Hits are distinct rule-and-line pairs at dcafadf; ast-grep itself prints 124 matches, because chained calls such as .replace(...).replace(...) match more than once on one line.
Rule Matches Hits Message names
net-scheme-in "…://…" in x or not in x 14 urllib.parse.urlsplit(value).scheme
net-scheme-affix startswith, endswith, removeprefix, removesuffix or replace with an argument holding ://, starting unix:, or an IPv4 prefix such as "169.254." 27 (debatable: ai/agents/media.py:184 and security/vault_broker.py:53, the project's own schemes) urlsplit, docker.utils.parse_host, jeepney, ipaddress
net-bracket-affix startswith("[") / endswith("[") inside a boolean expression that also holds a : string 3 urlsplit(value).hostname, httpx2.URL(value).host, ipaddress
net-domain-suffix endswith / removesuffix on a value named like host, domain, netloc, server, endpoint, url, addr or fqdn, with a .-leading argument (".x", f".{d}", "." + d) 10 dns.name is_subdomain, tldextract
net-ip-literal a comparison involving an IPv4 or IPv6 literal or CIDR 5 (false positive: ai/review/defects.py:693; debatable: security/tflint.py:63) ipaddress.ip_address properties, ip_network membership
net-address-list a set, tuple or list holding an IPv4 literal with an IPv6 literal or "localhost", an IPv6 literal with "localhost", a bare scheme ("http://") or "://" 23 (false positives: models/tls.py:51, config/defaults.py:189) ipaddress, urlsplit; provider data as ipaddress constants with source cited
net-domain-list an assignment to a domain- or tld-named target whose value holds a .-leading string 1 tldextract, dns.name
net-normalise strip/lstrip/rstrip with "[]", or with "." in a chain that contains .lower() 9 httpx2.URL(value).host, urlsplit(value).hostname, ipaddress, dns.name.from_text
net-hostport split/rsplit/partition/rpartition on ":" or "@" of a value named like host, netloc, addr, endpoint, server or authority 3 urlsplit (.hostname, .port, .username), urlsplit("//" + authority), httpx2.URL
net-port-table 443 if … else 80, 80 if … else 443 5 httpx2.URL(value).origin
net-cidr-build an f-string ending }/32 or }/128 1 ipaddress.ip_network(value, strict=False).with_prefixlen
net-url-build an f-string scheme://{…} whose first field names a host, addr, address, ip, netloc, url, target or endpoint 13 httpx2.URL(scheme=..., host=..., port=...), copy_with, join
  • Each rule has at least one valid and one invalid case in .ast-grep/rule-tests/<rule-id>-test.yml, and uv run ast-grep test --skip-snapshot-tests passes (measured: 12 passed in about 26 ms).
  • The root sgconfig.yml holds only ruleDirs: [.ast-grep/rules] and testConfigs: [{testDir: .ast-grep/rule-tests}].
Rule files (verified with ast-grep 0.45.3 against src at dcafadf: 114 rule hits, 103 lines, 46 files)
# .ast-grep/rules/net-scheme-in.yml
id: net-scheme-in
language: python
severity: error
message: Scheme detected by substring. Read it with urllib.parse.urlsplit(value).scheme.
rule:
  any:
    - pattern: $S in $X
    - pattern: $S not in $X
constraints:
  S:
    kind: string
    regex: "://"

# .ast-grep/rules/net-scheme-affix.yml
id: net-scheme-affix
language: python
severity: error
message: Prefix or suffix test on a scheme or an address. Read the scheme with urllib.parse.urlsplit(value).scheme, container-engine endpoints (Podman or Docker) with docker.utils.parse_host and D-Bus addresses with jeepney; classify addresses with ipaddress (is_link_local, is_loopback, is_private).
rule:
  kind: call
  all:
    - has:
        field: function
        kind: attribute
        has:
          field: attribute
          regex: ^(startswith|endswith|removeprefix|removesuffix|replace)$
    - has:
        field: arguments
        has:
          stopBy: end
          kind: string
          regex: '://|^["'']unix:|^["'']\d{1,3}\.(\d{1,3}\.){0,2}["'']$'

# .ast-grep/rules/net-bracket-affix.yml
id: net-bracket-affix
language: python
severity: error
message: IPv6 brackets handled by hand. urllib.parse.urlsplit(value).hostname or httpx2.URL(value).host returns the bare host; parse it with ipaddress.ip_address.
rule:
  kind: call
  all:
    - has:
        field: function
        kind: attribute
        has:
          field: attribute
          regex: ^(startswith|endswith)$
    - has:
        field: arguments
        has:
          kind: string
          regex: '^["'']\[["'']$'
    - inside:
        kind: boolean_operator
        stopBy: end
        has:
          stopBy: end
          kind: string
          regex: ':'

# .ast-grep/rules/net-domain-suffix.yml
id: net-domain-suffix
language: python
severity: error
message: Domain matched by string suffix. Use dns.name.from_text(host).is_subdomain(dns.name.from_text(domain)); public-suffix questions go to tldextract.
rule:
  kind: call
  all:
    - has:
        field: function
        kind: attribute
        all:
          - has:
              field: attribute
              regex: ^(endswith|removesuffix)$
          - has:
              field: object
              regex: (?i)(host|domain|netloc|server|endpoint|url|addr|fqdn)
    - has:
        field: arguments
        has:
          stopBy: end
          kind: string
          regex: '^f?["'']\.'

# .ast-grep/rules/net-ip-literal.yml
id: net-ip-literal
language: python
severity: error
message: Comparison with an IP address literal. Parse with ipaddress.ip_address(host) and test is_loopback, is_link_local, is_private, or membership in an ipaddress.ip_network.
rule:
  kind: comparison_operator
  has:
    stopBy: end
    kind: string
    regex: '^["''](\d{1,3}(\.\d{1,3}){3}(/\d+)?|[0-9a-fA-F]*:[0-9a-fA-F:]*:[0-9a-fA-F]+(/\d+)?)["'']$'

# .ast-grep/rules/net-address-list.yml
id: net-address-list
language: python
severity: error
message: Literal list of addresses, loopback names or schemes. Classify with ipaddress (is_loopback, is_link_local, is_private, is_global) and read schemes with urllib.parse.urlsplit; data no library knows is a constant of ipaddress objects with its source cited.
utils:
  ipv4:
    kind: string
    regex: '^["'']\d{1,3}(\.\d{1,3}){3}(/\d+)?["'']$'
  ipv6:
    kind: string
    regex: '^["''][0-9a-fA-F]*:[0-9a-fA-F:]*:[0-9a-fA-F]*(/\d+)?["'']$'
  localhost:
    kind: string
    regex: '^["'']localhost["'']$'
  scheme:
    kind: string
    regex: '^["''][a-z][a-z0-9+.-]*://["'']$|^["'']://["'']$'
rule:
  all:
    - any:
        - kind: set
        - kind: tuple
        - kind: list
    - any:
        - all:
            - has: {matches: ipv4}
            - any:
                - has: {matches: ipv6}
                - has: {matches: localhost}
        - all:
            - has: {matches: ipv6}
            - has: {matches: localhost}
        - has: {matches: scheme}

# .ast-grep/rules/net-domain-list.yml
id: net-domain-list
language: python
severity: error
message: Literal list of domain suffixes. Use tldextract (Public Suffix List) or dns.name is_subdomain.
rule:
  kind: assignment
  all:
    - has:
        field: left
        regex: (?i)(domain|tld)
    - has:
        field: right
        has:
          stopBy: end
          kind: string
          regex: '^["'']\.[a-z]'

# .ast-grep/rules/net-normalise.yml
id: net-normalise
language: python
severity: error
message: Host canonicalised by hand. httpx2.URL(value).host or urllib.parse.urlsplit(value).hostname drops brackets and lower-cases; ipaddress.ip_address and dns.name.from_text give the canonical form.
rule:
  kind: call
  all:
    - has:
        field: function
        kind: attribute
        has:
          field: attribute
          regex: ^(strip|rstrip|lstrip)$
    - any:
        - has:
            field: arguments
            has:
              kind: string
              regex: '^["'']\[\]["'']$'
        - all:
            - has:
                field: arguments
                has:
                  kind: string
                  regex: '^["'']\.["'']$'
            - regex: '\.lower\(\)'

# .ast-grep/rules/net-hostport.yml
id: net-hostport
language: python
severity: error
message: Host, port or userinfo split by hand. Use urllib.parse.urlsplit(value) (.hostname, .port, .username), urlsplit("//" + authority) for a bare authority, or httpx2.URL(value).
rule:
  any:
    - pattern: $R.$M($SEP)
    - pattern: $R.$M($SEP, $$$REST)
constraints:
  M:
    regex: ^(split|rsplit|partition|rpartition)$
  SEP:
    kind: string
    regex: '^["''][:@]["'']$'
  R:
    regex: (?i)(host|netloc|addr|endpoint|server|authority)

# .ast-grep/rules/net-port-table.yml
id: net-port-table
language: python
severity: error
message: Default-port table. httpx2.URL(value).origin fills in the scheme's default port.
rule:
  any:
    - pattern: 443 if $C else 80
    - pattern: 80 if $C else 443

# .ast-grep/rules/net-cidr-build.yml
id: net-cidr-build
language: python
severity: error
message: CIDR built as text. Use ipaddress.ip_network(value, strict=False).with_prefixlen.
rule:
  kind: string
  regex: '^f["''].*\}/(32|128)["'']$'

# .ast-grep/rules/net-url-build.yml
id: net-url-build
language: python
severity: error
message: URL authority built with an f-string. Build it with httpx2.URL(scheme=..., host=..., port=...), which brackets IPv6 hosts, or httpx2.URL.copy_with / join.
rule:
  kind: string
  regex: '(?i)^f["''][a-z][a-z0-9+.-]*://\{[a-z_.]*(host|addr|address|ip|netloc|url|target|endpoint)'
Rule test files (all 12 pass)
# .ast-grep/rule-tests/net-address-list-test.yml
id: net-address-list
valid:
  - 'METADATA = frozenset({ipaddress.ip_address("169.254.169.254")})'
  - 'EXTENSIONS = (".yaml", ".yml")'
invalid:
  - 'LOOPBACK = {"localhost", "127.0.0.1", "::1"}'
  - 'MARKERS = ("@", "://")'
  - 'SCHEMES = ("http://", "https://")'

# .ast-grep/rule-tests/net-bracket-affix-test.yml
id: net-bracket-affix
valid:
  - 'host = urlsplit(url).hostname'
invalid:
  - 'is_v6 = host.startswith("[") and ":" in host'

# .ast-grep/rule-tests/net-cidr-build-test.yml
id: net-cidr-build
valid:
  - 'cidr = ipaddress.ip_network(value, strict=False).with_prefixlen'
invalid:
  - 'cidr = f"{clean}/32"'
  - 'cidr = f"{clean}/128"'

# .ast-grep/rule-tests/net-domain-list-test.yml
id: net-domain-list
valid:
  - 'LOCAL_DOMAIN = "example.com"'
invalid:
  - 'LOCAL_DOMAIN_SUFFIXES = (".internal", ".home.arpa")'

# .ast-grep/rule-tests/net-domain-suffix-test.yml
id: net-domain-suffix
valid:
  - 'inside = dns.name.from_text(host).is_subdomain(dns.name.from_text("example.com"))'
  - 'is_yaml = filename.endswith(".yaml")'
invalid:
  - 'inside = host.endswith(".example.com")'
  - 'inside = hostname.endswith(f".{domain}")'
  - 'inside = netloc.endswith("." + domain)'

# .ast-grep/rule-tests/net-hostport-test.yml
id: net-hostport
valid:
  - 'host = urlsplit(url).hostname'
  - 'key, value = line.split(":", 1)'
invalid:
  - 'host = urlparse(url).netloc.split(":")[0]'
  - 'host, _, port = endpoint.rpartition(":")'

# .ast-grep/rule-tests/net-ip-literal-test.yml
id: net-ip-literal
valid:
  - 'local = ipaddress.ip_address(host).is_loopback'
invalid:
  - 'local = host == "127.0.0.1"'
  - 'local = host in ("::1",)'

# .ast-grep/rule-tests/net-normalise-test.yml
id: net-normalise
valid:
  - 'host = httpx2.URL(url).host'
  - 'name = value.strip().lower()'
invalid:
  - 'host = value.strip("[]")'
  - 'host = value.lower().rstrip(".")'

# .ast-grep/rule-tests/net-port-table-test.yml
id: net-port-table
valid:
  - 'origin = httpx2.URL(url).origin'
invalid:
  - 'port = 443 if scheme == "https" else 80'
  - 'port = 80 if plain else 443'

# .ast-grep/rule-tests/net-scheme-affix-test.yml
id: net-scheme-affix
valid:
  - 'secure = urlsplit(url).scheme == "https"'
  - 'is_meta = ipaddress.ip_address(host).is_link_local'
invalid:
  - 'secure = url.startswith("https://")'
  - 'is_meta = host.startswith("169.254.")'
  - 'path = address.removeprefix("unix:path=")'

# .ast-grep/rule-tests/net-scheme-in-test.yml
id: net-scheme-in
valid:
  - 'has_scheme = urlsplit(url).scheme in ("http", "https")'
invalid:
  - 'has_scheme = "://" in url'
  - 'bare = "://" not in url'

# .ast-grep/rule-tests/net-url-build-test.yml
id: net-url-build
valid:
  - 'url = str(httpx2.URL(scheme="http", host=host, port=port))'
  - 'message = f"see {host} for details"'
invalid:
  - 'url = f"http://{host}:{port}"'
  - 'url = f"http://{node_ip}:{node_port}"'

Gate

  • ast-grep-cli==0.45.3 is in the dev dependency group (pyproject.toml:64-77), installed the way actionlint-py is. Commands call the binary ast-grep, never sg, which on Linux is the shadow-utils group command.
  • Three new constants in src/devops_cli/config/constants.py back the gate and its meta-test:
    • CONST_NET_CONSTRUCT_RULES: the 12 rule ids above;
    • CONST_AST_GREP_SCAN_ARGS: ("scan", "--error=unused-suppression", "--error=no-suppress-all", "src");
    • CONST_BANNED_HAND_ROLLED_APIS: the four socket functions banned under TID251 below.
  • The two commands below land as one constructs row of refactor(ci): github ci runs the gate through devops ci from one check table #843's check table, which devops ci and GitHub CI both run (refactor(ci): github ci runs the gate through devops ci from one check table #843 makes the static job run the gate through devops ci, with a parity test over the table). If this item lands before refactor(ci): github ci runs the gate through devops ci from one check table #843, refactor(ci): github ci runs the gate through devops ci from one check table #843 carries the row. There is no separate task entry in commands/ci.py and no separate step in .github/workflows/ci.yml. The row builds the scan command as ["uv", "run", "ast-grep", *CONST_AST_GREP_SCAN_ARGS].
    • uv run ast-grep scan --error=unused-suppression --error=no-suppress-all src
    • uv run ast-grep test --skip-snapshot-tests
  • The same two commands run as hooks in the repo: local block of .pre-commit-config.yaml (:45) with language: system and pass_filenames: false. The hooks call uv run ast-grep directly, not devops ci, because importing devops_cli costs about five seconds (the comment at .pre-commit-config.yaml:47-51).
  • The step takes 1 s of wall time or less (measured 0.25-0.27 s on an idle host and 0.43-0.50 s at load average 20), and passes under unshare -rn, with no network. ast-grep sends no telemetry.
  • The generated CLI docs reflect the new row (uv run devops docs check passes), and the gate lists at AGENTS.md:60 and docs/SELF_IMPROVEMENT.md:332 name constructs. docs(agents): instruction surfaces state only what is true, and devops ai agents never overwrites AGENTS.md #840 replaces gate counts with "every check devops ci runs"; whichever lands second rebases.

Baseline

  • Every hit left after this item's own deletions carries # ast-grep-ignore: <rule-id>[, <rule-id>…] on its own line directly above the hit, at the hit's indentation, listing every rule that hits that line.
    • The markers are generated by a one-off script from uv run ast-grep scan --json=stream src on the PR's tree, grouping rule ids by start line; ast-grep has no --add-noqa.
    • At dcafadf this is 110 rule ids on 99 lines in 42 files: the 114 / 103 / 46 above, less the four hits this item deletes (ai/review/verification.py:1118, ai/review/common_hallucinations.py:732, models/tls.py:51, config/defaults.py:189). Recount at the merge base, which holds feat(cli): extend the ruff rule set to the correctness families #420 (see TID251 below) and any burn-down item that landed first.
  • Same-line markers are not used. On a copy of the tree they left 5 hits unsuppressed on continuation lines inside parenthesised expressions (core/validation.py:80 and :93, security/reference_extractor.py:739 and :747, core/paths.py:190), raised 5 unused-suppression errors there, and made ruff format rewrite 29 files.
  • Measured on a copy with line-above markers: the scan exits 0 with both --error flags, ruff check passes, and ruff format re-wraps one generator expression (security/reference_extractor.py near :973). The scan still passes after that re-wrap. In the PR, ruff check and ruff format --check pass.
  • The only permanent marker is ai/review/defects.py:693, where HCL mutation seeding tests a line for an existing "0.0.0.0/0". The debatable hits (security/tflint.py:63, ai/agents/media.py:184, security/vault_broker.py:53) keep baseline markers until the burn-down item for their file decides them.

Ceiling

  • DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING sits in src/devops_cli/config/defaults.py next to DEFAULT_C901_SUPPRESSION_CEILING (:694), with a comment saying it only goes down, and equals the number of net- rule ids in markers at merge. A marker that lists two ids counts two.
  • A test in tests/test_architectural_invariants.py, modelled on _c901_suppressions (:717) and test_c901_suppressions_stay_under_the_ceiling (:1088), counts net- ids in ast-grep-ignore: comments under src with a regex (about 0.02 s; no tokenize). It fails when the count exceeds the ceiling, and names the files that carry markers.
  • Each later item that removes markers lowers the ceiling in the same PR. The check is count ≤ ceiling, so independent PRs merge cleanly.
  • This is the only ceiling for these markers. When test(cli): suppression comments may not grow unnoticed #849 lands, its tokenize pass counts net- rule ids in ast-grep-ignore markers as one more suppression kind against this same constant, and replaces this item's regex count, so one count backs the ceiling. No second ceiling is declared for the same markers.

Behaviour (each shown in the PR with the command and its output; all three measured with ast-grep 0.45.3)

  • Adding if "://" in url: to a module under src fails the step with error[net-scheme-in] and a message naming urllib.parse.urlsplit.
  • A marker above a line with no hit fails (error[unused-suppression]).
  • A bare # ast-grep-ignore, on a line or at the top of a file, fails (error[no-suppress-all]).

Meta-test

  • A test in tests/test_architectural_invariants.py beside _complexity_cap_escapes (:697) reads files only (it does not run the binary) and reports each of:
    • sgconfig.yml keys other than ruleDirs and testConfigs, or ruleDirs other than [.ast-grep/rules]; this also bans languageGlobs, which could map .py files to another language;
    • a second sgconfig.yml anywhere in the checkout outside the excluded repos/;
    • a rule-id set that differs from CONST_NET_CONSTRUCT_RULES;
    • a rule whose severity is not error, or that sets files or ignores;
    • a rule with no valid or no invalid test case;
    • a scan command in the constructs row of refactor(ci): github ci runs the gate through devops ci from one check table #843's check table or in .pre-commit-config.yaml that differs from CONST_AST_GREP_SCAN_ARGS, so --off, --filter, --min-severity, --globs, --no-ignore, --rule, --inline-rules, --config and the --warning/--info/--hint overrides cannot be added;
    • an ignore file that hides a source: ast-grep honours .gitignore and .ignore, so reuse _ignore_file_escapes (:645);
    • TID251 not enforced (use _ruff_enforces, :480), a banned-api entry missing from CONST_BANNED_HAND_ROLLED_APIS, or a per-file ignore that waives TID251.
  • Each escape has a case that shows it is reported, as test_every_complexity_cap_escape_is_reported (:1053) does for C901.

TID251

AGENTS.md

- **Parse With the Library; Hand-Rolled Parsing Is a Defect**:
  - Parse and classify every structured value with the standard library or a maintained package, in this order: the standard library, a package already in `uv.lock` (declared in `pyproject.toml` when first imported), a new reputable, actively maintained package. URL parts and schemes: `urllib.parse.urlsplit`. Building URLs, origins and default ports: `httpx2.URL` and `httpx2.URL(...).origin`. Addresses and networks: `ipaddress` (`is_loopback`, `is_link_local`, `is_private`, `ipv4_mapped`, `ip_network(...).with_prefixlen`). Domain names: `dns.name` (`is_subdomain`, canonical form); public-suffix questions: `tldextract`. Container-engine endpoints, Podman's or Docker's: `docker.utils.parse_host`. D-Bus addresses: `jeepney`. File locks: `filelock`. Version specifiers: `packaging`. Trace context: the OpenTelemetry propagator. SSH host keys: OpenSSH, through `~/.ssh/known_hosts`.
  - A **hand-rolled** construct re-implements one of these with strings: an affix or substring test on a scheme, host, IP prefix or domain suffix; a literal list of addresses, loopback names, schemes or domain suffixes; a split on `:`, `@` or `/` of a host or URL; `strip("[]")` or `lower().rstrip(".")` canonicalisation; an f-string URL authority or CIDR; a default-port table; a regex over one of these formats.
  - Whenever a task, issue, review finding or fix touches a hand-rolled construct, the change deletes it and calls the library at that site, even when the issue's acceptance criteria or proposed answer spell out the hand-rolled form (say so in the PR). One more edge case handled inside it (a prefix, an `rstrip`, a regex branch), or a move into `config/constants.py`, keeps the defect.
  - Literal matching stays right for closed sets this project defines itself (its command names, enum values, config keys); where such a table lives is set by the Matching Table Placement bullet, not by this one.
  - Data a library cannot know is a constant with its source cited: a cloud's published metadata addresses as `ipaddress` objects; a vendor's published SSH host keys as its published known_hosts lines, written to `~/.ssh/known_hosts` for OpenSSH to check.
  - Enforced by the `net-*` ast-grep rules (`.ast-grep/rules/`) and ruff `TID251` in `uv run devops ci`, GitHub CI and pre-commit. Sites older than the rules carry `# ast-grep-ignore: <rule-id>` on the line above; a test caps their number, and `unused-suppression` flags a marker once its site is fixed. New code carries no marker; a false positive becomes a rule test case and a rule fix.
  - Review: a new hand-rolled construct is a major finding: HIGH where it decides egress, SSRF, a credential's destination, authentication or host trust; MEDIUM elsewhere.

Template and LLM path

  • The template (src/devops_cli/ai/instruction_generator.py) replaces :301-303 with the new bullet, turns :304's sentence, wording kept, into its own bullet headed "Matching Table Placement" (as in AGENTS.md), deletes :305-308, and drops the "Avoid custom workarounds" sentence at :266.
  • The template serves any repository (devops ai agents --template and devcontainer scaffolding), so the bullet's repository-specific parts sit behind meta.is_devops_cli, as alpha_lifecycle_block (:195-203) does. Those parts are: the library list beyond urllib.parse and ipaddress, the uv.lock and pyproject.toml wording, the name config/constants.py, and the enforcement sub-bullet. With meta.is_devops_cli the template yields the AGENTS.md bullet exactly; for any other repository it yields:
- **Parse With the Library; Hand-Rolled Parsing Is a Defect**:
  - Parse and classify every structured value with the standard library or a maintained package, in this order: the standard library, a package the project already depends on, a new reputable, actively maintained package. For example, URL parts and schemes: `urllib.parse.urlsplit`; addresses and networks: `ipaddress`.
  - A **hand-rolled** construct re-implements one of these with strings: an affix or substring test on a scheme, host, IP prefix or domain suffix; a literal list of addresses, loopback names, schemes or domain suffixes; a split on `:`, `@` or `/` of a host or URL; `strip("[]")` or `lower().rstrip(".")` canonicalisation; an f-string URL authority or CIDR; a default-port table; a regex over one of these formats.
  - Whenever a task, issue, review finding or fix touches a hand-rolled construct, the change deletes it and calls the library at that site, even when the issue's acceptance criteria or proposed answer spell out the hand-rolled form (say so in the PR). One more edge case handled inside it (a prefix, an `rstrip`, a regex branch), or a move into a constants module, keeps the defect.
  - Literal matching stays right for closed sets the project defines itself (its command names, enum values, config keys); where such a table lives is set by the Matching Table Placement bullet, not by this one.
  - Data a library cannot know is a constant with its source cited: a cloud's published metadata addresses as parsed address objects; a vendor's published SSH host keys as its published known_hosts lines, written to `~/.ssh/known_hosts` for OpenSSH to check.
  - Review: a new hand-rolled construct is a major finding: HIGH where it decides egress, SSRF, a credential's destination, authentication or host trust; MEDIUM elsewhere.
  • A test renders the template with meta.is_devops_cli false and checks that this bullet names none of config/constants.py, uv.lock, httpx2, docker.utils, jeepney or ast-grep.
  • src/devops_cli/ai/tasks/generate_agents.md Step 3 (:10-14) gains: "Define library-first parsing: URLs, hosts, IP addresses, domains, versions and paths are parsed by the standard library or a maintained dependency; a hand-rolled string or regex parser is a defect, and its fix deletes it."
  • src/devops_cli/ai/knowledge_base/devops_cli/architecture.md:29 drops ipaddress and urllib.parse from "Maximize standard library leverage" and adds: "Structured values (URLs, hosts, IP addresses, domains, versions) are parsed by the standard library or a maintained dependency; hand-rolled string or regex parsing is a defect."

Review (the review's deterministic layer only; see the key question on the prompt freeze)

  • _check_localhost_default_url_hallucination and _check_posix_signal_zero_liveness_hallucination are removed from early_checks (verification.py:1543-1544) and deleted. The LOCALHOST/LOOPBACK branch of _verify_general_ground_truth (ai/review/common_hallucinations.py:731-732) goes with them, because it is another substring test on the finding's prose. tests/test_common_hallucinations_hardening.py:272-317 keeps its pre-1.0 and compliment cases and drops the other two, with their imports (:18-19).
  • The catalogue entries HALLUCINATION-LOCALHOST-DEFAULT-CONFIG (ai/review/common_hallucinations.json:755) and HALLUCINATION-POSIX-SIGNAL-ZERO-LIVENESS (:778), which record the stances of the two deleted checks, are deleted. Neither dismisses the fixtures below through _check_catalog_hallucination (verification.py:1490) today: the first one's category check confirms only resource-exhaustion claims, and the second one's wants syntax words. Left in place, each would be an orphan that still states its stance.
  • Two regression tests build synthetic findings. The deleted checks read only a finding's title and description, so a fixture need not describe a defect at its cited line:
    • HIGH at src/devops_cli/config/settings.py:10, the location the existing test uses, title "Loopback guard compares host strings and misses 127.0.0.2", description "The SSRF egress check for a configured URL compares the host with the strings localhost and 127.0.0.1, so http://127.0.0.2/ and LOCALHOST. are not treated as loopback." The wording is the point: the real loopback check, _is_loopback_host (core/validation.py:328-336), already parses the host with ipaddress and treats both spellings as loopback.
    • MEDIUM at src/devops_cli/k8s/port_forward_daemon.py:67-68, the os.kill(pid, 0) fallback that is_alive (:55-71) uses where /proc cannot be read (elsewhere it compares the recorded /proc start time), title "A reused pid is signalled as a live port-forward", description "Where /proc cannot be read, the liveness test falls back to os.kill(pid, 0) on a pid read from a state file; after the forward exits the pid can be reused, so another process is reported as the live port-forward."
    • For each fixture, the test asserts that _check_early_hallucinations(finding, ()) returns None and that _deterministic_pre_verification(finding, repo_root=tmp_path, dependencies=(), consult_judged=False) (verification.py:1641) leaves its status UNVERIFIED. That function runs only the deterministic checks, with no model call and no network; the tests do not go through the model-backed verification path.
    • Measured offline at dcafadf: both fixtures come back INVALIDATED today (deterministic:localhost_default_config and deterministic:posix_signal_zero_liveness); with the two checks stubbed out, both stay UNVERIFIED.
  • A third test sends both fixtures through _check_catalog_hallucination, the loopback one located under config/, ai/ and core/ in turn, and asserts that none comes back INVALIDATED. Run offline at dcafadf, none does, so this test holds the line rather than fixing a failure.
  • verify_finding_system.md:33 keeps "os.kill(pid, 0) tests that a process exists without signalling it" and drops "it is not a race or a security flaw" (see the key question). The ("os.kill(pid, 0)", _VERIFIER) entry of _NON_DEFECTS (tests/test_review_prompt_consistency.py:100) goes with it, because the verification prompt no longer calls os.kill(pid, 0) a non-defect; the rest of that file stays green.
  • .devops/review.md "House rules" (:51-71) gains: "Hand-rolled network parsing: a changed line that hits a net-* ast-grep rule or a TID251 banned API, or adds an ast-grep-ignore / noqa: TID251 marker, is a finding: HIGH on an egress, SSRF, credential-destination, authentication or host-trust path, MEDIUM elsewhere. Its fix deletes the construct and calls the library AGENTS.md names."
  • No persona, review-task or verification prompt gains a sentence.

TLS defaults

  • DEFAULT_HOMELAB_IPS (config/defaults.py:189) and the sans default of CertGenerationRequest (models/tls.py:51) hold ipaddress objects for their addresses. Their consumers (crypto/tls_certificates.py:62-77 and :326, commands/tls.py:286) take the objects, and JSON output stays strings. This removes the 2 false positives without markers.

Release

Key questions

  • Is a new dev dependency acceptable? (owner decision) Proposed: yes, ast-grep-cli==0.45.3.
    • It is MIT-licensed, has about 16.1k GitHub stars, and ships wheels for Linux, macOS and Windows. It had six releases from 0.44.0 (2026-06-22) to 0.45.3 (2026-08-31) and none since; its main branch had commits as late as 2026-10-03.
    • It is a reputable, maintained tool, which is what the owner's 2026-10-03 rule asks fixes to use in place of hand-rolled parsers; it is still a new dependency in every CI run, so the owner confirms it.
    • Its tree-sitter parser handles the 86 files that use PEP 758 except A, B:.
    • Its built-in unused-suppression and no-suppress-all checks fill the roles RUF100 and PGH004 fill for ruff, and ast-grep test gives each rule unit tests.
    • Rejected: a stdlib ast test, at 2.2-2.4 s per run plus about 250 lines of home-grown detector, suppression syntax and stale-marker logic, which is the maintenance this policy removes. Also rejected: Semgrep 1.178, at 14-16 s per run, which failed to parse 30 files (PEP 758 except A, B: and PEP 696 type-parameter defaults).
  • Enforce first, or after the cleanup? Proposed: first, as feat(cli): enforce the complexity cap with ruff C901 and an inline baseline that only shrinks #586 did.
  • What about the 10 use sites the rules cannot see? Proposed: accept the gap; add no net-legacy-list rule.
  • Ban fcntl.flock and fcntl.lockf too? Proposed: not here. The 7 uses in 5 modules are not networking, and they go with the deferred filelock item (filelock 3.32.6 is already locked). So this item needs no noqa: TID251 baseline or ceiling.
  • Should the rules also run on repositories the review tool reviews? Proposed: not in this item. The evidence-first review can later run the same pack over a reviewed commit's changed files, offline, in about 0.25 s per 500 files. Hits on changed lines would become findings banded by the house rule, and hits on unchanged lines context for the personas.
  • How does this coexist with docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016, which rewrites the heading and placement sentence at AGENTS.md:21-24 and template :301-304? Proposed: this item replaces :21-23 and template :301-303, and leaves the placement sentence (:24, template :304) as its own bullet. docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016 then rewrites only that bullet, and whichever lands second rebases. The new bullet defers placement to that bullet, and says a move into config/constants.py does not fix a hand-rolled construct.
  • Does the "POSIX signal 0" line at verify_finding_system.md:33, which tells the verification model that os.kill(pid, 0) "is not a race", stay as written? Proposed: no. Left as is, it still refutes a fix(cli): argo ignores the namespace, and workspace, devcontainer, port-forward, tls, drift-report and label state handling #961-shaped finding after the deterministic check is gone. Keep the true half ("tests that a process exists without signalling it") and drop "it is not a race or a security flaw", so a finding that the pid may name another process is judged on where the pid comes from.
  • Do review prompt additions fall under the persona and verification-prompt freeze? Decided (owner, 2026-10-03): yes. Deterministic tools originate findings and the language model correlates and plans; persona and verification-prompt additions are frozen after the v0.2.25 cut and wait for the evidence-first redesign. This item lands after that cut and adds none.
    • Here the net-* rules and TID251 originate the findings, the house rule bands them, and the deletions above stop the review from discarding them. None of that needs a model to look for hand-rolled parsing.
    • Left to the evidence-first redesign as input: prompt lines that would tell the personas or the verification model to flag hand-rolled parsing themselves, and the Fix field. ai/tasks/review.md:42 defines a fix as "replacement code for the cited lines", so when the cited line is the construct, the fix adds one more case to it. A fix that deletes the construct and calls the library belongs in the redesign's planning step.
    • Proposed: the verify_finding_system.md:33 edit stays in this item, because it only deletes a refutation, the prompt form of the deleted check, and adds no instruction.

Strategic alignment

Update 2026-10-08: refinement

#420, #843, #840, #897 and #898 landed, so drop 'after #420 and before #897'; this lands first in its release and adds the constructs row itself. Recount the 114/103/46 counts. AGENTS.md lines are now :19-24 and :432-438. If #1150 lands first, the Review section keeps only the .devops/review.md house rule.

Proposed design

Problem statement

The codebase contains 114 hand-rolled URL, address, and host-parsing constructs across 46 files that should use standard-library or locked-dependency parsers. AGENTS.md both mandates and contradicts the library rule, no gate enforces it, fix PRs keep adding new copies (10 in two weeks), and the review system's deterministic checks dismiss exactly the findings that would flag these constructs.

Acceptance criteria

  • Criterion 1: Twelve ast-grep rules exist in .ast-grep/rules/ with language: python, severity: error, and a message naming the replacement library; the 12 rule ids match CONST_NET_CONSTRUCT_RULES.
    Verification: ls .ast-grep/rules/ shows exactly 12 .yml files; grep -l 'severity: error' .ast-grep/rules/*.yml lists all 12; each message field names at least one of urlsplit, ipaddress, httpx2.URL, docker.utils.parse_host, jeepney, dns.name, tldextract.
  • Criterion 2: Each rule has at least one valid and one invalid case in .ast-grep/rule-tests/-test.yml, and ast-grep test passes.
    Verification: uv run ast-grep test --skip-snapshot-tests exits 0 with 12 passed.
  • Criterion 3: The root sgconfig.yml holds only ruleDirs: [.ast-grep/rules] and testConfigs: [{testDir: .ast-grep/rule-tests}].
    Verification: cat sgconfig.yml shows exactly those two keys and no others; no second sgconfig.yml exists outside repos/.
  • Criterion 4: ast-grep-cli==0.45.3 is in the dev dependency group of pyproject.toml.
    Verification: grep 'ast-grep-cli' pyproject.toml shows the pinned version in the dev group; uv sync installs it.
  • Criterion 5: Three new constants (CONST_NET_CONSTRUCT_RULES, CONST_AST_GREP_SCAN_ARGS, CONST_BANNED_HAND_ROLLED_APIS) exist in src/devops_cli/config/constants.py.
    Verification: grep -n 'CONST_NET_CONSTRUCT_RULES|CONST_AST_GREP_SCAN_ARGS|CONST_BANNED_HAND_ROLLED_APIS' src/devops_cli/config/constants.py shows all three.
  • Criterion 6: The constructs row in the CI check table runs uv run ast-grep scan --error=unused-suppression --error=no-suppress-all src and uv run ast-grep test --skip-snapshot-tests; the same two commands run as pre-commit hooks with language: system and pass_filenames: false.
    Verification: grep -A5 'constructs' in the CI check table shows both commands; grep -A5 'ast-grep' .pre-commit-config.yaml shows both hooks with the required settings.
  • Criterion 7: Every remaining hit after this item's own deletions carries # ast-grep-ignore: on the line directly above, at the hit's indentation; the scan exits 0 with both --error flags.
    Verification: uv run ast-grep scan --error=unused-suppression --error=no-suppress-all src exits 0; grep -r 'ast-grep-ignore' src/ shows markers only on lines above hits.
  • Criterion 8: DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING in config/defaults.py equals the count of net- rule ids in markers at merge, and a test in tests/test_architectural_invariants.py fails when the count exceeds it.
    Verification: grep 'DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING' src/devops_cli/config/defaults.py shows the value; uv run pytest tests/test_architectural_invariants.py -k 'net_construct' passes.
  • Criterion 9: A meta-test in tests/test_architectural_invariants.py reports each escape: sgconfig keys, second sgconfig, rule-id mismatch, non-error severity, missing test cases, scan-command drift, ignore-file escapes, and TID251 not enforced.
    Verification: uv run pytest tests/test_architectural_invariants.py -k 'net_construct_escape' passes; each escape case has a test that shows it is reported.
  • Criterion 10: TID251 is in [tool.ruff.lint] select and [tool.ruff.lint.flake8-tidy-imports.banned-api] bans socket.inet_aton, inet_ntoa, inet_pton, inet_ntop; flake8-tidy-imports is in CONST_RUFF_LINT_KEYS.
    Verification: grep 'TID251' pyproject.toml shows the select entry; grep 'inet_aton|inet_ntoa|inet_pton|inet_ntop' pyproject.toml shows the banned-api entries; grep 'flake8-tidy-imports' src/devops_cli/config/constants.py shows it in the allowlist; uv run ruff check --select TID251 src/ reports 0 violations.
  • Criterion 11: AGENTS.md lines :19-24 are replaced with the new 'Parse With the Library' bullet and the 'Matching Table Placement' bullet; :432-438 (Standard Parsers heading) is deleted; the 'Avoid custom workarounds' sentence is removed; ipaddress and urllib.parse are dropped from the standard-library-leverage line.
    Verification: git diff AGENTS.md shows only the listed changes; grep 'Parse With the Library' AGENTS.md finds the new bullet; grep 'Avoid custom workarounds' AGENTS.md returns nothing.
  • Criterion 12: The template in instruction_generator.py replaces the brittle-pattern block with the new bullet behind meta.is_devops_cli; a test renders with is_devops_cli false and asserts no repository-specific names appear.
    Verification: uv run pytest tests/ -k 'template_non_devops_cli' passes; the rendered output names none of config/constants.py, uv.lock, httpx2, docker.utils, jeepney, or ast-grep.
  • Criterion 13: generate_agents.md Step 3 gains the library-first parsing sentence; architecture.md:29 drops ipaddress/urllib.parse and adds the hand-rolled-is-a-defect sentence.
    Verification: grep 'hand-rolled' src/devops_cli/ai/tasks/generate_agents.md finds the new sentence; grep 'hand-rolled' src/devops_cli/ai/knowledge_base/devops_cli/architecture.md finds the new sentence.
  • Criterion 14: _check_localhost_default_url_hallucination and _check_posix_signal_zero_liveness_hallucination are removed from early_checks and deleted; the LOCALHOST/LOOPBACK branch in common_hallucinations.py is removed; the two catalogue entries are deleted; regression tests confirm both synthetic fixtures stay UNVERIFIED.
    Verification: grep -n 'localhost_default_url_hallucination|posix_signal_zero_liveness' src/devops_cli/ai/review/verification.py returns nothing; uv run pytest tests/test_common_hallucinations_hardening.py -k 'loopback_guard|reused_pid' passes with both fixtures UNVERIFIED.
  • Criterion 15: .devops/review.md gains the hand-rolled network parsing house rule; verify_finding_system.md:33 keeps the true half and drops 'it is not a race or a security flaw'; the _NON_DEFECTS entry for os.kill(pid, 0) is removed.
    Verification: grep 'Hand-rolled network parsing' .devops/review.md finds the house rule; grep 'not a race' src/devops_cli/ai/tasks/verify_finding_system.md returns nothing; grep 'os.kill' tests/test_review_prompt_consistency.py returns nothing.
  • Criterion 16: DEFAULT_HOMELAB_IPS and the sans default of CertGenerationRequest hold ipaddress objects; their consumers accept the objects and JSON output stays strings.
    Verification: grep 'ipaddress' src/devops_cli/config/defaults.py shows ipaddress objects in DEFAULT_HOMELAB_IPS; uv run pytest tests/ -k 'tls_cert' passes.
  • Criterion 17: A changelog.d fragment records the new gate; uv run devops ci passes.
    Verification: ls changelog.d/ shows the fragment for this issue; uv run devops ci exits 0.

Key questions

  • Is a new dev dependency acceptable?: Yes. ast-grep-cli==0.45.3 is MIT-licensed, has about 16.1k GitHub stars, ships wheels for Linux/macOS/Windows, had six releases from 0.44.0 to 0.45.3 with main-branch commits as late as 2026-10-03, handles PEP 758 except syntax, and its built-in unused-suppression and no-suppress-all checks fill the roles RUF100 and PGH004 fill for ruff. [sources: pyproject.toml:64-77]
  • Enforce first, or after the cleanup?: Enforce first, as feat(cli): enforce the complexity cap with ruff C901 and an inline baseline that only shrinks #586 did. Ten fix PRs added constructs in two weeks, and every burn-down item is itself a fix PR at the same risk. Markers give each burn-down item a checkable finish line. The review must stop dismissing these findings before it reviews the burn-down PRs. The PR lands right after a release starts, as that release's first item PR. (proposed) [sources: AGENTS.md:19-24]
  • What about the 10 use sites the rules cannot see (imported from config/constants.py)?: Accept the gap; add no net-legacy-list rule. ast-grep cannot follow names imported from config/constants.py. The burn-down items delete the six lists. An interim identifier rule over those names would add 35 hits. (proposed) [sources: src/devops_cli/config/constants.py:2296-2299, src/devops_cli/config/constants.py:2505]
  • Ban fcntl.flock and fcntl.lockf too?: Not here. The 7 uses in 5 modules are not networking, and they go with the deferred filelock item (filelock 3.32.6 is already locked). This item needs no noqa: TID251 baseline or ceiling for them. (proposed) [sources: pyproject.toml]
  • Should the rules also run on repositories the review tool reviews?: Not in this item. The evidence-first review can later run the same pack over a reviewed commit's changed files, offline, in about 0.25 s per 500 files. Hits on changed lines would become findings banded by the house rule. (proposed) [sources: docs/adr/0005-review-findings-come-from-tools-not-models.md]
  • How does this coexist with docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016, which rewrites the heading and placement sentence at AGENTS.md:21-24 and template :301-304?: This item replaces :21-23 (now :19-21) and template :301-303, and leaves the placement sentence (:24, template :304) as its own bullet headed 'Matching Table Placement'. docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016 then rewrites only that bullet, and whichever lands second rebases. The new bullet defers placement to that bullet and says a move into config/constants.py does not fix a hand-rolled construct. (proposed) [sources: AGENTS.md:19-24, src/devops_cli/ai/instruction_generator.py:264-266]
  • Does the 'POSIX signal 0' line at verify_finding_system.md:33 stay as written?: No. Keep the true half ('tests that a process exists without signalling it') and drop 'it is not a race or a security flaw', so a finding that the pid may name another process is judged on where the pid comes from. The edit stays in this item because it only deletes a refutation, the prompt form of the deleted check, and adds no instruction. (proposed) [sources: docs/adr/0005-review-findings-come-from-tools-not-models.md]
  • Do review prompt additions fall under the persona and verification-prompt freeze?: Yes. Decided by the owner on 2026-10-03: persona and verification-prompt additions are frozen after the v0.2.25 cut and wait for the evidence-first redesign. This item lands after that cut and adds no prompt rule. The net-* rules and TID251 originate the findings, the house rule bands them, and the deletions stop the review from discarding them. None of that needs a model to look for hand-rolled parsing. (proposed) [sources: docs/adr/0005-review-findings-come-from-tools-not-models.md]

Open questions

Fit

Needs splitting into 5 items:

  1. Core gate: 12 ast-grep rules, 12 test files, sgconfig.yml, ast-grep-cli dependency, CI constructs row, pre-commit hooks, baseline markers in 42+ files, ceiling constant and test, meta-test
  2. TID251: ruff select and banned-api config for socket.inet_*, CONST_RUFF_LINT_KEYS update
  3. Documentation: AGENTS.md edits, instruction_generator.py template edits, generate_agents.md Step 3, architecture.md edit, non-devops-cli template test
  4. Review changes: remove 2 deterministic checks, delete 2 catalogue entries, regression tests, .devops/review.md house rule, verify_finding_system.md edit, test_review_prompt_consistency.py and test_common_hallucinations_hardening.py edits
  5. TLS defaults: ipaddress objects in config/defaults.py and models/tls.py, consumer updates

Suspected block

None.

Dependencies

None.

Activity

  1. added
    type/feature
    scope/review
    priority/p1-high
    scope/ci
    on Oct 3, 2026
  2. dan-petty-bot commented on Oct 10, 2026

    @dan-petty-bot
    Collaborator

    Proposal needs splitting into 5 items at 69c99cf (see proposed design in issue body).

  3. modified the milestone: v0.2.36 on Oct 11, 2026
  4. dan-petty commented on Oct 14, 2026

    @dan-petty
    OwnerAuthor

    Moved to the backlog: it was New, not Ready, when v0.2.36 started. (devops roadmap reprioritize)

  5. added this to the v0.2.37 milestone on Oct 17, 2026
  6. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Readiness check for v0.2.37, against release/v0.2.36 at 22d8748. Line numbers are at that commit.

    Status: partly done. Split into three.

    Not built: the gate. None of these exist:

    • .ast-grep/ and sgconfig.yml;
    • an ast-grep pin (pyproject.toml:78-97);
    • TID251 in Ruff's select (:113-116);
    • a constructs row in devops ci (src/devops_cli/commands/ci.py:435-548).

    The only check is tests/test_url_credential_masking.py:391, a grep over two files.

    Fewer constructs remain than the body counts:

    • one default-port table (src/devops_cli/core/validation.py:439), down from 5;
    • no strip("[]") calls;
    • about three f-string URL authorities, down from 13.

    The body's counts of 114, 103 and 46 need a recount.

    Done by #1150: verification.py, common_hallucinations.{py,json}, verify_finding_system.md, the hardening test and the os.kill _NON_DEFECTS entry are deleted. The Review section therefore shrinks to the .devops/review.md house rule (:57-78).

    Done by #849: DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING = 0 (src/devops_cli/config/defaults.py:703, :718), counted by tokenize (tests/test_architectural_invariants.py:1547-1590).

    References that moved

    Dependencies: closed: #420, #843, #840, #897, #898, #1150 and #849. Open: #1016, which edits the same bullet (AGENTS.md :20, template :315), and the children #887, #1110 and #1113, which don't block this issue.

    Questions for the owner

    Proposed split

    • (a, L) The gate, TID251, the markers, the ceiling value and the meta-test. This lands first.
    • (b, S) The AGENTS.md, template and knowledge-base text; the house rule; and a test that renders the template for another repository.
    • (c, S) TLS defaults as ipaddress objects.
  7. removed this from the v0.2.37 milestone on Oct 17, 2026
  8. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Moved to the backlog: it was New, not Ready, when v0.2.37 started. (devops roadmap reprioritize)

  9. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Ready: implementation plan (refined 2026-10-17 at 3dd7fa6)

    This section supersedes any text below that conflicts with it.

    Decisions

    • Does the gate need ast-grep, or do Ruff TID251 and Semgrep cover it? It needs ast-grep. ast-grep-cli==0.51.0 (MIT; 0.50.0 shipped 2026-10-09 and 0.51.0 on 2026-10-15) goes in the dev dependency group, as actionlint-py and zizmor are. TID251 is added as well, for the banned socket.inet_* APIs. Measured at 3dd7fa6:

      • Ruff has no custom-pattern rules, and TID251 only bans named APIs, so neither can express "://" in url or startswith("169.254.").
      • Semgrep 1.179.0 (pinned in src/devops_cli/tools_lock/tools.lock:381) took 14.3-15.6 s to run one rule over src. It skipped src/devops_cli/ai/review_schema.py entirely, at the PEP 695 bound on :286, and parsed three files only partly: ai/agents/agent.py:177, ai/analyze/scanner.py:377 (a three-name PEP 758 except) and ai/response_repair.py:523.
      • Semgrep lives outside the project environment, installed by devops install-tools, and feat(review): devops-cli's rule pack turns the recall set's network-exposure entries into tested Semgrep rules, and CI runs the pack's tests when a rule changes #1145 deliberately kept it out of the local gate (.github/workflows/ci.yml:371-372).
      • The review rule pack (src/devops_cli/review/rules_pack.py) is for reviewed repositories, and its validator requires MIT and CWE metadata on every rule (:80-92). Project lint rules do not belong there.
      • ast-grep 0.51.0 ran all 12 rules over src in 0.32-0.41 s, including uvx start-up, and all 12 rule tests passed. Its only parse errors are the two PEP 696 type-parameter defaults (ai/response_repair.py:523, ai/agents/agent.py:177), and they cover just T = and = Any. It skips no file.
      • So the gate cannot be built on the tools already pinned without holes and a 15-second step. That is the reason for the new dependency.
    • The suppression ceiling: DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING stays at 0 (src/devops_cli/config/defaults.py:703), and noqa: TID251 keeps the 0 every unlisted noqa code has (:704-706). There is no baseline of markers. A rule ships only in the PR that leaves src with no hit for it. The body's "markers above every hit, ceiling equal to their count, lowered by each burn-down" plan is dropped. Raising the ceiling would be a relaxation.

    • Enforce first, or clean up first? Clean up first, one rule group at a time. Each rule enters .ast-grep/rules/ and CONST_NET_CONSTRUCT_RULES in the PR that deletes its last hit, so the gate never carries a marker and never has a known hole for a shipped rule. This follows from the ceiling of 0.

    • Counts: the body's 114, 103 and 46 are replaced. At 3dd7fa6 the 12 rules report 52 rule hits on 46 lines in 31 files (55 raw matches). Each PR records the count at its own merge base in its PR body, and no doc or test hard-codes a count. Many constructs were deleted by the children that have landed.

    • A false positive in net-ip-literal: "0.0.0.0/0" in line at security/tflint.py:63, and the same shape at ai/review/defects.py:693, search HCL text for a literal and do not classify a host. The rule is refined so that a membership test with the literal on the left counts only when the right-hand name looks like a host or URL. "127.0.0.1" in url is still caught. Checked with 0.51.0: the refined rule passes its tests and leaves only security/sanitizer.py:393 in src. The not clause added to the body's rule is:

      not:
        all:
          - regex: '^["''][0-9a-fA-F.:/]+["'']\s+(not\s+)?in\s'
          - not:
              regex: '\sin\s+[\w.()\[\]]*(?i:host|url|addr|netloc|endpoint|server|target|ip)'

      Its tests add matches = "0.0.0.0/0" in line and if not match or "0.0.0.0/0" in match.group(3): pass as valid, and local = "127.0.0.1" in url and local = "::1" not in parsed.netloc as invalid. The body's rule says "a false positive becomes a rule test case and a rule fix". The HCL brace-counting in tflint.py is a different hand-rolled parser and is not this rule's business.

    • The other 11 rules: kept exactly as written in the body. Each passes ast-grep test with 0.51.0.

    • The constructs row: one CheckSpec in get_check_specs() (src/devops_cli/commands/ci.py:435-547) running ["uv", "run", "ast-grep", *CONST_AST_GREP_SCAN_ARGS], where CONST_AST_GREP_SCAN_ARGS is ("scan", "--error=unused-suppression", "--error=no-suppress-all", "src"). GitHub CI already runs the table through devops ci (refactor(ci): github ci runs the gate through devops ci from one check table #843). The rule unit tests run in pytest, through a test that calls ast-grep test --skip-snapshot-tests (about 30 ms, offline), and as a pre-commit hook. CheckSpec holds one command (:146-156). With no marker allowed, the two --error flags back up test(cli): suppression comments may not grow unnoticed #849's count: a stray marker fails the scan too.

    • Pre-commit: two language: system, pass_filenames: false hooks in the repo: local block (.pre-commit-config.yaml:45) call uv run ast-grep scan ... and uv run ast-grep test --skip-snapshot-tests directly, because importing devops_cli costs seconds (the block's comment, :47-53).

    • TID251: select (pyproject.toml:113-116) names TID251, and [tool.ruff.lint.flake8-tidy-imports.banned-api] bans socket.inet_aton, socket.inet_ntoa, socket.inet_pton and socket.inet_ntop, each with "Parse and format addresses with ipaddress.ip_address." flake8-tidy-imports joins CONST_RUFF_LINT_KEYS (src/devops_cli/config/constants.py:3235-3245). There are 0 uses at 3dd7fa6.

    • The meta-test, beside _complexity_cap_escapes (tests/test_architectural_invariants.py:969), reads files only and reports each of the following, with one case per escape, as test_every_complexity_cap_escape_is_reported (:1325) does:

      • sgconfig.yml keys other than ruleDirs and testConfigs, or ruleDirs other than [.ast-grep/rules];
      • a second sgconfig.yml outside repos/;
      • a rule-id set different from CONST_NET_CONSTRUCT_RULES;
      • a rule that is not severity: error, or that sets files or ignores;
      • a rule with no valid case or no invalid case;
      • a scan command in the constructs row or in pre-commit that differs from CONST_AST_GREP_SCAN_ARGS;
      • an ignore file that hides a source (reuse _ignore_file_escapes, :917);
      • TID251 not enforced (reuse _ruff_enforces, :731), a banned API missing from CONST_BANNED_HAND_ROLLED_APIS, or a per-file ignore that waives TID251.
    • Use sites the rules cannot see (names imported from config/constants.py): accept the gap and add no net-legacy-list rule. Most of those lists are gone, and fix(security): local names come from the public suffix list, and domains match on DNS labels, not string suffixes #887 deletes CONST_LOCAL_DOMAIN_SUFFIXES.

    • fcntl.flock/lockf: not banned here. Locking is not network parsing.

    • Running the rules on repositories the review tool reviews: not in this item. That is the Semgrep rule pack's job, if it is ever wanted.

    • D-Bus addresses (commands/devcontainer.py:1286-1288): read with jeepney.bus.get_connectable_addresses. jeepney 0.9.0 is already in uv.lock (:1526), installed on Linux through keyring, and is declared in pyproject.toml with the sys_platform == 'linux' marker when first imported, so deptry stays green. The body names jeepney, and its parser handles escapes and multiple addresses, which the hand-rolled removeprefix does not.

    • Valkey endpoint parsing (valkey/client.py:46-61, config/settings.py:213-250, commands/ai_runs.py:159): rewritten here with urllib.parse.urlsplit and httpx2.URL. fix(valkey): one validated URL names every Valkey endpoint, valkey-py dials an address that one check vetted, and the unused cache layer goes #1113 keeps its own scope, the GLIDE client swap and deleting the RESP stack, and starts from library-parsed endpoints. fix(valkey): one validated URL names every Valkey endpoint, valkey-py dials an address that one check vetted, and the unused cache layer goes #1113 is in the backlog, and waiting for it would hold four rules off indefinitely.

    • TLS defaults: DEFAULT_HOMELAB_IPS (src/devops_cli/config/defaults.py:181) and the sans default of CertGenerationRequest (src/devops_cli/models/tls.py:51) hold ipaddress objects for their addresses. Their consumers (src/devops_cli/crypto/tls_certificates.py:62-77, :325-326, src/devops_cli/commands/tls.py:298) take the objects, and JSON output stays strings. This lands with net-address-list, which cannot ship otherwise.

    • Instruction surfaces: the body's AGENTS.md and template bullets are kept, with one change. The enforcement sub-bullet now reads: "Enforced by the net-* ast-grep rules (.ast-grep/rules/) and Ruff TID251 in uv run devops ci and pre-commit. No site may carry an ast-grep-ignore or noqa: TID251 marker, because their suppression ceiling is 0. A rule ships only once src has no hit for it, and a false positive becomes a rule test case and a rule fix." The Review section shrinks to the .devops/review.md house rule, because refactor(review): the model verifier, the hallucination catalog and the model-claim guards are deleted, and person-recorded verdicts become suppressions #1150 deleted verification.py, the hallucination catalogue, verify_finding_system.md and their tests. The body's verification-prompt and hallucination-check items are therefore void.

    • docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016 coexistence: PR 2 replaces AGENTS.md:17-19 and template :312-314. It leaves the placement sentence (AGENTS.md:20, template :315) as its own bullet, headed "Matching Table Placement", for docs(agents): a matching table lives beside its one owner, and moves to config/ only when a second package imports it #1016 to rewrite. Whichever lands second rebases.

    • Children: feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107 is not a pure tracking parent, because it has its own gate. It closes with its last PR. fix(ai): replies carry their server as an httpx2 origin, so a password in an AI URL stays out of output, the spend ledger, metrics, spans and cache #1110 and fix(valkey): one validated URL names every Valkey endpoint, valkey-py dials an address that one check vetted, and the unused cache layer goes #1113 stay open as independent items, and no rule waits on them.

    Delivery

    1. PR 1 (M): the gate, with TID251, the meta-test and the first three rules: net-cidr-build (no hit), net-port-table (core/validation.py:439 becomes httpx2.URL(url).origin.port) and the refined net-ip-literal (security/sanitizer.py:393 becomes is_loopback_host). It also creates docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md and changelog.d/1107.md, and later PRs extend both. Refs feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107. Tests first:

      • the meta-test's escape cases;
      • a pytest wrapper running ast-grep test --skip-snapshot-tests;
      • _enforce_non_private_ssrf (core/validation.py:414) resolving with port 443 for https://example.com and 80 for http://example.com (_resolve_host_ips patched);
      • sanitize_telemetry_endpoint (security/sanitizer.py:383) keeping the hosts localhost, 127.0.0.2 and [::1], as it does today;
      • the constructs row's command;
      • with a scratch module under tmp_path, port = 443 if tls else 80 failing the scan with error[net-port-table].

      Files: pyproject.toml, uv.lock, sgconfig.yml, .ast-grep/rules/*.yml, .ast-grep/rule-tests/*-test.yml, .pre-commit-config.yaml, src/devops_cli/config/constants.py, src/devops_cli/commands/ci.py, src/devops_cli/lang/en/messages.py, src/devops_cli/core/validation.py, src/devops_cli/security/sanitizer.py, generated CLI docs, tests/test_architectural_invariants.py, tests/test_net_construct_rules.py (new), tests/test_validation.py, tests/test_consolidation_security_sanitizer.py, docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md, changelog.d/1107.md.

    2. PR 2 (S): the instruction surfaces, as the body specifies them with the enforcement sub-bullet above. They are AGENTS.md (:16, :17-20, :21, :185); the template in src/devops_cli/ai/instruction_generator.py (:277, :312-319, behind meta.is_devops_cli); src/devops_cli/ai/tasks/generate_agents.md Step 3 (:11-15); src/devops_cli/ai/knowledge_base/devops_cli/architecture.md:29; and the .devops/review.md house rule (after :77). AGENTS.md is edited by hand. Refs feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107. Tests first: render the template with is_devops_cli=False and assert that the bullet names none of config/constants.py, uv.lock, httpx2, docker.utils, jeepney or ast-grep; render it with is_devops_cli=True and assert that it equals the AGENTS.md bullet. Files: AGENTS.md, src/devops_cli/ai/instruction_generator.py, src/devops_cli/ai/tasks/generate_agents.md, src/devops_cli/ai/knowledge_base/devops_cli/architecture.md, .devops/review.md, tests/test_instruction_generator.py, the task file, changelog.d/1107.md.

    3. PR 3 (M): net-address-list. Scheme tuples become urlsplit(value).scheme membership at ai/agents/tools.py:156, ai/research/edges.py:173, ai/review/samples.py:67, commands/ai_ingest.py:91 and commands/k8s/networking.py:85, and the TLS defaults hold ipaddress objects. Refs feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107. Tests first:

      • each site with a URL whose scheme is upper-case (HTTPS://example.com, which urlsplit lowercases and today's startswith misses), and with a non-URL;
      • the TLS SAN list containing x509.IPAddress for each default address;
      • devops tls JSON output still being strings.

      Files: those five modules, src/devops_cli/config/defaults.py, src/devops_cli/models/tls.py, src/devops_cli/crypto/tls_certificates.py, src/devops_cli/commands/tls.py, their tests, .ast-grep/, src/devops_cli/config/constants.py, the task file, changelog.d/1107.md.

    4. PR 4 (M): net-scheme-in, net-scheme-affix, net-url-build and net-bracket-affix. Refs feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107. The sites:

      • "://" in tests become urlsplit(...).scheme at commands/k8s/cluster_context.py:195, commands/repos.py:208 and :211, commands/sandbox.py:456 and :678, config/settings.py:218, core/paths.py:190 and security/reference_extractor.py:178 and :455;
      • ai/agents/media.py:184 and roadmap/refine.py:458 become scheme comparisons;
      • the D-Bus address is read through jeepney (commands/devcontainer.py:1286-1288);
      • URL authorities are built with httpx2.URL(scheme=..., host=..., port=...) at commands/ai_gateway.py:206, commands/ai_runs.py:159 and config/settings.py:219;
      • the Valkey endpoint parsers use urlsplit (valkey/client.py:46-61, config/settings.py:213-250).

      Tests first:

      • IPv6 hosts ([2001:db8::1]:6379, valkey://[2001:db8::1]) and upper-case schemes at each parser;
      • a URL built from an IPv6 host being bracketed;
      • a DBUS_SESSION_BUS_ADDRESS with an escaped path and with two addresses;
      • a scratch module with if "://" in url: failing the scan with error[net-scheme-in].

      Files: the modules above, their tests, pyproject.toml (jeepney), uv.lock, .ast-grep/, src/devops_cli/config/constants.py, the task file, changelog.d/1107.md.

    5. PR 5 (S): net-domain-suffix, net-domain-list, net-normalise and net-hostport, after fix(security): local names come from the public suffix list, and domains match on DNS labels, not string suffixes #887 has merged and deleted its own sites. Closes feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107. The sites left outside fix(security): local names come from the public suffix list, and domains match on DNS labels, not string suffixes #887's scope at 3dd7fa6:

      The PR re-runs all 12 rules at its merge base and fixes whatever is left. Tests first: each site with mixed-case, trailing-dot and bracketed-IPv6 input, and a look-alike (evilollama.com) staying outside. Files: those modules, their tests, .ast-grep/, src/devops_cli/config/constants.py, the task file (**Status**: Done), changelog.d/1107.md.

    Acceptance criteria

    • ast-grep-cli==0.51.0 is in the dev group. uv run devops ci has a constructs row that runs ast-grep scan --error=unused-suppression --error=no-suppress-all src, and pre-commit runs the scan and ast-grep test --skip-snapshot-tests.
    • After PR 5, .ast-grep/rules/ holds exactly the 12 net-* rules, with net-ip-literal refined as above. Each has at least one valid and one invalid case, and CONST_NET_CONSTRUCT_RULES lists them.
    • uv run ast-grep scan ... src exits 0 with no hit at every PR's merge. No ast-grep-ignore or noqa: TID251 marker exists in src. DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING is still 0.
    • TID251 is selected, and the four socket.inet_* APIs are banned with the ipaddress message. Both socket.inet_aton(...) and from socket import inet_pton are reported in a scratch module.
    • The meta-test reports every listed escape, each shown by its own case.
    • The constructs step takes under 1 s and passes with no network (unshare -rn), and ast-grep sends no telemetry.
    • AGENTS.md, the template (with and without is_devops_cli), generate_agents.md, architecture.md:29 and .devops/review.md carry the library-first rule as decided above. git diff AGENTS.md shows only those lines.
    • DEFAULT_HOMELAB_IPS and the sans default hold ipaddress objects. Certificates and JSON output are unchanged in content.
    • uv run devops ci and uv run devops docs check pass. changelog.d/1107.md records the gate; CHANGELOG.md and docs/ROADMAP.md are not edited.
    • Pending a person: rerun the fix(review): the devsecops persona reports misconfiguration and error-handling defects again, scored against a fixed recall set #1015 recall set after PR 2's house rule, and record recall next to the previous run.

    Current references

    • Ceiling: DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING src/devops_cli/config/defaults.py:702-703, in DEFAULT_SUPPRESSION_CEILINGS :718; marker counting tests/test_architectural_invariants.py:1547-1555, ceiling test :1673; marker kind and regexes src/devops_cli/config/constants.py:3285, :3338-3344

    • Meta-test helpers: _ruff_enforces tests/test_architectural_invariants.py:731, _ignore_file_escapes :917, _complexity_cap_escapes :969, test_every_complexity_cap_escape_is_reported :1325, test_the_complexity_cap_has_no_escape :1348

    • Dev group: pyproject.toml:78-98; Ruff select: :113-116; CONST_RUFF_LINT_KEYS: src/devops_cli/config/constants.py:3235-3245

    • Check table: CheckSpec src/devops_cli/commands/ci.py:146-156; get_check_specs() :435-547

    • Pre-commit repo: local: .pre-commit-config.yaml:45

    • Semgrep pin: src/devops_cli/tools_lock/tools.lock:381; rule pack metadata check: src/devops_cli/review/rules_pack.py:80-92; rule-pack CI job: .github/workflows/ci.yml:371-417

    • AGENTS.md: standard-library list :16; brittle-pattern block :17-20 (placement :20); "Avoid custom workarounds" :21; Standard Parsers :185

    • Template: "Avoid custom workarounds" src/devops_cli/ai/instruction_generator.py:277; brittle block :312-315; Standard Parsers :316-319; is_devops_cli :48, :116

    • src/devops_cli/ai/tasks/generate_agents.md:11-15; src/devops_cli/ai/knowledge_base/devops_cli/architecture.md:29; .devops/review.md house rules :57-77

    • TLS: src/devops_cli/config/defaults.py:181-185; src/devops_cli/models/tls.py:51; src/devops_cli/crypto/tls_certificates.py:62-77, :325-326; src/devops_cli/commands/tls.py:298

    • Hits per rule at 3dd7fa6:

      • net-scheme-in 9;
      • net-scheme-affix 10;
      • net-address-list 8;
      • net-domain-suffix 6;
      • net-normalise 5;
      • net-bracket-affix 3;
      • net-hostport 3;
      • net-ip-literal 3 (1 after the refinement);
      • net-url-build 3;
      • net-domain-list 1;
      • net-port-table 1;
      • net-cidr-build 0.

      The sites are listed in the Delivery steps. fix(security): local names come from the public suffix list, and domains match on DNS labels, not string suffixes #887 owns ai/common_tools.py:481 and :486, ai/harness/agents.py:392 and :394, ai/spend/pricing.py:159, commands/k8s/networking.py:710, core/validation.py:358 and config/constants.py:2545.

    Dependencies and order

  10. 1 remaining item

  11. added this to the v0.2.38 milestone on Oct 20, 2026
  12. dan-petty commented on Oct 21, 2026

    @dan-petty
    OwnerAuthor

    Feasibility check: PR 2 cannot be built as specified (AGENTS.md character budget breach)

    During the pre-coding feasibility check for PR 2 of #1107:

    1. Specified Requirements:

      • PR 2 specifies adding the "Parse With the Library; Hand-Rolled Parsing Is a Defect" bullet and "Matching Table Placement" bullet to AGENTS.md while dropping ipaddress/urllib.parse from line 15, Avoid custom workarounds... from line 20, and line 186 ("Standard Parsers Over Brittle Literals").
      • Criterion 11 specifies: Verification: git diff AGENTS.md shows only the listed changes; grep 'Parse With the Library' AGENTS.md finds the new bullet; grep 'Avoid custom workarounds' AGENTS.md returns nothing.
      • Invariant: tests/test_agents_md_claims.py::test_agents_md_stays_within_character_budget asserts CONST_AGENTS_MD_MAX_CHARS <= 40_000 and len(AGENTS.md) <= CONST_AGENTS_MD_MAX_CHARS.
    2. Evidence of Unworkable Premise:

    3. Why Compensating Code Cannot Be Added:

      • CONST_AGENTS_MD_MAX_CHARS cannot be increased because test_agents_md_stays_within_character_budget explicitly asserts CONST_AGENTS_MD_MAX_CHARS <= 40_000 and modifying this invariant violates the rule "Never Lower Security Standards or Quality Thresholds".
      • Unilaterally condensing 1,600 characters from other unrelated sections of AGENTS.md violates Criterion 11 (git diff AGENTS.md shows only the listed changes) and requires refactoring beyond the scope of PR 2 (which was planned as a separate future deliverable in docs(agents): AGENTS.md fits a context budget and Claude Code loads it #841's Step 2 to lower AGENTS.md to 20,000 characters).
    4. Current Status of feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107:

    Per AGENTS.md ("Stop Rather Than Add Compensating Code" / #1348), returning #1107 to New for refinement on AGENTS.md character budgeting.

  13. dan-petty commented on Oct 21, 2026

    @dan-petty
    OwnerAuthor

    Proposal needs splitting into 5 items at be39289 (see proposed design in issue body).

  14. dan-petty commented on Oct 21, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1784, merged into release/v0.2.38 as df141a3.

    Closes #1107

    23 file(s) changed.

    How it was verified

    Check runs at 4ab26c9:

    • Prune PR DevContainer Images: pass
    • Audit Defect PR Hardening: skipping
    • zizmor: pass
    • devops-cli: pass
    • bandit: pass
    • CodeQL: pass
    • Rule Pack Tests: pass
    • Changed-Test Independence: pass
    • Tests & Coverage: pass
    • Analyze (python): pass
    • Fail-to-Pass Check: pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • Fail-to-Pass Self-Check: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md:

    No Acceptance Criteria section.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/ciscope/reviewtype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions