Files
marketplace/skills/sync/scripts/push.py
T
naudachu 091dceec1d refactor: split issue domain from Gitea transport
An issue was a Gitea row that happened to be cached locally: its identity
was the tracker's number (42.md), its dependencies were tracker numbers
(depends: [#12]), and a local issue existed only as a draft that push
deleted on success. Nothing could be planned or tracked without a tracker.

Split into layers, with knowledge flowing one way:

  skills/issue  DOMAIN  what an issue is: format, validation, dep graph
        ^               offline; stdlib imports only, no subprocess
        | imports
  skills/sync   BRIDGE  map.py    md <-> Gitea JSON, pure, no I/O
                        _gitea.py login pin, api, pagination, filters
  skills/use    REFERENCE  tea CLI docs for non-issue entities

skills/issue never imports skills/sync. Delete the sync layer and the
domain keeps working.

Identity is now a slug derived from the title (wire-sqlc-appclick.md) and
is stable across retitles and pushes. Tracker numbers live in a `gitea:`
field, never in a file name and never in `depends:`; the pair is indexed
in .remote.json, which is a cache over the files, not a second source of
truth.

Behavior changes:

- Pushing is additive. The file is never deleted; it gains gitea:/url:/
  synced: and origin: flips from local to gitea. `origin: local` is a
  durable state, not a pending one.
- Pushes go in topological order so dependencies get numbers first.
- The dependency graph is computed offline from `depends:` metadata; body
  prose is passed through unchanged in both directions rather than being
  rewritten between slugs and #N.
- `origin` is domain-owned (whether work exists elsewhere is a fact about
  the work); the handle and how to reach it stay with sync.

Script moves:

  issue_get.py   -> sync/pull.py
  issue_push.py  -> sync/push.py
  issue_list.py  -> sync/remote.py
  issue_index.py -> issue/issue_index.py
  _tea.py        -> split into issue/issue.py, sync/map.py, sync/_gitea.py

New: issue/issue_new.py, issue/issue_check.py, issue/issue_tree.py, and
sync/comment.py — comment posting was the last issue operation still
hand-rolled through raw `tea api`.

references/issue-format.md moves to skills/issue/references/format.md;
label hex colors move out of it into map.py, since a color is how a
tracker paints a chip, not what an issue is.

Verified: offline path end to end (new, check, tree, index, push
--dry-run) and read-only against Gitea (remote listing, pull with
mapping, comment guard). Write paths of push.py and comment.py are not
exercised here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 23:37:32 +05:00

178 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""
push.py — local store -> Gitea.
Pushing is additive. The local file is never deleted and never moves: it gains
`gitea:`, `url:` and `synced:`, and `origin:` flips from `local` to `gitea`.
One issue, two places it is visible — not two kinds of file. A local-only issue
is a finished state, not a step on the way to a tracker.
push.py every local-only issue, dependencies first
push.py wire-sqlc-appclick one issue
push.py --update <id …> PATCH issues that are already in Gitea
push.py --dry-run validate only, no network
Before anything is sent, each issue is validated against the canonical format
by the domain layer (exactly one type/*, English title with no type prefix,
`## Summary` / `## Spec` / `## Acceptance criteria` present). `--force` posts
anyway; say why when you use it.
Dependencies are pushed in topological order so a parent is created after the
issues it depends on. A dependency that is still local-only is reported, not
silently dropped — the body's `## Depends on` prose is sent verbatim either
way, so nothing is lost, but the `#N` cross-links will be missing.
Missing labels are created with the canonical color and, for type/* and
severity/*, `exclusive: true` — `tea labels create` cannot set that field.
Login: the operator's pin from .claude/settings.local.json (see /tea:auth).
"""
import argparse
import os
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
sys.path[:0] = [_HERE, os.path.normpath(os.path.join(_HERE, "..", "..", "issue", "scripts"))]
import _gitea # noqa: E402
import issue # noqa: E402
import issue_index # noqa: E402
import map as gmap # noqa: E402
def select(issues, ids, update):
"""Which issues to send, and refuse the ambiguous combinations."""
if ids:
missing = [i for i in ids if i not in issues]
if missing:
_gitea.die("no such issue(s) in the store: %s" % ", ".join(missing))
chosen = list(ids)
else:
chosen = sorted(i for i in issues
if update or not issues[i].extra.get("gitea"))
if not chosen:
_gitea.die("nothing to push: every issue in the store is already in Gitea "
"(use --update to PATCH them, or issue_new.py to make one)")
if not update:
already = [i for i in chosen if issues[i].extra.get("gitea")]
if already:
_gitea.die("already in Gitea: %s — pass --update to PATCH them"
% ", ".join(already))
return chosen
def main():
ap = argparse.ArgumentParser(description="Push local issues to Gitea")
ap.add_argument("ids", nargs="*", help="issue ids (default: every local-only issue)")
ap.add_argument("--update", action="store_true",
help="PATCH issues that already carry a gitea: field")
ap.add_argument("--dry-run", action="store_true", help="validate only, no network")
ap.add_argument("--force", action="store_true", help="push despite format violations")
ap.add_argument("--repo", help="owner/repo (default: auto-detect from CWD git remote)")
ap.add_argument("--out", default=issue.ISSUE_ROOT, help="store root (default: tmp/issues)")
args = ap.parse_args()
root = args.out
issues = issue.load_all(root)
if not issues:
_gitea.die("store %s is empty — create an issue with issue_new.py first" % root)
chosen = select(issues, args.ids, args.update)
# ---- validate (domain layer, no network) -----------------------------
known = set(issues)
blocked = False
for id in chosen:
err, warn = issue.validate(issues[id], known_ids=known)
for w in warn:
_gitea.warn("%s: %s" % (id, w))
for e in err:
sys.stderr.write("%s: %s\n" % (id, e))
if err:
blocked = True
if blocked and not args.force:
_gitea.die("format violations (see above); --force overrides")
# ---- dependencies first ----------------------------------------------
edges = {i: [d for d in issues[i].depends if d in issues] for i in chosen}
order = [i for i in issue.topo_order(chosen, edges) if i in set(chosen)]
for c in issue.find_cycles(edges):
_gitea.warn("dependency cycle: %s" % " -> ".join(c))
if args.dry_run:
for id in order:
iss = issues[id]
print("ok %s [type/%s] %s (%s)"
% (id, iss.type or "?", iss.title, ", ".join(iss.labels) or "no labels"))
print("%d issue(s) would be %s" % (len(order), "updated" if args.update else "created"))
return
login = _gitea.require_login()
base = _gitea.repo_base(args.repo)
repo = _gitea.repo_slug(login, args.repo)
wanted = sorted({l for id in order for l in issues[id].labels})
label_ids = _gitea.ensure_labels(login, base, gmap.label_specs(wanted), root) \
if wanted else {}
milestone_ids = {}
remote_map = _gitea.load_map(root) or _gitea.rebuild_map(root, issues)
for id in order:
iss = issues[id]
unsynced = [d for d in iss.depends
if d in issues and not issues[d].extra.get("gitea")
and d not in order]
if unsynced:
_gitea.warn("%s: depends on local-only issue(s) %s — no #N cross-link in Gitea"
% (id, ", ".join(unsynced)))
ms_id = None
if iss.milestone:
if iss.milestone not in milestone_ids:
milestone_ids[iss.milestone] = _gitea.resolve_milestone_id(
login, base, iss.milestone)
ms_id = milestone_ids[iss.milestone]
if ms_id is None:
_gitea.warn("%s: milestone %r does not exist in %s — not set"
% (id, iss.milestone, repo))
number = gmap.number_of(iss)
if number:
payload = gmap.to_payload(iss, label_ids, ms_id, include_state=True)
got = _gitea.api(login, "%s/issues/%d" % (base, number), "PATCH", payload,
payload_name="issue-%s" % id, out_root=root)
verb = "updated"
else:
payload = gmap.to_payload(iss, label_ids, ms_id)
got = _gitea.api(login, "%s/issues" % base, "POST", payload,
payload_name="issue-%s" % id, out_root=root)
verb = "created"
if not isinstance(got, dict) or "number" not in got:
_gitea.die("%s: %s failed, unexpected response" % (id, verb))
number = got["number"]
# Gitea occasionally drops labels on create — re-apply rather than
# trust the echo.
applied = {l.get("name", "") for l in got.get("labels") or []}
missing = [l for l in iss.labels if l in label_ids and l not in applied]
if missing:
_gitea.api(login, "%s/issues/%d/labels" % (base, number), "PUT",
{"labels": [label_ids[l] for l in iss.labels if l in label_ids]},
payload_name="labels-%s" % id, out_root=root)
_gitea.warn("%s: labels re-applied via PUT (%s)" % (id, ", ".join(missing)))
gmap.apply_remote(iss, got, repo, _gitea.now_iso())
issue.save(root, iss)
remote_map[gmap.remote_key(repo, number)] = id
print("%s %s #%d %s" % (verb, id, number, got.get("html_url", "")))
_gitea.save_map(root, remote_map)
path, n = issue_index.build(root)
print("index: %s%d issue(s)" % (path, n))
if __name__ == "__main__":
main()