Skip to content

feat(cli): add export-patch command to export local spec edits as upstream patches - #2162

Merged
Daniel Meppiel (danielmeppiel) merged 19 commits into
microsoft:mainfrom
edenfunf:feat/2118-export-patch
Nov 12, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 19 commits into
microsoft:mainfrom
edenfunf:feat/2118-export-patch

Conversation

@edenfunf

Copy link
Copy Markdown
Contributor

Closes #2118

What

New apm export-patch command: exports local edits to APM-managed files as unified diffs against the packages that deployed them -- one git apply-ready .patch file per package, with the locked base (resolved commit for git deps, version/URL for registry deps) recorded in the patch header.

$ apm export-patch
[>] Replaying install (cache-only)...
[+] Replayed 2 package(s)
[i] .github/instructions/design-standards.instructions.md ->
    microsoft/apm-sample-package:.apm/instructions/design-standards.instructions.md
[i] wrote apm-patches\microsoft-apm-sample-package.patch

How it works

  • Reuses the drift replay (install/drift.py) read-only: replay the locked install into a scratch tree, diff against the project, and take the modified findings.
  • Reverse mapping is content-addressed: a finding is exportable iff the replayed content digest-matches exactly one file in the owning package's source tree and that source is byte-identical to it (not merely normalized-equal), which guarantees the emitted diff applies to the raw on-disk source.
  • Everything that cannot be exported honestly says why: format-transformed deployments, CRLF/BOM-bearing sources, ambiguous matches, conflicting edits across multiple deployed copies, local-path deps, project-local content, binary content, cache misses.
  • Local deletions (unintegrated) are never exported -- deleting a deployed copy does not imply upstream removal intent.

Scope notes

  • Core logic lives in commands/export_patch.py: it consumes replay/diff APIs read-only and adds no install/lockfile semantics, so no normative critical path is touched (Mode B detector is clean).
  • The diff phase resolves targets with apm.yml's explicit target:, matching the replay's own resolution. _check_drift in policy/ci_checks.py has the same auto-detect-only pattern; left untouched here to keep scope contained -- can file a follow-up.

Testing

  • 34 unit tests covering reverse mapping, applicability gating, skip reasons, diff shape (git line model, no-newline markers), filename collision handling, and header sanitization.
  • 4 integration tests including a full closed loop: edit a deployed file -> apm export-patch -> git apply in the package source -> update the snapshot -> the same command reports nothing left to export.
  • Verified end-to-end against a real install of microsoft/apm-sample-package: exported patch applies cleanly with git apply in a fresh clone at the recorded base commit.

Docs page, changelog entry, and the apm-guide command reference are included.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new apm export-patch CLI command that turns local edits to APM-managed deployed files into git apply-compatible patch files against the originating package sources, using the drift replay/diff machinery as a read-only signal.

Changes:

  • Implement export-patch command + core reverse-mapping/diff generation logic with per-package patch output.
  • Add unit and integration coverage for patch generation, edge cases, and a closed-loop git apply convergence test.
  • Document the new command (docs site + apm-guide command reference) and add a changelog entry.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/apm_cli/commands/export_patch.py New command implementation: replay/diff integration, reverse mapping, patch/header generation, and patch file output.
src/apm_cli/cli.py Wires export-patch into the root CLI.
tests/unit/commands/test_export_patch.py Unit tests for filename sanitization, diff shape, reverse mapping, skip reasons, and CLI error handling.
tests/integration/test_export_patch_e2e.py End-to-end closed-loop test exercising export → git apply → convergence.
docs/src/content/docs/reference/cli/export-patch.md New CLI reference page for apm export-patch.
packages/apm-guide/.apm/skills/apm-usage/commands.md Updates the apm-guide command list to include export-patch.
CHANGELOG.md Adds an Unreleased entry for the new command.

Comment thread src/apm_cli/commands/export_patch.py Resolved
Comment thread src/apm_cli/commands/export_patch.py Resolved
Comment thread CHANGELOG.md Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Suppressed comments (2)

src/apm_cli/commands/export_patch.py:512

  • The --verbose help says it will show "skip details", but skip reasons are printed unconditionally (via logger.warning) even when verbose is off. Either gate per-file skip output on verbose, or update the flag help text so it matches the actual behavior.
    "--dry-run",
    is_flag=True,
    help="List what would be exported without writing patch files",
)
@click.option("--verbose", "-v", is_flag=True, help="Show replay progress and skip details")
def export_patch(out_dir, dry_run, verbose):

