@sema-agent/settings-schema 33.1.0 → 34.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +414 -0
  2. package/README.md +118 -14
  3. package/conformance/VERSION +1 -1
  4. package/dist/atomic-write.d.ts +59 -0
  5. package/dist/atomic-write.js +303 -1
  6. package/dist/cli.d.ts +5 -2
  7. package/dist/cli.js +15 -3
  8. package/dist/config-dir-migration.d.ts +2 -1
  9. package/dist/config-dir-migration.js +34 -20
  10. package/dist/config-fns.d.ts +60 -14
  11. package/dist/config-fns.js +48 -13
  12. package/dist/conformance/index.d.ts +1 -0
  13. package/dist/conformance/index.js +2 -0
  14. package/dist/conformance/warnings.d.ts +1 -1
  15. package/dist/conformance/warnings.js +3 -3
  16. package/dist/conformance/web-admin-credential-lock.d.ts +17 -0
  17. package/dist/conformance/web-admin-credential-lock.js +346 -0
  18. package/dist/cross-session.d.ts +2 -2
  19. package/dist/fleet.d.ts +5 -5
  20. package/dist/hooks-config.d.ts +12 -4
  21. package/dist/hooks-config.js +28 -11
  22. package/dist/index.js +2 -2
  23. package/dist/local-load.d.ts +66 -1
  24. package/dist/local-load.js +123 -39
  25. package/dist/mcp-request-entry.d.ts +24 -5
  26. package/dist/mcp-request-entry.js +57 -17
  27. package/dist/node.d.ts +1 -0
  28. package/dist/node.js +2 -0
  29. package/dist/read-sentences.d.ts +14 -3
  30. package/dist/read-sentences.js +32 -11
  31. package/dist/safety-merge-spec.d.ts +5 -5
  32. package/dist/safety-merge-spec.js +5 -3
  33. package/dist/settings-units.d.ts +35 -1
  34. package/dist/settings-units.js +51 -16
  35. package/dist/types.d.ts +9 -9
  36. package/dist/types.js +27 -8
  37. package/dist/ui-language.d.ts +3 -1
  38. package/dist/ui-language.js +3 -1
  39. package/dist/web-admin-credential.d.ts +14 -1
  40. package/dist/web-admin-credential.js +15 -1
  41. package/docs/API-SURFACE.md +31 -4
  42. package/docs/CONFORMANCE.md +19 -2
  43. package/docs/CONSUMER-INTEGRATION.md +114 -10
  44. package/llms-full.txt +39 -10
  45. package/llms.txt +15 -7
  46. package/package.json +1 -1
@@ -45,12 +45,35 @@
45
45
  * 认得的 errno 给对应出路,别的给 Node 自己的句子;`code` / `cause` 留着。
46
46
  * 可写目录里的只读文件照常写得进(`rename` 换的是目录项)。权限类 errno 的出路要一个只有 Node 一侧读得到的事实 —— 失败那一刻目录的权限位对本进程是否可写({@link directoryAdmitsWrite},模式判在本文件、与模式表同处),
47
47
  * 写器在建临时文件那一步读了经落点递给铸点(`EPERM` ∧ 可写 ⇒ 真因是不可变标志,首选出路是清标志;`EACCES` ∧ 可写 ⇒ 真因是 ACL / 安全模块;不可写 ⇒ 先让目录可写);`chmod` / `rename` 那两步不读 —— 临时文件刚在同目录建成,可写是已证明的事实,铸点自己给。
48
+ *
49
+ * ## web-admin 凭证文件的单写者锁({@link tryWebAdminCredentialFileLock},经 `./node` 出门)
50
+ * 同一只凭证文件(`SEMA_WEB_ADMIN_TOKEN_FILE` 指的信封)有两个写者:引擎的续签写回与壳的登录 / 刷新 / 登出。规则一条:**每一次改写 / 删除都在这只文件的叶子锁里「比较再写」**
51
+ * —— 锁内重读(原语把锁内读到的文本交给回调),世代等于这次动作预期的前像才落(比较归调用方:续签写回 = 它消费掉的那一代;读后改写 = 读时那一代;登出 / 新登录 = 任意),
52
+ * 否则一个字节不写。锁内只许同步的本机 IO(不出网、不等待、不再取别的锁),所以「锁的年龄」能当崩溃的证据。协议常量与锁名在包根(`./web-admin-credential`)。
53
+ * 锁的形(全部同步,不循环):
54
+ * 1. 凭证路径按**真目标**解({@link resolveSymlinkTarget},与原子写器同一只判法:软链写穿、悬空链接响亮拒);锁 = 真目标所在目录的 `.<真文件名>.lock`。
55
+ * 已知限制:经软链到达的凭据文件,登出(删掉链接指向的真目标)之后链接悬空 ⇒ 再取锁答 `unreadable`(失败关闭:不建文件、不写;出路 = 删掉悬空链接,或先重建目标);
56
+ * 悬空链接上「解到链接指向的落点」要另一套解软链的读法(含相对链接文本 / 尾斜线 / 跳数 / 判与开之间的变化),本版不带。
57
+ * 2. **取**:`open(锁, "wx")` 独占建;身份 = 这只 fd 的 `(dev, ino)`(与建立同一次拿到,不事后按路径 `stat`),**fd 开到放锁核完身份**:身份只是两个数,文件被删后
58
+ * inode 号可被新文件复用,钉住文件对象才让比对成立。撞 `EEXIST` ⇒ 先 `lstat` 锁路径:**不是普通文件**(命名管道 / 目录 / 任何符号链接,悬空与否)⇒ 答 `unreadable`(取锁那一刻看到的这种占位物:同码同句,
59
+ * 不打开它、不等待、不碰它);是普通文件 ⇒ 以非阻塞只读打开那只锁(同样钉住它,打开后再核一遍类型)读它的 mtime:不在了(持有者刚放)⇒ 再试一次;
60
+ * `now − mtime ≤ staleMs`(含 mtime 在未来 —— 时钟回拨不是持有者死了的证据)⇒ 忙;更老 ⇒ 收残留,收完再试一次。至多两次 `open(…, "wx")`,第二次再撞即忙 —— 从不等待。
61
+ * 已知限制(竞态窗,不声称封住;只对「判类型与动手之间锁名上的东西被换掉」成立):① `lstat` 判成普通文件之后、打开之前被换成软链 ⇒ 状态仍 `unreadable`,但 `code` 与句子是内核原生的(`ELOOP`),
62
+ * 不是上面那一句;② 第一次碰撞之后锁消失、第二次独占建之前锁名上被放进目录 / 软链 ⇒ 第二次直接答 `busy`(没有类型判);③ 旧锁过了 `fstat`、收残留的 `rename` 之前被换成软链 ⇒ 那只软链被当残留挪走、删掉。
63
+ * 3. **收 / 放同一套动作**({@link removeLockIf}):把锁路径上那只**改名挪开**(挪开件名长度有界,不接在锁名后)→ 核挪走的那只的身份 → 删掉挪开件。挪走的不是要收的那只
64
+ * (别人刚收完残留建的新锁)⇒ 答忙,那只锁的持有者从此读到失锁、这一次写不成;**不挪回**(挪回会盖掉第三者在锁名空出来那一刻合法建的锁)。
65
+ * 放锁先核身份,不是自己的就一个字节都不动。从不按路径删锁。
66
+ * 4. **最后一个系统调用前核身份**:回调经把手的 `replaceWith` / `remove` 落凭证文件,这两只先核锁路径上那只仍是自己钉着的那只,不是 ⇒ 答 `false`、不改名 / 不删。
67
+ * 失锁是粘的:把手答过一次「不是自己的」(含读不出)之后不再落写。写没写成看这两只方法的答案,不看结果是不是 `lost`。
68
+ * 5. 取锁 / 锁内读真目标的文件系统失败 ⇒ 结果 `unreadable`(带包里的文件系统失败句);**绝不退回无锁执行**。
69
+ * 剩下的一拍(不声称封住):持有者核过身份、还没落那一次改名 / 删除的系统调用期间,它的锁恰被挪走(它冻住了 > staleMs,或两只收残留者撞车时挪走了它刚建的锁)—— 对方的写可能落在它前面。
48
70
  */
