Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pkgs/atlas-search/book/reference/atlas-github-comments.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ The state file keeps the original `repos` map for comment streams and a `reviews

A completed repository's output is synced before its state is replaced. On a handled failure, the feed removes that repository's partial append and preserves its previous checkpoint. The process holds an advisory lock on the output and on a sibling `.lock` file next to the state. A hard crash between the append and checkpoint can leave replayed output; downstream promotion must deduplicate by source occurrence and revision. The feed's checkpoint only establishes extraction progress. Classification, promotion, publication, and retrieval need their own receipts.

### First-party source scope

An explicit `--repo` must name a single repository owned by `developing-today`, `developing-today-forks`, or `dezren39`. Comparison of owner names is case-insensitive. A malformed path or external owner fails argument parsing before output is opened. For both default discovery and explicit selection, the feed verifies the canonical API repository URL on returned issue, comment, and review rows. If GitHub follows a transfer or rename to a different repository, that pass fails closed; select the current eligible name explicitly after review. This checks exported provenance and cannot suppress redirects internal to the GitHub CLI.

### The HTTP 451 exception

One failure does not stop the run: a repository that is permanently access-blocked (HTTP 451, for example a DMCA block) is logged as `<repo>: skipped — repository access blocked (HTTP 451)`, counted in a final `skipped_repos: N (repository access blocked, HTTP 451)` line, and the run continues with the next repository. If nothing else failed, the run still exits 0.
Expand All @@ -47,9 +51,9 @@ See [Ingest today: staging, classification, promotion](../concepts/ingest.md) fo
Extracting one toy repository into a fresh state and records file:

```
$ atlas-github-comments --state /tmp/toy-watermarks.json --out /tmp/toy-records.jsonl --repo toy-owner/toy-repo
$ atlas-github-comments --state /tmp/toy-watermarks.json --out /tmp/toy-records.jsonl --repo developing-today/example-fixture
estate: 1 repos
toy-owner/toy-repo: issue_comments=2 review_comments=1 reviews=1 documents=4
developing-today/example-fixture: issue_comments=2 review_comments=1 reviews=1 documents=4
totals: …
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,51 @@ struct Args {
observed_date: Option<String>,
}

const ESTATE_OWNERS: [&str; 3] = ["developing-today", "developing-today-forks", "dezren39"];

fn validate_repo(repo: &str) -> Result<(), String> {
let Some((owner, name)) = repo.split_once('/') else {
return Err("--repo needs an owned owner/name pair".into());
};
let allowed = ESTATE_OWNERS.iter().any(|o| o.eq_ignore_ascii_case(owner));
Comment on lines +56 to +60

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add property tests for the repository-scope invariants

The new repository-name parser and canonical-repository guard establish meaningful scope invariants, but their only new coverage is the handful of examples in the Python fixture; neither function has property-based tests. The root AGENTS.md testing doctrine explicitly requires property tests where code has invariants, including parsers. Add proptest coverage with explicit oracles for owner case-insensitivity, rejection of malformed/external selections, and rejection of canonical owner/name mismatches; retain the CLI fixture as acceptance coverage.

AGENTS.md reference: AGENTS.md:L34-L39

Useful? React with 👍 / 👎.

if !allowed
|| name.is_empty()
|| matches!(name, "." | "..")
|| !name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
{
return Err(
"repository outside the permitted GitHub comments estate or malformed repository name"
.into(),
);
}
Ok(())
}

// GitHub can redirect a renamed or transferred repository. Validate the
// canonical source named by each response row before exporting any of it.
fn check_row_repo(row: &Json, field: &str, repo: &str) -> Result<(), String> {
let source = row
.get(field)
.and_then(Json::as_str)
.and_then(|u| u.strip_prefix("https://api.github.com/repos/"))
.and_then(|r| r.split_once('/'));
let (owner, name) = repo.split_once('/').ok_or("invalid repository name")?;
if source.is_some_and(|(o, rest)| {
o.eq_ignore_ascii_case(owner)
&& rest
.split('/')
.next()
.is_some_and(|n| n.eq_ignore_ascii_case(name))
}) {
return Ok(());
}
Err(format!(
"missing or unexpected GitHub repository in {field}"
))
}

