@danceiny/gotry 0.2.0-rc.27 → 0.2.0-rc.29

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 (79) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/bin/gotry-bootstrap.js +56 -12
  4. package/data/yunnan-pack.json +30 -27
  5. package/dist/capabilities/anything.js +26 -0
  6. package/dist/capabilities/channel-registry.js +4 -4
  7. package/dist/capabilities/doctor.js +14 -7
  8. package/dist/capabilities/effect.js +1 -1
  9. package/dist/capabilities/ground-transfer.js +168 -1
  10. package/dist/capabilities/provider-detail-sanitize.js +64 -0
  11. package/dist/capabilities/route-provider-conformance.js +341 -0
  12. package/dist/capabilities/session/extension-bridge.js +3 -3
  13. package/dist/capabilities/session-search.js +1 -1
  14. package/dist/scripts/anything-path-measure-tests.js +133 -0
  15. package/dist/scripts/anything-path-measure.js +150 -0
  16. package/dist/scripts/anything-tests.js +136 -2
  17. package/dist/scripts/booking-copilot-dsh-warmer-proof.js +5 -2
  18. package/dist/scripts/bootstrap-tests.js +77 -7
  19. package/dist/scripts/city-scenario-tier-tests.js +234 -0
  20. package/dist/scripts/doctor-tests.js +39 -3
  21. package/dist/scripts/drill-multiuser-ledger-tests.js +1076 -0
  22. package/dist/scripts/drill-sdk-descendant-cleanup-tests.js +606 -0
  23. package/dist/scripts/drill-w2a-sensor-tests.js +788 -0
  24. package/dist/scripts/dsh-llm-tests.js +437 -0
  25. package/dist/scripts/g5-guard-tests.js +20 -1
  26. package/dist/scripts/g5-guard.js +5 -1
  27. package/dist/scripts/gotry-backend-kernel-tests.js +1 -1
  28. package/dist/scripts/m3-cohort-tests.js +714 -0
  29. package/dist/scripts/m3-cohort.js +310 -0
  30. package/dist/scripts/nightly-evidence-tests.js +44 -2
  31. package/dist/scripts/nightly-evidence.js +21 -4
  32. package/dist/scripts/outcome-projection-tests.js +427 -0
  33. package/dist/scripts/persona-sim-tests.js +621 -0
  34. package/dist/scripts/persona-sim.js +1081 -0
  35. package/dist/scripts/replay-async.js +2 -0
  36. package/dist/scripts/replay.js +2 -0
  37. package/dist/scripts/route-provider-conformance-tests.js +391 -0
  38. package/dist/scripts/session-dida-live-e2e.js +1 -1
  39. package/dist/scripts/session-zone-crash.js +49 -0
  40. package/dist/scripts/session-zone-ledger-tests.js +432 -0
  41. package/dist/scripts/session-zone-observation-tests.js +492 -0
  42. package/dist/scripts/session-zone-observe.js +135 -0
  43. package/dist/scripts/session-zone-wiring-tests.js +566 -0
  44. package/dist/scripts/session-zones-tests.js +17 -1
  45. package/dist/scripts/spawn-bounded-abort-tests.js +3 -0
  46. package/dist/scripts/state-cli.js +16 -0
  47. package/dist/scripts/time-eval-tests.js +2 -0
  48. package/dist/scripts/unified-tests.js +79 -2
  49. package/dist/scripts/z3-race-tests.js +6 -1
  50. package/dist/src/backend/modules/session-search.js +1 -1
  51. package/dist/src/city-scenario-tier.js +378 -0
  52. package/dist/src/dsh-llm.js +84 -14
  53. package/dist/src/index.js +166 -7
  54. package/dist/src/loop.js +16 -5
  55. package/dist/src/m3-cohort.js +1577 -0
  56. package/dist/src/outcome-projection.js +746 -0
  57. package/dist/src/session-zone-ledger.js +312 -0
  58. package/dist/src/session-zone-observation.js +354 -0
  59. package/dist/src/session-zone-wiring.js +658 -0
  60. package/dist/src/session-zones.js +7 -4
  61. package/dist/src/state-ledger.js +293 -40
  62. package/dist/src/unified.js +69 -5
  63. package/extension/README.md +1 -1
  64. package/extension/README.zh-CN.md +1 -1
  65. package/extension/background.js +1 -1
  66. package/extension/content-bridge.js +1 -1
  67. package/extension/content-main.js +1 -1
  68. package/extension/manifest.json +2 -2
  69. package/package.json +1 -1
  70. package/ts/capabilities/anything.ts +27 -0
  71. package/ts/capabilities/session/extension-bridge.ts +3 -3
  72. package/ts/capabilities/session-search.ts +1 -1
  73. package/ts/scripts/state-cli.ts +18 -0
  74. package/ts/src/contracts.ts +4 -0
  75. package/ts/src/dsh-llm.ts +111 -9
  76. package/ts/src/index.ts +181 -8
  77. package/ts/src/loop.ts +15 -5
  78. package/ts/src/state-ledger.ts +294 -40
  79. package/ts/src/unified.ts +91 -18
@@ -4,6 +4,8 @@
4
4
  * migrate [root] one-shot 迁移:旧 JSON/JSONL → 账本 events
5
5
  * (导入前自动快照到 gotry-state/pre-ledger-backup/)
6
6
  * export [root] local-only:账本 → 旧文件名视图(红线 6:可见可导出;单向,不回流)
7
+ * 另含会话双区派生视图(P4-2):hot-context.jsonl /
8
+ * notebook.json,从事件 fold 渲染——视图永不是写路径
7
9
  * log [root] [--limit N] 事件账本尾部(append-only 审计面)
8
10
  * stats [root] 各面计数
9
11
  * rebuild [root] [toSeq] DROP 投影 → fold 重放(可截到 toSeq;账本/投影
@@ -47,6 +49,7 @@
47
49
  import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
48
50
  import { dirname, join } from 'node:path';
49
51
  import { ensureLedger, ledgerDbPath, ledgerExists, openLedgerIfExists } from '../src/state-ledger.js';
52
+ import { ZONE_EXPORT_HOT_FILE, ZONE_EXPORT_NOTEBOOK_FILE, readZoneExportViews, } from '../src/session-zone-ledger.js';
50
53
  import { formatRepairPlan, loadEvidenceMappingFile, planLedgerRepair } from '../src/ledger-repair-plan.js';
51
54
  import { applyLedgerRepair, formatRepairApplyResult, restoreRepairBackup, } from '../src/ledger-repair-apply.js';
52
55
  import { collectDeepPlanning, makeJournaledSolvePort, settleAsyncTicket } from '../src/loop.js';
@@ -382,6 +385,19 @@ switch (cmd) {
382
385
  const trips = ledger.readTrips();
383
386
  if (trips.length)
384
387
  atomicWrite(join(dir, 'trips.jsonl'), trips.map(e => JSON.stringify(e)).join('\n') + '\n');
388
+ // 会话双区派生视图(P4-2,design/session-dual-zone-memory-design.md §2):
389
+ // 从六个事件 kind 的确定性 fold 渲染;空分区不产生空文件(同既有视图纪律)。
390
+ // 日志触读上界即拒:导出残缺视图比不导出更坏(读者会当它是全量)。
391
+ const zone = readZoneExportViews(ledger);
392
+ if (!zone.ok) {
393
+ console.error(`${zone.code}: ${zone.detail}`);
394
+ process.exit(1);
395
+ }
396
+ const zoneViews = zone.views;
397
+ if (zoneViews.hotContextJsonl)
398
+ atomicWrite(join(dir, ZONE_EXPORT_HOT_FILE), zoneViews.hotContextJsonl);
399
+ if (zoneViews.notebookJson !== '[]')
400
+ atomicWrite(join(dir, ZONE_EXPORT_NOTEBOOK_FILE), zoneViews.notebookJson);
385
401
  console.log(`视图已导出(单向,DB→文件;红线 6):${dir}/`);
386
402
  break;
387
403
  }
@@ -26,6 +26,8 @@ import { newState, runTurn } from '../src/loop.js';
26
26
  import { parseRequest } from '../src/model.js';
27
27
  import { solveChoiceSegment } from '../src/unified.js';
28
28
  import { parsePlanningWindow } from '../src/time-anchor.js';
29
+ // issue #617:确定性部分(第 6 节)经 runTurn,其 PoI 探针缺省不得 spawn 本机真实 hbcli(显式设置的值不覆盖)
30
+ process.env['GOTRY_HBCLI_LIVE'] ??= '0';
29
31
  const dataset = JSON.parse(readFileSync(join('..', 'data', 'time-slot-eval.json'), 'utf-8'));
30
32
  const [ay, am, ad] = dataset.anchor_date.split('-').map(Number);
31
33
  const ANCHOR_NOW = new Date(ay, am - 1, ad, 12); // 锚点日中午,避免午夜边界
@@ -3,7 +3,7 @@
3
3
  * 运行(在 ts/ 下):npx tsx scripts/unified-tests.ts
4
4
  */
5
5
  import assert from 'node:assert/strict';
6
- import { readFile } from 'node:fs/promises';
6
+ import { readdir, readFile } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import { parseFlightPackToSpec, solveUnified } from '../src/unified.js';
9
9
  import { hhmmToMin } from '../src/model.js';
@@ -50,4 +50,81 @@ off.budgetCny = 9000;
50
50
  off.workWindow = undefined;
51
51
  const r4 = await solveUnified(off);
52
52
  assert.deepEqual(r4.work_window_exclusions, []); // 关掉窗口,周五班恢复可选
53
- console.log(`TS UNIFIED TESTS: 4/4 OK(工作窗口生效,f2=VZ303,¥${r1.money_cny})`);
53
+ // 5. Issue #620 / #635:云南包的 yn0 衔接段缺 buffer_min/origin_transfer_min/dest_transfer_min
54
+ // → 旧实现 Number(undefined)=NaN → Int.val(NaN) 在 z3 WASM 里 `Assertion failed`
55
+ // → 被兜底翻译成「不可行 + unsat_core:['wasm_runtime_error']」。五条红线:
56
+ // ① 出厂数据包里挂接引擎的每一段(`legs`)三字段必须是非负整数;缺真值的段只能记在
57
+ // `advisory_legs`(带理由、不挂接)——替它填数等于编造真实世界的事实(ADR-10);
58
+ // ② 出厂云南包整包可判定,yn0 不进求解(founder 2026-10-05 选「标 advisory」);
59
+ // ③ 防线仍在:缺字段的包(由测试构造)必须以 solver_error 返回而**绝不**是 infeasible;
60
+ // ④ 最小输入:健康包里塞一个 NaN 接驳分钟 → 同样是 solver_error;
61
+ // ⑤ 晋升路径:founder 给出三个真值后,把 advisory 段搬回 legs 即可整包判定。
62
+ const DATA_DIR = join('..', 'data');
63
+ const TRANSFER_FIELDS = ['buffer_min', 'origin_transfer_min', 'dest_transfer_min'];
64
+ const yunnanRaw = JSON.parse(await readFile(join(DATA_DIR, 'yunnan-pack.json'), 'utf-8'));
65
+ // ① 数据完整性:data/ 下每个带 legs 的包,挂接引擎的段三字段齐全;advisory 段自带理由且不与 legs 重名
66
+ let auditedPacks = 0;
67
+ for (const file of (await readdir(DATA_DIR)).filter(f => f.endsWith('.json')).sort()) {
68
+ const raw = JSON.parse(await readFile(join(DATA_DIR, file), 'utf-8'));
69
+ if (!Array.isArray(raw['legs']))
70
+ continue;
71
+ auditedPacks += 1;
72
+ const legs = raw['legs'];
73
+ for (const leg of legs) {
74
+ for (const field of TRANSFER_FIELDS) {
75
+ const value = leg[field];
76
+ assert.ok(typeof value === 'number' && Number.isInteger(value) && value >= 0, `${file}: leg ${String(leg['id'])}.${field} 必须是非负整数(got ${JSON.stringify(value)});缺真值的段请放进 advisory_legs,不要补编造值(issue #635)`);
77
+ }
78
+ }
79
+ const engineIds = new Set(legs.map(leg => String(leg['id'])));
80
+ for (const advisory of (raw['advisory_legs'] ?? [])) {
81
+ const reason = advisory['advisory_reason'];
82
+ assert.ok(typeof reason === 'string' && reason.trim() !== '', `${file}: advisory 段 ${String(advisory['id'])} 必须写明 advisory_reason`);
83
+ assert.ok(!engineIds.has(String(advisory['id'])), `${file}: ${String(advisory['id'])} 不能同时在 legs 与 advisory_legs`);
84
+ }
85
+ }
86
+ assert.ok(auditedPacks >= 2, `数据完整性审计应覆盖航班包与云南包(审计了 ${auditedPacks} 个)`);
87
+ // ② 出厂云南包按产品同款路径整包可判定;advisory 段 yn0 不进引擎段链,也不参与求解
88
+ const yunnanSpec = parseFlightPackToSpec(structuredClone(yunnanRaw));
89
+ assert.deepEqual(yunnanSpec.segments.map(s => s.id), ['yn1', 'yn2', 'yn3', 'yn4'], 'advisory 段 yn0 不得进引擎段链');
90
+ yunnanSpec.budgetCny = 9000;
91
+ const rYunnan = await solveUnified(yunnanSpec);
92
+ assert.equal(rYunnan.solver_error, undefined, `出厂云南包不得再有求解器失败(got ${JSON.stringify(rYunnan.solver_error)})`);
93
+ assert.equal(rYunnan.feasible, true, `出厂云南包应可行(unsat_core=${JSON.stringify(rYunnan.unsat_core)})`);
94
+ assert.deepEqual(rYunnan.legs.map(l => l.leg), ['yn1', 'yn2', 'yn3', 'yn4'], '四段全判定,yn0 不在其中');
95
+ // ③ 防线仍在:缺三个字段的包(由测试从出厂包构造)→ NaN → 必须是显式 solver_error,绝不是「不可行」
96
+ const yunnanGap = structuredClone(yunnanRaw);
97
+ for (const field of TRANSFER_FIELDS)
98
+ delete yunnanGap['legs'][0][field];
99
+ const yunnanGapSpec = parseFlightPackToSpec(yunnanGap);
100
+ yunnanGapSpec.budgetCny = 9000;
101
+ assert.ok(Number.isNaN(yunnanGapSpec.segments[0].options[0].move.bufferMin), '缺 buffer_min 的事实前提');
102
+ const rYunnanGap = await solveUnified(yunnanGapSpec);
103
+ assert.equal(rYunnanGap.solver_error?.code, 'solver_input_not_integer', `缺字段的包必须以 solver_error 返回(got ${JSON.stringify(rYunnanGap)})`);
104
+ assert.ok(rYunnanGap.solver_error.message.includes('yn1.bufferMin'), `solver_error 必须点名出问题的段与字段(got ${rYunnanGap.solver_error.message})`);
105
+ assert.equal(rYunnanGap.feasible, false, 'solver_error 轮次没有产出可行解');
106
+ assert.deepEqual(rYunnanGap.unsat_core, undefined, '求解器失败不得伪造 unsat_core(机器 token 不进冲突位)');
107
+ assert.ok(!JSON.stringify(rYunnanGap).includes('wasm_runtime_error'), '不得再出现 wasm_runtime_error 这个伪冲突 token');
108
+ // ④ 最小输入:健康包里塞一个 NaN 接驳分钟 → 同样是 solver_error,点名到字段
109
+ const nanSpec = parseFlightPackToSpec(pack);
110
+ nanSpec.budgetCny = 9000;
111
+ nanSpec.segments[0].options[0].move.bufferMin = Number.NaN;
112
+ const rNan = await solveUnified(nanSpec);
113
+ assert.equal(rNan.solver_error?.code, 'solver_input_not_integer', `NaN 接驳必须以 solver_error 返回(got ${JSON.stringify(rNan)})`);
114
+ assert.ok(rNan.solver_error.message.includes('f1.bufferMin'), `solver_error 必须点名字段(got ${rNan.solver_error.message})`);
115
+ assert.equal(rNan.feasible, false, 'solver_error 轮次没有产出可行解');
116
+ // ⑤ 晋升路径:三个真值由测试提供(数据包里不写——真值待 founder 校准),把 advisory 段搬回 legs 的头部
117
+ // → 五段全判定,证明「补齐三个整数」正是 yn0 从 advisory 晋升所需的全部
118
+ const yunnanPromoted = structuredClone(yunnanRaw);
119
+ const [promotedYn0] = yunnanPromoted['advisory_legs'];
120
+ delete promotedYn0['advisory_reason'];
121
+ Object.assign(promotedYn0, { buffer_min: 60, origin_transfer_min: 30, dest_transfer_min: 30 });
122
+ yunnanPromoted['legs'] = [promotedYn0, ...yunnanPromoted['legs']];
123
+ delete yunnanPromoted['advisory_legs'];
124
+ const promotedSpec = parseFlightPackToSpec(yunnanPromoted);
125
+ promotedSpec.budgetCny = 9000;
126
+ const rPromoted = await solveUnified(promotedSpec);
127
+ assert.equal(rPromoted.solver_error, undefined, `补齐三字段后不得再有求解器失败(got ${JSON.stringify(rPromoted.solver_error)})`);
128
+ assert.equal(rPromoted.feasible, true, `晋升后的云南包应可行(unsat_core=${JSON.stringify(rPromoted.unsat_core)})`);
129
+ assert.equal(rPromoted.legs.length, 5, '晋升后五段全判定');
130
+ console.log(`TS UNIFIED TESTS: 5/5 OK(工作窗口生效,f2=VZ303,¥${r1.money_cny};#620/#635 ${auditedPacks} 个包三字段齐全,出厂云南包四段可行,缺字段→solver_error 点名 yn1,晋升后五段可行)`);
@@ -6,7 +6,9 @@
6
6
  * (run-all §1 重试止血与 release-notes rc.2-rc.4 的实录根因)。
7
7
  * 修复(z3-shared.ts):单一 WASM 实例 + 单一 Context + 会话级互斥门。
8
8
  *
9
- * 断言:① 并发轮次无 unified WASM 降级(wasm_runtime_error);② 判定与顺序基线一致。
9
+ * 断言:① 并发轮次无 unified 求解器失败(issue #620 后形态:`solver_error`,
10
+ * 旧形态是伪造的 `unsat_core:['wasm_runtime_error']`——两条都断言不出现);
11
+ * ② 判定与顺序基线一致。
10
12
  * 运行(在 ts/ 下):npx tsx scripts/z3-race-tests.ts
11
13
  */
12
14
  import assert from 'node:assert/strict';
@@ -35,6 +37,9 @@ for (let round = 0; round < ROUNDS; round++) {
35
37
  void jny;
36
38
  assert.equal(eng['recommended'], baseEngine['recommended'], `r${round}: engine recommended 漂移`);
37
39
  assert.equal(jny['feasible'], baseJourney['feasible'], `r${round}: journey feasible 漂移`);
40
+ // issue #620:求解器失败现在是 solver_error(显式类别),不再伪装成 unsat_core 里的
41
+ // 机器 token。两种形态都断言不出现——旧形态回归也会被这条抓住。
42
+ assert.equal(uni['solver_error'], undefined, `r${round}: unified 会话求解器失败——race 复发(${JSON.stringify(uni['solver_error'])})`);
38
43
  assert.equal((uni['unsat_core'] ?? []).includes('wasm_runtime_error'), false, `r${round}: unified 会话触发 WASM 降级——race 复发`);
39
44
  assert.equal(uni['feasible'], true, `r${round}: unified 判定漂移(基线应为可行)`);
40
45
  }
@@ -384,7 +384,7 @@ export function startSessionSearchModule(options) {
384
384
  if (!queue.extensionConnected()) {
385
385
  sendJson(res, 200, {
386
386
  ok: true,
387
- suppliers: [{ supplier: 'dida-portal', loggedIn: false, reason: 'extension-not-connected', detail: '会话执行环境=管理员浏览器扩展(GoTry Session Bridge);扩展未连接桥——在管理员浏览器安装扩展并配置本服务桥地址' }],
387
+ suppliers: [{ supplier: 'dida-portal', loggedIn: false, reason: 'extension-not-connected', detail: '会话执行环境=管理员浏览器扩展(Stai Travel Bridge);扩展未连接桥——在管理员浏览器安装扩展并配置本服务桥地址' }],
388
388
  bridge: queue.stats(),
389
389
  checkedAt,
390
390
  });
@@ -0,0 +1,378 @@
1
+ /**
2
+ * City × scenario tiering MECHANISM v1 (issue #339 contract slice,
3
+ * SIMULATED-TRIGGER DRILL — default OFF, zero callers, trigger flag frozen false,
4
+ * registry frozen EMPTY).
5
+ *
6
+ * ⚠ Evidence boundary: this module ships the MECHANISM only. #339's trigger is
7
+ * "reviewable real usage samples with a stated scenario vocabulary and success
8
+ * metric"; it has NOT fired. The tracker is explicit that a profile must never be
9
+ * fabricated from fixtures (「没有样本时保持研究/设计状态,不凭 fixture 造画像」),
10
+ * so there is deliberately NO taxonomy CONTENT here:
11
+ * - `CITY_SCENARIO_TIER_REGISTRY` is frozen `[]`;
12
+ * - `CITY_SCENARIO_TIER_TRIGGER_FIRED` is frozen `false`, and `admitTierEntry`
13
+ * refuses every admission before validating anything while it is false, so no
14
+ * tier can enter the registry without real samples and a founder decision;
15
+ * - every resolution therefore returns the NEUTRAL modifier today.
16
+ * Any scenario vocabulary proposal lives in the drill report as a clearly labelled
17
+ * unvalidated hypothesis, never in this file.
18
+ *
19
+ * Shape (mirrors ts/capabilities/fx-contract.ts #344 / ts/capabilities/geo-atlas.ts
20
+ * #342 / ts/src/session-zones.ts P4-1): pure functions, zero IO / network / timers,
21
+ * closed error-code set, typed results, deterministic, versioned, fail-closed.
22
+ *
23
+ * Frozen upstream constraints (READ-ONLY reuse):
24
+ * - docs/design/memory-design.md §1 item 3: the profile only feeds ranking, never
25
+ * hard filters — future shape `semantic × bounded_modifier`, "otherwise memory
26
+ * would filter the search down to nothing";
27
+ * - docs/rfc/loopx-inspired-upgrades-rfc.md S2: the ranking form
28
+ * `rank = semantic × bounded_modifier` and the evidence-grade ordering
29
+ * `owner_correction > controlled_replay > deterministic_effect > evaluator_inference`;
30
+ * - the ranking-disclosure precedent in `ts/capabilities/` (the sponsored-inventory
31
+ * ranker): a non-semantic weight never silently rewrites the sort key, and a
32
+ * tie-break bias is disclosed per candidate;
33
+ * - ts/src/memory-decay.ts: decay touches behavioural events only and exposes no
34
+ * motivation-profile API; this module likewise touches no profile and no store.
35
+ *
36
+ * Red lines encoded structurally (each has a falsification test in
37
+ * ts/scripts/city-scenario-tier-tests.ts, run-all §86):
38
+ * 1. ranking only — `applyTierRanking` has NO filter/exclude surface at all, and
39
+ * the output always contains exactly the input candidates: a modifier may
40
+ * reorder, it can never remove a candidate (not even at the lower bound with
41
+ * a zero semantic score);
42
+ * 2. bounded — the modifier is an integer ppm inside declared [min,max] bounds;
43
+ * 0, negative, non-integer and out-of-range are refused at admission, so no
44
+ * tier can zero a candidate out;
45
+ * 3. neutral fallback, never a guess — unknown city, unknown scenario, conflicting
46
+ * evidence, empty registry and trigger-not-fired all return the NEUTRAL
47
+ * modifier with a stated reason; conflicting entries never elect a winner;
48
+ * 4. per-tier provenance (evidence grade + real sample refs + reviewer + freeze
49
+ * instant) and a retirement condition + review deadline are MANDATORY;
50
+ * 5. deterministic and versioned: same inputs → byte-identical result; ties keep
51
+ * declaration order.
52
+ *
53
+ * Only the real #339 trigger can supply: the taxonomy members themselves, the
54
+ * scenario vocabulary, the success metric, the numeric bounds justified by data,
55
+ * and the before/after ranking hypotheses with real counterexamples.
56
+ *
57
+ * @module src/city-scenario-tier
58
+ */
59
+ /** Versioned contract schema id (readers validate it). */
60
+ export const CITY_SCENARIO_TIER_SCHEMA = 'gotry_city_scenario_tier.v1';
61
+ /**
62
+ * #339 implementation trigger gate, frozen false. Flipping it true requires
63
+ * reviewable real usage samples plus an explicit scenario vocabulary and success
64
+ * metric. While false, `admitTierEntry` refuses every admission.
65
+ */
66
+ export const CITY_SCENARIO_TIER_TRIGGER_FIRED = false;
67
+ /**
68
+ * Declared modifier bounds, in ppm (1_000_000 = neutral ×1.0).
69
+ *
70
+ * NOT data-derived: RFC S2 fixes the FORM (`semantic × bounded_modifier`) but the
71
+ * repo states no numeric interval anywhere. These values are drill-declared so the
72
+ * bound CHECK can be proven; the interval itself must be re-frozen from real
73
+ * samples when #339's trigger fires. The lower bound is deliberately > 0 so no
74
+ * tier can ever annihilate a candidate's semantic score.
75
+ */
76
+ export const TIER_MODIFIER_PPM_NEUTRAL = 1_000_000;
77
+ export const TIER_MODIFIER_PPM_MIN = 850_000;
78
+ export const TIER_MODIFIER_PPM_MAX = 1_150_000;
79
+ /** The only admitted application surface. There is no hard-filter surface. */
80
+ export const TIER_APPLICATION_SURFACES = ['ranking'];
81
+ /** Evidence grades, strongest first (RFC S2 ordering, read-only reuse). */
82
+ export const TIER_EVIDENCE_GRADES = ['owner_correction', 'controlled_replay', 'deterministic_effect', 'evaluator_inference'];
83
+ /**
84
+ * Admitted sample sources. Exactly one member: a reviewable real usage sample.
85
+ * A fixture / synthetic / model-authored sample is outside the closed set and is
86
+ * refused by name — this is #339's「不凭 fixture 造画像」as code.
87
+ */
88
+ export const TIER_SAMPLE_SOURCES = ['real_usage_sample'];
89
+ /** Bounded shapes: keys are vocabulary members, never free prose. */
90
+ export const TIER_KEY_MAX_CHARS = 48;
91
+ export const TIER_TEXT_MAX_CHARS = 200;
92
+ export const TIER_MAX_REGISTRY_ENTRIES = 512;
93
+ function fail(code, detail) {
94
+ return { ok: false, code, detail };
95
+ }
96
+ function pass(value) {
97
+ return { ok: true, value };
98
+ }
99
+ // ---------------------------------------------------------------------------
100
+ // Key normalization (deterministic; never a guess)
101
+ // ---------------------------------------------------------------------------
102
+ /**
103
+ * Normalize a city / scenario key: trim, collapse internal whitespace, lowercase.
104
+ * No transliteration, no alias expansion, no fuzzy matching — an unrecognized key
105
+ * stays unrecognized and falls back to neutral (ADR-10: nothing is fabricated).
106
+ */
107
+ export function normalizeTierKey(value, label) {
108
+ if (typeof value !== 'string') {
109
+ return fail('bad_key', `${label} must be a string, got ${JSON.stringify(value)}`);
110
+ }
111
+ const normalized = value.trim().replace(/\s+/g, ' ').toLowerCase();
112
+ if (normalized === '')
113
+ return fail('bad_key', `${label} must not be blank (a blank key is not an unknown key; callers must pass the key they actually have)`);
114
+ if (normalized.length > TIER_KEY_MAX_CHARS) {
115
+ return fail('bad_key', `${label} exceeds ${TIER_KEY_MAX_CHARS} chars (${normalized.length}) — a key is a vocabulary member, never prose`);
116
+ }
117
+ return pass(normalized);
118
+ }
119
+ function requiredText(label, value, code) {
120
+ if (typeof value !== 'string' || value.trim() === '') {
121
+ return fail(code, `${label} must be a non-empty string, got ${JSON.stringify(value)}`);
122
+ }
123
+ if (value.length > TIER_TEXT_MAX_CHARS) {
124
+ return fail('bound_exceeded', `${label} exceeds ${TIER_TEXT_MAX_CHARS} chars (${value.length})`);
125
+ }
126
+ return pass(value.trim());
127
+ }
128
+ function requiredInstant(label, value) {
129
+ if (typeof value !== 'string' || value.trim() === '') {
130
+ return fail('bad_ts', `${label} must be a non-empty ISO-8601 instant, got ${JSON.stringify(value)}`);
131
+ }
132
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value.trim())) {
133
+ return fail('bad_ts', `${label} must carry a full time-of-day (date-only '${value}' cannot order a freeze/review)`);
134
+ }
135
+ const ms = Date.parse(value);
136
+ if (!Number.isFinite(ms))
137
+ return fail('bad_ts', `${label} is not a parseable ISO-8601 instant: ${JSON.stringify(value)}`);
138
+ return pass(new Date(ms).toISOString());
139
+ }
140
+ /**
141
+ * Runtime taxonomy registry, frozen EMPTY — #339 forbids fabricating city-scenario
142
+ * tiers from fixtures. A non-empty value requires reviewable real samples and is a
143
+ * founder decision; the focused suite asserts this declaration stays `[]` in source.
144
+ */
145
+ export const CITY_SCENARIO_TIER_REGISTRY = [];
146
+ /** Minimum reviewable real samples behind one tier (a single anecdote is not a tier). */
147
+ export const TIER_MIN_SAMPLE_REFS = 3;
148
+ /**
149
+ * Admit one taxonomy entry.
150
+ *
151
+ * While `CITY_SCENARIO_TIER_TRIGGER_FIRED` is false this refuses BEFORE validating
152
+ * anything, so no tier can be fabricated from fixtures. Tests and a future admitted
153
+ * slice pass `{ triggerFired: true }` explicitly to exercise the validation shape.
154
+ */
155
+ export function admitTierEntry(input, options) {
156
+ const triggerFired = options?.triggerFired ?? CITY_SCENARIO_TIER_TRIGGER_FIRED;
157
+ if (!triggerFired) {
158
+ return fail('trigger_not_fired', '#339 trigger has not fired (reviewable real usage samples + an explicit scenario vocabulary and success metric are required); zero tiers admitted — 不凭 fixture 造画像');
159
+ }
160
+ const registry = options?.registry ?? CITY_SCENARIO_TIER_REGISTRY;
161
+ if (registry.length >= TIER_MAX_REGISTRY_ENTRIES) {
162
+ return fail('bound_exceeded', `registry already holds ${registry.length} entries (bound ${TIER_MAX_REGISTRY_ENTRIES}); an unbounded taxonomy is not explainable`);
163
+ }
164
+ const tierId = requiredText('tier_id', input?.tier_id, 'binding_incomplete');
165
+ if (!tierId.ok)
166
+ return tierId;
167
+ const cityKey = normalizeTierKey(input?.city_key, 'city_key');
168
+ if (!cityKey.ok)
169
+ return cityKey;
170
+ const scenarioKey = normalizeTierKey(input?.scenario_key, 'scenario_key');
171
+ if (!scenarioKey.ok)
172
+ return scenarioKey;
173
+ const version = requiredText('taxonomy_version', input?.taxonomy_version, 'binding_incomplete');
174
+ if (!version.ok)
175
+ return version;
176
+ const modifier = input?.modifier_ppm;
177
+ if (typeof modifier !== 'number' || !Number.isInteger(modifier)) {
178
+ return fail('modifier_bounds', `modifier_ppm must be an integer ppm, got ${JSON.stringify(modifier)} (floats drift; ppm integers are exact)`);
179
+ }
180
+ if (modifier < TIER_MODIFIER_PPM_MIN || modifier > TIER_MODIFIER_PPM_MAX) {
181
+ return fail('modifier_bounds', `modifier_ppm ${modifier} is outside the declared bounds [${TIER_MODIFIER_PPM_MIN},${TIER_MODIFIER_PPM_MAX}] (lower bound is > 0 by design: a tier may reorder, never annihilate a candidate)`);
182
+ }
183
+ const surface = input?.applies_to ?? 'ranking';
184
+ if (!TIER_APPLICATION_SURFACES.includes(surface)) {
185
+ return fail('closed_set', `applies_to must be one of [${TIER_APPLICATION_SURFACES.join('/')}], got ${JSON.stringify(surface)} — memory never enters a hard filter (memory-design §1.3)`);
186
+ }
187
+ const prov = input?.provenance;
188
+ if (prov === null || typeof prov !== 'object') {
189
+ return fail('provenance_required', 'provenance is mandatory: a tier without a stated evidence source is not evidence');
190
+ }
191
+ if (!TIER_EVIDENCE_GRADES.includes(prov['evidence_grade'])) {
192
+ return fail('closed_set', `provenance.evidence_grade must be one of [${TIER_EVIDENCE_GRADES.join('/')}], got ${JSON.stringify(prov['evidence_grade'])}`);
193
+ }
194
+ if (!TIER_SAMPLE_SOURCES.includes(prov['sample_source'])) {
195
+ return fail('closed_set', `provenance.sample_source must be one of [${TIER_SAMPLE_SOURCES.join('/')}], got ${JSON.stringify(prov['sample_source'])} — fixture/synthetic/model-authored samples are refused (#339: 不凭 fixture 造画像)`);
196
+ }
197
+ const refs = prov['sample_refs'];
198
+ if (!Array.isArray(refs) || refs.length < TIER_MIN_SAMPLE_REFS || !refs.every(r => typeof r === 'string' && r.trim() !== '')) {
199
+ return fail('provenance_required', `provenance.sample_refs must list at least ${TIER_MIN_SAMPLE_REFS} non-empty reviewable sample references, got ${JSON.stringify(refs)} (a single anecdote is not a tier)`);
200
+ }
201
+ const reviewer = requiredText('provenance.reviewer', prov['reviewer'], 'provenance_required');
202
+ if (!reviewer.ok)
203
+ return reviewer;
204
+ const frozenAt = requiredInstant('provenance.frozen_at', prov['frozen_at']);
205
+ if (!frozenAt.ok)
206
+ return frozenAt;
207
+ const ret = input?.retirement;
208
+ if (ret === null || typeof ret !== 'object') {
209
+ return fail('retirement_required', 'retirement is mandatory: a tier that cannot expire is not evidence (#339 acceptance 1 requires a retirement condition per class)');
210
+ }
211
+ const condition = requiredText('retirement.condition', ret['condition'], 'retirement_required');
212
+ if (!condition.ok)
213
+ return condition;
214
+ const reviewBy = requiredInstant('retirement.review_by', ret['review_by']);
215
+ if (!reviewBy.ok)
216
+ return reviewBy;
217
+ if (reviewBy.value <= frozenAt.value) {
218
+ return fail('retirement_required', `retirement.review_by ${reviewBy.value} must postdate provenance.frozen_at ${frozenAt.value}`);
219
+ }
220
+ if (registry.some(e => e.tier_id === tierId.value)) {
221
+ return fail('duplicate_tier', `tier_id ${tierId.value} already exists in the registry`);
222
+ }
223
+ if (registry.some(e => e.city_key === cityKey.value && e.scenario_key === scenarioKey.value)) {
224
+ return fail('duplicate_tier', `(city ${cityKey.value}, scenario ${scenarioKey.value}) already carries a tier; a second weight for the same pair is conflicting evidence, not an additional tier`);
225
+ }
226
+ return pass(Object.freeze({
227
+ schema: CITY_SCENARIO_TIER_SCHEMA,
228
+ tier_id: tierId.value,
229
+ city_key: cityKey.value,
230
+ scenario_key: scenarioKey.value,
231
+ modifier_ppm: modifier,
232
+ applies_to: surface,
233
+ provenance: Object.freeze({
234
+ evidence_grade: prov['evidence_grade'],
235
+ sample_source: prov['sample_source'],
236
+ sample_refs: Object.freeze([...refs]),
237
+ reviewer: reviewer.value,
238
+ frozen_at: frozenAt.value,
239
+ }),
240
+ retirement: Object.freeze({ condition: condition.value, review_by: reviewBy.value }),
241
+ taxonomy_version: version.value,
242
+ }));
243
+ }
244
+ // ---------------------------------------------------------------------------
245
+ // Resolution: neutral fallback, never a guess
246
+ // ---------------------------------------------------------------------------
247
+ export const TIER_NEUTRAL_REASONS = [
248
+ 'trigger_not_fired',
249
+ 'empty_registry',
250
+ 'unknown_city',
251
+ 'unknown_scenario',
252
+ 'conflicting_evidence',
253
+ ];
254
+ function neutral(reason, explanation, conflicting = []) {
255
+ return Object.freeze({
256
+ status: 'neutral',
257
+ modifier_ppm: TIER_MODIFIER_PPM_NEUTRAL,
258
+ tier_id: null,
259
+ reason,
260
+ conflicting_tier_ids: Object.freeze([...conflicting]),
261
+ explanation,
262
+ });
263
+ }
264
+ /**
265
+ * Resolve the bounded modifier for one (city, scenario) pair.
266
+ *
267
+ * Returns NEUTRAL (×1.0) with a stated reason for: trigger not fired, empty
268
+ * registry, unknown city, unknown scenario, and conflicting evidence. Conflicting
269
+ * entries never elect a winner (geo-atlas `ambiguous` discipline). A malformed key
270
+ * is a caller error and is reported as such rather than silently neutralized.
271
+ */
272
+ export function resolveTier(query, options) {
273
+ const cityKey = normalizeTierKey(query?.cityKey, 'cityKey');
274
+ if (!cityKey.ok)
275
+ return cityKey;
276
+ const scenarioKey = normalizeTierKey(query?.scenarioKey, 'scenarioKey');
277
+ if (!scenarioKey.ok)
278
+ return scenarioKey;
279
+ const triggerFired = options?.triggerFired ?? CITY_SCENARIO_TIER_TRIGGER_FIRED;
280
+ if (!triggerFired) {
281
+ return pass(neutral('trigger_not_fired', '#339 trigger has not fired; every city×scenario pair resolves to the neutral modifier ×1.0 (no tier is guessed)'));
282
+ }
283
+ const registry = options?.registry ?? CITY_SCENARIO_TIER_REGISTRY;
284
+ if (registry.length === 0) {
285
+ return pass(neutral('empty_registry', 'the taxonomy registry is empty; neutral ×1.0 (an empty taxonomy is not a zero weight)'));
286
+ }
287
+ const cityMatches = registry.filter(e => e.city_key === cityKey.value);
288
+ if (cityMatches.length === 0) {
289
+ return pass(neutral('unknown_city', `city '${cityKey.value}' carries no tier in taxonomy; neutral ×1.0 (an unknown city is never guessed from a neighbour)`));
290
+ }
291
+ const matches = cityMatches.filter(e => e.scenario_key === scenarioKey.value);
292
+ if (matches.length === 0) {
293
+ return pass(neutral('unknown_scenario', `scenario '${scenarioKey.value}' carries no tier for city '${cityKey.value}'; neutral ×1.0 (an unknown scenario is never approximated by another scenario)`));
294
+ }
295
+ if (matches.length > 1) {
296
+ return pass(neutral('conflicting_evidence', `city '${cityKey.value}' × scenario '${scenarioKey.value}' carries ${matches.length} conflicting tiers; neutral ×1.0 and no winner is elected (conflict is surfaced, never resolved by guessing)`, matches.map(e => e.tier_id)));
297
+ }
298
+ const entry = matches[0];
299
+ if (entry.modifier_ppm < TIER_MODIFIER_PPM_MIN || entry.modifier_ppm > TIER_MODIFIER_PPM_MAX) {
300
+ return fail('modifier_bounds', `registry entry ${entry.tier_id} carries modifier_ppm ${entry.modifier_ppm} outside the declared bounds [${TIER_MODIFIER_PPM_MIN},${TIER_MODIFIER_PPM_MAX}] — a defective registry entry is refused, never clamped silently`);
301
+ }
302
+ return pass(Object.freeze({
303
+ status: 'hit',
304
+ modifier_ppm: entry.modifier_ppm,
305
+ tier_id: entry.tier_id,
306
+ taxonomy_version: entry.taxonomy_version,
307
+ evidence_grade: entry.provenance.evidence_grade,
308
+ explanation: `tier ${entry.tier_id} (${entry.taxonomy_version}, evidence ${entry.provenance.evidence_grade}) applies ×${(entry.modifier_ppm / 1_000_000).toFixed(6)} to the ranking score of city '${entry.city_key}' under scenario '${entry.scenario_key}'; retire when: ${entry.retirement.condition}`,
309
+ }));
310
+ }
311
+ /**
312
+ * Apply tier modifiers to a candidate ranking.
313
+ *
314
+ * There is deliberately NO filter, exclude, drop or threshold parameter and no
315
+ * such field in the result: the returned array always contains exactly the input
316
+ * candidates (same ids, same count), only reordered. `semantic` is preserved on
317
+ * every output row so a caller can always recover the unmodified ranking.
318
+ * Ties keep declaration order (stable).
319
+ */
320
+ export function applyTierRanking(candidates, context, options) {
321
+ if (!Array.isArray(candidates))
322
+ return fail('bad_candidate', 'candidates must be an array');
323
+ const seen = new Set();
324
+ for (const c of candidates) {
325
+ if (c === null || typeof c !== 'object' || typeof c.id !== 'string' || c.id.trim() === '') {
326
+ return fail('bad_candidate', `every candidate needs a non-empty id, got ${JSON.stringify(c)}`);
327
+ }
328
+ if (seen.has(c.id))
329
+ return fail('bad_candidate', `duplicate candidate id ${c.id} (ranking inputs must be a set)`);
330
+ seen.add(c.id);
331
+ if (typeof c.semantic !== 'number' || !Number.isFinite(c.semantic)) {
332
+ return fail('bad_candidate', `candidate ${c.id} semantic score must be finite, got ${String(c.semantic)}`);
333
+ }
334
+ if (c.semantic < 0) {
335
+ return fail('bad_candidate', `candidate ${c.id} semantic score must be non-negative, got ${String(c.semantic)} — the ranking contract is multiplicative, so a negative score would invert every modifier (a boost would demote)`);
336
+ }
337
+ }
338
+ const ranked = [];
339
+ for (const c of candidates) {
340
+ const resolution = resolveTier({ cityKey: c.cityKey, scenarioKey: context?.scenarioKey }, options);
341
+ if (!resolution.ok)
342
+ return resolution;
343
+ const r = resolution.value;
344
+ ranked.push(Object.freeze({
345
+ id: c.id,
346
+ semantic: c.semantic,
347
+ modifier_ppm: r.modifier_ppm,
348
+ score: (c.semantic * r.modifier_ppm) / 1_000_000,
349
+ tier_id: r.status === 'hit' ? r.tier_id : null,
350
+ explanation: r.explanation,
351
+ }));
352
+ }
353
+ const ordered = ranked
354
+ .map((row, index) => ({ row, index }))
355
+ .sort((a, b) => (b.row.score - a.row.score) || (a.index - b.index))
356
+ .map(({ row }) => row);
357
+ // Structural invariant: ranking never removes a candidate.
358
+ if (ordered.length !== candidates.length || !candidates.every(c => ordered.some(r => r.id === c.id))) {
359
+ return fail('bad_candidate', 'internal invariant violated: tier ranking must preserve the candidate set exactly (memory never enters a hard filter)');
360
+ }
361
+ return pass(Object.freeze([...ordered]));
362
+ }
363
+ /**
364
+ * Mechanical no-hard-filter check a caller (or a gate) can run: the ranked output
365
+ * must contain exactly the input candidate ids. Returns a violation string, or null.
366
+ */
367
+ export function tierRankingFilterViolation(before, after) {
368
+ if (before.length !== after.length) {
369
+ return `tier ranking changed the candidate count ${before.length} → ${after.length}: memory may reorder, never filter (memory-design §1.3)`;
370
+ }
371
+ const missing = before.filter(c => !after.some(r => r.id === c.id)).map(c => c.id);
372
+ if (missing.length > 0)
373
+ return `tier ranking dropped candidates [${missing.join(',')}]: memory may reorder, never filter`;
374
+ const added = after.filter(r => !before.some(c => c.id === r.id)).map(r => r.id);
375
+ if (added.length > 0)
376
+ return `tier ranking invented candidates [${added.join(',')}]`;
377
+ return null;
378
+ }