49
71
  import { randomBytes } from "node:crypto";
50
72
  import { readFile } from "node:fs/promises";
51
- import { chmodSync, closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
73
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
52
74
  import path from "node:path";
53
75
  import { FsFailure } from "./fs-failure.js";
76
+ import { WEB_ADMIN_CREDENTIAL_FILE_LOCK, webAdminCredentialLockName } from "./web-admin-credential.js";
54
77
  /** 按文档类的模式表(闭集)。 */
55
78
  export const ATOMIC_FILE_CLASSES = {
56
79
  "config-document": { newMode: 0o644, existing: "keep" },
@@ -312,3 +335,282 @@ export function ensureOwnerOnlyDirectory(dir) {
312
335
  }
313
336
  return created ? "created" : "present";
314
337
  }
338
+ // ── web-admin 凭证文件的单写者锁(见文件头同名一节)───────────────────────────────────────────────────────────────────────────
339
+ /** 锁文件新建的模式(经进程 umask):属主读写 —— 锁里只有诊断用的 pid 与随机串,不是秘密;它与凭证文件同目录,取与凭证同档的属主独占。锁文件不是文档类,不进 {@link ATOMIC_FILE_CLASSES}。 */
340
+ const CREDENTIAL_LOCK_FILE_MODE = 0o600;
341
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
342
+ const closeQuietly = (fd) => {
343
+ try {
344
+ closeSync(fd);
345
+ }
346
+ catch {
347
+ /* 关不掉的 fd 不改判 */
348
+ }
349
+ };
350
+ /** 路径上那只条目的身份;不在 ⇒ `undefined`;别的失败照抛。 */
351
+ function identityAt(p) {
352
+ try {
353
+ const st = statSync(p, { bigint: true });
354
+ return { dev: st.dev, ino: st.ino };
355
+ }
356
+ catch (e) {
357
+ if (e.code === "ENOENT")
358
+ return undefined;
359
+ throw e;
360
+ }
361
+ }
362
+ /**
363
+ * 收残留与放锁的**唯一一套动作**:把 `lock` 路径上那只**改名挪开**(同目录的 `.lock-aside.<进程号>.<随机>` —— 名字长度有界,不接在锁名后面:锁名已接近文件名上限时
364
+ * 挪开件名也不会超)→ 核挪走的那只是不是 `expected`(调用方此刻钉着 `expected` 那个文件对象,比对才成立)→ **挪开件一律删掉**。
365
+ * 答 `removed`(挪走的正是 `expected`)/ `displaced`(挪走的是别人的锁 —— 它的持有者从此读到失锁、写不成)/ `absent`(锁路径上本来就没有东西)。
366
+ * 不挪回:挪回只能用 `rename`,它会盖掉第三者在锁名空出来那一刻合法建的锁,造出两个都以为自己持锁的写者;删掉挪错的那只只让它的持有者这一次写不成(失败关闭)。
367
+ * 挪开件删不掉(目录这一刻变得不可写)⇒ 锁路径已经空出来,挪开件留作残件,不改判。
368
+ * 包内导出(不出任何子路径):协议一致性测试扮「另一个写者」接手时也走这一套动作,不另写一份(也不按路径删锁)。
369
+ */
370
+ export function removeLockIf(lock, expected) {
371
+ const aside = entryIn(path.dirname(lock), `.lock-aside.${process.pid}.${randomBytes(6).toString("hex")}`);
372
+ try {
373
+ renameSync(lock, aside);
374
+ }
375
+ catch (e) {
376
+ if (e.code === "ENOENT")
377
+ return "absent";
378
+ throw e;
379
+ }
380
+ let moved;
381
+ try {
382
+ moved = identityAt(aside);
383
+ }
384
+ catch {
385
+ moved = undefined; // 读不出挪走的那只 ⇒ 不认它是 `expected`
386
+ }
387
+ try {
388
+ unlinkSync(aside);
389
+ }
390
+ catch {
391
+ /* 锁路径已空出来;挪开件留作残件 */
392
+ }
393
+ return moved !== undefined && sameFile(moved, expected) ? "removed" : "displaced";
394
+ }
395
+ /** 独占建锁文件,身份取自这只 fd,**fd 不关**(交给持有者钉到放锁);写进 `pid + 随机串`(只作诊断,不作判据;写不进不改判)。`EEXIST` 与别的失败照抛。 */
396
+ function createLockFile(lock) {
397
+ const fd = openSync(lock, "wx", CREDENTIAL_LOCK_FILE_MODE);
398
+ let st;
399
+ try {
400
+ st = fstatSync(fd, { bigint: true });
401
+ }
402
+ catch (e) {
403
+ closeQuietly(fd); // 身份读不出:这只锁留在路径上,staleMs 之后可收(不按路径删)
404
+ throw e;
405
+ }
406
+ try {
407
+ writeSync(fd, `${process.pid} ${randomBytes(6).toString("hex")}\n`);
408
+ }
409
+ catch {
410
+ /* 诊断内容写不进:锁照样成立 */
411
+ }
412
+ return { fd, id: { dev: st.dev, ino: st.ino } };
413
+ }
414
+ /**
415
+ * 锁名上是一个**不是普通文件**的东西 —— 命名管道 / 套接字 / 设备 / 目录 / 任何符号链接(悬空与否)。协议只建普通文件,这些读不成一只锁:等它(命名管道的只读打开没有写端就永远等,违反「从不等待」)、
416
+ * 按它的年龄当残留收、把悬空链接当「持有者刚放锁」重试,都不对。**一个读法**:取锁答 `unreadable`,同一个 `code`(`EEXIST`:锁名被一个不是锁的东西占着)、同一句(出路:把它挪走)—— 对取锁那一刻看到的占位物;判类型与动手之间被换掉的竞态窗见头注「已知限制」。
417
+ */
418
+ function lockNameTaken() {
419
+ return Object.assign(new Error("the lock name is taken by something that is not a regular file (a named pipe, a directory, a symbolic link) — a lock is only ever a regular file; move that entry away"), { code: "EEXIST" });
420
+ }
421
+ const flagOrZero = (flag) => flag ?? 0;
422
+ /** 看锁的只读打开的标志:`O_NONBLOCK`(锁名万一被命名管道占着,打开不等写端)与 `O_NOFOLLOW`(不跟符号链接);没有这两个标志的平台(Windows)取 0,靠前后的类型判({@link lockNameTaken})挡。 */
423
+ const LOCK_PEEK_FLAGS = fsConstants.O_RDONLY | flagOrZero(fsConstants.O_NONBLOCK) | flagOrZero(fsConstants.O_NOFOLLOW);
424
+ /**
425
+ * 以只读打开锁路径上那只、钉住它,读它的身份与 mtime。不在 ⇒ `undefined`;锁名上不是普通文件 ⇒ 抛 {@link lockNameTaken}(**打开之前**先 `lstat` 判类型:符号链接与命名管道不被打开;
426
+ * 打开之后再 `fstat` 判一遍:`lstat` 与打开之间被换成别的东西也挡得住,命名管道有 `O_NONBLOCK`、打开本身不会挂);别的失败照抛。
427
+ */
428
+ function pinLockAt(lock) {
429
+ try {
430
+ if (!lstatSync(lock).isFile())
431
+ throw lockNameTaken();
432
+ }
433
+ catch (e) {
434
+ if (e.code === "ENOENT")
435
+ return undefined;
436
+ throw e;
437
+ }
438
+ let fd;
439
+ try {
440
+ fd = openSync(lock, LOCK_PEEK_FLAGS);
441
+ }
442
+ catch (e) {
443
+ if (e.code === "ENOENT")
444
+ return undefined;
445
+ throw e;
446
+ }
447
+ try {
448
+ const st = fstatSync(fd, { bigint: true });
449
+ if (!st.isFile())
450
+ throw lockNameTaken();
451
+ return { fd, id: { dev: st.dev, ino: st.ino }, mtimeMs: Number(st.mtimeMs) };
452
+ }
453
+ catch (e) {
454
+ closeQuietly(fd);
455
+ throw e;
456
+ }
457
+ }
458
+ /** 取锁:至多两次 `open`、从不等待(见文件头那一节的第 2 步)。文件系统失败抛 {@link FsFailure}(落点:建锁 = 往目录里建文件;看锁 = 读;收残留 = 改名)。 */
459
+ function acquireCredentialLock(lock, staleMs) {
460
+ for (let attempt = 0;; attempt += 1) {
461
+ try {
462
+ return { kind: "held", mine: createLockFile(lock) };
463
+ }
464
+ catch (e) {
465
+ if (e.code !== "EEXIST")
466
+ throw new FsFailure({ landing: "dir-create-temp", path: lock, directoryWritable: directoryAdmitsWrite(path.dirname(lock)) }, e);
467
+ }
468
+ if (attempt > 0)
469
+ return { kind: "busy" };
470
+ let seen;
471
+ try {
472
+ seen = pinLockAt(lock);
473
+ }
474
+ catch (e) {
475
+ throw new FsFailure({ landing: "read", of: "file", path: lock }, e);
476
+ }
477
+ if (seen === undefined)
478
+ continue; // 持有者刚放锁:再试一次
479
+ try {
480
+ const ageMs = Date.now() - seen.mtimeMs;
481
+ if (!(ageMs > staleMs))
482
+ return ageMs >= 0 ? { kind: "busy", heldForMs: ageMs } : { kind: "busy" }; // 新鲜,或 mtime 在未来(时钟回拨):忙
483
+ let reclaimed;
484
+ try {
485
+ reclaimed = removeLockIf(lock, seen.id); // 被判的那只此刻由 `seen.fd` 钉着:它的号不会被别的文件拿到
486
+ }
487
+ catch (e) {
488
+ throw new FsFailure({ landing: "rename", path: lock }, e);
489
+ }
490
+ if (reclaimed === "displaced")
491
+ return { kind: "busy" }; // 挪走的是别人刚收完残留建的新锁:它的持有者读到失锁;这一回让出,不接着抢
492
+ }
493
+ finally {
494
+ closeQuietly(seen.fd);
495
+ }
496
+ }
497
+ }
498
+ /**
499
+ * 在 web-admin 凭证文件的单写者锁里跑一次「读 → 比较 → 写」(规则与锁的形见文件头同名一节)。只试一次,从不等待:忙 ⇒ `busy`,调用方按自己的退避再来。
500
+ * `critical` 只许同步:返回类型对 `PromiseLike` 求值为 `never`,直接传 async 回调 = 编译错(静态误用防线,拦不住拓宽成 `unknown` 的回调、或回调里起一个不等待的异步任务);
501
+ * 运行期回调交回一个 thenable ⇒ 放锁后抛 `TypeError`(持锁段已经结束,它之后做的事不在锁里)。回调抛 ⇒ 放锁后原样重抛。
502
+ */
503
+ export function tryWebAdminCredentialFileLock(credentialPath, critical) {
504
+ let target;
505
+ try {
506
+ target = resolveSymlinkTarget(credentialPath);
507
+ }
508
+ catch (e) {
509
+ return { status: "unreadable", error: new FsFailure({ landing: "read", of: "file", path: credentialPath }, e) };
510
+ }
511
+ const lock = entryIn(path.dirname(target), webAdminCredentialLockName(path.basename(target)));
512
+ let attempt;
513
+ try {
514
+ attempt = acquireCredentialLock(lock, WEB_ADMIN_CREDENTIAL_FILE_LOCK.staleMs);
515
+ }
516
+ catch (e) {
517
+ return { status: "unreadable", error: e instanceof FsFailure ? e : new FsFailure({ landing: "read", of: "file", path: lock }, e) };
518
+ }
519
+ if (attempt.kind === "busy")
520
+ return attempt.heldForMs === undefined ? { status: "busy" } : { status: "busy", heldForMs: attempt.heldForMs };
521
+ const { fd: pinFd, id: mine } = attempt.mine; // 这只 fd 钉着自己的锁,直到放锁核完身份
522
+ let open = true;
523
+ let lost = false;
524
+ const live = () => {
525
+ if (!open)
526
+ throw new Error(`the lock on ${target} was already released — a held handle is valid only inside the callback`);
527
+ };
528
+ /** 锁路径上此刻是不是自己钉着的那只;读不出 ⇒ 证明不了 ⇒ 否。 */
529
+ const onPath = () => {
530
+ try {
531
+ const at = identityAt(lock);
532
+ return at !== undefined && sameFile(at, mine);
533
+ }
534
+ catch {
535
+ return false;
536
+ }
537
+ };
538
+ const stillMine = () => {
539
+ live();
540
+ if (lost)
541
+ return false; // 粘的:答过一次「不是」就不再答「是」
542
+ if (!onPath())
543
+ lost = true;
544
+ return !lost;
545
+ };
546
+ const release = () => {
547
+ try {
548
+ if (!onPath()) {
549
+ lost = true; // 锁已不是自己的(或读不出):一个字节都不动(继任者的锁原样留着)
550
+ return;
551
+ }
552
+ let released;
553
+ try {
554
+ released = removeLockIf(lock, mine);
555
+ }
556
+ catch {
557
+ released = "kept"; // 挪不开:锁仍在路径上、刚核过是自己的;staleMs 之后可被收,不改判
558
+ }
559
+ if (released !== "removed" && released !== "kept")
560
+ lost = true; // 核过身份之后、挪开之前它被接走了(只可能是自己的锁已过龄)
561
+ }
562
+ finally {
563
+ open = false;
564
+ closeQuietly(pinFd);
565
+ }
566
+ };
567
+ let current;
568
+ try {
569
+ current = readTextIfPresentSync(target);
570
+ }
571
+ catch (e) {
572
+ release();
573
+ return { status: "unreadable", error: new FsFailure({ landing: "read", of: "file", path: target }, e) };
574
+ }
575
+ const held = Object.freeze({
576
+ target,
577
+ current,
578
+ stillMine,
579
+ replaceWith(tempFile) {
580
+ if (!stillMine())
581
+ return false;
582
+ try {
583
+ renameSync(tempFile, target);
584
+ }
585
+ catch (e) {
586
+ throw new FsFailure({ landing: "rename", path: target }, e);
587
+ }
588
+ return true;
589
+ },
590
+ remove() {
591
+ if (!stillMine())
592
+ return false;
593
+ try {
594
+ unlinkSync(target);
595
+ }
596
+ catch (e) {
597
+ if (e.code !== "ENOENT")
598
+ throw new FsFailure({ landing: "write", path: target }, e);
599
+ }
600
+ return true;
601
+ },
602
+ });
603
+ let value;
604
+ try {
605
+ value = critical(held);
606
+ }
607
+ catch (e) {
608
+ release();
609
+ throw e;
610
+ }
611
+ release();
612
+ if (typeof value?.then === "function") {
613
+ throw new TypeError(`the callback under the lock on ${target} returned a promise — the lock only covers synchronous local IO, and it is already released`);
614
+ }
615
+ return lost ? { status: "lost", value } : { status: "acquired", value };
616
+ }
package/dist/cli.d.ts CHANGED
@@ -18,18 +18,21 @@
18
18
  * 含迁移不碰的陈旧形 —— `models.json` 里 retired 的 `default` 键、带 `#fragment` 的模型 URL、带事实的 `runtime.json` 一类:文档面判官判不过的文档不能报成「无事可做」;
19
19
  * 判官是文档面那一只,与读腿两个方向上不同 —— 比读腿宽(只在逐条丢弃域里:读腿只在那里拒条目体内被剥的键;不逐条丢的域两边都剥键受理、答得一样):条目只因带读侧不认识的键,读腿丢那一条、集合里每一条都这样时整域退缺省 / 整域拒,这里仍答 0;
20
20
  * 比读腿严:逐条丢弃域里一条 schema 不过的条目,读腿只丢它,这里整目录拒),**一字不写**;
