Skip to content

refactor: tighten privacy audit and runtime contracts - #283

Merged
Sinity merged 4 commits into
masterfrom
feature/refactor/privacy-audit-utility-runtime-contracts
Apr 21, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/refactor/privacy-audit-utility-runtime-contracts

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Tighten privacy, audit, redaction, query sorting, preparation, and scenario runtime contracts by replacing loose Any boundaries with explicit object, protocol, JSON, and parsed-conversation types.
  • Fix source-checkout version resolution for linked git worktrees by resolving symbolic refs through the common git directory.
  • Tighten report payload tests so strict mypy can index JSON-shaped outputs only after runtime narrowing, and disable Hypothesis deadlines for timing-variable report serialization properties.

Ref #281

Problem

The remaining runtime/reporting seams still carried broad Any annotations and ad hoc payload assumptions. Those loose contracts obscured the actual shape of privacy config overrides, report JSON payloads, query sort keys, parsed conversation preparation, and runner dispatch results.

Linked worktree checkouts also failed version resolution because symbolic branch refs were read only from the worktree git directory, not from the common git dir where normal branch refs live.

Solution

  • Added a runtime-checkable privacy config protocol and narrowed enum-value checking to string values after explicit config override handling.
  • Introduced typed JSON document returns for outcome, audit, and redaction reports, with downstream markdown/tests narrowing JSON unions before indexing.
  • Typed query sort keys, preparation inputs, and scenario runner dispatch returns without changing runtime behavior.
  • Resolved linked-worktree version metadata through commondir.
  • Updated report property tests to avoid deadline flakes under xdist and strict typing.

Verification

  • ruff check polylogue/schemas/privacy.py polylogue/scenarios/runtime.py polylogue/lib/outcomes.py polylogue/lib/query_sorting.py polylogue/lib/query_plan.py polylogue/pipeline/prepare.py polylogue/schemas/audit_models.py polylogue/schemas/redaction_report.py polylogue/showcase/qa_markdown.py polylogue/version.py
  • mypy polylogue/schemas/privacy.py polylogue/scenarios/runtime.py polylogue/lib/outcomes.py polylogue/lib/query_sorting.py polylogue/lib/query_plan.py polylogue/pipeline/prepare.py polylogue/schemas/audit_models.py polylogue/schemas/redaction_report.py polylogue/showcase/qa_markdown.py polylogue/version.py
  • pytest -q tests/unit/core/test_privacy_guards.py tests/unit/core/test_schema_privacy.py tests/unit/core/test_privacy_config.py tests/unit/scenarios/test_runtime.py tests/unit/pipeline/test_prepare.py tests/unit/pipeline/test_prepare_records.py tests/unit/core/test_audit.py tests/unit/core/test_redaction_report.py tests/unit/showcase/test_qa_markdown.py tests/unit/showcase/test_report.py
  • PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quick
  • Pre-push hook: devtools verify --quick
  • Basename-correct detached verification worktree: PATH=/tmp/polylogue-281-verify/polylogue/.cache/codex-bin:$PATH devtools verify reached and passed pytest; the first overall exit was nonzero only because ignored AGENTS.md was absent in the fresh detached worktree. After devtools render-agents --input CLAUDE.md --output AGENTS.md, PATH=/tmp/polylogue-281-verify/polylogue/.cache/codex-bin:$PATH devtools verify --quick passed.

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 45 minutes and 28 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 45 minutes and 28 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e924db2e-8e64-4f14-b8c2-cf7f0d61ff1c

📥 Commits

Reviewing files that changed from the base of the PR and between 11df8fc and eff08b5.

📒 Files selected for processing (11)
  • polylogue/artifact_graph.py
  • polylogue/artifacts.py
  • polylogue/maintenance_models.py
  • polylogue/maintenance_targets.py
  • polylogue/operations/specs.py
  • polylogue/publication.py
  • polylogue/showcase/report_files.py
  • polylogue/storage/artifact_persistence.py
  • polylogue/storage/derived_status_products.py
  • tests/unit/core/test_artifact_graph.py
  • tests/unit/showcase/test_qa_markdown.py
📝 Walkthrough

Walkthrough

