@wyattjoh/rfc 0.1.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.
@@ -0,0 +1,429 @@
1
+ import {
2
+ ConfigurationError,
3
+ createRfcClient,
4
+ decodeCitationVerificationRequest,
5
+ decodeResearchRequest,
6
+ schemaVersion,
7
+ toErrorEnvelope,
8
+ type CitationVerificationRequest,
9
+ type CitationVerificationResult,
10
+ type ErrorEnvelope,
11
+ type EvidenceBundle,
12
+ type ResearchRequest,
13
+ type RfcClient,
14
+ type RfcSourceCacheRemoveResult,
15
+ type RfcSourceCacheStatus,
16
+ } from "@wyattjoh/rfc-core";
17
+ import { automaticAnswerActivationFor, readCliConfig } from "./config";
18
+ import {
19
+ CredentialInputError,
20
+ CredentialMissingError,
21
+ CredentialStoreError,
22
+ resolveStoredCredential,
23
+ storedCredentialStatus,
24
+ type AuthStatus,
25
+ type CredentialStore,
26
+ } from "./credentials";
27
+ import type { UsageRecorder } from "./usage-store";
28
+
29
+ /**
30
+ * Trusted process configuration applied to one RFC operation.
31
+ */
32
+ export interface RfcOperationOptions {
33
+ /**
34
+ * Directory containing cached canonical RFC sources.
35
+ */
36
+ readonly cacheDirectory: string;
37
+ /**
38
+ * Optional Datatracker API base URL selected by the process operator.
39
+ */
40
+ readonly datatrackerApiUrl: string | undefined;
41
+ /**
42
+ * Optional TypeSafe API URL selected by the process operator.
43
+ */
44
+ readonly typeSafeApiUrl: string | undefined;
45
+ }
46
+
47
+ /**
48
+ * Injectable side effects shared by CLI and MCP operations.
49
+ */
50
+ export interface RfcOperationDependencies {
51
+ /**
52
+ * Credential boundary used for provider construction and safe status checks.
53
+ */
54
+ readonly credentialStore: CredentialStore;
55
+ /**
56
+ * Persist one successful semantic operation in the per-user usage totals.
57
+ */
58
+ readonly recordUsage: UsageRecorder;
59
+ /**
60
+ * Construct the RFC client for one operation.
61
+ */
62
+ readonly createClient: typeof createRfcClient;
63
+ }
64
+
65
+ /**
66
+ * Safe warning emitted when a successful semantic operation cannot update usage totals.
67
+ */
68
+ export interface RfcOperationWarning {
69
+ /**
70
+ * Public protocol version.
71
+ */
72
+ readonly schemaVersion: typeof schemaVersion;
73
+ /**
74
+ * Identifies a non-fatal operation warning.
75
+ */
76
+ readonly kind: "warning";
77
+ /**
78
+ * Stable warning code and safe message.
79
+ */
80
+ readonly warning: {
81
+ readonly code: "usage_accounting_failed";
82
+ readonly message: string;
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Successful operation value plus any non-fatal warnings produced after it completed.
88
+ */
89
+ export interface RfcOperationResult<A> {
90
+ /**
91
+ * Validated operation result.
92
+ */
93
+ readonly value: A;
94
+ /**
95
+ * Non-fatal warnings that callers should surface without encouraging a retry.
96
+ */
97
+ readonly warnings: ReadonlyArray<RfcOperationWarning>;
98
+ }
99
+
100
+ const usageAccountingWarning = Object.freeze({
101
+ schemaVersion,
102
+ kind: "warning",
103
+ warning: {
104
+ code: "usage_accounting_failed",
105
+ message: "Unable to update the per-user RFC usage totals",
106
+ },
107
+ } as const satisfies RfcOperationWarning);
108
+
109
+ const renderTokenCount = (value: number | null): string => value?.toString() ?? "unavailable";
110
+
111
+ /**
112
+ * Render an estimated USD value consistently across CLI output.
113
+ *
114
+ * @param value Estimated cost, or null when pricing is unavailable.
115
+ * @returns A dollar value with fixed sub-cent precision or `unavailable`.
116
+ */
117
+ export const renderEstimatedUsd = (value: number | null): string =>
118
+ value === null ? "unavailable" : `$${value.toFixed(9)}`;
119
+
120
+ const credentialErrorEnvelope = (error: unknown): ErrorEnvelope | undefined => {
121
+ if (error instanceof CredentialMissingError) {
122
+ return {
123
+ schemaVersion,
124
+ kind: "error",
125
+ error: {
126
+ code: "credential_missing",
127
+ message: "No TypeSafe API key is configured; run `rfc auth add`",
128
+ },
129
+ };
130
+ }
131
+
132
+ if (error instanceof CredentialInputError) {
133
+ return {
134
+ schemaVersion,
135
+ kind: "error",
136
+ error: {
137
+ code: "invalid_input",
138
+ message: "The TypeSafe API key input is invalid",
139
+ },
140
+ };
141
+ }
142
+
143
+ if (error instanceof CredentialStoreError) {
144
+ const messages = {
145
+ unavailable: "The platform credential store is unavailable",
146
+ denied: "Access to the platform credential store was denied",
147
+ storage: "Unable to store the TypeSafe API key",
148
+ deletion: "Unable to remove the TypeSafe API key",
149
+ } as const;
150
+ const codes = {
151
+ unavailable: "credential_store_unavailable",
152
+ denied: "credential_access_denied",
153
+ storage: "credential_storage_failed",
154
+ deletion: "credential_deletion_failed",
155
+ } as const;
156
+ return {
157
+ schemaVersion,
158
+ kind: "error",
159
+ error: {
160
+ code: codes[error.kind],
161
+ message: messages[error.kind],
162
+ },
163
+ };
164
+ }
165
+
166
+ return undefined;
167
+ };
168
+
169
+ const withClient = async <A>(
170
+ create: () => Promise<RfcClient>,
171
+ use: (client: RfcClient) => Promise<A>,
172
+ ): Promise<A> => {
173
+ const client = await create();
174
+ try {
175
+ return await use(client);
176
+ } finally {
177
+ await client.close();
178
+ }
179
+ };
180
+
181
+ const readOperationConfig = () => {
182
+ try {
183
+ return readCliConfig();
184
+ } catch (error) {
185
+ throw new ConfigurationError({
186
+ reason: error instanceof Error ? error.message : "Unknown configuration error",
187
+ });
188
+ }
189
+ };
190
+
191
+ const createSemanticClient = async (
192
+ options: RfcOperationOptions,
193
+ dependencies: RfcOperationDependencies,
194
+ ): Promise<RfcClient> => {
195
+ const cliConfig = readOperationConfig();
196
+ const apiKey = await resolveStoredCredential(dependencies.credentialStore);
197
+ return dependencies.createClient({
198
+ cacheDirectory: options.cacheDirectory,
199
+ datatrackerApiUrl: options.datatrackerApiUrl,
200
+ modelAlias: cliConfig.modelAlias,
201
+ policyPreset: cliConfig.policyPreset,
202
+ automaticAnswerActivation: automaticAnswerActivationFor(cliConfig),
203
+ typeSafeApiKey: apiKey,
204
+ typeSafeApiUrl: options.typeSafeApiUrl,
205
+ });
206
+ };
207
+
208
+ const recordResultUsage = async (
209
+ dependencies: RfcOperationDependencies,
210
+ inputTokens: number | null,
211
+ estimatedInputCostUsd: number | null,
212
+ ): Promise<ReadonlyArray<RfcOperationWarning>> => {
213
+ try {
214
+ await dependencies.recordUsage({ inputTokens, estimatedInputCostUsd });
215
+ return [];
216
+ } catch {
217
+ return [usageAccountingWarning];
218
+ }
219
+ };
220
+
221
+ /**
222
+ * Map an operation failure to the safe versioned error contract shared by CLI and MCP.
223
+ *
224
+ * @param error Rejected operation value.
225
+ * @returns An envelope that never contains credential values or unsafe platform details.
226
+ */
227
+ export const toRfcOperationErrorEnvelope = (error: unknown): ErrorEnvelope =>
228
+ credentialErrorEnvelope(error) ?? toErrorEnvelope(error);
229
+
230
+ /**
231
+ * Research one validated known-RFC or topic request.
232
+ *
233
+ * @param request Unknown input decoded through the public version-two request schema.
234
+ * @param options Trusted process configuration.
235
+ * @param dependencies Injectable operation boundaries.
236
+ * @returns The evidence bundle and any non-fatal usage warning.
237
+ */
238
+ export const executeResearch = async (
239
+ request: ResearchRequest | unknown,
240
+ options: RfcOperationOptions,
241
+ dependencies: RfcOperationDependencies,
242
+ ): Promise<RfcOperationResult<EvidenceBundle>> => {
243
+ const decoded = decodeResearchRequest(request);
244
+ const value = await withClient(
245
+ () => createSemanticClient(options, dependencies),
246
+ (client) => client.research(decoded),
247
+ );
248
+ return {
249
+ value,
250
+ warnings: await recordResultUsage(
251
+ dependencies,
252
+ value.diagnostics.usage.inputTokens,
253
+ value.diagnostics.inputCost.estimatedUsd,
254
+ ),
255
+ };
256
+ };
257
+
258
+ /**
259
+ * Verify one validated factual claim against one exact RFC quotation.
260
+ *
261
+ * @param request Unknown input decoded through the public version-two citation schema.
262
+ * @param options Trusted process configuration.
263
+ * @param dependencies Injectable operation boundaries.
264
+ * @returns The citation verdict and any non-fatal usage warning.
265
+ */
266
+ export const executeCitationVerification = async (
267
+ request: CitationVerificationRequest | unknown,
268
+ options: RfcOperationOptions,
269
+ dependencies: RfcOperationDependencies,
270
+ ): Promise<RfcOperationResult<CitationVerificationResult>> => {
271
+ const decoded = decodeCitationVerificationRequest(request);
272
+ const value = await withClient(
273
+ () => createSemanticClient(options, dependencies),
274
+ (client) => client.verifyCitation(decoded),
275
+ );
276
+ return {
277
+ value,
278
+ warnings: await recordResultUsage(
279
+ dependencies,
280
+ value.diagnostics.usage.inputTokens,
281
+ value.diagnostics.inputCost.estimatedUsd,
282
+ ),
283
+ };
284
+ };
285
+
286
+ /**
287
+ * Inspect one named RFC source-cache entry without network access.
288
+ *
289
+ * @param rfc RFC identifier to inspect.
290
+ * @param options Trusted process configuration.
291
+ * @param dependencies Injectable operation boundaries.
292
+ * @returns Local source-cache status.
293
+ */
294
+ export const executeSourceCacheStatus = (
295
+ rfc: string,
296
+ options: RfcOperationOptions,
297
+ dependencies: RfcOperationDependencies,
298
+ ): Promise<RfcSourceCacheStatus> =>
299
+ withClient(
300
+ () =>
301
+ dependencies.createClient({
302
+ cacheDirectory: options.cacheDirectory,
303
+ modelAlias: undefined,
304
+ automaticAnswerActivation: undefined,
305
+ typeSafeApiKey: undefined,
306
+ typeSafeApiUrl: undefined,
307
+ }),
308
+ (client) => client.sourceCacheStatus(rfc),
309
+ );
310
+
311
+ /**
312
+ * Remove one named RFC source-cache entry without network access.
313
+ *
314
+ * @param rfc RFC identifier to remove.
315
+ * @param options Trusted process configuration.
316
+ * @param dependencies Injectable operation boundaries.
317
+ * @returns Whether the named entry existed and was removed.
318
+ */
319
+ export const executeSourceCacheRemove = (
320
+ rfc: string,
321
+ options: RfcOperationOptions,
322
+ dependencies: RfcOperationDependencies,
323
+ ): Promise<RfcSourceCacheRemoveResult> =>
324
+ withClient(
325
+ () =>
326
+ dependencies.createClient({
327
+ cacheDirectory: options.cacheDirectory,
328
+ modelAlias: undefined,
329
+ automaticAnswerActivation: undefined,
330
+ typeSafeApiKey: undefined,
331
+ typeSafeApiUrl: undefined,
332
+ }),
333
+ (client) => client.sourceCacheRemove(rfc),
334
+ );
335
+
336
+ /**
337
+ * Inspect safe TypeSafe credential metadata without revealing the credential.
338
+ *
339
+ * @param dependencies Injectable operation boundaries.
340
+ * @returns Whether the stable credential identity is configured.
341
+ */
342
+ export const executeAuthStatus = (dependencies: RfcOperationDependencies): Promise<AuthStatus> =>
343
+ storedCredentialStatus(dependencies.credentialStore);
344
+
345
+ /**
346
+ * Render one evidence bundle for concise agent or human consumption.
347
+ *
348
+ * @param result Version-two evidence bundle.
349
+ * @returns Multi-line text preserving statuses, qualifications, provenance, and cost.
350
+ */
351
+ export const renderEvidenceBundle = (result: EvidenceBundle): string => {
352
+ const lines = [`Status: ${result.status}`, `RFC: ${result.rfc?.identifier ?? "none discovered"}`];
353
+ for (const context of result.contexts ?? []) {
354
+ lines.push(`Context: ${context.role} ${context.document.identifier} (${context.state})`);
355
+ }
356
+ for (const passage of result.evidence) {
357
+ lines.push(
358
+ `Evidence RFC: ${passage.provenance.identifier} (${passage.context} context)`,
359
+ `Section: ${passage.provenance.section ?? "unknown"}`,
360
+ `Quote: ${passage.quote}`,
361
+ `Source: ${passage.provenance.sourceUrl}`,
362
+ `Offsets: ${passage.provenance.startOffset}-${passage.provenance.endOffset} (${passage.provenance.offsetUnit})`,
363
+ );
364
+ }
365
+ for (const candidate of result.reviewCandidates ?? []) {
366
+ lines.push(
367
+ "Review candidate: not accepted evidence",
368
+ `Candidate RFC: ${candidate.provenance.identifier} (${candidate.context} context)`,
369
+ `Section: ${candidate.provenance.section ?? "unknown"}`,
370
+ `Quote: ${candidate.quote}`,
371
+ `Source: ${candidate.provenance.sourceUrl}`,
372
+ `Offsets: ${candidate.provenance.startOffset}-${candidate.provenance.endOffset} (${candidate.provenance.offsetUnit})`,
373
+ );
374
+ }
375
+ lines.push(
376
+ `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
377
+ `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
378
+ );
379
+ return lines.join("\n");
380
+ };
381
+
382
+ /**
383
+ * Render one citation-verification result for concise agent or human consumption.
384
+ *
385
+ * @param result Version-two citation verdict.
386
+ * @returns Multi-line text preserving verdict, provenance, and cost.
387
+ */
388
+ export const renderCitationVerification = (result: CitationVerificationResult): string =>
389
+ [
390
+ `Verdict: ${result.verdict}`,
391
+ `RFC: ${result.rfc.identifier}`,
392
+ `Quote: ${result.quote}`,
393
+ `Offsets: ${result.provenance.startOffset ?? "unknown"}-${result.provenance.endOffset ?? "unknown"}`,
394
+ `Section: ${result.provenance.section ?? "unknown"}`,
395
+ `Source: ${result.provenance.sourceUrl}`,
396
+ `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
397
+ `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
398
+ ].join("\n");
399
+
400
+ /**
401
+ * Render one local source-cache status.
402
+ *
403
+ * @param result Version-two source-cache status.
404
+ * @returns Concise multi-line status text.
405
+ */
406
+ export const renderSourceCacheStatus = (result: RfcSourceCacheStatus): string =>
407
+ `RFC: ${result.rfc}\nCache: ${result.state}`;
408
+
409
+ /**
410
+ * Render one local source-cache removal result.
411
+ *
412
+ * @param result Version-two source-cache removal result.
413
+ * @returns Concise multi-line removal text.
414
+ */
415
+ export const renderSourceCacheRemove = (result: RfcSourceCacheRemoveResult): string =>
416
+ `RFC: ${result.rfc}\nCache: ${result.removed ? "removed" : "missing"}`;
417
+
418
+ /**
419
+ * Render safe credential status metadata.
420
+ *
421
+ * @param result Version-two credential status.
422
+ * @returns Concise multi-line credential status text.
423
+ */
424
+ export const renderAuthStatus = (result: AuthStatus): string =>
425
+ [
426
+ `Credential: ${result.configured ? "configured" : "not configured"}`,
427
+ `Service: ${result.service}`,
428
+ `Name: ${result.name}`,
429
+ ].join("\n");
@@ -0,0 +1,245 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, stat, unlink, type FileHandle } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { Schema } from "effect";
6
+
7
+ const lockRetryMilliseconds = 10;
8
+ const lockAttemptLimit = 200;
9
+ const staleLockMilliseconds = 30_000;
10
+ const usdPrecision = 1_000_000_000_000;
11
+
12
+ const NonNegativeFiniteSchema = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0));
13
+
14
+ /**
15
+ * Default per-user file containing cumulative RFC CLI usage.
16
+ */
17
+ export const defaultUsageFile = join(homedir(), ".config", "rfc", "usage.json");
18
+
19
+ /**
20
+ * Schema for the cumulative per-user RFC CLI usage file.
21
+ */
22
+ export const UsageTotalsSchema = Schema.Struct({
23
+ schemaVersion: Schema.Literal(1),
24
+ kind: Schema.Literal("rfc_usage_totals"),
25
+ updatedAt: Schema.String,
26
+ operations: Schema.Natural,
27
+ pricedOperations: Schema.Natural,
28
+ unpricedOperations: Schema.Natural,
29
+ operationsWithoutInputTokens: Schema.Natural,
30
+ inputTokens: Schema.Natural,
31
+ pricedInputTokens: Schema.Natural,
32
+ unpricedInputTokens: Schema.Natural,
33
+ estimatedInputCostUsd: NonNegativeFiniteSchema,
34
+ });
35
+
36
+ /**
37
+ * Cumulative per-user RFC CLI usage persisted on disk.
38
+ */
39
+ export type UsageTotals = Schema.Schema.Type<typeof UsageTotalsSchema>;
40
+
41
+ /**
42
+ * One successful RFC CLI operation to include in cumulative usage.
43
+ */
44
+ export interface UsageObservation {
45
+ /**
46
+ * Provider-reported input tokens, or null when no model call occurred or usage was unavailable.
47
+ */
48
+ readonly inputTokens: number | null;
49
+ /**
50
+ * Estimated USD input charge, or null when the resolved model has no known price.
51
+ */
52
+ readonly estimatedInputCostUsd: number | null;
53
+ }
54
+
55
+ /**
56
+ * Function that records one successful RFC CLI operation.
57
+ */
58
+ export type UsageRecorder = (observation: UsageObservation) => Promise<UsageTotals>;
59
+
60
+ /**
61
+ * Function that reads the cumulative per-user RFC CLI usage.
62
+ */
63
+ export type UsageReader = () => Promise<UsageTotals>;
64
+
65
+ const isFileSystemError = (error: unknown, code: string): boolean =>
66
+ error instanceof Error && "code" in error && error.code === code;
67
+
68
+ const wait = (milliseconds: number): Promise<void> =>
69
+ new Promise((resolve) => setTimeout(resolve, milliseconds));
70
+
71
+ const releaseLock = async (path: string, handle: FileHandle): Promise<void> => {
72
+ let failure: unknown = null;
73
+ try {
74
+ await handle.close();
75
+ } catch (error) {
76
+ failure = error;
77
+ }
78
+ try {
79
+ await unlink(path);
80
+ } catch (error) {
81
+ if (!isFileSystemError(error, "ENOENT") && failure === null) failure = error;
82
+ }
83
+ if (failure !== null) throw failure;
84
+ };
85
+
86
+ const acquireLock = async (path: string): Promise<FileHandle> => {
87
+ for (let attempt = 0; attempt < lockAttemptLimit; attempt += 1) {
88
+ let handle: FileHandle;
89
+ try {
90
+ handle = await open(path, "wx", 0o600);
91
+ } catch (error) {
92
+ if (!isFileSystemError(error, "EEXIST")) throw error;
93
+
94
+ try {
95
+ const lock = await stat(path);
96
+ if (Date.now() - lock.mtimeMs > staleLockMilliseconds) await unlink(path);
97
+ } catch (inspectionError) {
98
+ if (!isFileSystemError(inspectionError, "ENOENT")) throw inspectionError;
99
+ }
100
+
101
+ await wait(lockRetryMilliseconds);
102
+ continue;
103
+ }
104
+
105
+ try {
106
+ await handle.writeFile(`${process.pid}\n`);
107
+ await handle.sync();
108
+ return handle;
109
+ } catch (error) {
110
+ await releaseLock(path, handle);
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ throw new Error("Timed out waiting for the RFC usage-store lock");
116
+ };
117
+
118
+ const emptyTotals = (updatedAt: string): UsageTotals => ({
119
+ schemaVersion: 1,
120
+ kind: "rfc_usage_totals",
121
+ updatedAt,
122
+ operations: 0,
123
+ pricedOperations: 0,
124
+ unpricedOperations: 0,
125
+ operationsWithoutInputTokens: 0,
126
+ inputTokens: 0,
127
+ pricedInputTokens: 0,
128
+ unpricedInputTokens: 0,
129
+ estimatedInputCostUsd: 0,
130
+ });
131
+
132
+ const readTotals = async (path: string, updatedAt: string): Promise<UsageTotals> => {
133
+ let contents: string;
134
+ try {
135
+ contents = await readFile(path, "utf8");
136
+ } catch (error) {
137
+ if (isFileSystemError(error, "ENOENT")) return emptyTotals(updatedAt);
138
+ throw error;
139
+ }
140
+
141
+ return Schema.decodeUnknownSync(UsageTotalsSchema)(JSON.parse(contents));
142
+ };
143
+
144
+ const validateObservation = (observation: UsageObservation): void => {
145
+ if (
146
+ observation.inputTokens !== null &&
147
+ (!Number.isSafeInteger(observation.inputTokens) || observation.inputTokens < 0)
148
+ ) {
149
+ throw new Error("RFC usage input tokens must be a non-negative safe integer or null");
150
+ }
151
+ if (
152
+ observation.estimatedInputCostUsd !== null &&
153
+ (!Number.isFinite(observation.estimatedInputCostUsd) || observation.estimatedInputCostUsd < 0)
154
+ ) {
155
+ throw new Error("RFC usage input cost must be a non-negative finite number or null");
156
+ }
157
+ };
158
+
159
+ const addObservation = (
160
+ totals: UsageTotals,
161
+ observation: UsageObservation,
162
+ updatedAt: string,
163
+ ): UsageTotals => {
164
+ const inputTokens = observation.inputTokens ?? 0;
165
+ const hasUsage = observation.inputTokens !== null;
166
+ const isPriced = hasUsage && observation.estimatedInputCostUsd !== null;
167
+
168
+ return Schema.decodeUnknownSync(UsageTotalsSchema)({
169
+ ...totals,
170
+ updatedAt,
171
+ operations: totals.operations + 1,
172
+ pricedOperations: totals.pricedOperations + (isPriced ? 1 : 0),
173
+ unpricedOperations: totals.unpricedOperations + (hasUsage && !isPriced ? 1 : 0),
174
+ operationsWithoutInputTokens: totals.operationsWithoutInputTokens + (hasUsage ? 0 : 1),
175
+ inputTokens: totals.inputTokens + inputTokens,
176
+ pricedInputTokens: totals.pricedInputTokens + (isPriced ? inputTokens : 0),
177
+ unpricedInputTokens: totals.unpricedInputTokens + (hasUsage && !isPriced ? inputTokens : 0),
178
+ estimatedInputCostUsd:
179
+ Math.round(
180
+ (totals.estimatedInputCostUsd + (observation.estimatedInputCostUsd ?? 0)) * usdPrecision,
181
+ ) / usdPrecision,
182
+ });
183
+ };
184
+
185
+ const writeTotals = async (path: string, totals: UsageTotals): Promise<void> => {
186
+ const directory = dirname(path);
187
+ const temporaryPath = join(directory, `.usage-${process.pid}-${randomUUID()}.tmp`);
188
+ try {
189
+ const handle = await open(temporaryPath, "wx", 0o600);
190
+ try {
191
+ await handle.writeFile(`${JSON.stringify(totals, null, 2)}\n`);
192
+ await handle.sync();
193
+ } finally {
194
+ await handle.close();
195
+ }
196
+ await rename(temporaryPath, path);
197
+ } catch (error) {
198
+ try {
199
+ await unlink(temporaryPath);
200
+ } catch {
201
+ // Preserve the original persistence failure.
202
+ }
203
+ throw error;
204
+ }
205
+ };
206
+
207
+ /**
208
+ * Create a reader for a per-user usage totals file.
209
+ *
210
+ * Reads are safe without taking the writer lock because updates replace the
211
+ * complete file atomically. A missing file is represented by zero totals.
212
+ *
213
+ * @param path Source JSON file. Defaults to `~/.config/rfc/usage.json`.
214
+ * @param now Clock used to timestamp zero totals when no file exists.
215
+ * @returns A reader that validates the versioned totals before returning them.
216
+ */
217
+ export const makeUsageReader =
218
+ (path: string = defaultUsageFile, now: () => Date = () => new Date()): UsageReader =>
219
+ () =>
220
+ readTotals(path, now().toISOString());
221
+
222
+ /**
223
+ * Create an atomic per-user usage recorder for a JSON totals file.
224
+ *
225
+ * @param path Destination JSON file. Defaults to `~/.config/rfc/usage.json`.
226
+ * @param now Clock used for deterministic timestamps in tests.
227
+ * @returns A recorder that serializes concurrent process updates through a lock file.
228
+ */
229
+ export const makeUsageRecorder =
230
+ (path: string = defaultUsageFile, now: () => Date = () => new Date()): UsageRecorder =>
231
+ async (observation) => {
232
+ validateObservation(observation);
233
+ const directory = dirname(path);
234
+ await mkdir(directory, { recursive: true, mode: 0o700 });
235
+ const lockPath = `${path}.lock`;
236
+ const lock = await acquireLock(lockPath);
237
+ try {
238
+ const updatedAt = now().toISOString();
239
+ const totals = addObservation(await readTotals(path, updatedAt), observation, updatedAt);
240
+ await writeTotals(path, totals);
241
+ return totals;
242
+ } finally {
243
+ await releaseLock(lockPath, lock);
244
+ }
245
+ };