fn parse_args() -> Result<Args, String> {
let mut state: Option<PathBuf> = None;
let mut out: Option<PathBuf> = None;
Expand All @@ -62,7 +107,11 @@ fn parse_args() -> Result<Args, String> {
match arg.as_str() {
"--state" => state = Some(PathBuf::from(it.next().ok_or("--state needs a path")?)),
"--out" => out = Some(PathBuf::from(it.next().ok_or("--out needs a path")?)),
"--repo" => repos.push(it.next().ok_or("--repo needs owner/name")?),
"--repo" => {
let repo = it.next().ok_or("--repo needs owner/name")?;
validate_repo(&repo)?;
repos.push(repo);
}
"--skip-reviews" => skip_reviews = true,
"--observed-date" => {
observed_date = Some(it.next().ok_or("--observed-date needs YYYY-MM-DD")?)
Expand Down Expand Up @@ -137,7 +186,11 @@ fn enumerate_estate() -> Result<Vec<String>, String> {
let text = gh_api(path, ".[].full_name")?;
for line in text.lines() {
let name = line.trim();
if !name.is_empty() && !repos.iter().any(|r| r == name) {
if name.is_empty() {
continue;
}
validate_repo(name)?;
if !repos.iter().any(|r| r == name) {
repos.push(name.to_string());
}
}
Expand Down Expand Up @@ -191,6 +244,7 @@ fn extract_repo(
let issues = gh_api_objects(&format!("repos/{repo}/issues?state=all&per_page=100"))?;
let mut threads: BTreeMap<u64, GhThread> = BTreeMap::new();
for issue in &issues {
check_row_repo(issue, "repository_url", repo)?;
let Some(number) = issue.get("number").and_then(Json::as_u64) else {
continue;
};
Expand Down Expand Up @@ -235,6 +289,9 @@ fn extract_repo(
let raw = gh_api_objects(&format!(
"repos/{repo}/issues/comments?per_page=100{since_q}"
))?;
for row in &raw {
check_row_repo(row, "issue_url", repo)?;
}
let comments: Vec<GhComment> = raw
.iter()
.filter_map(|c| {
Expand Down Expand Up @@ -265,6 +322,9 @@ fn extract_repo(
let raw = gh_api_objects(&format!(
"repos/{repo}/pulls/comments?per_page=100{since_q}"
))?;
for row in &raw {
check_row_repo(row, "pull_request_url", repo)?;
}
let comments: Vec<GhComment> = raw
.iter()
.filter_map(|c| {
Expand Down Expand Up @@ -302,6 +362,9 @@ fn extract_repo(
.collect();
for number in pr_numbers {
let raw = gh_api_objects(&format!("repos/{repo}/pulls/{number}/reviews?per_page=100"))?;
for row in &raw {
check_row_repo(row, "pull_request_url", repo)?;
}
let reviews: Vec<GhComment> = raw
.iter()
.filter_map(|r| {
Expand Down
21 changes: 18 additions & 3 deletions pkgs/atlas-search/tests/test_github_comments_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@ def record(n, key, thread):
"created_at":stamp(n), "submitted_at":stamp(n), "updated_at":stamp(n),
key:f"https://api.github.com/repos/developing-today/atlas-fixture/issues/{thread}"}
if route.endswith("/issues"):
rows = [{"number":n, "pull_request":{}, "labels":[]} for n in (1, 2)]
owner = "external-fixture" if os.environ.get("FIXTURE_TRANSFER") else "developing-today"
rows = [{"number":n, "repository_url":f"https://api.github.com/repos/{owner}/atlas-fixture",
"pull_request":{}, "labels":[]} for n in (1, 2)]
elif route.endswith("/issues/comments"):
rows = [record(5, "issue_url", 1)]
elif route.endswith("/pulls/comments"):
rows = [record(3, "pull_request_url", 2)]
elif route.endswith("/pulls/1/reviews"):
rows = [record(4, "unused", 1)]
rows = [record(4, "pull_request_url", 1)]
elif route.endswith("/pulls/2/reviews"):
if os.environ.get("FIXTURE_FAILURE"):
sys.exit(1)
rows = [record(2, "unused", 2)]
rows = [record(2, "pull_request_url", 2)]
else:
raise SystemExit("unexpected fixture route")
for row in rows:
Expand All @@ -52,6 +54,19 @@ def exercise(directory, cli):
def ids():
return [json.loads(line)["comment_id"] for line in output.read_text().splitlines()]

# Explicit targets must fail before creating output or using the fake gh.
scratch = directory / "forbidden-output"
for target in ("outside-fixture/name", "dezren39/../repos", "dezren39/%2e%2e",
"developing-today/name?query=1", "developing-today-forks/.."):
invalid = subprocess.run([str(cli), "--repo", target, "--state", str(state),
"--out", str(scratch)], env=env, capture_output=True)
assert invalid.returncode == 1 and b"permitted" in invalid.stderr
assert not scratch.exists()
# A transfer reflected in the canonical repository URL must fail closed.
transfer = subprocess.run(cmd, env=dict(env, FIXTURE_TRANSFER="1"), capture_output=True)
assert transfer.returncode == 1 and b"unexpected GitHub repository" in transfer.stderr
assert state.read_text() == initial and ids() == []

# Independent oracle: an unsuccessful last stream leaves the entire prior
# checkpoint and append unchanged. Successful retry emits every eligible ID.
failure = subprocess.run(cmd, env=dict(env, FIXTURE_FAILURE="1"), capture_output=True)
Expand Down