@qwen-code/channel-github 0.28.0 → 0.28.1-preview.1

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.
@@ -0,0 +1,202 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Qwen Team
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import type { ManagedReceipt, ManagedInboundEvent } from '@qwen-code/channel-base';
7
+ export type { ManagedReceipt };
8
+ export declare const MANAGED_GITHUB_PENDING_LIMIT = 32;
9
+ export declare const DISPATCHED_COMMENTS_LIMIT = 500;
10
+ /**
11
+ * The PR-watch transition vocabulary of the first slice (state_change is
12
+ * deferred). Mirrors the daemon's event set, minus state_change.
13
+ */
14
+ export type ManagedGithubPrTransition = 'ci_failure' | 'merge_conflict' | 'head_change';
15
+ export declare const MANAGED_GITHUB_PR_TRANSITIONS: readonly ManagedGithubPrTransition[];
16
+ /** The CI rollup vocabulary, one definition with the daemon's aggregateChecks. */
17
+ export type ManagedGithubCiAggregate = 'passing' | 'failing' | 'pending' | 'none';
18
+ /**
19
+ * Per-PR pending cap, the daemon's bound: overflow drops the oldest with a
20
+ * log line instead of growing the state file without limit.
21
+ */
22
+ export declare const MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT = 16;
23
+ /** Fired-ring cap, the retired channel watch's bound (MAX_FIRED_KEYS). */
24
+ export declare const MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT = 64;
25
+ /**
26
+ * Durable per-PR episode-watermark cap. The watermark outlives prune/rebind
27
+ * (the admission ledger is permanent), so it is bounded separately from the
28
+ * prunable baselines; overflow evicts the oldest watermark.
29
+ */
30
+ export declare const MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT = 1024;
31
+ /**
32
+ * One detected transition durably queued for injection. The full inject
33
+ * identity rides the entry because a restart re-drives it without re-listing
34
+ * bindings, and the control plane forces the target Session from its own
35
+ * binding — the adapter never chooses one.
36
+ */
37
+ export interface ManagedGithubPrWatchPending {
38
+ /** Local dedupe key; ci_failure keys match by PR+SHA prefix. */
39
+ key: string;
40
+ /**
41
+ * Durable per-PR occurrence number fed to the control plane's input-id
42
+ * derivation: a legitimate recurrence is a new episode (new input id), a
43
+ * redelivery of this same pending entry reuses it (same input id).
44
+ */
45
+ episode: number;
46
+ owner: string;
47
+ repo: string;
48
+ prNumber: number;
49
+ transition: ManagedGithubPrTransition;
50
+ headSha: string;
51
+ /** Sanitized transition summary for the injected prompt's evidence. */
52
+ evidence: string;
53
+ detectedAt: string;
54
+ }
55
+ /**
56
+ * Persisted per-PR observation backing edge-triggered watch events, the
57
+ * retired channel watch's PrWatchEntry shape: the baseline advances with
58
+ * each observation, ciFiredSha pins ci_failure once-per-head across fired-ring
59
+ * eviction, and seq numbers non-ci episodes so a legitimate recurrence
60
+ * (dirty → clean → dirty, a SHA revisit) fires again.
61
+ */
62
+ export interface ManagedGithubPrWatchEntry {
63
+ headSha?: string;
64
+ mergeableState?: string;
65
+ ci?: ManagedGithubCiAggregate;
66
+ ciFiredSha?: string;
67
+ seq?: number;
68
+ /** Monotonic per-PR occurrence counter; the last assigned pending episode. */
69
+ episode?: number;
70
+ /** Dedupe keys already injected, oldest first (capped ring). */
71
+ fired?: string[];
72
+ /** Detected but not yet injected transitions, oldest first (capped). */
73
+ pending?: ManagedGithubPrWatchPending[];
74
+ }
75
+ export interface ManagedGithubWatchState {
76
+ /** Keyed by lowercased `owner/repo#prNumber`. */
77
+ prs: Record<string, ManagedGithubPrWatchEntry>;
78
+ /**
79
+ * Rotation offset into the stably-ordered binding list: each tick observes a
80
+ * capped window starting here and advances, so every binding is observed
81
+ * across successive ticks instead of only the first cap (the daemon's
82
+ * sweepStart). Absent means start at the head of the list.
83
+ */
84
+ sweepStart?: number;
85
+ /**
86
+ * Durable per-PR occurrence watermark keyed like `prs`, carried across
87
+ * prune/rebind: the admission ledger is permanent and keyed without a
88
+ * binding discriminant, so a rebind must resume the episode counter rather
89
+ * than restart it and re-derive an already-admitted input id.
90
+ */
91
+ episodes?: Record<string, number>;
92
+ }
93
+ export interface ManagedGithubPendingEvent {
94
+ eventId: string;
95
+ /**
96
+ * The full admission, persisted because marking a notification thread read
97
+ * removes it from the unread list: after a restart the claim re-drives this
98
+ * exact event, never a comment re-fetched from the API (which may have been
99
+ * edited or deleted since admission).
100
+ */
101
+ event: ManagedInboundEvent;
102
+ /** The notification thread to mark read once this event is submitted. */
103
+ notificationThreadId: string;
104
+ held?: boolean;
105
+ }
106
+ export interface ManagedGithubOutboundSegment {
107
+ deliveryId: string;
108
+ ordinal: number;
109
+ receipt?: ManagedReceipt;
110
+ }
111
+ export interface ManagedGithubCursor {
112
+ /** The notification window watermark; null before the first poll. */
113
+ lastProcessedAt: string | null;
114
+ /** Comment keys already submitted; a work-saving filter over idempotency. */
115
+ dispatchedComments: string[];
116
+ }
117
+ export interface ManagedGithubState {
118
+ version: 1;
119
+ generation: number;
120
+ instanceRefusals?: number;
121
+ cursor: ManagedGithubCursor;
122
+ pending: ManagedGithubPendingEvent[];
123
+ outbound: ManagedGithubOutboundSegment[];
124
+ /** PR-watch baselines, fired-ring and pending; absent means no watch yet. */
125
+ watch?: ManagedGithubWatchState;
126
+ }
127
+ export declare function validManagedGithubState(value: unknown): value is ManagedGithubState;
128
+ export declare class ManagedGithubStateStore {
129
+ readonly directory: string;
130
+ readonly file: string;
131
+ constructor(name: string, cwd: string, baseUrl: string, identityKey?: string);
132
+ load(): ManagedGithubState | undefined;
133
+ /**
134
+ * The pre-registration-identity ledger this entry used before the upgrade.
135
+ * A sibling `managed-state.json` is stranded by the upgrade: its staged-but-
136
+ * unadmitted claims were never seen by the control plane (only `submitInbound`
137
+ * makes a claim visible), and the fresh ledger's null cursor starts the poll
138
+ * window at connect time, so the old notification is not re-listed. Report
139
+ * the path and its pending / outbound counts so the drop is explicit, never
140
+ * silent. Detection is NOT gated on the identity-keyed ledger being absent: a
141
+ * rollback to the pre-upgrade build can stage fresh claims into
142
+ * `managed-state.json` after a keyed ledger already exists, and those must
143
+ * still be reported. The caller archives the file once the start succeeds
144
+ * (`archiveStrandedLegacy`). The legacy ledger is NOT adopted — adopting it
145
+ * would replay one registration's pending into another, the cross-ownership
146
+ * hazard the identity keying prevents.
147
+ *
148
+ * `readable` distinguishes a legacy whose contents could not be read or
149
+ * parsed (counts unknown, reported as 0 but flagged) from one that parsed to
150
+ * an empty ledger: an unreadable legacy certainly strands whatever it held,
151
+ * so the caller must not render it as a quiescent "nothing was lost".
152
+ */
153
+ strandedLegacyLedger(): {
154
+ path: string;
155
+ pending: number;
156
+ outbound: number;
157
+ watchPending: number;
158
+ watchPendingKeys: string[];
159
+ readable: boolean;
160
+ watermark: string | null;
161
+ } | undefined;
162
+ /**
163
+ * The entry-scoped durable PR-watch episode counters, merged across every
164
+ * ledger this entry directory holds: the live legacy, each registration's
165
+ * identity-keyed ledger, and the `.stranded-*` archives (R3-1). The
166
+ * admission ledger is permanent and keyed without a registration
167
+ * discriminant, so the counters must outlive the legacy archive:
168
+ * registration A adopts them and archives the legacy, then registration B
169
+ * must still resume them rather than restart at 0 and re-derive an
170
+ * already-admitted input id (a silently deduped recurrence). Reading the
171
+ * archives — not just the live legacy — is what makes the carry survive the
172
+ * first start's rename. `Math.max` per key only errs toward a new id (the
173
+ * input id already binds tenant/channel), and values are sanitized to safe
174
+ * integers >= 1. A counter whose only home is a `watch.prs` baseline (its
175
+ * watermark was evicted) is carried too. This is the carry SOURCE, not the
176
+ * persisted state: it is returned uncapped, and the adapter merges it into the
177
+ * loaded ledger non-destructively under the validator's 1024 bound (R7-1) —
178
+ * capping here would discard recoverable counters before the adapter can
179
+ * place them. Best-effort: an unreadable or corrupt sibling is skipped, never
180
+ * a startup failure, but its path is returned in `skipped` so the caller can
181
+ * log that a counter source was unreadable rather than dropping it silently
182
+ * (deferred item 8). `episodes` is undefined when no ledger carries counters.
183
+ */
184
+ entryWatchEpisodes(): {
185
+ episodes: Record<string, number> | undefined;
186
+ skipped: string[];
187
+ };
188
+ /**
189
+ * Archive a reported legacy ledger so it is not re-announced on every later
190
+ * start (and a second registration of the entry is not told the first
191
+ * registration's claims were its own). Renaming — not deleting — keeps the
192
+ * stranded claims inspectable, and a rollback that stages a fresh
193
+ * `managed-state.json` is detected again on the next upgrade. This never
194
+ * adopts the claims into the keyed ledger. Returns the archived path, or
195
+ * undefined when there is nothing to archive or the rename fails (the file
196
+ * then stays and is reported again next start — degraded, never a startup
197
+ * failure).
198
+ */
199
+ archiveStrandedLegacy(): string | undefined;
200
+ save(state: ManagedGithubState): void;
201
+ }
202
+ //# sourceMappingURL=managed-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"managed-state.d.ts","sourceRoot":"","sources":["../src/managed-state.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAsBH,OAAO,KAAK,EACV,cAAc,EACd,mBAAmB,EACpB,MAAM,yBAAyB,CAAC;AAEjC,YAAY,EAAE,cAAc,EAAE,CAAC;AAW/B,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAC/C,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAE7C;;;GAGG;AACH,MAAM,MAAM,yBAAyB,GACjC,YAAY,GACZ,gBAAgB,GAChB,aAAa,CAAC;AAElB,eAAO,MAAM,6BAA6B,EAAE,SAAS,yBAAyB,EAC7B,CAAC;AAElD,kFAAkF;AAClF,MAAM,MAAM,wBAAwB,GAChC,SAAS,GACT,SAAS,GACT,SAAS,GACT,MAAM,CAAC;AAEX;;;GAGG;AACH,eAAO,MAAM,qCAAqC,KAAK,CAAC;AACxD,0EAA0E;AAC1E,eAAO,MAAM,mCAAmC,KAAK,CAAC;AACtD;;;;GAIG;AACH,eAAO,MAAM,qCAAqC,OAAO,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,WAAW,2BAA2B;IAC1C,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,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S;IAY3C,IAAI,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI;CAuBtC"}
@@ -0,0 +1,411 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Qwen Team
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { getGlobalQwenDir, getWorkspaceScopeDirName, MANAGED_OUTBOUND_LIMIT, validManagedReceipt, } from '@qwen-code/channel-base';
10
+ // H5f of #12827: the managed GitHub adapter's own locked state. The cursor
11
+ // (notification watermark plus the dispatched-comment ring) is the platform
12
+ // consumption commitment; pending holds the full inbound events because a
13
+ // marked-read notification cannot be re-listed; outbound is the sent-but-
14
+ // unreceipted segment ledger. Every claim persists before its side effect,
15
+ // so a restart replays the same event or reports the same segment unknown,
16
+ // never a second input and never a second send. See
17
+ // docs/design/2026-11-16-managed-channel-github-adapter.md.
18
+ export const MANAGED_GITHUB_PENDING_LIMIT = 32;
19
+ export const DISPATCHED_COMMENTS_LIMIT = 500;
20
+ export const MANAGED_GITHUB_PR_TRANSITIONS = ['ci_failure', 'merge_conflict', 'head_change'];
21
+ /**
22
+ * Per-PR pending cap, the daemon's bound: overflow drops the oldest with a
23
+ * log line instead of growing the state file without limit.
24
+ */
25
+ export const MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT = 16;
26
+ /** Fired-ring cap, the retired channel watch's bound (MAX_FIRED_KEYS). */
27
+ export const MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT = 64;
28
+ /**
29
+ * Durable per-PR episode-watermark cap. The watermark outlives prune/rebind
30
+ * (the admission ledger is permanent), so it is bounded separately from the
31
+ * prunable baselines; overflow evicts the oldest watermark.
32
+ */
33
+ export const MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT = 1024;
34
+ function validPrWatchEntry(value) {
35
+ if (!value || typeof value !== 'object' || Array.isArray(value))
36
+ return false;
37
+ const entry = value;
38
+ const nonEmptyStringOrUndefined = (v) => v === undefined || (typeof v === 'string' && v.length > 0);
39
+ return (nonEmptyStringOrUndefined(entry.headSha) &&
40
+ nonEmptyStringOrUndefined(entry.mergeableState) &&
41
+ nonEmptyStringOrUndefined(entry.ciFiredSha) &&
42
+ (entry.ci === undefined ||
43
+ entry.ci === 'passing' ||
44
+ entry.ci === 'failing' ||
45
+ entry.ci === 'pending' ||
46
+ entry.ci === 'none') &&
47
+ (entry.seq === undefined ||
48
+ (Number.isSafeInteger(entry.seq) && entry.seq >= 0)) &&
49
+ (entry.episode === undefined ||
50
+ (Number.isSafeInteger(entry.episode) && entry.episode >= 0)) &&
51
+ (entry.fired === undefined ||
52
+ (Array.isArray(entry.fired) &&
53
+ entry.fired.length <= MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT &&
54
+ entry.fired.every((key) => typeof key === 'string' && key.length > 0))) &&
55
+ (entry.pending === undefined ||
56
+ (Array.isArray(entry.pending) &&
57
+ entry.pending.length <= MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT &&
58
+ entry.pending.every((p) => !!p &&
59
+ typeof p === 'object' &&
60
+ typeof p.key === 'string' &&
61
+ p.key.length > 0 &&
62
+ Number.isSafeInteger(p.episode) &&
63
+ p.episode >= 1 &&
64
+ typeof p.owner === 'string' &&
65
+ p.owner.length > 0 &&
66
+ typeof p.repo === 'string' &&
67
+ p.repo.length > 0 &&
68
+ Number.isSafeInteger(p.prNumber) &&
69
+ p.prNumber >= 1 &&
70
+ MANAGED_GITHUB_PR_TRANSITIONS.includes(p.transition) &&
71
+ typeof p.headSha === 'string' &&
72
+ p.headSha.length > 0 &&
73
+ typeof p.evidence === 'string' &&
74
+ typeof p.detectedAt === 'string' &&
75
+ !Number.isNaN(Date.parse(p.detectedAt))))));
76
+ }
77
+ export function validManagedGithubState(value) {
78
+ if (!value || typeof value !== 'object')
79
+ return false;
80
+ const state = value;
81
+ return (state.version === 1 &&
82
+ Number.isSafeInteger(state.generation) &&
83
+ state.generation >= 1 &&
84
+ (state.instanceRefusals === undefined ||
85
+ (Number.isSafeInteger(state.instanceRefusals) &&
86
+ state.instanceRefusals >= 0)) &&
87
+ !!state.cursor &&
88
+ typeof state.cursor === 'object' &&
89
+ (state.cursor.lastProcessedAt === null ||
90
+ (typeof state.cursor.lastProcessedAt === 'string' &&
91
+ state.cursor.lastProcessedAt.length > 0 &&
92
+ !Number.isNaN(Date.parse(state.cursor.lastProcessedAt)))) &&
93
+ Array.isArray(state.cursor.dispatchedComments) &&
94
+ state.cursor.dispatchedComments.length <= DISPATCHED_COMMENTS_LIMIT &&
95
+ state.cursor.dispatchedComments.every((entry) => typeof entry === 'string' && entry.length > 0) &&
96
+ Array.isArray(state.pending) &&
97
+ state.pending.length <= MANAGED_GITHUB_PENDING_LIMIT &&
98
+ state.pending.every((entry) => entry &&
99
+ typeof entry.eventId === 'string' &&
100
+ entry.eventId.length > 0 &&
101
+ !!entry.event &&
102
+ typeof entry.event === 'object' &&
103
+ entry.event.platformEventId === entry.eventId &&
104
+ typeof entry.event.text === 'string' &&
105
+ typeof entry.notificationThreadId === 'string' &&
106
+ entry.notificationThreadId.length > 0) &&
107
+ Array.isArray(state.outbound) &&
108
+ state.outbound.length <= MANAGED_OUTBOUND_LIMIT &&
109
+ state.outbound.every((entry) => entry &&
110
+ typeof entry.deliveryId === 'string' &&
111
+ entry.deliveryId.length > 0 &&
112
+ Number.isSafeInteger(entry.ordinal) &&
113
+ entry.ordinal >= 0 &&
114
+ validManagedReceipt(entry.receipt)) &&
115
+ (state.watch === undefined ||
116
+ (!!state.watch &&
117
+ typeof state.watch === 'object' &&
118
+ !Array.isArray(state.watch) &&
119
+ !!state.watch.prs &&
120
+ typeof state.watch.prs === 'object' &&
121
+ !Array.isArray(state.watch.prs) &&
122
+ Object.values(state.watch.prs).every(validPrWatchEntry) &&
123
+ (state.watch.sweepStart === undefined ||
124
+ (Number.isSafeInteger(state.watch.sweepStart) &&
125
+ state.watch.sweepStart >= 0)) &&
126
+ (state.watch.episodes === undefined ||
127
+ (!!state.watch.episodes &&
128
+ typeof state.watch.episodes === 'object' &&
129
+ !Array.isArray(state.watch.episodes) &&
130
+ Object.keys(state.watch.episodes).length <=
131
+ MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT &&
132
+ Object.values(state.watch.episodes).every((episode) => Number.isSafeInteger(episode) && episode >= 1))))));
133
+ }
134
+ export class ManagedGithubStateStore {
135
+ directory;
136
+ file;
137
+ constructor(name, cwd, baseUrl, identityKey = '') {
138
+ // The lock directory is keyed by the configured entry (channel name +
139
+ // endpoint baseUrl) per workspace — NOT by destination — so two instances
140
+ // of the same name + endpoint contend for one connection lock even when
141
+ // they target different control-plane destinations; a per-destination lock
142
+ // would let both run concurrently and duplicate inbound processing. The
143
+ // ledger FILE beneath that directory is keyed by the full registration
144
+ // identity (control plane + tenant + channel + actor + workspace +
145
+ // cwd-relative), so a pending comment staged under one registration is
146
+ // never loaded or replayed under another. Credentials never define
147
+ // identity. The lock does not cross-lock the Legacy GitHub channel, so the
148
+ // operator must run exactly one consumer per bot identity.
149
+ const entryKey = createHash('sha256')
150
+ .update(`${name}\u0000${baseUrl}`)
151
+ .digest('hex')
152
+ .slice(0, 16);
153
+ this.directory = join(getGlobalQwenDir(), 'channels', getWorkspaceScopeDirName(cwd), `github-${entryKey}`);
154
+ const ledgerKey = createHash('sha256')
155
+ .update(identityKey)
156
+ .digest('hex')
157
+ .slice(0, 16);
158
+ this.file = join(this.directory, `managed-state-${ledgerKey}.json`);
159
+ }
160
+ load() {
161
+ // Name the file and keep the cause, and keep an I/O failure distinguishable
162
+ // from a corrupt state: the directory now holds a ledger per registration,
163
+ // so the operator must know WHICH file is unreadable (e.g. EISDIR) versus
164
+ // merely invalid, while a sibling registration's healthy ledger sits beside
165
+ // it. Mirrors the WeCom / DingTalk stores this change parallels.
166
+ let raw;
167
+ try {
168
+ raw = readFileSync(this.file, 'utf8');
169
+ }
170
+ catch (error) {
171
+ if (error.code === 'ENOENT')
172
+ return undefined;
173
+ throw new Error(`Managed GitHub state at ${this.file} could not be read; restore it before restarting.`, { cause: error });
174
+ }
175
+ let value;
176
+ try {
177
+ value = JSON.parse(raw);
178
+ }
179
+ catch (error) {
180
+ throw new Error(`Managed GitHub state at ${this.file} is not valid JSON; restore it before restarting.`, { cause: error });
181
+ }
182
+ if (!validManagedGithubState(value)) {
183
+ throw new Error(`Managed GitHub state at ${this.file} is invalid; restore it before restarting.`);
184
+ }
185
+ return value;
186
+ }
187
+ /**
188
+ * The pre-registration-identity ledger this entry used before the upgrade.
189
+ * A sibling `managed-state.json` is stranded by the upgrade: its staged-but-
190
+ * unadmitted claims were never seen by the control plane (only `submitInbound`
191
+ * makes a claim visible), and the fresh ledger's null cursor starts the poll
192
+ * window at connect time, so the old notification is not re-listed. Report
193
+ * the path and its pending / outbound counts so the drop is explicit, never
194
+ * silent. Detection is NOT gated on the identity-keyed ledger being absent: a
195
+ * rollback to the pre-upgrade build can stage fresh claims into
196
+ * `managed-state.json` after a keyed ledger already exists, and those must
197
+ * still be reported. The caller archives the file once the start succeeds
198
+ * (`archiveStrandedLegacy`). The legacy ledger is NOT adopted — adopting it
199
+ * would replay one registration's pending into another, the cross-ownership
200
+ * hazard the identity keying prevents.
201
+ *
202
+ * `readable` distinguishes a legacy whose contents could not be read or
203
+ * parsed (counts unknown, reported as 0 but flagged) from one that parsed to
204
+ * an empty ledger: an unreadable legacy certainly strands whatever it held,
205
+ * so the caller must not render it as a quiescent "nothing was lost".
206
+ */
207
+ strandedLegacyLedger() {
208
+ const legacyPath = join(this.directory, 'managed-state.json');
209
+ if (!existsSync(legacyPath))
210
+ return undefined;
211
+ let pending = 0;
212
+ let outbound = 0;
213
+ let watchPending = 0;
214
+ const watchPendingKeys = [];
215
+ let readable = true;
216
+ let watermark = null;
217
+ try {
218
+ const value = JSON.parse(readFileSync(legacyPath, 'utf8'));
219
+ // A parseable non-ledger (`{}`, `[]`, `null`, or an object without the
220
+ // ledger's pending/outbound arrays) is not a quiescent empty ledger: it
221
+ // is an unrecognized file whose claims are unknown. Flag it unreadable so
222
+ // the notice reports a possible loss, never a loss-free "0 pending / 0
223
+ // outbound" all-clear (deferred item 7).
224
+ const isLedgerShape = !!value &&
225
+ typeof value === 'object' &&
226
+ !Array.isArray(value) &&
227
+ Array.isArray(value.pending) &&
228
+ Array.isArray(value.outbound);
229
+ if (!isLedgerShape)
230
+ readable = false;
231
+ const pendingList = value?.pending;
232
+ const outboundList = value?.outbound;
233
+ pending = Array.isArray(pendingList) ? pendingList.length : 0;
234
+ // Only segments whose delivery status is UNKNOWN are a loss: a definitive
235
+ // receipt (accepted/rejected) proves the outcome, but an absent receipt —
236
+ // or one whose outcome is 'unknown' — does not, so both count toward the
237
+ // unknown-status clause (deferred item 9; an {outcome:'unknown'} receipt
238
+ // is not a known outcome).
239
+ outbound = Array.isArray(outboundList)
240
+ ? outboundList.filter((segment) => {
241
+ const receipt = segment && typeof segment === 'object'
242
+ ? segment.receipt
243
+ : undefined;
244
+ return !(receipt &&
245
+ (receipt.outcome === 'accepted' || receipt.outcome === 'rejected'));
246
+ }).length
247
+ : 0;
248
+ // The legacy notification watermark: the fresh ledger's null cursor
249
+ // restarts the poll window at connect time, so unread notifications
250
+ // updated after this watermark while the bot was down are never listed.
251
+ // Surfacing it lets the notice name that skipped window even when the
252
+ // legacy staged no pending/outbound (R1-4).
253
+ const lastProcessedAt = value?.cursor?.lastProcessedAt;
254
+ watermark = typeof lastProcessedAt === 'string' ? lastProcessedAt : null;
255
+ // The legacy watch.prs queue holds detected-but-undelivered transitions
256
+ // (R3-1). The fresh ledger re-baselines watch.prs empty and does NOT
257
+ // adopt them — injecting one registration's detected events under
258
+ // another is the cross-ownership replay the keying prevents — so they
259
+ // are stranded work. Count the PR entries whose queue is non-empty so
260
+ // the notice names that loss instead of a quiescent "0 pending", and
261
+ // collect their keys so the caller can tell whether the loaded ledger
262
+ // holds a baseline to re-detect them against (R5). The durable episode
263
+ // counters are carried separately, entry-scoped, by entryWatchEpisodes().
264
+ const rawPrs = value?.watch?.prs;
265
+ if (!!rawPrs && typeof rawPrs === 'object' && !Array.isArray(rawPrs)) {
266
+ for (const [key, entry] of Object.entries(rawPrs)) {
267
+ const queue = entry?.pending;
268
+ if (Array.isArray(queue) && queue.length > 0) {
269
+ watchPending += 1;
270
+ watchPendingKeys.push(key);
271
+ }
272
+ }
273
+ }
274
+ }
275
+ catch {
276
+ // A corrupt or unreadable legacy still strands; flag it so the caller
277
+ // reports unknown counts and a possible loss, never a silent "empty".
278
+ readable = false;
279
+ }
280
+ return {
281
+ path: legacyPath,
282
+ pending,
283
+ outbound,
284
+ watchPending,
285
+ watchPendingKeys,
286
+ readable,
287
+ watermark,
288
+ };
289
+ }
290
+ /**
291
+ * The entry-scoped durable PR-watch episode counters, merged across every
292
+ * ledger this entry directory holds: the live legacy, each registration's
293
+ * identity-keyed ledger, and the `.stranded-*` archives (R3-1). The
294
+ * admission ledger is permanent and keyed without a registration
295
+ * discriminant, so the counters must outlive the legacy archive:
296
+ * registration A adopts them and archives the legacy, then registration B
297
+ * must still resume them rather than restart at 0 and re-derive an
298
+ * already-admitted input id (a silently deduped recurrence). Reading the
299
+ * archives — not just the live legacy — is what makes the carry survive the
300
+ * first start's rename. `Math.max` per key only errs toward a new id (the
301
+ * input id already binds tenant/channel), and values are sanitized to safe
302
+ * integers >= 1. A counter whose only home is a `watch.prs` baseline (its
303
+ * watermark was evicted) is carried too. This is the carry SOURCE, not the
304
+ * persisted state: it is returned uncapped, and the adapter merges it into the
305
+ * loaded ledger non-destructively under the validator's 1024 bound (R7-1) —
306
+ * capping here would discard recoverable counters before the adapter can
307
+ * place them. Best-effort: an unreadable or corrupt sibling is skipped, never
308
+ * a startup failure, but its path is returned in `skipped` so the caller can
309
+ * log that a counter source was unreadable rather than dropping it silently
310
+ * (deferred item 8). `episodes` is undefined when no ledger carries counters.
311
+ */
312
+ entryWatchEpisodes() {
313
+ const skipped = [];
314
+ let names;
315
+ try {
316
+ names = readdirSync(this.directory);
317
+ }
318
+ catch {
319
+ return { episodes: undefined, skipped };
320
+ }
321
+ const merged = {};
322
+ for (const name of names) {
323
+ // The legacy ledger, the identity-keyed ledgers, and the legacy archives
324
+ // — never an in-flight <uuid>.tmp or the lock metadata.
325
+ if (!/^managed-state(-[0-9a-f]{16})?\.json(\.stranded-.+)?$/.test(name)) {
326
+ continue;
327
+ }
328
+ const filePath = join(this.directory, name);
329
+ let value;
330
+ try {
331
+ value = JSON.parse(readFileSync(filePath, 'utf8'));
332
+ }
333
+ catch {
334
+ skipped.push(filePath);
335
+ continue;
336
+ }
337
+ const watch = value?.watch;
338
+ const raw = watch?.episodes;
339
+ if (!!raw && typeof raw === 'object' && !Array.isArray(raw)) {
340
+ for (const [key, entry] of Object.entries(raw)) {
341
+ if (Number.isSafeInteger(entry) && entry >= 1) {
342
+ merged[key] = Math.max(merged[key] ?? 0, entry);
343
+ }
344
+ }
345
+ }
346
+ // A counter whose only home is a prs baseline (its watermark was evicted
347
+ // by the live cap) is still durable; carry it too, or a rebind would
348
+ // restart it and re-derive an admitted id.
349
+ const rawPrs = watch?.prs;
350
+ if (!!rawPrs && typeof rawPrs === 'object' && !Array.isArray(rawPrs)) {
351
+ for (const [key, entry] of Object.entries(rawPrs)) {
352
+ const episode = entry?.episode;
353
+ if (Number.isSafeInteger(episode) && episode >= 1) {
354
+ merged[key] = Math.max(merged[key] ?? 0, episode);
355
+ }
356
+ }
357
+ }
358
+ }
359
+ if (Object.keys(merged).length === 0)
360
+ return { episodes: undefined, skipped };
361
+ return { episodes: merged, skipped };
362
+ }
363
+ /**
364
+ * Archive a reported legacy ledger so it is not re-announced on every later
365
+ * start (and a second registration of the entry is not told the first
366
+ * registration's claims were its own). Renaming — not deleting — keeps the
367
+ * stranded claims inspectable, and a rollback that stages a fresh
368
+ * `managed-state.json` is detected again on the next upgrade. This never
369
+ * adopts the claims into the keyed ledger. Returns the archived path, or
370
+ * undefined when there is nothing to archive or the rename fails (the file
371
+ * then stays and is reported again next start — degraded, never a startup
372
+ * failure).
373
+ */
374
+ archiveStrandedLegacy() {
375
+ const legacyPath = join(this.directory, 'managed-state.json');
376
+ if (!existsSync(legacyPath))
377
+ return undefined;
378
+ const archived = `${legacyPath}.stranded-${randomUUID()}`;
379
+ try {
380
+ renameSync(legacyPath, archived);
381
+ return archived;
382
+ }
383
+ catch {
384
+ return undefined;
385
+ }
386
+ }
387
+ save(state) {
388
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
389
+ const temporary = join(this.directory, `${randomUUID()}.tmp`);
390
+ try {
391
+ const fd = openSync(temporary, 'wx', 0o600);
392
+ try {
393
+ writeFileSync(fd, JSON.stringify(state));
394
+ fsyncSync(fd);
395
+ }
396
+ finally {
397
+ closeSync(fd);
398
+ }
399
+ renameSync(temporary, this.file);
400
+ }
401
+ catch (error) {
402
+ // The fixed sentence keeps platform data out of the message, but the fs
403
+ // error rides on `cause` so the adapter's logs can name ENOSPC/EACCES.
404
+ throw new Error('Managed GitHub state could not be saved; admission stopped.', { cause: error });
405
+ }
406
+ finally {
407
+ rmSync(temporary, { force: true });
408
+ }
409
+ }
410
+ }
411
+ //# sourceMappingURL=managed-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"managed-state.js","sourceRoot":"","sources":["../src/managed-state.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,SAAS,EACT,UAAU,EACV,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,UAAU,EACV,MAAM,EACN,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,yB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