Skip to content

refactor: remove dead code, duplicates and redundant tests - #174

Merged
neoromantic merged 56 commits into
mainfrom
refactor/remove-dead-code
Nov 18, 2026
Merged

neoromantic merged 56 commits into
mainfrom
refactor/remove-dead-code

Conversation

@neoromantic

@neoromantic neoromantic commented Nov 17, 2026 •

Copy link
Copy Markdown
Owner

What

A review of the whole codebase for dead code, duplicates and tests that test nothing. No behaviour change: CLI output, error codes and texts, the DB schema and the daemon's request order stay the same. 129 files, +1,241 / −11,780 lines against main (with #155 and 0.13–0.14 merged in): about −2,900 in src/ and −7,650 in tests.

Removed, each in its own commit:

  • Modules with no production caller: the second, mock-style sync worker (sync-worker-core.ts), sync-worker-runner.ts, job-executor.ts, utils/message-parser.ts, db/cache.ts, db/cache-index.ts, handleBatchMessages, the test-only client manager, and dead types in db/types.ts.
  • Methods with no production caller in ChatSyncStateService, SyncJobsService, ChatsCache, UsersCache, MessagesCache, RateLimitsService, DaemonStatusService and the scheduler.
  • Tests of that dead code, and tautological tests in contacts, chats and user: tests that re-implement the logic instead of calling it.

Merged duplicates:

  • One requestPeer preamble for the job handlers. The rate-limit check still comes first.
  • One error-mapping helper for commands, one getErrorMessage, one saveLoggedInUser.
  • fetchMessageById reuses fetchMessagesByIdRaw.
  • Shared paginate() for the cache and API branches.
  • Shared test helpers: testDaemonContext, createAccountCacheDb, the chatRow fixtures and the cache-layout helpers.

How it was checked

Each change set was planned by a reviewer, confirmed by an independent skeptic, applied by its own agent with targeted tests, and committed. Three independent reviewers then read the whole diff for behaviour, lost coverage and leftovers. Their 12 findings were all minor and are fixed: one restored test, two new tests for the shared requestPeer exits, an empty --type again meaning no filter, and dead leftovers.

  • bun run check: pass
  • bun run test: 2029 pass, 0 fail
  • bun run test:e2e: 455 pass, 0 fail
  • bun run build: pass; tg --help and tg daemon --help work without credentials
  • bun run test:integration: not verified. The test session answers AUTH_KEY_UNREGISTERED, and its re-login is in progress separately.

🤖 Generated with Claude Code

neoromantic and others added 30 commits November 14, 2026 04:51
A group (basic group or supergroup) adds new messages to the cache only
while the account sent an ordinary message there in the last 90 days.
The rule lives in one place, MessagesCache, so live updates, the dialog
pass, every sync job, tg messages list/get (--fresh too) and tg send all
follow it, whatever the tg chats sync mode. Cached messages stay and are
still updated; private chats and channels are unchanged.

- group_participation keeps the newest own message per group;
  group_capture_gaps keeps the pauses, so catch-up and history after a
  return skip them. An older cache gets its own messages as first facts.
- After each dialog pass, one check_group_participation job per group
  searches for the newest own message of the last 90 days (catch-up
  lane, P4, usual retries and FLOOD_WAIT handling).
- The scheduler queues no work for a group that isn't active and drops
  its pending jobs; a page whose group went off in flight moves nothing.
  A page with messages kept out records no history range.
- tg messages list/get build API pages in memory, so they show
  Telegram's page whether the cache took it or not.
- tg chats list/sync show group_participation_required/_unknown and
  lastOwnMessageAt; tg status leaves paused groups out of its progress.

BREAKING CHANGE: groups without an own message in the last 90 days no
longer add messages to the cache, in any sync mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rticipation rule

Resolving a @username kept only the input peer, so a broadcast channel new
to the cache had no type, counted as a group and its first page was not
cached. Cache the resolved chat (not a min one) before its messages are
written, as `tg chats get` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
contacts.resolveUsername carries no last message and often no member
count, so the cache upsert cleared what the dialog pass had stored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ps, ID offset, header)

The merge already runs under the write lock, so the upsert is a plain
INSERT OR REPLACE. One schema check helper, the shared channel ID offset,
and history progress reads pauses in its own query instead of hasGaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…worker gate, accurate PAUSED comment

CacheWriteResult counts written messages instead of listing them; every
caller used only the length. The worker gate reuses
CHAT_INDEPENDENT_JOB_TYPES instead of a second list of capture jobs, and
the PAUSED comment no longer claims what the write did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le-row MessagesHistory.get, inline withSync

cacheHistoryResponse builds page rows with ChatsCache.getById (one lookup)
and UsersCache.getById instead of ad-hoc queries. MessagesHistory.getMany
becomes get(chatId, messageId), its only use. chats list inlines withSync
into toItem.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se fixture helpers

The e2e now checks the sender and that no history range is recorded, then
caches the page once the account took part, in one test. The unit copy of
the page test goes. Chat and photo fixtures use fakeDialog,
dialogToCacheInput, photoMessage and takePartIn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop takePartIn calls that changed nothing (repeated after a schema init,
or before writes to DMs only) and trim the rest to the groups whose
messages each test caches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ement of the rule

Other docs, the changelog entry and daemon-bootstrap comments link to the
section instead of restating the 90-day rule, its writers and scheduling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…articipation

The Pauses bullet says again that a pause ends at the newest own message the
search finds, and the date source says nothing of the search is cached.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… in the changelog

The Unreleased entry lists the commands the rule covers instead of "every
mode", and says the daemon sends one search per group after each dialog pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er-core.ts)

The daemon runs only createRealSyncWorker; the abstract worker in
sync-worker-core.ts had no production caller and was covered only by its
own test file. Move SyncWorkerConfig and its default into
sync-worker-real-types.ts, base RealJobResult on JobResultLike, and drop
the core file, its test and its mentions in the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and the worker object's test-only members

The daemon schedules jobs itself and calls only client, canMakeApiCall and
processJobReal on a worker. The runner, runOnceReal/runOnceBase, the other
worker members and the barrel's value re-exports had no production caller.
Their tests go with them; the config-override test stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No production code calls UpdateHandlers.handleBatchMessages; history sync
writes batches through the sync worker. Remove it with its helpers
(groupMessagesByChat, updateCursorsForBatch, processChatBatch) and the
three test blocks that covered only this dead path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lifecycle wrappers and SyncJobsService claimNextJob/cleanup*

JobExecutor, DEFAULT_SYNC_DELAYS and DaemonConfig's inter-batch/inter-job
delays had no production caller. The scheduler's claimNextJob, startJob,
completeJob, failJob, updateProgress, cleanup and cancelJobsForChat were
only used by job-executor and tests, and SyncJobsService's claimNextJob,
cleanupCompleted and cleanupFailed only by them; pruneCache does the
real job cleanup. Tests that called scheduler.cleanup() now call
pruneCache with a 24 h failed-job retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…iority

Nothing read the per-type and per-priority maps. getStatus now returns only
the pending and running counts, used by the startup log. The daemon tick
always counts an account's queue from its own sync_jobs table, the same
table the scheduler read, so the written figures are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imit/InputPeer preamble

requestPeer returns the chat's InputPeer or the job's result (rate limited,
or a permanent failure when the cache can't build the peer). Five job
handlers share it instead of repeating the two checks; initial load keeps
its leading rate-limit return before the cursor check. The `let result`
temporaries become direct returns. getInputPeer and its delegation test go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No caller read its minId/maxId: the job handlers compute their own
bounds. It now parses the page and drops what it can't parse. Callers in
the job handlers, tg messages history and the storage benchmark take the
array directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rward-ID helper

The daemon's onNewMessage was the only production user of
utils/message-parser.ts, for the forward sender ID. It now calls
extractForwardFromId from sync-worker-real-helpers, which resolves the
same marked ID through toPeerIdFromRawPeer. The rest of the file and its
test were dead; the forward and peer-ID cases stay covered by
telegram-peer-ids, sync-worker-real-helpers and daemon-accounts.connect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…x.ts and cache.ts, and schema.ts SyncStateRow

db/types.ts keeps only what src imports: the cache/retention config types and
defaults, ChatType, ApiActivityEntry, the duration helpers and isCacheStale.
cache-index.ts and cache.ts had no importers; SyncStateRow in schema.ts was unused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…piredFloodWaits

No production code called them. Remove the three methods, their seven
prepared statements, GetActivityOptions, ApiActivityRow and
ApiActivityEntry. Tests now read rate_limits and api_activity with SQL;
the tests of the removed methods go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rsor UPDATEs

getEnabledChats, getChatsByPriority, getIncompleteHistory, setSyncEnabled
and resetSyncState had no production callers; their tests go with them, and
the two tests that used resetSyncState for setup now run a direct UPDATE.
updateCursors uses one COALESCE statement instead of three, and
updateLastSync picks its statement with a ternary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 'Contacts Commands' block re-tested UsersCache, isCacheStale and
re-implemented command logic inline; cache.test.ts already covers the
cache. The phone search and last-name-only display_name cases move to
cache.test.ts, the only ones it lacked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop tests that re-implemented chat type detection and argument parsing
inline, exercised only an unused mock client, or re-tested ChatsCache
already covered in cache.test.ts. cache.test.ts gains the one missing
case: an exact title match outranks newer partial matches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
'Cache vs API behavior', 'Error handling' and the USERNAME_NOT_OCCUPIED
string check re-ran inline copies of command logic; 'Account parameter
handling' duplicated account-selector.test.ts and 'Staleness checking'
duplicated the isCacheStale tests in cache.test.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getStale, prune and delete had no production callers in either cache.
CachedChat is now the ChatCacheRow class (same keys and column order),
so rows come back as-is without rowToChat; list() runs one query with an
optional type filter, and the unused config parameter is gone. Tests of
the deleted methods go with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eleted count

listByChatId and countByChatId's includeDeleted flag had no production
callers; message listing goes through MessagesHistory. Remove the method,
its options type, its statements and its tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clear, isDaemonRunning, updateLastUpdate and setMessagesSynced had no
production callers. Remove them, their tests and their mock members.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The lane priority subquery and the runs-for-chat guard were spelled out
in several sync_jobs statements; name them once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
neoromantic and others added 6 commits November 18, 2026 01:37
…initial_load

cdc6f7e rewrote these branches with no test: a channel the cache lost ends
its sender lookups for good, a rate-limited fetch_senders or initial_load
makes no request and keeps its work pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Its only user was the cache-index.ts re-export that 12f9dcf deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…c worker

Only the deleted abstract worker, which never ran in production, made
messages without a TL tag, so extractAttachment no longer accepts them.
Comments in message-type.ts and raw-json-migrations.ts stop naming it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It only re-exported sync-worker-real, so everything imports that module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Its only outside importer went with sync-worker-core.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…AccountCacheDb

05f3a33 and e28beee missed these copies of the shared setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the participation rule in the new paths: the chats list output declaration gets the group_participation reasons and lastOwnMessageAt, live messages still note the chat's newest message, and wait/watch docs say a paused group shows nothing. New tests that write group messages take part in those groups.
Base automatically changed from feat/group-participation to main November 18, 2026 10:33
neoromantic and others added 3 commits November 18, 2026 14:38
Resolve the cleanup against main's 0.13-0.14 changes: reportConfigOrRateLimitError reports rate limits through main's reportRateLimit, chats and contacts lists keep their next commands on the shared paginate(), the chats cache keeps the unread state on its one list query, and handleReadInbox stays while handleBatchMessages goes.
#155 landed as 528f6ae, a squash of df2ad48, which this branch already holds, plus 6e2e551, picked above.
@neoromantic
neoromantic merged commit 70c6329 into main Nov 18, 2026
5 checks passed
@neoromantic
neoromantic deleted the refactor/remove-dead-code branch November 18, 2026 10:44
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. fetch.ts: the batch fetch is built
on main's shared fetchMessagesByIdRaw, with the peer check kept. README
and CHANGELOG: both sides' entries kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. README and CHANGELOG: both sides kept. main dropped MessagesHistory.getMany (neoromantic#174): the item is read with get. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. README and CHANGELOG: both sides kept. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. README and CHANGELOG: both sides kept. main dropped MessagesHistory.getMany (neoromantic#174): the item is read with get. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. README and CHANGELOG: both sides kept. main dropped MessagesHistory.getMany (neoromantic#174): the item is read with get. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. history.ts and two test files: imports of both sides. CHANGELOG: both sides kept. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. skill.ts: main's shared getErrorMessage, the manifest stays removed. CHANGELOG: both sides kept. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik added a commit to ertembiyik/telegram-sync-cli that referenced this pull request Nov 18, 2026
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. helpers.ts: the item reader takes main's raw string, with the transcript kept. sql.test.ts uses main's cache helper. CHANGELOG: both sides kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant