opencode-azure-devops-pr-review 0.4.0 → 0.4.2
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.md +173 -0
- package/README.md +136 -37
- package/package.json +11 -3
- package/src/attribution.mjs +18 -2
- package/src/azure.mjs +19 -13
- package/src/comment-work.mjs +5 -3
- package/src/config.mjs +63 -14
- package/src/diagnostics.mjs +1 -0
- package/src/host.mjs +13 -5
- package/src/review-tools.mjs +4 -3
- package/src/runtime.mjs +351 -58
- package/src/session.mjs +76 -18
- package/src/setup.mjs +120 -27
- package/src/store.mjs +94 -25
- package/src/tui-model.mjs +566 -0
- package/src/tui-view.jsx +438 -0
- package/src/tui.js +716 -0
package/src/session.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** OpenCode V2 session transport. No provider, Azure or HTTP client. */
|
|
2
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
-
import { FOREIGN_MESSAGE_TYPES, USED_UP_LIMITS, isHostContinuation, requireMethods } from './host.mjs';
|
|
3
|
+
import { FOREIGN_MESSAGE_TYPES, USED_UP_LIMITS, isHostContinuation, recordOf, requireMethods } from './host.mjs';
|
|
4
4
|
|
|
5
5
|
const pendingAdmissions = new WeakMap();
|
|
6
6
|
const textValue = value => typeof value === 'string' && value.length > 0;
|
|
@@ -66,19 +66,50 @@ function sameModel(actual, expected) {
|
|
|
66
66
|
(actual?.variant ?? 'default') === (expected.variant ?? 'default');
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
/**
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
/**
|
|
70
|
+
* The conversation's location, which a child session would inherit. Undefined
|
|
71
|
+
* when the host reports none; the host then uses the location this plugin
|
|
72
|
+
* instance serves.
|
|
73
|
+
*/
|
|
74
|
+
async function conversationLocation(api, origin, signal) {
|
|
75
|
+
const conversation = recordOf(await cancellable(() => api.get({ sessionID: origin }), signal).catch(() => null));
|
|
76
|
+
const directory = conversation?.location?.directory;
|
|
77
|
+
if (!textValue(directory)) return undefined;
|
|
78
|
+
const workspaceID = conversation.location.workspaceID;
|
|
79
|
+
return { directory, ...(workspaceID === undefined || workspaceID === null ? {} : { workspaceID }) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Create a session of its own with its agent and model already bound, at the
|
|
84
|
+
* conversation's location. It is deliberately not a child of the conversation:
|
|
85
|
+
* OpenCode 2.3.0 and later hand every answer of a child session to its parent
|
|
86
|
+
* and wake the parent's own model with it. `metadata` marks the session as
|
|
87
|
+
* AZPR's for tools that list sessions. A cancellation can overtake the host:
|
|
88
|
+
* the session may still be created after this call gave up, and nothing else
|
|
89
|
+
* would know it. `onLate` then receives it, when it is the session this call
|
|
90
|
+
* asked for, so that the caller can delete it.
|
|
91
|
+
*/
|
|
92
|
+
export async function createReviewSession(context, { origin, title, role, model, permissions, metadata, signal, onLate }) {
|
|
93
|
+
const api = sessionApi(context, ['create', 'get']);
|
|
72
94
|
if (!textValue(origin) || !textValue(role) || !textValue(title)) throw new Error('[AZPR] Incomplete review session identity.');
|
|
73
95
|
const selectedModel = modelRef(model);
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
96
|
+
const location = await conversationLocation(api, origin, signal);
|
|
97
|
+
const requested = made => record(made) && textValue(made.id) && made.id !== origin && (made.parentID ?? null) === null &&
|
|
98
|
+
made.agent === role && sameModel(made.model, selectedModel) &&
|
|
99
|
+
(location === undefined || !record(made.location) || made.location.directory === location.directory);
|
|
100
|
+
let creating, made;
|
|
101
|
+
try {
|
|
102
|
+
made = await cancellable(() => (creating = Promise.resolve(api.create({
|
|
103
|
+
title, agent: role, model: selectedModel,
|
|
104
|
+
...(location === undefined ? {} : { location }),
|
|
105
|
+
...(metadata === undefined ? {} : { metadata }),
|
|
106
|
+
...(permissions === undefined ? {} : { permissions }),
|
|
107
|
+
}))), signal);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (onLate) creating?.then(late => { if (requested(late)) onLate(late); }).catch(() => {});
|
|
110
|
+
throw error;
|
|
81
111
|
}
|
|
112
|
+
if (!requested(made)) throw new Error('[AZPR] OpenCode V2 did not create the requested independent reviewer session.');
|
|
82
113
|
return made;
|
|
83
114
|
}
|
|
84
115
|
|
|
@@ -116,9 +147,28 @@ function providerFailure(final, assistants) {
|
|
|
116
147
|
}
|
|
117
148
|
|
|
118
149
|
/**
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
* followed by the
|
|
150
|
+
* Errored assistant messages of steps the host retried by itself after an
|
|
151
|
+
* interrupted stream (OpenCode 2.3.0 and later): each is marked for retry and
|
|
152
|
+
* directly followed by the assistant message of the retried step. The retry is
|
|
153
|
+
* sent with what the step had finished (its tool calls that ran and what came
|
|
154
|
+
* before them) and without the output the interruption cut off, so the answer
|
|
155
|
+
* is the final message alone and nothing of these messages is joined to it.
|
|
156
|
+
*/
|
|
157
|
+
function retriedSteps(turn, enabled) {
|
|
158
|
+
const retried = new Set();
|
|
159
|
+
if (!enabled) return retried;
|
|
160
|
+
turn.forEach((message, index) => {
|
|
161
|
+
if (message?.type === 'assistant' && message.error && message.finish === 'error' && Number.isInteger(message.retry?.attempt) &&
|
|
162
|
+
message.retry.attempt >= 1 && Number.isFinite(message.time?.completed) && turn[index + 1]?.type === 'assistant') retried.add(message);
|
|
163
|
+
});
|
|
164
|
+
return retried;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Text fragments of a stream the host interrupted and resumed with a
|
|
169
|
+
* continuation message (OpenCode through 2.2.x). Accept only errored text-only
|
|
170
|
+
* assistant messages that the host marked for retry, each followed by the host
|
|
171
|
+
* continuation, and finally a successful text answer.
|
|
122
172
|
*/
|
|
123
173
|
function continuedText(turn, enabled) {
|
|
124
174
|
const none = { recovered: new Set(), synthetic: new Set() };
|
|
@@ -211,7 +261,9 @@ export async function requestReview(context, { sessionID, text, role, model, met
|
|
|
211
261
|
throw new Error('[AZPR] The projected prompt differs from the admitted literal input.');
|
|
212
262
|
}
|
|
213
263
|
const turn = messages.slice(indexes[0] + 1);
|
|
214
|
-
|
|
264
|
+
// Either way the host recovers an interrupted stream; both need the caller's consent.
|
|
265
|
+
const retried = retriedSteps(turn, allowHostContinuations);
|
|
266
|
+
const continuation = continuedText(turn.filter(message => !retried.has(message)), allowHostContinuations);
|
|
215
267
|
if (turn.some(message => FOREIGN_MESSAGE_TYPES.includes(message?.type) && !continuation.synthetic.has(message))) {
|
|
216
268
|
const error = new Error('[AZPR] The session received another message during this turn; its output cannot be assigned to the authorized request.');
|
|
217
269
|
error.contextChanged = true;
|
|
@@ -247,7 +299,7 @@ export async function requestReview(context, { sessionID, text, role, model, met
|
|
|
247
299
|
throw responseError('[AZPR] Reviewer agent or model binding changed; no output was accepted.', answer);
|
|
248
300
|
}
|
|
249
301
|
if (!final || turn.at(-2) !== final || !Array.isArray(final.content) || !Number.isFinite(final.time?.completed) ||
|
|
250
|
-
assistants.some(message => !continuation.recovered.has(message) && (message.error || !Number.isFinite(message.time?.completed) ||
|
|
302
|
+
assistants.some(message => !continuation.recovered.has(message) && !retried.has(message) && (message.error || !Number.isFinite(message.time?.completed) ||
|
|
251
303
|
!['stop', 'tool-calls'].includes(message.finish)))) {
|
|
252
304
|
const error = responseError('[AZPR] The session has no complete, successful final assistant response.', answer);
|
|
253
305
|
error.transient = true;
|
|
@@ -266,6 +318,7 @@ export async function requestReview(context, { sessionID, text, role, model, met
|
|
|
266
318
|
answer.parts = [{ type: 'text', text: texts.slice(restartedAt).join('') }];
|
|
267
319
|
answer.continuation = { count: continuation.recovered.size, fragments, ...(restartedAt ? { restartedAt } : {}) };
|
|
268
320
|
}
|
|
321
|
+
if (retried.size) answer.retriedSteps = retried.size;
|
|
269
322
|
aborted(signal);
|
|
270
323
|
return answer;
|
|
271
324
|
}
|
|
@@ -282,12 +335,17 @@ export async function interruptSession(context, { sessionID, signal }) {
|
|
|
282
335
|
return { interrupted: result.interrupted, settled: true };
|
|
283
336
|
}
|
|
284
337
|
|
|
285
|
-
/**
|
|
286
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Queue report data without starting a formatting or ordinary-agent model call.
|
|
340
|
+
* `metadata` is stored with the notice for clients that read it (the terminal panel); no model sees it,
|
|
341
|
+
* and a call without it is the request it always was.
|
|
342
|
+
*/
|
|
343
|
+
export async function appendReport(context, { sessionID, text, signal, metadata }) {
|
|
287
344
|
const api = sessionApi(context, ['synthetic']);
|
|
288
345
|
if (!textValue(sessionID) || !textValue(text)) throw new Error('[AZPR] Report destination and text are required.');
|
|
289
346
|
const result = await cancellable(() => api.synthetic({
|
|
290
347
|
sessionID, text, description: text,
|
|
348
|
+
...(metadata ? { metadata } : {}),
|
|
291
349
|
delivery: 'queue', resume: false,
|
|
292
350
|
}), signal);
|
|
293
351
|
if (!record(result) || !textValue(result.id) || result.sessionID !== sessionID || result.type !== 'synthetic' ||
|
package/src/setup.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/** Native package bootstrap. Configuration lives outside the package cache. */
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
|
-
import { open, readFile, lstat, mkdir, link, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { open, readFile, lstat, mkdir, link, rename, stat, unlink } from 'node:fs/promises';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
|
-
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { randomUUID } from 'node:crypto';
|
|
8
|
-
import { COMMANDS, modelRef, privateAgent, validateSettings } from './config.mjs';
|
|
8
|
+
import { COMMANDS, modelRef, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
|
|
9
9
|
import { parseUniqueJSON } from './output.mjs';
|
|
10
10
|
import { appendReport } from './session.mjs';
|
|
11
11
|
import { listOf, recordOf, requireMethods } from './host.mjs';
|
|
@@ -18,6 +18,10 @@ const SETUP_DESCRIPTION = 'Set up AZPR: organization, model, PAT file; --help. U
|
|
|
18
18
|
const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL [--pat-file "/absolute/path/to/pat"]';
|
|
19
19
|
const RESTART = 'restart the OpenCode service (in a terminal: opencode service restart; if you run opencode serve yourself, restart that process)';
|
|
20
20
|
const MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
21
|
+
// A writer holds the setup lock for a few milliseconds. One this old was left behind by a process that
|
|
22
|
+
// ended while it held it: no one will release it, so nothing waits for it.
|
|
23
|
+
const LOCK_LEFT_BEHIND_MS = 30000;
|
|
24
|
+
const lockOf = path => `${path}.setup.lock`;
|
|
21
25
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
22
26
|
|
|
23
27
|
/** AZPR's directory for user files: $XDG_CONFIG_HOME/azpr, otherwise ~/.config/azpr. */
|
|
@@ -103,26 +107,31 @@ async function checkModel(context, value) {
|
|
|
103
107
|
}
|
|
104
108
|
|
|
105
109
|
async function readExisting(path) {
|
|
106
|
-
let
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
110
|
+
for (let attempt = 1; ; attempt++) {
|
|
111
|
+
let handle;
|
|
112
|
+
try {
|
|
113
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
114
|
+
const info = await handle.stat();
|
|
115
|
+
// No name left: another writer replaced the file between the open and this check. Read the file that is there now.
|
|
116
|
+
if (info.nlink === 0 && attempt < 5) continue;
|
|
117
|
+
if (!info.isFile() || info.nlink !== 1 || (typeof process.getuid === 'function' && info.uid !== process.getuid())) {
|
|
118
|
+
throw new Error('[AZPR] Setup requires a regular settings file owned by you, without hard links.');
|
|
119
|
+
}
|
|
120
|
+
if (info.size > MAX_SETTINGS_BYTES) throw new Error('[AZPR] settings.json is larger than 1 MB.');
|
|
121
|
+
return await handle.readFile('utf8');
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error.code === 'ENOENT') return null;
|
|
124
|
+
if (error.code === 'ELOOP') throw new Error('[AZPR] Setup refuses a symbolic link for settings.json.');
|
|
125
|
+
throw error;
|
|
126
|
+
} finally { await handle?.close(); }
|
|
127
|
+
}
|
|
120
128
|
}
|
|
121
129
|
|
|
122
130
|
/**
|
|
123
131
|
* Atomic, owner-only save; serialize setup calls and preserve unrelated values.
|
|
124
132
|
* Without --pat-file, a replacement keeps the PAT file already set and a first
|
|
125
|
-
* setup uses the default PAT file.
|
|
133
|
+
* setup uses the default PAT file. The file names every setting, those setup
|
|
134
|
+
* does not ask for at their defaults. Returns the saved organization and PAT file.
|
|
126
135
|
*/
|
|
127
136
|
export async function saveSetup(context, path, arguments_, environment = process.env) {
|
|
128
137
|
const previous = await readExisting(path);
|
|
@@ -141,9 +150,9 @@ export async function saveSetup(context, path, arguments_, environment = process
|
|
|
141
150
|
if (typeof patFile !== 'string' || !isAbsolute(patFile) || resolve(patFile) === resolve(path)) {
|
|
142
151
|
throw new Error('[AZPR] --pat-file must name an absolute path separate from settings.json.');
|
|
143
152
|
}
|
|
144
|
-
const next = { ...raw, models: { ...raw.models,
|
|
153
|
+
const { settings: next } = withMissingSettings({ ...raw, models: { ...raw.models,
|
|
145
154
|
review: { functional: model, risk: model, verifier: model }, quick: { reviewer: model } },
|
|
146
|
-
azure: { ...raw.azure, organization, pat: '', patFile } };
|
|
155
|
+
azure: { ...raw.azure, organization, pat: '', patFile } });
|
|
147
156
|
validateSettings(next);
|
|
148
157
|
await checkModel(context, model);
|
|
149
158
|
try { await readPatFile(patFile); }
|
|
@@ -153,19 +162,39 @@ export async function saveSetup(context, path, arguments_, environment = process
|
|
|
153
162
|
const problem = error.message.replace(/^\[AZPR\] azure\.patFile /, '');
|
|
154
163
|
throw new Error(`[AZPR] No --pat-file was given, and the ${kept ? 'PAT file in the current settings' : 'default PAT file'} ${patFile} ${problem} Create it as the quickstart shows, or name another file with --pat-file.`);
|
|
155
164
|
}
|
|
165
|
+
await writeSettings(path, previous, next);
|
|
166
|
+
return { organization, patFile };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Replace the settings file (or create it, when `previous` is null) atomically and owner-only, under
|
|
171
|
+
* the setup lock, and only while the file still is what `previous` was. The errors of a held lock and
|
|
172
|
+
* of a file changed meanwhile are marked `busy`: someone else is writing the file.
|
|
173
|
+
*
|
|
174
|
+
* The lock keeps other AZPR writers out, not a person's editor. The file is therefore compared with
|
|
175
|
+
* `previous` once more after the new text is ready, right before it takes the file's place: what
|
|
176
|
+
* someone saved while that text was written is not overwritten.
|
|
177
|
+
*/
|
|
178
|
+
async function writeSettings(path, previous, settings, prepared) {
|
|
156
179
|
const parent = dirname(path);
|
|
157
180
|
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
158
181
|
const parentInfo = await lstat(parent);
|
|
159
182
|
if (!parentInfo.isDirectory() || (parentInfo.mode & 0o022) || (typeof process.getuid === 'function' && parentInfo.uid !== process.getuid())) {
|
|
160
183
|
throw new Error('[AZPR] The settings directory must be a directory owned by you, not a symbolic link or writable by other users.');
|
|
161
184
|
}
|
|
162
|
-
const lock =
|
|
185
|
+
const lock = lockOf(path), temporary = `${path}.${randomUUID()}.tmp`;
|
|
186
|
+
const changed = () => Object.assign(new Error('[AZPR] Settings changed during setup; retry after reviewing the file.'), { busy: true });
|
|
163
187
|
let handle, acquired = false;
|
|
164
188
|
try {
|
|
165
189
|
try { handle = await open(lock, 'wx', 0o600); acquired = true; }
|
|
166
|
-
catch (error) {
|
|
167
|
-
|
|
168
|
-
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error.code !== 'EEXIST') throw error;
|
|
192
|
+
throw Object.assign(new Error(`[AZPR] Another setup is active, or its lock was left behind (if none is running, delete ${basename(lock)} beside the settings file). No settings changed.`), { busy: true });
|
|
193
|
+
}
|
|
194
|
+
if (await readExisting(path) !== previous) throw changed();
|
|
195
|
+
await writeTemporary(temporary, settingsText(settings));
|
|
196
|
+
await prepared?.();
|
|
197
|
+
if (await readExisting(path) !== previous) throw changed();
|
|
169
198
|
if (previous === null) await link(temporary, path); // Refuse a concurrent creator rather than overwriting it.
|
|
170
199
|
else await rename(temporary, path);
|
|
171
200
|
} finally {
|
|
@@ -173,7 +202,6 @@ export async function saveSetup(context, path, arguments_, environment = process
|
|
|
173
202
|
await handle?.close();
|
|
174
203
|
if (acquired) await unlink(lock);
|
|
175
204
|
}
|
|
176
|
-
return { organization, patFile };
|
|
177
205
|
}
|
|
178
206
|
|
|
179
207
|
async function writeTemporary(path, text) {
|
|
@@ -181,6 +209,65 @@ async function writeTemporary(path, text) {
|
|
|
181
209
|
try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
|
|
182
210
|
}
|
|
183
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Write the settings a valid settings file leaves out into it, at their defaults, so that a version
|
|
214
|
+
* which brings a new setting shows it where its user edits the others. The defaults are what
|
|
215
|
+
* validation assumes for a missing setting anyway: the completed file behaves as the file did.
|
|
216
|
+
* Values, their order and unrelated names stay; the file is replaced like a setup's (atomic,
|
|
217
|
+
* owner-only, a regular file of the user's own, never through a symbolic link).
|
|
218
|
+
*
|
|
219
|
+
* This runs when OpenCode loads AZPR, before the settings are read for good, and never fails a load:
|
|
220
|
+
* a file that cannot be rewritten is used as it is. Several processes and project instances load
|
|
221
|
+
* AZPR at once; they would write the same text, and one that finds another writing waits for it
|
|
222
|
+
* and reads the result, so that each ends up with the file as it then stays. A load that stops
|
|
223
|
+
* waiting reads the file as it is; the runtime accepts the completed text when it appears later
|
|
224
|
+
* (see its preflight), so a slow writer never leaves commands refused.
|
|
225
|
+
*
|
|
226
|
+
* Returns `added` (the names written, possibly none) or, when the file could not be completed,
|
|
227
|
+
* `missing` (the names it lacks) with `problem`, which never holds a setting's value.
|
|
228
|
+
* `prepared` (offline tests only) runs once the new text is ready, before it replaces the file.
|
|
229
|
+
*/
|
|
230
|
+
export async function addMissingSettings(path, { waitMs = 3000, pauseMs = 100, prepared } = {}) {
|
|
231
|
+
const deadline = Date.now() + waitMs;
|
|
232
|
+
let missing = [];
|
|
233
|
+
try {
|
|
234
|
+
for (;;) {
|
|
235
|
+
const previous = await readExisting(path);
|
|
236
|
+
if (previous === null) return { added: [] };
|
|
237
|
+
const raw = settingsJSON(previous);
|
|
238
|
+
// Switched off, also since this load began: AZPR does nothing, also not to the file.
|
|
239
|
+
if (raw.enabled === false) return { added: [] };
|
|
240
|
+
const { settings, added } = withMissingSettings(raw);
|
|
241
|
+
if (!added.length) return { added: [] };
|
|
242
|
+
// A file that cannot be used is its user's to repair: nothing is added around the problem.
|
|
243
|
+
try { validateSettings(raw); validateSettings(settings); } catch { return { added: [] }; }
|
|
244
|
+
missing = added;
|
|
245
|
+
try {
|
|
246
|
+
await writeSettings(path, previous, settings, prepared);
|
|
247
|
+
return { added };
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (!error.busy || Date.now() >= deadline) throw error;
|
|
250
|
+
// A lock no live writer holds will not go away: do not wait for it.
|
|
251
|
+
const held = await stat(lockOf(path)).catch(() => null);
|
|
252
|
+
if (held && Date.now() - held.mtimeMs > LOCK_LEFT_BEHIND_MS) throw error;
|
|
253
|
+
await new Promise(done => setTimeout(done, pauseMs));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
} catch (error) {
|
|
257
|
+
// What the file lacks now, read as the runtime reads it: a file this refuses to replace (a symbolic link, a
|
|
258
|
+
// hard link) is still used, and another load may have completed the file since this one last looked.
|
|
259
|
+
try {
|
|
260
|
+
const raw = settingsJSON(await readFile(path, 'utf8'));
|
|
261
|
+
validateSettings(raw);
|
|
262
|
+
missing = raw.enabled === false ? [] : withMissingSettings(raw).added;
|
|
263
|
+
} catch { /* The runtime reports a file it cannot use; what was known of it stays. */ }
|
|
264
|
+
if (!missing.length) return { added: [] };
|
|
265
|
+
// Names and error codes only: an OS or parser message may quote the file.
|
|
266
|
+
const own = typeof error?.message === 'string' && error.message.startsWith('[AZPR] ');
|
|
267
|
+
return { added: [], missing, problem: own ? error.message.slice(7) : `the file could not be rewritten (${error?.code ?? 'unknown error'}).` };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
184
271
|
async function guide(context, path, problem, environment) {
|
|
185
272
|
let catalog = [], patFile;
|
|
186
273
|
try { catalog = (listOf(await context.model.list()) ?? []).filter(item => item.enabled !== false && item.capabilities?.tools === true); } catch { /* Help remains usable before provider setup. */ }
|
|
@@ -218,7 +305,7 @@ async function settingsProblem(path) {
|
|
|
218
305
|
|
|
219
306
|
/** Missing/invalid settings expose only setup and blocked command explanations, with the reason. */
|
|
220
307
|
export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, testOptions = {}) {
|
|
221
|
-
const { environment = process.env, ...runtimeOptions } = testOptions;
|
|
308
|
+
const { environment = process.env, settingsWaitMs, ...runtimeOptions } = testOptions;
|
|
222
309
|
const path = await settingsFileFor(context.options ?? {}, sourceDirectory, environment);
|
|
223
310
|
const { problem, disabled } = await settingsProblem(path);
|
|
224
311
|
const blocked = Boolean(problem);
|
|
@@ -258,7 +345,13 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
|
|
|
258
345
|
} });
|
|
259
346
|
});
|
|
260
347
|
let cleanup;
|
|
261
|
-
try {
|
|
348
|
+
try {
|
|
349
|
+
if (!blocked) {
|
|
350
|
+
// Before the runtime reads the settings for good: it compares later reads with this one.
|
|
351
|
+
const completion = await addMissingSettings(path, settingsWaitMs === undefined ? {} : { waitMs: settingsWaitMs, pauseMs: 10 });
|
|
352
|
+
cleanup = await setupAzurePrReview(context, sourceDirectory, { ...runtimeOptions, settingsPath: path, settingsCompletion: completion });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
262
355
|
catch (error) { await registration.dispose(); throw error; }
|
|
263
356
|
return async () => { await cleanup?.(); await registration.dispose(); };
|
|
264
357
|
}
|
package/src/store.mjs
CHANGED
|
@@ -18,6 +18,8 @@ const RECEIPT_LIMIT = 50;
|
|
|
18
18
|
const STALE_DATA_MS = 24 * 60 * 60 * 1000;
|
|
19
19
|
const FORMAT = 1;
|
|
20
20
|
const ATTEMPT_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
|
|
21
|
+
// Marks a record of sessions that should be gone and could not be deleted. Run and review IDs are hexadecimal.
|
|
22
|
+
const RETRY = 'retry';
|
|
21
23
|
|
|
22
24
|
export function stateRoot(env = process.env) {
|
|
23
25
|
const base = isAbsolute(env.XDG_STATE_HOME ?? '') ? env.XDG_STATE_HOME : join(homedir(), '.local', 'state');
|
|
@@ -27,15 +29,20 @@ export function stateRoot(env = process.env) {
|
|
|
27
29
|
const checksum = value => createHash('sha256').update(value).digest('hex');
|
|
28
30
|
const inside = (root, path) => { const rel = relative(root, path); return rel && !rel.startsWith('..') && !isAbsolute(rel); };
|
|
29
31
|
|
|
30
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Plain JSON form of a review; Sets and Maps become arrays. `closingSessions`
|
|
34
|
+
* (sessions whose deletion was asked for and never answered) is written only
|
|
35
|
+
* when there are any.
|
|
36
|
+
*/
|
|
31
37
|
export function serializeReview(review) {
|
|
32
|
-
const { data, reportSessions, publication, ...rest } = review;
|
|
33
|
-
return { ...rest, reportSessions: [...(reportSessions ?? [])],
|
|
34
|
-
dataDirectory: review.dataDirectory ?? null };
|
|
38
|
+
const { data, reportSessions, closingSessions, publication, ...rest } = review;
|
|
39
|
+
return { ...rest, reportSessions: [...(reportSessions ?? [])], ...(closingSessions?.size ? { closingSessions: [...closingSessions] } : {}),
|
|
40
|
+
publication: [...(publication ?? new Map())], dataDirectory: review.dataDirectory ?? null };
|
|
35
41
|
}
|
|
36
42
|
|
|
37
43
|
export function deserializeReview(value) {
|
|
38
|
-
return { ...value, reportSessions: new Set(value.reportSessions ?? []),
|
|
44
|
+
return { ...value, reportSessions: new Set(value.reportSessions ?? []), ...(value.closingSessions ? { closingSessions: new Set(value.closingSessions) } : {}),
|
|
45
|
+
publication: new Map(value.publication ?? []) };
|
|
39
46
|
}
|
|
40
47
|
|
|
41
48
|
/**
|
|
@@ -72,8 +79,12 @@ async function writeAtomic(path, content) {
|
|
|
72
79
|
}
|
|
73
80
|
|
|
74
81
|
/**
|
|
75
|
-
* `onRemove(review)` runs
|
|
76
|
-
* deleted
|
|
82
|
+
* `onRemove(review)` runs before an evicted or removed review's files are
|
|
83
|
+
* deleted, to delete its reviewer sessions: the review's record is what names
|
|
84
|
+
* them, so it stays until they are dealt with, and a process that ends
|
|
85
|
+
* meanwhile finds the review again. When it returns false (sessions that are
|
|
86
|
+
* still there could not be put on record elsewhere) the review stays for a
|
|
87
|
+
* later attempt; its errors are ignored.
|
|
77
88
|
*/
|
|
78
89
|
export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIMIT, now = () => Date.now(), onRemove } = {}) {
|
|
79
90
|
const dirs = { reviews: join(root, 'reviews'), data: join(root, 'data'), receipts: join(root, 'receipts'), sessions: join(root, 'sessions'), attempts: join(root, 'attempts') };
|
|
@@ -94,10 +105,27 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
|
|
|
94
105
|
return reviews.sort((a, b) => String(a.completedAt ?? '').localeCompare(String(b.completedAt ?? '')));
|
|
95
106
|
}
|
|
96
107
|
|
|
108
|
+
// One record of sessions per key: written, replaced in its place, or removed by an empty list.
|
|
109
|
+
async function recordSessions(key, sessionIDs) {
|
|
110
|
+
const own = (await readdir(dirs.sessions)).filter(name => name.endsWith(`-${key}.json`)).sort();
|
|
111
|
+
const record = own.at(-1) ?? `${new Date(now()).toISOString().replace(/[:.]/g, '-')}-${key}.json`;
|
|
112
|
+
for (const other of own.slice(0, -1)) await rm(join(dirs.sessions, other), { force: true });
|
|
113
|
+
if (sessionIDs.length) await writeAtomic(join(dirs.sessions, record), JSON.stringify(sessionIDs));
|
|
114
|
+
else await rm(join(dirs.sessions, record), { force: true });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// A record's name ends with its ID; the ID of a record of sessions still to be deleted starts with RETRY.
|
|
118
|
+
const idOf = name => name.slice(name.lastIndexOf('-') + 1, -'.json'.length);
|
|
119
|
+
const isRetry = name => idOf(name).startsWith(RETRY);
|
|
120
|
+
|
|
121
|
+
/** Remove a review and its data, after `onRemove`; false when `onRemove` kept it. */
|
|
97
122
|
async function removeReview(review) {
|
|
123
|
+
let settled = true;
|
|
124
|
+
try { settled = (await onRemove?.(review)) !== false; } catch { /* Cleanup never fails an eviction. */ }
|
|
125
|
+
if (!settled) return false;
|
|
98
126
|
await rm(join(dirs.reviews, `${review.id}.json`), { force: true });
|
|
99
127
|
if (review.dataDirectory && inside(dirs.data, review.dataDirectory)) await rm(review.dataDirectory, { recursive: true, force: true });
|
|
100
|
-
|
|
128
|
+
return true;
|
|
101
129
|
}
|
|
102
130
|
|
|
103
131
|
return {
|
|
@@ -113,12 +141,17 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
|
|
|
113
141
|
const body = JSON.stringify(serializeReview(review));
|
|
114
142
|
await writeAtomic(join(dirs.reviews, `${review.id}.json`), JSON.stringify({ format: FORMAT, sha256: checksum(body), body }));
|
|
115
143
|
},
|
|
116
|
-
/**
|
|
117
|
-
|
|
144
|
+
/**
|
|
145
|
+
* Remove the oldest reviews on disk beyond the limit; returns evicted IDs.
|
|
146
|
+
* `inUse(id)` names reviews a command is working on, which stay.
|
|
147
|
+
*/
|
|
148
|
+
async enforceLimit(inUse = () => false) {
|
|
118
149
|
const reviews = await listReviews();
|
|
119
|
-
const evicted =
|
|
120
|
-
for (const review of
|
|
121
|
-
|
|
150
|
+
const evicted = [];
|
|
151
|
+
for (const review of reviews.slice(0, Math.max(0, reviews.length - limit))) {
|
|
152
|
+
if (!inUse(review.id) && await removeReview(review)) evicted.push(review.id);
|
|
153
|
+
}
|
|
154
|
+
return evicted;
|
|
122
155
|
},
|
|
123
156
|
remove: removeReview,
|
|
124
157
|
/** Delete stale unreferenced data and legacy temporary directories. */
|
|
@@ -147,22 +180,58 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
|
|
|
147
180
|
return removed;
|
|
148
181
|
},
|
|
149
182
|
/**
|
|
150
|
-
* Remember reviewer sessions
|
|
151
|
-
*
|
|
152
|
-
*
|
|
183
|
+
* Remember the reviewer sessions a run that left no saved review keeps
|
|
184
|
+
* on purpose, such as the one holding its draft; the newest `limit` runs
|
|
185
|
+
* keep theirs. A run has one record: a later call replaces its earlier
|
|
186
|
+
* one and keeps its place in the order, and an empty list removes it.
|
|
187
|
+
*/
|
|
188
|
+
keepSessions: (runId, sessionIDs) => recordSessions(runId, sessionIDs),
|
|
189
|
+
/**
|
|
190
|
+
* Remember sessions that are still to be deleted, under the ID of the
|
|
191
|
+
* run or review they belonged to: those a cleanup is about to delete,
|
|
192
|
+
* then those it could not delete. They are due at every pass
|
|
193
|
+
* (`expiredSessions`) and do not count against the limit. One record per
|
|
194
|
+
* ID, replaced by a later call and removed by an empty list.
|
|
153
195
|
*/
|
|
154
|
-
|
|
155
|
-
|
|
196
|
+
retrySessions: (id, sessionIDs) => recordSessions(`${RETRY}${id}`, sessionIDs),
|
|
197
|
+
/**
|
|
198
|
+
* The sessions that are due to go, one entry per run or review, as
|
|
199
|
+
* { runId, sessionIDs, kept }: those still to be deleted, due at every
|
|
200
|
+
* pass, and the kept sessions of runs beyond the newest `limit` (`kept`),
|
|
201
|
+
* oldest first. A run with both has one entry, so that what is left of it
|
|
202
|
+
* is recorded once. `inUse(runId)` names runs whose command has not
|
|
203
|
+
* ended: their own cleanup deals with their sessions, so both of their
|
|
204
|
+
* records are left out, whatever their age. The records stay: the caller
|
|
205
|
+
* deletes the sessions, records what is left (`retrySessions`) and only
|
|
206
|
+
* then removes a kept record (`keepSessions`). An unreadable record
|
|
207
|
+
* names nothing and is removed.
|
|
208
|
+
*/
|
|
209
|
+
async expiredSessions(inUse = () => false) {
|
|
156
210
|
const files = (await readdir(dirs.sessions)).filter(name => name.endsWith('.json')).sort();
|
|
157
|
-
const
|
|
158
|
-
for (const
|
|
211
|
+
const kept = files.filter(name => !isRetry(name)), due = new Map();
|
|
212
|
+
for (const name of [...files.filter(isRetry), ...kept.slice(0, Math.max(0, kept.length - limit))]) {
|
|
213
|
+
const retry = isRetry(name), runId = retry ? idOf(name).slice(RETRY.length) : idOf(name);
|
|
214
|
+
if (inUse(runId)) continue;
|
|
215
|
+
let ids;
|
|
216
|
+
try { ids = JSON.parse(await readFile(join(dirs.sessions, name), 'utf8')); } catch { ids = null; }
|
|
217
|
+
if (!Array.isArray(ids)) { await rm(join(dirs.sessions, name), { force: true }); continue; }
|
|
218
|
+
const entry = due.get(runId) ?? { runId, sessionIDs: [], kept: false };
|
|
219
|
+
for (const id of ids) if (typeof id === 'string' && !entry.sessionIDs.includes(id)) entry.sessionIDs.push(id);
|
|
220
|
+
if (!retry) entry.kept = true;
|
|
221
|
+
due.set(runId, entry);
|
|
222
|
+
}
|
|
223
|
+
return [...due.values()];
|
|
224
|
+
},
|
|
225
|
+
/** Every session the records name, as { kept, due }: kept on purpose by an unfinished run, and still to be deleted. */
|
|
226
|
+
async recordedSessions() {
|
|
227
|
+
const kept = [], due = [];
|
|
228
|
+
for (const name of (await readdir(dirs.sessions).catch(() => [])).filter(file => file.endsWith('.json'))) {
|
|
159
229
|
try {
|
|
160
|
-
const ids = JSON.parse(await readFile(join(dirs.sessions,
|
|
161
|
-
if (Array.isArray(ids))
|
|
162
|
-
} catch { /* An unreadable record
|
|
163
|
-
await rm(join(dirs.sessions, old), { force: true });
|
|
230
|
+
const ids = JSON.parse(await readFile(join(dirs.sessions, name), 'utf8'));
|
|
231
|
+
if (Array.isArray(ids)) (isRetry(name) ? due : kept).push(...ids.filter(id => typeof id === 'string'));
|
|
232
|
+
} catch { /* An unreadable record names nothing. */ }
|
|
164
233
|
}
|
|
165
|
-
return
|
|
234
|
+
return { kept, due };
|
|
166
235
|
},
|
|
167
236
|
/**
|
|
168
237
|
* Thread-creation attempts of one PR, keyed by comment marker and shared by
|