21
- * 2 = 用法错,或**环境错**(读目录 / 读文件 / 写盘的 I/O 错:权限、磁盘、悬空符号链接 …;stdout 空、stderr 一行点名路径与 errno,不打栈;句子按落点分句、
21
+ * 任一参数是 `--help` / `-h`(闭集 {@link HELP_FLAGS})= 求用法,不是用法错:用法打 stdout、退出 0、stderr 空;
22
+ * 2 = 用法错(无参、不认识的命令 / 旗标、目录缺或多:用法打 stderr、stdout 空),或**环境错**(读目录 / 读文件 / 写盘的 I/O 错:权限、磁盘、悬空符号链接 …;stdout 空、stderr 一行点名路径与 errno,不打栈;句子按落点分句、
22
23
  * 一律出自文件系统失败句的唯一铸点 `./fs-failure` —— 例:目录建不出文件 ⇒ 点名目录、目标换不掉 ⇒ 点名文件,句尾是对应出路)——
23
24
  * rc 1 是「拒迁」的约定码,不许被一个权限错冒充),或覆盖面内某份文档(域文档或 `remote-exec.json`)是坏文件(空 / 纯空白 / 坏 JSON / 不是 JSON 对象 —— 与 `FileConfigStore` / `loadRemoteExec` 同一只判、同一句),**或目录里有条目却没有一个是域文档**
24
25
  * (多半是填错了目录:要的是 `config.d` 目录本身;`<目录>/config.d` 在场时句子直接点它)(此时 stdout 为空);3 = `--check` 且会有改动、整域判得过(不写)。`--check` 与真跑过同一只判定,只在
25
26
  * 「有改动、且整域判得过」那一支上分开(pending vs applied)—— 整域会被拒的目录 `--check` 也报 refused / rc 1。
26
27
  *
27
28
  * ## 报告形(让「没写」在机读上不可能被读成「写了」)
28
- * 退出码 0 / 1 / 3 时 stdout 恰两行:第 1 行 = **唯一结论行** `outcome=<refused|applied|noop|pending> written=<true|false>`;第 2 行 = JSON 报告
29
+ * 退出码 0 / 1 / 3 时(求用法的那个 0 不算 —— 它的 stdout 是用法)stdout 恰两行:第 1 行 = **唯一结论行** `outcome=<refused|applied|noop|pending> written=<true|false>`;第 2 行 = JSON 报告
29
30
  * (`event: "stored_documents_migrated"`,逐条收据只点名坐标与处置、不带值),同带 `outcome` / `written`。`written` 由 `outcome` 派生
30
31
  * (只有 `applied` 写盘)。**键名带时态**:`written=true` 才有 `applied`;没写(refused / noop / pending)时是 `wouldApply`。
31
32
  * 结论行在**写盘成功之后**才出(写盘抛错 ⇒ 没有 `outcome=applied`)。只写改过的文件,从不删文件 ——
32
33
  * 中途断掉再跑一次,迁移照样恒等收尾(写过的文件已是新形,再迁零改动)。
34
+ * 拒迁(退出 1)时 stderr 另有一行 `settings-schema: <why>; nothing was written`:`why` 是函数结果 `ConfigDirectoryMigration` 的那一句(几处被拒 · 每处的文件、坐标与原因 · 出路:手改后重跑),
35
+ * 其中的原因是 `refused[]` 每条拒 `reason` 里的那一句判官的话(迁移步拒就是收据的 `reason` 本身;同一只铸点,没有第二份措辞;后果与出路另在 `reason` 里)—— 命令行只渲染它;只截 stderr 的日志也读得到原因。
33
36
  */
34
37
  import { type ConfigDirectoryIo } from "./config-dir-migration.js";
35
38
  /** 入口注入的 I/O(核心不碰 node:fs):目录迁移的四个口加 stdout / stderr。入口注入的写盘是 `./atomic-write` 的那一只(经 `./config-dir-io`)。 */
package/dist/cli.js CHANGED
@@ -18,18 +18,21 @@
18
18
  * 含迁移不碰的陈旧形 —— `models.json` 里 retired 的 `default` 键、带 `#fragment` 的模型 URL、带事实的 `runtime.json` 一类:文档面判官判不过的文档不能报成「无事可做」;
19
19
  * 判官是文档面那一只,与读腿两个方向上不同 —— 比读腿宽(只在逐条丢弃域里:读腿只在那里拒条目体内被剥的键;不逐条丢的域两边都剥键受理、答得一样):条目只因带读侧不认识的键,读腿丢那一条、集合里每一条都这样时整域退缺省 / 整域拒,这里仍答 0;
20
20
  * 比读腿严:逐条丢弃域里一条 schema 不过的条目,读腿只丢它,这里整目录拒),**一字不写**;
