@dsh-ft/dsh-fft-paper-trading 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +3 -2
  2. package/README.zh.md +3 -2
  3. package/lib/agent/account-tools.d.ts +18 -0
  4. package/lib/agent/account-tools.d.ts.map +1 -0
  5. package/lib/agent/account-tools.js +127 -0
  6. package/lib/agent/account-tools.js.map +1 -0
  7. package/lib/agent/futures-tools.d.ts.map +1 -1
  8. package/lib/agent/futures-tools.js +1 -6
  9. package/lib/agent/futures-tools.js.map +1 -1
  10. package/lib/agent/ledger-tools.d.ts +15 -3
  11. package/lib/agent/ledger-tools.d.ts.map +1 -1
  12. package/lib/agent/ledger-tools.js +11 -15
  13. package/lib/agent/ledger-tools.js.map +1 -1
  14. package/lib/agent/tool-result.d.ts +19 -0
  15. package/lib/agent/tool-result.d.ts.map +1 -0
  16. package/lib/agent/tool-result.js +22 -0
  17. package/lib/agent/tool-result.js.map +1 -0
  18. package/lib/agent/tools.d.ts +10 -2
  19. package/lib/agent/tools.d.ts.map +1 -1
  20. package/lib/agent/tools.js +26 -11
  21. package/lib/agent/tools.js.map +1 -1
  22. package/lib/client.js +1448 -282
  23. package/lib/contract/accounts.d.ts +76 -0
  24. package/lib/contract/accounts.d.ts.map +1 -0
  25. package/lib/contract/accounts.js +6 -0
  26. package/lib/contract/accounts.js.map +1 -0
  27. package/lib/contract/common.d.ts +144 -0
  28. package/lib/contract/common.d.ts.map +1 -0
  29. package/lib/contract/common.js +33 -0
  30. package/lib/contract/common.js.map +1 -0
  31. package/lib/contract/domain.d.ts +196 -0
  32. package/lib/contract/domain.d.ts.map +1 -0
  33. package/lib/contract/domain.js +14 -0
  34. package/lib/contract/domain.js.map +1 -0
  35. package/lib/contract/errors.d.ts +6 -0
  36. package/lib/contract/errors.d.ts.map +1 -0
  37. package/lib/contract/errors.js +6 -0
  38. package/lib/contract/errors.js.map +1 -0
  39. package/lib/contract/index.d.ts +15 -0
  40. package/lib/contract/index.d.ts.map +1 -0
  41. package/lib/contract/index.js +15 -0
  42. package/lib/contract/index.js.map +1 -0
  43. package/lib/contract/ledger.d.ts +40 -0
  44. package/lib/contract/ledger.d.ts.map +1 -0
  45. package/lib/contract/ledger.js +6 -0
  46. package/lib/contract/ledger.js.map +1 -0
  47. package/lib/contract/market.d.ts +30 -0
  48. package/lib/contract/market.d.ts.map +1 -0
  49. package/lib/contract/market.js +6 -0
  50. package/lib/contract/market.js.map +1 -0
  51. package/lib/contract/rpc.d.ts +24 -0
  52. package/lib/contract/rpc.d.ts.map +1 -0
  53. package/lib/contract/rpc.js +6 -0
  54. package/lib/contract/rpc.js.map +1 -0
  55. package/lib/contract.d.ts +6 -403
  56. package/lib/contract.d.ts.map +1 -1
  57. package/lib/contract.js +6 -24
  58. package/lib/contract.js.map +1 -1
  59. package/lib/core/session.d.ts +1 -1
  60. package/lib/core/session.d.ts.map +1 -1
  61. package/lib/core/session.js +1 -2
  62. package/lib/core/session.js.map +1 -1
  63. package/lib/data/cached-market-data.d.ts +61 -0
  64. package/lib/data/cached-market-data.d.ts.map +1 -0
  65. package/lib/data/cached-market-data.js +174 -0
  66. package/lib/data/cached-market-data.js.map +1 -0
  67. package/lib/data/futures-market-data.d.ts.map +1 -1
  68. package/lib/data/futures-market-data.js +9 -10
  69. package/lib/data/futures-market-data.js.map +1 -1
  70. package/lib/index.d.ts +25 -1
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +156 -18
  73. package/lib/index.js.map +1 -1
  74. package/lib/service/account-moves.d.ts +64 -0
  75. package/lib/service/account-moves.d.ts.map +1 -0
  76. package/lib/service/account-moves.js +49 -0
  77. package/lib/service/account-moves.js.map +1 -0
  78. package/lib/service/accounts-rpc.d.ts +17 -0
  79. package/lib/service/accounts-rpc.d.ts.map +1 -0
  80. package/lib/service/accounts-rpc.js +77 -0
  81. package/lib/service/accounts-rpc.js.map +1 -0
  82. package/lib/service/compare-rpc.d.ts +22 -0
  83. package/lib/service/compare-rpc.d.ts.map +1 -0
  84. package/lib/service/compare-rpc.js +70 -0
  85. package/lib/service/compare-rpc.js.map +1 -0
  86. package/lib/service/errors.d.ts +20 -4
  87. package/lib/service/errors.d.ts.map +1 -1
  88. package/lib/service/errors.js +12 -5
  89. package/lib/service/errors.js.map +1 -1
  90. package/lib/service/futures-rpc.d.ts.map +1 -1
  91. package/lib/service/futures-rpc.js +7 -25
  92. package/lib/service/futures-rpc.js.map +1 -1
  93. package/lib/service/futures-service.d.ts +28 -8
  94. package/lib/service/futures-service.d.ts.map +1 -1
  95. package/lib/service/futures-service.js +144 -146
  96. package/lib/service/futures-service.js.map +1 -1
  97. package/lib/service/ledger-admin.d.ts +67 -0
  98. package/lib/service/ledger-admin.d.ts.map +1 -0
  99. package/lib/service/ledger-admin.js +102 -0
  100. package/lib/service/ledger-admin.js.map +1 -0
  101. package/lib/service/paper-service.d.ts +39 -12
  102. package/lib/service/paper-service.d.ts.map +1 -1
  103. package/lib/service/paper-service.js +177 -156
  104. package/lib/service/paper-service.js.map +1 -1
  105. package/lib/service/route.d.ts.map +1 -1
  106. package/lib/service/route.js +5 -2
  107. package/lib/service/route.js.map +1 -1
  108. package/lib/service/rpc-support.d.ts +34 -0
  109. package/lib/service/rpc-support.d.ts.map +1 -0
  110. package/lib/service/rpc-support.js +57 -0
  111. package/lib/service/rpc-support.js.map +1 -0
  112. package/lib/service/rpc.d.ts +20 -3
  113. package/lib/service/rpc.d.ts.map +1 -1
  114. package/lib/service/rpc.js +44 -25
  115. package/lib/service/rpc.js.map +1 -1
  116. package/lib/store/accounts.d.ts +110 -0
  117. package/lib/store/accounts.d.ts.map +1 -0
  118. package/lib/store/accounts.js +352 -0
  119. package/lib/store/accounts.js.map +1 -0
  120. package/lib/store/atomic-file.d.ts +16 -0
  121. package/lib/store/atomic-file.d.ts.map +1 -0
  122. package/lib/store/atomic-file.js +34 -0
  123. package/lib/store/atomic-file.js.map +1 -0
  124. package/lib/store/futures-repo.d.ts +8 -49
  125. package/lib/store/futures-repo.d.ts.map +1 -1
  126. package/lib/store/futures-repo.js +34 -246
  127. package/lib/store/futures-repo.js.map +1 -1
  128. package/lib/store/ledger-repo-base.d.ts +120 -0
  129. package/lib/store/ledger-repo-base.d.ts.map +1 -0
  130. package/lib/store/ledger-repo-base.js +275 -0
  131. package/lib/store/ledger-repo-base.js.map +1 -0
  132. package/lib/store/notes.d.ts +29 -0
  133. package/lib/store/notes.d.ts.map +1 -0
  134. package/lib/store/notes.js +78 -0
  135. package/lib/store/notes.js.map +1 -0
  136. package/lib/store/paths.d.ts +2 -0
  137. package/lib/store/paths.d.ts.map +1 -1
  138. package/lib/store/paths.js +4 -0
  139. package/lib/store/paths.js.map +1 -1
  140. package/lib/store/repo.d.ts +15 -55
  141. package/lib/store/repo.d.ts.map +1 -1
  142. package/lib/store/repo.js +41 -206
  143. package/lib/store/repo.js.map +1 -1
  144. package/lib/store/shortlist.d.ts.map +1 -1
  145. package/lib/store/shortlist.js +4 -6
  146. package/lib/store/shortlist.js.map +1 -1
  147. package/lib/store/snapshots.d.ts +0 -3
  148. package/lib/store/snapshots.d.ts.map +1 -1
  149. package/lib/store/snapshots.js +0 -3
  150. package/lib/store/snapshots.js.map +1 -1
  151. package/package.json +1 -1
  152. package/src/agent/account-tools.ts +136 -0
  153. package/src/agent/futures-tools.ts +1 -6
  154. package/src/agent/ledger-tools.ts +29 -16
  155. package/src/agent/tool-result.ts +27 -0
  156. package/src/agent/tools.ts +30 -10
  157. package/src/client/entry.js +14 -0
  158. package/src/client/parts/10-core.js +535 -0
  159. package/src/client/parts/20-styles.js +336 -0
  160. package/src/client/parts/30-atoms.js +769 -0
  161. package/src/client/parts/35-hooks.js +447 -0
  162. package/src/client/parts/40-stock-tabs.js +641 -0
  163. package/src/client/parts/50-futures.js +911 -0
  164. package/src/client/parts/60-shell.js +706 -0
  165. package/src/client/parts/70-plugin.js +67 -0
  166. package/src/contract/accounts.ts +82 -0
  167. package/src/contract/common.ts +173 -0
  168. package/src/contract/domain.ts +217 -0
  169. package/src/contract/errors.ts +34 -0
  170. package/src/contract/index.ts +15 -0
  171. package/src/contract/ledger.ts +42 -0
  172. package/src/contract/market.ts +39 -0
  173. package/src/contract/rpc.ts +15 -0
  174. package/src/contract.ts +6 -472
  175. package/src/core/session.ts +1 -2
  176. package/src/data/cached-market-data.ts +193 -0
  177. package/src/data/futures-market-data.ts +9 -10
  178. package/src/index.ts +168 -20
  179. package/src/service/account-moves.ts +72 -0
  180. package/src/service/accounts-rpc.ts +80 -0
  181. package/src/service/compare-rpc.ts +77 -0
  182. package/src/service/errors.ts +23 -4
  183. package/src/service/futures-rpc.ts +7 -24
  184. package/src/service/futures-service.ts +161 -159
  185. package/src/service/ledger-admin.ts +140 -0
  186. package/src/service/paper-service.ts +183 -153
  187. package/src/service/route.ts +5 -2
  188. package/src/service/rpc-support.ts +61 -0
  189. package/src/service/rpc.ts +59 -23
  190. package/src/store/accounts.ts +373 -0
  191. package/src/store/atomic-file.ts +37 -0
  192. package/src/store/futures-repo.ts +35 -260
  193. package/src/store/ledger-repo-base.ts +337 -0
  194. package/src/store/notes.ts +86 -0
  195. package/src/store/paths.ts +5 -0
  196. package/src/store/repo.ts +47 -229
  197. package/src/store/shortlist.ts +3 -5
  198. package/src/store/snapshots.ts +0 -3
  199. package/src/client/index.js +0 -3275
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Free-form notes for one account.
3
+ *
4
+ * A single text block the human rewrites however they like: no entries, no
5
+ * timestamps, no history. It lives beside the ledger (`note.md`) instead of the
6
+ * registry so a long note never bloats `accounts.json`, and the model has no
7
+ * tool for it — this is the human's own space.
8
+ * @module @dsh-ft/dsh-fft-paper-trading/store/notes
9
+ */
10
+
11
+ import { readFile, stat } from 'node:fs/promises'
12
+ import type { NoteView } from '../contract.js'
13
+ import { PaperError } from '../service/errors.js'
14
+ import { notePath } from './paths.js'
15
+ import { writeFileAtomic } from './atomic-file.js'
16
+
17
+ /** 100 KB of UTF-8: a very long research note, still cheap to load and save. */
18
+ export const NOTE_MAX_BYTES = 100_000
19
+
20
+ export interface AccountNotesOptions {
21
+ home: string
22
+ maxBytes?: number
23
+ }
24
+
25
+ export class AccountNotes {
26
+ private readonly home: string
27
+ private readonly maxBytes: number
28
+ /** Writes to one account must land in order; two quick saves used to race
29
+ * for the same temp file and one of them failed with ENOENT. */
30
+ private readonly queues = new Map<string, Promise<unknown>>()
31
+
32
+ constructor(options: AccountNotesOptions) {
33
+ this.home = options.home
34
+ this.maxBytes = options.maxBytes ?? NOTE_MAX_BYTES
35
+ }
36
+
37
+ /** Read one account's note; a missing file is an empty note, not an error. */
38
+ async read(accountId: string): Promise<NoteView> {
39
+ const file = notePath(this.home, accountId)
40
+ let text: string
41
+ try {
42
+ text = await readFile(file, 'utf8')
43
+ } catch (error) {
44
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
45
+ return { text: '', bytes: 0, maxBytes: this.maxBytes }
46
+ }
47
+ throw new PaperError('INTERNAL', `读取笔记失败:${error instanceof Error ? error.message : String(error)}`)
48
+ }
49
+ let updatedAt: string | undefined
50
+ try {
51
+ updatedAt = (await stat(file)).mtime.toISOString()
52
+ } catch {
53
+ updatedAt = undefined
54
+ }
55
+ return {
56
+ text,
57
+ bytes: byteLength(text),
58
+ maxBytes: this.maxBytes,
59
+ ...(updatedAt === undefined ? {} : { updatedAt }),
60
+ }
61
+ }
62
+
63
+ /** Replace the whole note atomically; an empty string clears it. */
64
+ async write(accountId: string, text: unknown): Promise<NoteView> {
65
+ if (typeof text !== 'string') throw new PaperError('INVALID_ARGUMENT', '笔记内容必须是文本')
66
+ const bytes = byteLength(text)
67
+ if (bytes > this.maxBytes) {
68
+ throw new PaperError('INVALID_ARGUMENT', `笔记不能超过 ${Math.round(this.maxBytes / 1000)} KB(当前 ${Math.round(bytes / 1000)} KB)`)
69
+ }
70
+ const previous = this.queues.get(accountId) ?? Promise.resolve()
71
+ const next = previous.then(async () => {
72
+ try {
73
+ await writeFileAtomic(notePath(this.home, accountId), text)
74
+ } catch (error) {
75
+ throw new PaperError('INTERNAL', `保存笔记失败:${error instanceof Error ? error.message : String(error)}`)
76
+ }
77
+ })
78
+ this.queues.set(accountId, next.catch(() => undefined))
79
+ await next
80
+ return this.read(accountId)
81
+ }
82
+ }
83
+
84
+ function byteLength(text: string): number {
85
+ return Buffer.byteLength(text, 'utf8')
86
+ }
@@ -28,3 +28,8 @@ export function eventsPath(home: string, accountId: string): string {
28
28
  export function backupsDir(home: string, accountId: string): string {
29
29
  return join(accountDir(home, accountId), 'backups')
30
30
  }
31
+
32
+ /** One account's free-form notes; lives beside the ledger, not in the registry. */
33
+ export function notePath(home: string, accountId: string): string {
34
+ return join(accountDir(home, accountId), 'note.md')
35
+ }
package/src/store/repo.ts CHANGED
@@ -1,95 +1,57 @@
1
- import { join, resolve } from 'node:path'
2
1
  import type { Quote } from '../contract.js'
3
- import { applyEvent, emptyState, verify } from '../core/ledger.js'
2
+ import { applyEvent, verify } from '../core/ledger.js'
4
3
  import { migrateLedger, ledgerVersionOf, MigrationUnavailable } from '../core/migrations.js'
5
- import { prepareLedger, replay, type PreparedLedger } from '../core/replay.js'
4
+ import { prepareLedger, replay } from '../core/replay.js'
6
5
  import type { AccountState, LedgerEvent } from '../core/types.js'
7
- import { EventStore, readEventsFile } from './event-store.js'
8
- import type { AccountStore, LedgerFile, LedgerSnapshot, Transaction, TransactionOutcome } from './port.js'
9
- import { backupsDir, eventsPath } from './paths.js'
10
- import {
11
- ensureAutoSnapshot,
12
- listSnapshotFiles,
13
- snapshotPath,
14
- writeSnapshot,
15
- type SnapshotFile,
16
- } from './snapshots.js'
17
-
18
- export interface RepoOptions {
19
- home: string
20
- accountId: string
21
- logger?: { warn(message: string): void }
6
+ import { readEventsFile } from './event-store.js'
7
+ import { LedgerRepoBase, type LedgerPlane, type LedgerRepoOptions } from './ledger-repo-base.js'
8
+ import type { AccountStore, LedgerSnapshot } from './port.js'
9
+ import { snapshotPath, writeSnapshot, type SnapshotFile } from './snapshots.js'
10
+
11
+ /** How the stock plane folds its event log; the storage mechanics are shared. */
12
+ const ACCOUNT_PLANE: LedgerPlane<AccountState, LedgerEvent> = {
13
+ label: 'paper-trading',
14
+ prepare: prepareLedger,
15
+ replay: (events, accountId) => replay(events, accountId),
16
+ applyEvent,
17
+ verify,
18
+ summary: state => ({
19
+ lastSeq: state.lastSeq,
20
+ tradeDate: state.tradeDate,
21
+ cashCents: state.cashCents,
22
+ blocked: state.blocked,
23
+ ...(state.blockedReason === undefined ? {} : { blockedReason: state.blockedReason }),
24
+ }),
25
+ ledgerVersion: ledgerVersionOf,
26
+ dropEventsWhenBlocked: true,
22
27
  }
23
28
 
24
29
  /**
25
- * Loads, replays and appends the single account ledger.
26
- *
27
- * Every write goes through one Promise queue and one sequence invariant, so a
28
- * concurrent read cannot duplicate a day-boundary event. Repairs and resets use
29
- * an atomic file replacement; a rejected write never touches the file.
30
+ * The stock account ledger: shared JSONL persistence plus the stock fold.
30
31
  *
31
32
  * Recovery is a first-class path: a ledger from a known older version is
32
33
  * migrated in place (snapshot first), and any snapshot can be restored into the
33
- * running process without restarting the host.
34
+ * running process without restarting the host. Only the migration chain and the
35
+ * migration-aware snapshot inspection are stock-specific.
34
36
  */
35
- export class AccountRepo implements AccountStore {
36
- private readonly store: EventStore
37
- private state: AccountState | undefined
38
- private loading: Promise<AccountState> | undefined
39
- private queue: Promise<unknown> = Promise.resolve()
40
-
41
- constructor(private readonly options: RepoOptions) {
42
- this.store = new EventStore(eventsPath(options.home, options.accountId))
43
- }
44
-
45
- /** Absolute path of `events.jsonl`, surfaced so a locked account is fixable. */
46
- get ledgerPath(): string {
47
- return this.store.filePath
48
- }
49
-
50
- private backups(): string {
51
- return backupsDir(this.options.home, this.options.accountId)
52
- }
53
-
54
- private async ensureLoaded(): Promise<AccountState> {
55
- if (this.state !== undefined) return this.state
56
- if (this.loading === undefined) this.loading = this.loadOnce()
57
- return this.loading
37
+ export class AccountRepo extends LedgerRepoBase<AccountState, LedgerEvent> implements AccountStore {
38
+ constructor(options: LedgerRepoOptions) {
39
+ super(ACCOUNT_PLANE, options)
58
40
  }
59
41
 
60
- private async loadOnce(): Promise<AccountState> {
61
- const { events, skipped } = await this.store.readAll()
62
- if (skipped > 0) this.options.logger?.warn(`paper-trading: dropped ${skipped} malformed ledger line(s)`)
63
-
64
- const prepared = prepareLedger(events)
65
- // Conflicting same-seq events are real corruption: replay the original file
66
- // untouched so the violation reports what is actually there.
67
- const source = prepared.issues.length > 0 ? events : prepared.events
68
-
69
- // A known older version is rewritten instead of locking: the account keeps
70
- // its history. `undefined` means "already current" or "no migration path";
71
- // only the latter locks, and replay below records the reason.
72
- const migrated = prepared.issues.length === 0 ? await this.tryMigrate(prepared.events) : undefined
73
- if (migrated !== undefined) {
74
- this.state = migrated
75
- } else {
76
- const result = replay(source, this.options.accountId)
77
- this.state = result.state
78
- const issues = [...prepared.issues, ...result.issues]
79
- if (issues.length > 0 && !result.state.blocked) {
80
- await this.recordViolation(issues)
81
- } else if (prepared.issues.length === 0 && prepared.duplicates > 0) {
82
- this.state = await this.compact(prepared, result.state)
42
+ /** Refresh the in-memory mark-to-market cache; quote ticks are not ledger events. */
43
+ async markPrices(quotes: readonly Quote[]): Promise<AccountState> {
44
+ return this.enqueue(async () => {
45
+ const state = await this.ensureLoaded()
46
+ for (const quote of quotes) {
47
+ const position = state.positions[quote.symbol]
48
+ if (position !== undefined) {
49
+ position.lastPrice = quote.last
50
+ position.lastTs = quote.marketTs ?? undefined
51
+ }
83
52
  }
84
- }
85
-
86
- // A known-good copy from before this session is what recovery has to fall
87
- // back on; it is deliberately skipped for a blocked ledger (that file is the
88
- // evidence, not the backup).
89
- if (!this.state.blocked) {
90
- await ensureAutoSnapshot(this.store, this.backups(), { logger: this.options.logger })
91
- }
92
- return this.state
53
+ return state
54
+ })
93
55
  }
94
56
 
95
57
  /**
@@ -99,7 +61,7 @@ export class AccountRepo implements AccountStore {
99
61
  * original file byte for byte, and returning `undefined` lets the normal
100
62
  * replay path lock the account with the version reason.
101
63
  */
102
- private async tryMigrate(events: LedgerEvent[]): Promise<AccountState | undefined> {
64
+ protected override async tryMigrate(events: LedgerEvent[]): Promise<AccountState | undefined> {
103
65
  let outcome
104
66
  try {
105
67
  outcome = migrateLedger(events)
@@ -139,138 +101,10 @@ export class AccountRepo implements AccountStore {
139
101
  }
140
102
 
141
103
  /**
142
- * Drop repeated events from the file and leave one `ledger.repaired` marker.
143
- *
144
- * Only reached when every duplicate was byte-equivalent apart from its
145
- * `recordedAt` stamp, so the account values themselves are untouched.
146
- */
147
- private async compact(prepared: PreparedLedger, state: AccountState): Promise<AccountState> {
148
- const seq = state.lastSeq + 1
149
- const event: LedgerEvent = {
150
- seq,
151
- id: `evt-${seq}`,
152
- ts: new Date().toISOString(),
153
- type: 'ledger.repaired',
154
- payload: { dropped: prepared.duplicates },
155
- }
156
- try {
157
- await writeSnapshot(this.store, this.backups(), 'repair')
158
- await this.store.replace([...prepared.events, event])
159
- applyEvent(state, event)
160
- this.options.logger?.warn(`paper-trading: dropped ${prepared.duplicates} duplicate ledger event(s)`)
161
- } catch (error) {
162
- this.options.logger?.warn(`paper-trading: ledger repair failed, kept in memory only: ${String(error)}`)
163
- }
164
- return state
165
- }
166
-
167
- private async recordViolation(issues: string[]): Promise<void> {
168
- const state = this.state
169
- // A blocked account never grows its ledger: a new violation per tick would
170
- // bury the original evidence under thousands of identical events.
171
- if (state === undefined || state.blocked) return
172
- const seq = state.lastSeq + 1
173
- const event: LedgerEvent = {
174
- seq,
175
- id: `evt-${seq}`,
176
- ts: new Date().toISOString(),
177
- type: 'ledger.violation',
178
- payload: { check: 'replay', expected: 'consistent', actual: issues.join('; ') },
179
- }
180
- await this.store.append([event])
181
- applyEvent(state, event)
182
- this.state = state
183
- this.options.logger?.warn(`paper-trading: ledger violation, account blocked: ${issues.join('; ')}`)
184
- }
185
-
186
- async current(): Promise<AccountState> {
187
- return this.ensureLoaded()
188
- }
189
-
190
- async transact<T>(build: (state: AccountState) => Transaction<T> | Promise<Transaction<T>>): Promise<TransactionOutcome<T>> {
191
- return this.enqueue(async () => {
192
- const state = await this.ensureLoaded()
193
- const built = await build(state)
194
- const events = built.events
195
- if (events.length === 0) return { state, value: built.value, events }
196
- if (state.blocked) {
197
- this.options.logger?.warn(`paper-trading: account blocked, dropped ${events.length} event(s)`)
198
- return { state, value: built.value, events: [] }
199
- }
200
- this.assertSequence(state, events)
201
- await this.store.append(events)
202
- for (const event of events) applyEvent(state, event)
203
- const issues = verify(state)
204
- this.state = state
205
- if (issues.length > 0) await this.recordViolation(issues)
206
- return { state: this.state ?? state, value: built.value, events }
207
- })
208
- }
209
-
210
- async append(events: readonly LedgerEvent[]): Promise<AccountState> {
211
- const outcome = await this.transact(() => ({ events: [...events], value: undefined }))
212
- return outcome.state
213
- }
214
-
215
- /**
216
- * Replace the file with a new ledger (reset, compaction).
217
- *
218
- * The replacement is validated and replayed before the atomic rename, so a
219
- * reset never leaves a ledger that would lock the account on the next start.
104
+ * Snapshot inspection for the stock plane: unlike futures, an older snapshot
105
+ * may be migratable, and the reason must be reported before the restore.
220
106
  */
221
- async replace(events: readonly LedgerEvent[]): Promise<AccountState> {
222
- return this.enqueue(async () => {
223
- this.assertSequence(emptyState(this.options.accountId), events)
224
- const result = replay([...events], this.options.accountId)
225
- if (result.issues.length > 0) {
226
- throw new Error(`paper-trading: refusing an inconsistent ledger: ${result.issues.join('; ')}`)
227
- }
228
- // Settle any in-flight load first: it may still repair or block the old file.
229
- await this.ensureLoaded()
230
- await this.store.replace(events)
231
- this.state = result.state
232
- this.loading = Promise.resolve(result.state)
233
- return this.state
234
- })
235
- }
236
-
237
- /** Refresh the in-memory mark-to-market cache; quote ticks are not ledger events. */
238
- async markPrices(quotes: readonly Quote[]): Promise<AccountState> {
239
- return this.enqueue(async () => {
240
- const state = await this.ensureLoaded()
241
- for (const quote of quotes) {
242
- const position = state.positions[quote.symbol]
243
- if (position !== undefined) {
244
- position.lastPrice = quote.last
245
- position.lastTs = quote.marketTs ?? undefined
246
- }
247
- }
248
- return state
249
- })
250
- }
251
-
252
- /** Copy the event file into `backups/`, named after the reset timestamp. */
253
- async backup(label: string): Promise<boolean> {
254
- return this.enqueue(async () => {
255
- const stamp = label.replace(/[:.]/g, '-')
256
- return this.store.backup(`${this.backups()}/events-${stamp}.jsonl`)
257
- })
258
- }
259
-
260
- /** Raw file text for `account/export`; `content: null` means "not created yet". */
261
- async readLedger(): Promise<LedgerFile> {
262
- return { path: resolve(this.store.filePath), content: await this.store.readText() }
263
- }
264
-
265
- /** List snapshots with replay metadata, newest first. */
266
- async snapshots(): Promise<LedgerSnapshot[]> {
267
- const files = await listSnapshotFiles(this.backups())
268
- const snapshots: LedgerSnapshot[] = []
269
- for (const file of files) snapshots.push(await this.inspectSnapshot(file))
270
- return snapshots
271
- }
272
-
273
- private async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
107
+ protected override async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
274
108
  const base = {
275
109
  name: file.name,
276
110
  createdAt: new Date(file.mtimeMs).toISOString(),
@@ -324,13 +158,13 @@ export class AccountRepo implements AccountStore {
324
158
  }
325
159
 
326
160
  /**
327
- * Replace the live ledger with one snapshot.
161
+ * Replace the live ledger with one snapshot, migrating it first when needed.
328
162
  *
329
163
  * Allowed while blocked: a locked account is exactly the case recovery exists
330
164
  * for. Validation happens before anything is written, and the current file is
331
165
  * snapshotted first so the recovery itself can be undone.
332
166
  */
333
- async restore(name: string): Promise<AccountState> {
167
+ override async restore(name: string): Promise<AccountState> {
334
168
  const file = snapshotPath(this.backups(), name)
335
169
  return this.enqueue(async () => {
336
170
  // Settle an in-flight load first: it may still repair/block the old file,
@@ -362,20 +196,4 @@ export class AccountRepo implements AccountStore {
362
196
  return this.state
363
197
  })
364
198
  }
365
-
366
- private assertSequence(state: AccountState, events: readonly LedgerEvent[]): void {
367
- let expected = state.lastSeq + 1
368
- for (const event of events) {
369
- if (!Number.isInteger(event.seq) || event.seq !== expected) {
370
- throw new Error(`paper-trading: ledger seq mismatch: expected ${expected}, got ${String(event.seq)}`)
371
- }
372
- expected += 1
373
- }
374
- }
375
-
376
- private enqueue<T>(task: () => Promise<T>): Promise<T> {
377
- const run = this.queue.then(task, task)
378
- this.queue = run.then(() => undefined, () => undefined)
379
- return run
380
- }
381
199
  }
@@ -1,6 +1,7 @@
1
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
1
+ import { mkdir, readFile, rename } from 'node:fs/promises'
2
2
  import { dirname, join } from 'node:path'
3
3
  import { paperRoot } from './paths.js'
4
+ import { writeFileAtomic } from './atomic-file.js'
4
5
 
5
6
  /** UI preference, deliberately not part of the account ledger. */
6
7
  export class ShortlistStore {
@@ -26,10 +27,7 @@ export class ShortlistStore {
26
27
 
27
28
  async write(symbols: string[]): Promise<string[]> {
28
29
  const clean = [...new Set(symbols.map(symbol => symbol.trim()).filter(Boolean))].slice(0, 200)
29
- await mkdir(dirname(this.file), { recursive: true, mode: 0o700 })
30
- const temporary = `${this.file}.tmp`
31
- await writeFile(temporary, `${JSON.stringify({ symbols: clean }, null, 2)}\n`, { mode: 0o600 })
32
- await rename(temporary, this.file)
30
+ await writeFileAtomic(this.file, `${JSON.stringify({ symbols: clean }, null, 2)}\n`)
33
31
  return clean
34
32
  }
35
33
  }
@@ -23,9 +23,6 @@ export interface SnapshotFile {
23
23
  /** `events-<reason>-<stamp>.jsonl`; the legacy names (`events-<stamp>.jsonl`) also match. */
24
24
  const SNAPSHOT_NAME = /^events-[A-Za-z0-9._-]+\.jsonl$/
25
25
  export const AUTO_SNAPSHOT_PREFIX = 'events-auto-'
26
- export const PRE_MIGRATE_PREFIX = 'events-pre-migrate-'
27
- export const PRE_RESTORE_PREFIX = 'events-pre-restore-'
28
- export const MANUAL_PREFIX = 'events-manual-'
29
26
 
30
27
  /** Keep only this many automatic snapshots; reset/repair/pre-* files are never pruned. */
31
28
  const KEEP_AUTO = 10