CHANGELOG.md:16

  • The new Unreleased entry spans multiple wrapped lines. This repository's changelog format expects one concise bullet per PR (ending with the PR number), which also makes backports/cherry-picks cleaner.
- New `apm export-patch` command exports local edits to APM-managed files
  as unified diffs against the packages that deployed them, one
  `git apply`-ready `.patch` file per package with the locked base recorded
  in the header. Verbatim-deployed files only; transformed deployments are
  listed as skipped with the reason. (by @edenfunf; closes #2118) (#2162)

Comment thread src/apm_cli/commands/export_patch.py Resolved
@sergio-sisternes-epam

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

export-patch ships the consume-to-produce flywheel with one blocking sidebar collision and useful hardening follow-ups.

cc Eden (@edenfunf) Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

This is a well-scoped, architecturally clean feature that closes the loop between drift detection and upstream contribution -- a key differentiator for APM's positioning as the AI-native package manager. No specialist disagreed on shippability; the only blocking finding is a trivial sidebar order collision (doc-writer) that takes one line to fix.

The supply-chain-security findings on _strip_userinfo and path containment are real hardening opportunities but carry low blast radius: the command writes patches to a user-specified directory and never executes them. I side with shipping now and filing a follow-up for the percent-encoded userinfo edge case, since the realistic threat requires a malicious lockfile entry the user already trusts enough to have installed.

The DevX UX recommendations (--json, --fail-on-empty) are strong post-merge candidates that should land before the next minor but are not blockers for initial merge. The growth-hacker's cross-link and end-to-end PR workflow story are the highest-leverage docs follow-ups for adoption.

Aligned with: Portable by manifest (patches reference source-relative paths from apm.lock.yaml, portable across hosts); Secure by default (userinfo stripping prevents accidental credential leakage in patch headers; hardening follow-up filed); OSS community driven (directly enables consumers to become upstream contributors with one command); Pragmatic as npm (mirrors npm/cargo patch-export patterns with zero config required).

Growth signal. export-patch ships the consume->produce flywheel. Track upstream PRs generated as a leading adoption metric. Story angle: 'Your local fix is one command away from an upstream PR.'

Panel summary

Persona B R N Takeaway
Python Architect 0 0 2 Clean single-module command with frozen dataclasses, content-addressed reverse mapping, and proper deferred imports; no architectural concerns.
CLI Logging Expert 0 0 2 Output is clean and follows CommandLogger conventions; two nits on success-level messaging.
DevX UX Expert 0 2 2 Solid command surface; missing --json flag and exit-code surprise are the main gaps for scripting ergonomics.
Supply Chain Security Expert 0 2 1 _strip_userinfo is adequate; no blocking issues found. Path containment is minimal but acceptable for a patch-write command.
OSS Growth Hacker 0 2 2 Strong flywheel feature; docs solid but missing the upstream-contribution workflow story.
Doc Writer 1 2 2 Solid new ref page with one blocking sidebar collision (order 14 = audit.md), missing cross-link from audit, and a section-heading inconsistency.
Test Coverage Expert 0 1 1 Strong unit+integration coverage; S7 probe inconclusive in review env (CI is the gate). No blocking gaps.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 5 follow-ups

  1. [Doc Writer] (blocking-severity) Fix sidebar.order: 14 collision with audit.md -- Two pages at order 14 causes non-deterministic sidebar rendering in Starlight; set to 15 and shift downstream pages.
  2. [Supply Chain Security Expert] Handle percent-encoded userinfo (%40) in _strip_userinfo -- Closes an edge-case credential leakage vector via crafted lockfile URLs.
  3. [DevX UX Expert] Add --json flag for machine-readable output -- export-patch is a scripting primitive; structured output is table-stakes for CI consumers.
  4. [OSS Growth Hacker] Add end-to-end PR workflow section and cross-link from audit.md -- Closes the discovery gap and converts patch exporters into visible upstream contributors.
  5. [DevX UX Expert] Add --fail-on-empty flag for CI gating -- Exit 0 on no-op surprises CI scripts that gate on patch production.

Architecture

classDiagram
    direction LR
    class ExportedEdit {
      <<ValueObject>>
      +deployed_path str
      +source_path str
      +package str
    }
    class SkippedEdit {
      <<ValueObject>>
      +deployed_path str
      +package str
      +reason str
    }
    class PatchExport {
      <<ValueObject>>
      +patches dict
      +exported list~ExportedEdit~
      +skipped list~SkippedEdit~
    }
    class _SourceIndex {
      <<ValueObject>>
      +by_digest dict
      +unindexed tuple
    }
    class LockFile {
      +dependencies dict
      +get_dependency(key) LockedDependency
    }
    class DriftFinding {
      +path str
      +kind str
      +package str
    }
    class CommandLogger {
      +error(msg)
      +warning(msg)
      +progress(msg)
      +success(msg)
    }
    PatchExport *-- ExportedEdit
    PatchExport *-- SkippedEdit
    class ExportedEdit:::touched
    class SkippedEdit:::touched
    class PatchExport:::touched
    class _SourceIndex:::touched
    classDef touched fill:#fff3b0,stroke:#d47600
Loading
flowchart TD
    A["CLI: export_patch click command"] --> B["_run_export_patch"]
    B --> C["[I/O] LockFile.read"]
    C --> D["[FS] run_replay\ninstall/drift.py"]
    D --> E["diff_scratch_against_project"]
    E --> F["build_patch_export"]
    F --> G{"finding.kind == modified?"}
    G -->|No| H["discard"]
    G -->|Yes| I["_resolve_package_key"]
    I --> J["[FS] _materialize_install_path\ncache_only=True"]
    J --> K["[FS] _index_source_tree\nsha256 reverse map"]
    K --> L["_export_one per finding"]
    L --> M{"digest match?"}
    M -->|No match / ambiguous| N["SkippedEdit"]
    M -->|Unique match| O{"source raw == normalized?"}
    O -->|No| N
    O -->|Yes| P["_unified_diff -> diff text"]
    P --> Q["group by source_rel\ndetect conflicts"]
    Q --> R["PatchExport result"]
    R --> S{"dry_run?"}
    S -->|Yes| T["log summary"]
    S -->|No| U["[FS] atomic_write_text\nper-package .patch file"]
Loading

Recommendation

Fix the sidebar order collision (one-line change) and merge. The security hardening, --json flag, and docs cross-links are valuable but non-blocking -- file as issues and land in the next patch cycle. This feature directly reinforces APM's positioning as the package manager that turns consumers into contributors, and the implementation is clean enough to ship with confidence.


Full per-persona findings

Python Architect

  • [nit] skip_group closure uses list instead of list[DriftFinding] for type annotation at src/apm_cli/commands/export_patch.py:337.
    Minor specificity loss; correct behavior.
  • [nit] _export_one returns SkippedEdit | tuple[str, str, str] instead of a named type at src/apm_cli/commands/export_patch.py:412.
    A _MappedEdit frozen dataclass would make the return self-documenting. Suggested: Replace tuple[str, str, str] return with a frozen dataclass _MappedEdit(deployed_path, source_rel, diff_text).

CLI Logging Expert

  • [nit] Final success message is very long -- consider splitting into a success line + an info hint at src/apm_cli/commands/export_patch.py:650.
    Lead with the outcome; 'git apply' instructions are secondary guidance.
  • [nit] logger.success used for 'no edits detected' -- contradictory signal at src/apm_cli/commands/export_patch.py:617.
    Nothing was accomplished; logger.info is more appropriate.

DevX UX Expert

  • [recommended] Add --json flag for machine-readable output.
    export-patch is a prime candidate for scripting. Without --json, consumers must parse human-readable text. Suggested: Add --json / --format=json emitting {patches: [{package, path, base_ref}], skipped: [{file, reason}]}.
  • [recommended] Exit 0 for 'nothing to export' may surprise CI scripts.
    CI scripts that gate on 'did we produce output?' need to check file existence rather than exit code. Suggested: Add --fail-on-empty flag (exits 1 when no patches produced).
  • [nit] Long success message could be shorter with a copy-pasteable example.
  • [nit] Skipped files shown as warnings pollute stderr in quiet pipelines -- consider logger.info with a summary count.

Supply Chain Security Expert

  • [recommended] _strip_userinfo regex misses edge cases with encoded @ (%40) in URLs.
    A malicious lockfile entry could encode credentials as user%3Atoken%40host, bypassing the literal @ match. Suggested: Use urllib.parse.urlparse to reconstruct URL without netloc credentials.
  • [recommended] Path containment only blocks apm_modules/; does not use project path_security guards.
    Diverges from the canonical path safety contract. Suggested: Add ensure_path_within(resolved_out, project_root) or document intentional exemption.
  • [nit] _header_value strips control chars but not newline-like Unicode (U+2028).
    Very low impact since git-apply ignores comment lines.

OSS Growth Hacker

  • [recommended] No cross-link from consumer/producer docs or quickstart to export-patch.
    Feature only discoverable via CLI reference, not at the moment of intent (drift overwrite). Suggested: Add a callout in drift-and-secure-by-default page.
  • [recommended] Docs stop at 'git apply' -- no end-to-end PR workflow.
    The highest-value conversion (patch exporter -> upstream PR opener) is left to the reader. Suggested: Add a short 'Contributing the patch upstream' section (fork, apply, push, gh pr create).
  • [nit] No mention in README feature list.
  • [nit] Command name export-patch could benefit from a shell alias hint in docs.

Auth Expert -- inactive

PR adds no auth flows; _strip_userinfo correctly strips userinfo from scheme-based URLs and passes SSH URLs through unchanged -- no token-leakage vector found.

Doc Writer

  • [blocking] sidebar.order: 14 collides with audit.md (also order: 14) at docs/src/content/docs/reference/cli/export-patch.md.
    Starlight renders two pages at the same sidebar position when order values clash. Suggested: Set sidebar.order to 15 and shift downstream pages.
  • [recommended] audit.md Related section has no link to export-patch at docs/src/content/docs/reference/cli/audit.md.
    A user reading apm audit will not discover export-patch. Suggested: Append: - [\apm export-patch`](../export-patch/) -- export detected drift as upstream-ready patches.`
  • [recommended] Section heading 'See also' differs from audit.md's 'Related' at docs/src/content/docs/reference/cli/export-patch.md.
    Suggested: Rename ## See also to ## Related.
  • [nit] Exit code 1 description bundles unrelated causes into one row.
  • [nit] CHANGELOG entry is verbose; trim to one sentence + attribution.

Test Coverage Expert

  • [recommended] Integration tests cannot be run in this env -- S7 probe inconclusive.
    apm_cli is not importable in the review environment; CI is the authoritative gate.
    Proof (unknown at integration-with-fixtures): tests/integration/test_export_patch_e2e.py::TestExportPatchE2E::test_closed_loop_edit_export_apply_converges -- proves: export-patch produces patches that git-apply can apply cleanly.
  • [nit] No test for --out creating a non-existent directory.
    Proof (missing at integration-with-fixtures): tests/integration/test_export_patch_e2e.py::test_output_dir_created_if_absent -- proves: export-patch creates missing output directory rather than crashing.

Performance Expert -- inactive

export-patch is a one-shot contributor tool with no install/update hot-path impact; the 2MB cap and rglob strategy are adequate for its use case.

This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) removed the panel-review Request an advisory PR review; consumed after review. Not human approval or a merge gate. label Aug 18, 2026
Eden (edenfunf) and others added 5 commits August 19, 2026 16:35
…tream patches (microsoft#2118)

Replays the locked install (same machinery as the audit drift check)
and re-expresses every locally modified managed file as a unified diff
against the package source file that deployed it, one .patch file per
package, applicable with 'git apply' at the base recorded in the patch
header (resolved commit for git deps, version/URL for registry deps).

Reverse mapping is content-addressed: a modified finding is exportable
iff the replayed content is byte-identical (after drift normalization)
to exactly one file in the owning package's source tree. Transformed
deployments (rule-dir frontmatter rewrites, compiled or aggregated
outputs, resolved links), ambiguous matches, local path deps, and
project-local content are skipped with an explicit reason instead of
producing a patch that would not apply.

The command consumes the replay/diff APIs read-only and never mutates
the project tree, cache, or lockfile; patch files are the only output.
Local deletions (unintegrated findings) are never exported since they
do not imply upstream removal intent.

Covered by unit tests for mapping/skip/diff semantics and an e2e
closed loop: edit -> export -> git apply in the package source ->
updated snapshot -> nothing left to export.
Address correctness and robustness gaps found in review of the initial
export-patch implementation:

- Gate exports on raw-bytes cleanliness of the matched source: a CRLF-,
  BOM-, or build-id-bearing source digest-matches in normalized space
  but would reject every hunk at git-apply time. Skipped with an
  accurate reason instead of exporting an unappliable patch.
- Disambiguate colliding patch filenames with a digest suffix and use
  an ASCII-only sanitizer (isalnum accepted Unicode) plus Windows
  reserved-name handling; previously one package's patch could silently
  overwrite another's.
- Deduplicate edits when one source file is deployed to several
  targets: identical edits export as a single diff, divergent edits are
  reported as a conflict instead of emitting clashing hunks.
- Resolve diff-phase targets with apm.yml's explicit target, matching
  the replay's own resolution; auto-detection alone silently hid
  findings for declared targets whose root directory does not exist.
- Split diff lines on newline only: str.splitlines also breaks on bare
  CR / form feed / U+2028 and desyncs hunk counts from git's line model.
- Sanitize lockfile-sourced header fields; an embedded newline could
  break out of the comment block and inject applyable diff content.
- Add an outer exception net (exit 1 with a message instead of a
  traceback), reject --out paths inside apm_modules/, distinguish an
  unparsable lockfile from a missing one, and short-circuit all-local
  lockfiles before the replay.
- Exclude .git/__pycache__/symlinks from the reverse-mapping index and
  track unindexed files (size cap, read errors) so skip reasons never
  misreport them as transformed; write patch files atomically.

Every fix carries a regression test (17 new). Also adds the changelog
entry and syncs the apm-guide command reference and the docs page.
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Private-registry and authenticated-source URLs can embed credentials
(user:token@host); patch files are made to be shared, so source and
resolved-URL header fields now pass through a shared _strip_userinfo
helper before being written. Query-string '@' and plain owner/repo
sources are unaffected (covered by regression tests).

Also appends the PR number to the changelog entry per repo convention.
- Restore the distinct unparsable-lockfile message: LockFile.read now
  raises LockfileFormatError instead of returning None, so the generic
  handler had swallowed the actionable "re-run apm install" guidance.

- Strip URL userinfo up to the authority's LAST '@'. A password holding
  an unencoded '@' (//user:p@ss@host/x) split the userinfo in two, and
  stopping at the first '@' left the secret in the shared patch header.
  An '@' in the path is still untouched.

- Document the eligibility contract precisely. The digest match is in
  normalized space and the source must be normalization-clean; together
  those make the diff's 'a' side byte-identical to the raw source file,
  which is the invariant git apply needs. Requiring raw byte-identity
  between the replayed and source bytes instead would reject legitimate
  build-id-stamped deployments -- normalization is applied symmetrically
  to both sides of the diff, so the stamp never reaches the patch body.
  Locked in by a regression test.

- Docs: move the reference page off the sidebar order that collided with
  audit.md, align the trailing section heading with the house "Related"
  convention, and cross-link export-patch from audit.
tests/unit/test_cli_docs_contract.py enforces that every public command
in the CLI registry is reachable from the reference landing page. The
new command shipped a per-command page but no index entry, so the
contract test failed.
@sergio-sisternes-epam

Copy link
Copy Markdown
Collaborator

PR triage recommendation

ready-for-review

Recommendation only, not merge or scope approval. A responsible
human maintainer must approve. Labels, automated advice, and
silence are not approval.

Linked issue

#2118 (open) -- "[FEATURE] Command to export local spec edit back to package as patch". Automated issue triage recorded ACCEPT and classification (type/feature, area/cli, theme/portability, priority/low) but the issue has no status/accepted. That automated verdict is not maintainer scope approval.

Proposed classification

type/feature, area/cli, theme/portability (PR currently unlabeled; matches #2118). Not adding priority/low (human metadata).

Suggested next action

Rebase onto current main (GitHub reports mergeable_state: dirty), then wait for a CODEOWNERS maintainer (@danielmeppiel, @sergio-sisternes-epam; already requested) to review. This comment is not a request to merge and not a request to run the PR review scheduler.

Suggested PR comment

Thanks @edenfunf -- this PR implements the export-patch loop requested in #2118 (export local edits to APM-managed files as git-apply patches against package source).

What the conversation shows:
- Linked issue #2118 is still open. An automated triage panel proposed ACCEPT; there is no `status/accepted` on the issue, so a human still owns scope.
- Copilot inline threads are resolved. Later commits also address the review-panel blocking sidebar-order collision, audit.md cross-link, and userinfo stripping in patch headers.
- CODEOWNERS remain `@danielmeppiel` and `@sergio-sisternes-epam` (already requested). This triage pass does not add or remove review requests.

Ask: please rebase onto current `main` -- GitHub reports merge conflicts -- then leave the rest for a maintainer review. Advisory only; not acceptance and not merge.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) added triage/recommended Automated advice completed; not human scope approval. type/feature New capability, new flag, new primitive. area/cli CLI command surface, flags, help text (cross-cutting). theme/portability labels Sep 16, 2026
@danielmeppiel

Copy link
Copy Markdown
Collaborator

Eden (@edenfunf), this is accepted (see the #2118 record). To merge today, maintainers will push a small reshape onto this branch, keeping your commits and authorship: rebase on main, write output to patches/<pkg>@<ref>.patch, and add the audit and install hint. --keep (re-applying on install) is tracked separately in #3597. Thank you for the excellent groundwork.


Posted with AI assistance on behalf of Daniel Meppiel (@danielmeppiel).

Resolve the cli.py conflict: main moved heavyweight verbs to the
_LAZY_COMMANDS table, so export-patch is registered there instead of
as an eager import (it drives the drift replay, like audit).

Co-authored-by: Copilot App <[email protected]>
Adopt the output convention from the microsoft#2118 scope record: patches go to
patches/<pkg>@<ref>.patch (the pnpm/Bun layout) so the later --keep
step (microsoft#3597) can register the same artifact unchanged. <ref> is the
locked registry version, else the locked git ref, else the short
commit; '/' maps to '__'. Collision suffixes and the apm_modules/
guard are kept. The --verbose help now matches behavior (skip reasons
always print; addresses suppressed Copilot note on export_patch.py).
Tests pin the naming, the read-only contract (edit, lockfile and
apm.yml untouched), and lazy loading of the verb.

Co-authored-by: Copilot App <[email protected]>
Step 2 of the microsoft#2118 scope: apm audit drift text and apm install now
surface one [i] hint when dependency-managed files carry local edits,
so users can export them before an install overwrites them. Wording
and the read-only install check live in install/local_edits.py; the
check routes recorded hashes through DeploymentLedgerCodec and skips
local-path packages, project-local content, dry-run, apm lock and
global installs. Install still proceeds; nothing is blocked.

Co-authored-by: Copilot App <[email protected]>
Update the export-patch, audit and install references, the consumer
drift page, the apm-guide command table and the CHANGELOG entry (now
one line under Added, ending with the PR number; addresses suppressed
Copilot note on CHANGELOG.md).

Co-authored-by: Copilot App <[email protected]>
The origin/main merge resurrected the already-released --trust-bin
bullet under [Unreleased] and four stale apm-guide rows. Restore both
files to main and keep only this PR's export-patch lines; lead the
CHANGELOG entry with the user benefit. Addresses doc-writer (blocking)
and oss-growth-hacker panel findings.

Co-authored-by: Copilot App <[email protected]>
CI 'Build & Test Shard 2' requires every CLI command in the lifecycle
ledger. export-patch is semantic_na: it only writes patch files and
never transitions installed dependency, lock or manifest state.

Co-authored-by: Copilot App <[email protected]>
Fold the panel and CI findings for the export hint:
- install/local_edits.py owns which owners are exportable upstream
  (is_upstream_package); export-patch, the audit renderer and the
  install check all route through it, so audit no longer points
  local-path package edits at export-patch (doc-writer).
- The install gating moves into hint_local_edits_before_install, so
  pipeline.py stays inside its 1000-line budget (CI Shard 1).
- Path containment uses utils.path_security; source indexing skips
  files reached through symlinked directories (security).
- Import read_manifest_target and _EXCLUDED_DIRS from their canonical
  modules instead of drift.py aliases and a mirrored set (architect).
- Install hint wording: 'next time, run apm export-patch first'
  (devx); drop the unneeded sort (perf).
- Tests: module-level component marker (CI taxonomy ratchet), a real
  'apm install --frozen' integration test for the hint (test
  coverage), and local-path exclusion cases. Mutation-break verified.

Co-authored-by: Copilot App <[email protected]>
Audit, install and drift pages now say the hint covers remote
(non-local) dependencies being installed, and the export-patch exit
table lists a missing apm.yml. Addresses doc-writer panel nits.

Co-authored-by: Copilot App <[email protected]>
Hoist the project-root resolve out of the per-file loop and use
ensure_path_within_resolved, as _index_source_tree already does
(performance delta finding). Align the install reference with the
hint text: this install may overwrite the edits, so export before the
next install (doc-writer delta finding).

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

apm export-patch ships a read-only patch-export step with audit and install hints, so users can send local edits upstream before the next install overwrites them.

panel-mode=full then delta; personas=python-architect,test-coverage-expert,cli-logging-expert,devx-ux-expert,doc-writer,performance-expert,supply-chain-security-expert,auth-expert,oss-growth-hacker,apm-ceo

cc Eden (@edenfunf) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

A full nine-persona panel reviewed the reshaped head, then a delta pass reviewed the folds. The full pass found one blocking-severity item (the main merge had resurrected a released CHANGELOG bullet and four stale apm-guide rows) plus recommended items on path containment, import hygiene, local-path counting, hint wording and docs. Every in-scope item was folded; the delta pass confirmed all of them resolved and raised two small items, also folded. Two items are deferred with clear boundaries (below).

The scope matches the #2118 record: read-only export to patches/<pkg>@<ref>.patch (the pnpm/Bun layout, so --keep in #3597 can register the same file), honest skip reasons, no lockfile or apm.yml writes, and one [i] hint from apm audit drift output and from apm install before it re-syncs edited files. Eden (@edenfunf)'s reverse mapping is unchanged at the core; maintainer folds sit on top with authorship kept.

Dissent. cli-logging-expert suggested a [!] warning for the install hint; declined because the scope record specifies an [i] hint and install never blocks.

Aligned with: Portable by manifest -- pnpm/Bun patch naming, ready for step 3 registration. Secure by default -- containment via utils/path_security, symlinked-dir guard, URL userinfo stripped from headers. Pragmatic as npm -- zero config, plain unified diffs, one-line hints.

Growth signal. The audit and install hints are the discovery channel: users meet apm export-patch at the moment they need it. The CHANGELOG line now leads with that benefit.

Panel summary

Persona B R N Takeaway
Python Architect 0 1 1 Single authority is_upstream_package verified; canonical imports folded; _materialize_install_path promotion deferred.
Test Coverage Expert 0 1 0 Real apm install --frozen integration test added for the hint; closed-loop e2e and 40 unit tests pass.
CLI Logging Expert 0 1 1 CommandLogger conventions followed; audit/install counts now agree; info-vs-warning declined per scope.
DevX UX Expert 0 0 1 Install hint now says "next time, run apm export-patch first".
Doc Writer 1 2 1 Merge artifacts removed; docs scoped to remote dependencies; install.md matches the hint.
Performance Expert 0 2 1 Linear per-install hash check; sort dropped and root resolve hoisted; mtime fast path deferred.
Supply Chain Security Expert 0 1 1 Containment routed through path_security; symlinked-dir traversal closed.
Auth Expert 0 0 0 Auth-neutral; replay is cache-only; headers strip userinfo.
OSS Growth Hacker 0 0 2 CHANGELOG hook folded; index row duplication declined.

B = blocking-severity findings, R = recommended, N = nits (full pass plus delta).
Counts are signal strength, not gates. The maintainer ships.

Top 2 follow-ups

  1. [Python Architect] Promote install.drift._materialize_install_path to a public API -- export_patch.py imports it as a private symbol; renaming touches the agent-plugin-package-projection owner surface, so it is a separate refactor.
  2. [Performance Expert] Add an mtime fast path to the install local-edit check -- it hashes each recorded managed file per install (O(N)); skipping unchanged files needs recorded install state, a lockfile change the scope record excludes.

Recommendation

All in-scope findings are folded and verified on the final head; CI is green there. Land when a maintainer approves, and track the two follow-ups.

Folded in this run

  • (panel) Merge main (CONFLICTING); register export-patch as a lazy CLI verb -- resolved in d488fa7.
  • (panel) Default output patches/<pkg>@<ref>.patch; collision suffix and apm_modules/ guard kept; read-only asserted in e2e -- resolved in 850c48d.
  • (panel) Step 2 [i] hint in apm audit drift text and once in apm install -- resolved in b107d09.
  • (panel) Docs: export-patch, audit, install, drift page, apm-guide, CHANGELOG -- resolved in b9712b3.
  • (panel) Remove merge artifacts (released --trust-bin bullet, stale apm-guide rows) -- resolved in 5f8ff72.
  • (panel) Lifecycle ledger assesses export-patch as semantic_na -- resolved in 1e9de54.
  • (panel) One authority for exportable owners; audit hint skips local-path packages; install gating moved out of pipeline.py; path_security containment; canonical imports; hint wording; integration test; taxonomy marker -- resolved in d0cda2a.
  • (panel) Docs scoped to remote dependencies; exit table lists missing apm.yml -- resolved in fc1cb34.
  • (panel) Resolve project root once; install.md matches the hint -- resolved in 988a30c.
  • (copilot) --verbose help matches behavior -- resolved in 850c48d.
  • (copilot) One-line CHANGELOG entry ending (feat(cli): add export-patch command to export local spec edits as upstream patches #2162) -- resolved in 5f8ff72.

Copilot signals reviewed

  • tests/unit/commands/test_export_patch.py:95 -- LEGIT: non-ASCII literal in test source (resolved in 1dc81b5).
  • src/apm_cli/commands/export_patch.py:253 -- LEGIT: registry URL userinfo could reach the header (resolved in d83b3f2).
  • src/apm_cli/commands/export_patch.py:276 -- LEGIT: source URL userinfo could reach the header (resolved in d83b3f2).
  • CHANGELOG.md -- LEGIT: entry lacked the PR number (resolved in 5f8ff72).
  • src/apm_cli/commands/export_patch.py:468 -- LEGIT: normalized-only match could export transformed files (resolved in 1855d1f).
  • src/apm_cli/commands/export_patch.py:512 (suppressed) -- LEGIT: --verbose help mismatch (resolved in 850c48d).
  • CHANGELOG.md:16 (suppressed) -- LEGIT: multi-line bullet (resolved in 5f8ff72).

Deferred (out-of-scope follow-ups)

Regression-trap evidence (mutation-break gate)

  • TestInstallPipelineHint::test_project_install_shows_hint_once and test_install_points_local_edits_at_export_patch -- deleted the hint_local_edits_before_install call; tests FAILED as expected; guard restored.
  • TestDriftTextHint::test_modified_findings_add_export_hint -- deleted the renderer hint line; test FAILED as expected; guard restored.
  • TestDriftTextHint::test_local_path_package_findings_get_no_hint -- deleted the local-path exclusion; test FAILED as expected; guard restored.
  • test_importing_cli_does_not_load_heavyweight_commands -- restored an eager export_patch import; test FAILED as expected; guard restored.

Lint contract

ruff check and ruff format --check (src, tests, architecture-linter scripts) silent; pylint R0801 10.00/10; lint-auth-signals.sh and lint-architecture-boundaries.sh clean.

CI

All checks green on 93ff9b1: CI, Merge Gate, Spec conformance, CodeQL; license/cla pass (after 2 CI fix iterations: taxonomy/LOC/lifecycle inventory, then a Windows runner cleanup flake re-run).

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#2162 93ff9b1 ship_with_followups 2 19 2 1 green MERGEABLE BLOCKED pending required review

Convergence

2 outer iterations; 1 Copilot round. Final panel stance: ship_with_followups. Review threads: 0 unresolved. Ready for maintainer review.

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-merge-worker. This comment is AI-generated and may contain errors.

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

Labels

area/cli CLI command surface, flags, help text (cross-cutting). triage/recommended Automated advice completed; not human scope approval. type/feature New capability, new flag, new primitive.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Command to export local spec edit back to package as patch

4 participants