Context
Second-pass governance (#1084) is winding down: 10 of its slices are merged and the remaining ones are tracked as sub-issues there. This issue tracks the third pass: ~150 source files ≥350 lines (everything not already covered by #1084) audited against the same four criteria, with per-finding adversarial verification against current main. 32 findings survived verification; 18 were refuted — plausible-but-justified coupling was explicitly rejected (e.g. model-adapter.ts usage normalization, permission.ts shell classification, and app-shell.tsx mode management are all fine as-is).
The dominant pattern this round is different from #1084: 25 of 32 findings are silently-diverging parallel implementations (copy-paste that must be kept in sync by hand), not mixed responsibilities. Several copies have already drifted.
Headline evidence
bots/qq-bridge.ts, bots/discord-bridge.ts, and most of bots/dingtalk-bridge.ts copy the same WebSocket gateway lifecycle wholesale (opcodes, heartbeat/seq/session, connect/reconnect/backoff — the backoff constants are byte-identical). bots/simple-bridge.ts additionally carries dead Feishu/Discord paths superseded by the dedicated bridges and only actually runs Telegram.
- Five
apps/desktop/src/main/oauth/*-subscription-service.ts files copy one service shell (pending/logout/refresh/getAccessToken/failure handling); the codex and antigravity services duplicate the loopback callback server nearly verbatim. The missing base leaks downstream into subscription-ipc-main.ts (7 same-shape handlers per provider) and oauth-model-connections-main.ts.
- Two full 5-field cron parsers exist across packages:
core/plan-reminders.ts (parsePlanReminderCronExpression/cronExpressionMatches, ~L541–656) and runtime/automation-state.ts (expandCronField/normalizeCronExpression/computeNextCronFire/matchesCronField, ~L521–696) — and inside automation-state.ts the same field grammar is parsed twice with already-divergent edge handling.
- Security-relevant:
main/rive-cli.ts ships a private redaction implementation (redactRiveText/redactRiveValue, ~L160–178) parallel to @maka/core's authoritative redactSecrets, with narrower coverage (misses GitHub/Google/Slack token shapes) — a future hardening of the authoritative rules silently won't apply here.
Slices
Each High/medium checkbox is one independently reviewable, independently revertible PR unless noted; low-severity items are batched.
High
packages/runtime
packages/headless
packages/core
packages/storage
packages/ui + apps/desktop
Mechanical cleanup batches (low, one PR per area)
Invariants
Same as #1084: behavior- and visually-neutral; preserve public imports (re-export compatibility where a moved symbol is public); no reverse imports from new leaf files; co-migrate tests; flat PRs off main; proportional verification (typecheck/build + targeted tests for pure moves). Per #1403, extraction PRs should pin their result with typed interface assertions and behavior tests, not new source-regex contracts.
Parallelization
All slices touch disjoint files except the compaction-helper batch (coordinate with #1374) and the OAuth lane (one owner, 2–3 ordered PRs). Before starting a slice, post a short claim comment here to avoid conflicts.
Out of scope
References
Context
Second-pass governance (#1084) is winding down: 10 of its slices are merged and the remaining ones are tracked as sub-issues there. This issue tracks the third pass: ~150 source files ≥350 lines (everything not already covered by #1084) audited against the same four criteria, with per-finding adversarial verification against current
main. 32 findings survived verification; 18 were refuted — plausible-but-justified coupling was explicitly rejected (e.g.model-adapter.tsusage normalization,permission.tsshell classification, andapp-shell.tsxmode management are all fine as-is).The dominant pattern this round is different from #1084: 25 of 32 findings are silently-diverging parallel implementations (copy-paste that must be kept in sync by hand), not mixed responsibilities. Several copies have already drifted.
Headline evidence
bots/qq-bridge.ts,bots/discord-bridge.ts, and most ofbots/dingtalk-bridge.tscopy the same WebSocket gateway lifecycle wholesale (opcodes, heartbeat/seq/session, connect/reconnect/backoff — the backoff constants are byte-identical).bots/simple-bridge.tsadditionally carries dead Feishu/Discord paths superseded by the dedicated bridges and only actually runs Telegram.apps/desktop/src/main/oauth/*-subscription-service.tsfiles copy one service shell (pending/logout/refresh/getAccessToken/failure handling); the codex and antigravity services duplicate the loopback callback server nearly verbatim. The missing base leaks downstream intosubscription-ipc-main.ts(7 same-shape handlers per provider) andoauth-model-connections-main.ts.core/plan-reminders.ts(parsePlanReminderCronExpression/cronExpressionMatches, ~L541–656) andruntime/automation-state.ts(expandCronField/normalizeCronExpression/computeNextCronFire/matchesCronField, ~L521–696) — and insideautomation-state.tsthe same field grammar is parsed twice with already-divergent edge handling.main/rive-cli.tsships a private redaction implementation (redactRiveText/redactRiveValue, ~L160–178) parallel to@maka/core's authoritativeredactSecrets, with narrower coverage (misses GitHub/Google/Slack token shapes) — a future hardening of the authoritative rules silently won't apply here.Slices
Each High/medium checkbox is one independently reviewable, independently revertible PR unless noted; low-severity items are batched.
High
GatewayBridgeBase(opcodes, heartbeat/seq/session, connect/reconnect/backoff, close policy); qq/discord/dingtalk override only auth header, identify/resume payload, dispatch event names, send route; includes the sharedreconnectBackoffMs. Follow-up in the same lane: deletesimple-bridge.ts's dead Feishu/Discord branches and rename ittelegram-bridgeto match its real responsibility.SubscriptionOAuthServiceBase(or composable helpers) for the five services; extractstartLoopbackAuthCallbackServershared by codex/antigravity; then collapse the per-provider handler blocks insubscription-ipc-main.tsand the repeated needs_reauth blocks inoauth-model-connections-main.ts. 2–3 PRs, one owner.@maka/core;plan-reminders.tsandruntime/automation-state.tsconsume it; inside it, one field-grammar parser (todayexpandCronFieldvalidates strictly whilematchesCronFieldsilently skips invalid parts).main/rive-cli.tsredaction (security) — deleteredactRiveText/redactRiveValue, use@maka/coreredactSecrets(thin deep-recursive wrapper if needed).packages/runtime
history-compact-checkpoint.ts(~L516–546) andsemantic-compact.ts(~L1515–1578) re-inline primitives their own domain authoritycontext-budget-helpers.tsalready exports (estimateTokens/sha256/nonEmpty/escapeAttribute/uniqueSorted/finiteRatio); theescapeAttributecopy has already diverged (extra>escaping). Also collapse thestableStringifycopies (active-full-compact-facts.ts:558et al.) and the ~9 three-linesha256wrappers. Coordinate with refactor: reuse shared result and hashing helpers #1374 (hash reuse, approved). Caution: the localuniqueSortedvariant keeps empty strings — a contract difference to preserve or consciously resolve.isLikelySandboxDenialis verbatim inshell-tools.ts:400andbuiltin-tools.ts:1085, with a third variant inshell-run-tool-result.ts:169; extract one primitive over{stdout, stderr, sandboxed}.packages/headless
canonicalJson— five copies (one already diverged onundefinedhandling); single serializer next tobuildRunManifestFingerprint.harbor-cli.tsconnection reading — stop re-parsing workspacellm-connections.json(schema + per-platform path, ~L770–843); route through the shared workspace-path + connection reader /ConnectionStoreauthority.packages/core
foreign-session.tssanitizeForeignText(~L94–106) copiessession-name.ts's pipeline and has drifted; extractsanitizeUnicodeText(text, {maxCodePoints}).TokenUsageFields— the same token-usage field bundle is declared in three places with no shared base and has already drifted (runtime-event.ts:204–229et al.); extract one shared interface and makeisTokenUsageFieldsfollow it.packages/storage
readJsonlLines(path, {strict, tolerateTornTail, decode})(today 5+ hand-rolled readers with silently divergent torn-tail policies); sharedwriteFileAtomic(6+ temp+rename copies;credential-store's hardened variant stays independent by design); collapsesession-store.ts's near-verbatim double message-parse loop (~L787–902); low: reuseisSafeSessionId/assertSafeSessionIdfromsession-storein the other stores.packages/ui + apps/desktop
chat-turn.tsxclipboard feedback —TurnFooterActionshand-rolls the copy-feedback state machine its same-file sibling already gets fromuseClipboardCopyFeedback; converge.bot-incoming-main.ts— the new-bot-conversation sequence (limit check + rate-limit + getReadyConnection + createSession + set + emit + ensureSend) is copied twice (~L192–219, 266–300); callcreateBotConversationSessionfrom both.capability-snapshot.ts— the macOS TCC/OS permission-probing subsystem (~L347–459) is an independently evolving concern; split intopermission-snapshot.ts.Mechanical cleanup batches (low, one PR per area)
sleepcopies in bots.DeepResearchProgressPanelfromchat-view.tsx(and re-point the desktop source-regex test at behavior); hoist the motion-collapse predicate thatreadStreamSnap/useStreamSnapduplicate fromscroll-motion-policy.ts; mergesmooth-stream.ts'sresolveLiveBacklogCps/resolveCompletionCps; collapse CLIruntime-bootstrap.ts's 4 verbatim subscription-cloak modelFetch blocks into one helper; movemain-window.ts's embedded smoke-diagnostic (~L502–585) to its own file; dedupeoffice-document-tool.ts's path-validation preamble.Invariants
Same as #1084: behavior- and visually-neutral; preserve public imports (re-export compatibility where a moved symbol is public); no reverse imports from new leaf files; co-migrate tests; flat PRs off
main; proportional verification (typecheck/build + targeted tests for pure moves). Per #1403, extraction PRs should pin their result with typed interface assertions and behavior tests, not new source-regex contracts.Parallelization
All slices touch disjoint files except the compaction-helper batch (coordinate with #1374) and the OAuth lane (one owner, 2–3 ordered PRs). Before starting a slice, post a short claim comment here to avoid conflicts.
Out of scope
session-manager.tschild-orchestration dedup (feat(runtime): migrate agent tools to child sessions #1385 follow-up: four copied child-run drive loops, three copied resume-lineage validations) is confirmed but will be filed separately once refactor(runtime): extract session branching into session-branch.ts #1253 lands, to avoid churn in the same file.References