Repository navigation
feat(policy): walk GitLab subgroups for org policy discovery (#2753) - #2933
Conversation
…icrosoft#2753) GitLab org-policy discovery previously probed only the top-level group (`<top-level-group>/apm-policy`), so a project under nested subgroups could not scope its own governance without changing the whole org. Walk the subgroup tree from the project's own group up to the top-level group and apply the closest `apm-policy` (closest wins); `absent` at an inner level ascends to the parent group, while any error/malformed outcome still fails closed. A flat `<group>/<project>` remote is unchanged. `extends:` now accepts nested-namespace references (`acme/dept-a/apm-policy`), and the pre-fetch host-pin guard no longer misreads a bare nested namespace's first segment as a cross-host FQDN (a real attacker FQDN is still rejected). Remote-URL splitting is centralized in a single `_remote_url_parts` owner (consumed by both `_parse_remote_url` and the new `_gitlab_namespace_descending`), and the `git remote get-url origin` subprocess in a single `_git_remote_origin_url` owner. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical host-pin and moderate GitLab discovery findings block approval.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds subgroup-aware GitLab policy discovery, selecting the closest policy and supporting nested extends: references.
Changes:
- Walks GitLab namespaces from deepest subgroup to top-level.
- Updates nested inheritance parsing and host validation.
- Adds tests, conformance updates, documentation, and changelog entries.
File summaries
| File | Summary |
|---|---|
tests/unit/policy/test_discovery.py |
Adds subgroup discovery and inheritance tests. |
tests/spec_conformance/test_policy_reqs.py |
Adds conformance coverage. |
src/apm_cli/policy/discovery.py |
Implements namespace walking and shared remote parsing. Critical (1 vote): single-label host prefixes can bypass the host-pin guard for non-GitLab leaves. Moderate (3 votes): origin is read twice during GitLab discovery. |
src/apm_cli/policy/_gitlab.py |
Supports nested GitLab policy references. Moderate (1 vote): mismatched host-like prefixes and malformed ports are not safely rejected. |
packages/apm-guide/.apm/skills/apm-usage/governance.md |
Updates usage guidance. Nit (1 vote): publishing checklist still describes top-level-only policies. |
docs/src/content/docs/enterprise/policy-reference.md |
Updates policy reference behavior. |
docs/src/content/docs/enterprise/governance-guide.md |
Updates governance guidance. |
docs/src/content/docs/enterprise/apm-policy.md |
Documents subgroup policy resolution. |
CONFORMANCE.md |
Updates generated conformance count. |
CONFORMANCE.json |
Updates generated conformance mapping. |
CHANGELOG.md |
Adds the feature entry. |
Review details
Suppressed comments (2)
packages/apm-guide/.apm/skills/apm-usage/governance.md:431
- The packaged usage guide still has a publishing checklist at
governance.md:681-682that says GitLab policy belongs under the top-level group only. With the subgroup walk described here, that omits the primary team-scoped deployment and leaves this user-facing guide incomplete; update the checklist to mention any ancestor namespace and closest-wins behavior.
to inherit it. A flat `<group>/<project>` remote probes only `<group>/apm-policy`.
src/apm_cli/policy/_gitlab.py:155
- For nested host-qualified refs, this branch now reaches
explicit.portfor any 3+ segment ref. On a non-default-port leaf,gitlab.example.test/acme/...passes hostname-only validation but is not stripped and is then fetched as namespacegitlab.example.test/acme/...; a malformed port such asgitlab.example.test:not-a-port/...instead raisesValueErrorbecause onlyurlsplitis caught. Treat host-like first segments whose host/port does not exactly match the leaf as invalid (and safely catch port parsing) rather than falling through.
and explicit.port == port
):
parts = parts[1:]
- Files reviewed: 11/11 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
- host-pin (F1): scope the "single-label first segment is a namespace" relaxation to GitLab leaves only. On GitHub/ADO leaves a 3-segment ref is host/owner/repo, so `extends: "evil/org/repo"` is again rejected as cross-host instead of routing a credential to `evil`. - GitLab extends: a host-like first segment must match the leaf host+port exactly or the ref is rejected (never folded into the namespace); a malformed port now fails closed instead of raising ValueError. - discovery: read `git remote get-url origin` once and reuse it for both identity and the namespace walk (`_gitlab_namespace_descending` takes the URL), removing the double subprocess and the TOCTOU on a changing remote. - docs: publishing checklist now says GitLab policy may live under any ancestor namespace (closest wins), not the top-level group only. - tests: cover GitHub-leaf cross-host rejection, port-mismatch and malformed-port rejection, and the pure namespace helper. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Thanks for the review — addressed all four findings in 🔴 Critical — host-pin bypass for single-label prefixes ( 🟠 Moderate — host-like prefix / malformed port ( 🟠 Moderate — origin read twice ( ⚪ Nit — publishing checklist ( Local gates green: |
There was a problem hiding this comment.
🟡 Changes recommended
The canonical-owner guard is incomplete, conformance coverage is misclassified, and dotted GitLab namespace guidance is missing.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
tests/spec_conformance/test_policy_reqs.py:150
- This marker overstates conformance coverage.
req-pl-011requires a registered, ordered provider list and per-project provider selection; this test only checks the implementation-specific namespace order inside one GitLab provider, which is already covered by the unit test. Remove this requirement marker/test from the conformance suite and regenerateCONFORMANCE.*, or replace it with an assertion that exercises the normative provider-registration contract.
- Files reviewed: 11/11 changed files
- Comments generated: 2
- Review effort level: Balanced
- architecture: add a registered static delegation guard (install-deployment-policy-remote-origin-owner) enforcing that only discovery.py reads `git remote get-url origin` and defines the remote-URL splitter/parsers; no other policy-tree module may re-read or re-parse the remote. Backs the single-owner claim the refactor makes. - docs: document that a bare nested `extends:` ref whose first segment contains a dot (group named e.g. `acme.tools`) must be host-qualified, since a dotted first segment is read as a host. - conformance: drop the req-pl-011 test that only re-asserted the GitLab provider's namespace order. Per req-pl-011 that order is implementation-defined, so it is not a normative conformance property; the unit suite already covers it. Regenerated CONFORMANCE.*. apm-spec-waiver: GitLab subgroup walk refines the existing req-pl-011 discovery provider (intra-provider search order is implementation-defined per spec 6.1.1); no new normative requirement, so no new anchor/manifest row/marker. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed the second review in Canonical-owner guard (incomplete) — Dotted GitLab namespace guidance (missing) — Conformance coverage misclassified — Local gates: |
There was a problem hiding this comment.
🟡 Changes recommended
Architecture mutation checks will fail or pass vacuously, and policy documentation remains internally inconsistent.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 10/10 changed files
- Comments generated: 4
- Review effort level: Balanced
- gitlab-facade-orchestration guard: the branch was renamed to `elif is_gitlab:` and the adapter call moved into `_gitlab_walk_candidate`, so the check scanned a stale `elif is_gitlab_hostname(host):` region and passed vacuously (its mutation case no longer produced a violation). Scope the orchestration scan to `_gitlab_walk_candidate`'s body instead; mutation case fires again. - policy-remote-origin-owner guard: give it teeth the mutation matrix can exercise -- require discovery.py to define all three canonical read/parse helpers -- and add its guard-less mutation case so the frozen matrix set-equality holds. - docs: reconcile policy-reference.md's `extends` table and the Discovery-vs-extends note with GitLab nested refs + closest-subgroup discovery; document that a host-qualified GitLab `extends:` ref must carry the exact `host:port` authority when the origin uses a port. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed the third review in Vacuous facade guard + failing mutation ( Guard-less rule without a mutation case ( policy-reference.md internal inconsistency Dotted-group workaround incomplete for explicit ports (apm-policy.md) Local gates: |
The frozen semantic-contract inventory in test_architecture_runner.py (_EXPECTED_RULE_ID_TEXT) must list every registered rule id; add install-deployment-policy-remote-origin-owner so the set-equality holds. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pre-emptive hardening in
Full local runs now green:
|
There was a problem hiding this comment.
🔵 Needs a closer look
The new canonical-owner rule is not registered and bound through the architecture owner registry.
Review details
Suppressed comments (1)
scripts/architecture_linter/checks/install_policy_intent.py:110
- This new canonical-owner check is registered through
_semantic_rule, which assignsguard_ids=(), and there is no matching owner record in.apm/architecture/owners/install-deployment.json. As a result, the owner registry cannot validate this guard bidirectionally or ensure it executes exactly once. Register the remote-origin decision in the owner registry and bind this rule to that guard ID rather than treating it as guard-less.
_semantic_rule(
RULE_REMOTE_ORIGIN_OWNER,
"Policy discovery reads and parses the git remote through one owner (discovery.py).",
check_policy_remote_origin_owner,
),
- Files reviewed: 12/12 changed files
- Comments generated: 0 new
- Review effort level: Balanced
Copilot review: a canonical-owner rule should be an owner-guard bound to an owner-registry record, not a guard-less semantic rule, so the registry can validate it bidirectionally and enforce single execution. - Register `install-deployment-policy-remote-origin-owner` with `guard_ids=(<id>,)` (a `Rule(...)`, not `_semantic_rule`), making it a known owner-guard that executes exactly once. - Reference it from discovery.py's existing owner record (`cached-policy-shape` in contracts-tooling.json); discovery.py can hold only one owner record, and a guard's shard is independent of its id prefix, so the remote-origin decision joins that record's guard list. - Move its mutation case from the guard-less matrix to the owner-guard matrix (test_architecture_owner_rule_mutations.py); both matrices' set-equality and the frozen inventory now hold. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed in What changed
Verification — full architecture suite green:
|
There was a problem hiding this comment.
🟡 Changes recommended
Concealed GitLab 404s can select a weaker ancestor policy, and the ownership guard does not fully enforce single-reader delegation.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 13/13 changed files
- Comments generated: 2
- Review effort level: Balanced
…uard Copilot review: - Concealed-404 fail-open (discovery.py): GitLab returns 404 both for a missing project and for a private one the token cannot read, so the subgroup walk could silently apply a weaker ancestor policy over a closer team policy the token was denied. Before applying an ancestor over skipped closer levels, verify via authenticated Git (`_gitlab.first_concealed_closer_policy`) that no skipped closer `apm-policy` project exists; if one is confirmed, fail closed. The residual case (token blind to both REST and Git) is indistinguishable from genuinely absent and still ascends -- documented. - Origin-read guard: the guard only required the three helper names to exist, so a second `git remote get-url origin` elsewhere in discovery.py would pass. Add an exact-count clause (one origin-read argv in the owner) and switch the owner-guard mutation to introduce a duplicate read, so the single-reader invariant is enforced and proven. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eppiel-w2-pr-2933 # Conflicts: # .apm/architecture/owners/install-deployment.json # tests/unit/policy/test_discovery.py
The accepted microsoft#2753 scope (apm-scope:v1, 2026-10-20) rejects closest-wins replacement: a team policy may only tighten applicable ancestors. GitLab discovery now probes apm-policy at every namespace of the project's ancestry and the chain owner (_resolve_and_persist_chain) composes them company-to-team with the existing tighten-only merger, so an ancestor restriction survives a closer policy that omits extends. The nearest discovered policy stays the policy.hash leaf; non-404 failures with any discovered policy become incomplete_chain (fail closed under warn); duplicate ancestors reuse one fetch without false cycles; the five-policy limit counts the composed chain; a dedicated ancestry cache key backs warm, stale and cache-only reads. Install, audit JSON/SARIF and policy status expose the ordered redacted chain. The walk moves into the GitLab adapter (_fetch_gitlab_ancestry) so discovery.py stays under the length guard, and the facade guard again scans the elif is_gitlab_hostname branch. Addresses Copilot inline on discovery.py (warn-mode partial chain) and test_install_logger_policy.py (URL substring assertion). apm-spec-waiver: GitLab discovery provider composes namespace ancestry through the existing tighten-only extends merge; req-pl-001/011/012 semantics unchanged Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
Replace the closest-wins description with the accepted contract: every ancestor apm-policy combines top-down with tighten-only merging, the nearest discovered policy is the policy.hash leaf (no silent repin), non-404 failures fail closed, offline uses only the complete cached chain, and GitLab's 404-for-unreadable limitation requires read access across the namespace ancestry. Drop two stale microsoft#2706 CHANGELOG lines the main merge resurrected under Unreleased. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
Drive the installed apm binary against a loopback HTTPS gitlab.com fixture: company-only, team-only, company plus team with a missing intermediate, multiple subgroup levels, empty and weaker children keep ancestor restrictions in both install and audit --ci; clean absence; 403/500 ancestor failures fail closed under warn; a new closer policy never silently repins; a complete cached chain enforces without contacting GitLab. The GitHub fixture's certificate minting now accepts the served host list so both fixtures share it. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
APM Review Panel:
|
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Python Architect | 0 | 0 | 2 | Chain composition stays single-owner; the GitLab adapter boundary and _remote.py owner are respected. |
| Test Coverage Expert | 0 | 0 | 1 | Every scope-contract scenario has a regression trap (unit) and the CLI surfaces have installed-binary e2e coverage. |
| Doc Writer | 0 | 2 | 1 | Docs match the code; fix the Inheritance and pin notes in policy-reference and shorten the CHANGELOG line. |
| CLI Logging Expert | 0 | 1 | 2 | Chain rendering works; enforcement: off must stay silent at default verbosity. |
| Supply Chain Security Expert | 0 | 0 | 2 | Fail-closed invariants, pin scoping, and cache-only safety are sound. |
| Auth Expert | 0 | 0 | 1 | Credential isolation (F1) holds; cross-host refs are rejected before any credential fill. |
| Performance Expert | 0 | 1 | 2 | Requests are bounded and warm runs make zero requests; sequential probes are a follow-up. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Top 5 follow-ups
- [Performance Expert] Parallelize GitLab namespace probes -- deep hierarchies pay one round trip per level on cold or stale runs; deferred as a new concurrency surface beyond the accepted bounded-fetch contract (follow-up issue).
- [Performance Expert] Negative caching for absent GitLab namespaces -- absent levels are re-probed on stale runs; a new cache record type is outside this PR's reuse of existing cache owners (follow-up issue).
- [CLI Logging Expert] Unify the provider-wide
org:source-label convention -- touches GitHub and ADO output, beyond this GitLab scope (follow-up issue). - [Supply Chain Security Expert] Document that
policy.hashpins only the nearest policy -- ancestor additions, removals, or edits are enforced through refresh and the tighten-only merge, not pin-detected; being folded into the docs now. - [Test Coverage Expert] Add an installed-CLI hierarchy that mixes
extends:with discovered ancestors -- promotes the duplicate-ancestor guard to e2e; being folded now.
Architecture
classDiagram
direction TB
class PolicyFetchResult {
<<Dataclass>>
+policy: ApmPolicy or None
+source: str
+outcome: str
+ancestry_parents: list~PolicyFetchResult~ or None
+chain_sources: list~str~
+subgroup_scoped: bool
}
class discovery {
<<Module>>
+discover_policy_with_chain()
-_resolve_and_persist_chain()
-_auto_discover()
-_validate_extends_host()
}
class _gitlab {
<<Adapter>>
-_fetch_gitlab_ancestry()
-_gitlab_parent_coordinates()
-_gitlab_ancestry_cached_result()
-_fetch_from_gitlab_repo()
-_fetch_gitlab_chain_parent()
}
class _remote {
<<SingleOwner>>
-_git_remote_origin_url()
-_remote_url_parts()
-_parse_remote_url()
-_extract_org_host_port_from_git_remote()
}
class inheritance {
<<Pure>>
+resolve_policy_chain()
+merge_policies()
+MAX_CHAIN_DEPTH: 5
}
discovery ..> _gitlab : GitLab ancestry walk
discovery ..> inheritance : tighten-only merge
discovery ..> _remote : reads origin once
_gitlab ..> _remote : splits URL
_gitlab ..> PolicyFetchResult : returns
discovery ..> PolicyFetchResult : composes in place
class PolicyFetchResult:::touched
class discovery:::touched
class _gitlab:::touched
class _remote:::touched
classDef touched fill:#fff3b0,stroke:#d47600
flowchart TD
A["install / audit / policy status<br/>discover_policy_with_chain"] --> B["_auto_discover: read origin once"]
B --> E{"GitLab host?"}
E -- "no" --> G["GitHub / ADO discovery (unchanged)"]
E -- "yes" --> F["_gitlab._fetch_gitlab_ancestry"]
F --> I{"nested namespace?"}
I -- "no: flat" --> J["single apm-policy fetch (unchanged)"]
I -- "yes" --> K{"fresh composed cache?"}
K -- "yes" --> L["serve composed chain, zero requests"]
K -- "no" --> M["probe every namespace, deepest first"]
M --> S{"non-404 failure?"}
S -- "stale composed cache" --> T["cached_stale (complete chain)"]
S -- "another level found" --> U["incomplete_chain: fail closed"]
S -- "none" --> V["leaf = nearest, ancestry_parents = farther"]
V --> X["_resolve_and_persist_chain: company to team, each with its extends chain"]
X --> Y["resolve_policy_chain + write composed cache + ordered redacted chain"]
Recommendation
Ship after the merge worker folds the in-scope items (policy-reference Inheritance and pin notes, CHANGELOG length, apm-guide fail-closed wording, off logger gating with a test, chain rendering without repeating the leaf, the dotted-namespace comment, pin-scope docs, a shared composed_sources set, a _segment return annotation, and an e2e extends: + ancestry hierarchy). File three follow-up issues for parallel probes, negative caching, and the provider-wide source label. Parallel probes is the only one with user-visible latency on deep hierarchies.
Full per-persona findings
Python Architect
- [nit]
_segmentdiscriminates success (list) from failure (tuple) withisinstanceand has no return annotation atsrc/apm_cli/policy/discovery.py:644
A future refactor that returns a tuple on success would silently become an incomplete chain.
Suggested: annotate the return aslist[...] | tuple[str, int, int]. - [nit] Patterns: Adapter (
_gitlab.py), Chain of Responsibility (per-levelextends:segments composed root-first), Single Owner (_remote.py). No further abstraction needed at one-provider scale.
Test Coverage Expert
- [nit] Installed-CLI hierarchies exercise only namespace composition; the
extends:+ ancestry duplicate guard is unit-only attests/integration/test_gitlab_subgroup_policy_lifecycle.py
The user promise is covered at e2e; the dedupe guard is an internal invariant covered at unit tier.
Proof (passed):tests/unit/policy/test_gitlab_ancestry_composition.py::test_explicit_extends_to_discovered_ancestor_is_deduplicated-- proves: anextends:naming a discovered ancestor is reused without refetch or false cycle [governed-by-policy,secure-by-default]
Doc Writer
- [recommended] policy-reference Inheritance note still says
extends:composes inside "that one discovered file", and the pin note does not say GitLab-discovered ancestors are outside the pin atdocs/src/content/docs/enterprise/policy-reference.md:479
A governance reader could assume a pinned GitLab project is protected from ancestor changes. - [recommended] The CHANGELOG entry is a long paragraph rather than one concise line at
CHANGELOG.md:12
.github/instructions/changelog.instructions.mdasks for one concise line ending with the PR number. - [nit] apm-guide says a non-404 failure "at any level" fails closed; the code fails closed only while another level has a policy at
packages/apm-guide/.apm/skills/apm-usage/governance.md:445
CLI Logging Expert
- [recommended]
enforcement: offwith a subgroup policy prints at default verbosity atsrc/apm_cli/core/command_logger.py:655
Anoffpolicy needs no action; it should stay silent unless--verbose.
Suggested: gate the info line onenforcement != "off". - [nit] The leaf appears twice on the install line (source and last chain entry).
- [nit]
org:prefix on the source vs bare refs in the chain.
Supply Chain Security Expert
- [nit] The dotted-first-segment host heuristic rejects a subgroup like
my.dept(fails closed); add an inline comment atsrc/apm_cli/policy/_gitlab.py:146 - [nit]
policy.hashpins only the nearest policy; ancestor changes are not pin-detected. Document it and point CI atapm policy statusto verify the chain.
Auth Expert
- [nit] Same dotted-namespace heuristic (fails closed, no credential leak) at
src/apm_cli/policy/_gitlab.py:143; documented next to the 404 caveat.
Performance Expert
- [recommended] Namespace probes run sequentially at
src/apm_cli/policy/_gitlab.py:355
Cold or stale runs pay one round trip per level; warm runs make zero requests. Follow-up, not a blocker. - [nit]
composed_sourcesis rebuilt per segment; share one set atsrc/apm_cli/policy/discovery.py:696 - [nit] Absent namespaces are re-probed on stale runs (documented trade-off); negative caching is a follow-up.
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.
CI shards 1-2 failed: lifecycle-script kill-switch tests stub discover_policy with a duck-typed leaf that predates ancestry_parents, so the new entry-point read raised inside the runner, which swallowed it and dropped deny_all. Read ancestry_parents defensively after the existing extends check. The docs link checker rejected ./apm-policy/ links from sibling pages; Starlight pages need ../apm-policy/. Addresses CI run 43270309942 and docs build 43270309904. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
Addresses the iteration-1 advisory (comment 6831280525): an off composed policy stays silent without --verbose and the install line names the extends chain without repeating the leaf (cli-logging); policy-reference Inheritance and pin notes, pin scope for discovered ancestors, a one-line CHANGELOG entry and precise fail-closed wording in apm-usage (doc-writer, supply-chain); an inline note on the dotted-group host heuristic (auth, supply-chain); a shared composed_sources set and a _segment return annotation (performance, architect); an installed-CLI hierarchy mixing extends: with discovered ancestors (test-coverage). Relative ./apm-policy/ links from sibling pages become ../apm-policy/. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
Addresses delta-panel python-architect follow-up: the entry point already tolerates duck-typed fetch results without ancestry_parents, but _resolve_and_persist_chain still read the attribute directly, so an extends-bearing duck-typed result would fail there instead. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
…eppiel-w2-pr-2933
Addresses terminal delta test-coverage follow-up: no test drove a duck-typed fetch result with extends: into _resolve_and_persist_chain, so reverting its defensive ancestry_parents read would have gone unnoticed. Mutation-break: restoring the bare attribute read fails the new test with AttributeError. Co-authored-by: Rafael Azevedo <[email protected]> Co-authored-by: Copilot App <[email protected]>
…eppiel-w2-pr-2933
…eppiel-w2-pr-2933
…eppiel-w2-pr-2933
…eppiel-w2-pr-2933
APM Review Panel:
|
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Python Architect | 0 | 0 | 0 | The asymmetric-getattr finding is resolved; no new concerns. |
| Test Coverage Expert | 0 | 0 | 0 | The callee-side trap was added and mutation-break verified; every scope scenario is covered. |
| Doc Writer | 0 | 0 | 0 | All three iteration-1 doc findings are fixed accurately; links are valid. |
| CLI Logging Expert | 0 | 0 | 0 | The off gate and leaf-free chain rendering are resolved and consistent with apm policy status. |
| Supply Chain Security Expert | 0 | 0 | 0 | The defensive read is equivalent for real results; no bypass. |
| Auth Expert | 0 | 0 | 0 | No credential-routing change. |
| Performance Expert | 0 | 0 | 0 | The shared set is correct; no regressions. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Top 3 follow-ups
- [Performance Expert] Parallelize GitLab namespace probes -- latency on deep hierarchies; a new concurrency surface beyond the bounded-fetch contract (follow-up issue).
- [Performance Expert] Cache absent GitLab namespaces -- re-probes on stale runs; this needs a new cache record type, which is outside this PR's reuse of existing cache owners (follow-up issue).
- [CLI Logging Expert] Unify the provider-wide
org:source label on thePolicy:line -- this changes GitHub and ADO output too (follow-up issue).
Recommendation
No in-PR work remains. The three items above are scope-boundary follow-ups for separate issues. The PR is ready for the required maintainer review against the #2753 scope (review contact Daniel Meppiel (@danielmeppiel)).
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.
e524b6b
into
microsoft:main
Clean merge of #3599, #3647, #3650, #2933; no lockfile or autopilot package conflicts. Co-authored-by: sergio-sisternes-epam <[email protected]> Co-authored-by: Copilot App <[email protected]>
* fix(tests): restore release-gate lanes for 0.36.0 Main's tag-gate lanes (build-release push + manual-build-release) were red on runs 43381609442, 43381682871 and 43394173235. PR CI never runs them. Product regressions (Windows/real installs), fixed: - Hook cleanup removed nothing on Windows: remove_stale_deployed_files looked up recorded hashes with POSIX keys while callers passed native backslash keys, so content proof failed closed (#3672, Refs #3649). - describe_path_obstruction returned None on Windows, which reports a directory-for-file as EACCES and a file-for-parent as ENOENT instead of EISDIR/ENOTDIR (#3709, Refs #3678). - Skill preflight refused claimed members of an unclaimed, populated skill directory that materialization leaves alone, failing a local bundle install (Refs #3625). Stale tests (behaviour changed intentionally), updated: - policy chain mocks now return real PolicyFetchResult (#2933, Refs #2753) - bare-cache/downloader/anonymous-https fixtures use real Git checkouts (#3603, Refs #3457) - mcp install help, registry error wording, deps why -g help (#3633 Refs #3588, #2803 Refs #2478, #3614 Refs #2884) - downloader stub carries carried_licenses (#3646, Refs #3556) - frozen-hash lifecycle uses a generic git host so -g URL validation uses git ls-remote instead of a live api.github.com 404 (#3672) New Windows-shaped regression tests are marked windows_compat. Co-authored-by: Copilot App <[email protected]> * chore: spec waiver for release-gate repair apm-spec-waiver: restores pre-existing behaviour on Windows and in skill preflight; no OpenAPM-observable change Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: danielmeppiel <[email protected]> Co-authored-by: Copilot App <[email protected]>
Important
Semantics changed after maintainer rework (2026-11-12). The accepted scope for #2753 (apm-scope:v1 record) rules out closest-wins. This PR now composes every ancestor
apm-policywith the tighten-only merge. The closest-wins description in the original text below is superseded; see "Maintainer rework" at the end.TL;DR
GitLab org-policy auto-discovery only ever probed the top-level group (
<top-level-group>/apm-policy), so a project nested under subgroups could not enforce its own governance without changing the whole organization. This PR walks the GitLab subgroup tree from the project's own group up to the top-level group and applies the closestapm-policy(closest wins), and letsextends:compose across nested namespaces. Flat<group>/<project>remotes are unchanged. Closes #2753.Problem (WHY)
For a project at
gitlab.com/acme/dept-a/team-x/my-project, discovery resolved onlyacme/apm-policyand discarded every intermediate subgroup:status/accepted.Root cause:
_parse_remote_urlreturned onlypath_parts[0]as the org, and_auto_discoverpassed that single org to the GitLab fetch — the full namespace was never derived.Approach (WHAT)
absentwins (closest)absent(404) ascends to the parent groupapm-policyis skipped in favour of the next ancestor (404 == no policy, like GitHub/ADO) — a platform limitation, documented (grant the token read access).extends:; now accepts nested-namespace refs<group>/apm-policy— identical to prior behaviorpolicy/_remote.pyowner (no split authority; architecture-guard enforced)Implementation (HOW)
src/apm_cli/policy/_remote.py(new)discovery.py(which grew past the 2100-line file-length ratchet):_git_remote_origin_url(singlegit remote get-url originowner),_remote_url_parts(single host+segments splitter),_parse_remote_url(refactored to consume the splitter — behavior-preserving for GitHub/GHE/ADO/visualstudio), plus_extract_org_host_port_from_git_remote/_extract_org_from_git_remote.discovery.pyre-exports them, so call sites/tests are unchanged.src/apm_cli/policy/discovery.py_gitlab_namespace_descending(deepest→top namespaces from the origin remote) and_gitlab_walk_candidate(the walk: first non-absentwins,absentascends). Readsoriginonce and reuses it for identity + the walk.src/apm_cli/policy/discovery.py(_extract_extends_host)acme/dept-a/apm-policy); on GitHub/ADO leaves it is still parsed as a (cross-)host, soextends: "evil/org/repo"remains rejected (Security Finding F1 preserved).src/apm_cli/policy/_gitlab.py_fetch_gitlab_chain_parentaccepts nested-namespaceextends:refs (namespace = parts[:-1],repo = parts[-1]) after an optional leaf-host-prefix strip.scripts/architecture_linter/checks/install_policy_gitlab_and_bundle.py,install_policy_intent.py,.apm/architecture/owners/install-deployment.jsoninstall-deployment-policy-remote-origin-owner), bound to a dedicated_remote.pyowner-registry record: only_remote.pymay readgit remote get-url originor define the remote-URL splitter/parsers. Also re-point the existinggitlab-facade-orchestrationguard at_gitlab_walk_candidate.test_discovery.pycoverage for the walk, nestedextends:, and F1; an owner-guard mutation-break case intest_architecture_owner_rule_mutations.pyand the frozen-inventory entry intest_architecture_runner.pyfor the new guard.CHANGELOG.mdapm-policy.md,governance-guide.md,policy-reference.md,apm-usage/governance.md; added theUnreleasedchangelog entry.Note
The GitLab REST transport and
AuthResolverauth already URL-encode a full multi-segmentproject_path, so no transport/auth changes were needed —org="acme/dept-a"was already fetchable.Diagram
The GitLab branch of
_auto_discover: each namespace level is probed closest-first; only a cleanabsentascends, every other outcome returns immediately.flowchart TD A[origin remote] --> B[_gitlab_namespace_descending] B --> C["deepest: acme/dept-a/team-x"] C -->|found / error| R[return result] C -->|absent| D["acme/dept-a"] D -->|found / error| R D -->|absent| E["acme (top-level)"] E -->|found / error| R E -->|absent| Z[outcome = absent, clean no-op]Trade-offs
debugso--verboseis not spammed. Absent REST results are served from the existing per-namespace policy cache on warm runs; caching the absent REST outcome itself is a possible follow-up, out of scope. (The concealment Git probe, a separate path, is cached — see below.)apm-policythe token cannot read is indistinguishable from a missing one, so it is skipped in favour of the next ancestor — the same404 == no policybehaviour GitHub/ADO discovery already have. An earlier revision tried to detect this via an authenticatedgit ls-remoteprobe; it was removed after review as scope creep (it caught only a narrow case, could not be soundly cached, and false-positived on anapm-policyproject containing only a README). Mitigation: grant the CI token read access to everyapm-policyit should honour.apm-policyproject in an intermediate subgroup can publish a weaker policy that shadows a stricter ancestor for projects under it (onlyextends:chains enforce tighten-only). This is intrinsic to team-scoped governance; the mitigation (restrictapm-policyproject creation via GitLab RBAC) is documented in the governance guide's sharp-edges list.extends: "org"resolves to the top-level group, not the nearest ancestor — kept consistent with GitHub/ADO semantics and documented explicitly, rather than silently redefining the shorthand per host.extends:refs is resolved by an FQDN heuristic (a host has a.or:port); a GitLab group whose name literally contains a dot would fail closed (rejected). This is safe and rare, and the docs prescribe the host-qualified spelling (gitlab.com/acme.tools/..., withhost:portwhen the origin uses a port) as the workaround.Benefits
apm-policywithout touching org-wide governance.acme/apm-policystill applies to every project with no closer policy — zero migration for existing setups.extends:(including nested-namespace parents).Validation
All CI-mirror gates pass locally on the merge base.
Lint, duplication, tests, architecture, conformance
Scenario evidence
test_gitlab_subgroup_closest_winstest_gitlab_subgroup_absent_ascends_to_parentabsenttest_gitlab_subgroup_all_absent_is_clean_absenttest_gitlab_subgroup_error_fails_closed,..._error_at_inner_level_fails_closedtest_gitlab_flat_project_falls_back_to_top_level_orgextends:allowed, cross-host FQDN rejectedTestValidateExtendsHostNestedNamespace_parse_remote_urlrefactor is behavior-preservingTestParseRemoteUrlADO/GHE/visualstudio casesImportant
The nested-
extends:host-pin fix was surfaced by the localapm-review-paneldogfood pass (supply-chain + auth personas, independently): the original tests exercised_fetch_chain_parentdirectly and bypassed_validate_extends_host, masking the reject. Regression tests now drive the real validation path.How to test
originat a nested GitLab remote (gitlab.com/acme/dept-a/team-x/my-project) and publishapm-policy.ymlinacme/dept-a/apm-policy.apm audit --ci(orapm install) and confirm theacme/dept-apolicy is applied (closest wins), not the top-level one.acme/apm-policy.absent(no warning, no fetch-failure).uv run python -m pytest tests/unit/policy/test_discovery.py.Co-authored-by: Copilot [email protected]
Maintainer rework (W2 merge worker, 2026-11-12)
The contributor's closest-wins head (97767eb) was reworked on this branch to the accepted #2753 contract. The contributor's
_remote.pysingle-owner extraction, its architecture guard, and nestedextends:refs are kept.extends:_gitlab._fetch_gitlab_ancestryprobes every namespace; the existing chain owner_resolve_and_persist_chainmerges root-first withresolve_policy_chaintest_gitlab_ancestry_composition.py; installed-CLItest_install_and_audit_enforce_the_composed_ancestry[*]absentteam-only,test_no_policy_in_any_namespace_is_clean_absencewarnincomplete_chain; a complete cached chain follows stale-cache rulestest_ancestor_failure_never_applies_a_weaker_partial_chain[403/500]policy.hash, no silent repintest_pin_follows_the_nearest_policy_and_never_silently_repins_gitlab_parent_coordinates; duplicates are reused without a second fetch, cycles raise, and depth counts the composed chainextends-plus-ancestrye2e case#ancestrycache key; cache-only serves only the complete composed chaintest_cache_only_*,test_cached_composition_enforces_offlinePolicy: <leaf> (extends chain: ...), audit JSON/SARIFpolicy.chain,apm policy statusextends chainValidation at this head: unit policy suites (1356 passed), installed-CLI GitLab lifecycle (12 passed against the installed
apmbinary over a loopback HTTPSgitlab.comfixture), owner-rule mutations (573 passed), semantic-rule mutations + runner (214 passed),lint-architecture-boundaries.shexit 0, ruff check/format, pylint R0801 and auth-signal lint clean. Seven mutation-break gates each killed their mutant.Closes #2753