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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Use the existing managed GitHub App for public-catalog renewals, report their actual quota observations, and rotate more public repositories within the existing bounded backfill window.

- Publish public organization grants without collecting history, and coordinate withdrawals with the reader’s final response dispatch.

- Schedule public organization history inside the existing analytics owner, with repository-bound hydration, resumable turns and an expiring public grant inventory.
Expand Down
6 changes: 4 additions & 2 deletions docs/org-watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ SELECT value FROM analytics_collection_state WHERE name='org_watch_public_v1:ope
{"schema":"gitcrawl.org-public-grants.v1","complete":true,"org_login":"openclaw","org_id":"252820863","generation":"1","observed_at":"2026-12-03T07:00:00Z","expires_at":"2026-12-03T07:05:00Z","repositories":[{"github_repo_id":"1103012935","node_id":"R_kgDOQb6kRw","full_name":"openclaw/openclaw","visibility":"public","membership":"public_org"}]}
```

Numeric provider IDs and the positive incrementing publication generation are **strings**, not SQLite row IDs. `membership=installation` means present in the managed credential's installation list; `public_org` means confirmed by the separate public GitHub organization catalog. Public read access does not imply the app was installed on that repository. Both are current organization membership, not reader authorization for private material. The operator-pinned organization ID is `252820863`. Unknown members, ambiguous identity, internal and private repositories never appear. The supplied installation may select zero public repositories even when it can read the whole public organization. Do not describe the public catalog as selected installation membership.
Numeric provider IDs and the positive incrementing publication generation are **strings**, not SQLite row IDs. `membership=installation` means present in the managed credential's installation list; `public_org` means confirmed by the separate public GitHub organization catalog. Public read access does not imply the app was installed on that repository. Both are current organization membership, not reader authorization for private material. The operator-pinned organization ID is `252820863`. Unknown members, ambiguous identity, internal and private repositories never appear. The supplied installation may select zero public repositories even when it can read the whole public organization. Do not describe the public catalog as selected installation membership. Organization census, grants-only publication, and ongoing org-watch use one pinned credential from the existing managed App for both inventories. The public directory still requests `type=public` and requires two complete matching passes. The distinct installation list supplies positive and negative installation membership evidence. Authentication does not change the `public_org` meaning, disclose nonpublic entries, grant additional permissions, or provide a fallback to a user token or the anonymous pool.

`--org-census --json` and the grants-only success receipt include separate `catalog_quota` diagnostics from the actual managed HTTP responses, not from an unrelated `/rate_limit` request. Sanitized samples identify the stage, page, pass, quota preflight, GitHub request ID, provider date and core counters. An incomplete observation is not proof of operating headroom. At one page per directory traversal and one installation page, each grant needs three metadata reads and three quota probes. A 210-second renewal schedule plans for at most 18 grants per peak hour (54 metadata reads or 108 total HTTP requests if probes are also counted). Page growth raises this cost. The planning check also budgets two extra renewals and retains the existing half-window/fixed reserve; it is a current estimate, never permission to ignore a later throttle. Renew before the five-minute TTL with sufficient time for owner handoff and the dispatch fence. GraphQL conversation acquisition uses the same managed App with its separate observed GraphQL balance and reserve; REST catalog headroom is not GraphQL evidence.

Only trust `complete=true`, matching schema/organization ID/login, a positive generation, `observed_at <= now < expires_at`, an expiry at most five minutes after observation, exact supported membership, and `visibility=public`. Match repository ID, node ID and current full name against the native source in the **same SQLite snapshot**; a name prefix or old `raw_json.private=false` is not a grant. Missing, malformed, future, stale, ambiguous or absent entries deny. Capture this generation with derived work and revalidate it before publication/serving, including caches, aggregates and exports. Revoke prior projections when a tuple disappears. Existing retained history is not deleted and a grant does not imply history completeness.

Expand Down Expand Up @@ -61,7 +63,7 @@ Do not run pre-fence organization writers on an enrolled archive. A rollback ove

A repository starts with two independent discovery streams for issues and pull requests. The scheduler records a page before loading its selected conversations, then advances the durable checkpoint only after native writes succeed. It compares unique hydrated parents with both provider totals and checks comment, review and review-thread writes. A count mismatch restarts enumeration rather than blessing an incomplete baseline. Once both streams reconcile, later turns overlap the saved watermark to catch edits. Provider-unavailable and owner-excluded items do not qualify as fully hydrated. This covers recoverable conversation history and PR metadata; it is not a claim to have acquired files, check runs, workflows, commits, model outputs or every historical state GitHub no longer supplies.

The primary runs first and remains the only source of the existing core handoff event. Expansion rotates by stable numeric ID, checkpoints its position before a provider call, and shares a 25-second window among at most eight repositories per ordinary poll. A restart or an unavailable repository therefore cannot monopolize the first turn. Installation membership disagreements, redirects and lost access never cause an automatic rebind to another repository. Do not run a second `--watch` job, restart an old full-history backfill, replace a running binary in place, or change processor/code scopes to enable this feature. Before moving an existing owner, stage a separate lineage-compatible binary, preserve the old binaries and matched controller pins, and coordinate the visibility-aware reader cutover.
The primary runs first and remains the only source of the existing core handoff event. Expansion rotates by stable numeric ID, checkpoints its position before a provider call, and shares a 25-second window among at most sixteen repositories per ordinary poll. A restart or an unavailable repository therefore cannot monopolize the first turn. Installation membership disagreements, redirects and lost access never cause an automatic rebind to another repository. Do not run a second `--watch` job, restart an old full-history backfill, replace a running binary in place, or change processor/code scopes to enable this feature. Before moving an existing owner, stage a separate lineage-compatible binary, preserve the old binaries and matched controller pins, and coordinate the visibility-aware reader cutover.

The actor queue is archive-wide. In organization mode it uses the same expansion quota guard as new history, rather than spending the primary reserve. **After even one expansion write, do not roll back to an old binary with `--enrich` on this archive.** An older owner cannot validate repository visibility for that mixed queue. If you must revert, stage and verify the matched controller set that runs the old primary watch **without** `--enrich`, and keep expanded data denied downstream as grants expire. Exact old enrichment may resume only on a separately authorized, verified pre-expansion archive or after a compatible guarded collector is installed. Do not delete retained data or rewind cursors to make a binary rollback work.

Expand Down
100 changes: 100 additions & 0 deletions internal/cli/org_catalog_budget.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package cli

import (
"context"
"encoding/json"
"fmt"
"time"

gh "github.com/openclaw/gitcrawl/internal/github"
)

// The public catalog and the installation list are separate authorization
// sources, even when both use the same managed core quota. This diagnostic is
// not a reader grant, and it never enters the archive's v1 public grant row.
type orgCatalogBudget struct {
Transport string `json:"transport"`
HTTP int `json:"http_responses"`
Reads int `json:"metadata_responses"`
Probes int `json:"quota_preflight_responses"`
Minimum *int `json:"minimum_remaining_above_reserve,omitempty"`
LatestReset time.Time `json:"latest_reset_at,omitzero"`
Fresh bool `json:"all_responses_fresh_and_identified"`
Samples []gh.OrgCatalogObservation `json:"samples"`
// Keep output bounded even for thousands of installation repositories.
seen map[string]struct{}
traversed bool
stages [3]int
}

const orgRenewalSeconds = 210

func newOrgCatalogBudget() *orgCatalogBudget {
return &orgCatalogBudget{Transport: "managed_installation", Fresh: true, seen: map[string]struct{}{}}
}
func (b *orgCatalogBudget) observe(o gh.OrgCatalogObservation) {
b.HTTP++
if o.QuotaPreflight {
b.Probes++
} else {
b.Reads++
switch {
case o.Stage == "installation" && o.Pass == 0:
b.stages[0]++
case o.Stage == "public_catalog" && o.Pass == 1:
b.stages[1]++
case o.Stage == "public_catalog" && o.Pass == 2:
b.stages[2]++
default:
b.Fresh = false
}
}
now := time.Now()
_, duplicate := b.seen[o.RequestID]
if len(b.seen) < 4096 {
b.seen[o.RequestID] = struct{}{}
} else {
b.Fresh = false
}
if o.Resource != "core" || o.SuspectCache || o.RequestID == "" || duplicate || o.Status != 200 || o.RetryAfter != "" || o.Date.IsZero() || o.Date.After(now.Add(5*time.Second)) || now.Sub(o.Date) > 15*time.Second || !o.ResetAt.After(now) || o.Limit == nil || o.Remaining == nil || o.Used == nil {
b.Fresh = false
} else {
l, r, u := *o.Limit, *o.Remaining, *o.Used
if l <= 0 || r < 0 || r > l || u < 0 || u > l {
b.Fresh = false
} else {
left := r - max(analyticsCoreReserve, l/2+l%2)
if b.Minimum == nil || left < *b.Minimum {
b.Minimum = &left
}
}
}
if o.ResetAt.After(b.LatestReset) {
b.LatestReset = o.ResetAt
}
if len(b.Samples) < 12 {
b.Samples = append(b.Samples, o)
} else {
b.Samples[11] = o
}
}
func (b *orgCatalogBudget) summary() map[string]any {
if b == nil {
return nil
}
valid := b.traversed && b.Fresh && b.stages[0] > 0 && b.stages[1] > 0 && b.stages[1] == b.stages[2] && b.Probes == b.Reads && b.Minimum != nil
const perHour = (3600 + orgRenewalSeconds - 1) / orgRenewalSeconds
return map[string]any{"observed": b, "evidence_complete": valid, "lease_seconds": int(orgFreshness / time.Second), "planning_interval_seconds": orgRenewalSeconds, "metadata_reads_per_peak_hour": perHour * b.Reads, "http_requests_per_peak_hour": perHour * b.HTTP, "one_hour_plus_two_renewals_headroom": valid && *b.Minimum >= (perHour+2)*b.HTTP}
}
func catalogContext(ctx context.Context, w *orgWatch) context.Context {
w.catalogBudget = newOrgCatalogBudget()
return gh.WithOrgCatalogObservation(ctx, w.catalogBudget.observe)
}
func (a *App) reportOrgCensusFailure(w *orgWatch, e error) {
msg := map[string]any{"event": "org_catalog_preflight_failed", "catalog_quota": w.catalogBudget.summary()}
if at := gh.OrgRetryAt(e, time.Now()); !at.IsZero() {
msg["not_before"] = at.UTC()
}
raw, _ := json.Marshal(msg)
fmt.Fprintln(a.Stderr, string(raw))
}
59 changes: 59 additions & 0 deletions internal/cli/org_catalog_budget_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package cli

import (
"fmt"
gh "github.com/openclaw/gitcrawl/internal/github"
"testing"
"time"
)

func TestOrgCatalogBudgetAccountsEveryCensusRequest(t *testing.T) {
now := time.Now().UTC()
for _, mode := range []string{"fresh", "floor", "missing", "stale", "cache", "duplicate", "incomplete", "failedComparison"} {
t.Run(mode, func(t *testing.T) {
b := newOrgCatalogBudget()
for i := 0; i < 6; i++ {
l, r, u := 20000, 19999-i, i+1
o := gh.OrgCatalogObservation{Stage: "installation", Pass: 0, Page: 1, QuotaPreflight: i%2 == 0, Status: 200, Resource: "core", Date: now, Remaining: &r, Limit: &l, Used: &u, ResetAt: now.Add(time.Hour), RequestID: fmt.Sprintf("A:B:C:D:%X", i)}
if i >= 2 {
o.Stage = "public_catalog"
o.Pass = i / 2
}
if i == 5 {
switch mode {
case "floor":
r = 10020
case "missing":
o.Remaining = nil
case "stale":
o.Date = now.Add(-time.Minute)
case "cache":
o.SuspectCache = true
case "duplicate":
o.RequestID = "A:B:C:D:0"
case "incomplete":
continue
}
}
b.observe(o)
}
b.traversed = mode != "failedComparison"
s := b.summary()
if (s["one_hour_plus_two_renewals_headroom"] == true) != (mode == "fresh") {
t.Fatal(mode, s)
}
if mode == "fresh" && (s["metadata_reads_per_peak_hour"] != 54 || s["http_requests_per_peak_hour"] != 108 || b.Reads != 3 || b.Probes != 3 || *b.Minimum != 9994) {
t.Fatal(s)
}
})
}
}
func TestOrgCatalogUnknownEvidenceNotGranted(t *testing.T) {
if (*orgCatalogBudget)(nil).summary() != nil {
t.Fatal("unobserved budget synthesized")
}
b := newOrgCatalogBudget()
if b.summary()["evidence_complete"] != false {
t.Fatal(b.summary())
}
}
100 changes: 96 additions & 4 deletions internal/cli/org_dispatch_poll_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"testing"
"time"

"github.com/openclaw/gitcrawl/internal/config"
gh "github.com/openclaw/gitcrawl/internal/github"
"github.com/openclaw/gitcrawl/internal/store"
"golang.org/x/sys/unix"
Expand All @@ -36,15 +37,21 @@ type dispatchPollFixture struct {
}

func newDispatchPoll(t *testing.T, age time.Duration) *dispatchPollFixture {
t.Helper()
return newDispatchPollPrimary(t, age, sliceRepo)
}

func newDispatchPollPrimary(t *testing.T, age time.Duration, primary gh.OrgRepository) *dispatchPollFixture {
t.Helper()
s := sliceArchive(t, filepath.Join(t.TempDir(), "archive.db"))
t.Cleanup(func() { s.Close() })
f := &dispatchPollFixture{t: t, s: s, w: &orgWatch{org: "example", orgID: 42, primary: sliceRepo.FullName}}
f := &dispatchPollFixture{t: t, s: s, w: &orgWatch{org: "example", orgID: 42, primary: primary.FullName}}
ctx := t.Context()
if _, err := s.UpsertRepository(ctx, store.Repository{Owner: "example", Name: "project", FullName: sliceRepo.FullName, GitHubRepoID: "17", RawJSON: `{"id":17,"node_id":"R_17","full_name":"example/project","private":false,"visibility":"public"}`}); err != nil {
raw := fmt.Sprintf(`{"id":%d,"node_id":%q,"full_name":%q,"private":false,"visibility":"public"}`, primary.ID, primary.NodeID, primary.FullName)
if _, err := s.UpsertRepository(ctx, store.Repository{Owner: "example", Name: strings.TrimPrefix(primary.FullName, "example/"), FullName: primary.FullName, GitHubRepoID: fmt.Sprint(primary.ID), RawJSON: raw}); err != nil {
t.Fatal(err)
}
if err := s.SaveAnalyticsCoverage(ctx, sliceRepo.FullName, sliceOld, 0, 0); err != nil {
if err := s.SaveAnalyticsCoverage(ctx, primary.FullName, sliceOld, 0, 0); err != nil {
t.Fatal(err)
}
prepareTestGrantFence(t, f.w, s)
Expand All @@ -66,7 +73,12 @@ func (f *dispatchPollFixture) RoundTrip(req *http.Request) (*http.Response, erro
var body any
switch req.URL.Path {
case "/rate_limit":
return (&sliceFixture{t: f.t}).RoundTrip(req)
res, err := (&sliceFixture{t: f.t}).RoundTrip(req)
if err == nil {
res.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
res.Header.Set("X-GitHub-Request-Id", fmt.Sprintf("A:B:C:D:%X", time.Now().UnixNano()))
}
return res, err
case "/installation/repositories":
f.census++
status = 429
Expand Down Expand Up @@ -248,3 +260,83 @@ func TestOrgDispatchPollCooldown(t *testing.T) {
f.noExpansion()
})
}

// Start with an exact-number page already checkpointed for the non-primary
// repository. Exercise the ordinary poll, including its actual client derivation
// and native history writer, never the catalog or a real provider.
func TestOrgPollManagedExpansionHistory(t *testing.T) {
t.Setenv("GITHUB_BASE_URL", "")
t.Setenv("GITCRAWL_GITHUB_BASE_URL", "")
for _, remaining := range []int{19000, 10000} {
t.Run(fmt.Sprint(remaining), func(t *testing.T) {
f := newDispatchPollPrimary(t, 0, pollPeer)
a := New()
dir := t.TempDir()
a.configPath = writeDoctorTestConfig(t, dir, f.s.Path())
a.Stderr = &f.log
helper := filepath.Join(dir, "helper")
if err := os.WriteFile(helper, []byte("#!/bin/sh\nprintf x >> \"$0.calls\"\nprintf ghs_fake_owner\n"), 0700); err != nil {
t.Fatal(err)
}
a.githubTokenCommand = &helper
ctx, err := a.orgCredentialContext(t.Context())
if err != nil {
t.Fatal(err)
}
p := orgNewSlice(sliceRepo, sliceOld)
p.Lanes[0] = orgSliceLane{Pending: []int{1, 2, 3, 4, 5}, Total: 5, End: true}
if err := p.save(ctx, f.s); err != nil {
t.Fatal(err)
}
history := &sliceFixture{t: t}
probes := 0
opts := a.analyticsOptions(ctx, config.Config{})
opts.HTTPClient = &http.Client{Transport: orgCredentialTransport(func(r *http.Request) (*http.Response, error) {
if r.URL.Host != "api.github.com" || r.Header.Get("Authorization") != "Bearer ghs_fake_owner" {
return nil, errors.New("request did not use the managed helper")
}
if r.URL.Path != "/graphql" || !strings.Contains(f.log.String(), `"github_update_complete"`) {
return f.RoundTrip(r)
}
body, e := io.ReadAll(r.Body)
if e != nil {
return nil, e
}
r.Body = io.NopCloser(bytes.NewReader(body))
var payload struct {
Query string
Variables map[string]any
}
if e := json.Unmarshal(body, &payload); e != nil {
return nil, e
}
if strings.Contains(payload.Query, "issueOrPullRequest(number:") {
if probes == 0 || payload.Variables["repo"] != "project" || payload.Variables["owner"] != "example" {
return nil, errors.New("unprobed or misdirected history")
}
return history.RoundTrip(r)
}
if !strings.HasPrefix(strings.TrimSpace(payload.Query), "query { rateLimit {") {
return nil, errors.New("unexpected expansion query")
}
probes++
quota := fmt.Sprintf(`{"data":{"rateLimit":{"cost":1,"limit":20000,"remaining":%d,"resetAt":"2099-01-01T00:00:00Z"}}}`, remaining)
return &http.Response{Request: r, StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(quota))}, nil
})}
err = a.orgPoll(ctx, f.s, gh.New(opts), f.w, "example", "peer")
calls, e := os.ReadFile(helper + ".calls")
if e != nil || string(calls) != "x" || probes == 0 || strings.Count(f.log.String(), `"github_update_complete"`) != 1 || f.state(orgSliceKey(pollPeer)) != "" {
t.Fatalf("wrong helper, quota probe, or primary receipt: calls=%q probes=%d log=%s err=%v", calls, probes, &f.log, err)
}
parents := sliceCount(t, f.s, `select count(*) from threads`)
if remaining == 10000 {
var reserve *gh.RateLimitReserveError
if !errors.As(err, &reserve) || reserve.Reserve != 10000 || reserve.RateLimit.Resource != "graphql" || len(history.history) != 0 || parents != 0 {
t.Fatalf("GraphQL floor did not stop peer history: %v %v parents=%d", err, history.history, parents)
}
} else if err != nil || !slices.Equal(history.history, []int{1, 2, 3, 4}) || parents != 4 {
t.Fatalf("nonprimary history: err=%v requested=%v parents=%d", err, history.history, parents)
}
})
}
}
Loading
Loading