From 7688eb584a8c21cce2a51660374f8a91f5ffcc8f Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 22 Oct 2026 18:54:52 -0700 Subject: [PATCH 1/6] Admit a Fixed Set of Emoji Callout Markers in the Prose Gate (#3376) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3373. The prose gate gains a fixed tier 4 of emoji callout markers, per the maintainer's recorded decision. Each marker is admitted alone or directly followed by VARIATION SELECTOR-16 (U+FE0F). Every other emoji and a U+FE0F not directly after a marker still report `charset-unknown`. Downstream needs no markup. Markers chosen (code point, name): - U+26A0 WARNING SIGN - U+2139 INFORMATION SOURCE - U+2705 WHITE HEAVY CHECK MARK - U+274C CROSS MARK - U+1F4DD MEMO (the note marker) - U+1F4A1 ELECTRIC LIGHT BULB Also: U+2139 is category Ll, so a new `starts_lowercase` helper keeps a marker opening a comment or line from tripping `comment-case`, `comment-wrap`, or `sentence-split`. Docs updated: the `comment-and-doc-style` Skill "Character set" section (source in `.agents/skills/`, generated trees regenerated with `build_dist.py`), `scripts/README.md`, and the gate's own docstring. Open for the maintainer, outside this change's file set: - `GOVERNANCE.md` line 174 lists the tiers as "never legitimate, legitimate next to a number, always legitimate, developer-typed Unicode". Proposed wording: "never legitimate, legitimate next to a number, always legitimate, a fixed set of emoji callout markers, developer-typed Unicode". - `spec/readme-structure.md` line 55 says "the three tiers in GOVERNANCE.md"; proposed: "the tiers". Local review findings left open after the two-round budget (for the review loop): - `CHARSET_CLASSIFY` and the assertion at `tests/test_prose_lint.py` still name only TIER1, TIER2, TIER3. - Tier 4 is not coupled to the Skill text in `TestCommentAndDocStyleSkillCoupling`, nor in the tier-overlap test. - The three `starts_lowercase` call sites are not each pinned by an end-to-end bait. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .agents/skills/comment-and-doc-style/SKILL.md | 10 +- .../.source-digests/comment-and-doc-style | 2 +- .../skills/comment-and-doc-style/SKILL.md | 10 +- .github/actions/prose-gate/prose_lint.py | 26 +++++- .github/skills/comment-and-doc-style/SKILL.md | 10 +- scripts/README.md | 4 +- tests/test_prose_lint.py | 92 ++++++++++++++++++- 7 files changed, 139 insertions(+), 15 deletions(-) diff --git a/.agents/skills/comment-and-doc-style/SKILL.md b/.agents/skills/comment-and-doc-style/SKILL.md index 3dab41740..9cfe3d3e8 100644 --- a/.agents/skills/comment-and-doc-style/SKILL.md +++ b/.agents/skills/comment-and-doc-style/SKILL.md @@ -317,9 +317,15 @@ silent pass, a letter of a recorded name excepted per the bullet below. - **Tier 3, always legitimate.** Scientific and unit symbols whose ASCII form would be a lie: micro (U+00B5), degree (U+00B0), ohm (U+2126), pi (U+03C0), superscript two and three (U+00B2, U+00B3), section (U+00A7). Keep the symbol, never approximate it away or spell it out. +- **Tier 4, emoji callout markers.** Each is admitted alone or followed by VARIATION SELECTOR-16 + (U+FE0F): warning (U+26A0), information (U+2139), check mark (U+2705), cross mark (U+274C), memo + as the note marker (U+1F4DD), and light bulb (U+1F4A1). The gate keeps reporting every other + emoji, and a U+FE0F not directly after a listed marker. A downstream repository needs no markup + to carry one, and an agent may write one only where it is mirroring a callout a developer typed. - **Unicode a developer deliberately typed** stays regardless of tier, such as emoji used for - emphasis or as callout markers. Never strip a developer's own characters, this is developer - authored text and not a license for the agent to add its own. + emphasis. Never strip a developer's own characters, this is developer authored text and not a + license for the agent to add its own. Among emoji the gate admits only the tier-4 markers, so + another developer-typed emoji is classified here before it passes. - **A letter in a recorded name keeps its actual spelling.** A person's or a place's name that a document records as data is written with its own letters and the marks they carry, since folding one to ASCII records a different name. Anywhere else a letter the agent writes that no diff --git a/.claude-plugin/fleet-skills/.source-digests/comment-and-doc-style b/.claude-plugin/fleet-skills/.source-digests/comment-and-doc-style index 41710e01e..313c46d12 100644 --- a/.claude-plugin/fleet-skills/.source-digests/comment-and-doc-style +++ b/.claude-plugin/fleet-skills/.source-digests/comment-and-doc-style @@ -1 +1 @@ -d6793f184056ef85 +ffd0a72a845531f3 diff --git a/.claude-plugin/fleet-skills/skills/comment-and-doc-style/SKILL.md b/.claude-plugin/fleet-skills/skills/comment-and-doc-style/SKILL.md index 3dab41740..9cfe3d3e8 100644 --- a/.claude-plugin/fleet-skills/skills/comment-and-doc-style/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/comment-and-doc-style/SKILL.md @@ -317,9 +317,15 @@ silent pass, a letter of a recorded name excepted per the bullet below. - **Tier 3, always legitimate.** Scientific and unit symbols whose ASCII form would be a lie: micro (U+00B5), degree (U+00B0), ohm (U+2126), pi (U+03C0), superscript two and three (U+00B2, U+00B3), section (U+00A7). Keep the symbol, never approximate it away or spell it out. +- **Tier 4, emoji callout markers.** Each is admitted alone or followed by VARIATION SELECTOR-16 + (U+FE0F): warning (U+26A0), information (U+2139), check mark (U+2705), cross mark (U+274C), memo + as the note marker (U+1F4DD), and light bulb (U+1F4A1). The gate keeps reporting every other + emoji, and a U+FE0F not directly after a listed marker. A downstream repository needs no markup + to carry one, and an agent may write one only where it is mirroring a callout a developer typed. - **Unicode a developer deliberately typed** stays regardless of tier, such as emoji used for - emphasis or as callout markers. Never strip a developer's own characters, this is developer - authored text and not a license for the agent to add its own. + emphasis. Never strip a developer's own characters, this is developer authored text and not a + license for the agent to add its own. Among emoji the gate admits only the tier-4 markers, so + another developer-typed emoji is classified here before it passes. - **A letter in a recorded name keeps its actual spelling.** A person's or a place's name that a document records as data is written with its own letters and the marks they carry, since folding one to ASCII records a different name. Anywhere else a letter the agent writes that no diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index 06aadb520..af208af44 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -3,7 +3,7 @@ markdownlint, cspell, actionlint, and editorconfig-checker all pass on prose that breaks these rules, so nothing enforced them before this script. Rules implemented: - charset Non-ASCII judged against the three tiers the charset rule defines. + charset Non-ASCII judged against the tiers the charset rule defines, tier 4 being emoji markers. charset-unknown Non-ASCII in no tier, bar a Latin letter and its U+0300-U+036F diacritics. semicolon No semicolon in prose, outside a series or labeled pair carrying a comma. dash No spaced hyphen joining or interrupting a sentence. @@ -1087,10 +1087,16 @@ def discover( } ) +# Tier 4 is a fixed set of emoji callout markers, each admitted alone or before VARIATION SELECTOR-16. +# They are warning, information, check mark, cross mark, memo (note), and light bulb. +# Every other emoji flags, and so does a selector not directly after one of these. +TIER4 = frozenset({"\u26a0", "\u2139", "\u2705", "\u274c", "\U0001f4dd", "\U0001f4a1"}) +VARIATION_SELECTOR_16 = "\ufe0f" + CHARSET_CLASSIFY = ( "classify it in ptr727/ProjectTemplate:" ' the comment-and-doc-style skill\'s "Character set" section' - " and prose_lint.py's TIER1, TIER2, or TIER3 table" + " and prose_lint.py's TIER1, TIER2, TIER3, or TIER4 table" ) COMBINING_DIACRITICS = frozenset(chr(c) for c in range(0x300, 0x370)) - { @@ -2053,6 +2059,11 @@ def neighbor(step: int) -> str: ) +def starts_lowercase(text: str) -> bool: + """Whether the text opens with a lowercase letter, a tier-4 marker being no letter.""" + return text[:1].islower() and text[0] not in TIER4 + + def charset_findings(lineno: int, line: str) -> list[tuple[int, str, str]]: """Every non-ASCII character on the line, judged against its tier. @@ -2065,10 +2076,15 @@ def charset_findings(lineno: int, line: str) -> list[tuple[int, str, str]]: """ out: list[tuple[int, str, str]] = [] carrier = False + marker = False for pos, ch in enumerate(line): + after_marker, marker = marker, ch in TIER4 if ch.isascii(): carrier = ch.isalpha() continue + if marker or (after_marker and ch == VARIATION_SELECTOR_16): + carrier = False + continue name = unicodedata.name(ch, f"U+{ord(ch):04X}") category = unicodedata.category(ch) if ( @@ -2401,7 +2417,7 @@ def comment_wrap_findings(path: Path, raw: str, lines: list[str]) -> list[tuple[ and prev_body and not SENT_END.search(prev_body) and not SENT_END.search(prev_whole) - and body[:1].islower() + and starts_lowercase(body) ) if continuation: out.append( @@ -2415,7 +2431,7 @@ def comment_wrap_findings(path: Path, raw: str, lines: list[str]) -> list[tuple[ # A label opening a definition is exempt, since the lowercase word is the name being defined. elif ( leading - and body[:1].islower() + and starts_lowercase(body) and not COMMENT_LABEL.match(body) and not is_tool_directive(body) ): @@ -3248,7 +3264,7 @@ def check_file( p and not SENT_END.search(p) and not p.endswith((":", "-", "|")) - and stripped[0].islower() + and starts_lowercase(stripped) ): out.append( ( diff --git a/.github/skills/comment-and-doc-style/SKILL.md b/.github/skills/comment-and-doc-style/SKILL.md index 3dab41740..9cfe3d3e8 100644 --- a/.github/skills/comment-and-doc-style/SKILL.md +++ b/.github/skills/comment-and-doc-style/SKILL.md @@ -317,9 +317,15 @@ silent pass, a letter of a recorded name excepted per the bullet below. - **Tier 3, always legitimate.** Scientific and unit symbols whose ASCII form would be a lie: micro (U+00B5), degree (U+00B0), ohm (U+2126), pi (U+03C0), superscript two and three (U+00B2, U+00B3), section (U+00A7). Keep the symbol, never approximate it away or spell it out. +- **Tier 4, emoji callout markers.** Each is admitted alone or followed by VARIATION SELECTOR-16 + (U+FE0F): warning (U+26A0), information (U+2139), check mark (U+2705), cross mark (U+274C), memo + as the note marker (U+1F4DD), and light bulb (U+1F4A1). The gate keeps reporting every other + emoji, and a U+FE0F not directly after a listed marker. A downstream repository needs no markup + to carry one, and an agent may write one only where it is mirroring a callout a developer typed. - **Unicode a developer deliberately typed** stays regardless of tier, such as emoji used for - emphasis or as callout markers. Never strip a developer's own characters, this is developer - authored text and not a license for the agent to add its own. + emphasis. Never strip a developer's own characters, this is developer authored text and not a + license for the agent to add its own. Among emoji the gate admits only the tier-4 markers, so + another developer-typed emoji is classified here before it passes. - **A letter in a recorded name keeps its actual spelling.** A person's or a place's name that a document records as data is written with its own letters and the marks they carry, since folding one to ASCII records a different name. Anywhere else a letter the agent writes that no diff --git a/scripts/README.md b/scripts/README.md index 70c33af11..4300b4726 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -38,9 +38,9 @@ Every Docker command has a timeout. The output identifies target counts, phase b ## `prose_lint.py` -Enforces the [`GOVERNANCE.md`][governance] "Documentation Style Conventions" rules that no linter checks: non-ASCII judged against the charset rule's three tiers, a semicolon in prose, a spaced hyphen joining or interrupting a sentence, a duplicated consecutive word, a British spelling, and the shape of a comment's prose. It carries one rule from elsewhere in that document, `home-path`, which comes from "Representative Data in Agent-Authored Text" and catches an absolute home path naming a real account. That rule closes the pattern-detectable sliver of its section and nothing beyond it, since the exposure the section exists for was name-shaped and no pattern finds a name. `OPERATIONS.md` is exempt because its runbooks carry the literal path an operator types. +Enforces the [`GOVERNANCE.md`][governance] "Documentation Style Conventions" rules that no linter checks: non-ASCII judged against the charset rule's tiers, a semicolon in prose, a spaced hyphen joining or interrupting a sentence, a duplicated consecutive word, a British spelling, and the shape of a comment's prose. It carries one rule from elsewhere in that document, `home-path`, which comes from "Representative Data in Agent-Authored Text" and catches an absolute home path naming a real account. That rule closes the pattern-detectable sliver of its section and nothing beyond it, since the exposure the section exists for was name-shaped and no pattern finds a name. `OPERATIONS.md` is exempt because its runbooks carry the literal path an operator types. -The tiers decide by context rather than by a flat ban. Tier 1 carries no meaning its ASCII form loses and always flags. Tier 2 is an operator, kept next to a figure or another operator and replaced between words, so a threshold table reads as the range it is. Tier 3 is a unit or scientific symbol whose ASCII form would be a lie and never flags. Developer-typed characters such as emoji are preserved regardless of tier, and an un-tiered one other than a Latin letter or a U+0300-U+036F diacritic it carries is still reported as `charset-unknown` until it is classified. +The tiers decide by context rather than by a flat ban. Tier 1 carries no meaning its ASCII form loses and always flags. Tier 2 is an operator, kept next to a figure or another operator and replaced between words, so a threshold table reads as the range it is. Tier 3 is a unit or scientific symbol whose ASCII form would be a lie and never flags. Tier 4 is a fixed set of emoji callout markers (warning, information, check mark, cross mark, memo, light bulb), each admitted alone or followed by VARIATION SELECTOR-16, and a U+FE0F anywhere else still flags. Developer-typed characters such as other emoji are preserved by the rule but not admitted by the gate, and an un-tiered one other than a Latin letter or a U+0300-U+036F diacritic it carries is still reported as `charset-unknown` until it is classified. A character in no tier is a `charset-unknown` finding rather than a silent pass, since a gate that allows whatever it does not recognize stops gating as the character set grows. A Latin letter, with any diacritic from the U+0300-U+036F combining block that it carries, is the exception and never flags, since it may spell a recorded name, which the charset rule says keeps its actual spelling, and nothing tells a name from a word by its characters. A letter of another script, a compatibility form such as a ligature, any other mark, and a diacritic standing alone still flag, so the gate covers the Latin part of that rule and nothing wider. Classifying one is a fleet-law edit, so the whole-tree step that reports the backlog is warn-only, while the pull request gate blocks on one the change itself introduces. Which letters count as Latin follows the Unicode data of the Python running the gate, so a letter newer than that data is still reported. diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 68c5d5f7e..312117649 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -219,7 +219,7 @@ def test_an_unclassified_character_names_where_to_classify_it(self) -> None: [(_, kind, message)] = prose_lint.check_file(path, {"charset-unknown"}) self.assertEqual("charset-unknown", kind) self.assertIn('the comment-and-doc-style skill\'s "Character set" section', message) - self.assertIn("prose_lint.py's TIER1, TIER2, or TIER3 table", message) + self.assertIn("prose_lint.py's TIER1, TIER2, TIER3, or TIER4 table", message) self.assertIn("classify it in ptr727/ProjectTemplate:", message) self.assertNotIn("GOVERNANCE.md", message) @@ -246,6 +246,85 @@ def test_a_latin_named_symbol_is_still_reported(self) -> None: self.kinds("a \u271d here\n", {"charset", "charset-unknown"}), ) + def test_a_callout_marker_is_admitted_alone_or_with_variation_selector_16(self) -> None: + """Tier 4 admits the documented emoji markers, each bare or followed by VARIATION SELECTOR-16.""" + rules = {"charset", "charset-unknown"} + documented = {0x26A0, 0x2139, 0x2705, 0x274C, 0x1F4DD, 0x1F4A1} + self.assertEqual(documented, {ord(ch) for ch in prose_lint.TIER4}) + for ch in prose_lint.TIER4: + with self.subTest(codepoint=f"U+{ord(ch):04X}"): + self.assertEqual([], self.kinds(f"> {ch} **Note:** text\n", rules)) + self.assertEqual([], self.kinds(f"> {ch}\ufe0f **Note:** text\n", rules)) + + def test_the_reported_warning_pair_is_admitted(self) -> None: + """The pair that rendered as a finding in the original report now passes.""" + line = "> \u26a0\ufe0f **Warning:** Example callout.\n" + self.assertEqual([], self.kinds(line, {"charset", "charset-unknown"})) + + def test_a_non_callout_emoji_is_still_reported_even_with_variation_selector_16(self) -> None: + """Only the fixed set is admitted, so any other emoji flags, selector or not.""" + rules = {"charset", "charset-unknown"} + for ch in ("\U0001f680", "\u2764", "\u2728", "\u2603"): + with self.subTest(codepoint=f"U+{ord(ch):04X}"): + self.assertNotIn(ch, prose_lint.TIER4) + self.assertEqual(["charset-unknown"], self.kinds(f"a {ch} here\n", rules)) + self.assertEqual( + ["charset-unknown", "charset-unknown"], + self.kinds(f"a {ch}\ufe0f here\n", rules), + ) + + def test_a_marker_opening_a_comment_or_line_is_not_a_lowercase_letter(self) -> None: + """U+2139 is category Ll, yet a marker opening a comment is no lowercase sentence start.""" + info = chr(0x2139) + self.assertTrue(info.islower()) + self.assertFalse(prose_lint.starts_lowercase(f"{info}\ufe0f Run setup first.")) + self.assertTrue(prose_lint.starts_lowercase("run setup first.")) + + def test_a_marker_opening_a_line_is_no_continuation_or_lowercase_start(self) -> None: + """Each caller of the lowercase test treats a marker as a sentence start, end to end.""" + info = chr(0x2139) + comment_rules = {"comment-wrap", "comment-case"} + for opener in (info, f"{info}\ufe0f"): + with self.subTest(opener=opener): + self.assertEqual( + [], + self.kinds( + f"# A sentence that keeps\n# {opener} Run setup first.\n", + comment_rules, + "bait.py", + ), + ) + self.assertEqual( + [], self.kinds(f"# {opener} Run setup first.\n", comment_rules, "bait.py") + ) + self.assertEqual( + [], + self.kinds( + f"A sentence that keeps\n{opener} Run setup first.\n", {"sentence-split"} + ), + ) + self.assertEqual( + ["comment-wrap"], + self.kinds("# A sentence that keeps\n# going on.\n", comment_rules, "bait.py"), + ) + self.assertEqual( + ["sentence-split"], + self.kinds("A sentence that keeps\ngoing on.\n", {"sentence-split"}), + ) + + def test_a_stray_variation_selector_16_is_still_reported(self) -> None: + """The selector is admitted only directly after a marker, never alone or after a gap.""" + rules = {"charset", "charset-unknown"} + marker = chr(0x26A0) + for text in ( + "stray \ufe0f here", + f"{marker} \ufe0f here", + f"{marker}\ufe0f\ufe0f here", + "\ufe0f" + marker + " here", + ): + with self.subTest(text=text): + self.assertEqual(["charset-unknown"], self.kinds(f"{text}\n", rules)) + def test_a_mark_that_spells_no_name_is_still_reported(self) -> None: """A mark that is no diacritic, or that no Latin letter carries, is reported, not passed.""" rules = {"charset", "charset-unknown"} @@ -364,11 +443,22 @@ def test_tier_three_is_allowed_rather_than_replaced(self) -> None: self.assertNotIn(chr(cp), prose_lint.TIER1) self.assertNotIn(chr(cp), prose_lint.TIER2) + def test_tier_four_markers_are_exactly_the_skill_text(self) -> None: + """The markers the rule text names, less the selector it admits, are the gate's set.""" + m = re.search(r"^- \*\*Tier 4,(.*?)(?=^- \*\*)", self.section, re.MULTILINE | re.DOTALL) + if m is None: + self.fail("the Tier 4 bullet moved, so the parse is blind") + named = {int(h, 16) for h in re.findall(r"U\+([0-9A-Fa-f]{4,6})\b", m.group(1))} + named.discard(ord(prose_lint.VARIATION_SELECTOR_16)) + self.assertEqual(named, {ord(ch) for ch in prose_lint.TIER4}) + def test_the_tiers_do_not_overlap(self) -> None: t1, t2, t3 = set(prose_lint.TIER1), set(prose_lint.TIER2), set(prose_lint.TIER3) + t4 = set(prose_lint.TIER4) self.assertEqual(set(), t1 & t2) self.assertEqual(set(), t1 & t3) self.assertEqual(set(), t2 & t3) + self.assertEqual(set(), t4 & (t1 | t2 | t3)) class TestDupword(BaitCase): From adf3bf84ac47238724344fbb30d53148fbc7377d Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 22 Oct 2026 19:05:38 -0700 Subject: [PATCH 2/6] Resolve the Open Review Findings on the Subprocess-Failure Rule (#3377) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Resolves the three open review findings on the `CODESTYLE.md` "Operations and Failure Messages" subprocess-failure bullet. The bullet stays a rule plus its reason, with no list of tools or cases. - **Finding 1, the apparent conflict with "Command-Line Arguments".** A closing sentence states that a test asserting a script's output, such as the refusal "Command-Line Arguments" requires, verifies that output rather than classifying a failure. It names a test, so a runtime fallback branching on a refusal's prose cannot claim it. The head rule now forbids classifying by the *prose* of a message, so the notation that marks a printed code is not read as forbidden wording. - **Finding 2, a printed status code located by the text around it.** Maintainer ruling on #3367 (option B): a printed code is read by the notation that marks it, and a match finding none counts as an unexpected failure. The reason sentence's stability claim now names the code's value. - **Finding 3, the pronoun and the quantifier.** "split it into real operations, one per failure" becomes: where one command's status code cannot separate the failures its caller handles differently, give each expected failure its own real operation, and where no such operation exists, treat the failure as unexpected. That names what gets an operation, covers two expected failures sharing one code, and gives the case with no operation the same fail-closed outcome as a printed code with no match. No generated include carries this bullet. `python-codestyle` and `shell-codestyle` include only `CODESTYLE.md > Command-Line Arguments`, so `scripts/build_dist.py --check` passes with nothing to regenerate. ## Rulings Recorded - Maintainer ruling on #3367 finding 2: option B, the notation sentence above. - Maintainer ruling on #3365: line 34, "Let the real operation be the check", stays unchanged. A capability check answered by its own exit status counts as a real operation of its own, which the follow-up change for #3365 applies. - Declined, a local pass's finding that "a status code's value does not [vary]" overstates, since tools sometimes change exit codes. That trade-off was already accepted on #3366, and the clause stays. - Dropped "and status code" from the remedy, as a local pass found. Separate operations are already told apart by which command failed, so a distinct code is not required. ## Local Review Findings Still Open The local pass's edit budget for this push is spent, so this goes to the review loop for an outcome before merge. 1. `introduced`: "give each expected failure its own real operation" could be read as allowing an existence test such as `test -e src` before a copy, which line 34 forbids. Sites that still classify by prose are filed as #3378 (`spec/audit.py`, `scripts/skills_install.py`), beside #3365 for `scripts/pr_review.py`. Closes #3367 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Summary by CodeRabbit * **Documentation** * Clarified how subprocess failures are classified, including how status codes and missing codes are handled. * Specified when commands should be split based on whether their status codes distinguish failures requiring different handling. --------- Co-authored-by: Claude Opus 5.5 --- CODESTYLE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CODESTYLE.md b/CODESTYLE.md index 4ff129457..4b3b10063 100644 --- a/CODESTYLE.md +++ b/CODESTYLE.md @@ -32,7 +32,7 @@ Each language defines a **clean-compile** verification: the combination of build ### Operations and Failure Messages - **Let the real operation be the check, not a prediction of it.** Attempt the read, the write, or the call itself, and turn its failure into a clean refusal. Do not probe first with an existence, type, or permission test. Where the operation could block or succeed on the wrong kind of target, judge what it opened instead. A probe is a second model of the operation. It misjudges each case its author did not foresee, such as a dangling link, a link loop, or a platform's own permission model. The operation cannot disagree with itself. -- **Classify a subprocess failure by which command failed and the status code it reports, never by the wording of its message.** That wording varies by tool version and locale, and a status code does not, even one printed inside the message. Where one command's status code cannot separate an expected failure from an unexpected one, split it into real operations, one per failure. +- **Classify a subprocess failure by which command failed and the status code it reports, never by the prose of its message.** That prose varies by tool version and locale, and a status code's value does not, even one printed inside the message. A printed code is read by the notation that marks it, and a match finding none counts as an unexpected failure. Where one command's status code cannot separate the failures its caller handles differently, give each expected failure its own real operation. Where no such operation exists, treat the failure as unexpected. A test asserting a script's output, such as the refusal "Command-Line Arguments" requires, verifies that output rather than classifying a failure. - **A failure message states the error, the path or other target, and the remedy, and claims nothing about the state the failure left.** The error the operation raised is the one fact the code holds at that point. A description of what the failure left behind is a prediction. It reads false once an unforeseen state reaches the message, such as a file written in full that then fails to close. A remedy such as "fix what it names, then re-run" needs no such claim. ### Command-Line Arguments From b27d693d3fdc07b36aca7147451b5975b3a054c4 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 22 Oct 2026 19:17:29 -0700 Subject: [PATCH 3/6] Update Character Set Tier Summaries for the Emoji Callout Tier (#3383) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3379. The GOVERNANCE.md "Character Set" pointer now lists the fixed set of emoji callout markers between the always-legitimate tier and developer-typed Unicode, matching the `comment-and-doc-style` Skill. The `spec/readme-structure.md` bullet now points at that Skill's "Character set" section instead of a GOVERNANCE.md section that holds no tiers. Its trailing clause about the em dash and spaced hyphen ban stays true, since the Skill section states both bans. A tree grep outside reports/ found no other summary counting or listing the tiers stale. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 5.5 --- GOVERNANCE.md | 2 +- spec/readme-structure.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 249ac6f95..14e4cc562 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -171,7 +171,7 @@ No comment, no docstring, and no instruction document names an issue, a pull req ### Character Set -The full ASCII tier system (never legitimate, legitimate next to a number, always legitimate, developer-typed Unicode), the letters of a recorded name keeping their actual spelling, and the semicolon and spaced-hyphen rules are in the `comment-and-doc-style` Skill referenced above. +The full ASCII tier system (never legitimate, legitimate next to a number, always legitimate, a fixed set of emoji callout markers, developer-typed Unicode), the letters of a recorded name keeping their actual spelling, and the semicolon and spaced-hyphen rules are in the `comment-and-doc-style` Skill referenced above. ### Line Endings diff --git a/spec/readme-structure.md b/spec/readme-structure.md index 3f7a5fe0d..c0acb2dfd 100644 --- a/spec/readme-structure.md +++ b/spec/readme-structure.md @@ -52,7 +52,7 @@ A **retired badge service** is the one exception to that floor, and the audit re - Write in the current state, present tense, so the reader needs no knowledge beyond what they are reading (GOVERNANCE.md Documentation Style). - One logical paragraph per line, with no hard-wrap. - Title-case headings with lowercase short bind words. -- US English and straight quotes. Judge a non-ASCII character against the three tiers in GOVERNANCE.md "Character Set", and restructure a sentence rather than joining its clauses with an em dash or with a spaced hyphen, which that section bans in the same terms. +- US English and straight quotes. Judge a non-ASCII character against the tiers in the `comment-and-doc-style` Skill's "Character set" section, and restructure a sentence rather than joining its clauses with an em dash or with a spaced hyphen, which that section bans in the same terms. - Verify every quantitative claim (counts, versions, supported platforms) against current code. - A project README describes only that project, with no cross-repo references and no template or inheritance framing. - Reference-style links only: every URI is a reference link defined at the bottom of the file, grouped and named per "Reference Links" below. The auto-generated Table of Contents is the one exception, keeping inline anchor links. From b1c593e56d84563c2a846cc59727633a842e14b9 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 22 Oct 2026 19:37:52 -0700 Subject: [PATCH 4/6] Ask gh Whether It Takes the Escape Flag Instead of Matching Its Refusal (#3386) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Moves the `scripts/pr_review.py` job-log read onto the `CODESTYLE.md` "Operations and Failure Messages" rule, as merged in #3377. A subprocess failure is classified by which command failed and the status code it reports, never by the prose of its message. - `gh_rest` used to retry a raw read without `--allow-escape-sequences` when its stderr held `unknown flag: --allow-escape-sequences`. `gh` exits 1 for an unknown flag and for an HTTP error alike, so the read's own status could not tell them apart. - New `gh_takes_escape_flag()` runs `gh api --allow-escape-sequences --help` once per process (`functools.cache`). Its exit status alone decides whether the read passes the flag. It reads nothing from GitHub. - A failed read is returned as it is, whatever its message says, with no retry. A non-log read never runs the probe. Measured on real binaries: the probe exits 0 on gh 2.103.0, and exits 1 on gh 2.90.0, which predates the flag. Neither needs the network. ## Tests `TestRawLogRead` clears the probe's cache in `setUp` and in `addCleanup`, the way `GqlCase.setUp` clears the other memoized helpers. It covers: - an older `gh` reading without the flag - a newer `gh` reading with it - the probe running once for two reads - a non-log read never asking - `test_another_failure_is_not_retried`, which keeps its intent. A failed read after the probe is returned unchanged after one attempt, including one whose stderr says `unknown flag`. `python3 -m unittest tests.test_pr_review` passes all 954 tests. ## Rulings Recorded - Maintainer ruling on #3365: option (a), a cached capability probe with its exit code as the answer. Line 34 of `CODESTYLE.md`, "Let the real operation be the check", stays unchanged, and the probe counts as a real operation of its own. The other sites of the same class are tracked in #3378. Closes #3365 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- scripts/pr_review.py | 23 +++++++++++++----- tests/test_pr_review.py | 53 +++++++++++++++++++++++++++++++++++------ 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index d50bfd0c3..403e6c23c 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -6275,13 +6275,24 @@ def gh_rest(path: str, jq: str | None = None, raw: bool = False) -> subprocess.C `raw` is for a job log, which carries terminal escape sequences that `gh` 2.97 and later refuse to print without `--allow-escape-sequences`. An older `gh` has no such flag and - prints the log as it is, so a run refused on the flag is retried without it. + prints the log as it is, so the flag is passed only where `gh_takes_escape_flag` says so. """ - base = ["gh", "api", path] + (["--jq", jq] if jq else []) - proc = _gh_run(base + (["--allow-escape-sequences"] if raw else []), raw) - if raw and proc.returncode != 0 and "unknown flag: --allow-escape-sequences" in proc.stderr: - proc = _gh_run(base, raw) - return proc + argv = ["gh", "api", path] + (["--jq", jq] if jq else []) + if raw and gh_takes_escape_flag(): + argv.append("--allow-escape-sequences") + return _gh_run(argv, raw) + + +@functools.cache +def gh_takes_escape_flag() -> bool: + """Whether this `gh` accepts `--allow-escape-sequences`, answered by its own exit status. + + The read itself exits 1 both for an unknown flag and for an HTTP error, so its status cannot + say which happened. Asking for `gh api --help` with the flag is an operation of its own whose + status answers that one question, and it reads nothing from GitHub. Memoized, since the + installed `gh` does not change within one run. + """ + return _gh_run(["gh", "api", "--allow-escape-sequences", "--help"], False).returncode == 0 def _gh_run(argv: list[str], raw: bool) -> subprocess.CompletedProcess: diff --git a/tests/test_pr_review.py b/tests/test_pr_review.py index 964ec4e9f..c088d6d47 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -3881,20 +3881,59 @@ def test_a_round_stating_coverage_on_the_head_carries_nothing(self) -> None: class TestRawLogRead(unittest.TestCase): """A job log read keeps working on a `gh` older than the escape-sequence flag.""" - def test_an_unknown_flag_is_retried_without_it(self) -> None: - refused = subprocess.CompletedProcess([], 1, "", "unknown flag: --allow-escape-sequences") + LOG = "repos/o/r/actions/jobs/1/logs" + PROBE = ("gh", "api", "--allow-escape-sequences", "--help") + + def setUp(self) -> None: + """The probe is memoized for the run, so each case starts from an unasked `gh`.""" + super().setUp() + pr_review.gh_takes_escape_flag.cache_clear() + self.addCleanup(pr_review.gh_takes_escape_flag.cache_clear) + + def test_an_older_gh_reads_the_log_without_the_flag(self) -> None: + refused = subprocess.CompletedProcess([], 1, "", "") read = subprocess.CompletedProcess([], 0, "the log", "") with mock.patch.object(pr_review, "_gh_run", side_effect=[refused, read]) as run: - proc = pr_review.gh_rest("repos/o/r/actions/jobs/1/logs", raw=True) + proc = pr_review.gh_rest(self.LOG, raw=True) self.assertEqual("the log", proc.stdout) - self.assertIn("--allow-escape-sequences", run.call_args_list[0].args[0]) + self.assertEqual(list(self.PROBE), run.call_args_list[0].args[0]) self.assertNotIn("--allow-escape-sequences", run.call_args_list[1].args[0]) + def test_a_newer_gh_reads_the_log_with_the_flag(self) -> None: + accepted = subprocess.CompletedProcess([], 0, "usage", "") + read = subprocess.CompletedProcess([], 0, "the log", "") + with mock.patch.object(pr_review, "_gh_run", side_effect=[accepted, read]) as run: + proc = pr_review.gh_rest(self.LOG, raw=True) + self.assertEqual("the log", proc.stdout) + self.assertIn("--allow-escape-sequences", run.call_args_list[1].args[0]) + def test_another_failure_is_not_retried(self) -> None: - failed = subprocess.CompletedProcess([], 1, "", "HTTP 404") - with mock.patch.object(pr_review, "_gh_run", return_value=failed) as run: - pr_review.gh_rest("repos/o/r/actions/jobs/1/logs", raw=True) + """A failed read is returned as it is, whatever its message says, after one attempt.""" + accepted = subprocess.CompletedProcess([], 0, "usage", "") + for stderr in ("gh: Not Found (HTTP 404)", "unknown flag: --allow-escape-sequences"): + with self.subTest(stderr=stderr): + pr_review.gh_takes_escape_flag.cache_clear() + failed = subprocess.CompletedProcess([], 1, "", stderr) + with mock.patch.object(pr_review, "_gh_run", side_effect=[accepted, failed]) as run: + proc = pr_review.gh_rest(self.LOG, raw=True) + self.assertIs(failed, proc) + self.assertEqual(2, run.call_count) + + def test_the_probe_runs_once_per_process(self) -> None: + accepted = subprocess.CompletedProcess([], 0, "usage", "") + read = subprocess.CompletedProcess([], 0, "the log", "") + with mock.patch.object(pr_review, "_gh_run", side_effect=[accepted, read, read]) as run: + pr_review.gh_rest(self.LOG, raw=True) + pr_review.gh_rest(self.LOG, raw=True) + probes = [c for c in run.call_args_list if c.args[0] == list(self.PROBE)] + self.assertEqual(1, len(probes)) + + def test_a_read_that_is_not_a_log_never_asks(self) -> None: + read = subprocess.CompletedProcess([], 0, "{}", "") + with mock.patch.object(pr_review, "_gh_run", return_value=read) as run: + pr_review.gh_rest("repos/o/r") self.assertEqual(1, run.call_count) + self.assertNotIn("--allow-escape-sequences", run.call_args.args[0]) class TestFileTableCarriesForward(CarryCase): From d4c283fc9a76689fd2f69718d00ee7f753198f61 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 22 Oct 2026 20:44:40 -0700 Subject: [PATCH 5/6] Close Export, Xargs, Env, and Launcher Allow Gaps in the Write Guard (#3390) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Closes the write guard's export, xargs, env, and launcher allow gaps for #3336, #3339, #3340, #3343, #3347, the open items of #3307, and #3337 under the maintainer's ruling recorded on that issue. The closing keywords go on the `develop -> main` promotion pull request. This change only closes allow gaps: no command develop's guard denies becomes allowed. - **One export primitive (#3339, #3340, #3347).** `_export_events` reads an `export`, a `declare`, `typeset`, or `local` given `-x`, and a bare-name export. A bare-name export reads every value a plain assignment, `declare`, `typeset`, `local`, or `readonly` gave that name. A plain assignment to an exported name exports too, and so does one after `set -a` or `set -o allexport`. `_exported_states`, `_env_assignments`, `_reading_env_config_values`, and `_wrapper_env_groups` all read it. Where a loop or a function may run a git word after a later export, every export is read. - **Run-time `GIT_DIR` (#3343).** A mutating git command whose `GIT_DIR`, `GIT_WORK_TREE`, `--git-dir`, or `--work-tree` value holds a run-time word other than `$HOME` fails closed. - **Launchers (#3340, #3347).** Behind a launcher the guard does not know, an assignment after an `env` or a `sudo` is read beside the shell's state rather than over it. That holds for `GIT_DIR`, config values, and `GH_REPO`, so `uv run env GH_REPO=stranger/example gh pr comment ...` is denied, and `find ./env -name GIT_DIR=... -exec git ...` cannot hide an export. - **xargs (#3336, #3307, #3340, #3347).** These now fail closed: a gh write that `xargs` runs, a bare `gh`, a `gh api` call it appends to, and a bare `git`. So do a replace string in git's subcommand, a `-c` value, or a mutating command's global options, and a shell string xargs fills that runs git or gh. The exception is a written-out gh write fed only inert literal words, as in `printf 5 | xargs gh pr comment --body x`. The config-change scan reads a `git config` xargs appends to, a replace string in the command word, and the replace option inside a cluster such as `-0I{}` or as the BSD `-J`. - **Config-change scan (#3307, #3340).** A wrapper body is read with the same per-word predicate as the outer command, `_word_may_change_config`, and a named coproc's group is read. A push denied because an earlier command may rewrite its remote config says so, and asks for the push as its own command. - **Outer-expanded wrapper bodies (#3337).** A double-quoted wrapper body holding a `$` or backtick word the outer shell expands fails closed where the body runs git or gh. A body running neither keeps its verdict, so `bash -c "cd $DIR && ls"` is allowed, and so is the issue's own `sh -c "echo $B"` example. - READMEs updated to match. ## Verification - `python3 host-setup/agent-safety/claude/gh-write-guard.py --selftest`: `SELFTEST PASS`, 1868 checks, 86 of them new: 59 denies, 26 allow controls, and one check that the config-change deny names its cause. - ruff format and check, mypy, and `prose_lint.py --diff` are clean, and the pre-commit and pre-push hooks passed. `host-setup/agent-safety/claude/test_install.py` passed 162 of 163 in a full run. The one failure, `test_a_write_cut_short_is_not_read_back_as_a_hand_edit`, passed when rerun alone, on this branch and on develop's tree alike. ### Develop-versus-branch differential | Corpus | Checks | Flips | | --- | --- | --- | | develop's own self-test corpus | 1782 | 0, every one passes with develop's verdict | | constructed probes | 261 | 100, all allow -> deny | The probes cover each issue's own commands, near variants of each, and controls. They span export forms, `set` flags, functions and loops, launchers with `env`, `sudo`, and `./env` paths, xargs option spellings and input producers, gh reads and writes, `git config` and `git remote` reads under xargs, named coprocs, and single- and double-quoted wrapper bodies. No probe flips from deny to allow, so there is no deny-to-allow flip to explain. ### Revert proof Each new case was classified by develop's guard, which is this change reverted, with the self-test's own seams. Every one of the 55 new deny cases that develop allows comes back `allow` there, so each fails without the fix. Four further new denies are regression guards for readings a review round found broken at an intermediate head, and develop denies all four. The config-change reason check fails on develop too, whose deny names the push's repository as undetermined. Every new allow control gives the same verdict on develop. ### Local strict review Six passes at the `frontier` tier. Passes 1 and 2 each raised findings answered in their own commit: a `./sudo` config-value override, several near variants, two over-denials, a consolidation of `_runs_git`, and narrowed README claims. Pass 3 was recorded at the opening head with its edit budget spent, so its introduced findings were listed here. Each is now fixed, and passes 4 to 6 reviewed those fixes. A seventh pass reviewed the fix for CodeRabbit's `flock -c` and `watch` finding and is recorded at the current head with no findings. **Local-review findings listed at the opening push (pass 3), each now fixed** - `introduced`: `_wrapper_dir_prefixes` reads a wrapper's prefix from `_wrapper_env_groups`, where a `./sudo` path's `-name GIT_DIR=...` argument joined the group and replaced an earlier prefix. `GIT_DIR=/example/primary/.git find ./sudo -name GIT_DIR=/example/scratch/.git -exec sh -c 'git reset --hard' \;` was denied on develop and allowed at the opening head. Fixed in 4e4649fc: the pre-launcher group is read beside it, as `_git_dir_rereading` does. b9bc9ddf also reads each GH_REPO value into a wrapper body on its own, closing the same collapse on the gh side. - `introduced`: `_xargs_reads_inert` ignored a redirection of xargs's own stdin, as in `printf 5 | xargs gh pr comment --body x <<< '-R stranger/example 9'`, which develop allows too. Fixed in 4e4649fc and b9bc9ddf: any input redirection in xargs's simple command voids the exception. - `introduced`: an inert word can be a bare owner after a trailing `--org`, `--owner`, `--target-owner`, or `-o`, as in `printf stranger | xargs gh secret set TOKEN --body x --org`, which develop allows too. Fixed in 4e4649fc and b9bc9ddf: an owner or repo flag ending the command, or holding the replace string, voids the exception. - `introduced`: BSD `-J` splices every input word, where `-I` replaces with one line, so the endpoint-only and read-only global-option exemptions did not hold under `-J`. Develop allows the shapes too. Fixed in 4e4649fc: a `-J` voids both exemptions. - `pre-existing`, filed: #3387 (a replace string as the command word in the other run-time readers), #3388 (rule 6's ref-checkout exemption under xargs), and #3389 (a git variable set by `printf -v`, `read`, `for`, or `mapfile`). Issues filed along the way: #3380 (over-denial of a quoted heredoc's data), #3381 (a coproc named `git`), #3382 (decision: a quoted run-time `-C` value), #3384 (an unquoted heredoc fed to a shell), and #3385 (decision: a shell string that is only an xargs replace string). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- host-setup/agent-safety/README.md | 63 +- host-setup/agent-safety/claude/README.md | 2 +- .../agent-safety/claude/gh-write-guard.py | 1413 ++++++++++++++--- 3 files changed, 1262 insertions(+), 216 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 7e27b3005..a2468a361 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -85,7 +85,18 @@ text says, because the harm it covers was never in the text. may not, every value the command sets is read as reaching its gh write. A run-time segment past a literal owner in a `gh api` endpoint is compared by that owner, though it may hold a `..` segment. A gh write or a `gh api` call nested in wrappers past the reading cap is denied. - None of requirements 1 to 3 can read it there. + None of requirements 1 to 3 can read it there. A gh write that `xargs` runs fails closed too. + `xargs` appends the words it reads, such as a `--repo`, or puts them where its replace string + sits. The exception is a write whose command and subcommand are written out, fed only inert + words. Those come from a pipe out of an `echo` or `printf` of literal words. Each such word + holds only letters, digits, `_`, and `.`, as in `printf 5 | xargs gh pr comment --body x`. A + redirection of the command's input voids the exception. So does a word that lands as an owner + or repo flag's value, as after a trailing `--org`, since an owner name is inert too. A + gh naming no subcommand under `xargs` is denied. So is one whose path words hold the replace + string, and a `gh api` call `xargs` appends to. So is a `gh api` call holding the replace + string in any word but its endpoint. Behind a launcher the hook does not know, an `env` or a + `sudo` may pass a `GH_REPO`, as in `uv run env GH_REPO=...`. That value is read beside the + shell's own rather than dropped. 4. **A git operation that would only succeed by bypassing an active branch rule is denied**: a direct push to a branch whose rules require a pull request, a force-push where history is protected, a delete where deletion is blocked, or an explicit-bypass flag (`--admin` on a merge, @@ -176,6 +187,14 @@ text says, because the harm it covers was never in the text. `--version` that ends git there. A redirection target spanning several words on a push or a commit is denied, and so is a comment among a push's words. A push, a commit, or a `gh pr merge` that `xargs` runs is denied, since `xargs` appends words the hook does not read. + So is a git word with no subcommand that `xargs` runs, since its input gives the subcommand. + So is an `xargs` replace string in git's subcommand or a `-c` value, or in the global options + of one that may mutate. Under the BSD `-J`, which splices in each word as a word of its own, + it is denied in any git command's global options. Some wrapper bodies are denied where the body runs git or gh. One is a double-quoted + body holding a `$` or backtick word the outer shell expands. Another is a shell string that + `xargs` fills with the words it reads. A value holding a `;` or a line break then adds whole + commands before the inner shell parses the body. A body running neither keeps its verdict, so + `bash -c "cd $DIR && ls"` is allowed. A command naming git or gh that holds a carriage return is denied, since the shell reads one as part of a word. So is one holding a word that a backslash-newline splits. So is one holding an escaped backslash before a line break. The shell reads that as a line break where the hook @@ -239,16 +258,22 @@ text says, because the harm it covers was never in the text. `flock` or `watch`, and after `while`, `until`, or `coproc`. A wrapper shell or a substitution running one counts, and so does a shell running a script file or its input. A `-c` shell given no command string counts as one, since `xargs` may supply it. So does one whose next word is an - option, as in `bash -c --`, and one whose string holds the string an `xargs -I` replaces. So + option, as in `bash -c --`, and one whose string holds the string an `xargs -I` replaces. That + replace option is read inside a short-option cluster such as `-0I{}`, and as the BSD `-J`. So does an `eval`, a `source`, or a shell running a script file inside a wrapper body or a - substitution. + substitution. A wrapper body is read word by word as the outer command is. A `git config` + that `xargs` runs counts unless its own words name a read such as `--get`. `xargs` appends the + key and value otherwise. So does a `git remote` naming no subcommand under `xargs`, and a git + word naming none. So does a command word holding the string `xargs -I` replaces. The group a + named `coproc` runs is read too. After one, the push reads its remote's `mirror` setting and its checkout's origin as undetermined. The hook reads both before the command runs, and a checkout or a switch changes - neither. + neither. A push to a protected default denied for that reason says so, and asks for the push + as its own command. A launcher in front of a git command, such as `flock `, passes its prefix to that git. - An `env` after the launcher does too. A launcher the hook does not know counts unless it only - names its arguments, as `grep` does. A shell such as `pwsh` behind such a launcher is read as - well. + An `env` or a `sudo` after the launcher does too. A launcher the hook does not know counts + unless it only names its arguments, as `grep` does. A shell such as `pwsh` behind such a + launcher is read as well. A shell whose command string runs git is denied where its prefix or an earlier `export` sets such a file, or config through `GIT_CONFIG_COUNT`. A variable git runs as a command, set there, counts too, unless it names a plain program that runs no git. The hook reads that @@ -356,13 +381,23 @@ text says, because the harm it covers was never in the text. real shell export persists into the following command exactly as effectively, confirmed live with a real reset that discards a tracked local modification with no redirect at all on the `git` invocation itself, a shape an inline-prefix scan alone cannot see. - An `export` anywhere before the git command is read too, as is a `declare -x`. An `export` of - a bare name exports the value set before it. A `GIT_DIR`/`GIT_WORK_TREE` prefix behind a - precommand or a launcher such as `timeout 60` or `flock ` is read as well. Each export - after the first command gives a reading of its own beside the one without it. An `export` in a - subshell does not reach a later command, though one there is still read as one that may. - A leading one is read as above. A subcommand this requirement denies, named in wrappers nested - past the reading cap, is denied wherever it runs. `--git-dir`/`GIT_DIR=` alone, + An `export` anywhere before the git command is read too, as is a `declare -x`, a + `typeset -x`, and a `local -x`. An `export` of a bare name exports the value set before it. A + plain assignment to a name exported before it exports its new value, and so does any plain + assignment after a `set -a` or `set -o allexport`. Where a loop or a function may run the git + command after a later export, every export in the command is read. The readers of an exported + git variable read these forms, the config and hook settings above included. A + `GIT_DIR`/`GIT_WORK_TREE` prefix behind a precommand or a launcher such as `timeout 60` or + `flock ` is read as well. Behind a launcher the hook does not know, an `env` or a `sudo` + may set one. That assignment is read beside each export rather than over it. It may be the + launcher's own argument, as in `find ./env -name GIT_DIR=...`. Each export + after the first command gives a reading of its own beside the one without it. An `export` in + a subshell does not reach a later command, though one there is still read as one that may. + A leading one is read as above. A value of `GIT_DIR`, `GIT_WORK_TREE`, `--git-dir`, or + `--work-tree` may hold a run-time word other than `$HOME`. A subcommand this requirement + denies is then denied, since that value names no checkout the hook can resolve. A + subcommand this requirement denies, named in wrappers nested past the reading cap, is denied + wherever it runs. `--git-dir`/`GIT_DIR=` alone, with no `--work-tree`/`GIT_WORK_TREE=` anywhere on the same invocation, never relocates that reported target, matching git's own documented fallback. diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 0f2c36437..0936c4d06 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -156,7 +156,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **Per-machine.** `~/.claude/` does not travel, so run the installer on each box. This is the rollout that [#365][issue-365] tracks. - **Precision over recall for the write footguns.** The hook denies the specific dangerous write shapes with high confidence rather than gating every write, so it is written to avoid blocking legitimate work -- a known false-positive shape is a parser defect to fix, not an accepted cost. The exception is a write whose target the hook cannot compare, which it denies. That is a write whose repository owner is a run-time word. It is also one whose target the hook does not read, as the root spec's requirement 3 lists. A shape it does not catch still falls under the behavioral rules. - **The branch-bypass rule fails closed.** Unlike the write-footgun rules, a push to `main`/`master`/`develop` is denied even when its rules cannot be determined (the API is unreachable, or the checkout's origin cannot be resolved to query them), because the harm there is a silent success under the maintainer's admin bypass. The rule reads each branch's live rules, so it adapts to every repo (a code-style `develop` denies, a config-style `develop` allows) with no per-repo configuration, and hands the exact command to the maintainer to run when a bypass is genuinely intended. -- **Opaque targets are unseen.** The hook cannot see the repository behind a GraphQL node id. That is why rule 2 blocks a *literal* id at all, since a captured `$variable` is trusted. Likewise, the cross-origin check only runs when an `origin` can be resolved and the write names an explicit target. Such a target is `-R`, `repos//`, a `GH_REPO` value, or a pull request URL. No owner comparison reads a write whose target is only a node id. A write from a non-git directory skips only the owner comparison and the run-time-word check. A target the hook does not read fails closed outside a checkout too. Examples are a gh write an `eval` runs and a `gh api` write to a `repositories/` endpoint or through a `..` segment. The hook reads an inherited `GH_REPO` from its own environment, the one the session was launched with. A value a Bash tool call gets some other way, such as from a shell profile it sources, is not seen. An inherited value is read beside any `export` in the command, since the hook cannot tell whether that export runs. To write elsewhere, override it with a prefix, as in `GH_REPO=/ gh ...`, or with `-R`. Where a command-text `export` may not run where it sits, as in a subshell or a branch, every value the command sets is read. A `gh api` endpoint's run-time segment past a literal owner is compared by that owner alone. Such a segment may still hold a `..` segment that reaches another owner. +- **Opaque targets are unseen.** The hook cannot see the repository behind a GraphQL node id. That is why rule 2 blocks a *literal* id at all, since a captured `$variable` is trusted. Likewise, the cross-origin check only runs when an `origin` can be resolved and the write names an explicit target. Such a target is `-R`, `repos//`, a `GH_REPO` value, or a pull request URL. No owner comparison reads a write whose target is only a node id. A write from a non-git directory skips only the owner comparison and the run-time-word check. A target the hook does not read fails closed outside a checkout too. Examples are a gh write an `eval` runs and one `xargs` runs on input the hook does not read. A `gh api` write to a `repositories/` endpoint or through a `..` segment is another. The hook reads an inherited `GH_REPO` from its own environment, the one the session was launched with. A value a Bash tool call gets some other way, such as from a shell profile it sources, is not seen. An inherited value is read beside any `export` in the command, since the hook cannot tell whether that export runs. To write elsewhere, override it with a prefix, as in `GH_REPO=/ gh ...`, or with `-R`. Where a command-text `export` may not run where it sits, as in a subshell or a branch, every value the command sets is read. A `gh api` endpoint's run-time segment past a literal owner is compared by that owner alone. Such a segment may still hold a `..` segment that reaches another owner. - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **Not a credential control.** A fine-grained PAT limited to owned repositories is a separate, stronger structural guard (a hard `403` on any non-owned repo) and is left to per-machine credential setup, out of this kit. - **Rule 6's ref-checkout and `--ff-only` exemptions are deliberate, not a gap.** The #1073 incident's own literal commands (an unforced `git checkout main`, then `git pull --ff-only`) are exactly this shape, so this rule does not deny the incident's own commands specifically. Denying them would also break the documented base-clone cleanup step in the `repo-worktree` skill, which needs precisely those two. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) is not decidable from the command text alone, so it stays the prose rule's job. A non-force flag alongside the ref, such as `--detach`, is exempt too, not only a strictly zero-flags invocation -- git's own overwrite-refusal on a dirty tracked file is unaffected by it, verified live. diff --git a/host-setup/agent-safety/claude/gh-write-guard.py b/host-setup/agent-safety/claude/gh-write-guard.py index 99dfb7f68..6990ca264 100755 --- a/host-setup/agent-safety/claude/gh-write-guard.py +++ b/host-setup/agent-safety/claude/gh-write-guard.py @@ -21,7 +21,8 @@ the maintainer granted that target in GH_WRITE_GUARD_ALLOW. The target is named by -R/--repo, repos//, GH_REPO, a pull request URL, an --org or --owner value, or a linked issue's URL. A write whose target the guard does not read fails closed, such as one an eval - runs or one to a repositories/ endpoint. Sibling + runs, one xargs runs on input the guard does not read, or one to a repositories/ + endpoint. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository, not working across your own fleet in one session. 4. a git operation that would only land by bypassing an active branch rule: a direct push to a branch @@ -1472,27 +1473,15 @@ def _config_override_sources(global_opts): def _env_assignments(toks, k=None): """The `NAME=value` words in `toks` that reach a git command, as (name, value). - That is each argument of an `export`, which persists to the commands after it. + That is each value an export exports, which persists to the commands after it (see `_export_events`). It is also the prefix of the git word at index `k`, or of every git word where `k` is None (see `_git_word_assignments`). """ out = [] + exports = dict(_export_events(toks)) for x, t in enumerate(toks): if _is_git_exe(t) and k in (None, x): out.extend(_git_word_assignments(toks, x)) - elif t == "export" and _opens_command(toks, x): - out.extend(_export_assignments(toks, x)) - return out - - -def _export_assignments(toks, x): - """The `NAME=value` arguments of the `export` at `toks[x]`, as (name, value), up to its first other word.""" - out = [] - for word in toks[x + 1 :]: - m = _ENV_ASSIGN_RE.match(word) - if not (m or word.startswith("-")): - break - if m: - out.append(m.groups()) + out.extend(exports.get(x, ())) return out @@ -1560,6 +1549,7 @@ def _export_assignments(toks, x): _LAUNCHER_POSITIONALS = {"flock": 1, "watch": 0, "winpty": 0, "coproc": 0, "while": 0, "until": 0} +_NAME_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") def _base_name(tok): @@ -1600,7 +1590,8 @@ def _command_prefix(toks, k): def _prefix_walk(toks, k): """(the index of the first word `_command_prefix` does not pass, the assignments before it). - The walk stops there, or at `k`, whichever comes first. + The walk stops there, or at `k`, whichever comes first. A named `coproc` passes its name too, + since it runs the compound command after it, as in `coproc name { ...; }`. """ start = k while start > 0 and not _is_separator(toks[start - 1]): @@ -1624,11 +1615,14 @@ def _prefix_walk(toks, k): i += 2 if _option_takes_next(toks[i], takes) else 1 elif _base_name(toks[i]) in _LAUNCHER_POSITIONALS: takes = _PRECOMMAND_VALUE_OPTS.get(_base_name(toks[i]), frozenset()) - positionals = _LAUNCHER_POSITIONALS[_base_name(toks[i])] + base = _base_name(toks[i]) + positionals = _LAUNCHER_POSITIONALS[base] i += 1 while i < k and toks[i].startswith("-"): i += 2 if _option_takes_next(toks[i], takes) else 1 i += positionals + named = base == "coproc" and i + 1 < k and _NAME_WORD.fullmatch(toks[i]) + i += bool(named and (toks[i + 1] == "{" or toks[i + 1].startswith("("))) else: return i, out return i, out @@ -1682,14 +1676,19 @@ def _reading_env_config_values(toks): Each git word's pairs are read from the exports before it and its own prefix, as git reads them. A later command reusing an index then cannot replace an earlier one's key. The pairs across every assignment `_env_assignments` returns are read too, so a reading never loses a value it gave before. + Behind a launcher, the exports are also read under only the assignments before it, since one + after an `env` or `sudo` there may be the launcher's own argument (see `_git_dir_rereading`). """ out = list(_env_config_values(_env_assignments(toks))) exported = [] + exports = dict(_export_events(toks)) for k, t in enumerate(toks): - if t == "export" and _opens_command(toks, k): - exported.extend(_export_assignments(toks, k)) - elif _is_git_exe(t): + exported.extend(exports.get(k, ())) + if _is_git_exe(t): out.extend(_env_config_values(exported + _git_word_assignments(toks, k))) + if not _command_prefix(toks, k)[0]: + before = _launcher_prefix(toks, k, env_args=False)[1] + out.extend(_env_config_values(exported + before)) return list(dict.fromkeys(out)) @@ -1862,35 +1861,81 @@ def _git_invocations_at(cmd): return out -_EXPORTING_BUILTINS = {"export": None, "declare": "-x", "typeset": "-x"} +_EXPORTING_BUILTINS = {"export": None, "declare": "-x", "typeset": "-x", "local": "-x"} -def _exported_states(toks, word): - """The exported variables before the git word at `toks[word]`, as one dict after each export. +def _export_events(toks): + """Each place in `toks` where the shell exports variables, as (index, the (name, value) pairs it exports). - An `export`, or a `declare`/`typeset` given `-x`, exports each `NAME=value` it names, read by - `_export_words`. One naming a bare `NAME` exports the value the last command of plain - assignments before it set (see `_plain_assignments`). A `builtin` or `command` before it counts. + An `export`, or a `declare`, `typeset`, or `local` given `-x`, exports each `NAME=value` it + names, read by `_export_words`. One naming a bare `NAME` exports each value a plain + assignment, a `declare`, a `typeset`, a `local`, or a `readonly` before it gave that name (see + `_plain_assignments`). Each is read, since a function or a branch may hold the one set last. + A `builtin` or `command` before it counts. A plain assignment standing as its own command + exports its value too. It does where the name was exported before it, or a `set -a` or + `set -o allexport` came before it, and so does a `declare` after one. The readers of an + exported git variable read these, so each form reaches every rule that reads one. `GH_REPO` + keeps its own reader (see `_gh_repo_states`). That reader fails closed on the forms it does + not follow (see `_gh_repo_unread_export`). """ - shell, current, states = {}, {}, [] - for x in range(word): - t = toks[x] - shell.update(_plain_assignments(toks, x)) + shell, marked, allexport, out = {}, set(), False, [] + + def remember(pairs): + for name, value in pairs: + shell.setdefault(name, []).append(value) + + for x, t in enumerate(toks): + plain = _plain_assignments(toks, x) + remember(plain) + reached = [(name, value) for name, value in plain if allexport or name in marked] + if reached: + out.append((x, reached)) runner = x > 0 and toks[x - 1] in ("builtin", "command") and _opens_command(toks, x - 1) - if t not in _EXPORTING_BUILTINS or not (_opens_command(toks, x) or runner): + if not (_opens_command(toks, x) or runner): continue - flag = _EXPORTING_BUILTINS[t] options = [] - for w in toks[x + 1 : word]: + for w in toks[x + 1 :]: if _is_shell_op(w): break options.append(w) - if flag and not any(w.startswith("-") and flag[1] in w for w in options): + if t == "set": + flags = [w for w in options if w[:1] == "-" and w[1:2] not in ("", "-")] + allexport = allexport or any("a" in w for w in flags) or "allexport" in options + continue + if t not in _EXPORTING_BUILTINS and t != "readonly": continue pairs, names = _export_words(toks, x) - current.update({name: shell[name] for name in names if name in shell}) + remember(pairs) + flag = _EXPORTING_BUILTINS.get(t, "-x") + if flag and not any(w.startswith("-") and flag[1] in w for w in options): + if allexport and pairs: + out.append((x, pairs)) + continue + marked.update(names) + marked.update(name for name, _value in pairs) + named = [(name, v) for name in names for v in dict.fromkeys(shell.get(name, ()))] + out.append((x, named + pairs)) + return out + + +def _exported_states(toks, word): + """The exported variables the git word at `toks[word]` may run under, as one dict after each export. + + Each export is read from `_export_events`, in order. Those before the git word are read, and + an export giving one name several values gives a state for each. Where + a loop or a function may run the git word after a later export, as in `f() { git ...; }; + export ...; f`, every export in the command is read (see `_reruns`). + """ + end = len(toks) if _reruns(toks, None, subshells=False) else word + current, states = {}, [] + for x, pairs in _export_events(toks): + if x >= end: + break + base = dict(current) current.update(pairs) states.append(dict(current)) + alternates = [(n, v) for n, v in pairs if current[n] != v] + states.extend({**base, **dict(pairs), n: v} for n, v in alternates) return states @@ -1904,19 +1949,26 @@ def _git_dir_rereading(toks, word, invocation, inherited=()): invocation's own value wins, as git reads it. The caller keeps the first reading as well, since an `export` in a subshell or a pipeline does not reach a later command. Such an export is still read, as one that may. + + Past a launcher, an assignment after an `env` or `sudo` word may be the launcher's own + argument, as `find ./env -name GIT_DIR=x -exec git ...` holds. So each state is also read + under only the assignments before the launcher, beside that prefix rather than under it. """ c_dirs, work_tree, git_dir, inline_aliases, sub, args, leading_cd = invocation - prefix = _git_word_assignments(toks, word) + prefixes = [_git_word_assignments(toks, word)] + if not _command_prefix(toks, word)[0]: + prefixes.append(_launcher_prefix(toks, word, env_args=False)[1]) out = [] for state in [{}, *inherited, *_exported_states(toks, word)]: - values = {**state, **dict(prefix)} - carried = ( - work_tree if work_tree is not None else values.get(_GIT_ENV_WORK_TREE_VAR), - git_dir if git_dir is not None else values.get(_GIT_ENV_GIT_DIR_VAR), - ) - reading = (c_dirs, *carried, inline_aliases, sub, args, leading_cd) - if carried != (work_tree, git_dir) and reading not in out: - out.append(reading) + for prefix in prefixes: + values = {**state, **dict(prefix)} + carried = ( + work_tree if work_tree is not None else values.get(_GIT_ENV_WORK_TREE_VAR), + git_dir if git_dir is not None else values.get(_GIT_ENV_GIT_DIR_VAR), + ) + reading = (c_dirs, *carried, inline_aliases, sub, args, leading_cd) + if carried != (work_tree, git_dir) and reading not in out: + out.append(reading) return out @@ -1986,7 +2038,7 @@ def _all_git_invocations(cmd, overflow=None): def _wrapper_dir_prefixes(text): """The (work tree, git dir) a `GIT_WORK_TREE`/`GIT_DIR` gives each shell in `text` whose command string runs git. - That is the shell's own prefix and each `export` before it (see `_wrapper_env_groups`). + That is the shell's own prefix and each export before it (see `_wrapper_env_groups`). A shell that is given neither is left out. """ out = [] @@ -2664,6 +2716,19 @@ def _check_primary_checkout_mutation( ) if dotted is not None: continue + unread_dir = next( + (v for v in (git_dir, work_tree) if v and _is_run_time_word(_expand_dir(v))), None + ) + if unread_dir is not None: + verdict = _primary_checkout_verdict(sub, args, None, lambda _d, _r: False) + if verdict or (verdict is None and sub not in _git_command_names()): + return "deny", ( + f"This `git {sub}` takes its git directory or work tree from a run-time word " + f"({unread_dir}), which the shell expands before git reads it, so the guard " + "cannot tell whether it runs against a primary checkout. Failing closed. " + "Write the directory out as an absolute path in GIT_DIR, GIT_WORK_TREE, " + "--git-dir, or --work-tree." + ) resolved = _resolve_target_dir(c_dirs, work_tree, leading_cd, cwd) repo_git_dir = _resolve_repo_dir(git_dir, c_dirs, leading_cd, cwd) # This rule tests two independent dimensions of "does this touch a primary checkout", since git's own --work-tree/--git-dir split lets a single invocation mutate one repository's index/refs/HEAD while writing working-tree files into an entirely different directory. @@ -3829,7 +3894,7 @@ def _export_words(toks, x): m = _ENV_ASSIGN_RE.match(word) if m: pairs.append(m.groups()) - elif re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", word): + elif _NAME_WORD.fullmatch(word): names.append(word) elif not word.startswith("-"): break @@ -3933,23 +3998,41 @@ def _gh_word_repo_values(text, inherited): for x, argv in invocations: if not _takes_gh_repo(argv): continue - reached, pairs = _command_prefix(toks, x) - if not reached: - reached, pairs = _launcher_prefix(toks, x, env_args=False) - if not reached: - continue - prefix = [(v, False) for name, v in pairs if name == "GH_REPO"] - out += [(v, argv, env) for v, env in prefix or states[x]] + reached, values = _gh_repo_reach(toks, x, states) + if reached: + out += [(v, argv, env) for v, env in values] return out +def _gh_repo_reach(toks, x, states): + """(whether the word at `toks[x]` runs as a command, the `GH_REPO` values reaching it as (value, from_env)). + + Its own prefix replaces the shell's state at `states[x]` (see `_command_prefix`). Behind a + launcher `_command_prefix` does not know, the assignments before that launcher do (see + `_launcher_prefix`). One after an `env` or `sudo` there is read beside them, since it is + either an argument, as in `find ./env -name GH_REPO=x -exec gh ...`, or one that word passes + on, as in `uv run env GH_REPO=x gh ...`. + """ + reached, pairs = _command_prefix(toks, x) + passed = [] + if not reached: + reached, pairs = _launcher_prefix(toks, x, env_args=False) + later = _launcher_prefix(toks, x)[1][len(pairs) :] + passed = [(v, False) for name, v in later if name == "GH_REPO"] + if not reached: + return False, [] + values = [(v, False) for name, v in pairs if name == "GH_REPO"] or states[x] + return True, values + [v for v in passed if v not in values] + + def _gh_wrapper_repo_values(text, inherited, _depth=0): """The `GH_REPO` value reaching each gh word in a wrapper body in `text`, read for that wrapper alone. A wrapper's bodies run under its own GH_REPO prefix, or else the value its command runs under (see `_gh_repo_states`), and a wrapper nested in one inherits from it in turn. A substitution body the tokenizer keeps inside one word, as in `"$(...)"`, runs under the value at each word - opening it, or at every word where none is found. + opening it, or at every word where none is found. Each value reaching a body is read as a + reading of its own, since `_gh_repo_states` takes only the latest of the values it inherits. """ if _depth > _WRAPPER_NESTING_LIMIT: return [] @@ -3960,21 +4043,20 @@ def _gh_wrapper_repo_values(text, inherited, _depth=0): found = _shell_bodies_at(toks, x) if not found: continue - reached, pairs = _command_prefix(toks, x) - if not reached: - reached, pairs = _launcher_prefix(toks, x, env_args=False) - prefix = [(v, False) for name, v in pairs if name == "GH_REPO"] if reached else [] - reach = prefix or states[x] + reached, reach = _gh_repo_reach(toks, x, states) + reach = reach if reached else states[x] for body in found[0]: - out += _gh_word_repo_values(body, reach) - out += _gh_wrapper_repo_values(body, reach, _depth + 1) + for each in [[v] for v in reach] or [[]]: + out += _gh_word_repo_values(body, each) + out += _gh_wrapper_repo_values(body, each, _depth + 1) for body in _substitution_bodies(text): at = [k for k, t in enumerate(toks) if "$(" + body in t or "`" + body in t] or range( len(toks) ) reach = list(dict.fromkeys(v for k in at for v in states[k])) if toks else list(inherited) - out += _gh_word_repo_values(body, reach) - out += _gh_wrapper_repo_values(body, reach, _depth + 1) + for each in [[v] for v in reach] or [[]]: + out += _gh_word_repo_values(body, each) + out += _gh_wrapper_repo_values(body, each, _depth + 1) return out @@ -4558,21 +4640,33 @@ def _config_may_change(toks, end, skip=None, mask=None): for k in range(end): if k == skip: continue - if _runs_run_time_word(toks, k, mask): - return True - if _runs_unread_script(toks, k, mask): + if _word_may_change_config(toks, k, mask): return True found = _shell_bodies_at(toks, k) - if found and _word_runs(toks, k, mask): - if found[0] and _string_read_elsewhere(toks, k): - return True - if any(_names_config_change(body) for body in found[0]): - return True - if _config_changing_word(toks, k, mask): + if found and _word_runs(toks, k, mask) and any(map(_names_config_change, found[0])): return True return False +def _word_may_change_config(toks, k, mask=None): + """True when the word at `toks[k]` runs something that may rewrite git config, read the same in every config scan. + + That is a run-time command word (see `_runs_run_time_word`), a shell given no command string + (see `_runs_unread_script`), and a word `_config_changing_word` counts. It is also a shell + whose command string it may not run (see `_string_read_elsewhere`). `_config_may_change` and + `_names_config_change` both read each word with it, so a wrapper body is read as the outer + command is. + """ + if _runs_run_time_word(toks, k, mask) or _runs_unread_script(toks, k, mask): + return True + if _config_changing_word(toks, k, mask): + return True + found = _shell_bodies_at(toks, k) + return bool( + found and found[0] and _word_runs(toks, k, mask) and _string_read_elsewhere(toks, k) + ) + + def _word_runs(toks, k, mask=None): """True when the word at `toks[k]` may run as a command, read fail-closed. @@ -4607,7 +4701,7 @@ def _string_read_elsewhere(toks, k): That is where no word follows the option or the word after it is an option, as in `bash -c --`. The shell then takes its string from a later word. It is also a string holding the string an - `xargs` running the shell replaces with each word it reads (see `_xargs_replace_string`). + `xargs` running the shell replaces with each word it reads (see `_xargs_replace_strings`). """ exe = _command_string_exe(toks[k]) args, _ = _collect_arglist(toks, k + 1) @@ -4616,32 +4710,66 @@ def _string_read_elsewhere(toks, k): return False if ci + 1 >= len(args) or args[ci + 1].startswith("-"): return True - replaced = _xargs_replace_string(toks, k) - return bool(replaced) and replaced in args[ci + 1] + return any(r in args[ci + 1] for r in _xargs_replace_strings(toks, k)) + +_XARGS_VALUE_LETTERS = "adEILnPsJRS" -def _xargs_replace_string(toks, k): - """The string an `xargs` running `toks[k]` replaces with each word it reads, or None. - That is the value of `-I`, attached or the next word, or of `-i` or `--replace`, `{}` where - they name none. +def _xargs_replace_strings(toks, k, parsed=False, spliced=False): + """Each string an `xargs` running `toks[k]` may replace with each word it reads, empty where it replaces none. + + That is the value of `-I` or the BSD `-J`, attached or the next word, or of `-i` or + `--replace`, `{}` where they name none. Each is read whole and inside a short-option cluster, + as in `-0I{}` or `-rI{}`, where a letter taking a value takes the rest of the word or the + next word, as xargs reads it. An option named first is read too, wherever it sits, unless + `parsed` asks for xargs's own options alone, as a reader asking whether xargs appends does. + With `spliced`, only a `-J` string is given. BSD xargs puts every word it reads there as + words of their own, where `-I` puts one whole line there as one word. """ if not _xargs_runs(toks, k): - return None + return [] start = max(x for x in range(k) if _base_name(toks[x]) == "xargs") - for x in range(start + 1, k): + out = [] + for x in range(start + 1, start + 1 if parsed else k): w = toks[x] if w == "-I": - return toks[x + 1] if x + 1 < k else None - if w.startswith("-I"): - return w[2:] - if w.startswith("--replace="): - return w.partition("=")[2] or "{}" - if w == "--replace": - return "{}" - if w.startswith("-i"): - return w[2:] or "{}" - return None + out += [toks[x + 1]] if x + 1 < k else [] + elif w.startswith("-I"): + out.append(w[2:]) + elif w.startswith("--replace="): + out.append(w.partition("=")[2] or "{}") + elif w == "--replace": + out.append("{}") + elif w.startswith("-i"): + out.append(w[2:] or "{}") + else: + continue + break + splices = [] + x = start + 1 + while x < k and toks[x].startswith("-") and toks[x] != "--": + w, x = toks[x], x + 1 + if w.startswith("--replace"): + out.append(w.partition("=")[2] or "{}") + continue + if w.startswith("--"): + x += "=" not in w and w in _PRECOMMAND_VALUE_OPTS["xargs"] + continue + for at, letter in enumerate(w[1:], 2): + rest = w[at:] + if letter in "IJ": + found = [rest] if rest else toks[x : x + 1] if x < k else [] + out += found + splices += found if letter == "J" else [] + elif letter == "i": + out.append(rest or "{}") + elif letter in _XARGS_VALUE_LETTERS: + x += not rest + else: + continue + break + return [r for r in dict.fromkeys(splices if spliced else out) if r] def _xargs_runs(toks, k, mask=None): @@ -4655,6 +4783,18 @@ def _xargs_runs(toks, k, mask=None): return any(_base_name(toks[x]) == "xargs" and not (mask and mask[x]) for x in range(start, k)) +def _xargs_command(toks, k, mask=None): + """True when an `xargs` runs the word at `toks[k]` as the command it runs (see `_xargs_runs`). + + That is the command word past xargs and its options (see `_command_prefix`), or past a + launcher after it (see `_launcher_prefix`). A word that is that command's argument, as the + `git` of `xargs grep -l git` is, is no command. + """ + return _xargs_runs(toks, k, mask) and ( + _command_prefix(toks, k)[0] or _launcher_prefix(toks, k)[0] + ) + + _CONFIG_READ_ACTIONS = frozenset( {"--get", "--get-all", "--get-regexp", "--get-urlmatch", "-l", "--list"} ) @@ -4708,22 +4848,42 @@ def _git_word_changes_config(toks, k): A `git config` or `git remote` that only reads is left out (see `_config_only_reads`). It is a bare `git remote`, with or without `-v`, or its `show` or `get-url`. One whose arguments hold a substitution is not left out, since the guard does not read what the substitution gives. + Nor is one an `xargs` runs as its command (see `_xargs_command`), which appends the words it + reads, as `xargs git config` writes the key and value its input gives, unless its own words + name a read (see `_config_names_read`), or it is a `git remote` naming its subcommand. A git + word an `xargs` runs with no subcommand counts too, since its input gives the subcommand. """ j = _git_subcommand_index(toks, k) + appended = _xargs_command(toks, k) if j >= len(toks) or _is_shell_op(toks[j]): - return False + return appended sub = toks[j] args, _ = _collect_arglist(toks, j + 1) if sub in ("config", "remote") and any("`" in a or "$(" in a for a in args): return True if sub == "config": + if appended: + return not _config_names_read(args) return not _config_only_reads(args) if sub == "remote": rest = [a for a in args if a not in ("-v", "--verbose")] - return bool(rest) and rest[0] not in ("show", "get-url") + if not rest: + return appended + return rest[0] not in ("show", "get-url") return _may_be_alias(sub) +def _config_names_read(args): + """True when a `git config`'s own arguments name a read, so words appended after them cannot make it a write. + + That is a read action such as `--get` or `--list`, or a `get` or `list` subcommand, with no + write action beside it. Git refuses a second action, so an appended one runs nothing. + """ + positionals = [a for a in args if not a.startswith("-")] + named = positionals[:1] in (["get"], ["list"]) or any(a in _CONFIG_READ_ACTIONS for a in args) + return named and _config_only_reads(args) + + def _config_only_reads(args): """True when a `git config`'s arguments only read. @@ -4754,10 +4914,15 @@ def _runs_run_time_word(toks, k, mask=None): That is the command word `_command_prefix` names, or a word right after an unquoted `(`. An argument holding one, as in `mkdir -p "$D"`, runs nothing. An assignment, or a shell operator such as `(`, is no command word. + A command word holding the string an `xargs` running it replaces is one too, as in `xargs + -I{} {} config ...`, since each word xargs reads takes its place (see `_xargs_replace_strings`). """ t = toks[k] - if _is_shell_op(t) or not _is_run_time_word(t) or _ENV_ASSIGN_RE.match(t): + if _is_shell_op(t) or _ENV_ASSIGN_RE.match(t): return False + if not _is_run_time_word(t): + replaced = any(r in t for r in _xargs_replace_strings(toks, k)) + return replaced and _command_prefix(toks, k)[0] if k and toks[k - 1].endswith("(") and not (mask and mask[k - 1]): return True return _command_prefix(toks, k)[0] @@ -4798,13 +4963,11 @@ def _names_config_change(text): for body in bodies: toks = _shell_tokens(body) if any( - _config_changing_word(toks, k) - or _runs_run_time_word(toks, k) + _word_may_change_config(toks, k) or ( toks[k] in ("source", ".") and (_command_prefix(toks, k)[0] or (k > 0 and toks[k - 1] == "builtin")) ) - or _runs_unread_script(toks, k) for k in range(len(toks)) ): return True @@ -5436,7 +5599,7 @@ def _wrapper_env_assignments(toks, runs=None): `runs` stands in for `_runs_git` where another command's reach is read, as gh's is. The shell is a `sh -c`-style wrapper or one `_FOREIGN_SHELL_FLAGS` names, as its simple command's command. - That is its own prefix (see `_command_prefix`), and each `export` argument before it. + That is its own prefix (see `_command_prefix`), and each value exported before it (see `_export_events`). Behind a launcher `_command_prefix` does not know, it is the assignments before that launcher (see `_launcher_prefix`). Its command string is read as a command of its own, which these do not reach. """ @@ -5444,19 +5607,33 @@ def _wrapper_env_assignments(toks, runs=None): def _wrapper_env_groups(toks, runs=None): - """`_wrapper_env_assignments`, as one list of (name, value) per shell, in the order the shells appear.""" + """`_wrapper_env_assignments`, as one list of (name, value) per shell, in the order the shells appear. + + Where a loop or a function may run a shell after a later export, every export is read as + reaching it (see `_exported_states`). Behind a launcher, a shell is also read under only the + assignments before it, since one after an `env` or `sudo` there may be the launcher's own + argument (see `_git_dir_rereading`). + """ out, exported = [], [] + exports = dict(_export_events(toks)) + if _reruns(toks, None, subshells=False): + exported = [pair for pairs in exports.values() for pair in pairs] for x, t in enumerate(toks): - if t == "export" and _opens_command(toks, x): - exported.extend(_export_assignments(toks, x)) - continue + if x in exports: + exported.extend(exports[x]) + if t in _EXPORTING_BUILTINS: + continue found = _shell_bodies_at(toks, x) if found and any((runs or _runs_git)(body) for body in found[0]): reached, prefix = _command_prefix(toks, x) + before = None if not reached: reached, prefix = _launcher_prefix(toks, x) + before = _launcher_prefix(toks, x, env_args=False)[1] if reached: out.append(exported + prefix) + if reached and before is not None and before != prefix: + out.append(exported + before) return out @@ -5465,30 +5642,48 @@ def _launcher_prefix(toks, k, env_args=True): Such a launcher, as `uv run` is, passes its environment to the command it runs. The launcher is the first word `_prefix_walk` does not pass, and runs `toks[k]` unless `_NAMES_ITS_ARGUMENTS` names it, as `grep`. - With `env_args`, an assignment after an `env` among the words after it is read too, since - that `env` passes it on. Any other assignment there is the launcher's own argument, as - `find -name A=b` holds. Without it, only the assignments before the launcher are read. A - reader that takes them in place of a shell's state then never loses that state to an argument. + With `env_args`, an assignment after an `env` or a `sudo` among the words after it is read + too, since either passes it on, as in `uv run sudo NAME=value git ...`. Any other assignment + there is the launcher's own argument, as `find -name A=b` holds. Without it, only the + assignments before the launcher are read. A reader that takes them in place of a shell's + state then never loses that state to an argument, and one reading both reads them beside it. """ i, out = _prefix_walk(toks, k) if i >= k or _base_name(toks[i]) in _NAMES_ITS_ARGUMENTS: return False, [] if not env_args: return True, out - env = next((x for x in range(i, k) if _base_name(toks[x]) == "env"), k) + env = next((x for x in range(i, k) if _base_name(toks[x]) in ("env", "sudo")), k) return True, out + [m.groups() for t in toks[env:k] for m in [_ENV_ASSIGN_RE.match(t)] if m] -def _runs_git(text): +def _names_owner_flag(word): + """True when a gh word is an owner or repo flag, whole, with `=`, or ending a short cluster. + + That is one of `_GH_OWNER_FLAGS`, `--repo`, `-R`, or `-o`, which take an owner or a repository + as their value (see `_gh_owner_words`). + """ + name = word.partition("=")[0] + if name in _GH_OWNER_FLAGS or name == "--repo": + return True + return word[:1] == "-" and word[1:2] not in ("", "-") and ("R" in word or "o" in word) + + +def _runs_git(text, gh=False): """True when a git word runs as a command (see `_runs_as_command`) in `text`, or in a command string it embeds. - The embedded strings are those `_embedded_wrapper_commands` reads. + The embedded strings are those `_embedded_wrapper_commands` reads. With `gh`, a gh word + counts too, and a body nested past the reading cap counts as one that runs either. """ - for body in [text, *_embedded_wrapper_commands(text)]: + overflow = [] if gh else None + for body in [text, *_embedded_wrapper_commands(text, overflow=overflow)]: toks = _shell_tokens(body) - if any(_is_git_exe(t) and _runs_as_command(toks, k) for k, t in enumerate(toks)): + if any( + (_is_git_exe(t) or (gh and _is_gh_exe(t))) and _runs_as_command(toks, k) + for k, t in enumerate(toks) + ): return True - return False + return bool(overflow) def _wrapper_env_reason(assignments): @@ -5890,6 +6085,144 @@ def _xargs_merge(text): return False +def _xargs_gh_unread(text): + """True when `text` runs a gh command under `xargs` whose words the guard cannot read in full. + + xargs appends the words it reads to the command it runs, or puts each where its replace + string sits (see `_xargs_replace_strings`). So a gh write it runs, or a gh naming no + subcommand, may take a repo flag, a body, or the write itself from its input. So may a gh + whose `_GH_WRITE_SUBSUBS` third word is missing, and one holding the replace string in a path + word. So may a `gh api` call it appends to, or one holding the replace string in any word but + its endpoint, which may then be an option such as `-XPOST` or a GraphQL mutation. A read whose command, subcommand, and options are written out, as in `xargs gh pr view`, + takes nothing from its input that makes it a write. Nor does a write whose command and + subcommand are written out, where xargs reads only inert words (see `_xargs_reads_inert`), as + `printf 5 | xargs gh pr comment --body x` does. + """ + toks = _shell_tokens(text) + for k, t in enumerate(toks): + if not (_is_gh_exe(t) and _xargs_command(toks, k)): + continue + args = _api_first(_collect_arglist(toks, k + 1)[0]) + path, path3 = _gh_path(args), _gh_path(args, 3) + replaced = _xargs_replace_strings(toks, k) + if len(path) < 2 or (tuple(path[:2]) in _GH_WRITE_SUBSUBS and len(path3) < 3): + return True + words = path3 if tuple(path[:2]) in _GH_WRITE_SUBSUBS else path + if args[0] != "api" and any(r in w for w in words for r in replaced): + return True + if _gh_argv_is_write(args): + xargs = max(x for x in range(k) if _base_name(toks[x]) == "xargs") + if args[0] == "api" or not _xargs_reads_inert(toks, xargs, k): + return True + elif args[0] == "api": + at = _gh_path_at(args) + endpoint = at[1] if len(at) > 1 else None + own = _xargs_replace_strings(toks, k, parsed=True) + if not own or _xargs_replace_strings(toks, k, spliced=True): + return True + if any(r in a for x, a in enumerate(args) if x != endpoint for r in replaced): + return True + return False + + +_INERT_WORD = re.compile(r"[A-Za-z0-9_.]+") + + +def _xargs_reads_inert(toks, x, k): + """True when the `xargs` at `toks[x]`, running the command at `toks[k]`, reads only inert words. + + An inert word is made of letters, digits, `_`, and `.` alone, so it names no option, + repository, or URL, wherever xargs puts it. The input must be a pipe from an `echo` or a + `printf` of literal words, as `printf 5 | xargs ...` gives. A word the shell rewrites, a + redirection, a `printf` format holding a `%` or a backslash other than `\\n` or `\\t`, and + an `--arg-file` or a short option holding `a`, which may read another file, each leave the + input unread. So does a redirection of the command's input, which takes the pipe's place. A + word still names an owner where it is an owner or repo flag's value, as after `--org`, so the + input is not inert where the command ends in such a flag, or where the replace string sits in + one or its value (see `_names_owner_flag`). + """ + for w in toks[x + 1 : k]: + if w.startswith("--a") or (w[:1] == "-" and w[1:2] != "-" and "a" in w): + return False + start = x + while start > 0 and not _is_separator(toks[start - 1]): + start -= 1 + end = next((j for j in range(k, len(toks)) if _is_separator(toks[j])), len(toks)) + if any(_is_redir_op(t) and "<" in t for t in toks[start:end]): + return False + args = _collect_arglist(toks, k + 1)[0] + if args and _names_owner_flag(args[-1]): + return False + for i, a in enumerate(args): + held = any(r in a for r in _xargs_replace_strings(toks, k)) + if held and (_names_owner_flag(a) or (i and _names_owner_flag(args[i - 1]))): + return False + if start == 0 or toks[start - 1] != "|": + return False + first = start - 1 + while first > 0 and not _is_separator(toks[first - 1]): + first -= 1 + words = toks[first : start - 1] + if not words or any(_is_run_time_word(w) or _is_redir_op(w) for w in words): + return False + base, args = _base_name(words[0]), words[1:] + if base == "echo": + while args and re.fullmatch(r"-[neE]+", args[0]): + args = args[1:] + text = " ".join(args) + elif base == "printf": + args = args[1:] if args[:1] == ["--"] else args + text = args[0] if args else "" + if "%" in text: + return False + text = text.replace("\\n", " ").replace("\\t", " ") + else: + return False + return "\\" not in text and all(_INERT_WORD.fullmatch(w) for w in text.split()) + + +def _xargs_filled_body(cmd): + """A shell command string in `cmd` that `xargs` fills with the words it reads, where it runs git or gh, else None. + + That is the string of a shell xargs runs as its command whose string holds xargs's replace + string, or whose string option the next word does not follow (see `_string_read_elsewhere`). + It is also the string a launcher such as `flock -c` hands a shell where it holds the replace + string, and that of any `watch` xargs runs, since `watch` joins the words xargs appends into + its string (see `_shell_bodies_at`). The inner shell parses each word xargs puts there, so a word holding a separator adds whole + commands, as `echo 'x; git push origin develop' | xargs -I{} sh -c 'git status {}'` does. + """ + for text in _data_free_texts(cmd) if _names_git_or_gh(cmd) else []: + toks = _shell_tokens(text) + for k in range(len(toks)): + found = _shell_bodies_at(toks, k) + if not (found and found[0] and _xargs_command(toks, k)): + continue + reps = _xargs_replace_strings(toks, k) + filled = _string_read_elsewhere(toks, k) or _base_name(toks[k]) == "watch" + if filled or any(r in b for b in found[0] for r in reps): + body = next((b for b in found[0] if _runs_git(b, gh=True)), None) + if body is not None: + return body + return None + + +def _outer_expanded_body(cmd): + """A wrapper body in `cmd` the outer shell expands before the inner shell parses it, where it runs git or gh, else None. + + The outer shell expands a `$` or backtick word inside a double-quoted `-c` body, so a value + holding a separator adds whole commands the guard never reads, as `B="x; git push origin + develop"; sh -c "echo $B"` does. Such a body fails closed only where it runs git or gh + itself (see `_runs_git`). A body running neither keeps its verdict, so `bash -c "cd + $DIR && ls"` is not denied for its expansion alone, and nor is that first example, whose body + runs only `echo`. Heredoc data is not read (see `_data_free_texts`). + """ + for body in _data_free_texts(cmd) if _names_git_or_gh(cmd) else []: + expands = isinstance(body, _ExpandedText) and ("$" in body or "`" in body) + if expands and _runs_git(body, gh=True): + return body + return None + + def _rewritten_git_words(cmd): """Name the form when a git command holds a rewritten word where it can change what git runs, else None. @@ -5920,6 +6253,10 @@ def _rewritten_git_words(cmd): `commit`, since `G=git; $G push` and `` `which git` push `` each run git - an unquoted pathname pattern in a directory value, since it may match several names - a push or a commit that `xargs` runs, since it appends words the guard does not read + - a git word with no subcommand that `xargs` runs, since its input gives the subcommand + - an `xargs` replace string in git's subcommand or a `-c` value, or among the global options + of a git command that may mutate, since each word xargs reads takes its place, and among + any git command's global options under a BSD `-J`, which splices in words of their own The text an `eval` runs is read too. A word of any `eval`'s arguments in a text may expand outside single quotes. Each payload that text's evals run is then text the shell has already @@ -5979,12 +6316,20 @@ def _rewritten_git_words(cmd): (mask, raw), masked = _quoting(text, toks), True end = _region_end(toks, k, mask) j = min(_git_subcommand_index(toks, k), end) - if j == k + 1 and j >= end: + appended = _xargs_command(toks, k, mask) and toks[k + 1 : k + 2] != ["--version"] + if j == k + 1 and j >= end and not appended: continue opened = k and toks[k - 1].endswith("(") and not (mask and mask[k - 1]) if not opened and not _runs_as_command(toks, k, mask): continue if j >= end: + if appended: + return "a `git` with no subcommand word that `xargs` runs", ( + "xargs appends the words it reads from its input to the command it runs, " + "so the guard cannot read them, and they may name any subcommand, a push " + "or a reset among them. Failing closed. Run the git command as its own " + "command with every word written out." + ) if any( _is_run_time_word(toks[x]) and not _split_free(x, toks, mask, raw) for x in range(k + 1, end) @@ -5992,6 +6337,32 @@ def _rewritten_git_words(cmd): return "a run-time word among the options of a `git` with no subcommand word" continue sub = toks[j] + reps = _xargs_replace_strings(toks, k) if _xargs_command(toks, k, mask) else [] + held = next((r for r in reps if r in sub), None) + configured = any( + r in toks[x] + and (toks[x - 1] in ("-c", "--config-env") or toks[x].startswith("--config-env")) + for x in range(k + 1, j) + for r in reps + ) + held = held or (next(iter(reps)) if configured else None) + if held is None and any(r in toks[x] for x in range(k + 1, j) for r in reps): + verdict = _primary_checkout_verdict( + sub, _collect_arglist(toks, j + 1)[0], None, lambda _d, _r: False + ) + mutates = verdict or (verdict is None and sub not in _git_command_names()) + spliced = _xargs_replace_strings(toks, k, spliced=True) + mutates = mutates or sub in ("push", "commit") or bool(spliced) + held = next(r for r in reps) if mutates else None + if held is not None: + return ( + f"an `xargs` replace string, `{held}`, in the subcommand or global options of `git`", + ( + "xargs puts each word it reads there, so the guard cannot read the subcommand " + "or the directory git runs. Failing closed. Run the git command as its own " + "command with every word written out." + ), + ) if _is_run_time_word(sub): return f"a run-time word, `{sub}`, where the subcommand of `git` goes" redirected = _is_redir_op(sub) or ( @@ -6157,10 +6528,10 @@ def _push_invocations(cmd): repo_unreliable = ( wrapped_cd or redirected - or config_moves or _repo_may_move( body_toks, word, leading_cd, quoted if body is text else None ) + or (_CONFIG_UNRESOLVED if config_moves else False) ) unreliable = extra > 0 or head_moves or repo_unreliable refs_moves = head_moves or repo_unreliable @@ -6289,6 +6660,7 @@ def _remote_mirrors(cwd, remote): _REMOTE_UNRESOLVED = object() +_CONFIG_UNRESOLVED = object() _SCP_LIKE_URL = re.compile(r"^[^/]+:") _DOS_DRIVE_PATH = re.compile(r"^[A-Za-z]:") @@ -7217,8 +7589,12 @@ def _push_repo(cwd, c_dirs, leading_cd, repo_unreliable): """The (owner, repo) origin of the checkout a push the command moves to runs in, or `_UNRESOLVED`. That checkout's origin may differ from the session's. A directory that does not resolve, or a - checkout with no origin the guard can read, is `_UNRESOLVED`. + checkout with no origin the guard can read, is `_UNRESOLVED`. A push whose repository only + an earlier command rewriting its remote config may move is `_CONFIG_UNRESOLVED`, so the deny + names that cause. """ + if repo_unreliable is _CONFIG_UNRESOLVED: + return _CONFIG_UNRESOLVED target = _push_dir(cwd, c_dirs, leading_cd, repo_unreliable) repo = None if target is _UNRESOLVED else _origin_owner_repo(target) return _UNRESOLVED if repo is None else repo @@ -7310,7 +7686,7 @@ def _check_push_bypass(cmd, cwd, origin, current_branch=None, rules_lookup=None) ":refs/heads/)." + _handoff(cmd) ) readings = [None] - unnamed = repo is _UNRESOLVED or repo is _REMOTE_UNRESOLVED + unnamed = repo in (_UNRESOLVED, _REMOTE_UNRESOLVED, _CONFIG_UNRESOLVED) if repo is not None and repo != origin and (unnamed or rules_lookup is None): readings.append(repo) for checkout in readings: @@ -7337,6 +7713,13 @@ def _check_push_bypass(cmd, cwd, origin, current_branch=None, rules_lookup=None) "rules could not be read. Run the push from that checkout's own directory, or " "with -C naming a directory that exists" ) + elif checkout is _CONFIG_UNRESOLVED: + rules, where = None, "" + reason = ( + "an earlier command in it may rewrite the remote config the push reads, so " + "its remote's repository and mirror setting could not be read. Run the push " + "as its own command, after the command that changes the config" + ) elif checkout is _REMOTE_UNRESOLVED: rules, where = None, "" reason = ( @@ -8935,6 +9318,25 @@ def classify( "commit as its own command with every word written out, and a push with an explicit " "refspec (git push origin :refs/heads/)." + _handoff(cmd) ) + filled = _xargs_filled_body(cmd) + if filled is not None: + return "deny", ( + f"This command runs a shell command string, `{filled}`, that `xargs` fills with the " + "words it reads, and the string runs git or gh. The inner shell parses each word, so " + "one holding a `;` or a line break adds whole commands the guard cannot read. Failing " + "closed. Pass each word as an argument, as in xargs sh -c '... \"$1\"' _, or run the " + "command with every word written out." + _handoff(cmd) + ) + expanded = _outer_expanded_body(cmd) + if expanded is not None: + return "deny", ( + f"This command runs a double-quoted wrapper body, `{expanded}`, holding a `$` or " + "backtick word the outer shell expands before the inner shell parses the body, so a " + "value holding a `;` or a line break adds whole commands the guard cannot read, and " + "the body runs git or gh. Failing closed. Single-quote the body and pass the value as " + 'an argument, as in sh -c \'... "$1"\' _ "$VALUE", or run the command directly.' + + _handoff(cmd) + ) # The `_push_targets` helper tokenizes with shlex and keys off a real `git push` argv adjacency, so a push named only inside a quoted argument yields no target. # The raw substring is just a cheap pre-filter. if _names_push(cmd) or _names_include(cmd): @@ -8964,6 +9366,17 @@ def classify( "handling, or ids. Failing closed. Run the gh command with fewer levels of nesting." + _handoff(cmd) ) + if ( + _NAMES_GH.search(cmd) + and "xargs" in cmd + and any(_xargs_gh_unread(t) for t in _data_free_texts(cmd)) + ): + return "deny", ( + "This runs a gh command under `xargs`, which appends the words it reads from its " + "input, or puts them where its replace string sits, where the guard cannot read them. " + "They may name a write, a --repo under another owner, or a body. Failing closed. " + "Write every word of the gh command out." + _handoff(cmd) + ) payloads = _eval_payload_texts(_data_free_texts(cmd)) if "eval" in cmd else [] eval_write = any(_names_gh_write(t) for t in payloads) if not eval_write and not _is_gh_write(cmd): @@ -9762,171 +10175,333 @@ def _nested_wrapper(body, depth): _STRANGER_GH_REPO = {"GH_REPO": "stranger/example"} _GH_TARGET_CASES: list[tuple[str, dict[str, str], str, str]] = [ ( - "gh pr comment 5 --body hi", - _STRANGER_GH_REPO, + "printf -- '-R stranger/example' | xargs gh pr comment 5 -b x", + {}, "deny", - "a GH_REPO the session's environment holds", + "a gh write that xargs runs may take a --repo from its input", ), ( - "bash -c 'gh issue comment 5 --body hi'", - _STRANGER_GH_REPO, + "echo stranger/example | xargs -I{} gh pr comment 5 -b x -R {}", + {}, "deny", - "an environment GH_REPO in a wrapper", + "a repo flag value an xargs replace string fills is not read", ), ( - "gh api -X POST repos/{owner}/{repo}/issues/1/comments -f body=x", - _STRANGER_GH_REPO, + "echo comment 5 -b x | xargs gh pr", + {}, "deny", - "an environment GH_REPO filling api placeholders", + "a gh naming no subcommand under xargs may take a write from its input", ), ( - 'GH_REPO="$T"; gh pr comment 5 --body hi', - _STRANGER_GH_REPO, + "echo -XPOST repos/stranger/example/issues | xargs gh api", + {}, "deny", - "a run-time plain GH_REPO, exported", + "a gh api call xargs appends to may take a method and an endpoint from its input", ), - ("gh pr view 5", _STRANGER_GH_REPO, "allow", "an environment GH_REPO on a read"), ( - "flock /tmp/l gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "echo https://github.com/stranger/example/pull/5 | xargs gh pr comment --body x", + {}, "deny", - "an environment GH_REPO behind a launcher", + "an xargs input word naming a URL is not inert", ), ( - "find . -name x -exec gh pr comment 5 -b x +", - _STRANGER_GH_REPO, - "deny", - "an environment GH_REPO behind find -exec", + "echo 5 | xargs gh pr view --comments", + {}, + "allow", + "control: a gh read whose subcommand is written out takes no write from xargs", ), ( - "if false; then export GH_REPO=example/repo; fi; gh pr comment 5 -b x", - _STRANGER_GH_REPO, - "deny", - "an export in an untaken branch does not replace an environment GH_REPO", + "printf '5\\n6\\n' | xargs -n1 gh pr comment --body x", + {}, + "allow", + "control: a written-out gh write that xargs feeds only inert literal words is read", ), ( - "GH_REPO=example/repo bash -c 'gh pr comment 5 -b x'", - _STRANGER_GH_REPO, + "ls | xargs grep -l gh", + {}, "allow", - "a wrapper prefix replaces an environment GH_REPO", + "control: a gh word that is an argument of the command xargs runs runs nothing", ), - ("echo gh pr comment 5 -b x", _STRANGER_GH_REPO, "allow", "a gh word that is an argument"), ( - "false && export GH_REPO=example/repo; gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "uv run env GH_REPO=stranger/example gh pr comment 5 --body x", + {"GH_REPO": "example/other"}, "deny", - "a conditional export does not replace an environment GH_REPO", + "a GH_REPO an env passes behind an unknown launcher is read beside the session's own", ), ( - "export GH_REPO=example/repo & gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "uv run sudo GH_REPO=stranger/example gh pr comment 5 --body x", + {}, "deny", - "a backgrounded export does not replace an environment GH_REPO", + "a GH_REPO a sudo passes behind an unknown launcher is read", ), ( - "export GH_REPO=example/repo | cat; gh pr comment 5 -b x", - _STRANGER_GH_REPO, - "deny", - "an export in a pipeline does not replace an environment GH_REPO", + "uv run env GH_REPO=example/other gh pr comment 5 --body x", + {}, + "allow", + "control: a same-owner GH_REPO an env passes behind an unknown launcher is allowed", ), ( - "case a in a) true;; esac; (true; export GH_REPO=example/repo); gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "echo '-R stranger/example' | xargs -I{} sh -c 'gh pr comment 5 -b x {}'", + {}, "deny", - "a subshell export past a case does not replace an environment GH_REPO", + "a shell string that xargs fills and that runs gh may take a --repo from its input", ), ( - "f() { export GH_REPO=example/repo; }; gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "echo delete 5 -R stranger/example | xargs gh repo deploy-key", + {}, "deny", - "a function's export does not replace an environment GH_REPO", + "a three-word gh write missing its third word under xargs may take it from its input", ), ( - "(export GH_REPO=example/repo; gh pr view 1); gh pr comment 5 -b x", - _STRANGER_GH_REPO, + "echo 'mutation{x}' | xargs -I{} gh api graphql -f query={}", + {}, "deny", - "a subshell export does not replace an environment GH_REPO", + "a gh api field holding the xargs replace string may be a mutation", ), ( - 'echo "run: gh pr comment 5 -b hi"; export GH_REPO=stranger/example; o="$(gh pr comment 5 -b hi)"', + "printf -- '-XPOST -f title=x' | xargs stdbuf -i0 gh api repos/stranger/example/issues", {}, "deny", - "a substitution runs under the value at the word opening it", + "a launcher option shaped like a replace option leaves xargs appending to gh api", ), ( - "gh repo delete ssh://git@github.com/stranger/example.git --yes", + "printf 5 | xargs --max-args=1 gh pr comment --body x", {}, - "deny", - "an ssh URL repo positional", + "allow", + "control: an xargs long option that reads no file keeps inert input inert", ), ( - "gh issue transfer 1 git@github.com:stranger/example.git", + "echo 5 | xargs -I{} gh api repos/example/repo/pulls/{}", {}, - "deny", - "an scp-form destination", + "allow", + "control: a gh api read whose endpoint alone holds the replace string is read", ), ( - "$G api graphql -f query='mutation($i: ID!) { m(input: {id: $i}) { x } }' -F i=PR_kwDOABCDEFGHIJKLMNOP", + "gh pr list --json number -q '.[].number' | xargs -I{} gh pr view {}", {}, - "deny", - "a literal node id in a mutation behind a run-time command word", + "allow", + "control: a gh read whose target alone holds the replace string is read", ), ( - "gh pr comment 5 -R example/repo --body hi", - _STRANGER_GH_REPO, + "printf 5 | xargs -I{} gh pr comment {} --body x", + {}, "allow", - "a repo flag overrides it", + "control: a written-out gh write whose target an inert replace fills is read", ), ( - "GH_REPO=example/repo gh pr comment 5 --body hi", - _STRANGER_GH_REPO, + "echo 5 | xargs --replace gh api repos/example/repo/pulls/{}", + {}, "allow", - "a prefix overrides it", + "control: a long --replace is read as xargs's own replace option", ), - ("gh pr comment 5 --body hi", {"GH_REPO": "example/other"}, "allow", "a sibling one"), - ('gh "$R" pr comment 5 --body hi', {}, "deny", "a quoted run-time word before pr comment"), - ('gh pr "$R" comment 5 --body hi', {}, "deny", "a quoted run-time word before comment"), - ('gh "$F" x pr comment 5 --body hi', {}, "deny", "a run-time flag taking the next word"), ( - 'gh "$R" api -X POST repos/example/repo/issues -f title=t', + "printf 5 | xargs gh pr comment --body x <<< '-R stranger/example 9'", {}, "deny", - "a run-time word before an api write", + "a redirection of xargs's input replaces the inert pipe", ), - ('gh "$R" pr view 5', {}, "allow", "a run-time word before a read"), - ('gh pr "$S" 5', {}, "allow", "a quoted run-time subcommand with no write behind it"), ( - "GH_REPO=stranger/example; export GH_REPO; gh pr comment 5 --body hi", + "printf stranger | xargs gh secret set TOKEN --body x --org", {}, "deny", - "a bare export of a plain GH_REPO", + "an inert word that lands as an owner flag's value names an owner", ), ( - "export GH_REPO; GH_REPO=stranger/example; gh pr comment 5 --body hi", + "printf -- '-XPOST repos/stranger/example/issues -f title=x' | xargs -J% gh api %", {}, "deny", - "a plain GH_REPO after a bare export", + "a BSD -J splices words of their own, so a gh api endpoint holding it is no read", ), ( - "export A GH_REPO=stranger/example; gh pr comment 5 --body hi", + "export GH_REPO=stranger/example; find ./env -name GH_REPO=example/x -exec sh -c 'gh pr comment 5 -b x' \\; ; GH_REPO=example/y sh -c 'gh pr view 1'", {}, "deny", - "a GH_REPO export past a bare name", + "each GH_REPO value reaching a wrapper body is read on its own, not collapsed to the last", ), ( - "GH_REPO=stranger/example; gh pr comment 5 --body hi", + "printf 5 | Date: Thu, 22 Oct 2026 21:17:31 -0700 Subject: [PATCH 6/6] Name the Character Set Pointer's Tier System as Character-Set (#3396) Co-Authored-By: Claude Sonnet 5.5 --- GOVERNANCE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 14e4cc562..a34d710ad 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -171,7 +171,7 @@ No comment, no docstring, and no instruction document names an issue, a pull req ### Character Set -The full ASCII tier system (never legitimate, legitimate next to a number, always legitimate, a fixed set of emoji callout markers, developer-typed Unicode), the letters of a recorded name keeping their actual spelling, and the semicolon and spaced-hyphen rules are in the `comment-and-doc-style` Skill referenced above. +The full character-set tier system (never legitimate, legitimate next to a number, always legitimate, a fixed set of emoji callout markers, developer-typed Unicode), the letters of a recorded name keeping their actual spelling, and the semicolon and spaced-hyphen rules are in the `comment-and-doc-style` Skill referenced above. ### Line Endings