This pull request systematically improves type safety across the codebase by replacing loose Any types with concrete types, introducing the SortKey type alias, wrapping JSON returns with JSONDocument, adding a PrivacyConfigLike Protocol, and adjusting runtime type checks and git worktree handling.

Changes

Cohort / File(s) Summary
Type Alias & Generic Sorting
polylogue/lib/query_plan.py, polylogue/lib/query_sorting.py
Introduced SortKey type alias (`datetime
JSON Serialization Typing
polylogue/lib/outcomes.py, polylogue/schemas/audit_models.py, polylogue/schemas/redaction_report.py
Updated return types from dict[str, Any] to JSONDocument and wrapped dictionary construction with json_document(...) calls while preserving JSON structure.
Function Parameter Type Tightening
polylogue/pipeline/prepare.py, polylogue/schemas/privacy.py
Replaced Any parameter types with concrete types: prepare_bundle/prepare_records now expect ParsedConversation; added PrivacyConfigLike Protocol and narrowed _is_safe_enum_value parameters from Any to object.
Runtime & Logic Adjustments
polylogue/scenarios/runtime.py, polylogue/showcase/qa_markdown.py, polylogue/version.py
Updated dispatch_execution return type to object; replaced inspect.isawaitable() with isinstance(dispatched, Awaitable); made qa_markdown summary access safer with .get() default; enhanced git worktree support in version resolution.
Test Assertion Improvements
tests/unit/core/test_audit.py, tests/unit/core/test_redaction_report.py, tests/unit/showcase/test_report.py
Added explicit type assertions (dict, list) on extracted JSON payloads; tightened parameter type annotations from Any to int in Hypothesis tests; added deadline=None to test timeouts.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Type guards now guard with care and grace,
No more Any floating through this place!
SortKey sorts and JSONDocument seals,
Protocols define what privacy feels.
More explicit, more clear—debugging appeals! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.24% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: tighten privacy audit and runtime contracts' clearly and accurately summarizes the main change: tightening type contracts across privacy, audit, and runtime modules by replacing loose Any annotations with explicit types.
Description check ✅ Passed The description comprehensively follows the template structure with all required sections (Summary, Problem, Solution, Verification) completed in detail, including specific modules touched, the rationale for changes, and exact verification commands.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/privacy-audit-utility-runtime-contracts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 11df8fcc62

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +112 to +113
if isinstance(dispatched, Awaitable):
return await dispatched

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore full awaitable detection in runner dispatch

dispatch_execution now uses isinstance(dispatched, Awaitable), which does not recognize generator-based coroutines (for example, runners implemented with @types.coroutine). In those cases the runner result is returned as a raw generator instead of being awaited, so the execution body never runs and callers receive the wrong object type; this regresses behavior that previously worked via inspect.isawaitable.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
polylogue/showcase/qa_markdown.py (1)

63-68: ⚠️ Potential issue | 🟡 Minor

Inconsistent defensiveness around summary.

.get("summary", {}) tolerates a missing summary key, but the very next lines index audit_summary['passed'|'warned'|'failed'] unguarded — so on the empty-default path you'd trade a KeyError on "summary" for a KeyError on "passed". Since AuditReport.to_json() always emits summary, the .get default is dead defense. Either drop the default (keep types honest) or make downstream access symmetric via .get(..., 0).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/showcase/qa_markdown.py` around lines 63 - 68, The code obtains
audit_summary via _payload_mapping(result.audit_report.to_json().get("summary",
{})) but then indexes into audit_summary['passed'|'warned'|'failed'] unguarded;
either remove the dead default on .get and rely on AuditReport.to_json() always
providing "summary" (i.e., call result.audit_report.to_json()["summary"] so
missing-key errors reflect real issues), or keep the safe path and make the
downstream accesses defensive by fetching counts with .get('passed', 0),
.get('warned', 0), and .get('failed', 0) before formatting lines; update the
code around audit_summary and the lines that append Passed/Warned/Failed
accordingly (refer to audit_summary, _payload_mapping, and
result.audit_report.to_json()).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/scenarios/runtime.py`:
- Around line 111-114: The dispatch code is using isinstance(dispatched,
Awaitable) which misses generator-based coroutines; replace that check with
inspect.isawaitable(dispatched) (import inspect if missing) so all awaitable
kinds are awaited when returned from runner in the dispatch logic (the variable
dispatched produced by runner(*runner_args, **dict(runner_kwargs or {}))).
Ensure the returned value is awaited if inspect.isawaitable(dispatched) is true,
matching the existing pattern used in _resolve_maybe_awaitable.

In `@polylogue/schemas/audit_models.py`:
- Around line 75-85: The current serializer builds the checks list by assigning
"details": c.details by reference, which can lead to shared-mutation bugs;
update the comprehension in the checks serialization to copy details (e.g., use
list(c.details) or an appropriate shallow copy) so the returned JSON payload is
independent of the underlying AuditCheck objects—mirror the behavior of
OutcomeCheck.to_dict to ensure symmetry and safety when mutating the returned
document.

In `@polylogue/schemas/privacy.py`:
- Around line 233-254: The field-level "allow" currently short-circuits for any
value type; update the logic in the privacy check so that non-string values are
rejected before honoring an "allow" return. Concretely: keep the
field_override(path) check for "deny" returning False immediately, but only
treat field_override(path) == "allow" as a True short-circuit if
isinstance(value, str); move or add the non-string guard (not isinstance(value,
str) -> False) to run before applying an "allow" short-circuit, while preserving
existing value-level checks (privacy_config.is_value_allowed) and the fallback
to privacy_config.safe_enum_max_length when max_length is None.

In `@polylogue/version.py`:
- Around line 110-120: Hoist the call to _resolve_common_git_dir(git_dir) into a
local variable (e.g. common_git_dir) and use that variable both in the for loop
over (git_dir, common_git_dir) and in the fallback call to
_read_packed_ref(common_git_dir, ref_name); this avoids calling
_resolve_common_git_dir twice and prevents iterating the same directory twice
when commondir is absent while preserving the existing logic around ref_path,
commit validation, and the final fallback.

---

Outside diff comments:
In `@polylogue/showcase/qa_markdown.py`:
- Around line 63-68: The code obtains audit_summary via
_payload_mapping(result.audit_report.to_json().get("summary", {})) but then
indexes into audit_summary['passed'|'warned'|'failed'] unguarded; either remove
the dead default on .get and rely on AuditReport.to_json() always providing
"summary" (i.e., call result.audit_report.to_json()["summary"] so missing-key
errors reflect real issues), or keep the safe path and make the downstream
accesses defensive by fetching counts with .get('passed', 0), .get('warned', 0),
and .get('failed', 0) before formatting lines; update the code around
audit_summary and the lines that append Passed/Warned/Failed accordingly (refer
to audit_summary, _payload_mapping, and result.audit_report.to_json()).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 65249127-700c-4e01-91de-18f1c40e99e3

📥 Commits

Reviewing files that changed from the base of the PR and between 1e9c6af and 11df8fc.

📒 Files selected for processing (13)
  • polylogue/lib/outcomes.py
  • polylogue/lib/query_plan.py
  • polylogue/lib/query_sorting.py
  • polylogue/pipeline/prepare.py
  • polylogue/scenarios/runtime.py
  • polylogue/schemas/audit_models.py
  • polylogue/schemas/privacy.py
  • polylogue/schemas/redaction_report.py
  • polylogue/showcase/qa_markdown.py
  • polylogue/version.py
  • tests/unit/core/test_audit.py
  • tests/unit/core/test_redaction_report.py
  • tests/unit/showcase/test_report.py

Comment on lines 111 to +114
dispatched = runner(*runner_args, **dict(runner_kwargs or {}))
return await dispatched if inspect.isawaitable(dispatched) else dispatched
if isinstance(dispatched, Awaitable):
return await dispatched
return dispatched

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Demonstrate that inspect.isawaitable() accepts awaitable objects
# that isinstance(..., collections.abc.Awaitable) can miss.

python - <<'PY'
import inspect
import types
from collections.abc import Awaitable

`@types.coroutine`
def legacy_coroutine():
    yield
    return "ok"

value = legacy_coroutine()

print("inspect.isawaitable:", inspect.isawaitable(value))
print("isinstance Awaitable:", isinstance(value, Awaitable))
PY

Repository: Sinity/polylogue

Length of output: 113


🏁 Script executed:

cat -n polylogue/scenarios/runtime.py | head -150 | tail -50

Repository: Sinity/polylogue

Length of output: 2085


🏁 Script executed:

rg "inspect" polylogue/scenarios/runtime.py

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

rg "inspect\.isawaitable" --type py

Repository: Sinity/polylogue

Length of output: 326


🏁 Script executed:

rg "isinstance.*Awaitable" polylogue/scenarios/runtime.py

Repository: Sinity/polylogue

Length of output: 105


🏁 Script executed:

head -20 polylogue/scenarios/runtime.py

Repository: Sinity/polylogue

Length of output: 567


🏁 Script executed:

rg "ExecutionRunner" polylogue/scenarios/runtime.py -A 2 -B 2

Repository: Sinity/polylogue

Length of output: 832


🏁 Script executed:

cat polylogue/cli/query.py | head -60 | tail -20

Repository: Sinity/polylogue

Length of output: 554


🏁 Script executed:

rg "dispatch_execution" --type py -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 3270


🏁 Script executed:

grep -r "legacy_coroutine\|types\.coroutine" polylogue tests/ --include="*.py"

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

cat polylogue/cli/query.py | grep -A 10 "_resolve_maybe_awaitable"

Repository: Sinity/polylogue

Length of output: 863


Restore inspect.isawaitable() to avoid leaking unawaited coroutines from runner dispatch.

isinstance(dispatched, Awaitable) misses generator-based coroutines and other awaitable objects that inspect.isawaitable() detects. The ExecutionRunner type signature allows either object | Awaitable[object], so the dispatch must handle all awaitable kinds. Currently, a runner returning a generator-based coroutine will bypass the isinstance check and be returned directly without awaiting, contradicting the async function's contract.

The codebase already uses this pattern elsewhere (e.g., polylogue/cli/query.py:_resolve_maybe_awaitable), which uses inspect.isawaitable() with a cast for type safety.

🐛 Proposed fix
+import inspect
 import os
 import subprocess
 from collections.abc import Awaitable, Callable, Mapping, Sequence
 from dataclasses import dataclass
 from pathlib import Path
+from typing import cast
@@
         runner = resolve_execution_runner(execution, runner_resolver=runner_resolver)
         dispatched = runner(*runner_args, **dict(runner_kwargs or {}))
-        if isinstance(dispatched, Awaitable):
-            return await dispatched
+        if inspect.isawaitable(dispatched):
+            return await cast(Awaitable[object], dispatched)
         return dispatched
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
dispatched = runner(*runner_args, **dict(runner_kwargs or {}))
return await dispatched if inspect.isawaitable(dispatched) else dispatched
if isinstance(dispatched, Awaitable):
return await dispatched
return dispatched
dispatched = runner(*runner_args, **dict(runner_kwargs or {}))
if inspect.isawaitable(dispatched):
return await cast(Awaitable[object], dispatched)
return dispatched
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/scenarios/runtime.py` around lines 111 - 114, The dispatch code is
using isinstance(dispatched, Awaitable) which misses generator-based coroutines;
replace that check with inspect.isawaitable(dispatched) (import inspect if
missing) so all awaitable kinds are awaited when returned from runner in the
dispatch logic (the variable dispatched produced by runner(*runner_args,
**dict(runner_kwargs or {}))). Ensure the returned value is awaited if
inspect.isawaitable(dispatched) is true, matching the existing pattern used in
_resolve_maybe_awaitable.

Comment on lines +75 to +85
"checks": [
{
"name": c.name,
"provider": getattr(c, "provider", None),
"status": self._LABELS[c.status],
"message": c.summary,
"details": c.details,
}
for c in self.checks
],
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Minor: details aliased into JSON payload.

Unlike OutcomeCheck.to_dict (which emits list(self.details)), this serialization assigns c.details by reference. A caller that mutates the returned JSON document (e.g., append to a check's details) will mutate the underlying AuditCheck, and vice-versa. Consider copying for symmetry and safety.

Proposed fix
-                        "details": c.details,
+                        "details": list(c.details),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/schemas/audit_models.py` around lines 75 - 85, The current
serializer builds the checks list by assigning "details": c.details by
reference, which can lead to shared-mutation bugs; update the comprehension in
the checks serialization to copy details (e.g., use list(c.details) or an
appropriate shallow copy) so the returned JSON payload is independent of the
underlying AuditCheck objects—mirror the behavior of OutcomeCheck.to_dict to
ensure symmetry and safety when mutating the returned document.

Comment on lines +233 to +254
privacy_config = config if isinstance(config, PrivacyConfigLike) else None

if privacy_config is not None:
# Field-level override
field_action = config.field_override(path)
field_action = privacy_config.field_override(path)
if field_action == "allow":
return True
if field_action == "deny":
return False
# Value-level override
if isinstance(value, str):
val_override = config.is_value_allowed(value)
val_override = privacy_config.is_value_allowed(value)
if val_override is True:
return True
if val_override is False:
return False
# Use config's max_length if not explicitly overridden
if max_length is None:
effective_max_len = config.safe_enum_max_length
effective_max_len = privacy_config.safe_enum_max_length

if not isinstance(value, str):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Reject non-string values before honoring field-level allow.

Line 238 can return True for any object when field_override(path) == "allow", so non-string observed/redaction values bypass the new runtime guard. Keep deny highest precedence, but only let allow short-circuit after value is confirmed to be a str.

🛡️ Proposed fix
     # Check config-level overrides first (highest precedence)
     privacy_config = config if isinstance(config, PrivacyConfigLike) else None
 
+    field_action: str | None = None
     if privacy_config is not None:
         # Field-level override
         field_action = privacy_config.field_override(path)
-        if field_action == "allow":
-            return True
         if field_action == "deny":
             return False
+
+    if not isinstance(value, str):
+        return False
+
+    if privacy_config is not None:
+        if field_action == "allow":
+            return True
         # Value-level override
-        if isinstance(value, str):
-            val_override = privacy_config.is_value_allowed(value)
-            if val_override is True:
-                return True
-            if val_override is False:
-                return False
+        val_override = privacy_config.is_value_allowed(value)
+        if val_override is True:
+            return True
+        if val_override is False:
+            return False
         # Use config's max_length if not explicitly overridden
         if max_length is None:
             effective_max_len = privacy_config.safe_enum_max_length
 
-    if not isinstance(value, str):
-        return False
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/schemas/privacy.py` around lines 233 - 254, The field-level "allow"
currently short-circuits for any value type; update the logic in the privacy
check so that non-string values are rejected before honoring an "allow" return.
Concretely: keep the field_override(path) check for "deny" returning False
immediately, but only treat field_override(path) == "allow" as a True
short-circuit if isinstance(value, str); move or add the non-string guard (not
isinstance(value, str) -> False) to run before applying an "allow"
short-circuit, while preserving existing value-level checks
(privacy_config.is_value_allowed) and the fallback to
privacy_config.safe_enum_max_length when max_length is None.

Comment thread polylogue/version.py
Comment on lines +110 to +120
for ref_root in (git_dir, _resolve_common_git_dir(git_dir)):
ref_path = ref_root / ref_name
if not ref_path.exists():
continue
try:
commit = ref_path.read_text(encoding="utf-8").strip()
except OSError:
return None
return commit if re.fullmatch(r"[0-9a-f]{40}", commit) else None
return _read_packed_ref(git_dir, ref_name)
continue
if re.fullmatch(r"[0-9a-f]{40}", commit):
return commit
return _read_packed_ref(_resolve_common_git_dir(git_dir), ref_name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Minor: compute the common git dir once.

_resolve_common_git_dir(git_dir) is invoked twice (loop init and packed-refs fallback) which re-reads/parses the commondir file each time. Also, when git_dir has no commondir, the loop iterates the same directory twice. Hoisting it into a local avoids both:

♻️ Proposed refactor
-    for ref_root in (git_dir, _resolve_common_git_dir(git_dir)):
-        ref_path = ref_root / ref_name
-        if not ref_path.exists():
-            continue
+    common_dir = _resolve_common_git_dir(git_dir)
+    search_roots = (git_dir,) if common_dir == git_dir else (git_dir, common_dir)
+    for ref_root in search_roots:
+        ref_path = ref_root / ref_name
+        if not ref_path.exists():
+            continue
         try:
             commit = ref_path.read_text(encoding="utf-8").strip()
         except OSError:
             continue
         if re.fullmatch(r"[0-9a-f]{40}", commit):
             return commit
-    return _read_packed_ref(_resolve_common_git_dir(git_dir), ref_name)
+    return _read_packed_ref(common_dir, ref_name)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for ref_root in (git_dir, _resolve_common_git_dir(git_dir)):
ref_path = ref_root / ref_name
if not ref_path.exists():
continue
try:
commit = ref_path.read_text(encoding="utf-8").strip()
except OSError:
return None
return commit if re.fullmatch(r"[0-9a-f]{40}", commit) else None
return _read_packed_ref(git_dir, ref_name)
continue
if re.fullmatch(r"[0-9a-f]{40}", commit):
return commit
return _read_packed_ref(_resolve_common_git_dir(git_dir), ref_name)
common_dir = _resolve_common_git_dir(git_dir)
search_roots = (git_dir,) if common_dir == git_dir else (git_dir, common_dir)
for ref_root in search_roots:
ref_path = ref_root / ref_name
if not ref_path.exists():
continue
try:
commit = ref_path.read_text(encoding="utf-8").strip()
except OSError:
continue
if re.fullmatch(r"[0-9a-f]{40}", commit):
return commit
return _read_packed_ref(common_dir, ref_name)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/version.py` around lines 110 - 120, Hoist the call to
_resolve_common_git_dir(git_dir) into a local variable (e.g. common_git_dir) and
use that variable both in the for loop over (git_dir, common_git_dir) and in the
fallback call to _read_packed_ref(common_git_dir, ref_name); this avoids calling
_resolve_common_git_dir twice and prevents iterating the same directory twice
when commondir is absent while preserving the existing logic around ref_path,
commit validation, and the final fallback.

@Sinity
Sinity merged commit 2356602 into master Apr 21, 2026
13 checks passed
@Sinity
Sinity deleted the feature/refactor/privacy-audit-utility-runtime-contracts branch April 21, 2026 07:02
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary

- Tighten privacy, audit, redaction, query sorting, preparation, and scenario runtime contracts by replacing loose `Any` boundaries with explicit object, protocol, JSON, and parsed-conversation types.
- Fix source-checkout version resolution for linked git worktrees by resolving symbolic refs through the common git directory.
- Tighten report payload tests so strict mypy can index JSON-shaped outputs only after runtime narrowing, and disable Hypothesis deadlines for timing-variable report serialization properties.

Ref #281

## Problem

The remaining runtime/reporting seams still carried broad `Any` annotations and ad hoc payload assumptions. Those loose contracts obscured the actual shape of privacy config overrides, report JSON payloads, query sort keys, parsed conversation preparation, and runner dispatch results.

Linked worktree checkouts also failed version resolution because symbolic branch refs were read only from the worktree git directory, not from the common git dir where normal branch refs live.

## Solution

- Added a runtime-checkable privacy config protocol and narrowed enum-value checking to string values after explicit config override handling.
- Introduced typed JSON document returns for outcome, audit, and redaction reports, with downstream markdown/tests narrowing JSON unions before indexing.
- Typed query sort keys, preparation inputs, and scenario runner dispatch returns without changing runtime behavior.
- Resolved linked-worktree version metadata through `commondir`.
- Updated report property tests to avoid deadline flakes under xdist and strict typing.

## Verification

- `ruff check polylogue/schemas/privacy.py polylogue/scenarios/runtime.py polylogue/lib/outcomes.py polylogue/lib/query_sorting.py polylogue/lib/query_plan.py polylogue/pipeline/prepare.py polylogue/schemas/audit_models.py polylogue/schemas/redaction_report.py polylogue/showcase/qa_markdown.py polylogue/version.py`
- `mypy polylogue/schemas/privacy.py polylogue/scenarios/runtime.py polylogue/lib/outcomes.py polylogue/lib/query_sorting.py polylogue/lib/query_plan.py polylogue/pipeline/prepare.py polylogue/schemas/audit_models.py polylogue/schemas/redaction_report.py polylogue/showcase/qa_markdown.py polylogue/version.py`
- `pytest -q tests/unit/core/test_privacy_guards.py tests/unit/core/test_schema_privacy.py tests/unit/core/test_privacy_config.py tests/unit/scenarios/test_runtime.py tests/unit/pipeline/test_prepare.py tests/unit/pipeline/test_prepare_records.py tests/unit/core/test_audit.py tests/unit/core/test_redaction_report.py tests/unit/showcase/test_qa_markdown.py tests/unit/showcase/test_report.py`
- `PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quick`
- Pre-push hook: `devtools verify --quick`
- Basename-correct detached verification worktree: `PATH=/tmp/polylogue-281-verify/polylogue/.cache/codex-bin:$PATH devtools verify` reached and passed pytest; the first overall exit was nonzero only because ignored `AGENTS.md` was absent in the fresh detached worktree. After `devtools render-agents --input CLAUDE.md --output AGENTS.md`, `PATH=/tmp/polylogue-281-verify/polylogue/.cache/codex-bin:$PATH devtools verify --quick` passed.
@Sinity Sinity added area:parser Parser tool:claude Claude type:refactor Code restructuring labels Apr 22, 2026
Sinity added a commit that referenced this pull request Apr 22, 2026
Remaining runtime/reporting seams carried broad `Any` annotations
and ad hoc payload assumptions, obscuring the shape of privacy
config overrides, report JSON payloads, query sort keys, parsed
conversation preparation, and runner dispatch results. Linked
worktree checkouts also failed version resolution because symbolic
branch refs were read only from the worktree git directory, not
from the common git dir where normal branch refs live.

Adds a runtime-checkable privacy config protocol and narrows
enum-value checking to string values after explicit config override
handling. Introduces typed JSON document returns for outcome, audit,
and redaction reports, with downstream markdown/tests narrowing
JSON unions before indexing. Types query sort keys, preparation
inputs, and scenario runner dispatch returns without changing
runtime behavior. Resolves linked-worktree version metadata through
`commondir`. Updates report property tests to avoid deadline flakes
under xdist and strict typing.

Verification: ruff + mypy + pytest over privacy / scenario /
prepare / audit / redaction / showcase suites; devtools verify
green.

Ref #281
Sinity added a commit that referenced this pull request Apr 22, 2026
Remaining runtime/reporting seams carried broad `Any` annotations
and ad hoc payload assumptions, obscuring the shape of privacy
config overrides, report JSON payloads, query sort keys, parsed
conversation preparation, and runner dispatch results. Linked
worktree checkouts also failed version resolution because symbolic
branch refs were read only from the worktree git directory, not
from the common git dir where normal branch refs live.

Adds a runtime-checkable privacy config protocol and narrows
enum-value checking to string values after explicit config override
handling. Introduces typed JSON document returns for outcome, audit,
and redaction reports, with downstream markdown/tests narrowing
JSON unions before indexing. Types query sort keys, preparation
inputs, and scenario runner dispatch returns without changing
runtime behavior. Resolves linked-worktree version metadata through
`commondir`. Updates report property tests to avoid deadline flakes
under xdist and strict typing.

Verification: ruff + mypy + pytest over privacy / scenario /
prepare / audit / redaction / showcase suites; devtools verify
green.

Ref #281
Sinity added a commit that referenced this pull request Apr 22, 2026
Remaining runtime/reporting seams carried broad `Any` annotations
and ad hoc payload assumptions, obscuring the shape of privacy
config overrides, report JSON payloads, query sort keys, parsed
conversation preparation, and runner dispatch results. Linked
worktree checkouts also failed version resolution because symbolic
branch refs were read only from the worktree git directory, not
from the common git dir where normal branch refs live.

Adds a runtime-checkable privacy config protocol and narrows
enum-value checking to string values after explicit config override
handling. Introduces typed JSON document returns for outcome, audit,
and redaction reports, with downstream markdown/tests narrowing
JSON unions before indexing. Types query sort keys, preparation
inputs, and scenario runner dispatch returns without changing
runtime behavior. Resolves linked-worktree version metadata through
`commondir`. Updates report property tests to avoid deadline flakes
under xdist and strict typing.

Verification: ruff + mypy + pytest over privacy / scenario /
prepare / audit / redaction / showcase suites; devtools verify
green.

Ref #281
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 5 finding(s) confirmed still present → tracked in #550.

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

Labels

area:parser Parser tool:claude Claude type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant