dexbot 1.7.0 → 1.7.2

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 (115) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +12 -1
  24. package/dist/modules/account_bots.js +7 -5
  25. package/dist/modules/account_orders.d.ts +12 -0
  26. package/dist/modules/account_orders.js +30 -0
  27. package/dist/modules/bitshares-native/transport.js +24 -6
  28. package/dist/modules/bitshares_client.d.ts +24 -6
  29. package/dist/modules/bitshares_client.js +44 -7
  30. package/dist/modules/bot_settings.d.ts +2 -0
  31. package/dist/modules/constants.d.ts +28 -3
  32. package/dist/modules/constants.js +79 -10
  33. package/dist/modules/dexbot_class.d.ts +23 -6
  34. package/dist/modules/dexbot_class.js +44 -0
  35. package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
  36. package/dist/modules/dexbot_cow_runtime.js +688 -188
  37. package/dist/modules/dexbot_fill_runtime.js +124 -35
  38. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  39. package/dist/modules/dexbot_maintenance_runtime.js +259 -79
  40. package/dist/modules/dexbot_startup_runtime.js +32 -20
  41. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  42. package/dist/modules/dexbot_state_recovery.js +167 -5
  43. package/dist/modules/node_connect_policy.d.ts +8 -1
  44. package/dist/modules/node_connect_policy.js +18 -2
  45. package/dist/modules/node_flap_score.d.ts +87 -0
  46. package/dist/modules/node_flap_score.js +124 -0
  47. package/dist/modules/node_health_cache.d.ts +40 -3
  48. package/dist/modules/node_health_cache.js +66 -20
  49. package/dist/modules/node_manager.d.ts +101 -19
  50. package/dist/modules/node_manager.js +255 -65
  51. package/dist/modules/order/accounting.d.ts +9 -4
  52. package/dist/modules/order/accounting.js +131 -19
  53. package/dist/modules/order/async_lock.d.ts +7 -1
  54. package/dist/modules/order/async_lock.js +7 -1
  55. package/dist/modules/order/export.js +25 -18
  56. package/dist/modules/order/fill_ledger.d.ts +99 -0
  57. package/dist/modules/order/fill_ledger.js +103 -0
  58. package/dist/modules/order/format.d.ts +24 -10
  59. package/dist/modules/order/format.js +30 -10
  60. package/dist/modules/order/grid.d.ts +75 -18
  61. package/dist/modules/order/grid.js +289 -72
  62. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  63. package/dist/modules/order/grid_reconcile.js +333 -210
  64. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  65. package/dist/modules/order/grid_reconcile_internal.js +223 -91
  66. package/dist/modules/order/index.d.ts +18 -5
  67. package/dist/modules/order/index.js +5 -5
  68. package/dist/modules/order/lifecycle.d.ts +353 -0
  69. package/dist/modules/order/lifecycle.js +1109 -0
  70. package/dist/modules/order/manager.d.ts +277 -20
  71. package/dist/modules/order/manager.js +680 -64
  72. package/dist/modules/order/placement_lock.d.ts +102 -0
  73. package/dist/modules/order/placement_lock.js +222 -0
  74. package/dist/modules/order/strategy.js +13 -1
  75. package/dist/modules/order/sync_engine.d.ts +74 -114
  76. package/dist/modules/order/sync_engine.js +254 -198
  77. package/dist/modules/order/utils/math.d.ts +29 -4
  78. package/dist/modules/order/utils/math.js +61 -4
  79. package/dist/modules/order/utils/order.d.ts +106 -37
  80. package/dist/modules/order/utils/order.js +256 -81
  81. package/dist/modules/order/utils/system.d.ts +99 -6
  82. package/dist/modules/order/utils/system.js +249 -35
  83. package/dist/modules/order/utils/validate.d.ts +7 -1
  84. package/dist/modules/order/utils/validate.js +48 -2
  85. package/dist/modules/outcome.d.ts +54 -0
  86. package/dist/modules/outcome.js +51 -0
  87. package/dist/modules/settings_merge.d.ts +4 -0
  88. package/dist/modules/settings_merge.js +9 -0
  89. package/dist/modules/timing_policy.d.ts +82 -0
  90. package/dist/modules/timing_policy.js +244 -0
  91. package/dist/modules/types.d.ts +149 -22
  92. package/dist/scripts/analyze-credit.js +54 -17
  93. package/dist/scripts/analyze-orders.d.ts +4 -2
  94. package/dist/scripts/analyze-orders.js +113 -34
  95. package/dist/scripts/chart_targets.js +11 -15
  96. package/dist/scripts/test-credit-renewal.js +12 -5
  97. package/docs/COW_INVARIANTS.md +71 -8
  98. package/docs/DEXBOT_COMPARISON.md +6 -6
  99. package/docs/EVOLUTION.md +10 -8
  100. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  101. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  102. package/docs/GRID_RECONCILE.md +18 -13
  103. package/docs/LOGGING.md +25 -1
  104. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
  105. package/docs/README.md +23 -2
  106. package/docs/WORKFLOW.md +9 -3
  107. package/docs/architecture.md +68 -13
  108. package/docs/developer_guide.md +25 -8
  109. package/modules/README.md +6 -0
  110. package/package.json +3 -3
  111. package/scripts/README.md +16 -0
  112. package/scripts/pdev.sh +14 -1
  113. package/scripts/pmain.sh +23 -8
  114. package/scripts/ptest.sh +7 -0
  115. package/tests/README.md +30 -1
@@ -0,0 +1,54 @@
1
+ /**
2
+ * modules/outcome.ts - Three-valued outcomes
3
+ *
4
+ * The engine has many operations whose result is genuinely unknowable: a
5
+ * broadcast whose receipt was lost, a chain read that came back ambiguous, a
6
+ * timeout that won a race. Historically each such site returned a plain object
7
+ * with an ad-hoc `uncertain: true` field — sometimes next to a *second* ad-hoc
8
+ * flag describing the same fact (`ambiguousRead`), so the two could disagree
9
+ * and no consumer was forced to handle the third case at all.
10
+ *
11
+ * `Outcome<T>` (modules/types.ts) gives that third case a name. This module is
12
+ * the only place those result objects are constructed, so the flags cannot
13
+ * drift apart: one `cause` in, both legacy booleans derived out.
14
+ *
15
+ * Browser-safe: no Node APIs.
16
+ */
17
+ import type { UnknownCause, UnknownOutcome } from './types.js';
18
+ /**
19
+ * Build an `unknown` outcome. Callers must name the cause.
20
+ *
21
+ * @param cause - Why the outcome is unknown
22
+ * @param detail - Optional human-readable context
23
+ * @returns {UnknownOutcome} An `unknown` outcome
24
+ */
25
+ export declare function unknownOutcome(cause: UnknownCause, detail?: string): UnknownOutcome;
26
+ export interface CowOutcomeShape {
27
+ executed: boolean;
28
+ hadRotation: boolean;
29
+ [key: string]: unknown;
30
+ }
31
+ export interface UnknownCowOutcome extends CowOutcomeShape {
32
+ /** Canonical discriminator. */
33
+ kind: 'unknown';
34
+ /** Canonical reason. */
35
+ cause: UnknownCause;
36
+ /** Legacy alias kept for existing readers; always true. */
37
+ uncertain: true;
38
+ /** Legacy alias kept for existing readers; derived from `cause`. */
39
+ ambiguousRead: boolean;
40
+ }
41
+ /**
42
+ * Build a COW result for a batch whose effect is not knowable.
43
+ *
44
+ * `cause` is the single input: `uncertain` is always true and `ambiguousRead`
45
+ * is true exactly when the cause is an ambiguous read. A caller cannot make
46
+ * those two disagree because it never sets them. Fields in `extra` are merged
47
+ * FIRST, so they cannot override the canonical ones either.
48
+ *
49
+ * @param cause - Why the outcome is unknown
50
+ * @param extra - Additional fields to merge (e.g. adoptedCount)
51
+ * @returns {UnknownCowOutcome} Consistent COW result
52
+ */
53
+ export declare function unknownCowOutcome(cause: UnknownCause, extra?: Record<string, unknown>): UnknownCowOutcome;
54
+ //# sourceMappingURL=outcome.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * modules/outcome.ts - Three-valued outcomes
3
+ *
4
+ * The engine has many operations whose result is genuinely unknowable: a
5
+ * broadcast whose receipt was lost, a chain read that came back ambiguous, a
6
+ * timeout that won a race. Historically each such site returned a plain object
7
+ * with an ad-hoc `uncertain: true` field — sometimes next to a *second* ad-hoc
8
+ * flag describing the same fact (`ambiguousRead`), so the two could disagree
9
+ * and no consumer was forced to handle the third case at all.
10
+ *
11
+ * `Outcome<T>` (modules/types.ts) gives that third case a name. This module is
12
+ * the only place those result objects are constructed, so the flags cannot
13
+ * drift apart: one `cause` in, both legacy booleans derived out.
14
+ *
15
+ * Browser-safe: no Node APIs.
16
+ */
17
+ /**
18
+ * Build an `unknown` outcome. Callers must name the cause.
19
+ *
20
+ * @param cause - Why the outcome is unknown
21
+ * @param detail - Optional human-readable context
22
+ * @returns {UnknownOutcome} An `unknown` outcome
23
+ */
24
+ export function unknownOutcome(cause, detail) {
25
+ return detail ? { kind: 'unknown', cause, detail } : { kind: 'unknown', cause };
26
+ }
27
+ /**
28
+ * Build a COW result for a batch whose effect is not knowable.
29
+ *
30
+ * `cause` is the single input: `uncertain` is always true and `ambiguousRead`
31
+ * is true exactly when the cause is an ambiguous read. A caller cannot make
32
+ * those two disagree because it never sets them. Fields in `extra` are merged
33
+ * FIRST, so they cannot override the canonical ones either.
34
+ *
35
+ * @param cause - Why the outcome is unknown
36
+ * @param extra - Additional fields to merge (e.g. adoptedCount)
37
+ * @returns {UnknownCowOutcome} Consistent COW result
38
+ */
39
+ export function unknownCowOutcome(cause, extra = {}) {
40
+ const outcome = unknownOutcome(cause);
41
+ return {
42
+ ...extra,
43
+ executed: false,
44
+ hadRotation: false,
45
+ kind: outcome.kind,
46
+ cause: outcome.cause,
47
+ uncertain: true,
48
+ ambiguousRead: outcome.cause === 'ambiguous-read',
49
+ };
50
+ }
51
+ //# sourceMappingURL=outcome.js.map
@@ -44,6 +44,10 @@ interface NodesHealthCheckView {
44
44
  timeoutMs?: number;
45
45
  maxPingMs?: number;
46
46
  blacklistThreshold?: number;
47
+ strikeDecayMs?: number;
48
+ flapHalfLifeMs?: number;
49
+ flapPenaltyMsPerDrop?: number;
50
+ flapPenaltyMaxMs?: number;
47
51
  [key: string]: unknown;
48
52
  }
49
53
  interface NodesSelectionView {
@@ -86,6 +86,11 @@ const NODES_SUBKEY_MAP = {
86
86
  timeoutMs: 'HEALTH_CHECK_TIMEOUT_MS',
87
87
  maxPingMs: 'MAX_PING_MS',
88
88
  blacklistThreshold: 'BLACKLIST_THRESHOLD',
89
+ // Strike lifetime and flapping penalty (see modules/node_flap_score.ts).
90
+ strikeDecayMs: 'FAILURE_STRIKE_DECAY_MS',
91
+ flapHalfLifeMs: 'FLAP_HALF_LIFE_MS',
92
+ flapPenaltyMsPerDrop: 'FLAP_PENALTY_MS_PER_DROP',
93
+ flapPenaltyMaxMs: 'FLAP_PENALTY_MAX_MS',
89
94
  },
90
95
  selection: {
91
96
  strategy: 'SELECTION_STRATEGY',
@@ -134,6 +139,10 @@ function buildNodesView(nm) {
134
139
  timeoutMs: nm.HEALTH_CHECK_TIMEOUT_MS,
135
140
  maxPingMs: nm.MAX_PING_MS,
136
141
  blacklistThreshold: nm.BLACKLIST_THRESHOLD,
142
+ strikeDecayMs: nm.FAILURE_STRIKE_DECAY_MS,
143
+ flapHalfLifeMs: nm.FLAP_HALF_LIFE_MS,
144
+ flapPenaltyMsPerDrop: nm.FLAP_PENALTY_MS_PER_DROP,
145
+ flapPenaltyMaxMs: nm.FLAP_PENALTY_MAX_MS,
137
146
  },
138
147
  selection: {
139
148
  strategy: nm.SELECTION_STRATEGY,
@@ -0,0 +1,82 @@
1
+ /**
2
+ * modules/timing_policy.ts - Timing window classification
3
+ *
4
+ * The engine has 84 timing knobs. The reason that number kept growing is that
5
+ * every "the state was briefly wrong" bug got fixed by adding a window, and
6
+ * nothing ever removed one. A window is a substitute for evidence: it says
7
+ * "wait, then guess". Some of that is unavoidable (a block takes as long as it
8
+ * takes); most of it is not.
9
+ *
10
+ * This module is the audit. Every window key is classified into one of four
11
+ * kinds, and a test fails when a new unclassified window appears — so the
12
+ * inventory can only shrink by decision, never grow by accident.
13
+ *
14
+ * EXTERNAL encodes how long the OUTSIDE world takes. Legitimate.
15
+ * (block time, node lag, RPC deadline, poll cadence)
16
+ * BOUND a leak/GC bound. Caps retention, never a correctness gate.
17
+ * Deleting one leaks memory; it cannot create a wrong decision.
18
+ * POLICY a deliberate product choice (grace, cooldown, backoff).
19
+ * Defensible, but each one is a place where behaviour is
20
+ * encoded in milliseconds instead of in state.
21
+ * SELF_HEALING compensates for our OWN lost or divergent state.
22
+ * REMOVAL TARGET: the fix is evidence (a lifecycle phase),
23
+ * not patience. See `removal` for the precondition.
24
+ *
25
+ * `derived` marks a value computed from another timing. Those are the worst
26
+ * offenders when they are also user-tunable, because the relationship is
27
+ * correctness and the surface is a settings file. constants.ts recomputes them
28
+ * post-merge and throws on a broken ordering, so they are safe to keep — but
29
+ * they must be declared, not discovered.
30
+ *
31
+ * Browser-safe: no Node APIs.
32
+ */
33
+ /** What a timing window means. See the module doc for the definitions. */
34
+ export type TimingClass = 'external' | 'bound' | 'policy' | 'self-healing';
35
+ export interface TimingClassification {
36
+ /** What kind of thing this window is. */
37
+ kind: TimingClass;
38
+ /** Why it exists, in one line. */
39
+ rationale: string;
40
+ /**
41
+ * For `self-healing`: what evidence must exist before the window can be
42
+ * deleted. Absent for other kinds.
43
+ */
44
+ removal?: string;
45
+ /** Computed from another timing rather than declared. */
46
+ derived?: boolean;
47
+ }
48
+ /**
49
+ * Classifications keyed by TIMING key.
50
+ *
51
+ * Keep entries alphabetical. A key that is not here and looks like a window
52
+ * fails `tests/test_timing_policy.ts` — that is the point.
53
+ */
54
+ export declare const TIMING_CLASSIFICATIONS: Readonly<Record<string, TimingClassification>>;
55
+ /**
56
+ * Keys that must never be classified as a time window (units, flags, counts).
57
+ * Kept explicit so the audit list stays honest.
58
+ */
59
+ export declare const NON_WINDOW_KEYS: ReadonlySet<string>;
60
+ /** True when the key looks like a time window (and is not a declared non-window). */
61
+ export declare function looksLikeTimingWindow(key: string): boolean;
62
+ /** Classify a timing key, or null when it is not a window or not classified. */
63
+ export declare function classifyTiming(key: string): TimingClassification | null;
64
+ /**
65
+ * Timing keys that look like windows but carry no classification.
66
+ *
67
+ * This is the growth gate: a new window with no rationale fails the test.
68
+ *
69
+ * @param timing - The live TIMING map (or a fixture)
70
+ * @returns {string[]} Unclassified window keys, sorted
71
+ */
72
+ export declare function unclassifiedTimingKeys(timing: Record<string, unknown>): string[];
73
+ /** All classified self-healing windows, ordered by key. */
74
+ export declare function selfHealingWindows(): Array<{
75
+ key: string;
76
+ classification: TimingClassification;
77
+ }>;
78
+ /** All classified derived timings (computed from another timing). */
79
+ export declare function derivedTimings(): string[];
80
+ /** Count of classified keys per kind, for reporting. */
81
+ export declare function timingKindCounts(): Record<TimingClass, number>;
82
+ //# sourceMappingURL=timing_policy.d.ts.map
@@ -0,0 +1,244 @@
1
+ /**
2
+ * modules/timing_policy.ts - Timing window classification
3
+ *
4
+ * The engine has 84 timing knobs. The reason that number kept growing is that
5
+ * every "the state was briefly wrong" bug got fixed by adding a window, and
6
+ * nothing ever removed one. A window is a substitute for evidence: it says
7
+ * "wait, then guess". Some of that is unavoidable (a block takes as long as it
8
+ * takes); most of it is not.
9
+ *
10
+ * This module is the audit. Every window key is classified into one of four
11
+ * kinds, and a test fails when a new unclassified window appears — so the
12
+ * inventory can only shrink by decision, never grow by accident.
13
+ *
14
+ * EXTERNAL encodes how long the OUTSIDE world takes. Legitimate.
15
+ * (block time, node lag, RPC deadline, poll cadence)
16
+ * BOUND a leak/GC bound. Caps retention, never a correctness gate.
17
+ * Deleting one leaks memory; it cannot create a wrong decision.
18
+ * POLICY a deliberate product choice (grace, cooldown, backoff).
19
+ * Defensible, but each one is a place where behaviour is
20
+ * encoded in milliseconds instead of in state.
21
+ * SELF_HEALING compensates for our OWN lost or divergent state.
22
+ * REMOVAL TARGET: the fix is evidence (a lifecycle phase),
23
+ * not patience. See `removal` for the precondition.
24
+ *
25
+ * `derived` marks a value computed from another timing. Those are the worst
26
+ * offenders when they are also user-tunable, because the relationship is
27
+ * correctness and the surface is a settings file. constants.ts recomputes them
28
+ * post-merge and throws on a broken ordering, so they are safe to keep — but
29
+ * they must be declared, not discovered.
30
+ *
31
+ * Browser-safe: no Node APIs.
32
+ */
33
+ /**
34
+ * Classifications keyed by TIMING key.
35
+ *
36
+ * Keep entries alphabetical. A key that is not here and looks like a window
37
+ * fails `tests/test_timing_policy.ts` — that is the point.
38
+ */
39
+ export const TIMING_CLASSIFICATIONS = Object.freeze({
40
+ // --- transport / external world -----------------------------------------
41
+ ACCOUNT_TOTALS_TIMEOUT_MS: { kind: 'external', rationale: 'RPC deadline for the account-balances read.' },
42
+ BLOCKCHAIN_FETCH_INTERVAL_MIN: { kind: 'external', rationale: 'How often chain state is polled (minutes).' },
43
+ BLOCKCHAIN_SETTLE_DELAY_MS: { kind: 'external', rationale: 'Block-production latency before a write is expected to be visible.' },
44
+ BOTS_CONFIG_POLL_INTERVAL_MS: { kind: 'external', rationale: 'Bots-config file poll cadence.' },
45
+ BROADCAST_DEFER_SAFETY_MARGIN_MS: { kind: 'external', rationale: 'Headroom over the stale-broadcast watchdog; feeds a derived bound.', derived: true },
46
+ BROADCAST_STALE_CLEAR_MS: { kind: 'external', rationale: 'Single authority for how long a broadcast may stay unresolved before the watchdog clears it.' },
47
+ CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Readiness poll cadence.' },
48
+ CONNECTION_TIMEOUT_MS: { kind: 'external', rationale: 'Connection-establishment deadline.' },
49
+ CREDENTIAL_BROADCAST_TIMEOUT_MS: { kind: 'external', rationale: 'Outer deadline for a daemon broadcast.' },
50
+ CREDENTIAL_DAEMON_BROADCAST_BACKOFF_MS: { kind: 'external', rationale: 'Delay between pinned-node broadcast attempts.' },
51
+ CREDENTIAL_DAEMON_INNER_DEADLINE_MS: { kind: 'external', rationale: 'Inner daemon deadline, deliberately under the outer timeout.' },
52
+ CREDENTIAL_DAEMON_SOCKET_TIMEOUT_MS: { kind: 'external', rationale: 'Idle socket timeout for the credential daemon.' },
53
+ DAEMON_PING_TIMEOUT_MS: { kind: 'external', rationale: 'Daemon healthcheck deadline.' },
54
+ DAEMON_STARTUP_TIMEOUT_MS: { kind: 'external', rationale: 'Daemon startup deadline.' },
55
+ FETCH_HISTORY_PAGE_TIMEOUT_MS: { kind: 'external', rationale: 'Per-page fill-history deadline.' },
56
+ FETCH_HISTORY_TOTAL_DEADLINE_MS: { kind: 'external', rationale: 'Total fill-history crawl deadline.' },
57
+ LOGGER_DRAIN_TIMEOUT_MS: { kind: 'bound', rationale: 'Caps how long shutdown waits for the log sink.' },
58
+ MPA_FEED_MAX_AGE_MS: { kind: 'external', rationale: 'External feed staleness (on-chain feed publication cadence).' },
59
+ OFFER_CACHE_TTL_MS: { kind: 'bound', rationale: 'Cache-retention bound for credit offers.' },
60
+ SAFETY_NET_SYNC_TIMEOUT_MS: { kind: 'external', rationale: 'Deadline for the end-of-tick safety-net sync.' },
61
+ SAFETY_PAUSE_TIMEOUT_MS: { kind: 'external', rationale: 'Upper bound on a paused pipeline before the watchdog releases it.' },
62
+ SLOW_RECONNECT_INTERVAL_MS: { kind: 'external', rationale: 'Reconnect cadence for a slow/flapping node.' },
63
+ SYNC_DELAY_MS: { kind: 'external', rationale: 'Pacing between sync attempts; keeps a burst from hammering the node.' },
64
+ SYNC_EMPTY_READ_CONFIRM_DELAY_MS: { kind: 'external', rationale: 'Node lag: wait before re-reading a suspiciously empty snapshot.' },
65
+ SYNC_LOCK_TIMEOUT_MS: { kind: 'external', rationale: 'Lock acquisition deadline; also the observed-latency scale for in-flight windows.' },
66
+ CREDIT_DEAL_CHECK_INTERVAL_MIN: { kind: 'external', rationale: 'Credit-deal poll cadence.' },
67
+ CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS: { kind: 'external', rationale: 'External deal expiry horizon.' },
68
+ CREDIT_RATE_MAX_AGE_MS: { kind: 'external', rationale: 'Staleness bound for an externally quoted rate.' },
69
+ CREDIT_DEAL_SPLIT_MAX_PIECES: { kind: 'bound', rationale: 'Caps how many pieces a credit deal may be split into.' },
70
+ CREDIT_REBORROW_MAX_ATTEMPTS: { kind: 'policy', rationale: 'Retry budget for reborrowing.' },
71
+ DUST_HEALTH_CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Dust-sweep cadence.' },
72
+ DUST_CANCEL_TIMEOUT_MS: { kind: 'external', rationale: 'How long a dust cancel waits for the fill-processing lock.' },
73
+ LIGHTWEIGHT_SYNC_CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Cadence for the cheap open-orders check.' },
74
+ RUN_LOOP_DEFAULT_MS: { kind: 'external', rationale: 'Default open-orders sync cycle length.' },
75
+ SHARED_ACCOUNT_FETCH_INTERVAL_MIN: { kind: 'external', rationale: 'Shared-account balance fetch cadence.' },
76
+ BTS_ACQUIRE_COOLDOWN_MIN: { kind: 'policy', rationale: 'Cooldown between attempts to acquire BTS for fees.' },
77
+ // --- retry / backoff (bounded policy) -----------------------------------
78
+ RETRY_BACKOFF_CAP_MS: { kind: 'policy', rationale: 'Upper bound on exponential backoff.' },
79
+ FILL_TOTALS_RETRY_BASE_MS: { kind: 'policy', rationale: 'Backoff base for re-processing a fill whose totals were unavailable.' },
80
+ FILL_TOTALS_RETRY_MAX_MS: { kind: 'policy', rationale: 'Backoff ceiling for the same retry.' },
81
+ CREDENTIAL_DAEMON_BROADCAST_RETRIES: { kind: 'policy', rationale: 'Attempt budget for a pinned-node broadcast.' },
82
+ CREDENTIAL_DAEMON_WATCHDOG_MS: { kind: 'external', rationale: 'Watchdog poll cadence.' },
83
+ CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD: { kind: 'policy', rationale: 'Consecutive watchdog failures that mark the daemon dead.' },
84
+ // --- resource bounds (never a correctness gate) -------------------------
85
+ AUDIT_LOG_MAX_FILES: { kind: 'bound', rationale: 'Audit-log rotation bound.' },
86
+ AUDIT_LOG_MAX_SIZE: { kind: 'bound', rationale: 'Audit-log size bound.' },
87
+ CREDENTIAL_DAEMON_MAX_BUFFER_SIZE: { kind: 'bound', rationale: 'Daemon socket buffer bound.' },
88
+ FILL_RECORD_RETENTION_MS: { kind: 'bound', rationale: 'How long persisted fill records are kept (double-credit window).' },
89
+ PROCESSED_FILL_PERSIST_BATCH_SIZE: { kind: 'bound', rationale: 'Coalescing bound for processed-fill writes.' },
90
+ PROCESSED_FILL_PERSIST_BATCH_MS: { kind: 'bound', rationale: 'Coalescing window for processed-fill writes.' },
91
+ MILLISECONDS_PER_SECOND: { kind: 'bound', rationale: 'Unit constant, not a window.' },
92
+ OPEN_ORDERS_SYNC_LOOP_ENABLED: { kind: 'policy', rationale: 'Feature flag, not a window.' },
93
+ GRID_LOCK_HOLD_WARN_MS: { kind: 'bound', rationale: 'Observability: warn when a grid lock is held too long.' },
94
+ LOG_THROTTLE_INTERVAL_MS: { kind: 'bound', rationale: 'Log rate limit.' },
95
+ STALE_TOTALS_WARN_RATE_LIMIT_MS: { kind: 'bound', rationale: 'Log rate limit.' },
96
+ LOCK_REFRESH_MIN_MS: { kind: 'bound', rationale: 'Lease-refresh cadence during long operations.' },
97
+ LOCK_TIMEOUT_MS: { kind: 'external', rationale: 'Order-lock lease length (network latency scale).' },
98
+ MAX_ACCOUNT_TOTALS_AGE_MS: { kind: 'bound', rationale: 'Staleness bound before totals are refetched.' },
99
+ // --- policy windows (real product choices) ------------------------------
100
+ BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on boundary-hold resync escalation.' },
101
+ BOUNDARY_HOLD_RESYNC_THRESHOLD: { kind: 'policy', rationale: 'Consecutive boundary holds before escalation.' },
102
+ GRID_BLOAT_RESYNC_GRACE_MS: { kind: 'policy', rationale: 'Grace before a bloat resync is re-requested.' },
103
+ GRID_PRICE_INVARIANT_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on invariant resync escalation.' },
104
+ GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: { kind: 'policy', rationale: 'Consecutive invariant failures before escalation.' },
105
+ SPREAD_CORRECTION_MAX_ATTEMPTS: { kind: 'policy', rationale: 'Attempt budget for spread correction.' },
106
+ SPREAD_CORRECTION_SYNC_FRESH_MS: { kind: 'policy', rationale: 'How fresh the last sync must be to trust a spread decision.' },
107
+ SPREAD_STALE_ESCALATE_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before escalation.' },
108
+ SPREAD_STALE_FUND_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is fundability.' },
109
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is geometry.' },
110
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: { kind: 'policy', rationale: 'How long in-tolerance must hold before the watchdog resets.' },
111
+ SPREAD_STALE_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on spread-correction resyncs.' },
112
+ SPREAD_STALE_TRANSIENT_GRACE: { kind: 'policy', rationale: 'Consecutive transient corrections tolerated before escalating.' },
113
+ SPREAD_STALE_WARN_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before a warning.' },
114
+ TARGETED_DRIFT_SYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on targeted drift syncs.' },
115
+ DEFERRED_HOLD_ESCALATE_MS: { kind: 'policy', rationale: 'How long an unchanged deferred-hold signature is tolerated.' },
116
+ DEFERRED_HOLD_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on deferred-hold resyncs.' },
117
+ // --- self-healing windows -----------------------------------------------
118
+ //
119
+ // These exist because the engine could not tell two local states apart.
120
+ // modules/order/lifecycle.ts now records the difference explicitly, so each
121
+ // of these is a candidate for deletion once its evidence path is proven in
122
+ // live operation.
123
+ SURPLUS_CANCEL_GRACE_MS: {
124
+ kind: 'self-healing',
125
+ rationale: 'A just-placed order may be missing from a slightly stale reconcile snapshot; wait instead of cancelling it.',
126
+ removal: 'Delete when the COW planner reads the chain id from the lifecycle record (phase landed) instead of tolerating its absence.',
127
+ },
128
+ PENDING_BROADCAST_TTL_MS: {
129
+ kind: 'self-healing',
130
+ rationale: 'A CREATE whose receipt was lost used to be forgotten after a timeout; now it also becomes lifecycle phase unknown.',
131
+ removal: 'Keep as a GC/abandon bound until lost receipts are resolved by evidence (adoption or confirmed absence). The correctness role is already gone — only the retention cap remains.',
132
+ },
133
+ CHAIN_SIZE_APPLIED_MARKER_TTL_MS: {
134
+ kind: 'self-healing',
135
+ rationale: 'Dedupe marker for a chain-size resize already absorbed by sync pass 1.',
136
+ removal: 'Delete when the fill-history path can identify an already-applied resize from the lifecycle record rather than a timestamped marker.',
137
+ },
138
+ BATCH_INFLIGHT_STALE_MS: {
139
+ kind: 'bound',
140
+ rationale: 'Leak watchdog for an in-flight batch flag. Cannot affect a decision.',
141
+ },
142
+ RECOVERY_INFLIGHT_STALE_MS: {
143
+ kind: 'bound',
144
+ rationale: 'Leak watchdog for an in-flight recovery flag.',
145
+ },
146
+ PLACEMENT_STALE_CLEAR_MS: {
147
+ kind: 'bound',
148
+ rationale: 'Leak watchdog for a placement lease.',
149
+ },
150
+ STRUCTURAL_REBUILD_DEFER_MAX_MS: {
151
+ kind: 'self-healing',
152
+ rationale: 'Caps how long a fill-driven rebalance may defer behind a structural rebuild.',
153
+ removal: 'Delete when the rebuild publishes a completion event the rebalance can await instead of polling a deadline.',
154
+ },
155
+ FILL_BROADCAST_DEFER_MAX_MS: {
156
+ kind: 'self-healing',
157
+ rationale: 'Bound on fill-consumer deferral while a broadcast is unresolved.',
158
+ removal: 'Delete when the fill consumer can query the lifecycle phase instead of a clock.',
159
+ derived: true,
160
+ },
161
+ SYNC_LOCK_FORCE_RELEASE_AGE_MS: {
162
+ kind: 'bound',
163
+ rationale: 'Force-release a sync lock held past 2× its timeout (deadlock escape hatch).',
164
+ removal: 'Keep: this is a liveness bound on a lock, not a state guess.',
165
+ derived: true,
166
+ },
167
+ SYNC_SUSPECT_EMPTY_READ_LIMIT: {
168
+ kind: 'policy', rationale: 'Consecutive empty reads before an empty snapshot is believed.',
169
+ },
170
+ FILL_DEDUPE_WINDOW_MS: {
171
+ kind: 'self-healing',
172
+ rationale: 'Lease on a fill CLAIM accepted but not yet booked (deferral/crash). The processed-fill store refuses a booked key while retained, at any age; FILL_RECORD_RETENTION_MS bounds retention, not an expiry.',
173
+ removal: 'Delete once startup recovery reconciles a restored claim against chain-balance evidence (recomputing the credit from chain truth) instead of bounding it by age.',
174
+ },
175
+ });
176
+ /**
177
+ * Keys that must never be classified as a time window (units, flags, counts).
178
+ * Kept explicit so the audit list stays honest.
179
+ */
180
+ export const NON_WINDOW_KEYS = new Set([
181
+ 'AUDIT_LOG_MAX_FILES',
182
+ 'CREDENTIAL_DAEMON_BROADCAST_RETRIES',
183
+ 'CREDIT_DEAL_SPLIT_MAX_PIECES',
184
+ 'CREDIT_REBORROW_MAX_ATTEMPTS',
185
+ 'MILLISECONDS_PER_SECOND',
186
+ 'OPEN_ORDERS_SYNC_LOOP_ENABLED',
187
+ 'PROCESSED_FILL_PERSIST_BATCH_SIZE',
188
+ 'SPREAD_CORRECTION_MAX_ATTEMPTS',
189
+ 'SPREAD_STALE_TRANSIENT_GRACE',
190
+ 'BOUNDARY_HOLD_RESYNC_THRESHOLD',
191
+ 'GRID_PRICE_INVARIANT_RESYNC_THRESHOLD',
192
+ 'CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD',
193
+ 'CREDENTIAL_DAEMON_MAX_BUFFER_SIZE',
194
+ 'AUDIT_LOG_MAX_SIZE',
195
+ 'SYNC_SUSPECT_EMPTY_READ_LIMIT',
196
+ ]);
197
+ /** Name shape that makes a key look like a time window. */
198
+ const WINDOW_PATTERN = /(_MS|_MIN|_HOURS|_TTL|_GRACE|_COOLDOWN|_WINDOW|_DELAY|_INTERVAL|_DEADLINE|_TIMEOUT|_AGE|_LIFETIME)$/;
199
+ /** True when the key looks like a time window (and is not a declared non-window). */
200
+ export function looksLikeTimingWindow(key) {
201
+ if (NON_WINDOW_KEYS.has(key))
202
+ return false;
203
+ return WINDOW_PATTERN.test(key);
204
+ }
205
+ /** Classify a timing key, or null when it is not a window or not classified. */
206
+ export function classifyTiming(key) {
207
+ return TIMING_CLASSIFICATIONS[key] ?? null;
208
+ }
209
+ /**
210
+ * Timing keys that look like windows but carry no classification.
211
+ *
212
+ * This is the growth gate: a new window with no rationale fails the test.
213
+ *
214
+ * @param timing - The live TIMING map (or a fixture)
215
+ * @returns {string[]} Unclassified window keys, sorted
216
+ */
217
+ export function unclassifiedTimingKeys(timing) {
218
+ return Object.keys(timing)
219
+ .filter((key) => looksLikeTimingWindow(key) && classifyTiming(key) === null)
220
+ .sort();
221
+ }
222
+ /** All classified self-healing windows, ordered by key. */
223
+ export function selfHealingWindows() {
224
+ return Object.entries(TIMING_CLASSIFICATIONS)
225
+ .filter(([, classification]) => classification.kind === 'self-healing')
226
+ .map(([key, classification]) => ({ key, classification }))
227
+ .sort((a, b) => a.key.localeCompare(b.key));
228
+ }
229
+ /** All classified derived timings (computed from another timing). */
230
+ export function derivedTimings() {
231
+ return Object.entries(TIMING_CLASSIFICATIONS)
232
+ .filter(([, classification]) => classification.derived === true)
233
+ .map(([key]) => key)
234
+ .sort();
235
+ }
236
+ /** Count of classified keys per kind, for reporting. */
237
+ export function timingKindCounts() {
238
+ const counts = { external: 0, bound: 0, policy: 0, 'self-healing': 0 };
239
+ for (const classification of Object.values(TIMING_CLASSIFICATIONS)) {
240
+ counts[classification.kind] += 1;
241
+ }
242
+ return counts;
243
+ }
244
+ //# sourceMappingURL=timing_policy.js.map