@ceralive/modem-control 0.1.0 → 1.0.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,297 @@
1
+ // The evidence-bundle ingestion seam — turning ONE real `certify` bundle into (i) a
2
+ // classifier test fixture in the real udev shape and (ii) a candidate catalog entry.
3
+ //
4
+ // This is the documented path between the bench and the catalog. It is deliberately a
5
+ // PURE TRANSFORM that produces a REVIEW ARTIFACT: nothing here writes a file, mutates
6
+ // `certified-catalog.json`, or promotes anything. A catalog addition stays what Phase A
7
+ // made it — a human-reviewed commit — and this seam only removes the hand-transcription
8
+ // step between the bundle and that commit.
9
+ //
10
+ // THE ONE RULE THE CODE ENFORCES, NOT THE REVIEWER:
11
+ // A bundle marked `synthetic: true` is REFUSED for catalog promotion, with a typed
12
+ // reason. Synthetic bundles are legitimate test data — `buildClassifierFixture` accepts
13
+ // them and stamps the fixture's provenance with `synthetic: true` — but a catalog entry
14
+ // asserts a certified hardware fact, and no synthetic capture may ever back one.
15
+ //
16
+ // SHAPE COMPATIBILITY, not shape duplication: the bundle is validated here through a
17
+ // deliberately NON-strict VIEW schema. The authoritative bundle schema lives beside the
18
+ // `certify` command in the CLI, which depends on this package and not the reverse, so
19
+ // this file describes only the subset ingestion reads and ignores the rest (`lsusb`,
20
+ // `modemManager`, the transition timeline). Adding a field to the bundle can therefore
21
+ // never break ingestion — which is the point of a view.
22
+
23
+ import { z } from 'zod';
24
+ import type { UsbDeviceSnapshot } from '../backend/device-classifier';
25
+ import {
26
+ CANONICAL_USB_MODES,
27
+ type CanonicalUsbMode,
28
+ type CatalogEntry,
29
+ catalogEntrySchema,
30
+ expectedDescriptorsSchema,
31
+ MM_USB_MODES,
32
+ } from './catalog-schema';
33
+ import { parseUsbDevices, selectUniqueDevice } from './usb-devices-parse';
34
+
35
+ const mmMode = z.enum(MM_USB_MODES);
36
+
37
+ /** The ingestion VIEW of a certification bundle — non-strict on purpose (see header). */
38
+ export const evidenceBundleViewSchema = z.object({
39
+ schemaVersion: z.literal(1),
40
+ synthetic: z.boolean(),
41
+ capturedAtMs: z.number(),
42
+ slot: z.string().min(1),
43
+ sku: z
44
+ .object({
45
+ vidPid: z.string().regex(/^[0-9a-f]{4}:[0-9a-f]{4}$/),
46
+ model: z.string().min(1),
47
+ firmwarePrefix: z.string().min(1),
48
+ })
49
+ .optional(),
50
+ usb: z.object({
51
+ usbDevices: z.string().min(1),
52
+ udevProperties: z.record(z.string(), z.string()),
53
+ }),
54
+ transition: z
55
+ .object({
56
+ from: mmMode,
57
+ to: mmMode,
58
+ atCommand: z.string().min(1),
59
+ expectedResponse: z.string().min(1),
60
+ expectsPortDrop: z.boolean(),
61
+ afterDescriptors: expectedDescriptorsSchema,
62
+ })
63
+ .optional(),
64
+ });
65
+ export type EvidenceBundleView = z.infer<typeof evidenceBundleViewSchema>;
66
+
67
+ /** Every way ingestion can refuse. Each is a named, actionable condition — never a throw. */
68
+ export type IngestionRefusalReason =
69
+ | 'bundle-malformed'
70
+ | 'sha256-malformed'
71
+ | 'sku-missing'
72
+ | 'device-not-in-capture'
73
+ | 'device-ambiguous'
74
+ | 'no-interfaces-captured'
75
+ | 'synthetic-bundle'
76
+ | 'transition-mode-mismatch'
77
+ | 'entry-schema-invalid';
78
+
79
+ /** A typed refusal. `detail` is for a human reviewer; `reason` is for a machine. */
80
+ export interface IngestionRefusal {
81
+ readonly ok: false;
82
+ readonly reason: IngestionRefusalReason;
83
+ readonly detail: string;
84
+ }
85
+
86
+ /** A refusal or a value — ingestion never throws and never returns a partial result. */
87
+ export type IngestionOutcome<T> = { readonly ok: true; readonly value: T } | IngestionRefusal;
88
+
89
+ const refuse = (reason: IngestionRefusalReason, detail: string): IngestionRefusal => ({
90
+ ok: false,
91
+ reason,
92
+ detail,
93
+ });
94
+
95
+ /** Where a fixture came from — stamped onto every fixture, honest about synthetic input. */
96
+ export interface FixtureProvenance {
97
+ readonly bundleSha256: string;
98
+ /** `true` when the source bundle was synthetic — such a fixture is test data only. */
99
+ readonly synthetic: boolean;
100
+ readonly slot: string;
101
+ readonly capturedAtMs: number;
102
+ }
103
+
104
+ /** A classifier fixture: the snapshot `classifyDevice` consumes, plus its provenance. */
105
+ export interface ClassifierFixture {
106
+ readonly snapshot: UsbDeviceSnapshot;
107
+ readonly provenance: FixtureProvenance;
108
+ }
109
+
110
+ /** One bundle plus the sha256 `certify` printed for it — the two halves are inseparable. */
111
+ export interface IngestionRequest {
112
+ /** The bundle JSON, already `JSON.parse`d. Validated here against the view schema. */
113
+ readonly bundle: unknown;
114
+ /** The `CERTIFY OK: sha256=…` value. Becomes the entry's `evidenceBundleSha256`. */
115
+ readonly bundleSha256: string;
116
+ }
117
+
118
+ /**
119
+ * The claim a REVIEWER makes about the SKU. `canonicalMode` is stated, never inferred:
120
+ * a machine reading descriptors could guess it, but a catalog entry is an assertion a
121
+ * human signs, and a stage-2 bundle's `transition.from` is cross-checked against it.
122
+ */
123
+ export interface CatalogClaim {
124
+ readonly canonicalMode: CanonicalUsbMode;
125
+ }
126
+
127
+ const SHA256_RE = /^[0-9a-f]{64}$/;
128
+
129
+ /** Validate a request's bundle + sha, or refuse with a precise reason. */
130
+ export function parseIngestionRequest(
131
+ request: IngestionRequest,
132
+ ): IngestionOutcome<EvidenceBundleView> {
133
+ if (!SHA256_RE.test(request.bundleSha256)) {
134
+ return refuse(
135
+ 'sha256-malformed',
136
+ `bundle sha256 must be 64 lowercase hex characters, got '${request.bundleSha256}'`,
137
+ );
138
+ }
139
+ const parsed = evidenceBundleViewSchema.safeParse(request.bundle);
140
+ if (!parsed.success) {
141
+ return refuse('bundle-malformed', z.prettifyError(parsed.error));
142
+ }
143
+ return { ok: true, value: parsed.data };
144
+ }
145
+
146
+ /**
147
+ * Build a classifier test fixture from a bundle — the real udev shape, not a hand-typed
148
+ * approximation. Descriptors and per-interface DRIVERS come from the bundle's
149
+ * `usb-devices` text (the only structured descriptor source a base bundle carries);
150
+ * identity comes from the bundle's SKU; `physicalUid` / `ifname` come from the captured
151
+ * udev properties. A synthetic bundle is ACCEPTED here and the provenance says so.
152
+ */
153
+ export function buildClassifierFixture(
154
+ request: IngestionRequest,
155
+ ): IngestionOutcome<ClassifierFixture> {
156
+ const parsed = parseIngestionRequest(request);
157
+ if (!parsed.ok) {
158
+ return parsed;
159
+ }
160
+ const bundle = parsed.value;
161
+ const sku = bundle.sku;
162
+ if (sku === undefined) {
163
+ // Blocker B2 in `docs/BENCH.md` produces exactly this: an unmatched USB device
164
+ // yields a bundle with no SKU at all.
165
+ return refuse(
166
+ 'sku-missing',
167
+ 'bundle carries no `sku` — the capture did not match a USB device to the slot',
168
+ );
169
+ }
170
+
171
+ const selected = selectUniqueDevice(parseUsbDevices(bundle.usb.usbDevices), sku.vidPid);
172
+ if (!('device' in selected)) {
173
+ return selected.ambiguousMatches === 0
174
+ ? refuse(
175
+ 'device-not-in-capture',
176
+ `no device with vidPid ${sku.vidPid} in the bundle's usb-devices capture`,
177
+ )
178
+ : refuse(
179
+ 'device-ambiguous',
180
+ `${selected.ambiguousMatches} devices share vidPid ${sku.vidPid} in this capture; a fixture must name one physical device`,
181
+ );
182
+ }
183
+ const device = selected.device;
184
+ if (device.interfaces.length === 0) {
185
+ return refuse(
186
+ 'no-interfaces-captured',
187
+ `device ${sku.vidPid} has no parsed interface lines; a classifier fixture with no interfaces classifies nothing`,
188
+ );
189
+ }
190
+
191
+ const [vendorId, productId] = sku.vidPid.split(':') as [string, string];
192
+ const props = bundle.usb.udevProperties;
193
+ const physicalUid = props.ID_PATH;
194
+ const ifname = props.INTERFACE;
195
+
196
+ return {
197
+ ok: true,
198
+ value: {
199
+ snapshot: {
200
+ vendorId,
201
+ productId,
202
+ model: sku.model,
203
+ firmwareRevision: sku.firmwarePrefix,
204
+ bDeviceClass: device.bDeviceClass,
205
+ interfaces: device.interfaces,
206
+ udevProperties: props,
207
+ ...(physicalUid !== undefined ? { physicalUid } : {}),
208
+ ...(ifname !== undefined ? { ifname } : {}),
209
+ },
210
+ provenance: {
211
+ bundleSha256: request.bundleSha256,
212
+ synthetic: bundle.synthetic,
213
+ slot: bundle.slot,
214
+ capturedAtMs: bundle.capturedAtMs,
215
+ },
216
+ },
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Build a CANDIDATE catalog entry from a bundle. The entry is a review artifact: it is
222
+ * returned, never written.
223
+ *
224
+ * REFUSES a `synthetic: true` bundle — a catalog entry asserts a certified hardware
225
+ * fact, so synthetic evidence can never back one (`docs/BENCH.md` Must-NOT-Have 7).
226
+ *
227
+ * A stage-1 (base) bundle yields `permittedTransitions: []`. A stage-2 bundle — one
228
+ * captured with `certify --transition` — yields exactly ONE permitted transition, whose
229
+ * `expectedDescriptors` is the captured `afterDescriptors` and whose
230
+ * `evidenceBundleSha256` is this bundle's hash. The reviewer's stated `canonicalMode`
231
+ * must equal the captured `transition.from`; a mismatch is refused rather than silently
232
+ * resolved in either direction.
233
+ */
234
+ export function buildCatalogEntryCandidate(
235
+ request: IngestionRequest,
236
+ claim: CatalogClaim,
237
+ ): IngestionOutcome<CatalogEntry> {
238
+ const parsed = parseIngestionRequest(request);
239
+ if (!parsed.ok) {
240
+ return parsed;
241
+ }
242
+ const bundle = parsed.value;
243
+ if (bundle.synthetic) {
244
+ return refuse(
245
+ 'synthetic-bundle',
246
+ `bundle for slot '${bundle.slot}' is marked synthetic:true; a catalog entry requires a real capture (synthetic:false)`,
247
+ );
248
+ }
249
+ const sku = bundle.sku;
250
+ if (sku === undefined) {
251
+ return refuse(
252
+ 'sku-missing',
253
+ 'bundle carries no `sku` — a catalog entry needs all three discriminators (vidPid, model, firmwarePrefix)',
254
+ );
255
+ }
256
+
257
+ const transition = bundle.transition;
258
+ if (transition !== undefined && transition.from !== claim.canonicalMode) {
259
+ return refuse(
260
+ 'transition-mode-mismatch',
261
+ `claimed canonicalMode '${claim.canonicalMode}' contradicts the captured transition.from '${transition.from}'`,
262
+ );
263
+ }
264
+
265
+ const candidate = {
266
+ vidPid: sku.vidPid,
267
+ model: sku.model,
268
+ firmwarePrefix: sku.firmwarePrefix,
269
+ canonicalMode: claim.canonicalMode,
270
+ permittedTransitions:
271
+ transition === undefined
272
+ ? []
273
+ : [
274
+ {
275
+ from: transition.from,
276
+ to: transition.to,
277
+ atCommand: transition.atCommand,
278
+ expectedResponse: transition.expectedResponse,
279
+ expectsPortDrop: transition.expectsPortDrop,
280
+ expectedDescriptors: transition.afterDescriptors,
281
+ evidenceBundleSha256: request.bundleSha256,
282
+ },
283
+ ],
284
+ };
285
+
286
+ // The candidate is re-validated through the AUTHORITATIVE entry schema, so an
287
+ // impossible combination (a router-mode SKU declaring a transition, say) is refused
288
+ // here rather than at review time.
289
+ const entry = catalogEntrySchema.safeParse(candidate);
290
+ if (!entry.success) {
291
+ return refuse('entry-schema-invalid', z.prettifyError(entry.error));
292
+ }
293
+ return { ok: true, value: entry.data };
294
+ }
295
+
296
+ /** The canonical-mode vocabulary a reviewer's claim may use — re-exported for callers. */
297
+ export const CLAIMABLE_CANONICAL_MODES = CANONICAL_USB_MODES;
@@ -0,0 +1,117 @@
1
+ // Rendering the REVIEW ARTIFACT for a catalog promotion — the PR-comment template.
2
+ //
3
+ // Catalog additions are human-reviewed commits (Phase-A rule). This module renders what
4
+ // a reviewer reads: the proposed entry, the classifier fixture derived from the same
5
+ // bundle, and a checklist whose boxes a machine cannot tick. It renders a REFUSAL with
6
+ // equal prominence — a refused promotion produces a comment that says so, never silence,
7
+ // because a silently-absent comment is indistinguishable from a forgotten run.
8
+ //
9
+ // Nothing here writes a file or opens a PR. The output is text.
10
+
11
+ import type { CatalogEntry } from './catalog-schema';
12
+ import type { ClassifierFixture, IngestionOutcome, IngestionRefusal } from './ingestion';
13
+
14
+ /** Everything the rendered comment needs beyond the two ingestion outcomes. */
15
+ export interface PromotionContext {
16
+ /** The runbook that captured the bundle (`RB-11` …) — the evidence's provenance. */
17
+ readonly runbook: string;
18
+ /** The repo-local evidence path the bundle was written to. */
19
+ readonly evidencePath: string;
20
+ }
21
+
22
+ /** A promotion request: the two ingestion outcomes plus where the evidence came from. */
23
+ export interface PromotionRequest {
24
+ readonly context: PromotionContext;
25
+ readonly entry: IngestionOutcome<CatalogEntry>;
26
+ readonly fixture: IngestionOutcome<ClassifierFixture>;
27
+ }
28
+
29
+ function refusalBlock(what: string, refusal: IngestionRefusal): string {
30
+ return [
31
+ `### ❌ ${what} — REFUSED`,
32
+ '',
33
+ `**Reason:** \`${refusal.reason}\``,
34
+ '',
35
+ `> ${refusal.detail}`,
36
+ '',
37
+ 'This is a typed refusal from the ingestion seam, not a review opinion. Fix the',
38
+ 'capture and re-run the runbook; do not hand-author the artifact around it.',
39
+ ].join('\n');
40
+ }
41
+
42
+ function entryBlock(entry: CatalogEntry): string {
43
+ return [
44
+ '### Proposed `certified-catalog.json` entry',
45
+ '',
46
+ '```json',
47
+ JSON.stringify(entry, null, 2),
48
+ '```',
49
+ ].join('\n');
50
+ }
51
+
52
+ function fixtureBlock(fixture: ClassifierFixture): string {
53
+ const { snapshot, provenance } = fixture;
54
+ const syntheticNote = provenance.synthetic
55
+ ? '> ⚠️ Derived from a **synthetic** bundle — valid as test data, never as certification evidence.'
56
+ : `> Derived from a real capture, bundle sha256 \`${provenance.bundleSha256}\`.`;
57
+ return [
58
+ '### Proposed classifier fixture (`control/src/backend/device-classifier.test.ts`)',
59
+ '',
60
+ syntheticNote,
61
+ '',
62
+ '```ts',
63
+ `const FIXTURE: UsbDeviceSnapshot = ${JSON.stringify(snapshot, null, 2)};`,
64
+ '```',
65
+ ].join('\n');
66
+ }
67
+
68
+ function checklistBlock(context: PromotionContext, entry: CatalogEntry): string {
69
+ const transitions = entry.permittedTransitions.length;
70
+ return [
71
+ '### Reviewer checklist (every box is a human judgement)',
72
+ '',
73
+ `- [ ] The bundle at \`${context.evidencePath}\` was captured by **${context.runbook}** on real hardware, and its \`CERTIFY OK\` line reads \`synthetic=false\`.`,
74
+ '- [ ] The bundle sha256 in the entry matches the sha256 the capture printed — recomputed, not copied from this comment.',
75
+ `- [ ] \`canonicalMode: "${entry.canonicalMode}"\` is the mode the device was actually observed in, not the mode it was expected to be in.`,
76
+ transitions === 0
77
+ ? '- [ ] `permittedTransitions: []` is correct for this stage — a stage-1 entry never declares a transition.'
78
+ : '- [ ] The declared transition was OBSERVED end to end: the AT command executed, the port dropped if `expectsPortDrop`, and the device re-enumerated presenting `expectedDescriptors`.',
79
+ '- [ ] No claim in `docs/MODEM-SUPPORT-MATRIX.md` is being changed by this commit without its own evidence.',
80
+ ].join('\n');
81
+ }
82
+
83
+ /**
84
+ * Render the review comment for a promotion request. Always returns a comment: a
85
+ * refusal renders a refusal block, so a run that produced nothing promotable still
86
+ * leaves a visible, auditable trace.
87
+ */
88
+ export function renderPromotionReview(request: PromotionRequest): string {
89
+ const { context, entry, fixture } = request;
90
+ const parts: string[] = [
91
+ `## Catalog promotion review — ${context.runbook}`,
92
+ '',
93
+ `Evidence: \`${context.evidencePath}\``,
94
+ '',
95
+ 'Generated by the `control/src/usb-mode/` ingestion seam. **This comment promotes',
96
+ 'nothing** — the promotion is the human-reviewed commit that follows it.',
97
+ '',
98
+ ];
99
+
100
+ parts.push(entry.ok ? entryBlock(entry.value) : refusalBlock('Catalog entry', entry));
101
+ parts.push('');
102
+ parts.push(
103
+ fixture.ok ? fixtureBlock(fixture.value) : refusalBlock('Classifier fixture', fixture),
104
+ );
105
+ parts.push('');
106
+ if (entry.ok) {
107
+ parts.push(checklistBlock(context, entry.value));
108
+ } else {
109
+ parts.push(
110
+ '### No checklist',
111
+ '',
112
+ 'The catalog entry was refused, so there is nothing to review. A checklist here',
113
+ 'would invite a reviewer to approve an artifact that does not exist.',
114
+ );
115
+ }
116
+ return `${parts.join('\n')}\n`;
117
+ }
@@ -0,0 +1,196 @@
1
+ // Parsing `usb-devices` text — the ONLY per-interface descriptor source inside a
2
+ // certification bundle.
3
+ //
4
+ // A base certification bundle (`certify <slot>` with no `--transition`) carries no
5
+ // structured descriptors at all: it holds `lsusb -v` and `usb-devices` as raw text plus
6
+ // the slot's udev property map. Authoring a classifier fixture or a catalog entry from
7
+ // such a bundle therefore requires reading the descriptors back out of that text, and
8
+ // `usb-devices` is the right half to read — it is line-oriented, one fixed-width record
9
+ // per device, and it names each interface's BOUND KERNEL DRIVER, which `lsusb -v` does
10
+ // not. The driver is not optional detail here: `classifyDevice` decides `mm-managed` vs
11
+ // `router-mode` partly on `qmi_wwan` / `cdc_ether` / `option` bindings.
12
+ //
13
+ // The parser is pure and total: unparseable lines are SKIPPED, never guessed at, and a
14
+ // device that yields no interfaces still yields a record (callers decide whether an
15
+ // interface-less device is usable — this file never makes that judgement).
16
+ //
17
+ // Record shape (`usb-devices`, one blank-line-separated block per device):
18
+ // T: Bus=04 Lev=03 Prnt=03 Port=03 Cnt=01 Dev#= 7 Spd=480 MxCh= 0
19
+ // D: Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs= 1
20
+ // P: Vendor=2c7c ProdID=0801 Rev=05.04
21
+ // S: Manufacturer=Quectel
22
+ // S: Product=RM530N-GL
23
+ // I: If#= 4 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=ff Driver=qmi_wwan
24
+
25
+ /** One interface line of a `usb-devices` record. */
26
+ export interface ParsedUsbInterface {
27
+ readonly interfaceClass: number;
28
+ readonly interfaceSubClass: number;
29
+ readonly interfaceProtocol: number;
30
+ /** The bound kernel driver, omitted when `usb-devices` reports `(none)`. */
31
+ readonly driver?: string;
32
+ }
33
+
34
+ /** One device block of a `usb-devices` capture. */
35
+ export interface ParsedUsbDevice {
36
+ /** Lowercase hex `xxxx:xxxx`, exactly the catalog's `vidPid` discriminator shape. */
37
+ readonly vidPid: string;
38
+ /** The `D:` line's `Cls=` byte — the device-descriptor `bDeviceClass`. */
39
+ readonly bDeviceClass: number;
40
+ readonly manufacturer?: string;
41
+ readonly product?: string;
42
+ readonly interfaces: readonly ParsedUsbInterface[];
43
+ }
44
+
45
+ /** Read `Key=value` from a `usb-devices` line; `undefined` when the key is absent. */
46
+ function field(line: string, key: string): string | undefined {
47
+ // Values are whitespace-delimited and may be preceded by padding spaces (`Dev#= 7`).
48
+ // `Cls=ff(vend.)` carries a trailing gloss, stripped by the hex/number parsers below.
49
+ const match = new RegExp(`${key}=\\s*(\\S+)`).exec(line);
50
+ return match?.[1];
51
+ }
52
+
53
+ /** Parse a hex byte field, tolerating `usb-devices`' `ff(vend.)` gloss suffix. */
54
+ function hexByte(line: string, key: string): number | undefined {
55
+ const raw = field(line, key);
56
+ if (raw === undefined) {
57
+ return undefined;
58
+ }
59
+ const digits = /^[0-9a-fA-F]{1,2}/.exec(raw)?.[0];
60
+ if (digits === undefined) {
61
+ return undefined;
62
+ }
63
+ const value = Number.parseInt(digits, 16);
64
+ return Number.isNaN(value) ? undefined : value;
65
+ }
66
+
67
+ /** Parse an `S: Manufacturer=…` style line into its `[key, value]` pair. */
68
+ function stringField(line: string): readonly [string, string] | undefined {
69
+ const eq = line.indexOf('=');
70
+ if (eq < 0) {
71
+ return undefined;
72
+ }
73
+ const key = line.slice(3, eq).trim();
74
+ const value = line.slice(eq + 1).trim();
75
+ return key === '' || value === '' ? undefined : [key, value];
76
+ }
77
+
78
+ interface DeviceAccumulator {
79
+ vidPid?: string;
80
+ bDeviceClass?: number;
81
+ manufacturer?: string;
82
+ product?: string;
83
+ interfaces: ParsedUsbInterface[];
84
+ }
85
+
86
+ function emptyAccumulator(): DeviceAccumulator {
87
+ return { interfaces: [] };
88
+ }
89
+
90
+ function finish(acc: DeviceAccumulator, out: ParsedUsbDevice[]): void {
91
+ // A record with no `P:` line is not a device — never synthesise an identity for it.
92
+ if (acc.vidPid === undefined) {
93
+ return;
94
+ }
95
+ out.push({
96
+ vidPid: acc.vidPid,
97
+ bDeviceClass: acc.bDeviceClass ?? 0,
98
+ interfaces: acc.interfaces,
99
+ ...(acc.manufacturer !== undefined ? { manufacturer: acc.manufacturer } : {}),
100
+ ...(acc.product !== undefined ? { product: acc.product } : {}),
101
+ });
102
+ }
103
+
104
+ function applyProductLine(line: string, acc: DeviceAccumulator): void {
105
+ const vendor = field(line, 'Vendor');
106
+ const product = field(line, 'ProdID');
107
+ if (vendor !== undefined && product !== undefined) {
108
+ acc.vidPid = `${vendor.toLowerCase()}:${product.toLowerCase()}`;
109
+ }
110
+ }
111
+
112
+ function applyStringLine(line: string, acc: DeviceAccumulator): void {
113
+ const pair = stringField(line);
114
+ if (pair === undefined) {
115
+ return;
116
+ }
117
+ const [key, value] = pair;
118
+ if (key === 'Manufacturer') {
119
+ acc.manufacturer = value;
120
+ } else if (key === 'Product') {
121
+ acc.product = value;
122
+ }
123
+ }
124
+
125
+ function applyInterfaceLine(line: string, acc: DeviceAccumulator): void {
126
+ const interfaceClass = hexByte(line, 'Cls');
127
+ const interfaceSubClass = hexByte(line, 'Sub');
128
+ const interfaceProtocol = hexByte(line, 'Prot');
129
+ if (
130
+ interfaceClass === undefined ||
131
+ interfaceSubClass === undefined ||
132
+ interfaceProtocol === undefined
133
+ ) {
134
+ return;
135
+ }
136
+ const driver = field(line, 'Driver');
137
+ acc.interfaces.push({
138
+ interfaceClass,
139
+ interfaceSubClass,
140
+ interfaceProtocol,
141
+ ...(driver !== undefined && driver !== '(none)' ? { driver } : {}),
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Parse `usb-devices` output into one record per device. Pure and total: malformed
147
+ * lines are skipped rather than guessed at, and a block with no `P:` line yields no
148
+ * record (it has no identity, so inventing one would be a lie).
149
+ */
150
+ export function parseUsbDevices(text: string): ParsedUsbDevice[] {
151
+ const out: ParsedUsbDevice[] = [];
152
+ let acc = emptyAccumulator();
153
+ for (const line of text.split('\n')) {
154
+ // A `T:` line opens a new device record; `usb-devices` also blank-line-separates
155
+ // them, but the topology line is the reliable delimiter (blank lines are optional
156
+ // in some kernels' output).
157
+ if (line.startsWith('T:')) {
158
+ finish(acc, out);
159
+ acc = emptyAccumulator();
160
+ continue;
161
+ }
162
+ if (line.startsWith('D:')) {
163
+ const deviceClass = hexByte(line, 'Cls');
164
+ if (deviceClass !== undefined) {
165
+ acc.bDeviceClass = deviceClass;
166
+ }
167
+ } else if (line.startsWith('P:')) {
168
+ applyProductLine(line, acc);
169
+ } else if (line.startsWith('S:')) {
170
+ applyStringLine(line, acc);
171
+ } else if (line.startsWith('I:')) {
172
+ applyInterfaceLine(line, acc);
173
+ }
174
+ }
175
+ finish(acc, out);
176
+ return out;
177
+ }
178
+
179
+ /**
180
+ * Find the single device matching `vidPid` in a parsed capture. Returns `undefined`
181
+ * when there is NO match, and — deliberately — also when there is more than one: a
182
+ * duplicate VID:PID (this bench has two identical Huawei HiLink units) makes the
183
+ * selection ambiguous, and an ambiguous selection must refuse rather than pick the
184
+ * first. The caller turns that into a typed refusal.
185
+ */
186
+ export function selectUniqueDevice(
187
+ devices: readonly ParsedUsbDevice[],
188
+ vidPid: string,
189
+ ): { readonly device: ParsedUsbDevice } | { readonly ambiguousMatches: number } {
190
+ const matches = devices.filter((d) => d.vidPid === vidPid);
191
+ const only = matches[0];
192
+ if (matches.length === 1 && only !== undefined) {
193
+ return { device: only };
194
+ }
195
+ return { ambiguousMatches: matches.length };
196
+ }