-
Notifications
You must be signed in to change notification settings - Fork 155
fix(compile): stabilize __BUILD_ID__ in all compiled outputs #959
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
danielmeppiel
merged 4 commits into
microsoft:main
from
edenfunf:fix/compile-build-id-placeholder
Apr 30, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5b718fc
fix(compile): stabilize __BUILD_ID__ in all compiled outputs
edenfunf 38a18ec
Merge branch 'main' into fix/compile-build-id-placeholder
danielmeppiel ff4ff4b
Merge remote-tracking branch 'origin/main' into fix/compile-build-id-…
edenfunf c59e009
chore(959): clean up imports and ASCII test data
edenfunf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| """Build ID stabilization for compiled outputs. | ||
|
|
||
| Formatters insert ``BUILD_ID_PLACEHOLDER`` (a sentinel marker line) into | ||
| their generated content. Before persisting that content to disk, callers | ||
| must replace the placeholder with a deterministic 12-char SHA256 hash so | ||
| the file stays byte-stable across rebuilds with identical input. | ||
|
|
||
| The hash is computed over the content with the placeholder line *removed* | ||
| so the hash is not self-referential -- it would otherwise change every | ||
| time the placeholder string itself changed. | ||
|
|
||
| This module is the single source of truth for that replacement; all | ||
| compiled-output write sites must route through ``CompiledOutputWriter`` | ||
| (see ``output_writer.py``) which calls this helper. | ||
| """ | ||
|
|
||
| import hashlib | ||
|
|
||
| from .constants import BUILD_ID_PLACEHOLDER | ||
|
|
||
|
|
||
| def stabilize_build_id(content: str) -> str: | ||
| """Replace BUILD_ID_PLACEHOLDER with a deterministic 12-char SHA256 hash. | ||
|
|
||
| Idempotent: returns ``content`` unchanged if no placeholder is present. | ||
| Preserves a trailing newline if the input had one. | ||
| """ | ||
| lines = content.splitlines() | ||
| try: | ||
| idx = lines.index(BUILD_ID_PLACEHOLDER) | ||
| except ValueError: | ||
| return content | ||
|
|
||
| hash_input_lines = [line for i, line in enumerate(lines) if i != idx] | ||
| build_id = hashlib.sha256( | ||
| "\n".join(hash_input_lines).encode("utf-8") | ||
| ).hexdigest()[:12] | ||
|
|
||
| lines[idx] = f"<!-- Build ID: {build_id} -->" | ||
| trailing_nl = "\n" if content.endswith("\n") else "" | ||
| return "\n".join(lines) + trailing_nl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| """Single chokepoint for persisting compiled outputs. | ||
|
|
||
| All compilation targets (single-file AGENTS.md, distributed AGENTS.md, | ||
| CLAUDE.md, GEMINI.md, future targets) MUST route their writes through | ||
| ``CompiledOutputWriter.write``. The writer guarantees: | ||
|
|
||
| 1. ``BUILD_ID_PLACEHOLDER`` is replaced with a deterministic hash | ||
| (see ``build_id.stabilize_build_id``). | ||
| 2. A defensive assertion fails loudly if the placeholder survives | ||
| stabilization, so a future code path that bypasses or breaks | ||
| stabilization cannot silently emit ``__BUILD_ID__`` to disk. | ||
| 3. Parent directories are created. | ||
| 4. The write is atomic (replace-on-rename), so a crash mid-write cannot | ||
| corrupt a pre-existing target file. | ||
|
|
||
| Direct ``Path.write_text`` / ``open(...).write`` on compiled output is a | ||
| contract violation -- adding new write sites without using this writer | ||
| will, by design, miss every cross-cutting concern this writer owns. | ||
|
|
||
| Error contract: | ||
| - ``OSError`` from filesystem operations (mkdir, rename) propagates | ||
| to callers, which typically log + continue. | ||
| - ``RuntimeError`` is raised when the stabilization assertion fails | ||
| (i.e. ``BUILD_ID_PLACEHOLDER`` survived ``stabilize_build_id``). | ||
| This is a programmer error -- never expected in production -- and | ||
| is intentionally NOT caught by callers' ``except OSError`` blocks | ||
| so it surfaces as a loud traceback rather than a silent skip. | ||
| """ | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| from ..utils.atomic_io import atomic_write_text | ||
| from .build_id import stabilize_build_id | ||
| from .constants import BUILD_ID_PLACEHOLDER | ||
|
|
||
|
|
||
| class CompiledOutputWriter: | ||
| """Persist compiled output with cross-cutting concerns applied.""" | ||
|
|
||
| def write(self, path: Path, content: str) -> None: | ||
| final = stabilize_build_id(content) | ||
| if BUILD_ID_PLACEHOLDER in final: | ||
| raise RuntimeError( | ||
| "build_id stabilization bypassed: " | ||
| f"{BUILD_ID_PLACEHOLDER!r} still present after stabilization " | ||
| f"(target={path})" | ||
| ) | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| atomic_write_text(path, final) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| """Atomic file-write primitive for APM. | ||
|
|
||
| Writes go to a temp file in the same directory as the target, then are | ||
| renamed via :func:`os.replace`. A crash mid-write cannot leave a half- | ||
| written destination, and on POSIX the rename is atomic with respect to | ||
| concurrent readers. | ||
|
|
||
| This is the single canonical implementation; both | ||
| ``apm_cli.commands._helpers._atomic_write`` (kept as an alias for | ||
| backward compatibility with existing tests) and | ||
| ``apm_cli.compilation.output_writer`` route through here. | ||
| """ | ||
|
|
||
| import os | ||
| import tempfile | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def atomic_write_text(path: Path, data: str) -> None: | ||
| """Atomically write ``data`` (UTF-8) to ``path``. | ||
|
|
||
| The temp file is created in ``path.parent`` so the eventual | ||
| ``os.replace`` is a same-filesystem rename. Caller is responsible | ||
| for ensuring the parent directory exists. | ||
|
|
||
| On any failure, the temp file is removed and the original target | ||
| file (if any) remains untouched. | ||
| """ | ||
| fd, tmp_name = tempfile.mkstemp(prefix="apm-atomic-", dir=str(path.parent)) | ||
| try: | ||
| with os.fdopen(fd, "w", encoding="utf-8") as fh: | ||
|
edenfunf marked this conversation as resolved.
|
||
| fh.write(data) | ||
| os.replace(tmp_name, path) | ||
| except Exception: | ||
| try: | ||
| os.unlink(tmp_name) | ||
| except OSError: | ||
| pass | ||
| raise | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.