@defrex/autobuild 1.4.2 → 1.6.0
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/README.md +1 -1
- package/SPEC.md +512 -101
- package/bin/ab-dispatch-kernel.ts +1 -0
- package/docs/accounts.md +9 -0
- package/docs/agent-runtimes.md +1 -0
- package/docs/answering-blocked-builds.md +7 -3
- package/docs/architecture.md +313 -130
- package/docs/assets/headline-wide.png +0 -0
- package/docs/build-store.md +33 -3
- package/docs/cli.md +2 -1
- package/docs/configuration-overview.md +9 -0
- package/docs/configuration.md +217 -106
- package/docs/dispatcher-hosting.md +19 -3
- package/docs/dispatcher.md +11 -6
- package/docs/glossary.md +1 -1
- package/docs/integration-overview.md +2 -2
- package/docs/integration-tree.md +91 -28
- package/docs/merge-policy.md +28 -9
- package/docs/operating.md +1 -1
- package/docs/operator-api.md +57 -20
- package/docs/operator-surfaces.md +1 -1
- package/docs/plugin-authoring.md +89 -8
- package/docs/remote-store-protocol.md +39 -11
- package/docs/remote-ticket-protocol.md +126 -12
- package/docs/restacking.md +24 -6
- package/docs/seams.md +2 -2
- package/docs/setup.md +19 -13
- package/docs/spec-standard.md +2 -1
- package/docs/ticket-dependencies.md +26 -8
- package/docs/ticket-migration.md +70 -7
- package/docs/ticket-sources.md +82 -5
- package/docs/tickets.md +34 -2
- package/docs/troubleshooting.md +3 -3
- package/docs/verification.md +5 -5
- package/docs/website.md +8 -0
- package/docs/workspaces.md +1 -1
- package/package.json +4 -3
- package/packages/core/src/accounts/hosted-readiness.ts +21 -0
- package/packages/core/src/cli/attention.ts +3 -0
- package/packages/core/src/cli/build-control.ts +36 -12
- package/packages/core/src/cli/connect.ts +9 -18
- package/packages/core/src/cli/context.ts +44 -0
- package/packages/core/src/cli/dashboard/configuration.ts +11 -0
- package/packages/core/src/cli/dashboard/model.ts +51 -11
- package/packages/core/src/cli/dashboard/poll.ts +14 -0
- package/packages/core/src/cli/dashboard/queue.ts +21 -0
- package/packages/core/src/cli/dashboard/render.ts +43 -22
- package/packages/core/src/cli/dispatch-frontend.ts +63 -30
- package/packages/core/src/cli/dispatch-mode.ts +35 -16
- package/packages/core/src/cli/dispatch-preflight.ts +4 -1
- package/packages/core/src/cli/dispatch-repository-feed.ts +40 -11
- package/packages/core/src/cli/dispatch-tickets.ts +47 -0
- package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
- package/packages/core/src/cli/dispatch.ts +522 -145
- package/packages/core/src/cli/help.ts +63 -24
- package/packages/core/src/cli/init-hosted-accounts.ts +54 -0
- package/packages/core/src/cli/init-readiness-remote.ts +16 -3
- package/packages/core/src/cli/init-validation.ts +144 -42
- package/packages/core/src/cli/issue-links.ts +67 -0
- package/packages/core/src/cli/main.ts +32 -15
- package/packages/core/src/cli/pr-summary-publication.ts +38 -7
- package/packages/core/src/cli/publication-settlement.ts +36 -24
- package/packages/core/src/cli/repo-lease.ts +225 -0
- package/packages/core/src/cli/repository-status.ts +203 -49
- package/packages/core/src/cli/status.ts +42 -4
- package/packages/core/src/cli/terminals.ts +37 -2
- package/packages/core/src/cli/ticket-editor.ts +20 -6
- package/packages/core/src/cli/ticket.ts +264 -46
- package/packages/core/src/cli/triage-count-sampler.ts +59 -0
- package/packages/core/src/cli/wait.ts +4 -1
- package/packages/core/src/cli/watch.ts +19 -4
- package/packages/core/src/config/live.ts +45 -4
- package/packages/core/src/config/load.ts +9 -0
- package/packages/core/src/config/pipeline-source.ts +6 -2
- package/packages/core/src/config/ready-assignee.ts +86 -0
- package/packages/core/src/config/schema.ts +202 -38
- package/packages/core/src/distribution-packaging.ts +1 -1
- package/packages/core/src/events/catalog.ts +7 -0
- package/packages/core/src/events/compatibility.ts +2 -1
- package/packages/core/src/events/payloads.ts +85 -0
- package/packages/core/src/events/policy.ts +10 -0
- package/packages/core/src/events/repository.ts +93 -28
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +237 -230
- package/packages/core/src/kernel/build-identity.ts +12 -0
- package/packages/core/src/kernel/change-presence.ts +139 -6
- package/packages/core/src/kernel/dispatch-capacity.ts +189 -19
- package/packages/core/src/kernel/dispatch-status.ts +10 -1
- package/packages/core/src/kernel/dispatch-upgrade.ts +104 -5
- package/packages/core/src/kernel/engine.ts +17 -8
- package/packages/core/src/kernel/finalize-pr-rejection.ts +95 -0
- package/packages/core/src/kernel/generators/build-log.ts +9 -0
- package/packages/core/src/kernel/generators/repository-journals.ts +15 -1
- package/packages/core/src/kernel/harvest.ts +4 -1
- package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
- package/packages/core/src/kernel/integration-completeness.ts +104 -17
- package/packages/core/src/kernel/integration-landing.ts +17 -0
- package/packages/core/src/kernel/integration-state.ts +17 -0
- package/packages/core/src/kernel/issue-keywords.ts +202 -0
- package/packages/core/src/kernel/janitor-failure.ts +96 -5
- package/packages/core/src/kernel/kernel-git.ts +87 -0
- package/packages/core/src/kernel/landing-readiness.ts +25 -17
- package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
- package/packages/core/src/kernel/log-index.ts +1 -1
- package/packages/core/src/kernel/node-issue-links.ts +142 -0
- package/packages/core/src/kernel/node-landing.ts +2 -1
- package/packages/core/src/kernel/node-parent.ts +6 -0
- package/packages/core/src/kernel/node-restack-transaction.ts +2 -0
- package/packages/core/src/kernel/pr-summary.ts +24 -0
- package/packages/core/src/kernel/read-deferrals.ts +75 -12
- package/packages/core/src/kernel/read-facts.ts +32 -1
- package/packages/core/src/kernel/reconcile-restack.ts +1 -1
- package/packages/core/src/kernel/reducer-registry.ts +37 -2
- package/packages/core/src/kernel/reducer.ts +147 -5
- package/packages/core/src/kernel/ticket-preparation.ts +16 -0
- package/packages/core/src/kernel/verify-budget.ts +43 -0
- package/packages/core/src/operator/index.ts +3 -1
- package/packages/core/src/operator/presentation.ts +3 -0
- package/packages/core/src/operator/protocol.ts +38 -2
- package/packages/core/src/operator/query.ts +69 -29
- package/packages/core/src/operator/registry.ts +47 -26
- package/packages/core/src/operator/tickets.ts +77 -10
- package/packages/core/src/plugin-sdk/index.ts +13 -0
- package/packages/core/src/plugins/manifest.ts +1 -1
- package/packages/core/src/plugins/registry.ts +1 -0
- package/packages/core/src/ports/forge/contract.ts +69 -0
- package/packages/core/src/ports/forge/create.ts +5 -0
- package/packages/core/src/ports/forge/fake.ts +184 -3
- package/packages/core/src/ports/forge/git-rewrite.ts +4 -2
- package/packages/core/src/ports/forge/github.ts +175 -38
- package/packages/core/src/ports/forge/local-git.ts +14 -0
- package/packages/core/src/ports/forge/readiness.ts +10 -0
- package/packages/core/src/ports/forge-failure.ts +43 -0
- package/packages/core/src/ports/runner/claude.ts +7 -1
- package/packages/core/src/ports/runner/codex.ts +7 -2
- package/packages/core/src/ports/runner/native-cli-fixture.ts +2 -1
- package/packages/core/src/ports/runner/pi.ts +7 -1
- package/packages/core/src/ports/runner/runtime.ts +3 -0
- package/packages/core/src/ports/runner/start-prompt.ts +37 -0
- package/packages/core/src/ports/tickets/contract.ts +320 -7
- package/packages/core/src/ports/tickets/create.ts +89 -20
- package/packages/core/src/ports/tickets/fake.ts +18 -0
- package/packages/core/src/ports/tickets/file-codec.ts +20 -0
- package/packages/core/src/ports/tickets/file.ts +43 -1
- package/packages/core/src/ports/tickets/github-fake.ts +1123 -0
- package/packages/core/src/ports/tickets/github-issues.ts +431 -0
- package/packages/core/src/ports/tickets/github-validators.ts +194 -0
- package/packages/core/src/ports/tickets/github.ts +2029 -0
- package/packages/core/src/ports/tickets/hosted-index.ts +34 -3
- package/packages/core/src/ports/tickets/issue-links.ts +86 -0
- package/packages/core/src/ports/tickets/lifecycle.ts +60 -4
- package/packages/core/src/ports/tickets/linear.ts +66 -6
- package/packages/core/src/ports/tickets/migration.ts +290 -68
- package/packages/core/src/ports/tickets/operations.ts +98 -12
- package/packages/core/src/ports/tickets/priority.ts +55 -0
- package/packages/core/src/ports/tickets/remote-protocol.ts +195 -29
- package/packages/core/src/ports/tickets/remote.ts +188 -13
- package/packages/core/src/ports/tickets/revision.ts +22 -1
- package/packages/core/src/ports/tickets/states.ts +43 -0
- package/packages/core/src/ports/tickets/tree.ts +58 -12
- package/packages/core/src/ports/tickets/update.ts +12 -2
- package/packages/core/src/ports/types.ts +194 -9
- package/packages/core/src/ports/workspace/commit-preservation.ts +163 -25
- package/packages/core/src/ports/workspace/git-worktree.ts +6 -2
- package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +121 -27
- package/packages/core/src/processes/build-runner.ts +101 -22
- package/packages/core/src/processes/dispatcher.ts +1046 -372
- package/packages/core/src/processes/execution-no-progress.ts +7 -0
- package/packages/core/src/processes/harvest-child.ts +4 -2
- package/packages/core/src/processes/harvest-execution-state.ts +104 -0
- package/packages/core/src/processes/harvest-runner.ts +263 -25
- package/packages/core/src/processes/harvest.ts +5 -8
- package/packages/core/src/processes/tick-publication.ts +12 -2
- package/packages/core/src/processes/ticket-scan-schedule.ts +78 -0
- package/packages/core/src/processes/workspace-preservation.ts +36 -1
- package/packages/core/src/runtime-identity.ts +10 -2
- package/packages/core/src/scenarios/harness.ts +149 -35
- package/packages/core/src/store/adapter.ts +7 -1
- package/packages/core/src/store/contract.ts +83 -2
- package/packages/core/src/store/digest.ts +32 -1
- package/packages/core/src/store/reduced-reads.ts +10 -0
- package/packages/core/src/store/reducer-value-shapes.json +4471 -3427
- package/packages/core/src/store/remote/protocol.ts +2 -0
- package/packages/core/src/store/remote/released-clients.json +22 -0
- package/packages/core/src/store/remote/released-reducer-values/1.5.0.json +26924 -0
- package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
- package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
- package/packages/core/src/store/repo-state-events.ts +2 -0
- package/packages/core/src/store/types.ts +5 -0
- package/packages/core/src/testing/dispatch-read-budget.ts +729 -123
- package/packages/core/src/testing/index.ts +18 -1
- package/packages/core/src/testing/presence-history.ts +79 -0
- package/packages/core/src/testing/reduced-read-budget.ts +1424 -33
- package/packages/core/src/testing/upgrade-generations.ts +77 -0
- package/skills/code-review/SKILL.md +4 -3
- package/skills/finalize/SKILL.md +18 -2
- package/skills/guide/SKILL.md +417 -143
- package/skills/guide/references/accounts.md +9 -0
- package/skills/guide/references/integration-tree.md +91 -28
- package/skills/guide/references/merge-policy.md +28 -9
- package/skills/guide/references/operator-api.md +57 -20
- package/skills/guide/references/plugin-authoring.md +89 -8
- package/skills/guide/references/remote-store-protocol.md +39 -11
- package/skills/guide/references/remote-ticket-protocol.md +126 -12
- package/skills/guide/references/restacking.md +24 -6
- package/skills/guide/references/setup.md +19 -13
- package/skills/guide/references/spec-standard.md +2 -1
- package/skills/guide/references/ticket-dependencies.md +26 -8
- package/skills/guide/references/ticket-migration.md +70 -7
- package/skills/harvest-review/SKILL.md +4 -3
- package/skills/implement/SKILL.md +20 -1
- package/skills/operate/SKILL.md +149 -35
- package/skills/plan/SKILL.md +1 -1
- package/skills/reconcile/SKILL.md +5 -4
- package/skills/spec/SKILL.md +15 -2
- package/skills/tickets/SKILL.md +116 -37
- package/templates/autobuild.toml +5 -0
- package/templates/hosted-service/package.json +2 -2
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure mapping between GitHub issues and Autobuild tickets for the `github`
|
|
3
|
+
* ticket source (SPEC §13). Nothing here performs I/O: the adapter in
|
|
4
|
+
* `github.ts` reads and writes through the transport, and these functions
|
|
5
|
+
* decide what an issue means and what a write must send.
|
|
6
|
+
*
|
|
7
|
+
* Vocabulary on GitHub:
|
|
8
|
+
* - a state is an `autobuild:<state>` label on an open issue; an open issue
|
|
9
|
+
* with none is in triage; closed as completed (or with no recorded reason)
|
|
10
|
+
* is done; closed as not planned or duplicate is the rejected role, or the
|
|
11
|
+
* fixed `not-planned` state when no rejected role is configured;
|
|
12
|
+
* - a link to another forge issue is an `autobuild-link:<intent> #<n>` label;
|
|
13
|
+
* - a node is an issue carrying the exact `node` label; a ticket targets a
|
|
14
|
+
* node by being a sub-issue of the node's issue, and any other parent is
|
|
15
|
+
* ordinary grouping with no target;
|
|
16
|
+
* - a creation key is a hidden HTML comment at the end of the body.
|
|
17
|
+
*/
|
|
18
|
+
import { z } from 'zod'
|
|
19
|
+
import type { IssueLink } from '../types'
|
|
20
|
+
import { normalizeIssueLinks } from './issue-links'
|
|
21
|
+
import { holdsState, type TicketLifecycle } from './lifecycle'
|
|
22
|
+
import { validateStateName } from './states'
|
|
23
|
+
|
|
24
|
+
export const STATE_LABEL_PREFIX = 'autobuild:'
|
|
25
|
+
export const LINK_LABEL_PREFIX = 'autobuild-link:'
|
|
26
|
+
/** The state of an issue closed as not planned or duplicate when no rejected
|
|
27
|
+
* role is configured. Listed, never ready, never resolves, never a target. */
|
|
28
|
+
export const NOT_PLANNED_STATE = 'not-planned'
|
|
29
|
+
|
|
30
|
+
// ── Wire shapes ──────────────────────────────────────────────────────────────
|
|
31
|
+
//
|
|
32
|
+
// Only the fields this source relies on are validated; unknown fields pass
|
|
33
|
+
// through so an added GitHub field cannot break a tick.
|
|
34
|
+
|
|
35
|
+
const labelRef = z.union([z.string(), z.object({ name: z.string() }).passthrough()])
|
|
36
|
+
|
|
37
|
+
export const githubIssueSchema = z
|
|
38
|
+
.object({
|
|
39
|
+
id: z.number().int(),
|
|
40
|
+
number: z.number().int().positive(),
|
|
41
|
+
title: z.string(),
|
|
42
|
+
body: z.string().nullable().optional(),
|
|
43
|
+
html_url: z.string(),
|
|
44
|
+
state: z.enum(['open', 'closed']),
|
|
45
|
+
state_reason: z.string().nullable().optional(),
|
|
46
|
+
labels: z.array(labelRef),
|
|
47
|
+
assignees: z
|
|
48
|
+
.array(z.object({ login: z.string() }).passthrough())
|
|
49
|
+
.nullable()
|
|
50
|
+
.optional(),
|
|
51
|
+
pull_request: z.unknown().optional(),
|
|
52
|
+
repository_url: z.string().optional(),
|
|
53
|
+
created_at: z.string().optional(),
|
|
54
|
+
parent_issue_url: z.string().nullable().optional(),
|
|
55
|
+
sub_issues_summary: z
|
|
56
|
+
.object({ total: z.number().int().optional() })
|
|
57
|
+
.passthrough()
|
|
58
|
+
.nullable()
|
|
59
|
+
.optional(),
|
|
60
|
+
issue_dependencies_summary: z
|
|
61
|
+
.object({
|
|
62
|
+
blocked_by: z.number().int().optional(),
|
|
63
|
+
total_blocked_by: z.number().int().optional(),
|
|
64
|
+
})
|
|
65
|
+
.passthrough()
|
|
66
|
+
.nullable()
|
|
67
|
+
.optional(),
|
|
68
|
+
})
|
|
69
|
+
.passthrough()
|
|
70
|
+
export type GitHubIssue = z.infer<typeof githubIssueSchema>
|
|
71
|
+
|
|
72
|
+
export const githubLabelSchema = z
|
|
73
|
+
.object({ name: z.string(), description: z.string().nullable().optional() })
|
|
74
|
+
.passthrough()
|
|
75
|
+
export type GitHubLabel = z.infer<typeof githubLabelSchema>
|
|
76
|
+
|
|
77
|
+
export const githubTimelineNodeSchema = z
|
|
78
|
+
.object({
|
|
79
|
+
__typename: z.string(),
|
|
80
|
+
label: z.object({ name: z.string() }).passthrough().nullable().optional(),
|
|
81
|
+
})
|
|
82
|
+
.passthrough()
|
|
83
|
+
export type GitHubTimelineNode = z.infer<typeof githubTimelineNodeSchema>
|
|
84
|
+
|
|
85
|
+
// ── Ids ──────────────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
/** `123` or `#123` → 123; anything else (UUIDs included) is no such ticket. */
|
|
88
|
+
export function parseIssueId(id: string): number | null {
|
|
89
|
+
const match = /^#?([1-9][0-9]*)$/.exec(id.trim())
|
|
90
|
+
if (!match) return null
|
|
91
|
+
const number = Number(match[1])
|
|
92
|
+
return Number.isSafeInteger(number) ? number : null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── Labels and states ────────────────────────────────────────────────────────
|
|
96
|
+
|
|
97
|
+
export function labelNames(issue: Pick<GitHubIssue, 'labels'>): string[] {
|
|
98
|
+
return issue.labels.map((label) => (typeof label === 'string' ? label : label.name))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function hasPrefix(name: string, prefix: string): boolean {
|
|
102
|
+
return name.toLowerCase().startsWith(prefix)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Kernel-owned marker labels that share the state prefix but are ordinary
|
|
106
|
+
* ticket labels: the dispatcher marks an aborted build's ticket with
|
|
107
|
+
* `autobuild:aborted`, and harvest files proposals with `autobuild:proposal`.
|
|
108
|
+
* Their names can never be states. */
|
|
109
|
+
export const MARKER_LABELS: readonly string[] = ['autobuild:aborted', 'autobuild:proposal']
|
|
110
|
+
|
|
111
|
+
function isMarkerLabel(name: string): boolean {
|
|
112
|
+
return MARKER_LABELS.includes(name.toLowerCase())
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function isStateLabel(name: string): boolean {
|
|
116
|
+
return hasPrefix(name, STATE_LABEL_PREFIX) && !isMarkerLabel(name)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function isLinkLabel(name: string): boolean {
|
|
120
|
+
return hasPrefix(name, LINK_LABEL_PREFIX)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function stateLabel(state: string): string {
|
|
124
|
+
return `${STATE_LABEL_PREFIX}${state}`
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The `autobuild:` labels on an issue, in label case. */
|
|
128
|
+
export function stateLabelsOf(issue: Pick<GitHubIssue, 'labels'>): string[] {
|
|
129
|
+
return labelNames(issue).filter(isStateLabel)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The ticket's own labels: every label except state and link labels. */
|
|
133
|
+
export function ticketLabelsOf(issue: Pick<GitHubIssue, 'labels'>): string[] {
|
|
134
|
+
return labelNames(issue).filter((name) => !isStateLabel(name) && !isLinkLabel(name))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── Kind and target ──────────────────────────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
/** The label that makes an issue a node, compared exactly as Linear does. */
|
|
140
|
+
export const NODE_LABEL = 'node'
|
|
141
|
+
|
|
142
|
+
export function isNode(issue: Pick<GitHubIssue, 'labels'>): boolean {
|
|
143
|
+
return labelNames(issue).includes(NODE_LABEL)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The issue's GitHub parent, from `parent_issue_url`, as `owner/repo` and
|
|
147
|
+
* number; `undefined` when it has none. */
|
|
148
|
+
export function parentOf(
|
|
149
|
+
issue: Pick<GitHubIssue, 'parent_issue_url'>,
|
|
150
|
+
): { repo: string; number: number } | undefined {
|
|
151
|
+
const match = /\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)$/.exec(issue.parent_issue_url ?? '')
|
|
152
|
+
if (!match) return undefined
|
|
153
|
+
const number = Number(match[2])
|
|
154
|
+
return Number.isSafeInteger(number) && number > 0 ? { repo: match[1]!, number } : undefined
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The ticket labels a kind and label instruction leave, with Linear's
|
|
158
|
+
* semantics: a kind adds or removes `node` over the given (or existing)
|
|
159
|
+
* labels; an explicit kind and labels that disagree about `node` conflict. */
|
|
160
|
+
export function effectiveLabels(
|
|
161
|
+
kind: string | undefined,
|
|
162
|
+
labels: readonly string[] | undefined,
|
|
163
|
+
existing: readonly string[],
|
|
164
|
+
): string[] | undefined {
|
|
165
|
+
if (kind !== undefined && kind !== 'work' && kind !== 'node')
|
|
166
|
+
throw new Error('kind must be work or node')
|
|
167
|
+
if (
|
|
168
|
+
kind !== undefined &&
|
|
169
|
+
labels !== undefined &&
|
|
170
|
+
(kind === 'node') !== labels.includes(NODE_LABEL)
|
|
171
|
+
)
|
|
172
|
+
throw new Error('conflicting kind and node label instructions')
|
|
173
|
+
if (kind === undefined) return labels === undefined ? undefined : [...labels]
|
|
174
|
+
const result = (labels ?? existing).filter((label) => label !== NODE_LABEL)
|
|
175
|
+
if (kind === 'node') result.push(NODE_LABEL)
|
|
176
|
+
return result
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The lifecycle names in workflow order, without duplicates. */
|
|
180
|
+
export function lifecycleNames(lifecycle: TicketLifecycle): string[] {
|
|
181
|
+
return [
|
|
182
|
+
...new Set(
|
|
183
|
+
[
|
|
184
|
+
lifecycle.triage,
|
|
185
|
+
lifecycle.ready,
|
|
186
|
+
lifecycle.doing,
|
|
187
|
+
lifecycle.done,
|
|
188
|
+
lifecycle.create,
|
|
189
|
+
lifecycle.proposal,
|
|
190
|
+
lifecycle.backlog,
|
|
191
|
+
lifecycle.rejected,
|
|
192
|
+
].filter((name): name is string => name !== undefined),
|
|
193
|
+
),
|
|
194
|
+
]
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The state of a closed issue that was not completed. */
|
|
198
|
+
export function rejectedStateOf(lifecycle: TicketLifecycle): string {
|
|
199
|
+
return lifecycle.rejected ?? NOT_PLANNED_STATE
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A label suffix spelled as its configured lifecycle name when one matches
|
|
203
|
+
* ignoring case, so `autobuild:Ready` reads as the configured `ready`. */
|
|
204
|
+
function canonicalState(name: string, lifecycle: TicketLifecycle): string {
|
|
205
|
+
return lifecycleNames(lifecycle).find((known) => holdsState(known, name)) ?? name
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function isClosedCompleted(issue: Pick<GitHubIssue, 'state' | 'state_reason'>): boolean {
|
|
209
|
+
// A null reason is a legacy completion: GitHub recorded no reason before
|
|
210
|
+
// close reasons existed, and treating it as done keeps old blockers resolved.
|
|
211
|
+
return (
|
|
212
|
+
issue.state === 'closed' &&
|
|
213
|
+
(issue.state_reason === 'completed' ||
|
|
214
|
+
issue.state_reason === null ||
|
|
215
|
+
issue.state_reason === undefined)
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export type IssueStateResult = { state: string } | { malformed: string[] }
|
|
220
|
+
|
|
221
|
+
/** What an issue's GitHub facts say its state is, before any reopen check. */
|
|
222
|
+
export function issueState(
|
|
223
|
+
issue: Pick<GitHubIssue, 'state' | 'state_reason' | 'labels'>,
|
|
224
|
+
lifecycle: TicketLifecycle,
|
|
225
|
+
): IssueStateResult {
|
|
226
|
+
if (issue.state === 'closed')
|
|
227
|
+
return { state: isClosedCompleted(issue) ? lifecycle.done : rejectedStateOf(lifecycle) }
|
|
228
|
+
const labels = stateLabelsOf(issue)
|
|
229
|
+
if (labels.length === 0) return { state: lifecycle.triage }
|
|
230
|
+
if (labels.length > 1) return { malformed: labels }
|
|
231
|
+
return { state: canonicalState(labels[0]!.slice(STATE_LABEL_PREFIX.length), lifecycle) }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Whether a reopened issue's single state label needs the reopen check. */
|
|
235
|
+
export function needsReopenCheck(
|
|
236
|
+
issue: Pick<GitHubIssue, 'state' | 'state_reason' | 'labels'>,
|
|
237
|
+
): boolean {
|
|
238
|
+
return (
|
|
239
|
+
issue.state === 'open' && issue.state_reason === 'reopened' && stateLabelsOf(issue).length === 1
|
|
240
|
+
)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export type ReopenVerdict = 'fresh' | 'stale' | 'undecidable'
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Walk timeline nodes (oldest first, as GitHub returns them) newest first and
|
|
247
|
+
* stop at the first decisive one: the current state label's `LabeledEvent`
|
|
248
|
+
* means the label was put on after the reopen (fresh), a `ReopenedEvent`
|
|
249
|
+
* means the label predates the reopen (stale). Neither in the window is
|
|
250
|
+
* undecidable, and the caller fails closed.
|
|
251
|
+
*/
|
|
252
|
+
export function reopenVerdict(
|
|
253
|
+
nodes: ReadonlyArray<GitHubTimelineNode>,
|
|
254
|
+
currentStateLabel: string,
|
|
255
|
+
): ReopenVerdict {
|
|
256
|
+
const wanted = currentStateLabel.toLowerCase()
|
|
257
|
+
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
258
|
+
const node = nodes[i]!
|
|
259
|
+
if (node.__typename === 'ReopenedEvent') return 'stale'
|
|
260
|
+
if (node.__typename === 'LabeledEvent' && node.label?.name.toLowerCase() === wanted)
|
|
261
|
+
return 'fresh'
|
|
262
|
+
}
|
|
263
|
+
return 'undecidable'
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface IssueWrite {
|
|
267
|
+
state: 'open' | 'closed'
|
|
268
|
+
state_reason?: 'completed' | 'not_planned'
|
|
269
|
+
/** The complete label set after the write. */
|
|
270
|
+
labels: string[]
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The issue facts that put a ticket in `state`, keeping every non-state label.
|
|
275
|
+
* Closing always strips state labels, so a reopen in the GitHub UI comes back
|
|
276
|
+
* label-less, which is triage.
|
|
277
|
+
*/
|
|
278
|
+
export function writeForState(
|
|
279
|
+
state: string,
|
|
280
|
+
lifecycle: TicketLifecycle,
|
|
281
|
+
currentLabels: readonly string[],
|
|
282
|
+
): IssueWrite {
|
|
283
|
+
const kept = currentLabels.filter((name) => !isStateLabel(name))
|
|
284
|
+
if (holdsState(state, lifecycle.done))
|
|
285
|
+
return { state: 'closed', state_reason: 'completed', labels: kept }
|
|
286
|
+
if (lifecycle.rejected !== undefined && holdsState(state, lifecycle.rejected))
|
|
287
|
+
return { state: 'closed', state_reason: 'not_planned', labels: kept }
|
|
288
|
+
if (holdsState(state, NOT_PLANNED_STATE))
|
|
289
|
+
throw new Error(
|
|
290
|
+
`github ticket source: "${NOT_PLANNED_STATE}" holds issues closed as not planned and cannot be moved into; configure [tickets].rejectedState to move tickets there`,
|
|
291
|
+
)
|
|
292
|
+
if (holdsState(state, lifecycle.triage)) return { state: 'open', labels: kept }
|
|
293
|
+
return { state: 'open', labels: [...kept, stateLabel(state)] }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** A state name GitHub can hold as an `autobuild:` label: the shared state
|
|
297
|
+
* name rule (lowercase, at most 40 characters), so the label fits GitHub's
|
|
298
|
+
* 50-character limit. */
|
|
299
|
+
export function representableState(name: string): boolean {
|
|
300
|
+
try {
|
|
301
|
+
validateStateName(name, 'github ticket source')
|
|
302
|
+
} catch {
|
|
303
|
+
return false
|
|
304
|
+
}
|
|
305
|
+
return !isMarkerLabel(stateLabel(name))
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ── Issue links ──────────────────────────────────────────────────────────────
|
|
309
|
+
|
|
310
|
+
export function linkLabel(link: IssueLink): string {
|
|
311
|
+
return `${LINK_LABEL_PREFIX}${link.intent} #${link.issue}`
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** An `autobuild-link:` label's link; `'invalid'` for a malformed one and
|
|
315
|
+
* `null` for a label without the prefix. */
|
|
316
|
+
export function parseLinkLabel(name: string): IssueLink | 'invalid' | null {
|
|
317
|
+
if (!isLinkLabel(name)) return null
|
|
318
|
+
const match = /^(closes|refs) #([1-9][0-9]*)$/i.exec(name.slice(LINK_LABEL_PREFIX.length))
|
|
319
|
+
if (!match) return 'invalid'
|
|
320
|
+
const issue = Number(match[2])
|
|
321
|
+
if (!Number.isSafeInteger(issue)) return 'invalid'
|
|
322
|
+
return { issue, intent: match[1]!.toLowerCase() as IssueLink['intent'] }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Merge links so one issue appears once; `closes` wins over `refs`. */
|
|
326
|
+
export function mergeIssueLinks(links: readonly IssueLink[]): IssueLink[] {
|
|
327
|
+
const merged = new Map<number, IssueLink>()
|
|
328
|
+
for (const link of links) {
|
|
329
|
+
const known = merged.get(link.issue)
|
|
330
|
+
if (known === undefined || (known.intent === 'refs' && link.intent === 'closes'))
|
|
331
|
+
merged.set(link.issue, { ...link })
|
|
332
|
+
}
|
|
333
|
+
return normalizeIssueLinks([...merged.values()])
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export interface IssueLinksRead {
|
|
337
|
+
/** The issue's own `closes` link plus every valid link label. */
|
|
338
|
+
links: IssueLink[]
|
|
339
|
+
/** Link labels that do not parse. */
|
|
340
|
+
invalid: string[]
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function issueLinksOf(issue: Pick<GitHubIssue, 'number' | 'labels'>): IssueLinksRead {
|
|
344
|
+
const links: IssueLink[] = [{ issue: issue.number, intent: 'closes' }]
|
|
345
|
+
const invalid: string[] = []
|
|
346
|
+
for (const name of labelNames(issue)) {
|
|
347
|
+
const link = parseLinkLabel(name)
|
|
348
|
+
if (link === null) continue
|
|
349
|
+
if (link === 'invalid') invalid.push(name)
|
|
350
|
+
else links.push(link)
|
|
351
|
+
}
|
|
352
|
+
return { links: mergeIssueLinks(links), invalid }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** The link labels a ticket's written links are stored as; the own issue's
|
|
356
|
+
* `closes` link is implicit and never a label. */
|
|
357
|
+
export function linkLabelsFor(own: number | undefined, links: readonly IssueLink[]): string[] {
|
|
358
|
+
return links.filter((link) => link.issue !== own).map(linkLabel)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ── Creation key marker ──────────────────────────────────────────────────────
|
|
362
|
+
|
|
363
|
+
const KEY_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/
|
|
364
|
+
const MARKER_PATTERN =
|
|
365
|
+
/\n<!-- autobuild:creation-key ([A-Za-z0-9._:-]{1,200})(?: pending ([A-Za-z0-9_-]*))? -->$/
|
|
366
|
+
|
|
367
|
+
/** The follow-up intent a keyed create records atomically with the issue. */
|
|
368
|
+
export interface CreationIntent {
|
|
369
|
+
state: string
|
|
370
|
+
issueLinks: IssueLink[]
|
|
371
|
+
blockedBy: string[]
|
|
372
|
+
/** The node the issue becomes a sub-issue of; absent in older markers. */
|
|
373
|
+
target?: string
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const creationIntentSchema = z.object({
|
|
377
|
+
state: z.string(),
|
|
378
|
+
issueLinks: z.array(
|
|
379
|
+
z.object({ issue: z.number().int().positive(), intent: z.enum(['closes', 'refs']) }),
|
|
380
|
+
),
|
|
381
|
+
blockedBy: z.array(z.string()),
|
|
382
|
+
target: z.string().optional(),
|
|
383
|
+
})
|
|
384
|
+
|
|
385
|
+
export function validCreationKey(key: string): boolean {
|
|
386
|
+
return KEY_PATTERN.test(key)
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** The body with a creation-key marker appended: pending (with the intent the
|
|
390
|
+
* retry must finish) or plain (create complete). */
|
|
391
|
+
export function encodeCreationMarker(body: string, key: string, intent?: CreationIntent): string {
|
|
392
|
+
if (!validCreationKey(key))
|
|
393
|
+
throw new Error(
|
|
394
|
+
`github create: creation key "${key}" must be 1-200 letters, digits, dots, colons, underscores or hyphens`,
|
|
395
|
+
)
|
|
396
|
+
const pending =
|
|
397
|
+
intent === undefined
|
|
398
|
+
? ''
|
|
399
|
+
: ` pending ${Buffer.from(JSON.stringify(intent), 'utf8').toString('base64url')}`
|
|
400
|
+
return `${body}\n<!-- autobuild:creation-key ${key}${pending} -->`
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export interface CreationMarker {
|
|
404
|
+
key: string
|
|
405
|
+
/** Present while the create's follow-ups are unfinished. */
|
|
406
|
+
pending?: CreationIntent
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Split a stored body into the ticket body (byte-exact) and its marker. */
|
|
410
|
+
export function splitCreationMarker(stored: string | null | undefined): {
|
|
411
|
+
body: string
|
|
412
|
+
marker?: CreationMarker
|
|
413
|
+
} {
|
|
414
|
+
const raw = stored ?? ''
|
|
415
|
+
const match = MARKER_PATTERN.exec(raw)
|
|
416
|
+
if (!match) return { body: raw }
|
|
417
|
+
const body = raw.slice(0, match.index)
|
|
418
|
+
const key = match[1]!
|
|
419
|
+
if (match[2] === undefined) return { body, marker: { key } }
|
|
420
|
+
let pending: CreationIntent = { state: '', issueLinks: [], blockedBy: [] }
|
|
421
|
+
try {
|
|
422
|
+
const parsed = creationIntentSchema.safeParse(
|
|
423
|
+
JSON.parse(Buffer.from(match[2], 'base64url').toString('utf8')),
|
|
424
|
+
)
|
|
425
|
+
if (parsed.success) pending = parsed.data
|
|
426
|
+
} catch {
|
|
427
|
+
// An unreadable intent still marks the create unfinished; the retry then
|
|
428
|
+
// finishes nothing it cannot read and clears the flag.
|
|
429
|
+
}
|
|
430
|
+
return { body, marker: { key, pending } }
|
|
431
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable conditional-read validators for the `github` ticket source.
|
|
3
|
+
*
|
|
4
|
+
* A dispatcher tick re-reads the same GitHub resources (the ready listing,
|
|
5
|
+
* each candidate's blockers) every few seconds. Sending the last response's
|
|
6
|
+
* ETag as `If-None-Match` turns an unchanged read into a 304, which costs no
|
|
7
|
+
* primary rate-limit budget. Keeping those validators under the local state
|
|
8
|
+
* root lets restarts and fresh CLI processes stay at zero too. Nothing here
|
|
9
|
+
* touches the BuildStore or the hosted service.
|
|
10
|
+
*
|
|
11
|
+
* Entries are evicted by age, never by count: a working set of any size
|
|
12
|
+
* stays warm, and an entry unused for {@link VALIDATOR_MAX_AGE_MS} goes.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from 'node:crypto'
|
|
15
|
+
import { mkdir, readFile, readdir, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
|
|
18
|
+
/** One remembered GET: the response's ETag, its JSON, and its `Link` header. */
|
|
19
|
+
export interface GitHubValidatorEntry {
|
|
20
|
+
etag: string
|
|
21
|
+
json: unknown
|
|
22
|
+
link?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface GitHubValidatorStore {
|
|
26
|
+
get(key: string): Promise<GitHubValidatorEntry | undefined>
|
|
27
|
+
/** Save an entry; rewriting is skipped when the ETag did not change. */
|
|
28
|
+
set(key: string, entry: GitHubValidatorEntry): Promise<void>
|
|
29
|
+
/** Record a hit (a 304 or a reused entry) as a use. */
|
|
30
|
+
touch(key: string): Promise<void>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** An entry unused this long is evicted. */
|
|
34
|
+
export const VALIDATOR_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
|
35
|
+
/** A hit refreshes last-used at most this often, so hits rarely write. */
|
|
36
|
+
export const VALIDATOR_TOUCH_INTERVAL_MS = 60 * 60 * 1000
|
|
37
|
+
/** The file store lists its directory to evict at most this often. */
|
|
38
|
+
export const VALIDATOR_SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000
|
|
39
|
+
|
|
40
|
+
export class MemoryGitHubValidatorStore implements GitHubValidatorStore {
|
|
41
|
+
private readonly entries = new Map<string, { entry: GitHubValidatorEntry; usedAt: number }>()
|
|
42
|
+
private readonly now: () => number
|
|
43
|
+
|
|
44
|
+
constructor(opts: { now?: () => number } = {}) {
|
|
45
|
+
this.now = opts.now ?? Date.now
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Number of live entries, for tests. */
|
|
49
|
+
get size(): number {
|
|
50
|
+
this.evict()
|
|
51
|
+
return this.entries.size
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async get(key: string): Promise<GitHubValidatorEntry | undefined> {
|
|
55
|
+
this.evict()
|
|
56
|
+
return this.entries.get(key)?.entry
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async set(key: string, entry: GitHubValidatorEntry): Promise<void> {
|
|
60
|
+
this.entries.set(key, { entry, usedAt: this.now() })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async touch(key: string): Promise<void> {
|
|
64
|
+
const held = this.entries.get(key)
|
|
65
|
+
if (held !== undefined && this.now() - held.usedAt > VALIDATOR_TOUCH_INTERVAL_MS)
|
|
66
|
+
held.usedAt = this.now()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private evict(): void {
|
|
70
|
+
const cutoff = this.now() - VALIDATOR_MAX_AGE_MS
|
|
71
|
+
for (const [key, held] of this.entries) if (held.usedAt < cutoff) this.entries.delete(key)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const SWEEP_MARKER = '.swept'
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* One JSON file per entry, named by the sha256 of its key. Writes go through a
|
|
79
|
+
* temp file and `rename`, so a dispatcher and concurrent CLI processes never
|
|
80
|
+
* see a torn entry and need no lock; two writers of one key leave the last
|
|
81
|
+
* write, which has the same meaning. A file's mtime is its last use. A
|
|
82
|
+
* per-process map fronts the files, so a key costs at most one file read per
|
|
83
|
+
* process. A corrupt or unreadable file is a miss and is overwritten.
|
|
84
|
+
*/
|
|
85
|
+
export class FileGitHubValidatorStore implements GitHubValidatorStore {
|
|
86
|
+
private readonly front = new Map<string, { entry: GitHubValidatorEntry; usedAt: number }>()
|
|
87
|
+
private readonly now: () => number
|
|
88
|
+
private readonly touchFile: (path: string, at: Date) => Promise<void>
|
|
89
|
+
private swept?: Promise<void>
|
|
90
|
+
|
|
91
|
+
constructor(
|
|
92
|
+
readonly dir: string,
|
|
93
|
+
opts: {
|
|
94
|
+
now?: () => number
|
|
95
|
+
/** Last-used refresh seam; tests count calls through it. */
|
|
96
|
+
utimes?: (path: string, at: Date) => Promise<void>
|
|
97
|
+
} = {},
|
|
98
|
+
) {
|
|
99
|
+
this.now = opts.now ?? Date.now
|
|
100
|
+
this.touchFile = opts.utimes ?? ((path, at) => utimes(path, at, at))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private file(key: string): string {
|
|
104
|
+
return join(this.dir, `${createHash('sha256').update(key).digest('hex')}.json`)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async get(key: string): Promise<GitHubValidatorEntry | undefined> {
|
|
108
|
+
await this.sweep()
|
|
109
|
+
const held = this.front.get(key)
|
|
110
|
+
if (held !== undefined) return held.entry
|
|
111
|
+
const path = this.file(key)
|
|
112
|
+
try {
|
|
113
|
+
const [raw, info] = await Promise.all([readFile(path, 'utf8'), stat(path)])
|
|
114
|
+
if (this.now() - info.mtimeMs > VALIDATOR_MAX_AGE_MS) return undefined
|
|
115
|
+
const parsed = JSON.parse(raw) as {
|
|
116
|
+
key?: unknown
|
|
117
|
+
etag?: unknown
|
|
118
|
+
json?: unknown
|
|
119
|
+
link?: unknown
|
|
120
|
+
}
|
|
121
|
+
if (parsed.key !== key || typeof parsed.etag !== 'string') return undefined
|
|
122
|
+
const entry: GitHubValidatorEntry = {
|
|
123
|
+
etag: parsed.etag,
|
|
124
|
+
json: parsed.json,
|
|
125
|
+
...(typeof parsed.link === 'string' ? { link: parsed.link } : {}),
|
|
126
|
+
}
|
|
127
|
+
this.front.set(key, { entry, usedAt: info.mtimeMs })
|
|
128
|
+
return entry
|
|
129
|
+
} catch {
|
|
130
|
+
return undefined
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async set(key: string, entry: GitHubValidatorEntry): Promise<void> {
|
|
135
|
+
const held = this.front.get(key)
|
|
136
|
+
if (held !== undefined && held.entry.etag === entry.etag) {
|
|
137
|
+
held.entry = entry
|
|
138
|
+
await this.touch(key)
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
const path = this.file(key)
|
|
142
|
+
const temp = `${path}.${process.pid}.${crypto.randomUUID()}.tmp`
|
|
143
|
+
try {
|
|
144
|
+
await mkdir(this.dir, { recursive: true })
|
|
145
|
+
await writeFile(temp, JSON.stringify({ key, ...entry }))
|
|
146
|
+
await rename(temp, path)
|
|
147
|
+
// The mtime is the entry's last use, on the store's clock.
|
|
148
|
+
const at = new Date(this.now())
|
|
149
|
+
await utimes(path, at, at)
|
|
150
|
+
this.front.set(key, { entry, usedAt: at.getTime() })
|
|
151
|
+
} catch {
|
|
152
|
+
// A validator is an optimization; failing to save one costs only a
|
|
153
|
+
// future unconditional read.
|
|
154
|
+
await unlink(temp).catch(() => {})
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async touch(key: string): Promise<void> {
|
|
159
|
+
const held = this.front.get(key)
|
|
160
|
+
if (held === undefined || this.now() - held.usedAt <= VALIDATOR_TOUCH_INTERVAL_MS) return
|
|
161
|
+
held.usedAt = this.now()
|
|
162
|
+
await this.touchFile(this.file(key), new Date(held.usedAt)).catch(() => {})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Evict entries unused for the maximum age, at most once a day across
|
|
166
|
+
* processes (gated by the marker file's mtime). Local disk only. */
|
|
167
|
+
private sweep(): Promise<void> {
|
|
168
|
+
this.swept ??= (async () => {
|
|
169
|
+
const marker = join(this.dir, SWEEP_MARKER)
|
|
170
|
+
try {
|
|
171
|
+
const info = await stat(marker)
|
|
172
|
+
if (this.now() - info.mtimeMs < VALIDATOR_SWEEP_INTERVAL_MS) return
|
|
173
|
+
} catch {
|
|
174
|
+
// No marker yet: sweep (an empty or missing directory costs nothing).
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const cutoff = this.now() - VALIDATOR_MAX_AGE_MS
|
|
178
|
+
for (const name of await readdir(this.dir)) {
|
|
179
|
+
if (!name.endsWith('.json')) continue
|
|
180
|
+
const path = join(this.dir, name)
|
|
181
|
+
const info = await stat(path).catch(() => undefined)
|
|
182
|
+
if (info !== undefined && info.mtimeMs < cutoff) await unlink(path).catch(() => {})
|
|
183
|
+
}
|
|
184
|
+
await mkdir(this.dir, { recursive: true })
|
|
185
|
+
await writeFile(marker, '')
|
|
186
|
+
const at = new Date(this.now())
|
|
187
|
+
await utimes(marker, at, at)
|
|
188
|
+
} catch {
|
|
189
|
+
// Eviction is housekeeping; a failure leaves entries for the next day.
|
|
190
|
+
}
|
|
191
|
+
})()
|
|
192
|
+
return this.swept
|
|
193
|
+
}
|
|
194
|
+
}
|