kunibert
All repositories: gitoria
12.1 KB
# K5: event intake and job queue (kunibert#5, step 1)Built in Hybriel .hl only. No real gitoria, tickets, codex or posting. No commits. Test scripts are Python, in scratch.Includes the design consultant's changes (a)-(d) from the follow-up message (handover point 21).## Files (all new)- `service/project.hl`: the map. Run: `hybriel service <config.json>`. Routes `POST /hook/gitoria`, `GET /health`, and a `hl:time` `every(tickSeconds)` timer calling `intake.tick()`.- `lib/intake.hl`: the route logic: checks, answers, logs.- `lib/gitoria-events.hl`: THE adapter. All event names, header names and field paths of apps-api.md v0 are here and only here.- `lib/queue.hl`: jobs, closed marks, stored thread flips, last-run heads, delivery ids, the worker tick and backoff.- `lib/run-job.hl`: `runJob(job)`. It only appends the job it would run to `<data>/runjobs.jsonl`. Test hooks: file `<data>/fail-<key, # as _>` makes it fail, `<data>/slow-<key>` makes it take 3 s.Config JSON: `{port, dataDir, secretsFile, tickSeconds, maxTries, backoffSeconds}`. The secrets file is JSON `{"default":"…","repos":{"<repo.id>":"…"}}` and lives outside the repo (tests: `/media/STORAGE/claude-scratch/kunibert/K5/secrets/secrets.json`).Data dir: `queue.json` (jobs, closed, pendingThreads, lastHead, seq) and `deliveries.json` (id → epoch ms; pruned at start, older than 7 days). Writes are atomic (`writeFile`).## BehaviourOrder of checks, each with its own answer and a log line (never the secret or the body):1. `X-Push-Signature-256` missing → 401 `missing_signature`.2. Wrong signature, or body changed after signing → 401 `bad_signature`. HMAC = `sha256=` + `hkdfExtract(toBytes(secret), req.bytes).hex()`.3. `X-Push-Event` unknown → 202 `ignored`.4. JSON parse (see GAP 2).5. `X-Push-Delivery` seen before → 200 `duplicate`, no new job.6. Mapping (`classify` in the adapter).Mapping:- `opened`, `reopened`, `synchronize`, `ready`, `review_requested` (sets force) → review job.- `review_comment.created` → merged into the job; `threadReplyOnly` (d).- `review_thread` resolved/unresolved → NO review (b).- `pull_comment`: `@kunibert reset` → reset; `@kunibert <text>` → note; anything else → ignored.- `closed`/`merged` → drop the job and mark the session for removal (c).- `ping` → logged only. A draft PR gives no job (a).Queue:- One job per `<repo.id>#<number>`. A newer event is folded in: the newest `time` wins for head and pull; force and reset OR together; thread updates and notes append; an older event never replaces the head.- A job that is running gets a follow-up (`next`). On success the follow-up takes its place; on failure it is folded into the retry.- A closed PR ignores events until `opened`/`reopened` with `time >=` the close time.Worker:- One tick takes the OLDEST queued job whose backoff is over, marks it running, calls `runJob`.- Success removes it. Failure keeps it with `tries+1` and backoff `backoffSeconds * 2^(tries-1)`. At `maxTries` (3) it becomes `failed` and one `OPERATOR:` log line is written.- A new event for a failed PR re-queues it with tries reset.- After a restart, a job that was `running` is `queued` again.### The design consultant changes(a) **Draft:** `pull.draft == true` → 202 ignored `draft pull request`, no job (not for closed/merged). `pull_request.ready` → review job.(b) **review_thread:** answered `thread-merged` (merged into the queued job's `threads`, no new job, no flag change) or `thread-stored` (kept in `pendingThreads[key]`, and picked up by the next job created for that PR, also while a job is running). It never starts a review.(c) **closed/merged:** the queued job and stored flips are dropped. `closed[key] = {time, state, removeSession:true, repo}` is recorded; `/health` lists `sessionsToRemove`. The runner acts on it later (nothing consumes the mark yet; clearing it is the runner's job). A running job is dropped when it ends. `reopened`/`opened` with a newer time clears the mark.(d) **threadReplyOnly:** a new job starts `true`. Any event except a `review_comment` carrying the same head as the baseline sets it false for good. Baseline = the job's own head, else `lastHead[key]` (head of the last successful run). A `review_comment` with another head, or with no baseline, makes it a full review.## Commands```sh# service (config tickSeconds 3600 for phases 1+2, 1 for 3+4); the test script starts and stops it itself by PIDpython3 /media/STORAGE/claude-scratch/kunibert/K5/tests/proof.py phase1 # intake, merge, close, draft, thread, answer timepython3 /media/STORAGE/claude-scratch/kunibert/K5/tests/proof.py phase2 # restart survivespython3 /media/STORAGE/claude-scratch/kunibert/K5/tests/proof.py phase3 # worker order, retry, failed, prunepython3 /media/STORAGE/claude-scratch/kunibert/K5/tests/proof.py phase4 # follow-up while running# by hand: hybriel service <config.json>/media/STORAGE/projects/hybriel/native/zig-out/bin/hybriel /media/STORAGE/projects/kunibert/service /media/STORAGE/claude-scratch/kunibert/K5/config-run.json```Full outputs: `/media/STORAGE/claude-scratch/kunibert/K5/proof-phase{1,2,3,4}.txt`, service log `svc.log`, the runJob record `data/runjobs.jsonl`. The service was stopped by PID after every phase, and no listener on 8850 remained. Port 8850 was free (`ss -ltn`) before the first start.## Proof (excerpts of the real output)```opened PR1 (valid) -> 202 {"status":"queued","job":"R1#1"} (6.7 ms)same delivery again -> 200 {"status":"duplicate"} queue unchanged (1 job)wrong signature -> 401 bad_signaturemissing signature -> 401 missing_signaturebody changed after signing -> 401 bad_signature queue still only PR1unknown event (signed) -> 202 ignored; ping -> 202 pingsynchronize PR1 head b, c, d -> 202 updated x3 queue: ONE job R1#1, head ddddOLDER synchronize (time 00:02) late -> head stays ddddreview_comment PR1 -> updated (merged); review_thread resolved PR1 -> thread-merged; job threads=2pull_comment "nice work" -> 202 ignored (comment without @kunibert)"@kunibert reset" / "@kunibert look at the db code" / review_requested -> job flags: force, reset, notes=['look at the db code']opened PR3 then closed PR3 -> {"status":"closed","dropped":true}; queue has no PR3(c) health: sessionsToRemove ['R1#3']; closed mark {'R1#3': time, state 'closed', removeSession True}(a) opened PR4 draft:true -> 202 ignored "draft pull request"; review_requested PR4 draft -> ignored; no PR4 job(a) pull_request.ready PR4 -> 202 queued R1#4(b) review_thread resolved PR5 (no job) -> thread-stored, health pendingThreadPrs 1;opened PR5 -> job R1#5 with threads=1 (its stored flip: ['review_thread.resolved'], seen again after the restart)answer time, 20 signed pings: min 1.4 avg 1.6 max 2.7 ms (single requests 1-7 ms)```Restart (phase 2): after stopping and starting again the queue has the same 4 jobs with the same flags, `deliveries` 40, and re-sending `d-open2` → 200 duplicate.Worker (phase 3, tick 1 s, `backoffSeconds` 2; PR2 has the fail hook; log lines from `svc.log`):```worker: start R1#1 try=1 -> done R1#1 (oldest first, one at a time; runJob saw force+reset+threads=2+note, all 7 merged events, head dddd)worker: start R1#2 try=1 -> failed (test failure hook), try 1/3, retry in 2sworker: start R1#4 ... done; start R1#5 ... done (threads=1)worker: start R1#2 try=2 -> failed, try 2/3, retry in 4sworker: start R1#6 ... doneworker: start R1#2 try=3 -> OPERATOR: job R1#2 FAILED after 3 tries: test failure hook (stays in queue.json as 'failed', tries=3)```- **Prune:** with an 8-day-old and a 6-day-old id added before start, only the 8-day-old one was gone after start.- **(d) PR6** (opened, run ok, `lastHead` aaaa): `review_comment` with the SAME head → `{"status":"queued","threadReplyOnly":true}`; then `review_comment` with a NEW head → `updated, threadReplyOnly:false`. runJob saw `threadReplyOnly:false`, head ffff, 2 thread updates.## DOCS lines- DOCS: hl:crypto has no named HMAC. `hkdfExtract(salt, ikm)` is used as HMAC-SHA256 (RFC 5869 §2.2). Please add `hmacSha256(key, data)`. Also a hex/constant-time compare of two digests.- DOCS: `verify(password, stored)` is constant-time but PHC-only, so it cannot compare two signatures.- DOCS: how a function route sets a status code and headers is only in the plugin source (`import { Response } from 'hl:http1'`, `new Response(body, { status, headers })`). COMPONENTS.md "function route" says only "a `Response` instance as it is".- DOCS: the HL-PRIMER does not say that a hybrid copies when it is read from a list or map into a local and when it is passed to a function. Changes need `jobs[i] = changed` or `&`. This was a bug in the first version (fold had no effect). The primer says "copies on assignment" but not "also an argument/element read".- DOCS: `;` between statements in a block (even `{ a(); b() }` on one line) is a parse error. Only the hybrid literal and `for(;;)` allow it. The primer says so, but the error costs time when one writes one-line blocks.- DOCS: how a project gets its arguments (`hybriel <dir> <arg>` → `args()[0]`) is only inferable. It worked.## GAP lines- **GAP 1: constant-time comparison.** No call compares two strings/Bytes in constant time. The signature is compared with `!=`, so it is timing-attackable in principle. No workaround.- **GAP 2: no catchable JSON.parse.** A SIGNED body that is not JSON gives HTTP 500 `Internal Server Error` plus the located error text (file path and line in the answer body!) and an `on Error` event, not the 400 `invalid_json` that was asked for. Unsigned garbage gets 401 first, since the signature check comes before the parse. Repro: `routes=[{pattern="/j" method="POST" function=(route,req)=>{ let b = JSON.parse(req.body) return {ok=true} }}]`, `curl -d '{bad' …/j` → 500. Needed: a `tryParse`/null-returning parse, or `on Error` that can answer for the request. Per-repo secrets (the `repos` map) force a parse BEFORE the signature check (the secret is keyed by `repo.id`), so with per-repo secrets garbage also gives 500 instead of 401; with only the default secret no parse happens before the check. Not worked around.- **GAP 3: blocking in the worker (not conclusive).** `runJob` is called awaited in the tick. In the service (phase 4), a `/health` poll sent while a job ran in `run('sleep 3')` was only answered after the job ended (`running` was already `None`), so the follow-up path (`next`) could NOT be hit live: the sync event arrived after the job had finished and was queued normally (runJob then saw the second head `bbbb` 3 s later, correct but not the follow-up path). In a tiny repro (timer + `run('sleep 3')` + a ping route) one trial answered the ping in 1 ms during the run and cut the run to 1.7 s, another ran 3.0 s. I did not clarify this. The real runJob (model runs of minutes) needs a non-blocking form (`spawn` + `on exit`), which means the queue needs a completion call (`done(key, result)`) instead of a return value. Open point for the next step.- **GAP 4 (earlier, known):** a task cannot be detached from a request, so a timer tick is used (DESIGN §5). Works.## Open points- The `follow-up` branch (event while a job runs) is written but only unit-reasoned, not shown live (GAP 3).- `@kunibert` is recognised only at the START of a comment (case-insensitive). A mention in the middle is ignored.- A `review_comment` with no `lastHead` baseline counts as a full review. `lastHead` is memory of the last successful run and is deleted on close.- Per-repo secrets are implemented (`repos` map) but not tested; only the default secret is in the tests.- No `tickets`, no `GET /pulls` start-up poll (planned later in DESIGN §2).- A PR closed while running is dropped on completion; no live test.- The `X-Push-Delivery` is recorded before the job is stored. If the process dies between the two writes the event is lost; gitoria cannot retry it because it counts as seen. Order could be swapped (job first) at the price of a double job on a crash.- `removeSession` marks are never cleared by anything yet; the runner must consume them.- `lib/runner.hl`/`tools/runner.hl` were not touched.
Branches
Latest commits
- 2eee9dbbMerge branch 'revendor-day44' into mainKunibert
- e96721cb|||PR Re-vendor plugins from Hybriel day44 (hl:fetch redirect fix)mre
- 0c67ab8cLog: kunibert repo ping provenmre
- b6f3039cLog: kunibert repo connectedmre
- b143c3c7CONDUCTOR: push recipemre
- 7a1279eeRule: conductor merges own utility PRs after green reviewmre
- 4038b3e0Log: kunibert#18 openedmre
- 18543db1Log: day42 fetch fix, re-vendor pendingmre
- 81a12f96Statusmre
- 6ce706abRecords: neutral wording, split cleanupmre
- 81a4d31bDocs: neutral wordingKunibert
- 8205b05eRecords: #17 livemre
- c3391204Answer fresh reviews under open threadsKunibert
- a0f3d147Records: #16 livemre
- 04322148Run reviews in parallel across repositoriesKunibert
- a6577aaeRecords: #14 live, #16 startedmre
- 0382238bStart fresh on Review again and name vendored pathsKunibert
- 5608c6f1Records: kunibert#13 vendored paths livemre
- 8840771dExclude vendored findings from app verdictsKunibert
- 6aa65353Records: jukebox connected, first reviewmre