pubcheck 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pubcheck/sources.py ADDED
@@ -0,0 +1,277 @@
1
+ """What the check looks up: a repo's visibility, the acquaint registry, private companions.
2
+
3
+ **Visibility** comes from a visibility cache shared with other tools on the machine
4
+ (``~/.cache/priv/repo_visibility/<sanitized remote>.json``, ``$PRIV_VISIBILITY_CACHE_DIR``,
5
+ 24 h; one JSON file per remote: ``remote``, ``slug``, ``is_private``, ``checked_at``). Every
6
+ fresh entry is read, whatever its remote spelling. A miss asks ``gh repo view`` and records
7
+ the answer in the same format. Unknown (offline, no ``gh``, no such repo) is ``None``,
8
+ which the check treats as public.
9
+
10
+ **The registry** is acquaint's Do-not-identify vocabulary for a public audience
11
+ (``acquaint disclosure --audience '{"scope": "public"}' --json``), cached an hour in
12
+ ``~/.cache/public-text-guard/`` (``term`` and ``entity`` only, mode 0600). A stale cache
13
+ serves when acquaint cannot be asked. ``$PUBLIC_TEXT_GUARD_VOCAB_FILE`` names a JSON list
14
+ to use instead (tests).
15
+
16
+ >>> parse_slug("git@github.com:octo/app.git")
17
+ 'octo/app'
18
+ >>> terms_for([{"term": "Ada Quill", "entity": "person:a"}, {"term": "AQ", "entity": "person:a"}], "o/r")
19
+ ['Ada Quill']
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ import time
29
+ from pathlib import Path
30
+
31
+ from pubcheck.base import Budget, cache_dir, write_private
32
+ from pubcheck.detectors import MIN_TERM_LEN, is_common
33
+
34
+ VISIBILITY_CACHE_ENV = "PRIV_VISIBILITY_CACHE_DIR" # the shared cache's own name
35
+ VISIBILITY_TTL = 24 * 60 * 60
36
+ VOCAB_FILE_ENV = "PUBLIC_TEXT_GUARD_VOCAB_FILE"
37
+ VOCAB_TTL = 60 * 60
38
+ VOCAB_MAX_AGE = (
39
+ 7 * 24 * 60 * 60
40
+ ) # an old copy serves when acquaint cannot answer, up to this age
41
+ COMPANION_TTL = 24 * 60 * 60
42
+ ACQUAINT_CANDIDATES = ("~/.pyenv/shims/acquaint", "~/.local/bin/acquaint")
43
+ PUBLIC_AUDIENCE = '{"scope": "public"}'
44
+
45
+ # ---- visibility ----
46
+
47
+
48
+ def parse_slug(remote_url):
49
+ """``owner/repo`` from a github.com remote URL, else ``None``."""
50
+ url = (remote_url or "").strip()
51
+ m = re.match(r"^[\w.+-]+@([^:/]+):(.+)$", url) or re.match(
52
+ r"^[a-zA-Z][a-zA-Z0-9+.-]*://(?:[^@/]*@)?([^/:]+)(?::\d+)?/(.+)$", url
53
+ )
54
+ if not m or m.group(1).lower() != "github.com":
55
+ return None
56
+ path = m.group(2).strip("/")
57
+ path = path[:-4] if path.endswith(".git") else path
58
+ return path if path.count("/") == 1 else None
59
+
60
+
61
+ def _visibility_dir():
62
+ return Path(
63
+ os.environ.get(VISIBILITY_CACHE_ENV) or "~/.cache/priv/repo_visibility"
64
+ ).expanduser()
65
+
66
+
67
+ def cache_key(remote_url):
68
+ """The cache's file name for a remote."""
69
+ return re.sub(r"[^A-Za-z0-9._-]", "_", remote_url)
70
+
71
+
72
+ def cached_visibility(*, now=None, directory=None):
73
+ """``{slug (lowercase): is_private}`` from every fresh entry of the shared visibility cache."""
74
+ now = time.time() if now is None else now
75
+ d = directory or _visibility_dir()
76
+ out = {}
77
+ try:
78
+ files = list(d.glob("*.json"))
79
+ except OSError:
80
+ return out
81
+ for f in files:
82
+ try:
83
+ data = json.loads(f.read_text())
84
+ except (OSError, ValueError):
85
+ continue
86
+ slug = data.get("slug") or parse_slug(data.get("remote", ""))
87
+ checked, private = data.get("checked_at"), data.get("is_private")
88
+ if slug and isinstance(private, bool) and isinstance(checked, (int, float)):
89
+ if 0 <= now - checked < VISIBILITY_TTL:
90
+ out[slug.lower()] = private
91
+ return out
92
+
93
+
94
+ def gh_repo_view(slug, *, budget: Budget):
95
+ """``True`` private, ``False`` public, ``"missing"`` no such repo, ``None`` unknown."""
96
+ if not shutil.which("gh"):
97
+ return None
98
+ r = budget.run(
99
+ ["gh", "repo", "view", slug, "--json", "isPrivate", "-q", ".isPrivate"]
100
+ )
101
+ if r is None:
102
+ return None
103
+ if r.returncode == 0:
104
+ return {"true": True, "false": False}.get(r.stdout.strip())
105
+ return "missing" if "Could not resolve to a Repository" in r.stderr else None
106
+
107
+
108
+ def write_visibility(slug, is_private, remote=None):
109
+ """Record a verdict in the shared cache's format."""
110
+ remote = remote or f"https://github.com/{slug}"
111
+ d = _visibility_dir()
112
+ try:
113
+ d.mkdir(parents=True, exist_ok=True)
114
+ tmp = d / f"{cache_key(remote)}.json.tmp"
115
+ tmp.write_text(
116
+ json.dumps(
117
+ {
118
+ "remote": remote,
119
+ "slug": slug,
120
+ "is_private": is_private,
121
+ "checked_at": time.time(),
122
+ }
123
+ )
124
+ )
125
+ tmp.replace(d / f"{cache_key(remote)}.json")
126
+ except OSError:
127
+ pass
128
+
129
+
130
+ def lookup_visibility(slug, cache, *, budget: Budget, remote=None):
131
+ """``True`` private, ``False`` public, ``None`` unknown (does not exist, or offline)."""
132
+ if slug.lower() in cache:
133
+ return cache[slug.lower()]
134
+ private = gh_repo_view(slug, budget=budget)
135
+ if isinstance(private, bool):
136
+ cache[slug.lower()] = private
137
+ write_visibility(slug, private, remote)
138
+ return private
139
+ return None
140
+
141
+
142
+ def companion_exists(slug, cache, *, budget: Budget):
143
+ """Whether ``slug`` exists (remembered a day); ``None`` when it cannot be asked."""
144
+ if slug.lower() in cache:
145
+ return True
146
+ store = cache_dir() / "companions.json"
147
+ try:
148
+ known = json.loads(store.read_text())
149
+ except (OSError, ValueError):
150
+ known = {}
151
+ hit = known.get(slug.lower())
152
+ if (
153
+ isinstance(hit, dict)
154
+ and 0 <= time.time() - hit.get("checked_at", 0) < COMPANION_TTL
155
+ ):
156
+ return hit.get("exists")
157
+ answer = gh_repo_view(slug, budget=budget)
158
+ if answer is None:
159
+ return None
160
+ exists = answer != "missing"
161
+ if isinstance(answer, bool):
162
+ cache[slug.lower()] = answer
163
+ write_visibility(slug, answer)
164
+ known[slug.lower()] = {"exists": exists, "checked_at": time.time()}
165
+ write_private(store, json.dumps(known))
166
+ return exists
167
+
168
+
169
+ def origin(directory, *, budget: Budget):
170
+ """``(slug, remote url)`` of ``directory``'s ``origin``, or ``(None, None)``."""
171
+ if not directory:
172
+ return None, None
173
+ r = budget.run(["git", "-C", str(directory), "remote", "get-url", "origin"], cap=5)
174
+ if r is None or r.returncode != 0:
175
+ return None, None
176
+ url = r.stdout.strip()
177
+ return parse_slug(url), url
178
+
179
+
180
+ # ---- the acquaint registry ----
181
+
182
+
183
+ def _acquaint():
184
+ found = shutil.which("acquaint")
185
+ if found:
186
+ return found
187
+ for c in ACQUAINT_CANDIDATES:
188
+ p = Path(c).expanduser()
189
+ if p.exists():
190
+ return str(p)
191
+ return None
192
+
193
+
194
+ def _fetch_vocabulary(budget: Budget):
195
+ exe = _acquaint()
196
+ if not exe:
197
+ return None
198
+ r = budget.run([exe, "disclosure", "--audience", PUBLIC_AUDIENCE, "--json"])
199
+ if r is None or r.returncode != 0:
200
+ return None
201
+ try:
202
+ rows = json.loads(r.stdout).get("vocabulary")
203
+ except (ValueError, AttributeError):
204
+ return None
205
+ if not isinstance(rows, list):
206
+ return None
207
+ return [
208
+ {"term": v.get("term"), "entity": v.get("entity")}
209
+ for v in rows
210
+ if isinstance(v, dict)
211
+ ]
212
+
213
+
214
+ def vocabulary(*, budget: Budget):
215
+ """``(rows, available)``: acquaint's public-audience vocabulary ``[{term, entity}]``, cached ``VOCAB_TTL``.
216
+
217
+ When acquaint cannot answer, a copy up to ``VOCAB_MAX_AGE`` old serves. ``available``
218
+ is False when there is nothing usable: no answer, no copy young enough, or an empty
219
+ vocabulary (records not synced to this machine check no name at all).
220
+ """
221
+ override = os.environ.get(VOCAB_FILE_ENV)
222
+ if override:
223
+ try:
224
+ rows = json.loads(Path(override).read_text())
225
+ except (OSError, ValueError):
226
+ return [], False
227
+ return rows, bool(rows)
228
+ cache = cache_dir() / "vocabulary.json"
229
+ old = None
230
+ try:
231
+ old = json.loads(cache.read_text())
232
+ if 0 <= time.time() - old["checked_at"] < VOCAB_TTL and old["vocabulary"]:
233
+ return old["vocabulary"], True
234
+ except (OSError, ValueError, KeyError, TypeError):
235
+ pass
236
+ fresh = _fetch_vocabulary(budget)
237
+ if fresh is None:
238
+ try:
239
+ young = 0 <= time.time() - old["checked_at"] < VOCAB_MAX_AGE
240
+ rows = old["vocabulary"] if young else None
241
+ except (KeyError, TypeError):
242
+ rows = None
243
+ return (rows, True) if rows else ([], False)
244
+ if not fresh:
245
+ return [], False # never cached: an empty answer is no registry
246
+ write_private(cache, json.dumps({"checked_at": time.time(), "vocabulary": fresh}))
247
+ return fresh, True
248
+
249
+
250
+ def terms_for(vocab, repo):
251
+ """The terms to scan for when posting to ``repo``.
252
+
253
+ An org record that the target's owner names is the target itself: all its terms go. A
254
+ person's term equal to the owner goes alone. Short terms and common lowercase words go.
255
+ """
256
+ owner = (repo or "").split("/")[0].lower()
257
+ own_orgs = {
258
+ v.get("entity")
259
+ for v in vocab
260
+ if str(v.get("term", "")).lower() == owner
261
+ and str(v.get("entity", "")).startswith("org:")
262
+ }
263
+ out = []
264
+ for v in vocab:
265
+ term = " ".join(str(v.get("term") or "").split())
266
+ if (
267
+ not term
268
+ or v.get("entity") in own_orgs
269
+ or term.lower() == owner
270
+ or len(term) < MIN_TERM_LEN
271
+ ):
272
+ continue
273
+ if term.isalpha() and term.islower() and is_common(term):
274
+ continue
275
+ if term not in out:
276
+ out.append(term)
277
+ return out
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: pubcheck
3
+ Version: 0.0.2
4
+ Summary: One publication check for every writer: is this text fit for a public repository? Personal names, the owner's own matters, private references, credentials and @mentions, failing closed when nobody is watching.
5
+ Project-URL: Homepage, https://github.com/thorwhalen/pubcheck
6
+ Project-URL: Repository, https://github.com/thorwhalen/pubcheck
7
+ Project-URL: Documentation, https://thorwhalen.github.io/pubcheck
8
+ Project-URL: Issues, https://github.com/thorwhalen/pubcheck/issues
9
+ Author: Thor Whalen
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,claude-code,github,guard,privacy,publication
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: POSIX
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: openloops
22
+ Provides-Extra: correspond
23
+ Requires-Dist: correspond; extra == 'correspond'
24
+ Provides-Extra: dev
25
+ Requires-Dist: correspond; extra == 'dev'
26
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # pubcheck
32
+
33
+ One publication check for every writer: is this text fit for the repository it is about to be published to?
34
+
35
+ ```bash
36
+ pip install pubcheck
37
+ printf '%s' "$BODY" | public-text-guard check --repo octo/app --unattended
38
+ # exit 0 pass, 1 flag, 2 unavailable; one JSON line naming the categories, never the text
39
+ ```
40
+
41
+ ```python
42
+ from pubcheck import check
43
+
44
+ v = check("As the owner asked, we fixed it.", repo="octo/app")
45
+ v.decision, v.categories # ('flag', ['owner-relation'])
46
+ ```
47
+
48
+ A private target passes untouched. A public one, or one whose visibility is unknown, is scanned for:
49
+
50
+ - `registry`: names from the owner's acquaint records that a public reader may not see (`acquaint disclosure --audience '{"scope": "public"}'`);
51
+ - `owner-relation`: the owner's own preferences, corrections or relations ("the operator stated", "my agents");
52
+ - `private-ref`: repos known to be private, private companions, this machine's home folder, and your own `private_patterns`;
53
+ - `session-link`: Claude session links;
54
+ - `credential`: credential-shaped strings (the patterns of `openloops.egress`);
55
+ - `mention`: `@login` and `@org/team` outside code, for an **unattended** writer only, since a mention notifies a person.
56
+
57
+ ## Attended and unattended writers
58
+
59
+ An attended writer (an agent session someone is driving) proceeds without the registry when acquaint cannot be asked, and the gap is logged. An unattended writer (a connector, a scheduled job, anything that posts with nobody reading first) fails closed: a missing registry, a lookup out of time or any error is `unavailable` (exit 2), and the text must be held, never posted.
60
+
61
+ ## Three ways in, one check
62
+
63
+ - **Python**: `pubcheck.check(text, repo=..., title=..., unattended=...)` returns a `Verdict`.
64
+ - **CLI**: `public-text-guard check --repo OWNER/REPO [--unattended] [--title T] [--hold TARGET] [--terms]`, the text on stdin. `--terms` adds the matched terms, for a local author who has to reword; `--hold` files a held post as a desk item.
65
+ - **correspond**: at the top of `~/.config/correspond/config.toml`, `before_send = "pubcheck.correspond:before_send"`. Every write to a public audience is checked unattended; a held one raises correspond's `NeedsApproval` with the categories, and on a real send (not a dry run) becomes a desk item.
66
+
67
+ ## Held posts become desk items
68
+
69
+ With `hold_repo` set, a held post is filed as an issue in that private repo with the label the desk reads (`hold_label`, default `escalate`): the target, the title, the text (credential-shaped strings redacted) and the categories, so it can be published as is, edited or dropped. The hold repo's visibility is asked of GitHub just before filing, and nothing is copied to a repo that is not private. The same text held twice is filed once. With no `hold_repo`, the post is still held; only the desk item is missing.
70
+
71
+ ## Settings
72
+
73
+ `~/.config/pubcheck/config.toml` (`$PUBCHECK_CONFIG` names another file), then environment variables, then keyword arguments:
74
+
75
+ | key | env | default |
76
+ |---|---|---|
77
+ | `hold_repo` | `PUBCHECK_HOLD_REPO` | unset (no desk item) |
78
+ | `hold_label` | `PUBCHECK_HOLD_LABEL` | `escalate` |
79
+ | `budget_seconds` | `PUBCHECK_BUDGET_SECONDS` | `12` |
80
+ | `private_owner` | `PUBCHECK_PRIVATE_OWNER` | unset: the account whose `<owner>/_<name>` repos are private companions |
81
+ | `private_issues` | `PUBCHECK_PRIVATE_ISSUES` | unset: where context with no companion goes |
82
+ | `private_patterns` | (config only) | none: regexes for private references, such as working folders |
83
+
84
+ ## Caches and log
85
+
86
+ Visibility comes from a cache shared with other tools (`~/.cache/priv/repo_visibility/`), then `gh repo view`. The vocabulary is cached an hour in `~/.cache/public-text-guard/`. Decisions worth keeping go to `~/.local/state/public-text-guard/events.jsonl` (mode 0600): categories, repo, writer, a short hash of the text, an error's type and an override's reason; never the text or the matched terms.
87
+
88
+ ## System requirements
89
+
90
+ `gh` (authenticated) for visibility lookups and desk items; `acquaint` for the registry. Without `gh`, visibility is unknown and so public; without `acquaint`, an unattended check is unavailable.
@@ -0,0 +1,13 @@
1
+ pubcheck/__init__.py,sha256=5RgYLR5NBYNgceULNOhbO_XZIDVR9an3nnI3Fj4eOQM,1010
2
+ pubcheck/__main__.py,sha256=HEtR6zPqZK0HviWHFuFdAQJhQWjehqlICCIkRPCWJkE,3711
3
+ pubcheck/base.py,sha256=1Hg0HCxo4uYpcckyeKJR7muSdMXghHmNKmM0oCbqRdo,6364
4
+ pubcheck/core.py,sha256=wd3xFuRRd0NLravL2OXaine27Rs8LJYMw16wctSNkRo,11224
5
+ pubcheck/correspond.py,sha256=XBw9s7Z9suUzLkOrJ11MnU72p2QFXdZXvxMTaw4YdjQ,5624
6
+ pubcheck/detectors.py,sha256=SRbUbNBySSql8z56HvOSabkfIhIyv-tts1ci2mxO870,8439
7
+ pubcheck/hold.py,sha256=S4s31kTl2Z3IhKrkwyYVzFm0hR8A4llxuwEc89xXK5Q,6375
8
+ pubcheck/sources.py,sha256=u-fjSOUCk5O4DvwufW28fp5N6zARIQWOsk-n5UImiDM,9494
9
+ pubcheck-0.0.2.dist-info/METADATA,sha256=bQ8PqNUfKC4YtbKgZ8LibkQCRKxNM3TtsgQ__ZcNxJI,5501
10
+ pubcheck-0.0.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ pubcheck-0.0.2.dist-info/entry_points.txt,sha256=aeayClVNxsKx8Wb_poWzthaiDj4yo38bzwWtZe8gmiY,95
12
+ pubcheck-0.0.2.dist-info/licenses/LICENSE,sha256=ekE13yCE9fWWEJfP1NPnUJabZ_Wwrc6coKJV2ZZx27w,1068
13
+ pubcheck-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pubcheck = pubcheck.__main__:main
3
+ public-text-guard = pubcheck.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Whalen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.