21
- * 2 = 用法错,或**环境错**(读目录 / 读文件 / 写盘的 I/O 错:权限、磁盘、悬空符号链接 …;stdout 空、stderr 一行点名路径与 errno,不打栈;句子按落点分句、
21
+ * 任一参数是 `--help` / `-h`(闭集 {@link HELP_FLAGS})= 求用法,不是用法错:用法打 stdout、退出 0、stderr 空;
22
+ * 2 = 用法错(无参、不认识的命令 / 旗标、目录缺或多:用法打 stderr、stdout 空),或**环境错**(读目录 / 读文件 / 写盘的 I/O 错:权限、磁盘、悬空符号链接 …;stdout 空、stderr 一行点名路径与 errno,不打栈;句子按落点分句、
22
23
  * 一律出自文件系统失败句的唯一铸点 `./fs-failure` —— 例:目录建不出文件 ⇒ 点名目录、目标换不掉 ⇒ 点名文件,句尾是对应出路)——
23
24
  * rc 1 是「拒迁」的约定码,不许被一个权限错冒充),或覆盖面内某份文档(域文档或 `remote-exec.json`)是坏文件(空 / 纯空白 / 坏 JSON / 不是 JSON 对象 —— 与 `FileConfigStore` / `loadRemoteExec` 同一只判、同一句),**或目录里有条目却没有一个是域文档**
24
25
  * (多半是填错了目录:要的是 `config.d` 目录本身;`<目录>/config.d` 在场时句子直接点它)(此时 stdout 为空);3 = `--check` 且会有改动、整域判得过(不写)。`--check` 与真跑过同一只判定,只在
25
26
  * 「有改动、且整域判得过」那一支上分开(pending vs applied)—— 整域会被拒的目录 `--check` 也报 refused / rc 1。
26
27
  *
27
28
  * ## 报告形(让「没写」在机读上不可能被读成「写了」)
28
- * 退出码 0 / 1 / 3 时 stdout 恰两行:第 1 行 = **唯一结论行** `outcome=<refused|applied|noop|pending> written=<true|false>`;第 2 行 = JSON 报告
29
+ * 退出码 0 / 1 / 3 时(求用法的那个 0 不算 —— 它的 stdout 是用法)stdout 恰两行:第 1 行 = **唯一结论行** `outcome=<refused|applied|noop|pending> written=<true|false>`;第 2 行 = JSON 报告
29
30
  * (`event: "stored_documents_migrated"`,逐条收据只点名坐标与处置、不带值),同带 `outcome` / `written`。`written` 由 `outcome` 派生
30
31
  * (只有 `applied` 写盘)。**键名带时态**:`written=true` 才有 `applied`;没写(refused / noop / pending)时是 `wouldApply`。
31
32
  * 结论行在**写盘成功之后**才出(写盘抛错 ⇒ 没有 `outcome=applied`)。只写改过的文件,从不删文件 ——
32
33
  * 中途断掉再跑一次,迁移照样恒等收尾(写过的文件已是新形,再迁零改动)。
34
+ * 拒迁(退出 1)时 stderr 另有一行 `settings-schema: <why>; nothing was written`:`why` 是函数结果 `ConfigDirectoryMigration` 的那一句(几处被拒 · 每处的文件、坐标与原因 · 出路:手改后重跑),
35
+ * 其中的原因是 `refused[]` 每条拒 `reason` 里的那一句判官的话(迁移步拒就是收据的 `reason` 本身;同一只铸点,没有第二份措辞;后果与出路另在 `reason` 里)—— 命令行只渲染它;只截 stderr 的日志也读得到原因。
33
36
  */
34
37
  import { reportReceipt, joinDirPath, migrateConfigDirectory } from "./config-dir-migration.js";
35
38
  import { MIGRATE_COMMAND_TEMPLATE, migrateCommandFor } from "./retired-form.js";
@@ -48,8 +51,13 @@ const USAGE = [
48
51
  " refused (exit 2); an empty directory has nothing to migrate (exit 0). An I/O failure (reading or writing a file) exits 2 with",
49
52
  " one line on stderr naming the path and the error.",
50
53
  " stdout (exit 0 / 1 / 3): line 1 = outcome=<refused|applied|noop|pending> written=<true|false>, line 2 = the JSON report",
51
- " (applied only when written=true; otherwise wouldApply).",
54
+ " (applied only when written=true; otherwise wouldApply). A refusal (exit 1) also says on stderr, in one line, how many places were refused,",
55
+ " each place's file, coordinate and reason, and the way out (fix it by hand and re-run); the same reasons are in the report's refused[].",
56
+ " --help, -h: print this usage on stdout and exit 0. Any other usage error (no arguments, an unknown command, a missing or extra",
57
+ " directory, a flag it does not know) prints it on stderr and exits 2.",
52
58
  ].join("\n");
59
+ /** 求用法的旗标(闭集):任一参数是它们之一 ⇒ 用法打 stdout、退出 0。别的用法错(无参、不认识的命令 / 旗标、目录缺或多)是 stderr、退出 2。 */
60
+ const HELP_FLAGS = ["--help", "-h"];
53
61
  /** 这个结论写没写盘 —— 只有 `applied` 写。`written` 从这里派生,不是报告里一个可以和 `outcome` 各说各话的独立字段。 */
