@ouro.bot/cli 0.1.0-alpha.1557 → 0.1.0-alpha.1559
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.
- package/changelog.json +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/desk.lock.json +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/vendor/desk/.claude-plugin/plugin.json +1 -1
- package/vendor/desk/.ouro-desk.json +3 -3
- package/vendor/desk/CHANGELOG.md +40 -0
- package/vendor/desk/activation/copilot-root.flattened-bundle.json +1 -1
- package/vendor/desk/activation/desk.activation.json +3 -3
- package/vendor/desk/agency.json +1 -1
- package/vendor/desk/docs/issue-drains.md +8 -6
- package/vendor/desk/mcp/README.md +3 -1
- package/vendor/desk/mcp/scripts/local-recovery.js +89 -7
- package/vendor/desk/mcp/src/runtime/drains.js +474 -38
- package/vendor/desk/plugin.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1559",
|
|
6
|
+
"changes": [
|
|
7
|
+
"Update the Ouro UI files to Ouro UI v1.3.541."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1558",
|
|
12
|
+
"changes": [
|
|
13
|
+
"The Desk built into every agent is now release 3.2.552 (was 3.2.546). It includes Desk's drains correction from ourostack/desk#1746."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1557",
|
|
6
18
|
"changes": [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?xml version="1.0"?>
|
|
2
2
|
<Container version="2">
|
|
3
3
|
<Name>ouro-butler</Name>
|
|
4
|
-
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1559</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
package/desk.lock.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"repository": "ourostack/desk",
|
|
3
3
|
"branch": "release",
|
|
4
4
|
"path": "plugins/desk",
|
|
5
|
-
"version": "3.2.
|
|
6
|
-
"commit": "
|
|
7
|
-
"tree": "
|
|
5
|
+
"version": "3.2.552",
|
|
6
|
+
"commit": "5a822078555c6e21c0ba79a1221d9374a87ec529",
|
|
7
|
+
"tree": "38e483ce399e6b328239ba608fb7660c8939c1ee"
|
|
8
8
|
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1559",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@ouro.bot/cli",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.1559",
|
|
10
10
|
"bundleDependencies": [
|
|
11
11
|
"@ouro.bot/friends"
|
|
12
12
|
],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1559",
|
|
4
4
|
"description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
|
|
5
5
|
"homepage": "https://ouroboros.bot/",
|
|
6
6
|
"engines": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"repository": "ourostack/desk",
|
|
3
|
-
"version": "3.2.
|
|
4
|
-
"commit": "
|
|
5
|
-
"tree": "
|
|
3
|
+
"version": "3.2.552",
|
|
4
|
+
"commit": "5a822078555c6e21c0ba79a1221d9374a87ec529",
|
|
5
|
+
"tree": "38e483ce399e6b328239ba608fb7660c8939c1ee"
|
|
6
6
|
}
|
package/vendor/desk/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
1
1
|
# desk plugin — changelog
|
|
2
2
|
|
|
3
|
+
## 3.2.552 — 2026-11-25
|
|
4
|
+
|
|
5
|
+
- Issue drains: `Check gh auth status` is now said only for an HTTP 401 (a refused token). Any other refusal (403 permissions, 404, 422) and an unreadable GraphQL edit-history answer are recorded as GitHub's answer (`drains_github_refused`, `drains_graphql_failed`) with no credential diagnosis; quota handling and the no-retry of non-5xx answers, writes and network errors are unchanged.
|
|
6
|
+
|
|
7
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
8
|
+
|
|
9
|
+
## 3.2.551 — 2026-11-25
|
|
10
|
+
|
|
11
|
+
Desk's MCP server now vendors Ouro UI v1.3.540, moved by Ouro Current.
|
|
12
|
+
|
|
13
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
14
|
+
|
|
15
|
+
## 3.2.550 — 2026-11-25
|
|
16
|
+
|
|
17
|
+
Local recovery no longer reports a queued card log as `unexpected_tool_result`. A `task_update` that only logs (or logs alongside other fields) writes the entry before it returns and leaves the commit to Desk's background writer, so recovery now says so: exit `2`, `status: "partial"`, `code: "commit_queued"`, `effects.mutation: "reported_applied"`, `effects.commit: "queued"` and a `queued` object with the log path, whether Git still shows it uncommitted (`pending`) and who commits it. A mixed update keeps the card's observed commit in `effects.commit` and reports the log separately in `effects.log`. If the writer has already committed the entry when recovery looks, the result is the usual completed `observed` result. The receipt says not to resend, because a resend duplicates the entry. With `--publication deferred` no background commit is scheduled, and the receipt says the next Desk session start commits it or the caller must. Unknown results and refusals still end `unexpected_tool_result` or `tool_error` and are never resent. See [the recovery contract](mcp/README.md).
|
|
18
|
+
|
|
19
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
20
|
+
|
|
21
|
+
## 3.2.549 — 2026-11-25
|
|
22
|
+
|
|
23
|
+
### Issue drains: a GitHub 5xx is no longer worded as an auth problem
|
|
24
|
+
|
|
25
|
+
When GitHub answers a drain's read with a 5xx (500, 502, 503, 504), the poll now asks once more in the same poll. If the retry fails too, the drain's last error says GitHub's server failed and needs nothing from you (`drains_github_server_error`) instead of sending an agent to `Check gh auth status`, which stays for a refused credential. Writes are never retried, and a persistent failure still wakes nobody and leaves what the drain has seen untouched. See [issue drains](docs/issue-drains.md).
|
|
26
|
+
|
|
27
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
28
|
+
|
|
29
|
+
## 3.2.548 — 2026-11-25
|
|
30
|
+
|
|
31
|
+
The issue-drain poller now decides whether a body change is a bot's from the issue's edit history, on any issue whoever created it. A body that only bots edited since the last poll, such as a health table refreshed every few minutes, wakes nobody, and a person's edit among a bot's still wakes the drain. Anything the history cannot prove (an unknown or deleted edit, a history that cycles, a changed title, a revision recorded before titles were kept) stays news. The history is read page by page with progress kept in the poll state, so a very long one is finished across GraphQL quota windows, scans share the pages fairly, and an issue that needs no read is never held behind one. A read that fails or runs out of quota leaves only that issue for the next poll and is shown as the poll's error without waking the drain. The GraphQL quota is kept apart from the REST quota. See [issue drains](docs/issue-drains.md).
|
|
32
|
+
|
|
33
|
+
Someone else assigning or unassigning an issue now wakes the drain (`assigned <login>`, `unassigned <login>`), while the drain's own assignment during its turn stays quiet. A poll lock is no longer taken from a live owner however long it holds it, is published whole as a directory, and is released only by its owner; a lock file left by an earlier Desk is never replaced, and the poll says so instead of calling it busy.
|
|
34
|
+
|
|
35
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
36
|
+
|
|
37
|
+
## 3.2.547 — 2026-11-25
|
|
38
|
+
|
|
39
|
+
Desk's MCP server now vendors Ouro UI v1.3.539, moved by Ouro Current.
|
|
40
|
+
|
|
41
|
+
Ships `desk-mcp@1.4.0-alpha.6`.
|
|
42
|
+
|
|
3
43
|
## 3.2.546 — 2026-11-25
|
|
4
44
|
|
|
5
45
|
Desk's MCP server now vendors Ouro UI v1.3.538, moved by Ouro Current.
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema_version": 1,
|
|
3
3
|
"id": "desk",
|
|
4
|
-
"version": "3.2.
|
|
4
|
+
"version": "3.2.552",
|
|
5
5
|
"dependencies": [
|
|
6
6
|
{
|
|
7
7
|
"id": "desk",
|
|
8
8
|
"kind": "substrate",
|
|
9
|
-
"version": "3.2.
|
|
9
|
+
"version": "3.2.552",
|
|
10
10
|
"provenance": {
|
|
11
11
|
"source": "plugins/desk/.claude-plugin/plugin.json",
|
|
12
12
|
"package": "ourostack/desk"
|
|
13
13
|
},
|
|
14
14
|
"lock": {
|
|
15
|
-
"version": "3.2.
|
|
15
|
+
"version": "3.2.552",
|
|
16
16
|
"integrity": "sha256-desk-activation-manifest-v1"
|
|
17
17
|
}
|
|
18
18
|
},
|
package/vendor/desk/agency.json
CHANGED
|
@@ -35,28 +35,30 @@ Only `repo` and `session` are required. `session` is opaque to Desk: the runner
|
|
|
35
35
|
|
|
36
36
|
## What wakes a drain
|
|
37
37
|
|
|
38
|
-
An issue is news when something other than the drain changed it since the revision last recorded: a new issue, a title or body edit, a comment, a reopen, or a label change. These are not news:
|
|
38
|
+
An issue is news when something other than the drain changed it since the revision last recorded: a new issue, a title or body edit, a comment, a reopen, an assignment change, or a label change. These are not news:
|
|
39
39
|
|
|
40
40
|
- a new issue the drain filed or already triaged: a label in its `drain:` namespace, or the `<!-- ouro-drain-status -->` marker in its body, is there before the poll first sees it, so the issue is recorded as seen and only later changes by others count;
|
|
41
41
|
- the drain's own status comment, matched by the `<!-- ouro-drain-status -->` marker and the polling account, including its edits. The polling account is whoever the drain's token is (`GET /user` on its own `account`'s token), resolved per repository, so a drain on a work account and one on a personal account each recognise only their own comments;
|
|
42
42
|
- labels starting with `drain:`, any label in the drain's `ignoredLabels`, and any label whose name matches a regular expression in its `ignoreLabels` (case-insensitive, for example `["^waiting:", "^lane:"]`): the escape hatch for a lane's own labels;
|
|
43
|
-
- a label or
|
|
43
|
+
- a label, reopen or assignment change made by the polling account during the drain's turn, whatever the label. The turn opens when a wake is delivered (a minute earlier, for a drain that acts before the delivery is acknowledged) and lasts 90 minutes; the poller keeps each drain's recent delivery times in its state (`turns`). The same account's changes outside a turn, and anyone else's inside one, still wake the drain;
|
|
44
|
+
- a body edit that only bots made, whoever created the issue. When its body changed (its title did not) the poll reads the issue's edit history over GraphQL (`Issue.userContentEdits`, 100 a page, from the start and the end in turn once a baseline is recorded) and stays quiet only when it has at least one edit since the revision last recorded and every such edit is a bot's (`Bot` or a login ending `[bot]`), so a health table a bot refreshes every few minutes wakes nobody. A person's edit anywhere in that interval wakes the drain, whatever bots edited around it. So does anything the history cannot prove: an edit whose editor is unknown or gone, a deleted edit, an edit with no id or time, a history that cycles or stands still, a changed title, or a revision recorded before the poll kept titles. The issue's creator is no part of the decision. Comments, labels, reopens, cross-references and someone else's assigning or unassigning are checked as usual after a quiet body edit.
|
|
45
|
+
The read is kept in the poll state per issue (`scans`), so it survives quota windows and a history of any length: each poll spends pages only while the account's GraphQL quota (the last `rateLimit` answer, each page costing what GitHub charged for it) stays above the 25-call reserve, pending reads take turns a page at a time (least recently served first) so none starves, and nothing else waits for them: an issue that needs no read is judged in the first poll. A read that stops (quota, network, authentication, a history that lags the issue) leaves that issue's marker where it was and the poll reports `N issue(s) were left for it` as its last error, with the code of the failure; that alone wakes nobody, and the next poll goes on from the saved page. Edits made while a read is under way are not a reason to restart it; an edit by a person among them still wakes the drain. Limits: GitHub's GraphQL answers, an append-only history and agreeing clocks are assumed, not verified; after a wake the next bot-only body change is read from the start once.
|
|
44
46
|
- body lines that start with a key in `ignoredBodyTrailers` (`Active-at: …`), so a lane's scheduled beat does not wake the drain;
|
|
45
47
|
- comments that fit an `ignoreComments` rule: written by its `author` (case-insensitive) and, when the rule has a `match`, a body that matches the regular expression. A rule without `match` skips every comment by that author; the same bot's other comments still wake the drain;
|
|
46
48
|
- a bot's comment that repeats that bot's previous comment on the issue: the two texts are the same once run URLs and IDs, dates, times and durations (`took 14 min`) are replaced, so a daily "checks failed" report or a CI-budget note wakes the drain the first time and when its text changes, not on every repeat. A person's comment, a bot's first comment and a changed text still wake it;
|
|
47
49
|
- a reopen that is the drain claiming the issue: the polling account reopens it within a minute of its own `drain:` label change;
|
|
48
50
|
- commit references (`referenced` events) and edits to the drain's own marked comment, which the rules above already skip;
|
|
49
|
-
- closes
|
|
51
|
+
- closes, and cross-references: a cross-reference the drain made itself. When an issue's `updated_at` moved and nothing above was news, the poll reads its timeline, and a `cross-referenced` event after the last marker wakes the drain unless its source is the drain's own work: an issue or pull request the drain filed (a label in its `drain:` namespace, or the `<!-- ouro-drain-status -->` marker in its body), a pull request on a `drain-…` or `drain/…` branch, the drain's marked status comment on this issue that names the source (`#50`, `owner/name#50` or a link), or its marked comment on the source that names this issue around then. Put the marker in the body of every pull request the drain opens: it is the one deterministic link between a drain's pull request and the issue it fixes, on any branch name. Any other cross-reference is news, and its event says where it came from. A pull request's merge or close is not news: the drain learns a fix landed from its own PR. A closed issue is not polled at all. GitHub does not move an issue's `updated_at` for a cross-reference or a commit reference, so an outside cross-reference is noticed with the issue's next change, which can be hours later; the poll does not read every open issue's timeline to find it sooner.
|
|
50
52
|
|
|
51
53
|
## Spending little quota
|
|
52
54
|
|
|
53
|
-
A poll is cheap on the account's REST quota. Between full syncs it asks GitHub only for what changed: `state=all&sort=updated&since=` the newest change it knew (less two minutes), sent with the `ETag` of the last answer as `If-None-Match`, so an unchanged repository costs one call that GitHub answers with a 304 and does not count against the rate limit. A change that closed an issue is in that list and marks it gone; a reopen is news. Once an hour the whole open list is read again (a full sync), which also catches anything the `since` window missed. The timeline of an issue is read only when its `updated_at` moved with nothing else news. The account's login is asked of GitHub once a day and kept in the state.
|
|
55
|
+
A poll is cheap on the account's REST quota. Between full syncs it asks GitHub only for what changed: `state=all&sort=updated&since=` the newest change it knew (less two minutes), sent with the `ETag` of the last answer as `If-None-Match`, so an unchanged repository costs one call that GitHub answers with a 304 and does not count against the rate limit. A change that closed an issue is in that list and marks it gone; a reopen is news. Once an hour the whole open list is read again (a full sync), which also catches anything the `since` window missed. The timeline of an issue is read only when its `updated_at` moved with nothing else news. The account's login is asked of GitHub once a day and kept in the state. The edit history is read only for an issue whose body changed and whose title did not, with one GraphQL call per 100 edits, read to the end of the history however long it is (a cursor that repeats counts as incomplete). GraphQL has its own quota window: its reading is kept apart as `graphqlQuota` in the state and never replaces the REST quota that holds a drain.
|
|
54
56
|
|
|
55
57
|
Every answer's `x-ratelimit-*` headers are kept per account. When an account has 25 calls or fewer left, its drains are not polled until the window resets; when it is under 200 left (or under a tenth of its limit), they are polled at most every 15 minutes. Drains that share an account share the reading. `status` shows each account's quota first (`quota <account>: 4700/5000 calls left, resets <time> (read 2m ago); the last cycle used 3 calls, 2 of them not modified`) and `held: …` after a drain that is waiting on quota.
|
|
56
58
|
|
|
57
59
|
## Seeing a gap
|
|
58
60
|
|
|
59
|
-
`status` (and the `status` lines `poll` prints) start with the Desk in use (`desk <version> (ourostack/desk@release 1a2b3c4d, the launcher's own copy)`; the JSON also has `desk.version` and `desk.release`) and then show, per drain, the last poll that read GitHub without an error and its lag (`last ok poll … (lag 2m)`), the last attempt, and how long the oldest waiting event has waited (`2 waiting (oldest 5h)`). A poll that keeps failing shows a growing lag and its last error; a wake that is made but never delivered shows a growing wait. Each recorded event carries `seenAt`, the time the poll first saw it, and `why`, the one change that made it news (`new issue`, `title or body edited`, `comment <id> by <login>`, `labeled <name>`, `unlabeled <name>`, `reopened`), so a wake nobody expected can be traced to a signal. The wake message names the reason after each issue (`#876 Title (cross-reference from owner/name#9)`), and each drain keeps its last 200 events in its state (with the Desk version, and the release commit for the launcher's own copy, that polled them), so `drains.js why owner/name#123` prints the reasons recorded for that issue (newest first), the marker the poll keeps for it and whether a wake is still waiting.
|
|
61
|
+
`status` (and the `status` lines `poll` prints) start with the Desk in use (`desk <version> (ourostack/desk@release 1a2b3c4d, the launcher's own copy)`; the JSON also has `desk.version` and `desk.release`) and then show, per drain, the last poll that read GitHub without an error and its lag (`last ok poll … (lag 2m)`), the last attempt, and how long the oldest waiting event has waited (`2 waiting (oldest 5h)`). A poll that keeps failing shows a growing lag and its last error; a read GitHub answers with a 5xx is asked once more at once, and if that fails too the last error says GitHub's server failed (`drains_github_server_error`, it usually clears on the next poll, nothing to do), while `Check gh auth status` is kept for a refused credential (HTTP 401 only) and any other refusal (403 permissions, 404, 422, an unreadable GraphQL answer) is reported as GitHub's answer without a credential diagnosis (`drains_github_refused`, `drains_graphql_failed`); a wake that is made but never delivered shows a growing wait. Each recorded event carries `seenAt`, the time the poll first saw it, and `why`, the one change that made it news (`new issue`, `title or body edited`, `comment <id> by <login>`, `labeled <name>`, `unlabeled <name>`, `assigned <login>`, `unassigned <login>`, `reopened`), so a wake nobody expected can be traced to a signal. The wake message names the reason after each issue (`#876 Title (cross-reference from owner/name#9)`), and each drain keeps its last 200 events in its state (with the Desk version, and the release commit for the launcher's own copy, that polled them), so `drains.js why owner/name#123` prints the reasons recorded for that issue (newest first), the marker the poll keeps for it and whether a wake is still waiting.
|
|
60
62
|
|
|
61
63
|
## Delivering a wake
|
|
62
64
|
|
|
@@ -72,7 +74,7 @@ Every answer's `x-ratelimit-*` headers are kept per account. When an account has
|
|
|
72
74
|
|
|
73
75
|
If a drain's `session` is archived or gone, the `--error` text from `done` says so and the drain recovers by itself: Desk starts a successor session with `shepherd create` (its first kickoff line is `Succeeds: <old id>`), keeps the new id in the drain's state (the config is never edited), and sends later wakes there. A failed start is retried after ten minutes, and a changed `session` in the config drops the override. `gh auth token` is read up to three times, so a timeout or a busy keyring is retried; only gh's own "no oauth token" says to sign in.
|
|
74
76
|
|
|
75
|
-
One poll or ack runs at a time
|
|
77
|
+
One poll or ack runs at a time. `poll.lock` is a directory that is published whole: Desk writes `poll.lock.new-<pid>-<token>/owner-<token>` (the process id) and renames it onto `poll.lock`, which succeeds only where the lock is absent or empty, so the lock is never visible empty or half-written. A second run stops with `desk_drains_busy` while the owner's process is alive, however long it has held it, and nothing ages a live owner out. A dead owner is retired by removing its own `owner-<token>` file (a name no later owner reuses, so a run with a stale view removes nothing of a newer lock) and then `rmdir`, which refuses a lock that has an owner; a poll releases only its own owner file. On Windows, whose rename replaces a plain file (measured on a Windows runner), the directory is published with .NET's `Directory.Move` through `pwsh` or, if that cannot be launched, `powershell` (a fixed script with the paths passed as data; it ends in a move without replace-existing, so the system refuses an existing target); a shell that ran is never retried and `rename` is never the fallback, so with neither shell the lock is `desk_drains_lock_unavailable`. When the publish fails for any reason, Desk looks at what is at `poll.lock` rather than trusting the error code (Windows reports `EPERM` for an occupied target): an owner, an empty directory or a file is handled as below, and only a failure with nothing in the way is `desk_drains_lock_unavailable`. Staging directories of dead processes, which a crash can leave, are removed by exact name. Desk fails closed, without removing anything and with its own error, on a `poll.lock` that is a file (`desk_drains_lock_legacy`, the lock of an earlier Desk, whose owner cannot be told: once no earlier poll or ack is running, remove it yourself), on entries or an owner file it did not make (`desk_drains_lock_unrecognized`), and on a failure to use the directory (`desk_drains_lock_unavailable`, naming the error code). Limits: a recycled process id can make a dead owner look alive, and the run stays busy until that process ends; the behaviour is verified on POSIX file systems only (not Windows), and without fsync, so not across power loss.
|
|
76
78
|
|
|
77
79
|
## Moving an Ouroboros drain list
|
|
78
80
|
|
|
@@ -49,10 +49,12 @@ The command writes one local JSON report and exits:
|
|
|
49
49
|
| --- | --- |
|
|
50
50
|
| `0` | The tool reported completion, no pending push is claimed (with `--publication deferred`, the push is reported `deferred` and left to the caller), and any expected Git commit was observed through a HEAD change. This is not a project's code-delivery claim. |
|
|
51
51
|
| `1` | No mutation was dispatched: input, root, admission, scope or transport preflight refused. |
|
|
52
|
-
| `2` | Partial or unknown effects: tool/parse/transport failure after dispatch, missing commit evidence, `commit_failed`, `push_pending`, or uncertain child shutdown. |
|
|
52
|
+
| `2` | Partial or unknown effects: tool/parse/transport failure after dispatch, missing commit evidence, `commit_failed`, `commit_queued`, `push_pending`, or uncertain child shutdown. |
|
|
53
53
|
|
|
54
54
|
The report retains `operation`, `requestedRoot`, `actualRoot` when available, `preflight`, `result`, `effects`, local `git.headBefore`/`headAfter`, `transport.pid`/`shutdown`, and concrete `readback` commands. Tool-result string values matching input strings are redacted, and our shared credential scrub also covers runtime error text; the original JSON remains the source for exact card/file identities. Raw parser errors and child stderr are not printed. `effects.mutation: "not_dispatched"` establishes only that this client sent no mutation; admission may still create derived runtime state or perform its already-declared state-branch checks. `reported_applied` is the tool's account, not an independent diff. `reported_complete` covers `nothing_to_commit` and `already_archived` without claiming those responses prove unchanged files. An `isError` response alone never establishes unchanged files. A changed HEAD is an observation, not attribution against a concurrent writer.
|
|
55
55
|
|
|
56
|
+
A `task_update` `log` is written before the call returns but committed later by Desk's background writer. Recovery accepts that admitted queued result without waiting: `status: "partial"`, `code: "commit_queued"`, exit `2`, `effects.mutation: "reported_applied"`, `effects.commit: "queued"` for a log-only call, and `queued: {path, state, committer}`. `state` is `pending` while the path is not at `HEAD` or its bytes differ from the `HEAD` blob and `committer` is `background_worker`, or `next_session_start` under `--publication deferred`, which schedules no worker. In a mixed call `effects.commit` keeps the card commit's own observation and `effects.log` carries the log's `queued` or `observed`. Readback is qualified: it reads the log only through a root-contained, link-free directory chain pinned by an opened descriptor, and when the log is not yet at `HEAD` it lists Git's names for the path without reading its bytes. If the path is ignored, missing, linked or relocated, or a read of a log already at `HEAD` cannot be completed or its identity changes, the log's state is `unknown`: the call stays `partial` with the same do-not-resend receipt, never `observed`. A log not yet at `HEAD` is `pending` on Git's listed names alone; its readability is not checked. Observation shows the entry's bytes at `HEAD`; it does not say who wrote them. If the writer already committed the entry when recovery looks, the ordinary `observed`/exit `0` rules apply. Never resend a queued log; it would duplicate the entry. A `logged` result without the queued marker, or any other unknown result, stays `unexpected_tool_result`.
|
|
57
|
+
|
|
56
58
|
Push runs through the existing asynchronous handler. A configured remote is conservatively reported as pending, even if its worker later finishes; the client does not poll for delivery or advertise a successful push. A commit failure can leave the real card write applied. A timeout after dispatch can also occur after application. Read the named card/files and local status, HEAD, last commit paths and upstream in the confirmed desk before considering another mutation. Do not automatically resend, retry a permission/validation refusal elsewhere, or replace this path with unvalidated card edits.
|
|
57
59
|
|
|
58
60
|
The owned bootstrap is closed on every outcome, with bounded EOF/SIGTERM shutdown; the scheduled push keeps its ordinary lifetime. At the agent's reporting boundary, use `desk-problem`'s existing `broke / means / fix / file / tell` fields, keeping private roots local and public filings generic. This JSON transport report does not replace that block or change any published MCP result schema.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { spawn, spawnSync } from "node:child_process"
|
|
4
|
-
import { realpathSync, statSync, promises as fs } from "node:fs"
|
|
4
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, realpathSync, statSync, promises as fs } from "node:fs"
|
|
5
5
|
import * as path from "node:path"
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from "node:url"
|
|
7
7
|
import { resolveStartupStateBranch } from "../src/runtime/startup-resolve.js"
|
|
@@ -191,6 +191,64 @@ function gitHead(root, env) {
|
|
|
191
191
|
return result.status === 0 ? result.stdout.trim() : null
|
|
192
192
|
}
|
|
193
193
|
|
|
194
|
+
// The qualified namespace of one log: the root and every directory below it down to the leaf, each by exact (dev, ino). Any symbolic link, non-directory parent or non-regular leaf, and a root that is not its own real path, disqualifies it.
|
|
195
|
+
function qualifyLog(root, rel) {
|
|
196
|
+
try {
|
|
197
|
+
if (realpathSync(root) !== path.resolve(root)) return null
|
|
198
|
+
const identity = (stat) => ({ dev: stat.dev, ino: stat.ino })
|
|
199
|
+
const chain = []
|
|
200
|
+
let current = path.resolve(root)
|
|
201
|
+
const parts = rel.split(/[\\/]/u)
|
|
202
|
+
for (const [index, part] of [null, ...parts].entries()) {
|
|
203
|
+
if (part !== null) current = path.join(current, part)
|
|
204
|
+
const stat = lstatSync(current, { bigint: true })
|
|
205
|
+
const last = index === parts.length
|
|
206
|
+
if (stat.isSymbolicLink() || (last ? !stat.isFile() : !stat.isDirectory())) return null
|
|
207
|
+
chain.push(identity(stat))
|
|
208
|
+
}
|
|
209
|
+
return { file: current, chain }
|
|
210
|
+
} catch { return null }
|
|
211
|
+
}
|
|
212
|
+
const sameChain = (a, b) => a.chain.length === b.chain.length && a.chain.every((entry, i) => entry.dev === b.chain[i].dev && entry.ino === b.chain[i].ino)
|
|
213
|
+
|
|
214
|
+
// A queued log is already in the working tree. It counts as committed only when the working file, hashed with the path's own Git filters (EOL included), is the very blob `head` holds at that path. Status flags such as assume-unchanged cannot hide a difference from that comparison, and every path is literal. A path Git neither tracks at `head` nor lists as indexed or untracked (missing, ignored) stays unknown; that listing reads names only, never the file's bytes, and runs only through a qualified namespace.
|
|
215
|
+
// Acquisition: the qualified namespace is walked, the leaf opened with O_NOFOLLOW, and the descriptor must be the walked leaf (exact bigint dev/ino) and the walk must repeat unchanged BEFORE Git is handed the descriptor, and again after. Git then reads that descriptor; `--path` only supplies the logical attribute/filter context. This pins what is hashed to the object the qualified path named; it does not keep the namespace unchanged while reading, and Node has no race-free openat. It observes content at `head`; it does not attribute who wrote it. `probe` is a test seam between the steps.
|
|
216
|
+
export function logCommitState(root, env, rel, head, probe = {}) {
|
|
217
|
+
if (typeof rel !== "string" || !rel || path.isAbsolute(rel) || rel.split(/[\\/]/u).includes("..") || !head) return "unknown"
|
|
218
|
+
const git = (args, stdio) => spawnSync("git", ["--literal-pathspecs", ...args], { cwd: root, env, encoding: "utf8", timeout: 5000, windowsHide: true, ...(stdio ? { stdio } : {}) })
|
|
219
|
+
const first = qualifyLog(root, rel)
|
|
220
|
+
const blob = git(["rev-parse", "--verify", `${head}:${rel}`])
|
|
221
|
+
if (blob.status !== 0) {
|
|
222
|
+
// Not at `head`: only the names Git lists (index entries, untracked non-ignored files) are consulted, never the file's bytes, and only through a namespace that qualified before and still does after.
|
|
223
|
+
if (first === null) return "unknown"
|
|
224
|
+
probe.afterWalk?.()
|
|
225
|
+
const listed = git(["ls-files", "--cached", "--others", "--exclude-standard", "--", rel])
|
|
226
|
+
const again = qualifyLog(root, rel)
|
|
227
|
+
return listed.status === 0 && listed.stdout.trim() !== "" && again !== null && sameChain(first, again) ? "pending" : "unknown"
|
|
228
|
+
}
|
|
229
|
+
if (first === null) return "unknown"
|
|
230
|
+
probe.afterWalk?.()
|
|
231
|
+
let fd
|
|
232
|
+
try {
|
|
233
|
+
fd = openSync(first.file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)
|
|
234
|
+
const opened = fstatSync(fd, { bigint: true })
|
|
235
|
+
const leaf = first.chain.at(-1)
|
|
236
|
+
if (!opened.isFile() || opened.dev !== leaf.dev || opened.ino !== leaf.ino) return "unknown"
|
|
237
|
+
probe.afterOpen?.()
|
|
238
|
+
const again = qualifyLog(root, rel)
|
|
239
|
+
if (again === null || !sameChain(first, again)) return "unknown"
|
|
240
|
+
const working = git(["hash-object", `--path=${rel}`, "--stdin"], [fd, "pipe", "pipe"])
|
|
241
|
+
probe.afterHash?.()
|
|
242
|
+
const after = fstatSync(fd, { bigint: true })
|
|
243
|
+
const last = qualifyLog(root, rel)
|
|
244
|
+
if (working.status !== 0 || last === null || !sameChain(first, last)
|
|
245
|
+
|| after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) return "unknown"
|
|
246
|
+
return working.stdout.trim() === blob.stdout.trim() ? "committed" : "pending"
|
|
247
|
+
} catch { return "unknown" } finally {
|
|
248
|
+
if (fd !== undefined) closeSync(fd)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
194
252
|
/** One mutation at most, through the ordinary MCP bootstrap and admission. */
|
|
195
253
|
export async function runRecovery({
|
|
196
254
|
argv = process.argv.slice(2), options, env = process.env, cwd = process.cwd(),
|
|
@@ -309,26 +367,50 @@ export async function runRecovery({
|
|
|
309
367
|
const response = await client.request("tools/call", { name: report.operation, arguments: payload }, Math.min(Date.now() + dispatchTimeoutMs, totalDeadline))
|
|
310
368
|
const result = toolPayload(response)
|
|
311
369
|
report.result = redact(result, payload)
|
|
370
|
+
// Only an admitted queued log is accepted; a bare "logged" without it stays unexpected.
|
|
371
|
+
const queuedPath = result.status === "logged" && result.commit === "queued" ? result.path
|
|
372
|
+
: result.status === "updated" && result.log?.commit === "queued" ? result.log.path : null
|
|
312
373
|
report.git.headAfter = gitHead(root, env)
|
|
374
|
+
const logState = queuedPath === null ? null : logCommitState(root, env, queuedPath, report.git.headAfter)
|
|
313
375
|
if (response.isError || result.status === "error") throw failure("tool_error")
|
|
314
|
-
if (!["updated", "created", "archived", "already_archived", "committed", "nothing_to_commit", "commit_failed", "commit_unknown"].includes(result.status)) {
|
|
376
|
+
if (!["logged", "updated", "created", "archived", "already_archived", "committed", "nothing_to_commit", "commit_failed", "commit_unknown"].includes(result.status) || (result.status === "logged" && queuedPath === null)) {
|
|
315
377
|
throw failure("unexpected_tool_result")
|
|
316
378
|
}
|
|
317
379
|
report.effects.mutation = ["nothing_to_commit", "already_archived"].includes(result.status)
|
|
318
380
|
? "reported_complete" : "reported_applied"
|
|
319
|
-
report.
|
|
381
|
+
const headChanged = report.git.headBefore !== null && report.git.headAfter !== null && report.git.headBefore !== report.git.headAfter
|
|
382
|
+
const logOnly = result.status === "logged"
|
|
383
|
+
if (queuedPath !== null) {
|
|
384
|
+
report.effects.log = logState === "pending" ? "queued" : logState === "committed" && headChanged ? "observed" : "unknown"
|
|
385
|
+
report.queued = { path: queuedPath, state: logState, committer: options["publication"] === "deferred" ? "next_session_start" : "background_worker" }
|
|
386
|
+
}
|
|
387
|
+
report.effects.commit = logOnly ? report.effects.log
|
|
388
|
+
: result.commit?.status === "failed" ? "failed"
|
|
320
389
|
: result.commit?.status === "unknown" ? "unknown"
|
|
321
390
|
: report.git.headBefore !== null && report.git.headAfter !== null
|
|
322
391
|
? report.git.headBefore !== report.git.headAfter ? "observed" : "not_observed"
|
|
323
392
|
: "unknown"
|
|
324
393
|
report.effects.push = status.sync === "no remote configured" ? "not_applicable" : options["publication"] === "deferred" ? "deferred" : "pending"
|
|
325
|
-
const commitExpected = ["updated", "created", "archived", "committed"].includes(result.status)
|
|
326
|
-
|
|
327
|
-
|
|
394
|
+
const commitExpected = ["updated", "created", "archived", "committed"].includes(result.status) || (logOnly && logState === "committed")
|
|
395
|
+
const logPending = report.effects.log === "queued"
|
|
396
|
+
if (report.effects.log === "unknown") {
|
|
397
|
+
report.readback = `The entry at ${queuedPath} was reported written, but Git does not show it committed or pending. Do not resend it: that may duplicate the entry. Read that path first. ${report.readback}`
|
|
398
|
+
}
|
|
399
|
+
if (logPending) {
|
|
400
|
+
// --publication deferred schedules no background worker, so nothing in this run will commit the entry.
|
|
401
|
+
const who = report.queued.committer === "background_worker" ? "its commit is pending in Desk's background writer"
|
|
402
|
+
: "publication is deferred, so no background commit is scheduled: the next Desk session start commits it, or commit that path yourself"
|
|
403
|
+
report.readback = `Entry written to ${queuedPath}; ${who}. Do not resend it: that would duplicate the entry. ${report.readback}`
|
|
404
|
+
}
|
|
405
|
+
if (report.effects.commit === "failed" || result.commit?.status === "unknown" || report.effects.push === "pending" || logPending ||
|
|
406
|
+
report.effects.log === "unknown" || (commitExpected && report.effects.commit !== "observed")) {
|
|
328
407
|
report.status = "partial"
|
|
329
408
|
report.code = report.effects.commit === "failed" ? "commit_failed"
|
|
330
409
|
: result.commit?.status === "unknown" ? "commit_unknown"
|
|
331
|
-
: report.effects.
|
|
410
|
+
: commitExpected && report.effects.commit !== "observed" ? "commit_not_observed"
|
|
411
|
+
: logPending ? "commit_queued"
|
|
412
|
+
: report.effects.log === "unknown" ? "log_evidence_unknown"
|
|
413
|
+
: "push_pending"
|
|
332
414
|
exitCode = 2
|
|
333
415
|
} else {
|
|
334
416
|
report.status = "completed"
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
//
|
|
5
5
|
// `updated_at` alone is not a revision: the drain's own label edits and status comment move it too. An issue is news only when
|
|
6
6
|
// something other than the drain changed it since the revision last recorded for that issue.
|
|
7
|
-
import { createHash } from "node:crypto"
|
|
7
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
8
8
|
import { spawnSync } from "node:child_process"
|
|
9
|
-
import {
|
|
9
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"
|
|
10
10
|
import { fileURLToPath } from "node:url"
|
|
11
11
|
import * as os from "node:os"
|
|
12
12
|
import * as path from "node:path"
|
|
@@ -26,9 +26,11 @@ const TURN_MS = 90 * 60_000
|
|
|
26
26
|
const TURNS_KEPT = 50
|
|
27
27
|
/** A closed issue's record is kept this long, so one that comes back unchanged is not mistaken for a new issue. */
|
|
28
28
|
const GONE_MS = 30 * 24 * 3_600_000
|
|
29
|
-
const LOCK_STALE_MS = 15 * 60_000
|
|
30
29
|
const MAX_TITLES = 20
|
|
31
30
|
const PAGE = 100
|
|
31
|
+
const EDIT_FIELDS = "totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } nodes { id editedAt deletedAt editor { __typename login } }"
|
|
32
|
+
const EDITS_FORWARD = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { rateLimit { cost } repository(owner: $owner, name: $name) { issue(number: $number) { updatedAt userContentEdits(first: 100, after: $cursor) { ${EDIT_FIELDS} } } } }`
|
|
33
|
+
const EDITS_BACKWARD = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { rateLimit { cost } repository(owner: $owner, name: $name) { issue(number: $number) { updatedAt userContentEdits(last: 100, before: $cursor) { ${EDIT_FIELDS} } } } }`
|
|
32
34
|
/** A full listing of the open issues is read again this often; between them only issues updated since the last change are read. */
|
|
33
35
|
const FULL_SYNC_MS = 3_600_000
|
|
34
36
|
/** The list is read from a little before the newest change it knew, so an update GitHub lists late is still seen. */
|
|
@@ -225,38 +227,207 @@ function writeDrainStates(file, states) {
|
|
|
225
227
|
renameSync(temporary, file)
|
|
226
228
|
}
|
|
227
229
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
230
|
+
const OWNER_FILE = /^owner-[0-9a-f-]{36}$/u
|
|
231
|
+
const busy = (lockFile, who) => problem("desk_drains_busy", "drains lock", `${who} holds ${lockFile} and is still working`, `check that process; it releases the lock itself when it finishes, and a lock whose process has died is taken over by the next run`, "run the command again once it finishes")
|
|
232
|
+
const lockProblem = (code, lockFile, probably, look, fix) => problem(code, "drains lock", probably, look, fix)
|
|
233
|
+
const unavailable = (lockFile, error) => lockProblem("desk_drains_lock_unavailable", lockFile, `${lockFile} cannot be created or read because of ${error.code ?? error.message}`, `the permissions and free space of ${path.dirname(lockFile)}, and the error code ${error.code ?? "unknown"}`, "fix that, then run the command again")
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Takes the lock, or throws. The lock is a directory that is published whole: a sibling `<lock>.new-<pid>-<token>` is filled with
|
|
237
|
+
* the one file `owner-<token>` (this process's id) and then renamed onto the lock, which succeeds only where the lock is absent or
|
|
238
|
+
* an empty directory. So the lock is never visible empty or half-written, and a live owner is never taken from, however long it
|
|
239
|
+
* works. A dead owner is retired by removing its own `owner-<token>` file, a name no later owner reuses, so a contender holding a
|
|
240
|
+
* stale view finds nothing to remove (ENOENT) instead of a newer owner's lock; the empty directory is then removed with `rmdir`,
|
|
241
|
+
* which refuses a directory that has become someone's. Nothing is aged out, renamed away or removed recursively. An earlier Desk's
|
|
242
|
+
* lock is a plain file: it is never replaced, because replacing it by name cannot be made safe against that Desk's own takeover.
|
|
243
|
+
* `onStep` is a test seam called at "staging" (the sibling exists, the owner file is not written), "staged" and "inspected".
|
|
244
|
+
*/
|
|
245
|
+
export function acquireDrainLock(lockFile, { alive = processAlive, onStep = () => {}, rename = publishDirectory } = {}) {
|
|
246
|
+
const dir = path.dirname(lockFile)
|
|
247
|
+
const base = path.basename(lockFile)
|
|
248
|
+
sweepStaging(dir, base, alive)
|
|
249
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
250
|
+
const token = randomUUID()
|
|
251
|
+
const staging = path.join(dir, `${base}.new-${process.pid}-${token}`)
|
|
252
|
+
const owner = path.join(staging, `owner-${token}`)
|
|
253
|
+
let renamed = false
|
|
254
|
+
try {
|
|
255
|
+
try {
|
|
256
|
+
mkdirSync(staging)
|
|
257
|
+
onStep("staging")
|
|
258
|
+
writeFileSync(owner, `${process.pid}\n`)
|
|
259
|
+
onStep("staged")
|
|
260
|
+
} catch (error) {
|
|
261
|
+
throw unavailable(lockFile, error)
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
rename(staging, lockFile)
|
|
265
|
+
renamed = true
|
|
266
|
+
} catch (error) {
|
|
267
|
+
// Platforms name an occupied target differently (POSIX ENOTEMPTY, ENOTDIR, EEXIST; Windows EPERM), so the error code is not
|
|
268
|
+
// trusted: the target itself is inspected next. Only a rename that failed with nothing in the way is a failure to use the lock.
|
|
269
|
+
// A move that was cut short (Windows, a timeout) may still have happened. It is ours only if the lock is a directory holding this
|
|
270
|
+
// acquisition's own `owner-<token>` (a name nothing else uses); any other target, live or legacy, is left alone.
|
|
271
|
+
if (!existsAt(staging) && holdsOwner(lockFile, `owner-${token}`)) renamed = true
|
|
272
|
+
else if (!existsAt(lockFile)) throw unavailable(lockFile, error)
|
|
273
|
+
}
|
|
274
|
+
} finally {
|
|
275
|
+
if (!renamed) removeStaging(staging)
|
|
276
|
+
}
|
|
277
|
+
if (renamed) return () => releaseDrainLock(lockFile, `owner-${token}`)
|
|
278
|
+
retireDeadOwner(lockFile, alive, onStep)
|
|
279
|
+
}
|
|
280
|
+
throw busy(lockFile, "another poll, which started while this one looked,")
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The one step that must never replace what is at the lock: POSIX `rename` refuses all but an absent or empty directory, but Windows' replaces a plain file. */
|
|
284
|
+
function publishDirectory(from, to) {
|
|
285
|
+
// Only Windows runs the first branch; the native Windows suite (desk-windows-suite.yml) exercises it, a Linux or macOS run cannot.
|
|
286
|
+
/* istanbul ignore if */
|
|
287
|
+
if (process.platform === "win32") moveWithoutReplace(from, to, { shells: ["pwsh", "powershell"] })
|
|
288
|
+
else renameSync(from, to)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Fixed script, paths as data (environment), never interpolated. Directory.Move ends in MoveFileExW without MOVEFILE_REPLACE_EXISTING
|
|
292
|
+
// (dotnet/runtime, Interop.MoveFileEx.cs and FileSystem.Windows.cs: MoveFile(..., overwrite: false)), so an existing target is refused
|
|
293
|
+
// by the system, not by a check made first. Windows PowerShell 5.1 runs .NET Framework, whose Directory.InternalMove makes no existence
|
|
294
|
+
// check either: it validates paths and the shared root, then calls Win32Native.MoveFile, i.e. MoveFileEx(src, dst, 2 /* MOVEFILE_COPY_ALLOWED */)
|
|
295
|
+
// or MoveFileW, neither of which replaces (microsoft/referencesource@ec9fa9ae770d, mscorlib/system/io/directory.cs InternalMove and
|
|
296
|
+
// mscorlib/microsoft/win32/win32native.cs MoveFile). The native per-shell target tests are evidence, not a proof of every interleaving. Exit 3 means "refused", with the outer exception, and its inner one if any, named on stderr.
|
|
297
|
+
const MOVE_SCRIPT = "try { [System.IO.Directory]::Move($env:DESK_MOVE_FROM, $env:DESK_MOVE_TO) } catch { $e = $_.Exception; $i = $e.InnerException; [Console]::Error.Write('refused ' + $e.GetType().Name + ' ' + $e.HResult + $(if ($i) { ' inner ' + $i.GetType().Name + ' ' + $i.HResult } else { ' no-inner' })); exit 3 }"
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Moves a directory to a path that must not exist, failing (and changing nothing) if anything is there. The next shell is tried only
|
|
301
|
+
* when the first cannot be launched at all; a move that ran, was refused or timed out is never retried and never falls back to `rename`.
|
|
302
|
+
*/
|
|
303
|
+
export function moveWithoutReplace(from, to, { shells, timeoutMs = TOKEN_MS }) {
|
|
304
|
+
for (const shell of shells) {
|
|
305
|
+
const result = spawnSync(shell, ["-NoProfile", "-NonInteractive", "-Command", MOVE_SCRIPT], { env: { ...process.env, DESK_MOVE_FROM: from, DESK_MOVE_TO: to }, encoding: "utf8", timeout: timeoutMs, windowsHide: true })
|
|
306
|
+
if (result.error?.code === "ENOENT") continue
|
|
307
|
+
if (result.error) throw Object.assign(new Error(`${shell}: ${result.error.message}`), { code: result.error.code })
|
|
308
|
+
if (result.status === 0) return
|
|
309
|
+
throw Object.assign(new Error(`Run the command again once what is at the lock is dealt with: ${shell} did not move it (exit ${result.status}): ${String(result.stderr).trim() || "no message"}`), { code: "desk_move_refused" })
|
|
310
|
+
}
|
|
311
|
+
throw Object.assign(new Error(`Install PowerShell (pwsh) or put powershell on PATH: none of ${shells.join(", ")} could be started`), { code: "desk_move_no_shell" })
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function holdsOwner(lockFile, ownerName) {
|
|
315
|
+
try {
|
|
316
|
+
return lstatSync(lockFile).isDirectory() && lstatSync(path.join(lockFile, ownerName)).isFile()
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return false
|
|
319
|
+
throw unavailable(lockFile, error)
|
|
320
|
+
}
|
|
231
321
|
}
|
|
232
322
|
|
|
233
|
-
function
|
|
323
|
+
function existsAt(target) {
|
|
234
324
|
try {
|
|
235
|
-
|
|
325
|
+
lstatSync(target)
|
|
326
|
+
return true
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (error.code === "ENOENT") return false
|
|
329
|
+
throw unavailable(target, error)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function legacyLock(lockFile) {
|
|
334
|
+
let pid = "an unknown process"
|
|
335
|
+
try {
|
|
336
|
+
pid = `process ${Number.parseInt(readFileSync(lockFile, "utf8"), 10)}`
|
|
236
337
|
} catch {
|
|
237
|
-
|
|
338
|
+
// A file that cannot be read is named by its path alone.
|
|
238
339
|
}
|
|
340
|
+
return lockProblem("desk_drains_lock_legacy", lockFile, `${lockFile} is a file, the lock of an earlier Desk, and Desk cannot tell whether a poll still holds it (it names ${pid})`, `whether ${pid}, or any drains poll or ack started by an earlier Desk, is still running`, `once none is, remove ${lockFile} yourself and run the command again; Desk never replaces it, because that could take the lock from a poll that is still working`)
|
|
239
341
|
}
|
|
240
342
|
|
|
241
|
-
|
|
242
|
-
export async function withDrainLock(lockFile, work, { now = Date.now(), alive = processAlive } = {}) {
|
|
243
|
-
assertNotRealStateUnderTest(path.dirname(lockFile))
|
|
244
|
-
mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
343
|
+
function removeStaging(staging) {
|
|
245
344
|
try {
|
|
246
|
-
|
|
345
|
+
for (const name of readdirSync(staging)) if (OWNER_FILE.test(name)) unlinkSync(path.join(staging, name))
|
|
346
|
+
rmdirSync(staging)
|
|
247
347
|
} catch (error) {
|
|
248
|
-
if (error.code
|
|
249
|
-
const owner = lockOwner(lockFile, now)
|
|
250
|
-
if (owner && owner.ageMs <= LOCK_STALE_MS && alive(owner.pid)) {
|
|
251
|
-
throw problem("desk_drains_busy", "drains lock", `process ${owner.pid} holds ${lockFile} and is still working`, `check that process, then look at ${lockFile}`, "run the command again once it finishes")
|
|
252
|
-
}
|
|
253
|
-
rmSync(lockFile, { force: true })
|
|
254
|
-
create(lockFile)
|
|
348
|
+
if (!["ENOENT", "ENOTEMPTY"].includes(error.code)) throw unavailable(staging, error)
|
|
255
349
|
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** A staging directory is never shared, so one whose creating process has died is a crash leftover and is removed by its exact name. */
|
|
353
|
+
function sweepStaging(dir, base, alive) {
|
|
354
|
+
let names
|
|
355
|
+
try {
|
|
356
|
+
names = readdirSync(dir)
|
|
357
|
+
} catch (error) {
|
|
358
|
+
if (error.code === "ENOENT") return
|
|
359
|
+
throw unavailable(path.join(dir, base), error)
|
|
360
|
+
}
|
|
361
|
+
for (const name of names) {
|
|
362
|
+
const match = name.startsWith(`${base}.new-`) ? /^(\d+)-[0-9a-f-]{36}$/u.exec(name.slice(base.length + 5)) : null
|
|
363
|
+
if (match && !alive(Number(match[1]))) removeStaging(path.join(dir, name))
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function retireDeadOwner(lockFile, alive, onStep) {
|
|
368
|
+
let names = null
|
|
369
|
+
try {
|
|
370
|
+
if (lstatSync(lockFile).isDirectory()) names = readdirSync(lockFile)
|
|
371
|
+
} catch (error) {
|
|
372
|
+
// A lock that vanished since the publish failed belongs to someone who just released it: the next attempt publishes.
|
|
373
|
+
/* istanbul ignore if -- a race with another process's release */
|
|
374
|
+
if (error.code === "ENOENT") return
|
|
375
|
+
throw unavailable(lockFile, error)
|
|
376
|
+
}
|
|
377
|
+
if (names === null) throw legacyLock(lockFile)
|
|
378
|
+
if (names.length === 0) return removeEmptyLock(lockFile)
|
|
379
|
+
if (names.length !== 1 || !OWNER_FILE.test(names[0])) {
|
|
380
|
+
throw lockProblem("desk_drains_lock_unrecognized", lockFile, `${lockFile} holds ${names.slice(0, 5).join(", ")}, which is not one owner file of this Desk's lock`, `${lockFile}, and whether another tool or a newer Desk made it`, "leave it, or ask its owner; Desk removes nothing it did not make")
|
|
381
|
+
}
|
|
382
|
+
let pid
|
|
383
|
+
try {
|
|
384
|
+
pid = Number.parseInt(readFileSync(path.join(lockFile, names[0]), "utf8"), 10)
|
|
385
|
+
} catch (error) {
|
|
386
|
+
/* istanbul ignore if -- a race with another process's release */
|
|
387
|
+
if (error.code === "ENOENT") return
|
|
388
|
+
throw unavailable(lockFile, error)
|
|
389
|
+
}
|
|
390
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
391
|
+
throw lockProblem("desk_drains_lock_unrecognized", lockFile, `${path.join(lockFile, names[0])} does not name a process`, `${lockFile}, and whether another tool or a newer Desk made it`, "leave it, or ask its owner; Desk removes nothing it did not make")
|
|
392
|
+
}
|
|
393
|
+
if (alive(pid)) throw busy(lockFile, `process ${pid}`)
|
|
394
|
+
onStep("inspected")
|
|
395
|
+
try {
|
|
396
|
+
unlinkSync(path.join(lockFile, names[0]))
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (error.code !== "ENOENT") throw unavailable(lockFile, error)
|
|
399
|
+
}
|
|
400
|
+
removeEmptyLock(lockFile)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** `rmdir` fails on a directory that has an owner, so it cannot remove a lock published after it was looked at. */
|
|
404
|
+
function removeEmptyLock(lockFile) {
|
|
405
|
+
try {
|
|
406
|
+
rmdirSync(lockFile)
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw unavailable(lockFile, error)
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Removes only this run's own owner file, so a lock that has since passed to another owner is left alone. */
|
|
413
|
+
function releaseDrainLock(lockFile, ownerName) {
|
|
414
|
+
try {
|
|
415
|
+
unlinkSync(path.join(lockFile, ownerName))
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error.code !== "ENOENT") throw unavailable(lockFile, error)
|
|
418
|
+
}
|
|
419
|
+
removeEmptyLock(lockFile)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Runs `work`, which may be async, while this process holds the lock (see acquireDrainLock). Only this run's owner file is removed afterwards. */
|
|
423
|
+
export async function withDrainLock(lockFile, work, { alive = processAlive, onStep } = {}) {
|
|
424
|
+
assertNotRealStateUnderTest(path.dirname(lockFile))
|
|
425
|
+
mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
426
|
+
const release = acquireDrainLock(lockFile, { alive, onStep })
|
|
256
427
|
try {
|
|
257
428
|
return await work()
|
|
258
429
|
} finally {
|
|
259
|
-
|
|
430
|
+
release()
|
|
260
431
|
}
|
|
261
432
|
}
|
|
262
433
|
|
|
@@ -307,6 +478,162 @@ const ownStatus = (comment, login) => comment.user?.login?.toLowerCase() === log
|
|
|
307
478
|
const ignoredComment = (comment, rules) => rules.some((rule) => comment.user?.login?.toLowerCase() === rule.author && (rule.match === null || rule.match.test(comment.body ?? "")))
|
|
308
479
|
|
|
309
480
|
const isBot = (item) => item.user?.type === "Bot" || (item.user?.login ?? "").toLowerCase().endsWith("[bot]")
|
|
481
|
+
const isBotActor = (actor) => actor?.type === "Bot" || (actor?.login ?? "").toLowerCase().endsWith("[bot]")
|
|
482
|
+
|
|
483
|
+
// ── Who edited an issue's body ──
|
|
484
|
+
//
|
|
485
|
+
// An issue whose body changed is news unless every edit made since it was last recorded was a bot's. The proof reads the issue's
|
|
486
|
+
// edit history one GraphQL page at a time, and the progress is kept in `state.scans[number]`, so a history of any length is read
|
|
487
|
+
// across polls and quota windows without starting over. No order of the history is assumed. What is counted instead:
|
|
488
|
+
// - `base`: how many edits were already judged when the issue was last recorded (null when that is not known: the first pass
|
|
489
|
+
// then counts the edits older than `floor` as it reads forward, and knows `base` once it reaches the end);
|
|
490
|
+
// - an edit is new when it is not older than `floor` and is not one of the `tail` ids already judged at that second;
|
|
491
|
+
// - `total` is read from every page, so the new edits still to find are `total - base`, wherever they sit and however many more
|
|
492
|
+
// arrive while the scan runs (an edit that arrives behind the cursor makes `total` grow, and the scan reads on until it has found them).
|
|
493
|
+
// The scan stops at once on an edit that is not a bot's (or has no editor, no id, no time, or is deleted): that is news.
|
|
494
|
+
|
|
495
|
+
const pagesFor = (total) => Math.ceil(total / PAGE) + 1
|
|
496
|
+
const emptySide = () => ({ cursor: null, pages: 0, done: false })
|
|
497
|
+
|
|
498
|
+
function newScan(before) {
|
|
499
|
+
const edits = before.edits
|
|
500
|
+
return { of: before.updatedAt, floor: edits?.at ?? before.updatedAt, base: edits ? edits.total : null, tail: edits ? [...edits.tail] : [], old: 0, found: {}, total: 0, passTotal: null, fwd: emptySide(), bwd: emptySide(), next: "fwd", stamp: null, served: 0 }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const restartPass = (scan) => Object.assign(scan, { fwd: emptySide(), bwd: emptySide(), passTotal: scan.total, old: 0, next: "fwd" })
|
|
504
|
+
|
|
505
|
+
const isNewEdit = (scan, edit) => !(Date.parse(edit.editedAt) < Date.parse(scan.floor)) && !scan.tail.includes(edit.id)
|
|
506
|
+
|
|
507
|
+
const botEdit = (edit) => typeof edit.id === "string" && Number.isFinite(Date.parse(edit.editedAt)) && !edit.deletedAt && Boolean(edit.editor) && isBotActor(edit.editor)
|
|
508
|
+
|
|
509
|
+
/** What a finished scan leaves on the issue's record: how many edits are now judged, when the newest was made and which ones were made then. */
|
|
510
|
+
function baselineOf(scan) {
|
|
511
|
+
const at = Object.values(scan.found).reduce((top, editedAt) => (Date.parse(editedAt) > Date.parse(top) ? editedAt : top))
|
|
512
|
+
const same = (editedAt) => Date.parse(editedAt) === Date.parse(at)
|
|
513
|
+
return { total: scan.total, at, tail: [...(same(scan.floor) ? scan.tail : []), ...Object.entries(scan.found).filter(([, editedAt]) => same(editedAt)).map(([id]) => id)] }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const NEWS = { kind: "news" }
|
|
517
|
+
|
|
518
|
+
const validPage = (page) => Array.isArray(page.edits) && Number.isInteger(page.total) && typeof page.updatedAt === "string" && typeof page.hasMore === "boolean"
|
|
519
|
+
|
|
520
|
+
/** What the pages read so far settle: the issue's new edits are all found (a bot-only proof, once a page is as fresh as the issue), not all found yet (null), or cannot be explained (news). */
|
|
521
|
+
function conclude(scan, issue) {
|
|
522
|
+
const found = Object.keys(scan.found).length
|
|
523
|
+
const exhausted = scan.base === null ? scan.fwd.done : scan.fwd.done || scan.bwd.done
|
|
524
|
+
const expected = scan.total - (scan.base ?? scan.old)
|
|
525
|
+
if (found === expected && (scan.base !== null || exhausted)) {
|
|
526
|
+
if (found === 0) return NEWS
|
|
527
|
+
if (Date.parse(scan.stamp) < Date.parse(issue.updated_at)) {
|
|
528
|
+
scan.base ??= scan.old
|
|
529
|
+
scan.lag = true
|
|
530
|
+
return { kind: "deferred", message: "Wait for the next poll: GitHub's edit history is behind the issue and is read again then", code: "drains_edit_history_behind" }
|
|
531
|
+
}
|
|
532
|
+
return { kind: "bot", baseline: baselineOf(scan) }
|
|
533
|
+
}
|
|
534
|
+
if (found > expected && scan.base !== null) return NEWS
|
|
535
|
+
if (exhausted) {
|
|
536
|
+
// Edits that arrived while the history was being read make `total` grow past the pass, and another pass finds them. When nothing new arrived the count cannot be explained.
|
|
537
|
+
if (scan.total <= scan.passTotal || found + (scan.base === null ? scan.old : 0) > scan.total) return NEWS
|
|
538
|
+
scan.base ??= scan.old
|
|
539
|
+
restartPass(scan)
|
|
540
|
+
}
|
|
541
|
+
return null
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** Reads one page of the scan and says what it settled, or null when it is not settled yet: news, a bot-only proof with the record it leaves, or waiting for GitHub's history to catch up with the issue. */
|
|
545
|
+
async function advance(api, repo, issue, scan) {
|
|
546
|
+
if (!Number.isFinite(Date.parse(scan.floor)) || typeof api.editPage !== "function") return NEWS
|
|
547
|
+
if (scan.lag) {
|
|
548
|
+
// The history was behind the issue: the first page, read again, tells whether it has caught up and whether more edits arrived.
|
|
549
|
+
const page = await api.editPage(repo, issue.number, { backward: false, cursor: null })
|
|
550
|
+
if (!page || !validPage(page)) return NEWS
|
|
551
|
+
scan.total = page.total
|
|
552
|
+
scan.stamp = page.updatedAt
|
|
553
|
+
if (Date.parse(scan.stamp) < Date.parse(issue.updated_at)) return { kind: "deferred", message: "Wait for the next poll: GitHub's edit history is behind the issue and is read again then", code: "drains_edit_history_behind" }
|
|
554
|
+
scan.lag = false
|
|
555
|
+
return conclude(scan, issue)
|
|
556
|
+
}
|
|
557
|
+
let direction = scan.base !== null && scan.next === "bwd" ? "bwd" : "fwd"
|
|
558
|
+
// A finished side ends the pass in `conclude`, which either settles it or restarts both sides, so this only guards a state no page can produce.
|
|
559
|
+
/* istanbul ignore if */
|
|
560
|
+
if (scan[direction].done) direction = direction === "fwd" ? "bwd" : "fwd"
|
|
561
|
+
const side = scan[direction]
|
|
562
|
+
const page = await api.editPage(repo, issue.number, { backward: direction === "bwd", cursor: side.cursor })
|
|
563
|
+
if (!page || !validPage(page)) return NEWS
|
|
564
|
+
scan.total = page.total
|
|
565
|
+
scan.stamp = page.updatedAt
|
|
566
|
+
scan.passTotal ??= page.total
|
|
567
|
+
side.pages += 1
|
|
568
|
+
scan.next = direction === "fwd" ? "bwd" : "fwd"
|
|
569
|
+
for (const edit of page.edits) {
|
|
570
|
+
if (!edit || typeof edit !== "object") return NEWS
|
|
571
|
+
if (!isNewEdit(scan, edit)) {
|
|
572
|
+
if (scan.base === null) scan.old += 1
|
|
573
|
+
continue
|
|
574
|
+
}
|
|
575
|
+
if (!botEdit(edit)) return NEWS
|
|
576
|
+
scan.found[edit.id] = edit.editedAt
|
|
577
|
+
}
|
|
578
|
+
if (page.hasMore) {
|
|
579
|
+
// A cursor that does not move, or more pages than the history can hold, is a cycle: it would never end.
|
|
580
|
+
if (typeof page.cursor !== "string" || page.cursor === side.cursor || side.pages >= pagesFor(scan.total)) return NEWS
|
|
581
|
+
side.cursor = page.cursor
|
|
582
|
+
} else {
|
|
583
|
+
side.done = true
|
|
584
|
+
}
|
|
585
|
+
return conclude(scan, issue)
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Whether the GraphQL quota allows another page now: the same reserve as REST's, read from the connection's own headers, else from the last poll's reading while its window is open. */
|
|
589
|
+
function canSpend(api, state, now) {
|
|
590
|
+
const quota = api.graphqlQuota?.() ?? state.graphqlQuota
|
|
591
|
+
if (!quota || now >= quota.reset * 1000) return true
|
|
592
|
+
return quota.remaining - (api.graphqlCost?.() ?? 1) > QUOTA_RESERVE
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Settles, for the issues whose body changed, whether bots alone made the edits. Every open scan gets one page per round, the one
|
|
597
|
+
* served longest ago first (`served` is kept with the scan), so scans that outnumber the pages the quota allows still take turns,
|
|
598
|
+
* and an issue with a short history is settled in the first round. A scan that cannot go on keeps its progress and is deferred,
|
|
599
|
+
* never settled by a guess.
|
|
600
|
+
*/
|
|
601
|
+
async function attribute(api, repo, state, needs, now) {
|
|
602
|
+
const verdicts = new Map()
|
|
603
|
+
const scans = state.scans ?? (state.scans = {})
|
|
604
|
+
const wanted = new Set(needs.map(({ issue }) => String(issue.number)))
|
|
605
|
+
for (const key of Object.keys(scans)) if (!wanted.has(key)) delete scans[key]
|
|
606
|
+
const pending = new Set()
|
|
607
|
+
for (const { issue, before } of needs) {
|
|
608
|
+
const key = String(issue.number)
|
|
609
|
+
if (scans[key]?.of !== before.updatedAt) scans[key] = newScan(before)
|
|
610
|
+
pending.add({ issue, key, scan: scans[key] })
|
|
611
|
+
}
|
|
612
|
+
let halted = null
|
|
613
|
+
while (pending.size > 0 && !halted) {
|
|
614
|
+
for (const item of [...pending].sort((a, b) => a.scan.served - b.scan.served || a.issue.number - b.issue.number)) {
|
|
615
|
+
if (!canSpend(api, state, now)) {
|
|
616
|
+
const quota = api.graphqlQuota?.() ?? state.graphqlQuota
|
|
617
|
+
halted = { message: `Wait for the quota to reset: GitHub's GraphQL limit leaves ${quota.remaining}/${quota.limit} calls until ${new Date(quota.reset * 1000).toISOString()}`, code: "drains_rate_limited" }
|
|
618
|
+
break
|
|
619
|
+
}
|
|
620
|
+
item.scan.served = state.scanTurn = (state.scanTurn ?? 0) + 1
|
|
621
|
+
try {
|
|
622
|
+
const verdict = await advance(api, repo, item.issue, item.scan)
|
|
623
|
+
if (!verdict) continue
|
|
624
|
+
verdicts.set(item.issue.number, verdict)
|
|
625
|
+
pending.delete(item)
|
|
626
|
+
if (verdict.kind !== "deferred") delete scans[item.key]
|
|
627
|
+
} catch (error) {
|
|
628
|
+
pending.delete(item)
|
|
629
|
+
verdicts.set(item.issue.number, { kind: "deferred", message: error.message, code: error.code })
|
|
630
|
+
if (error.code === "drains_rate_limited") halted = { message: error.message, code: error.code }
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
for (const item of pending) verdicts.set(item.issue.number, { kind: "deferred", ...halted })
|
|
635
|
+
return verdicts
|
|
636
|
+
}
|
|
310
637
|
|
|
311
638
|
/** A bot comment's text without what changes from run to run: run URLs and IDs, dates, times and durations. */
|
|
312
639
|
function repeatableText(body) {
|
|
@@ -338,12 +665,16 @@ const duringTurn = (event, login, turns) => {
|
|
|
338
665
|
return event.actor?.login?.toLowerCase() === login.toLowerCase() && turns.some((from) => at >= from - TURN_LEAD_MS && at <= from + TURN_MS)
|
|
339
666
|
}
|
|
340
667
|
|
|
341
|
-
/** What made a reopen or a label change news, or null: a label outside the drain's namespace, ignored list and ignored patterns,
|
|
668
|
+
/** What made a reopen or a label change news, or null: a label outside the drain's namespace, ignored list and ignored patterns, a reopen that is not the drain claiming the issue, or an assignment change (assigned or unassigned) outside the drain's turn (its own `drain:` label change within a minute). A label or assignee applied within a minute of the issue being opened was part of filing it, and the "new issue" wake shows it. A label, reopen or assignment change by the polling account during the drain's turn is its own work. Closes and mentions are not news. */
|
|
342
669
|
function newsEvent(event, rules, claims, login, openedAt) {
|
|
343
670
|
if (event.event === "reopened") {
|
|
344
671
|
const own = event.actor?.login?.toLowerCase() === login.toLowerCase() && claims.some((claim) => claim.actor?.login?.toLowerCase() === login.toLowerCase() && Math.abs(Date.parse(claim.created_at) - Date.parse(event.created_at)) <= CLAIM_SLACK_MS)
|
|
345
672
|
return own || duringTurn(event, login, rules.turns) ? null : "reopened"
|
|
346
673
|
}
|
|
674
|
+
if (event.event === "assigned" || event.event === "unassigned") {
|
|
675
|
+
if (event.event === "assigned" && Date.parse(event.created_at) <= openedAt + OPENING_LABEL_MS) return null
|
|
676
|
+
return duringTurn(event, login, rules.turns) ? null : `${event.event} ${event.assignee?.login ?? "nobody"}`
|
|
677
|
+
}
|
|
347
678
|
if (event.event !== "labeled" && event.event !== "unlabeled") return null
|
|
348
679
|
if (event.event === "labeled" && Date.parse(event.created_at) <= openedAt + OPENING_LABEL_MS) return null
|
|
349
680
|
const name = (event.label?.name ?? "").toLowerCase()
|
|
@@ -354,10 +685,10 @@ function newsEvent(event, rules, claims, login, openedAt) {
|
|
|
354
685
|
/** An issue the drain filed or already triaged: a label in its `drain:` namespace, or its status marker in the body, is there before the poll first sees it, so it is already seen. */
|
|
355
686
|
const filedByDrain = (issue) => (issue.labels ?? []).some((label) => (label?.name ?? "").toLowerCase().startsWith(DRAIN_LABEL_PREFIX)) || (issue.body ?? "").includes(DRAIN_STATUS_MARKER)
|
|
356
687
|
|
|
357
|
-
/** What someone but the drain changed since `before` (a new issue,
|
|
358
|
-
async function changedByOthers(api, repo, issue, before, digest, ignored, rules) {
|
|
688
|
+
/** What someone but the drain changed since `before` (a new issue, a title or body edit (an edit that only bots made to the body, such as a health table's refresh, is not news), an edit, another comment, a reopen or a label outside the drain's own), or null. The reason travels with the event. */
|
|
689
|
+
async function changedByOthers(api, repo, issue, before, digest, ignored, rules, edited) {
|
|
359
690
|
if (!before) return filedByDrain(issue) ? null : "new issue"
|
|
360
|
-
if (
|
|
691
|
+
if (edited) return edited
|
|
361
692
|
const since = before.updatedAt
|
|
362
693
|
const comments = (await api.comments(repo, issue.number, since)).filter((comment) => comment.updated_at > since)
|
|
363
694
|
const all = {}
|
|
@@ -415,8 +746,7 @@ async function listIssues(api, drain, state, now) {
|
|
|
415
746
|
const since = isoSeconds(Date.parse(state.cursor) - DELTA_SLACK_MS)
|
|
416
747
|
const changed = await api.changedIssues(drain.repo, since, state.etag?.since === since ? state.etag.tag : undefined)
|
|
417
748
|
if (changed.notModified) return { full: false, issues: [], untouched: true }
|
|
418
|
-
|
|
419
|
-
return { full: false, issues: changed.issues }
|
|
749
|
+
return { full: false, issues: changed.issues, etag: changed.etag ? { since, tag: changed.etag } : undefined, newEtag: true }
|
|
420
750
|
}
|
|
421
751
|
|
|
422
752
|
/** What the account's quota says to do about this drain now: null to poll, or why not (until the window resets, or for a while). */
|
|
@@ -433,6 +763,7 @@ export function quotaHold(quota, lastPollAt, now) {
|
|
|
433
763
|
export async function pollDrain(drain, states, { connect, now, desk }) {
|
|
434
764
|
const state = states[drain.repo] ?? (states[drain.repo] = blank())
|
|
435
765
|
let api = null
|
|
766
|
+
let left = null
|
|
436
767
|
try {
|
|
437
768
|
const knownLogin = state.loginAt && now - Date.parse(state.loginAt) < LOGIN_MS ? state.login : undefined
|
|
438
769
|
api = await connect(drain.account, { login: knownLogin })
|
|
@@ -441,10 +772,25 @@ export async function pollDrain(drain, states, { connect, now, desk }) {
|
|
|
441
772
|
state.loginAt = new Date(now).toISOString()
|
|
442
773
|
}
|
|
443
774
|
const listed = await listIssues(api, drain, state, now)
|
|
444
|
-
if (!listed.untouched)
|
|
775
|
+
if (!listed.untouched) {
|
|
776
|
+
const { deferred } = await recordChanges(api, drain, state, listed, { now, desk })
|
|
777
|
+
// The tag of the list is kept only once every change in it is recorded: a failed poll, or an issue left for the next one, asks for the same list again, never a 304 for it.
|
|
778
|
+
if (deferred.length > 0) delete state.etag
|
|
779
|
+
else if (listed.newEtag) state.etag = listed.etag
|
|
780
|
+
if (deferred.length > 0) {
|
|
781
|
+
const shown = deferred.slice(0, 3).map((item) => `#${item.number} (${item.message})`).join(", ")
|
|
782
|
+
left = { message: `Wait for the next poll: ${deferred.length} issue(s) were left for it: ${shown}${deferred.length > 3 ? ", …" : ""}`, code: "drains_issues_deferred" }
|
|
783
|
+
const specific = deferred.find((item) => item.code)?.code
|
|
784
|
+
if (specific) left.code = specific
|
|
785
|
+
}
|
|
786
|
+
}
|
|
445
787
|
state.lastOkAt = new Date(now).toISOString()
|
|
446
788
|
delete state.lastError
|
|
447
789
|
delete state.lastErrorCode
|
|
790
|
+
if (left) {
|
|
791
|
+
state.lastError = left.message
|
|
792
|
+
state.lastErrorCode = left.code
|
|
793
|
+
}
|
|
448
794
|
} catch (error) {
|
|
449
795
|
state.lastError = error.message
|
|
450
796
|
if (typeof error.code === "string") state.lastErrorCode = error.code
|
|
@@ -452,6 +798,8 @@ export async function pollDrain(drain, states, { connect, now, desk }) {
|
|
|
452
798
|
}
|
|
453
799
|
const quota = api?.quota?.()
|
|
454
800
|
if (quota) state.quota = quota
|
|
801
|
+
const graphqlQuota = api?.graphqlQuota?.()
|
|
802
|
+
if (graphqlQuota) state.graphqlQuota = graphqlQuota
|
|
455
803
|
state.calls = api?.calls?.() ?? { total: 0, notModified: 0 }
|
|
456
804
|
delete state.hold
|
|
457
805
|
state.lastPollAt = new Date(now).toISOString()
|
|
@@ -466,6 +814,9 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
|
|
|
466
814
|
const seen = full ? {} : { ...state.seen }
|
|
467
815
|
const recorded = []
|
|
468
816
|
const closed = new Set()
|
|
817
|
+
const todo = []
|
|
818
|
+
const deferred = []
|
|
819
|
+
let held = null
|
|
469
820
|
let cursor = state.cursor ?? ""
|
|
470
821
|
for (const issue of issues) {
|
|
471
822
|
if (!full && issue.updated_at > cursor) cursor = issue.updated_at
|
|
@@ -479,10 +830,31 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
|
|
|
479
830
|
}
|
|
480
831
|
if (full && issue.updated_at > cursor) cursor = issue.updated_at
|
|
481
832
|
const digest = digestOf(issue, trailers)
|
|
482
|
-
seen[key] = { updatedAt: issue.updated_at, digest, ...(ignored ? { ignored } : {}) }
|
|
833
|
+
seen[key] = { updatedAt: issue.updated_at, digest, title: issue.title, ...(ignored ? { ignored } : {}), ...(before?.edits && before.digest === digest ? { edits: before.edits } : {}) }
|
|
483
834
|
if (!state.seeded || before?.updatedAt === issue.updated_at) continue
|
|
484
|
-
|
|
485
|
-
|
|
835
|
+
// A body that changed is news unless bots alone edited it, whoever created the issue.
|
|
836
|
+
const bodyChanged = Boolean(before?.digest) && (before.ignored ?? "") === ignored && before.digest !== digest
|
|
837
|
+
// A record from before titles were kept cannot show the title is unchanged, so its first changed poll is news as it always was.
|
|
838
|
+
const edited = bodyChanged && before.title !== issue.title ? "title or body edited" : null
|
|
839
|
+
todo.push({ issue, key, before, digest, edited, scan: bodyChanged && !edited })
|
|
840
|
+
}
|
|
841
|
+
const verdicts = await attribute(api, drain.repo, state, todo.filter((item) => item.scan), now)
|
|
842
|
+
for (const item of todo) {
|
|
843
|
+
const { issue, key, before, digest } = item
|
|
844
|
+
const verdict = verdicts.get(issue.number)
|
|
845
|
+
try {
|
|
846
|
+
if (verdict?.kind === "deferred") throw Object.assign(new Error(verdict.message), { code: verdict.code })
|
|
847
|
+
if (verdict?.kind === "news") item.edited = "title or body edited"
|
|
848
|
+
const why = await changedByOthers(api, drain.repo, issue, before, digest, ignored, rules, item.edited)
|
|
849
|
+
if (verdict?.kind === "bot") seen[key].edits = verdict.baseline
|
|
850
|
+
if (why) recorded.push({ number: issue.number, title: issue.title, updatedAt: issue.updated_at, seenAt: new Date(now).toISOString(), why })
|
|
851
|
+
} catch (error) {
|
|
852
|
+
// This issue's marker stays where it was, so the next poll judges the same change again; the others go on.
|
|
853
|
+
// Only an issue that was seen before can fail here (a new one is judged without a read), so there is always a marker to restore.
|
|
854
|
+
seen[key] = before
|
|
855
|
+
deferred.push({ number: issue.number, message: error.message, code: error.code })
|
|
856
|
+
if (!held || issue.updated_at < held) held = issue.updated_at
|
|
857
|
+
}
|
|
486
858
|
}
|
|
487
859
|
for (const [key, entry] of Object.entries(state.seen)) {
|
|
488
860
|
const gone = seenIssue(entry)
|
|
@@ -497,8 +869,10 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
|
|
|
497
869
|
state.seen = seen
|
|
498
870
|
state.seeded = true
|
|
499
871
|
state.openCount = Object.values(seen).filter((entry) => !seenIssue(entry).goneAt).length
|
|
872
|
+
if (held && (!cursor || held < cursor)) cursor = held
|
|
500
873
|
if (cursor) state.cursor = cursor
|
|
501
874
|
if (full) state.syncedAt = new Date(now).toISOString()
|
|
875
|
+
return { deferred }
|
|
502
876
|
}
|
|
503
877
|
|
|
504
878
|
function span(ms) {
|
|
@@ -688,6 +1062,13 @@ export function recoverDrainTarget({ paths, repo, now, start = startSuccessor })
|
|
|
688
1062
|
|
|
689
1063
|
// ── GitHub ──
|
|
690
1064
|
|
|
1065
|
+
/** What a non-OK answer means: GitHub's own server failing (5xx) clears by itself; only a 401 (a refused credential) is for the person to fix; any other refusal is reported as the answer GitHub gave, with no credential diagnosis. */
|
|
1066
|
+
function failedAnswer(status, route) {
|
|
1067
|
+
if (status >= 500) return Object.assign(new Error(`Wait for the next poll: GitHub's server answered HTTP ${status} for ${route} (asked twice); this usually clears on its own and needs nothing from you`), { code: "drains_github_server_error", status })
|
|
1068
|
+
if (status === 401) return Object.assign(new Error(`Check gh auth status, then try again: GitHub answered HTTP ${status} for ${route}, which means the token was refused`), { code: "drains_check_gh_auth_status_then", status })
|
|
1069
|
+
return Object.assign(new Error(`Read GitHub's answer, then fix its cause: GitHub refused the request with HTTP ${status} for ${route}; that is not by itself a credential problem`), { code: "drains_github_refused", status })
|
|
1070
|
+
}
|
|
1071
|
+
|
|
691
1072
|
/** The drain's GitHub access: its account's token from the `gh` CLI, then the REST API. `login` skips asking GitHub who the token is. */
|
|
692
1073
|
export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fetch, env = process.env, login: knownLogin, pauseMs = TOKEN_PAUSE_MS } = {}) {
|
|
693
1074
|
const tokenArgs = ["auth", "token", "--hostname", "github.com", ...(account ? ["--user", account] : [])]
|
|
@@ -708,15 +1089,24 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
|
|
|
708
1089
|
if (!token && transient) throw Object.assign(new Error(`Wait for the next poll, which reads the token again: the GitHub CLI's token read for ${account ?? "its active account"} gave no answer, probably because the keyring was busy or slow (${transient.slice(0, 160)})`), { code: "drains_github_cli_token_unavailable", transient: true })
|
|
709
1090
|
if (!token) throw Object.assign(new Error(`Sign in the GitHub CLI: the GitHub CLI has no token for ${account ?? "its active account"} (run \`gh auth login --hostname github.com\`)`), { code: "drains_sign_in_the_github_cli" })
|
|
710
1091
|
// What this connection spent and what GitHub says is left in the account's window; a 304 answer costs nothing against it.
|
|
711
|
-
const meter = { total: 0, notModified: 0, quota: null }
|
|
1092
|
+
const meter = { total: 0, notModified: 0, quota: null, graphqlQuota: null, graphqlCost: 1 }
|
|
1093
|
+
// A read that GitHub answers with a 5xx is asked once more, at once: its own server failing usually clears. Only reads are repeated, never a write.
|
|
1094
|
+
const readTwice = async (url, init) => {
|
|
1095
|
+
let response = await fetchImpl(url, init())
|
|
1096
|
+
meter.total += 1
|
|
1097
|
+
if (response.status >= 500) {
|
|
1098
|
+
response = await fetchImpl(url, init())
|
|
1099
|
+
meter.total += 1
|
|
1100
|
+
}
|
|
1101
|
+
return response
|
|
1102
|
+
}
|
|
712
1103
|
const get = async (route, { etag } = {}) => {
|
|
713
|
-
const response = await
|
|
1104
|
+
const response = await readTwice(`https://api.github.com${route}`, () => ({
|
|
714
1105
|
headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "desk-issue-drains", ...(etag ? { "If-None-Match": etag } : {}) },
|
|
715
1106
|
signal: AbortSignal.timeout(30_000),
|
|
716
|
-
})
|
|
717
|
-
meter.total += 1
|
|
1107
|
+
}))
|
|
718
1108
|
const remaining = response.headers.get("x-ratelimit-remaining")
|
|
719
|
-
if (remaining !== null) meter.quota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
|
|
1109
|
+
if (remaining !== null && response.headers.get("x-ratelimit-resource") !== "graphql") meter.quota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
|
|
720
1110
|
if (response.status === 304) {
|
|
721
1111
|
meter.notModified += 1
|
|
722
1112
|
return { notModified: true }
|
|
@@ -729,7 +1119,7 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
|
|
|
729
1119
|
const until = Number.isFinite(reset) && reset > 0 ? new Date(reset * 1000).toISOString() : "the next window"
|
|
730
1120
|
throw Object.assign(new Error(`Wait for the quota to reset: GitHub's hourly API limit is used up, rate limited until ${until} (HTTP ${response.status} for ${route.split("?")[0]})`), { code: "drains_rate_limited", status: response.status, rateLimited: true })
|
|
731
1121
|
}
|
|
732
|
-
throw
|
|
1122
|
+
throw failedAnswer(response.status, route.split("?")[0])
|
|
733
1123
|
}
|
|
734
1124
|
return { body: await response.json(), next: /rel="next"/u.test(response.headers.get("link") ?? ""), etag: response.headers.get("etag") }
|
|
735
1125
|
}
|
|
@@ -755,6 +1145,49 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
|
|
|
755
1145
|
meter.total += 1
|
|
756
1146
|
return { ok: response.ok, status: response.status, body: await response.json().catch(() => ({})) }
|
|
757
1147
|
}
|
|
1148
|
+
// GraphQL has its own quota window: its headers are kept apart from the REST reading, and a failure names this API.
|
|
1149
|
+
const graphql = async (query, variables) => {
|
|
1150
|
+
const response = await readTwice("https://api.github.com/graphql", () => ({
|
|
1151
|
+
method: "POST",
|
|
1152
|
+
headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "desk-issue-drains", "Content-Type": "application/json" },
|
|
1153
|
+
body: JSON.stringify({ query, variables }),
|
|
1154
|
+
signal: AbortSignal.timeout(30_000),
|
|
1155
|
+
}))
|
|
1156
|
+
const remaining = response.headers.get("x-ratelimit-remaining")
|
|
1157
|
+
if (remaining !== null) meter.graphqlQuota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
|
|
1158
|
+
const payload = response.ok ? await response.json().catch(() => null) : null
|
|
1159
|
+
const limited = response.status === 429 || (response.status === 403 && remaining === "0") || (payload?.errors ?? []).some((error) => error?.type === "RATE_LIMITED")
|
|
1160
|
+
if (limited) {
|
|
1161
|
+
const reset = Number(response.headers.get("x-ratelimit-reset"))
|
|
1162
|
+
const until = Number.isFinite(reset) && reset > 0 ? new Date(reset * 1000).toISOString() : "the next window"
|
|
1163
|
+
throw Object.assign(new Error(`Wait for the quota to reset: GitHub's hourly GraphQL limit is used up, rate limited until ${until} (HTTP ${response.status} for /graphql)`), { code: "drains_rate_limited", status: response.status, rateLimited: true })
|
|
1164
|
+
}
|
|
1165
|
+
if (!response.ok) throw failedAnswer(response.status, "/graphql")
|
|
1166
|
+
if (!payload || (Array.isArray(payload.errors) && payload.errors.length > 0) || typeof payload.data !== "object" || payload.data === null) {
|
|
1167
|
+
const said = Array.isArray(payload?.errors) ? payload.errors.map((error) => String(error?.message ?? "")).join("; ").slice(0, 160) : "no data"
|
|
1168
|
+
throw Object.assign(new Error(`Read GitHub's answer, then retry on the next poll: its GraphQL answer for the issue's edit history was refused or unreadable (${said}); that is not by itself a credential problem`), { code: "drains_graphql_failed" })
|
|
1169
|
+
}
|
|
1170
|
+
return payload.data
|
|
1171
|
+
}
|
|
1172
|
+
// One page of an issue's edit history, from its start or, with `backward`, from its end, after `cursor`. `hasMore` says whether
|
|
1173
|
+
// more lies beyond in that direction; `total` and `updatedAt` are the issue's as this page saw them.
|
|
1174
|
+
const editPage = async (repo, number, { backward = false, cursor = null } = {}) => {
|
|
1175
|
+
const [owner, name] = repo.split("/")
|
|
1176
|
+
const data = await graphql(backward ? EDITS_BACKWARD : EDITS_FORWARD, { owner, name, number, cursor })
|
|
1177
|
+
if (Number.isFinite(data.rateLimit?.cost)) meter.graphqlCost = data.rateLimit.cost
|
|
1178
|
+
const found = data.repository?.issue
|
|
1179
|
+
if (!found) return null
|
|
1180
|
+
const connection = found.userContentEdits
|
|
1181
|
+
const info = connection?.pageInfo
|
|
1182
|
+
if (!Array.isArray(connection?.nodes) || typeof info?.[backward ? "hasPreviousPage" : "hasNextPage"] !== "boolean") return { edits: null }
|
|
1183
|
+
return {
|
|
1184
|
+
updatedAt: found.updatedAt,
|
|
1185
|
+
total: connection.totalCount,
|
|
1186
|
+
edits: connection.nodes.map((node) => ({ id: node?.id ?? null, editedAt: node?.editedAt ?? null, deletedAt: node?.deletedAt ?? null, editor: node?.editor ? { type: node.editor.__typename ?? null, login: node.editor.login ?? null } : null })),
|
|
1187
|
+
hasMore: backward ? info.hasPreviousPage : info.hasNextPage,
|
|
1188
|
+
cursor: backward ? info.startCursor : info.endCursor,
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
758
1191
|
// Who the token really is decides which comments are the drain's own, so each drain's account is resolved from the token that polls its repository.
|
|
759
1192
|
const login = knownLogin || (await get("/user").then(({ body }) => String(body.login ?? ""), () => "")) || account || ""
|
|
760
1193
|
return {
|
|
@@ -777,6 +1210,9 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
|
|
|
777
1210
|
get,
|
|
778
1211
|
send,
|
|
779
1212
|
quota: () => meter.quota,
|
|
1213
|
+
graphqlQuota: () => meter.graphqlQuota,
|
|
1214
|
+
editPage,
|
|
1215
|
+
graphqlCost: () => meter.graphqlCost,
|
|
780
1216
|
calls: () => ({ total: meter.total, notModified: meter.notModified }),
|
|
781
1217
|
timeline: (repo, issue) => all(`/repos/${repo}/issues/${issue}/timeline`),
|
|
782
1218
|
pull: async (repo, number) => (await get(`/repos/${repo}/pulls/${number}`)).body,
|