@dybai/dsh-editor 0.5.0 → 0.8.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,154 @@
1
+ /**
2
+ * Safe single-line serialization of log arguments — the Host-side stringifier
3
+ * the persistent log channel (log-manager) builds its Host lines with.
4
+ * Arguments are stringified one by one, joined with single spaces, then capped
5
+ * at `maxChars` (default 2000); a capped line ends with `…(truncated)`.
6
+ *
7
+ * SEMANTIC SYNC OBLIGATION: this module is an INDEPENDENT reimplementation of
8
+ * the client-side `src/serialize-log.js` — the plugin deliberately shares no
9
+ * code between the client bundle and the Host package, so the two files must
10
+ * never import from each other. Their semantics, however, are pinned to be
11
+ * identical (same placeholders, same joining, same truncation): for a given
12
+ * input both implementations MUST render the same output. The consistency
13
+ * sentinel in `host/log-serialize.test.js` pins the client matrix outputs
14
+ * verbatim to enforce this. Any semantic change on one side MUST be mirrored
15
+ * on the other side in the same change.
16
+ *
17
+ * Iron rule: `formatLogArgs` NEVER throws, whatever it is handed. Every
18
+ * failure mode degrades to a placeholder instead: circular references render
19
+ * as `[circular]`, unserializable members (throwing getters, hostile proxies,
20
+ * stack-depth overflows) as `[unserializable]`, and bigint / function /
21
+ * symbol values as their dedicated placeholders (`123n` form, `[function]`,
22
+ * `[symbol]`). Line breaks inside string arguments become the literal two
23
+ * characters `\n`, so the output is always a single line.
24
+ *
25
+ * Primitive values render exactly like `JSON.stringify` (including `undefined`
26
+ * members being skipped and `NaN`/`Infinity` degrading to `null`); only the
27
+ * placeholders and cycle handling differ, since plain `JSON.stringify` cannot
28
+ * express either.
29
+ *
30
+ * Zero imports: pure functions only, unit-testable without DOM.
31
+ *
32
+ * @module @dybai/dsh-editor/host/log-serialize
33
+ */
34
+
35
+ /** Line cap before truncation; the brief's default for the log channel. */
36
+ const DEFAULT_MAX_CHARS = 2000;
37
+
38
+ /** Appended to a cut line; the truncated result stays within `maxChars`. */
39
+ const TRUNCATION_MARKER = '…(truncated)';
40
+
41
+ /** Line breaks (CRLF, LF, CR) collapse to the literal two characters `\n`. */
42
+ const LINE_BREAKS = /\r\n|\r|\n/g;
43
+
44
+ /**
45
+ * Serialize log arguments into one safe single-line string.
46
+ * @param {unknown[]} args - the arguments as passed to the logger.
47
+ * @param {{ maxChars?: number }} [opts] - `maxChars` caps the returned line
48
+ * (default 2000); a non-finite or negative value falls back to the default.
49
+ * @returns {string} a single line of at most `maxChars` characters; cut lines
50
+ * end with `…(truncated)`. Never throws on any input.
51
+ */
52
+ export function formatLogArgs(args, opts) {
53
+ const maxChars =
54
+ typeof opts?.maxChars === 'number' && Number.isFinite(opts.maxChars) && opts.maxChars >= 0
55
+ ? opts.maxChars
56
+ : DEFAULT_MAX_CHARS;
57
+ let line;
58
+ try {
59
+ line = args.map(renderArg).join(' ');
60
+ } catch {
61
+ line = '[unserializable]'; // 铁律兜底:任何输入都不得抛出(含非数组 args)
62
+ }
63
+ if (line.length > maxChars) {
64
+ line = line.slice(0, Math.max(0, maxChars - TRUNCATION_MARKER.length)) + TRUNCATION_MARKER;
65
+ }
66
+ return line;
67
+ }
68
+
69
+ /**
70
+ * Render one argument; string arguments keep their text with line breaks
71
+ * replaced by literal `\n`, everything else goes through the placeholder-safe
72
+ * value renderer. Any failure degrades to `[unserializable]`.
73
+ * @param {unknown} arg
74
+ * @returns {string}
75
+ */
76
+ function renderArg(arg) {
77
+ if (typeof arg === 'string') return arg.replace(LINE_BREAKS, '\\n');
78
+ try {
79
+ return renderValue(arg, new Set());
80
+ } catch {
81
+ return '[unserializable]';
82
+ }
83
+ }
84
+
85
+ /**
86
+ * JSON.stringify-shaped value renderer: same primitive rendering as
87
+ * `JSON.stringify`, plus type-dispatch placeholders for bigint / function /
88
+ * symbol, on-stack cycle detection and per-member getter guards.
89
+ * @param {unknown} value
90
+ * @param {Set<object>} seen - objects on the current rendering stack.
91
+ * @returns {string}
92
+ * @throws nothing on plain values; hostile `toJSON`/proxies propagate to the
93
+ * per-argument guard in `renderArg`.
94
+ */
95
+ function renderValue(value, seen) {
96
+ if (typeof value === 'string') return JSON.stringify(value);
97
+ if (typeof value === 'function') return '[function]';
98
+ if (typeof value === 'symbol') return '[symbol]';
99
+ if (typeof value === 'bigint') return `${value}n`;
100
+ if (typeof value === 'undefined') return 'undefined';
101
+ if (value === null) return 'null';
102
+ if (typeof value === 'object') return renderContainer(value, seen);
103
+ // number / boolean: finite numbers render like `JSON.stringify`, which
104
+ // also renders NaN and the infinities as `null`.
105
+ return typeof value === 'number' && !Number.isFinite(value) ? 'null' : String(value);
106
+ }
107
+
108
+ /**
109
+ * Render an object, array or exotic container (Map/Set/Date/…). Cycles are
110
+ * detected against the on-stack `seen` set only, so the same object visited
111
+ * twice across sibling branches still renders in full. A `toJSON` method is
112
+ * honoured first, exactly like `JSON.stringify` does (this also gives `Date`
113
+ * its ISO-string rendering). Throwing member reads degrade per member instead
114
+ * of sinking the whole container.
115
+ * @param {object} value
116
+ * @param {Set<object>} seen
117
+ * @returns {string}
118
+ */
119
+ function renderContainer(value, seen) {
120
+ if (seen.has(value)) return '[circular]';
121
+ seen.add(value);
122
+ try {
123
+ if (typeof value.toJSON === 'function') return renderValue(value.toJSON(), seen);
124
+ if (Array.isArray(value)) {
125
+ const members = []; // JSON.stringify renders in-array `undefined` as `null`
126
+ for (let i = 0; i < value.length; i++) {
127
+ let member;
128
+ try {
129
+ member = value[i];
130
+ } catch {
131
+ members.push('[unserializable]'); // 元素读取抛错(如 Proxy 陷阱)
132
+ continue;
133
+ }
134
+ members.push(member === undefined ? 'null' : renderValue(member, seen));
135
+ }
136
+ return `[${members.join(',')}]`;
137
+ }
138
+ const entries = []; // undefined-valued own enumerable keys are skipped like JSON.stringify
139
+ for (const key of Object.keys(value)) {
140
+ let member;
141
+ try {
142
+ member = value[key];
143
+ } catch {
144
+ entries.push(`${JSON.stringify(key)}:[unserializable]`); // getter 抛错
145
+ continue;
146
+ }
147
+ if (member === undefined) continue;
148
+ entries.push(`${JSON.stringify(key)}:${renderValue(member, seen)}`);
149
+ }
150
+ return `{${entries.join(',')}}`;
151
+ } finally {
152
+ seen.delete(value);
153
+ }
154
+ }
@@ -0,0 +1,504 @@
1
+ /**
2
+ * Host-side persistent log service: chunked appends into ONE DSH storage KV
3
+ * unit, count+age rotation on the append path, and a cordis-shaped exporter
4
+ * that funnels the plugin's OWN named logger records into the same write
5
+ * chain (spec: plugin log manager §7.2).
6
+ *
7
+ * `createLogService({ kv, now, report })` builds the service over the unit
8
+ * `dsh_editor_logs` (single layout, verbatim descriptor below):
9
+ *
10
+ * - `chunks` table — one record per appended batch; key = `'c'` + the seq
11
+ * zero-padded to 12 digits (lexicographic order = numeric order, keys are
12
+ * NEVER reused), value = `{ seq, ts, entries }` with `ts` the Host clock at
13
+ * append time (rotation ages by it);
14
+ * - global singleton — `{ lastSeq }`, the monotonic seq cursor, 0 before the
15
+ * first write. The cursor is only a HINT: each append derives its seq from
16
+ * the max of the cursor and the largest chunk key actually on disk (same
17
+ * snapshot), so a rejected `setGlobal` or a lost global slot can never
18
+ * make a later append overwrite a persisted chunk.
19
+ *
20
+ * `appendEntries(entries)` validates the payload fail-loud BEFORE anything
21
+ * else (an `Error` with `code === 'logs/invalid'`, storage untouched), then
22
+ * runs the write inside ONE serialized chain: load the cursor, write the
23
+ * chunk, restamp the global, rotate. A batch is 1–200 entries, so one chunk
24
+ * never exceeds 200 entries.
25
+ *
26
+ * `createExporter({ loggerName })` returns a cordis exporter object:
27
+ * records are accepted only for the named logger (`message.name`), same-tick
28
+ * records coalesce via ONE microtask into a single batch, and an oversized
29
+ * coalesced batch splits into ≤200-entry `appendEntries` calls made
30
+ * sequentially (the write chain serializes them — a chatty tick must never
31
+ * hit the `logs/invalid` >200 rejection). Exporter entries carry
32
+ * `source: 'host'`, `scope: 'host'` and `text = formatLogArgs(args)`.
33
+ *
34
+ * Concurrency shape (the preferences-service pattern):
35
+ * - the unit opens lazily on first use, memoized; concurrent callers share
36
+ * one open promise;
37
+ * - every append runs inside ONE internal write chain (promise queue) —
38
+ * the KV unit does NOT serialize writes itself, and each append must read
39
+ * the cursor, write the chunk and rotate as one uninterrupted critical
40
+ * section. A rejected write never poisons the chain (the chain tail stays
41
+ * settled);
42
+ * - the FIRST `kv.open` failure DEGRADES the service permanently (spec §7.2,
43
+ * deliberately different from preferences-service's retry-on-next-call):
44
+ * `appendEntries` then always resolves `{ accepted: 0 }`, never retries
45
+ * the open, and reports the failure via `report.error` exactly once.
46
+ *
47
+ * Re-entrancy guard: while the exporter is processing (building entries /
48
+ * appending) a flag makes it ignore incoming records — the log module's own
49
+ * errors (routed to `report.error`/console) can never loop back into the
50
+ * channel. `export()` never throws on any input. A rotation pass deleting
51
+ * more than 500 entries reports one `report.warn` (storage anomaly
52
+ * touchpoint, spec §7.2).
53
+ *
54
+ * Failure policy: `appendEntries` is fail-loud for structural violations
55
+ * (`logs/invalid`) and propagates storage write rejections to its caller
56
+ * (the RPC endpoint / exporter layer decides what to do with them); the
57
+ * exporter catches everything it triggers and reports instead of throwing.
58
+ * `close()` is terminal: it drains the write chain and releases the unit,
59
+ * after which `appendEntries` resolves `{ accepted: 0 }` rather than lazily
60
+ * reopening it (a post-close exporter microtask must never leave a unit
61
+ * open across a quick fiber restart). `report` defaults to `console`.
62
+ *
63
+ * @module @dybai/dsh-editor/host/log-service
64
+ */
65
+
66
+ import { formatLogArgs } from './log-serialize.js';
67
+
68
+ /**
69
+ * Static identity and shape of the `dsh_editor_logs` KV unit (verbatim,
70
+ * storage contract; single layout is the backend's default, so it is not
71
+ * declared).
72
+ */
73
+ const UNIT_DESCRIPTOR = Object.freeze({
74
+ name: 'dsh_editor_logs',
75
+ version: 1,
76
+ tables: Object.freeze(['chunks']),
77
+ hasGlobal: true
78
+ });
79
+
80
+ /** Table whose records are the log chunks: record key = padded seq. */
81
+ const TABLE = 'chunks';
82
+
83
+ /** Entry levels the channel persists. */
84
+ const LEVELS = new Set(['debug', 'info', 'warn', 'error']);
85
+ /** Entries per appendEntries call (the RPC batch cap). */
86
+ const MAX_BATCH_ENTRIES = 200;
87
+ /** Rotation cap: total persisted entries converge to at most this. */
88
+ const MAX_TOTAL_ENTRIES = 2000;
89
+ /** Rotation cap: chunks older than 7 days are pruned (ts == cutoff KEPT). */
90
+ const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
91
+ /**
92
+ * Rotation anomaly threshold (spec §7.2): one rotation pass deleting MORE
93
+ * than 500 entries is reported via `report.warn`.
94
+ */
95
+ const ROTATION_ANOMALY_ENTRIES = 500;
96
+ /** Scope length cap for an entry. */
97
+ const MAX_SCOPE_CHARS = 64;
98
+ /** Text length cap for an entry. */
99
+ const MAX_TEXT_CHARS = 2000;
100
+ /** Scope stamped on exporter-built (Host) entries. */
101
+ const HOST_SCOPE = 'host';
102
+ /** Source stamped on exporter-built (Host) entries. */
103
+ const HOST_SOURCE = 'host';
104
+ /** The only source `appendEntries` accepts (Host entries never go via RPC). */
105
+ const CLIENT_SOURCE = 'client';
106
+
107
+ /**
108
+ * Build a stable-code error (`message` === `code`, plus a `.code` property
109
+ * the client can switch on).
110
+ * @param code - stable discriminant, e.g. 'logs/invalid'.
111
+ * @returns a fresh Error carrying the code.
112
+ */
113
+ function codedError(code) {
114
+ const error = new Error(code);
115
+ error.code = code;
116
+ return error;
117
+ }
118
+
119
+ /**
120
+ * Chunk record key: `'c'` + the seq zero-padded to 12 digits, so
121
+ * lexicographic order equals numeric order.
122
+ * @param seq - the chunk's monotonic sequence number.
123
+ * @returns the 13-character record key.
124
+ */
125
+ function chunkKey(seq) {
126
+ return `c${String(seq).padStart(12, '0')}`;
127
+ }
128
+
129
+ /**
130
+ * Read the `lastSeq` cursor out of the unit's global singleton.
131
+ * @param global - the global slot as `loadAll` returned it (`null` when
132
+ * never written).
133
+ * @returns the stored number, or 0 when nothing was written yet.
134
+ */
135
+ function globalLastSeq(global) {
136
+ if (global !== null && typeof global === 'object' && typeof global.lastSeq === 'number') {
137
+ return global.lastSeq;
138
+ }
139
+ return 0;
140
+ }
141
+
142
+ /**
143
+ * One table's records out of a `loadAll` snapshot (`{}` when absent).
144
+ * @param snapshot - the `loadAll` result.
145
+ * @param name - table name.
146
+ * @returns the table's record map.
147
+ */
148
+ function tableOf(snapshot, name) {
149
+ return snapshot.tables !== null && typeof snapshot.tables === 'object' ? snapshot.tables[name] ?? {} : {};
150
+ }
151
+
152
+ /**
153
+ * Validate one entry: `ts` a finite number, `level` one of the four levels,
154
+ * `source` matching the expected lane (`'client'` for the public RPC lane,
155
+ * `'host'` for the exporter's internal lane — spec §5: Host entries never
156
+ * go through RPC), `scope` a non-empty string of at most 64 chars, `text` a
157
+ * string of at most 2000 chars. Extra properties are tolerated (only the
158
+ * contract fields are read).
159
+ * @param entry - the caller's entry.
160
+ * @param source - the lane's required source value.
161
+ * @returns whether the entry is storable.
162
+ */
163
+ function isValidEntry(entry, source) {
164
+ if (entry === null || typeof entry !== 'object') return false;
165
+ if (typeof entry.ts !== 'number' || !Number.isFinite(entry.ts)) return false;
166
+ if (!LEVELS.has(entry.level)) return false;
167
+ if (entry.source !== source) return false;
168
+ if (typeof entry.scope !== 'string' || entry.scope.length === 0 || entry.scope.length > MAX_SCOPE_CHARS) return false;
169
+ if (typeof entry.text !== 'string' || entry.text.length > MAX_TEXT_CHARS) return false;
170
+ return true;
171
+ }
172
+
173
+ /**
174
+ * Validate an append payload: an array of 1–200 valid entries.
175
+ * @param entries - the caller's payload.
176
+ * @param source - the lane's required source value.
177
+ * @returns whether the payload is storable.
178
+ */
179
+ function isValidEntries(entries, source) {
180
+ if (!Array.isArray(entries) || entries.length === 0 || entries.length > MAX_BATCH_ENTRIES) return false;
181
+ for (const entry of entries) {
182
+ if (!isValidEntry(entry, source)) return false;
183
+ }
184
+ return true;
185
+ }
186
+
187
+ /**
188
+ * Build the Host log service.
189
+ * @param kv - a `StorageBackend` KvFacet (`open(descriptor)` → `KvUnit`).
190
+ * @param now - clock producing millisecond chunk timestamps.
191
+ * @param report - internal failure sink; `error` is called on permanent
192
+ * degrade and exporter failures, `warn` on rotation anomalies (a pass
193
+ * deleting more than 500 entries). Both default to `console`.
194
+ * @returns the service (methods on its prototype so a Host SRC registration
195
+ * can read them for remote discovery); also carries `close()` for disposal.
196
+ */
197
+ export function createLogService({ kv, now, report }) {
198
+ if (kv === undefined || kv === null || typeof kv.open !== 'function') {
199
+ throw new Error('dsh-editor: createLogService requires a kv facet with open(descriptor)');
200
+ }
201
+ if (typeof now !== 'function') {
202
+ throw new Error('dsh-editor: createLogService requires a now() clock function');
203
+ }
204
+
205
+ /** Memoized `kv.open(UNIT_DESCRIPTOR)`; undefined until first use. */
206
+ let unitPromise;
207
+ /** Tail of the serialized write queue; always settled, never rejecting. */
208
+ let writeChain = Promise.resolve();
209
+ /** Permanent degrade flag: set by the FIRST open failure, never cleared. */
210
+ let degraded = false;
211
+ /**
212
+ * Set synchronously when `close()` begins: the service never opens or
213
+ * reopens a unit again, so a late exporter microtask queued just before
214
+ * fiber disposal cannot resurrect the unit (a "same unit opened twice"
215
+ * rejection on a quick restart). Jobs already enqueued before close still
216
+ * drain first.
217
+ */
218
+ let closed = false;
219
+
220
+ /**
221
+ * Report one internal failure through `report.error`, falling back to
222
+ * `console.error`. The report channel itself must never throw (iron
223
+ * rule): a hostile sink is swallowed.
224
+ * @param args - message parts handed to the sink.
225
+ */
226
+ function reportError(...args) {
227
+ try {
228
+ if (typeof report?.error === 'function') {
229
+ report.error(...args);
230
+ } else {
231
+ console.error(...args);
232
+ }
233
+ } catch {
234
+ // 上报通道自身失败只吞掉:日志模块的失败不得外溢
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Report one internal anomaly through `report.warn`, falling back to
240
+ * `console.warn`. Same swallow rule as `reportError`.
241
+ * @param args - message parts handed to the sink.
242
+ */
243
+ function reportWarn(...args) {
244
+ try {
245
+ if (typeof report?.warn === 'function') {
246
+ report.warn(...args);
247
+ } else {
248
+ console.warn(...args);
249
+ }
250
+ } catch {
251
+ // 上报通道自身失败只吞掉:日志模块的失败不得外溢
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Open the unit lazily, memoizing the open so concurrent callers share
257
+ * one promise. Unlike preferences-service there is NO forget-on-reject:
258
+ * the first failure degrades this service for its lifetime (spec §7.2),
259
+ * so a retry can never be attempted.
260
+ * @returns the open unit promise.
261
+ */
262
+ function openUnit() {
263
+ if (unitPromise === undefined) {
264
+ unitPromise = kv.open(UNIT_DESCRIPTOR);
265
+ }
266
+ return unitPromise;
267
+ }
268
+
269
+ /**
270
+ * Degrade the service permanently and report the triggering failure
271
+ * exactly once (the flag makes this idempotent).
272
+ * @param error - the open rejection.
273
+ */
274
+ function degrade(error) {
275
+ if (degraded) return;
276
+ degraded = true;
277
+ reportError('dsh-editor log-service: kv.open failed; logging degraded for this session (appendEntries resolves { accepted: 0 }):', error);
278
+ }
279
+
280
+ /**
281
+ * Append one serialized job to the write chain. The returned promise
282
+ * settles with the job's outcome while the chain's tail stays resolved,
283
+ * so one rejected write never poisons the next.
284
+ * @param job - async critical section to run once all earlier writes
285
+ * settled.
286
+ * @returns the job's own outcome.
287
+ */
288
+ function enqueue(job) {
289
+ const run = writeChain.then(job, job);
290
+ writeChain = run.then(
291
+ () => {},
292
+ () => {}
293
+ );
294
+ return run;
295
+ }
296
+
297
+ /**
298
+ * Rotate storage inside the write chain: ONE ascending pass over the
299
+ * stored chunk keys (= seq order, oldest first). A chunk is deleted when
300
+ * the running total still exceeds MAX_TOTAL_ENTRIES after everything
301
+ * deleted before it, OR its stored `ts` is older than the 7-day cutoff
302
+ * (`ts` EQUAL to the cutoff is kept). `remaining` shrinks with every
303
+ * deletion and a chunk never exceeds 200 entries, so the pass terminates
304
+ * with at most MAX_TOTAL_ENTRIES entries. Judging by the STORED `ts`
305
+ * (never re-derived) keeps a regressed clock from deleting fresh chunks.
306
+ * Anomaly touchpoint (spec §7.2): a pass deleting MORE than 500 entries
307
+ * reports exactly one `report.warn` carrying the deleted count.
308
+ * @param unit - the open KV unit.
309
+ * @param storedChunks - pre-write chunks from the job's snapshot,
310
+ * already sorted ascending by key: `{ key, ts, count }`.
311
+ * @param appendedCount - entries in the chunk just written.
312
+ */
313
+ async function rotate(unit, storedChunks, appendedCount) {
314
+ let remaining = appendedCount;
315
+ for (const chunk of storedChunks) remaining += chunk.count;
316
+ const cutoff = now() - RETENTION_MS;
317
+ const doomed = [];
318
+ let deletedEntries = 0;
319
+ for (const chunk of storedChunks) {
320
+ if (remaining > MAX_TOTAL_ENTRIES || chunk.ts < cutoff) {
321
+ doomed.push(chunk.key);
322
+ deletedEntries += chunk.count;
323
+ remaining -= chunk.count;
324
+ }
325
+ }
326
+ if (doomed.length > 0) {
327
+ await unit.deleteRecords(TABLE, doomed);
328
+ }
329
+ if (deletedEntries > ROTATION_ANOMALY_ENTRIES) {
330
+ reportWarn(`dsh-editor log-service: rotation deleted ${deletedEntries} entries in one pass (> ${ROTATION_ANOMALY_ENTRIES}); inspect the dsh_editor_logs storage`);
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Validate, then append one batch as a chunk inside the write chain:
336
+ * load the cursor, `putRecord` the chunk (`{ seq, ts: now(), entries }`),
337
+ * restamp the global, rotate. The public lane requires
338
+ * `source === 'client'` (the RPC contract); the exporter's internal lane
339
+ * requires `source === 'host'` (Host entries never go through RPC).
340
+ * Degraded state always resolves `{ accepted: 0 }`; structural
341
+ * violations reject `logs/invalid` before the chain (and before the
342
+ * unit) is ever touched.
343
+ * @param entries - the caller's payload (1–200 valid entries).
344
+ * @param source - the lane's required source value.
345
+ * @returns `{ accepted }` — the number of entries persisted.
346
+ */
347
+ async function appendEntriesImpl(entries, source) {
348
+ if (!isValidEntries(entries, source)) {
349
+ throw codedError('logs/invalid');
350
+ }
351
+ // A closed service never opens a unit again (the call is synchronous,
352
+ // so no close() can interleave between this check and the enqueue).
353
+ if (degraded || closed) return { accepted: 0 };
354
+ return enqueue(async () => {
355
+ if (degraded) return { accepted: 0 }; // 排队期间前序作业已降级
356
+ let unit;
357
+ try {
358
+ unit = await openUnit();
359
+ } catch (error) {
360
+ degrade(error);
361
+ return { accepted: 0 };
362
+ }
363
+ const snapshot = await unit.loadAll();
364
+ const records = tableOf(snapshot, TABLE);
365
+ // Seq derivation must honor the "keys are NEVER reused" invariant
366
+ // even when the global cursor lies: a rejected `setGlobal` (or a
367
+ // crash between `putRecord` and `setGlobal`, or a lost global
368
+ // slot) leaves the chunk on disk with the cursor unchanged, so
369
+ // the next seq is the max of the global AND the largest chunk key
370
+ // actually stored — read from the SAME snapshot rotation uses.
371
+ let maxSeq = globalLastSeq(snapshot.global);
372
+ const storedChunks = Object.keys(records)
373
+ .sort()
374
+ .map((key) => {
375
+ const record = records[key];
376
+ const keySeq = Number(key.slice(1));
377
+ if (Number.isFinite(keySeq) && keySeq > maxSeq) maxSeq = keySeq;
378
+ return {
379
+ key,
380
+ ts: record?.ts,
381
+ count: Array.isArray(record?.entries) ? record.entries.length : 0
382
+ };
383
+ });
384
+ const seq = maxSeq + 1;
385
+ await unit.putRecord(TABLE, chunkKey(seq), { seq, ts: now(), entries });
386
+ await unit.setGlobal({ lastSeq: seq });
387
+ await rotate(unit, storedChunks, entries.length);
388
+ return { accepted: entries.length };
389
+ });
390
+ }
391
+
392
+ return Object.create({
393
+ /**
394
+ * Append one batch of client entries as a single chunk (the RPC
395
+ * endpoint `dshEditor/appendLogs` delegates here). Only
396
+ * `source === 'client'` entries are accepted — Host entries enter
397
+ * via the exporter's internal lane and never through this public
398
+ * surface.
399
+ * @param entries - 1–200 entries of the contract shape.
400
+ * @returns `{ accepted }`; `{ accepted: 0 }` once degraded.
401
+ * @throws a `logs/invalid` coded Error for a structurally invalid
402
+ * payload (storage untouched).
403
+ */
404
+ async appendEntries(entries) {
405
+ return appendEntriesImpl(entries, CLIENT_SOURCE);
406
+ },
407
+
408
+ /**
409
+ * Build a cordis exporter for ONE named logger: only records with
410
+ * `message.name === loggerName` enter the channel. Same-tick records
411
+ * coalesce into one batch flushed on a microtask; a batch over 200
412
+ * entries splits into sequential ≤200-entry appends. Records arriving
413
+ * while a flush is in flight are dropped (the re-entrancy guard: the
414
+ * module's own errors must never loop back into the channel).
415
+ * `export` NEVER throws.
416
+ * @param loggerName - the cordis logger name to filter by.
417
+ * @returns the `{ export(message) }` exporter object.
418
+ */
419
+ createExporter({ loggerName }) {
420
+ /** Same-tick coalesced records awaiting the flush microtask. */
421
+ let queue = [];
422
+ /** Whether the flush microtask is scheduled. */
423
+ let scheduled = false;
424
+ /** Re-entrancy guard: true while building entries / appending. */
425
+ let processing = false;
426
+
427
+ /**
428
+ * Drain the coalesced queue into the write chain; any failure is
429
+ * reported (never thrown, never re-queued).
430
+ */
431
+ const flush = async () => {
432
+ scheduled = false;
433
+ if (queue.length === 0) return;
434
+ const messages = queue;
435
+ queue = [];
436
+ processing = true;
437
+ try {
438
+ const entries = messages.map((message) => ({
439
+ ts: now(),
440
+ level: message?.type,
441
+ source: HOST_SOURCE,
442
+ scope: HOST_SCOPE,
443
+ text: formatLogArgs(message?.args)
444
+ }));
445
+ for (let i = 0; i < entries.length; i += MAX_BATCH_ENTRIES) {
446
+ await appendEntriesImpl(entries.slice(i, i + MAX_BATCH_ENTRIES), HOST_SOURCE);
447
+ }
448
+ } catch (error) {
449
+ reportError('dsh-editor log-service: exporter append failed:', error);
450
+ } finally {
451
+ processing = false;
452
+ }
453
+ };
454
+
455
+ return {
456
+ /**
457
+ * Cordis exporter entry point.
458
+ * @param message - `{ name, type, args }` logger record.
459
+ */
460
+ export(message) {
461
+ try {
462
+ if (processing) return; // 防自激:处理期间一律拦截
463
+ if (message?.name !== loggerName) return; // 只收命名 logger
464
+ queue.push(message);
465
+ if (!scheduled) {
466
+ scheduled = true;
467
+ queueMicrotask(flush);
468
+ }
469
+ } catch {
470
+ // 铁律:export 永不 throw
471
+ }
472
+ }
473
+ };
474
+ },
475
+
476
+ /**
477
+ * Drain the write chain, close the unit when one was opened, and stop
478
+ * the service for good: from the moment close() begins, later
479
+ * `appendEntries` calls resolve `{ accepted: 0 }` without opening (or
480
+ * reopening) the unit, so a late exporter microtask cannot leave a
481
+ * unit open across a fiber restart. A batch already enqueued before
482
+ * the close still drains and persists. Idempotent; a degraded open
483
+ * failure does not reject the close. Wired into the plugin's effect
484
+ * cleanup.
485
+ * @returns resolution after the unit (if any) is released.
486
+ */
487
+ async close() {
488
+ closed = true;
489
+ const closing = writeChain.then(async () => {
490
+ if (unitPromise === undefined) return;
491
+ const unit = await unitPromise.catch(() => undefined); // 降级 memo 不让 close 炸
492
+ unitPromise = undefined;
493
+ if (unit !== undefined) {
494
+ await unit.close();
495
+ }
496
+ });
497
+ writeChain = closing.then(
498
+ () => {},
499
+ () => {}
500
+ );
501
+ return closing;
502
+ }
503
+ });
504
+ }
@@ -7,7 +7,7 @@
7
7
  * - `mode_associations` — the complete set of `glob → modeId` associations
8
8
  * the "open as default" / "reset to default" menu writes;
9
9
  * - `keymap` — the framework's SELF-MANAGED key bindings for the actions
10
- * save / saveAll / deleteLines (record key = action id, value =
10
+ * save / saveAll / deleteLines / gotoLine (record key = action id, value =
11
11
  * `{ code, modifiers, updatedAt }`), written by the status-bar keymap
12
12
  * recorder;
13
13
  * - `settings` — the editor's behavior toggles (record key = setting name,
@@ -74,8 +74,8 @@ const SETTINGS_TABLE = 'settings';
74
74
  /** Setting names this build knows; unknown keys in a payload are rejected. */
75
75
  const SETTINGS_KEYS = new Set(['autoReloadClean', 'highlightActiveLine', 'showLineNumbers']);
76
76
 
77
- /** Keymap action ids the editor framework owns (spec §6). */
78
- const KEYMAP_ACTIONS = new Set(['save', 'saveAll', 'deleteLines']);
77
+ /** Keymap action ids the editor framework owns (spec §6; `gotoLine` v0.6.0). */
78
+ const KEYMAP_ACTIONS = new Set(['save', 'saveAll', 'deleteLines', 'gotoLine']);
79
79
  /** Storable `KeyboardEvent.code` alphabet for a keymap binding. */
80
80
  const KEYMAP_CODE_RE = /^(Key[A-Z]|Digit[0-9])$/;
81
81
  /** Abstract modifier vocabulary for a keymap binding. */
@@ -138,7 +138,7 @@ function tableOf(snapshot, name) {
138
138
 
139
139
  /**
140
140
  * Validate the keymap payload: a NON-EMPTY array of
141
- * `{ action ∈ {save, saveAll, deleteLines}, code: /^(Key[A-Z]|Digit[0-9])$/,
141
+ * `{ action ∈ {save, saveAll, deleteLines, gotoLine}, code: /^(Key[A-Z]|Digit[0-9])$/,
142
142
  * modifiers: array ⊆ {primary, control, alt, shift, meta} }` with unique
143
143
  * action ids and no two bindings sharing one (code, modifier-set) combo — a
144
144
  * duplicated combo would make dispatch ambiguous. Extra properties are