54
62
  function writtenOf(outcome) {
55
63
  switch (outcome) {
@@ -107,6 +115,10 @@ async function noDomainDocumentsSentence(dir, io) {
107
115
  return nestedExists ? `${base}; ${nested} exists — run: ${migrateCommandFor(nested)}` : base;
108
116
  }
109
117
  export async function runSettingsSchemaCli(argv, io) {
118
+ if (argv.some((a) => HELP_FLAGS.includes(a))) {
119
+ io.stdout(`${USAGE}\n`); // 求用法不是用法错:用法是答案,打 stdout、退 0(只截 stdout 的脚本与习惯 `--help` 退 0 的运维都读成成功)
120
+ return 0;
121
+ }
110
122
  const [command, ...rest] = argv;
111
123
  const check = rest.includes("--check");
112
124
  const dirs = rest.filter((a) => a !== "--check");
@@ -56,7 +56,8 @@ export interface MigrateConfigDirectoryOptions {
56
56
  * 的迁移问的是这一问:一份陈旧的文档不该挡住同目录里别的文档的迁移(同一个目录里别的可迁文档照迁,陈旧的那份由读腿按它的墓碑 / 档位处置);
57
57
  * · `"present"` —— 问「**这个目录现在干不干净**」:在场的**每一份**覆盖面内文档都判(含 retired 域:带事实的墓碑文档读侧拒,这里同拒),判官是文档面那几只
58
58
  * (`parseDomain` / `parseRemoteExecDocument` / 墓碑判 `refuseRetiredDomain`,不另写第二份判形)。不过 ⇒ `refused`、一字不写,`refused[]` 点名文档与坐标;迁移没碰的那几份,`reason` 说读腿会怎么处置它与出路;
59
- * 迁移改过、改完仍判不过的那一份(两个值下都有),`reason` 是判官的原句(`parseDomain` 出门前已脱敏;不带后果与出路、不折行、不剥控制符),出路在整份 `why`(手改后重跑)。命令行 `migrate`(`--check` 与真跑都传它)问的是这一问:运维跑完它不该带着一份文档面判不过的文档上线。
59
+ * 迁移改过、改完仍判不过的那一份(两个值下都有),`reason` 是判官那一句(与读腿告警同一只 `issueSentence`:折成一行、剥过一行回显的剥除集,嵌套的拒句 —— 例:记录的坏键 —— 读到里面一层,整句再过脱敏器;不带后果与出路),
60
+ * 条目本身没有出路,出路在整份 `why`(手改后重跑)。命令行 `migrate`(`--check` 与真跑都传它)问的是这一问:运维跑完它不该带着一份文档面判不过的文档上线。
60
61
  * 判官是文档面那一只(`parseDomain`),它与读腿(视图面)两个方向上不同,这一问的答案因此不等于「读腿读不读得干净」(已知的边):
61
62
  * 比读腿宽(只在逐条丢弃域里:视图面只在那里拒条目体内被剥的键;不逐条丢的域两面都剥键受理、答得一样)—— 条目只因带读侧不认识的键,文档面剥键受理:视图面丢那一条,集合里每一条都这样(零幸存者)时整域退缺省(`models` 读成空目录)/ 整域拒,这一问仍答「干净」;
62
63
  * 比读腿严 —— 逐条丢弃域里一条 schema 不过的条目:视图面只丢它、其余照读,这一问答 `refused`。
@@ -37,7 +37,7 @@ import { fsFailureMessage } from "./fs-failure.js";
37
37
  import { stripControlAndBidi } from "./control-and-bidi.js";
38
38
  import { isPlainJsonObject } from "./plain-json-object.js";
39
39
  import { migrateStoredDocuments } from "./one-time-migrations.js";
40
- import { issueSentence, readConsequenceSentence } from "./read-sentences.js";
40
+ import { causeText, issueSentence, readConsequenceSentence } from "./read-sentences.js";
41
41
  import { REMOTE_EXEC_DOCUMENT } from "./remote-exec.js";
42
42
  import { isDomainName, isRetiredDomainName } from "./types.js";
43
43
  const isConfigDirectoryDocument = (name) => isDomainName(name) || isRetiredDomainName(name) || name === REMOTE_EXEC_DOCUMENT;
@@ -98,7 +98,9 @@ function untouchedReason(name, sentence) {
98
98
  }
99
99
  /**
100
100
  * 一份文档的整文档终判的拒(同一套形:每条 issue 一条 `ConfigDirectoryRefusal`,`migration: null`)。`untouched` = 这份文档迁移没碰(只有 `judge: "present"` 才会判到):
101
- * 它的拒句除判官的原句外,还说读腿会怎么处置它与出路({@link untouchedReason})—— 迁移改过的文档是**我们要写的**那一份,拒句就是判官的原句(整份 `why` 说「手改后重跑」)。
101
+ * 它的拒句除判官的原句外,还说读腿会怎么处置它与出路({@link untouchedReason})—— 迁移改过的文档是**我们要写的**那一份,拒句就是判官的那一句(整份 `why` 说「手改后重跑」)。
102
+ * 两臂的「判官那一句」是同一只 {@link issueSentence}(读腿告警说同一件事用的也是它:记录的坏键说键自己那张 schema 的拒句,不是 zod 的泛话 `Invalid key in record`);
103
+ * 剥掉一行回显的剥除集可以拼出密钥形,所以迁移改过的那一臂的句子在这里再过一次脱敏器(没碰的那一臂在 {@link untouchedReason} 里整句过)。
102
104
  */
103
105
  function wholeDocumentRefusals(name, doc, untouched) {
104
106
  try {
@@ -107,16 +109,36 @@ function wholeDocumentRefusals(name, doc, untouched) {
107
109
  }
108
110
  catch (err) {
109
111
  const found = err instanceof z.ZodError
110
- ? err.issues.map((i) => ({ path: i.path, message: i.message, sentence: issueSentence(i) }))
111
- : [{ path: [], message: messageOf(err), sentence: issueSentence({ message: messageOf(err) }) }];
112
- return found.map((i) => withIdentity(wholeDomainRefusal(name, i.path, untouched ? untouchedReason(name, i.sentence) : i.message), doc, i.path));
112
+ ? err.issues.map((i) => ({ path: i.path, sentence: issueSentence(i) }))
113
+ : [{ path: [], sentence: issueSentence({ message: messageOf(err) }) }];
114
+ return found.map((i) => ({
115
+ refusal: withIdentity(wholeDomainRefusal(name, i.path, untouched ? untouchedReason(name, i.sentence) : redactSecrets(i.sentence)), doc, i.path),
116
+ sentence: i.sentence,
117
+ }));
113
118
  }
114
119
  }
115
- /** 一批拒的**所在**,一行(stderr 用):`<文档>.json (<坐标>)`,同一处只列一次,最多三处。坐标里有用户写的键段:先剥一行回显的剥除集,
116
- * 剥完再过本包唯一的脱敏器(剥掉隔开的字符可以拼出一个密钥形,判在剥之后)。 */
117
- function refusedLocations(refused) {
118
- const seen = [...new Set(refused.map((r) => (r.path === "" ? `${r.document}.json` : `${r.document}.json (${r.path})`)))];
119
- return redactSecrets(stripControlAndBidi(seen.length <= 3 ? seen.join(", ") : `${seen.slice(0, 3).join(", ")}, …`));
120
+ /** 一处坐标的出门形标签:`<文档>.json (<坐标>)`;坐标是文档根时只有 `<文档>.json`。 */
121
+ const placeOf = (document, path) => (path === "" ? `${document}.json` : `${document}.json (${path})`);
122
+ /** 数的一致:一处用单数、多处用复数(整份 `why` 里每一处「几个」都读它,不写 `(s)` 两可)。 */
123
+ const agree = (count, one, many) => (count === 1 ? one : many);
124
+ /**
125
+ * 整份 `why`(命令行 stderr 的那一句、引擎起服的拒因日志读的也是它):**几处 · 原因 · 出路** 一句话。几处 = 迁移步拒的坐标数 / 整域判不过的文档数(数的一致按个数分单复数);
126
+ * 原因 = 每条拒的 `<所在>: <句子>`,与读腿告警的原因段同一只 {@link causeText}(至多三段,多出来的写个数)—— 迁移步拒读收据的 `reason`、整域终判拒读判官那一句({@link JudgedRefusal.sentence}),
127
+ * 所以 stderr 说的原因就是 `refused[]` 每条拒 `reason` 里的那一句判官的话(没有第二份措辞;迁移没碰的文档的 `reason` 在它后面还接读腿的处置与出路,这里只取前一句,出路写在整份 `why` 的尾);
128
+ * 出路 = 手改后重跑。所在里有用户写的键段:整个原因段先剥一行回显的剥除集,剥完再过本包唯一的脱敏器
129
+ * (剥掉隔开的字符可以拼出一个密钥形,判在剥之后)。
130
+ */
131
+ function refusalWhy(byMigration, byJudge, judge) {
132
+ const migrationItems = byMigration.map((r) => ({ path: placeOf(r.document, r.path), sentence: issueSentence({ message: r.reason }) }));
133
+ const judgedItems = byJudge.map((j) => ({ path: placeOf(j.refusal.document, j.refusal.path), sentence: j.sentence }));
134
+ const documents = new Set(byJudge.map((j) => j.refusal.document)).size;
135
+ const heads = [];
136
+ if (byMigration.length > 0)
137
+ heads.push(`${byMigration.length} ${agree(byMigration.length, "coordinate cannot", "coordinates cannot")} be migrated`);
138
+ if (byJudge.length > 0)
139
+ heads.push(`${documents} ${judge === "changed" ? "migrated " : ""}${agree(documents, "document does", "documents do")} not read as a whole domain`);
140
+ const causes = redactSecrets(stripControlAndBidi(causeText([...migrationItems, ...judgedItems])));
141
+ return `${heads.join(" and ")}: ${causes} (see "refused") — fix ${agree(migrationItems.length + judgedItems.length, "it", "them")} by hand and re-run`;
120
142
  }
121
143
  /**
122
144
  * 迁移结果 → 结论。顺序:迁移步拒 → 无改动 ⇒ noop → **整域终判**(`judge: "changed"`:要写回的每个域文档 —— 改过的、新建的;`"present"`:在场的每一份)→ 有改动。整域终判在 `check` 之前:否则同一个目录 `check` 报 pending、
@@ -126,10 +148,9 @@ function refusedLocations(refused) {
126
148
  function verdictOf(input, migrated, receipts, judge) {
127
149
  const refusedReceipts = receipts.filter((r) => r.appliedAs === "refused");
128
150
  const byMigration = refusedReceipts.map((r) => withIdentity(reportReceipt(r), input[r.document], r.path));
129
- const migrationWhy = `${refusedReceipts.length} coordinate(s) cannot be migrated`;
130
151
  // 迁移步拒:`"changed"`(引擎起服)问的是「迁移有没有把它改坏」,答案已经是否,不再往下判;`"present"` 问「这个目录现在干不干净」,下面接着判别的文档,两样并在一份报告里。
131
152
  if (refusedReceipts.length > 0 && judge === "changed")
132
- return { kind: "refused", refused: byMigration, why: `${migrationWhy} (see "refused") — fix them by hand and re-run` };
153
+ return { kind: "refused", refused: byMigration, why: refusalWhy(byMigration, [], judge) };
133
154
  if (receipts.length === 0 && judge === "changed")
134
155
  return { kind: "noop" };
135
156
  const receiptDocuments = new Set(refusedReceipts.map((r) => r.document)); // 文档名按串比(收据上的是闭集 `MigrationDocument`,这里遍历的键是任意串):这些文档的毛病已经在 byMigration 里(要猜才改得动的形),不再判第二遍、不重复报
@@ -143,14 +164,7 @@ function verdictOf(input, migrated, receipts, judge) {
143
164
  byJudge.push(...wholeDocumentRefusals(name, doc, untouched));
144
165
  }
145
166
  if (byMigration.length > 0 || byJudge.length > 0) {
146
- const documents = [...new Set(byJudge.map((r) => r.document))];
147
- const judged = judge === "changed" ? `the migrated ${documents.join(" / ")} document(s) do not read as a whole domain` : `${refusedLocations(byJudge)} do not read as a whole domain`;
148
- const why = byJudge.length === 0
149
- ? `${migrationWhy} (see "refused") — fix them by hand and re-run`
150
- : byMigration.length === 0
151
- ? `${judged} (see "refused") — fix them by hand and re-run`
152
- : `${migrationWhy} and ${judged} (see "refused") — fix them by hand and re-run`;
153
- return { kind: "refused", refused: [...byMigration, ...byJudge], why };
167
+ return { kind: "refused", refused: [...byMigration, ...byJudge.map((j) => j.refusal)], why: refusalWhy(byMigration, byJudge, judge) };
154
168
  }
155
169
  return receipts.length === 0 ? { kind: "noop" } : { kind: "changes" };
156
170
  }