A fork of Telegram-iOS, shipped as Nicegram. We periodically merge the latest upstream Telegram into this repo, so every change here must be written to survive that merge with as few conflicts as possible.
Most standalone feature work does not belong here — it lives in the sibling
Swift package nicegram-assistant-ios. This repo is for code that must
physically live inside the Telegram app.
The assistant is vendored as a git submodule at
packages/nicegram-assistant-ios, so its sources sit in this working
tree and local edits build immediately. Commits there belong to the assistant
repo and land through its own PR — or, from extract-to-develop, a direct
fast-forward push — before this repo bumps the pointer. See
"Cross-repo feature workflow" below.
Two independent directions — don't conflate them:
- Calling assistant features (host → assistant): the Telegram shell invokes
assistant code directly (import the assistant module and call it / its
Presenter). Host-side dependencies are wired into the assistant once at launch viaNGEntryPoint.onAppLaunch(...). TelegramBridge(assistant → host): the abstraction the assistant uses to reach Telegram/host capabilities. nicegram-ios provides the bridge implementations (typically inNGUtils), injected throughNGEntryPoint. It is dependency-injection into the assistant — NOT how the host calls assistant features.
- Full features inside Telegram — code that genuinely needs Telegram
internals (chat UI,
Postbox,AccountContext, navigation, ...). - Call-sites into
nicegram-assistant-ios— thin hooks that invoke assistant features from the Telegram shell.
Whatever the change, choose the highest applicable option:
- Keep it out of Telegram code. Put it in
nicegram-assistant-ios, or in a brand-new separate file here (a new file never conflicts on merge). Bridge Telegram dependencies throughTelegramBridge. That includes Telegram code that already calls an assistant API: when every caller should get the new behaviour, change what the API returns and leave the host line alone. WhiteBridge's ads gate lives inGetWhitebridgeConfigUseCase, not beside its three host callers. - Add new code to an existing Telegram file, wrapped in Nicegram markers.
- Modify an existing Telegram line — last resort, with a marker above it.
Never leave an unmarked edit in Telegram code — the marker is what lets us
re-apply and audit our changes at the next merge. Exact marker syntax and the
Signal bridges live in the telegram-interop rule.
Nicegram/— our in-repoNG*modules (mainlyNGUtils). See thenicegram-modulesrule.submodules/**/Nicegram/— whole new Nicegram files inside a Telegram submodule.- Marked blocks/lines across
submodules/**— inline integration.
Nicegram/NGWebDomains/web_domains.bzl is the only place the Nicegram web
domains are written, in two families. NICEGRAM_PRIMARY_DOMAIN is what the app
links to; NICEGRAM_ALL_DOMAINS is every Nicegram web domain it claims, with
auxiliary entries written as prefixed forms of the primary so the domain itself
is stated once. Nicegram Business is the second family:
NICEGRAM_BUSINESS_PRIMARY_DOMAIN, the dashboard and its API, which the app
does not claim, and NICEGRAM_BUSINESS_UNIVERSAL_LINK_DOMAIN, the
universal-link host, which it does — both deliberately outside
NICEGRAM_ALL_DOMAINS, because WebDomains.contains would count their hosts as
the Nicegram domain.
Everything derives from it. Telegram/BUILD generates one applinks: line per
claimed domain into the associated-domains entitlement, and a write_file rule
generates the Swift constants behind //Nicegram/NGWebDomains — a module kept
dependency-free because submodules/UrlWhitelist, a leaf module with no deps at
all, needs the list.
The assistant never learns the domain at compile time: AppDelegate passes it
through Env.webDomains, whose business carries both Business hosts, and to the
wallet as appUniversalLinkDomain; inside the assistant, WebDomains owns link
recognition while NicegramLinks — read as NGCore.links — owns every
hardcoded URL.
Two things to keep true. Never write any of these domains anywhere else,
including in a test: assertions build their expectations from a fake domain. And
an upstream merge that rewrites Telegram/BUILD's associated_domains_fragment
must keep the {nicegram_applinks} interpolation rather than reverting to
literal <string>applinks:…</string> entries.
New Nicegram strings go in the assistant package's en.lproj files. Their
translations live in the SSOT, the shared repository
nicegram/nicegram-localization, which iOS and Android both translate through,
so one English sentence gets one translation on both. The
localization@nicegram-localization plugin, enabled in .claude/settings.json,
carries the flow:
translate-uploadputs new strings into the SSOT and translates them there;sync-translationswrites the SSOT's translations back into an app, for the apps the installed version supports.
If the session lists no localization: skills, the plugin is not installed on
this machine: the entry in .claude/settings.json turns it on but downloads
nothing. Ask the human to run these once in a terminal and start a new session,
rather than working around it:
claude plugin marketplace add nicegram/nicegram-localization
claude plugin install localization@nicegram-localization --scope userRead packages/nicegram-assistant-ios/.claude/rules/localization.md before
running either skill. It does not attach from here, and it says what to do
when sync refuses or rewrites translations users already see.
Run the plugin from packages/nicegram-assistant-ios, never from this
repository's root.
- It recognises the iOS app by
Package.swiftplusSources/NGCore, which only the package root has. From here it stops withno Nicegram app layout matches. - Its skills say "run from the app repository root", which in a session opened here reads as the wrong directory.
- Use the subshell form
(cd packages/nicegram-assistant-ios && <command>), so thecddoes not carry into later calls.
The host's legacy Telegram/Telegram-iOS/*/NiceLocalizable.strings is outside
the plugin, which never scans it. A change that edits an existing string there
updates that string's translation by hand, in the same change, in every .lproj
that holds the file. Nothing else will.
Bazel (BUILD files; some legacy BUCK remain), not hand-managed SPM/Xcode.
When you add a source file or dependency, update that module's build target. Do
not hand-edit generated files.
The build layer is ci/fastlane. Do not invoke build-system/Make/Make.py
directly — the fastlane lanes resolve the configuration, cache directory, and
codesigning repository for you, and a hand-written Make.py command will use the
wrong ones.
ci/generate-project.sh # generate the Xcode project and open it (a human's step)
ci/generate-project.sh --no-open # ...generate only (scripts and agents)
ci/verify-build.sh # compile check (arm64 device by default; --sim for the simulator)
(cd ci && ./build-to-testflight.sh "1.2.3 (456)") # QA / TestFlight build
Run them from the repository root as written. The first three move to ci/
themselves. build-to-testflight.sh sources ./_env.sh, so it needs ci/ as
its working directory, and the subshell keeps that cd from outliving the
call: in Claude Code a cd inside the session's folder carries into every
later Bash call (.claude/reference/entering-a-worktree.md, step 2). A cold
build runs past the Bash tool's 10-minute foreground limit, so an agent runs
the gate in the background.
verify-build.sh and generate-project.sh both run ci/bootstrap-submodules.sh
first and abort if it fails. This matters because a freshly created worktree
starts with every submodule uninitialized — neither the "create worktree"
checkbox nor the harness's EnterWorktree tool runs git submodule update --init, and no single harness hook covers every path that creates a
worktree — so without this, the first build fails ~30s into Bazel with a No MODULE.bazel, REPO.bazel, or WORKSPACE file found in .../rules_xcodeproj
error that names neither "submodule" nor "worktree". The script is idempotent
and near-instant when nothing is missing (one git submodule status call);
when something is missing it prefers cloning from the main clone's own
gitdirs over the network (see "Starting a feature" below for why), and if it
still can't fully initialize everything — most likely
packages/nicegram-assistant-ios, which needs Bitbucket SSH access — it
prints exactly which paths failed and exits non-zero rather than letting the
build proceed into the confusing Bazel error above. The same holds for a
submodule it initialized that does not end at its pinned commit (the script's
header says how it fetches a pin the main clone's gitdir lacks, and what it
does with a checkout that still misses it). build-to-testflight.sh
skips this step: it doesn't build locally, it just pushes the branch and
triggers the Bitbucket pipeline, which does its own recursive submodule
checkout.
All three wrappers then source ci/_env.sh, which sources
ci/fastlane-env.sh — untracked because it holds credentials, obtain it
from the shared env store, like the demo app's Env.swift. From a worktree,
where that untracked file does not exist, it falls back to the main clone's
copy automatically, so the same three commands work everywhere. (That
fallback depends on every wrapper starting with #!/bin/bash: under
/bin/sh — on macOS that's bash itself running in POSIX mode, reproduced
directly — a failed . on a missing file aborts the shell before the ||
alternative runs, so the fallback would silently never fire.) ci/_env.sh
then re-derives SOURCE_PATH itself and re-exports it, derived from its
own file location rather than the caller's working directory
(SOURCE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"), so it
resolves correctly however _env.sh is sourced, not only when the
caller happens to be sitting in ci/. This overrides whatever the
untracked fastlane-env.sh happened to set. That's deliberate: leaving the
guarantee "a build from a worktree builds that worktree" resting only on
the untracked file would make it depend on every teammate's local,
unversioned copy deriving the path the same way — one copy that
hardcodes a stale absolute path and a worktree build silently builds the
main clone instead, with no error. The Fastfile has its own separate
fallback, SOURCE_PATH = ENV["SOURCE_PATH"] || File.expand_path("../..", __dir__) — a second, independent safety net for a lane invoked directly
without going through any wrapper, not the mechanism the guarantee above
actually rests on (__dir__ evaluates to "." in fastlane's eval; the
fallback only lands on the repo root because fastlane wraps that eval in
Dir.chdir(FastlaneFolder.path), i.e. ci/fastlane). CI sets
SOURCE_PATH directly as job env before invoking a lane, so
ENV["SOURCE_PATH"] wins there without ever touching _env.sh.
The target environment comes from ng-env.txt (test or prod), which
resolve_telegram_configuration reads to pick between
TELEGRAM_CONFIGURATION_TEST and TELEGRAM_CONFIGURATION_PROD.
Add --continueOnError to a Make.py call only if you are debugging the build
system itself; for normal work, use the wrappers.
ci/verify-build.sh is the supported way to answer "does this still compile" —
for any change, not just an upstream merge. It passes bazel's --keep_going so
one pass reports every broken module, and runs whether or not Xcode is open —
see "Building alongside Xcode" below. It builds through
rules_xcodeproj's command-line API, which is what makes it share cache with
an Xcode build, and there is no second build path. Read the script's own header
before changing it: it records what each step exists to prevent, including one
bazel behaviour that silently turns a naive version of this gate permanently
green.
Before any bazel work the gate also checks the selected Xcode for the two
components a fresh install can lack and a build only reaches minutes in — an
iOS Simulator runtime for its iphonesimulator SDK (actool needs one even for a
device build) and the Metal Toolchain — and fails in seconds with the fix:
xcodebuild -downloadPlatform iOS or xcodebuild -downloadComponent MetalToolchain, run against the same Xcode. Both were missing from a new
Xcode 26.6 during the 13.0 merge; the check is ci/lib/xcode-preflight.sh, and
ci/generate-project.sh runs it too.
The destination is decided in exactly one place, ci/verify-build.sh, in
this order: --device/--sim on the command line, then
$NG_BUILD_DESTINATION (device|sim), then device. Everything downstream —
the signing pre-flight, the target-id prefix, the report label — derives from
that single variable, and the tg-merge and sync-from-develop skills pass no
flag at all, so they inherit whatever it resolves to. Set
NG_BUILD_DESTINATION in the untracked ci/fastlane-env.sh if you build
the simulator in Xcode: the choice is genuinely per-machine, because the disk
cache is local and only ever needs to match what you build here. ng-env.txt
is the wrong home for it — that file is tracked, so it is project-wide. A value
that is not exactly device or sim is refused with exit 2 rather than quietly
treated as one of them.
Bazel's cache has four layers here, each with a different scope. The first two
live under Bazel's output user root, which is
~/Library/Caches/bazel/_bazel_$USER since the 13.0 merge took Bazel 9.2.0;
8.x used /private/var/tmp/_bazel_$USER, and a checkout still on 8.x builds
there.
- Repository cache,
<user root>/cache— fetched external dependencies. Global to its user root: shared by every workspace and every worktree on the machine that builds under that root. - The output base,
<user root>/<md5-of-workspace-path>/— execroot, thebazel-outtree, the action cache, the analysis graph. Bazel names this directory by hashing the workspace's filesystem path, so it is per workspace path — one per worktree; a worktree shares none of another worktree's output base. - The disk cache,
~/work/nicegram-bazel-cache(BAZEL_LOCAL_CACHE, reaching bazel throughMake.py's command line and through the generatedxcodeproj.bazelrc). Content-addressed, keyed by action key, and the only layer that bridges worktrees. Bounded — see below. - The rules_xcodeproj nested output base, at
<output_base>/rules_xcodeproj.noindex/build_output_base— a second, separate bazel server thatrules_xcodeprojruns inside the outer output base. Both an Xcode build andci/verify-build.shbuild here; the outer base only holds the smallxcodeprojrunner target (measured: 8 packages, 2.6s from a cold server, and abazel cleanthat removed 34G from the outer base cost the gate nothing). Anything that builds plain target labels — thecompile_checklane,Make.py build— lands in the outer base instead, which is exactly why it shares nothing.
What actually shares with what, as measured:
-
CLI ↔ CLI, across worktrees: excellent. A cold worktree with no output base at all completed a full simulator app compile in 179s, with 5,857 of 7,490 actions (78%) served from the disk cache. A fresh worktree is not a full rebuild.
-
Xcode ↔ a plain label build: nothing, and no flag can fix it. A device gate run immediately after a successful Xcode device build of the same code got zero disk-cache hits and took 1,114s. Flag alignment was carried all the way to completion — the two flows' swiftc command lines for
submodules/Displaybecame byte-identical — and it bought nothing: output paths are part of every action key, and the two configuration directories differ (ST-a7beea3c269efor a label build vs.ST-9cbb67e27a8ffor Xcode), with zero overlap across all seven min-version configurations, unchanged by the alignment. The-ST-suffix is derived from the Starlark transition path, not from flags. (Their exec configurations do overlap, which is why a post-alignment run still showed ~145 disk-cache hits: host-tool actions, not app code.) The full trail is inci/nicegram.bazelrc'sng_devcomment. -
Xcode ↔
ci/verify-build.sh: shared, since 2026-08-28. The gate runs bazel through the generator label with rules_xcodeproj's command-line API, so it lands on the same transition path, the same output base and the same action keys. Measured on the same worktree and the same commit: the device gate went from 1,114s with zero cache hits to 6s with every action a cache hit, and a run of the whole project through the API took 8,750 action-cache hits straight out of Xcode's own base.ci/verify-build.sh's header carries the full measurement set and the three traps involved. -
And it is bidirectional, measured as a controlled pair on 2026-08-28 so that "it was all built already" cannot explain it. Each round changed one source file, so exactly one Swift module needed compiling, and the round's first builder is what proves the work was real:
round compiled the change then built actions the follower executed 1 the gate — 1 worker action Xcode 0 (157 processes, every one a cache hit) 2 Xcode — 1 worker action the gate 0 (1 process, 7,648 action-cache hits) Xcode's follow-up build reported
** BUILD SUCCEEDED **in 24.0s with a 3.96s bazel phase and nolocalorworkerterm in its process summary at all. (Its log does printINFO: From Compiling Swift module …:lines — 27 of them — but those are bazel replaying a cached action's stderr, not executions, and none of them names the module that changed.) -
A release build shares nothing with a debug one, because
-c optwith whole-module optimisation and-Osizeproduces different object code than-c dbg. -
Simulator vs. device is a genuine full rebuild — different CPU (
sim_arm64vs.arm64). "Any iOS Device (arm64)" and a real device are the same configuration, which is why those two do share.
How the API route works, and what it needs. rules_xcodeproj's
docs/usage.md states the problem in the same terms this audit measured it: the
xcodeproj rule applies a configuration transition, so "building targets by
specifying their labels will build potentially different versions of those
targets, and minimally versions that have different cache keys." The answer is
to run bazel through the generator so it inherits the same output base,
configs and transition:
./build-input/bazel-9.2.0-darwin-arm64 run //Telegram:Telegram_xcodeproj -- \
--generator_output_groups=<group> 'build --keep_going'
Two corrections to what an earlier pass of this document claimed here, both measured:
- It does not require a generated project. The runner script creates the
generator package itself at run time; verified by moving
Telegram/Telegram.xcodeprojaway and running the API anyway (exit 0, 1.6s). It does requirexcodeproj.bazelrcandbuild-input/configuration-repository, both written byMake.py—ci/verify-build.shensures each of them. --generator_output_groups=all_targets, the form the docs lead with, is the wrong scope for a compile gate.Telegram/BUILDdeclares Xcode configurations Debug and Release and target environments device and simulator, soall_targetsis four full app builds plus the UI test suite: measured at 26,880 actions and 1,900s. The gate asks for one configuration's app product through the per-targetbp <target-id>group instead — 4,528 actions — which is the same group rules_xcodeproj's own Xcode scripts drive.
--experimental_output_paths=strip (bazel's generic path-mapping feature) is
not an alternative: no vendored rule declares the supports-path-mapping
execution requirement, so Swift compiles ignore it.
ci/verify-build.sh defaults to the device configuration, because an
Xcode build on a real device now shares its cache: after one, the gate is
nearly free, while a simulator default would compile a whole second
configuration for every change. Because a device build signs the app and its
six extensions, that path also runs a signing pre-flight that hashes each
certificate the resolved provisioning profiles require and compares it against
the installed identities, catching a codesigning failure before a long build
instead of after. tg-merge and sync-from-develop use that same device
default deliberately: they run on this machine, so the device configuration is
the one whose disk-cache entries the human's own Xcode builds keep populating,
and a simulator gate would share with nothing anyone here builds. The price is
that an unattended run depends on the team development certificate; the
pre-flight is what makes that acceptable, since it fails in seconds and names
the fix instead of failing at the end of a long build.
What "device needs a signature" actually means, since simulator-vs-device
otherwise looks like nothing but a different CPU. For compilation that is all it
is. The difference is the last step: a device build bundles and codesigns the
app and its six extensions, because iOS will not install unsigned code, while a
simulator build is fake-signed and needs no certificate and no profile at all.
This fork sets telegram_use_xcode_managed_codesigning = False, so bazel signs
with the match profiles from the codesigning repository, and each of those
profiles names one specific certificate — which is why "some Apple
Development identity is installed" proves nothing (verified on 2026-08-27: two
personal-team identities were installed and the build still failed at
IntentsExtension). It is the same requirement an Xcode build for "Any iOS
Device (arm64)" already satisfies, so if that works, the gate works. Install it
with ci/nicegram-match.sh development; the certificate in use here
expires 2027-04-01.
The operational trap, and what it now costs. xcodeproj.bazelrc is written
by get_project_generation_arguments() at generation time, so changing
ng_dev (or anything else in Make.py's common_debug_args, or
ProjectGeneration.py's own two --features lines) without regenerating leaves
that file describing the previous configuration. Both flows read the same file,
so they stay consistent with each other and keep sharing; what goes stale is
the match between the configuration they build and the one Make.py would
produce today. Regenerate (ci/generate-project.sh; an agent adds
--no-open) after any such change.
The gate now tells you when it stopped sharing. A build that reuses nothing
still succeeds — the only symptom is that it took twenty minutes instead of
thirty seconds, which is easy to blame on something else. So after the build the
gate looks for bazel's own Build options ... have changed, discarding analysis cache line and, if it finds one, prints a loud warning naming the options.
Getting that check right needed two scoping rules, both learned by getting them
wrong: it must ignore the outer base (which legitimately reconfigures twice
on every run, because resolve_config's aquery and the plain bazel run
alternate two option sets there), and it must look at both inner
invocations, because the reconfiguration surfaces in whichever runs first — the
target-ids step — and the build a second later sees matching options and says
nothing. Verified to stay silent on a warm repeat, on alternating
--device/--sim, after a real Xcode build, after an Xcode Index Build, and on
a cold fresh worktree; verified to fire on a deliberately diverged
configuration.
And the sharp edge underneath it: if xcodeproj.bazelrc is missing, bazel
says so plainly — Build options --//Telegram:disableStripping, --@@rules_swift+//swift:copt, --define, and 1 more have changed, discarding analysis cache — and rebuilds 124,829 targets in a different configuration,
while the target ids, and therefore the bp <id> output-group name, come out
byte-identical. The -ST- hash tracks the transition path, not the flags. So
the id is not a witness that the configuration matches: nothing downstream can
detect the missing file, which is why ci/verify-build.sh guarantees it exists
before it starts.
Reclaiming disk: ci/clean-caches.sh reports every Bazel output base —
under both user roots, so the bases 8.x left behind stay reclaimable — and
every Xcode DerivedData directory on the machine and, with --yes, deletes the
ones whose checkout no longer exists. Deleting a worktree removes neither on its
own — and deleting a worktree does not, by itself, make its caches
reclaimable. Two things keep the recorded path alive, both measured
2026-08-28: its bazel servers idle for three hours (two per worktree, the
outer one and rules_xcodeproj's nested one) and an idle server recreates its
--workspace_directory; and git worktree remove --force can leave
gitignored build output behind (observed: 16 KB of
Telegram/Telegram.xcodeproj/project.xcworkspace), which is enough on its own.
Either one makes the report say live, i.e. "Nothing to reclaim" — which reads
like a clean machine. The script's own header carries the two commands that fix
it, and the merge-to-develop skill runs them. On 2026-08-27, five worktrees' output bases measured 12G, 18G, 24G, 41G,
and 60G, and a DerivedData directory reached 18G — but those are dated
observations, not a ceiling: this worktree's own output base later grew to
70G the same day. An output base has no upper bound; it grows as more
configurations get built inside it, and nothing removes it until the worktree
is deleted and ci/clean-caches.sh --yes is run. On this machine, that script
reclaimed 80 GB from six orphaned stores, and on 2026-08-28 another 71 GiB of
df free space from three (a run the report predicted at 80.8 GiB — du
counts what the files claim, APFS frees what is no longer shared, so expect the
figure to be optimistic). That isn't the whole story, though:
a single day of this audit's builds consumed about 100 GB, because every
configuration built (sim debug, device debug, and the Xcode nested base's
copies of both) keeps its own bazel-out tree. All of these numbers are
dated observations, not maximums, and a reader needs them together — pruning
orphans is necessary but building still costs real, growing disk.
The disk cache is bounded, not unbounded: ci/nicegram.bazelrc sets
--experimental_disk_cache_gc_max_size=100G and
--experimental_disk_cache_gc_max_age=45d. Collection runs in the bazel
server, but only once it has sat idle for 5 minutes
(--experimental_disk_cache_gc_idle_delay's default), so it happens between
builds, never during one — a machine that never leaves a server idle will not
collect. ci/clean-caches.sh's report prints the disk cache's current size so
that's at least visible.
Where bazel flags come from, in the order they're read. Exactly one of the
five is ours (Make.py is upstream's structure with a few marked fork edits —
build cache, remote downloader, XcodeParse, headless generation — not ours):
.bazelrc— upstream's own file.ci/nicegram.bazelrc— ours, reached from.bazelrcthrough onetry-importat the end. The disk-cache GC bounds andng_dev.Make.py's Python argument lists (common_debug_args,common_release_args,configuration_args) — upstream's structure, with one fork edit: the two Swiftcoptvalues incommon_debug_argslost their surrounding quotes and gained--config=ng_dev, both for action-key alignment (seeci/nicegram.bazelrc).- The generated
xcodeproj.bazelrc— written byProjectGeneration.pyfromget_project_generation_arguments()at project-generation time (see the operational trap above). - rules_xcodeproj's own rc, from the runner's runfiles — it is what
try-imports the generatedxcodeproj.bazelrcabove.
There used to be a sixth, user.bazelrc, generated per machine by
ci/write-user-bazelrc.sh to give a hand-run bazel the disk cache. It was
removed on 2026-08-28: sourcekit-bsp is not configured on this machine (no
buildServer.json or .bsp anywhere, and upstream dropped its
sourcekit-bazel-bsp submodule in 13.0), tgcalls_cli has never been built, and
the disk cache reaches every flow that exists through Make.py's command line
and the generated xcodeproj.bazelrc. If you do start running bazel by hand
and want the cache, pass --disk_cache=$HOME/work/nicegram-bazel-cache
yourself, or bring the script back from git history.
Upstream dead ends we deliberately leave alone — each costs nothing at runtime, and removing it would only create merge-conflict surface for no benefit:
.bazelrc'sbuild:dbg --features=swift.emit_swiftsourceinfonever applies, because nothing in this fork passes--config=dbg(-c dbgis--compilation_mode, a different flag).build:ng_devinci/nicegram.bazelrccarries that same intent for the dev flows instead.Make.py'sadditional_args/add_additional_args— stored on the command-line-builder object, never read by anyinvoke_*method.Make.py's--profileSwiftflag expands to--config=swift_profile, which no bazelrc in this repo defines, so the switch fails loudly if used. We don't define that config ourselves because upstream's intended semantics for it are unknown.
Housekeeping, not caching: a stale nicegram-codesigning keychain may
still exist on machines that ran the pre-audit lanes; it's unreferenced now and
safe to delete by hand. Every .sh file under ci/ now carries
#!/bin/bash — on the sourced ones (_env.sh, lib/*.sh) purely as a dialect
marker for editors and shellcheck, since their 644 mode, not the absence
of a shebang, is what stops them being executed. And the three scripts a human
runs by hand — verify-build.sh, generate-project.sh, nicegram-match.sh —
cd to ci/ themselves, so each runs from the repository root as
ci/<script> and none depends on the caller's working directory.
These live under ci/ alongside the fastlane lanes but are plain bash, so
fastlane's own doc generation never lists them. They are documented here and
not in ci/fastlane/README.md: that file is regenerated from the lane list
every time any fastlane lane runs, so anything hand-written in it is silently
erased — as happened once already.
-
ci/clean-caches.sh [--yes] [--only <path>]— reports every Bazel output base (~/Library/Caches/bazel/_bazel_$USER/*for Bazel 9,/private/var/tmp/_bazel_$USER/*for 8.x) and Xcode DerivedData directory on the machine with its size and whether it is orphaned, and with--yesdeletes the orphans. With no arguments it only reports; nothing is deleted. Run it after deleting a worktree — that is the case it exists for, since removing a worktree leaves both its output base and its DerivedData behind. Note it classifies DerivedData by theWorkspacePathXcode records, which names the generated<worktree>/Telegram/Telegram.xcodeproj; a live worktree that has never runci/generate-project.shtherefore reads as orphaned. The consequence is mild (DerivedData is rebuildable) but check the table before passing--yes.--only <path>narrows deletion to orphans recorded at or under that path and reports the rest as kept; it is what letsmerge-to-developprune the worktree it just removed without asking. An unscoped--yesstays a human's call: "orphan" only means the path is absent now, and build-to-testflight's persistent.claude/worktrees/testflight-buildis absent between builds yet recreated at the same path, so its output base is meant to survive. -
Build logs are not kept. Both wrappers capture their bazel output to a scratch directory under
$TMPDIRand delete it on the way out (trap ... EXIT, plusINT/TERMso a Ctrl-C cleans up too). They capture at all only because the gate greps its own output — the target-ids path out of--show_result, the positive output-group assertion, the report, the divergence check — and every one of those reads happens inside the run. Nothing outside a run ever read those files:teeputs every line on stdout, so an interactive run has the whole thing in the terminal,tg-merge/fix-crashredirect the gate into their own scratch file and read that, and the other skills read the background call's output. An earlier pass wrote three timestamped files per run intoci/working_dir/logs/and kept them forever — one of the three was never read by anything at all. If you want a copy, redirect:ci/verify-build.sh > run.log 2>&1. -
ci/evict-swiftpm-build.shandci/lib/swiftpm-build.sh— movepackages/nicegram-assistant-ios/.buildout of the package, permanently, to../.swiftpm-scratch/<checkout>.verify-build.shandgenerate-project.shdo this themselves before touching bazel; the standalone script is for the Xcode case, which nothing can hook — Xcode runs bazel itself through the generated project. Without it, any bazel run fails during analysis withERROR: Cycle detected but could not be properly displayed due to an internal problem. Please file an issue.That is not a bazel bug:rules_swift_package_managerdigests the whole package tree,.buildincluded, and SwiftPM's checkouts symlink to their own ancestors (the one bazel names isGRDB.swift/Tests/CustomSQLite/GRDB -> ../..). It is hard to read because the message blames bazel, the cycle report names.buildbut never the symlink, and it only appears after someone runs SwiftPM in that package — so a clean checkout is fine and it looks intermittent.The resting state must be "outside". SwiftPM re-creates
.buildevery time it runs there (swift test, the Demo app,Scripts/generate_resources.sh), so after any of those, evict again before building. Four things that do not work, all measured:.bazelignoregoverns package loading, not a repository rule's digest; renaming.buildin place just makes bazel walk the new name;--scratch-pathrelocates checkouts and products but binary targets are still read from<package>/.build/artifacts, so resource generation dies witherror: XCFramework Info.plist not found; and moving it aside for a run and restoring it afterwards is worse than nothing — it cannot help Xcode, and putting the directory back re-arms the trap for the next Xcode build. That last one was shipped here and had to be replaced;ci/tests/test-swiftpm-build.shnow fails if anyone reintroduces it. -
ci/tests/run-all.sh— runs everyci/tests/test-*.shand exits non-zero if any fails. No framework and nothing to install: plain bash asserting against fixture directories and fixture log files. -
make_py_prefix(a Fastfile helper, not a lane) — the one place that assembles thepython3 build-system/Make/Make.pyinvocation prefix (--bazel,--bazelUserRoot,--cacheDir,--cacheHost).build_bazel,generate_projectandcompile_checkall call it, so the three lanes cannot drift apart on which bazel binary or cache directory they point at — which they had already done before it existed. -
The
resolve_configlane resolvesbuild-input/configuration-repository— the local bazel module holdingvariables.bzland the provisioning profiles — without building anything and without generating a project, via the oneMake.pysubcommand (query) that resolves the configuration and then does something cheap.ci/verify-build.shruns it first (~11s) because its API path no longer goes throughMake.py build, and without it a flippedng-env.txtwould keep building the previous environment while looking perfectly healthy. -
The
compile_checklane has no caller in this repo and is kept for hand invocation only, likeci/nicegram-match.sh— do not delete it because a grep says it is dead.ci/verify-build.shstopped using it on 2026-08-28: it builds plain target labels, so it cannot share cache with Xcode by construction. Reach for it only to answer "is the API path itself broken, or is my code broken?", and expect a full rebuild of whatever configuration it builds, since nothing else populates it:(cd ci && fastlane compile_check configuration:debug_arm64). There is deliberately no--make-pyflag on the gate any more: a blessed one-flag fallback invites reaching for it instead of fixing the shared cache, which is the thing actually worth keeping working.
ci/verify-build.sh runs whether or not Xcode is open. It used to refuse while
any Xcode was running (pgrep -x Xcode). That was removed on 2026-10-01: the
check was machine-wide, while the contention it was meant to prevent happens
only within one worktree.
Bazel names its output base after the workspace path, so every worktree has its own outer and nested bazel servers:
-
Xcode on another checkout shares no server and no command lock with the gate. They share only the content-addressed disk cache and the repository cache, and bazel locks both itself.
-
Xcode on this checkout does share the nested server, and so does its background Index Build (
separate_index_build_output_baseis off). Bazel then queues the gate:Another command (pid=N) is running. Waiting for it to complete on the server (server_pid=M)...It runs the gate when Xcode's command finishes. That is safe, as measured on a throwaway workspace: the second client waited 25s for the first and exited 0, and nothing was corrupted. Xcode re-runs an Index Build on its own after edits while a project is open, so on that checkout the wait has no fixed bound. The waiting line, which names the pid of the bazel client Xcode started, is the explanation, not a hang.
Concurrency itself is ordinary contention, measured back when the two flows
used separate output bases — today's cross-checkout case. An Xcode simulator
build and a CLI device build were run concurrently, both doing real Swift
compilation, monitored every 20s for 12 minutes. Both succeeded: the CLI
build exited 0 in 845.1s (902 processes); Xcode reported
** BUILD SUCCEEDED ** in 943.0s (2,935 processes). Peak swap across the run
was 5040.56 MB, and it fell to 4999.69 MB by the end — no thrashing. Only 5
of the 36 samples showed any compiler momentarily at 0% CPU, and none of those
was a sustained stall. Concurrency cost about 1.4x wall clock (845s concurrent
vs. 606s for the same CLI build run alone).
A shared global module cache (--features=swift.use_global_module_cache) was
once said to make concurrent builds wedge. That is provably wrong:
rules_swift passes -module-cache-path <bin_dir>/_swift_module_cache, which is
execroot-relative, so separate output bases never share it. Older plans still
state it as fact. Do not repeat it. If a wedge does turn up, treat the cause as
open.
Diagnosing a suspected wedge — check all three:
ps -eo pid,etime,%cpu,command | grep -E "[s]wift-frontend|[s]wiftc"
find -L ~/Library/Caches/bazel/_bazel_*/ -mmin -1 -type f | head # 8.x: /private/var/tmp/_bazel_*/
# and whether progress lines are still advancing in the build output
The find used to read -newermt '-60 seconds'. -mmin -1 is used instead
because it is portable, not because -newermt is broken: an earlier version
of this document claimed -newermt silently matches zero files on macOS, and
that is false — /usr/bin/find on macOS 26.4.1 accepts -newermt '-60 seconds' and discriminates correctly (verified against a fresh file and one
dated 2026-01-01: only the fresh one matched). What actually fails is find
inside Claude Code's Bash tool, where find is a shell function shimming to
bfs, and bfs rejects the relative form with a loud Invalid timestamp
error. The lesson generalises: a utility's behaviour measured through that tool
is not necessarily the system utility's behaviour, so a claim about "macOS"
needs /usr/bin/-qualified evidence. Note also that this find runs over an
output base that easily reaches the tens of GB (see "Reclaiming disk" above),
so it takes minutes either way; watching a build log's byte count grow is the
faster progress signal in practice.
Several compilers at 0.0% CPU with growing elapsed time, no writes for
minutes, and a stalled log together are the actual signal to act on. Recovery:
kill the stuck swift-frontend processes, then the bazel server, then re-run
the build alone.
A feature moves through the same sequence of stages regardless of size, each one owned by a single skill and producing a fixed set of artifacts:
| stage | skill | artifacts |
|---|---|---|
| start | start-feature |
worktree + branch in both repos, change record stub, spec, plan whose last task completes the change record, ticket → IN PROGRESS |
| implement | superpowers:subagent-driven-development, in a fresh child session start-feature starts once the plan is approved (or from the prompt it prints, where it cannot) |
code, docs/changes/<date>-<slug>.md, the human's code review, then a self-test checklist the human runs on a device |
| refresh | sync-from-develop |
merge commits in both repos |
| share early | extract-to-develop |
the approved part of the feature as one commit per repo on develop, pushed directly; the feature branch re-synced |
| ship to QA | build-to-testflight |
build/{N}, a TestFlight build, a change-record comment on each ticket, tickets → READY FOR QA, a Confluence row; for develop tickets never in a QA build, a stamp commit on develop, pushed directly |
| bug round | fix-qa-bugs |
fix commits on the feature branch, a change-record delta, bug linked and → DEV COMPLETED |
| land | merge-to-develop |
squash on develop in both repos, the change record re-posted at the freeze point, branches and worktree removed |
| upstream | tg-merge |
its own branch + worktree, a docs/changes record it writes but does not deliver, and a self-test checklist for its 🔴 features |
| crashes | triage-crashes → diagnose-crash → fix-crash |
the round's records, pushed straight to develop; per crash, a feat/crash-<slug> worktree holding its diagnosis and, when fixed, the fix, its change record and ticket → IN PROGRESS; landed by merge-to-develop, records-only straight to develop when not fixed |
Between implement and ship to QA, the human reviews the code, then runs a
self-test. The implementation session and fix-crash hand over for a code
review first; then they, and tg-merge at handover, end with a short checklist
the human runs on a real device: the main paths only, so that a broken task
never reaches QA and the human sees what changed for the user. At both stages
the human answers with an OK or a list, and a list is answered item by item,
changing nothing before the human approves. That procedure is owned by
.claude/reference/human-review.md; how the checklist is written, by
.claude/reference/self-test-checklist.md.
Ship to QA and bug round form a loop, not a line: a build surfaces bugs, a bug
round fixes them, the next build ships the fixes, and QA may bounce it back
again. Only merge-to-develop exits that loop — nothing else marks a feature
done, so don't treat a green TestFlight build as the finish line by itself.
Share early sits outside that loop, at any point between start and land.
extract-to-develop lands the part of a feature that is useful on its own —
tooling, a shared component, a fix in code the feature passed through — on
develop ahead of the rest, after one approval, and merges develop back into
the feature. The feature itself carries on through the loop unchanged; only
merge-to-develop still marks it done.
An upstream merge joins that loop; it does not skip it. tg-merge writes
the change record and stops — it posts nothing to Jira and edits no
description — so its branch then goes through build-to-testflight like
any other feature, which is what posts the record's orientation and its links
as a comment, transitions the ticket and records the Confluence row. To that
skill a tg-merge branch looks exactly like a feature branch, with slug
tg-merge-<VERSION>. One wrinkle: its commits deliberately carry no Task:
trailer, so trailer-based key detection finds nothing and asks — answer with
the key on the change record's own Tickets: line. Only after that build does
merge-to-develop land it. Handing tg-merge straight to merge-to-develop
would route around the only skill that delivers the change record, leaving it
written and unread.
Production crashes go through three skills and one registry, so that the
analysis accumulates instead of being redone. triage-crashes runs a round in
the main clone — verify what we shipped, pick the live version, rank and triage
its top crashes — pushes the records straight to develop, and proposes one
session per crash worth taking on. That session runs diagnose-crash in its own
feat/crash-<slug> worktree: it finds the root cause and tells the human whose
crash it is, whether and how it can be fixed, and whether that is worth doing.
The human decides. On "fix", fix-crash continues in the same session and
branch: ticket, fix, the human's code review, a device self-test, then a build
or a merge. Any other decision lands the record on develop by itself, through
merge-to-develop's records-only path. Several crash sessions run in parallel.
docs/crashes/ is the single source of truth — one markdown file per
Crashlytics issue, keyed by issue id, with a flat frontmatter header over mostly
prose. README.md there is generated and must never be hand-edited; on a
conflict, discard both sides and regenerate. Crash branches never regenerate
it while they work, only when they land, so parallel crash branches do not
collide in it. The tree is stripped from the public mirror.
A conflict in a record — a crash branch landing after a triage round
touched the same record — keeps both sides: observation rows in date order,
decision-log lines newest first, and in the frontmatter the branch's value for
the fields a crash session owns (status, ownership, subsystem, files,
markers, fix_*, verified_*) and develop's for the rest, which triage
owns (counts, share, trend, ids, console, triaged_*).
A diagnosis writes no app code before a human decision. It reports, drafts
a patch, and stops. A fix is written only after the human says to fix and names
the option, by fix-crash, in the branch the diagnosis started; a small fix
needs no spec or plan, because the approved option in the record is the spec.
Two rules bind every diagnosis: never remove a fatalError or assert to make a
crash go away (that trades a visible crash for silent data corruption), and
"upstream race — do not touch it" counts as a successful diagnosis, because a
session under pressure to produce a patch will patch someone else's engine on a
theory.
The status chain has one owner per transition: triage-crashes opens a record
on develop; diagnose-crash sets diagnosed on the crash branch, wont-fix
or skipped when the human decides not to fix, and fixing under another
crash's fix_branch when that crash's fix covers it; fix-crash sets fixing
when the human decides to fix, and wont-fix or skipped when a fix is
abandoned; merge-to-develop sets shipped when the fix lands; and the next
round's verify pass closes it as verified or reopens it as regressed. A
crash left to upstream stays skipped until the human asks for it by name.
tg-merge also reads the registry, open crash branches included, reporting
where an upstream change touches an open crash's files.
AGENTS.md carries the Nicegram dataroom protocol: read nicegram/dataroom
before a task, record the work in it after. The text between its markers
belongs to the dataroom (docs/operations/agent-protocol-block.md there,
applied by its scripts/agentops/adopt.py), so never edit inside the markers;
a new version arrives as a replacement block. The dataroom's checks read the
block only from the root AGENTS.md and need a bare @AGENTS.md line in
CLAUDE.md, which is why it is not in this file.
In this repository the steps fall at fixed points of the lifecycle:
- Before is the first stage of the task:
start-feature,diagnose-crash,tg-merge, or the start of a change that goes straight todevelop. - After is when the work lands on
develop—merge-to-develop,extract-to-developor a direct push — and not earlier: QA builds and bug rounds are part of their feature, not tasks of their own. Each repository the task changed gets its own work log entry naming itsdevelopcommit (the dataroom's rule: one entry per repository, the same slug with the repository's name in it), so a cross-repo feature writes one forbitbucket:mobyrix/nicegram-iosand one forbitbucket:mobyrix/nicegram-assistant-ios. Both are written under the approval the landing already asks for. - A feature's
docs/kb/record in the dataroom is taken from its change record indocs/changes/, which stays the source of truth here.
The nightly audit reads master with --first-parent, so the block counts from
the next release on, and a release merge is covered when any entry names a
commit it brings in.
nicegram-assistant-ios is vendored as a git submodule at
packages/nicegram-assistant-ios and consumed as a local SwiftPM path
package, so assistant edits reach the build with no push and no re-pin.
A feature spanning both repos uses one worktree and two same-named branches:
.claude/worktrees/<slug>/ branch feat/<slug>
packages/nicegram-assistant-ios/ branch feat/<slug>
Use the start-feature skill. It runs
.claude/scripts/new-feature-worktree.sh [--base <branch>] <slug>, which
creates that pair of worktree and branches in one step — from develop unless
--base names another branch — and prints the worktree's absolute path on
stdout (all git chatter goes to stderr, so WT="$(…)" captures the path alone).
The branch name is load-bearing — the rest of the toolchain keys on it.
build-to-testflight resolves origin/feat/<slug> for every feature it
builds and locates each feature's assistant checkout by that same ref;
fix-qa-bugs finds a feature's worktree with git branch --list 'feat/<slug>'; merge-to-develop cites this very section for the worktree
slug it removes. A worktree created any other way does not get that name:
the harness's EnterWorktree tool names the host branch
claude/<slug>-<hash>.
That is not hypothetical. Measured on this machine on 2026-09-01 —
git worktree list reported host branches develop,
claude/testflight-build-skill-c6db7e and
claude/speech-to-text-refactor-93dba0, while all four feat/* branches
(ai-chat, ai-context, auto-telegram-login,
core-remote-config-firebase-migration) were held by no worktree at all.
Both live features were in the claude/* state. Their assistant
branches are still named feat/<slug>, which is exactly why
build-to-testflight keys its assistant search on the assistant branch
rather than the host one.
So create feature worktrees with start-feature. A feature that already sits
on a claude/* host branch is not broken — fix-qa-bugs §2 and
build-to-testflight's Phase 0, under "Getting the branch wrong halts under
two different letters", each say what to do — but say so as an input rather
than letting a skill infer a host branch name that does not exist.
Creating and entering the worktree is one shared procedure,
.claude/reference/entering-a-worktree.md — the script above, then
EnterWorktree and change_directory, then an assert that the move happened.
start-feature, tg-merge and diagnose-crash follow it, so change the flow
there rather than in any of them.
Two of its consequences reach the rest of this document. An entered worktree
clamps git to itself: the harness reads each command's text and refuses
git redirected outside the worktree, git beside a value existing only at run
time — a $(…), a ${X:?}, or a variable an earlier Bash call set, since
shell state does not survive between calls — and any command it cannot parse.
The reference states the measured rule in full. And EnterWorktree does not
move the file viewer, which is why the procedure also calls
change_directory; without that second call every file link written during
feature work comes back "Couldn't find this file".
So: start-feature, superpowers:subagent-driven-development, sync-from-develop,
extract-to-develop and merge-to-develop run inside the feature worktree;
build-to-testflight and fix-qa-bugs run from the main clone, in a session
that has not entered one.
Those two are written throughout in the git -C "${WT:?}" form — deliberately,
so that a failed cd cannot silently leave a command operating on the wrong
repository — and that form does not survive the clamp. The worktree skills are
the opposite: bare git from the working directory, every value written
literally. sync-from-develop also runs in build-to-testflight's build
worktree, which that skill's Phase 1 has cd'd into without entering, so its
bare git works there too. merge-to-develop is the awkward one — it has to
land from the worktree, because its landing procedure diffs and pushes HEAD,
and then leave with ExitWorktree before cleanup, because the removal deletes
the directory the shell was standing in.
The crash skills follow the same split: triage-crashes runs in the main clone
on develop, and diagnose-crash and fix-crash run in the crash's own
feat/crash-<slug> worktree, which diagnose-crash creates from the main
clone — so the two crash-branch skills use bare git, like the worktree skills.
Each of those skills now opens with its own ## Where this runs section,
naming the position and carrying a probe that halts rather than guessing. That
section, not this paragraph, is what a skill is executed against; this one only
says how the set fits together.
Everything below this line is background: what the script already does and why each step is shaped that way. None of it needs running by hand.
The base ref is asserted, not trusted. The script passes HEAD explicitly
to git worktree add -b, so it does not depend on .claude/settings.json's
worktree.baseRef: head — that key governs EnterWorktree (the Claude Code
changelog shows it shipping in v2.1.133 with values fresh | head, and the
CLI installed here is newer). What the assertion catches is a different, real
failure: the main clone sitting on the wrong branch when the worktree was
created. The base is develop unless --base names another branch.
git -C "$MAIN" log --oneline -1 <base> # want
git -C "$WT" log --oneline -1 # got
On a mismatch the script exits 1 and tells you to branch the worktree onto the
base before continuing. It cuts from HEAD rather than from the base ref
because the submodules are cloned from the main clone's gitdirs (next
paragraph), which only reliably hold what the main clone has checked out — so a
feature cut from an epic needs the main clone at the epic's tip.
Submodules are cloned from the main clone's own gitdirs, not the network —
measured at ~4 s for all 14, versus refetching ~550 MB. That needs
protocol.file.allow=always: git blocks file-protocol submodule transports by
default (CVE-2022-39253) and otherwise fails with fatal: transport 'file' not allowed.
Three guards in that loop each exist because their absence has a silent
failure mode, and they are the same three ci/bootstrap-submodules.sh carries:
- Ask git for each gitdir; don't construct
$MAIN/.git/modules/<path>. That construction is wrong for at least one submodule —packages/nicegram-assistant-iosstores its gitdir at the legacy path.git/modules/Nicegram/packages/nicegram-assistant-ios. And guard the lookup:git -C <dir> rev-parse --absolute-git-dirwalks up to the enclosing repo and returns its gitdir with exit 0 when<dir>exists but isn't itself a repository — confirmed empirically with an empty directory inside a throwaway repo. Without an[ -e "$MAIN/$p/.git" ]test first, the loop clones the superproject into the submodule's path, fails confusingly, and leaves a non-empty directory that blocks a retry. git submodule syncis scoped to the one path it initializes. An unscoped sync rewritessubmodule.<name>.urlfor every submodule in.git/config— which a worktree shares with the main clone — clobbering any deliberate local URL override.git submodule statusis parsed withsed, notawk '{print $2}'. Whitespace field-splitting silently truncates any submodule path containing a space at its first word; this repo has 1661 tracked paths with spaces.
Nothing else is needed: Make.py regenerates build-input/,
build-input/configuration-repository, and xcodeproj.bazelrc itself.
Bootstrapping is not a build prerequisite either. ci/verify-build.sh and
ci/generate-project.sh both run ci/bootstrap-submodules.sh before anything
else and initialize whatever is missing — see "Build" above for why that
exists. It brings submodules to their currently pinned commit; it does not
create branches, which is the part new-feature-worktree.sh still owns.
Builds from the worktree need TELEGRAM_CODESIGNING_GIT_PASSWORD; ci/fastlane-env.sh
is untracked and absent in a fresh worktree, but the ci/ wrappers fall back to the
main clone's copy automatically — see "Build" above. No manual sourcing needed.
- Branch names are
feat/<slug>in both repos, with no ticket key. The ticket goes only in the commit trailer (Task: NCG-XXXX). - One spec and one plan, both in this repo under
docs/superpowers/, with plan tasks tagged[ios]/[assistant]. - Worktrees live under
.claude/worktrees/, which is listed in.bazelignore(a nested worktree copies the root BUILD files and Bazel would otherwise discover it as a package) and covered by.gitignore's pre-existing blanket/.claude/*rule — it has no entry of its own. - When the assistant gains a new dependency, re-resolve this repo's
Package.resolved(swift package resolve) and commit it with the feature. This is the only case left that touchesPackage.resolved; ordinary code edits never do. - Merge-watch files — an upstream merge can clobber any of these; check
all of them after every upstream merge:
.gitmodules— carries a# MARK:comment marking the private submodule stanza; re-add the stanza if a merge drops it. Note that any futuregit submodule add/git submodule deinitrewrites this file from scratch and silently drops the# MARK:comments, so re-mark it by hand afterward.Package.swift— must stay.package(path: "packages/nicegram-assistant-ios"); never let a merge revert it back to a remote git URL dependency.Telegram/BUILD'sassociated_domains_fragment— must keep generating itsapplinksentries fromNICEGRAM_ALL_DOMAINSandNICEGRAM_BUSINESS_UNIVERSAL_LINK_DOMAIN; see "The web domain" above.docs/tg-merge/state.json— the merge skill's only record of the last merged upstream commit. Never hand-edit the sha to make a check pass; a wrong base silently produces a plausible merge against the wrong upstream. Both this file anddocs/tg-merge/reports/are stripped from the public mirror bybitbucket-pipelines.yml.bitbucket-pipelines.yml's strip lists —docs/crashesmust stay in both of them (therm -rfand the staged-path guard), exactly like the four trees beside it.ci/tests/test-mirror-strip.shcatches a tree dropped from one list but not a tree dropped from both, which is what an upstream merge that rewrites this file would do.build-system/Make/Make.py'sgenerate_project— upstream'skillall Xcodeandopenmust both stay behindif not arguments.headless:, and--headlessmust stay an argument. Dropping the argument fails loudly, since thegenerate_projectlane passes it. Dropping a guard is silent, and the firstci/verify-build.shin a fresh worktree then closes every Xcode window on the machine. tg-merge's merge-watch counts the guards and rejects any unguardedkillall/open.AGENTS.mdand the@AGENTS.mdline inCLAUDE.md's import — upstream added its ownAGENTS.mdon 2026-10-17 (51ff08f183f), after our 13.0 base, so the merge that first brings it is an add/add conflict. Resolve it as upstream's file with our marked pointer and the dataroom block right under its# AGENTS.mdheading, the block byte for byte, and keep@AGENTS.mdin the import at the top ofCLAUDE.md(see "The dataroom protocol" above). tg-merge's merge-watch asserts both.- The work-account phone guards — every place in Telegram code that would show
or send a Nicegram Business work account's own number carries a
// Nicegram Business, work-account phone: <site>block. tg-merge's merge-watch runs.claude/skills/tg-merge/scripts/work-account-phone.py checkover them, and itsreviewmode lists the phone-number uses upstream added, which are read at every merge: a new display or send of the account's number gets a block and aSITESentry.
(cd ci && ./build-to-testflight.sh "<version> (<build>)")
Preconditions, in this order:
- The assistant feature branch is pushed (not merged — the branch stays open).
- The host's submodule pointer is committed at that pushed commit.
The script pushes the current host branch, then triggers the Bitbucket
push-to-github-repo pipeline on it, which mirrors to GitHub beta, where
.github/workflows/beta.yml checks out with submodules: 'recursive' and builds.
An assistant commit that exists only locally fails at that checkout, so both
preconditions are about making the SHA fetchable — not about merging.
The mirror step also strips five trees before pushing — .claude/,
docs/superpowers/, docs/tg-merge/, docs/changes/ and docs/crashes/ — so
fork-internal tooling, process docs, the upstream-merge state, the change
records and the crash registry never reach the public GitHub repo; all five stay
fully tracked in Bitbucket. Keep
this list in step with bitbucket-pipelines.yml, which names each tree
twice: once in the rm -rf and once in the staged-path assertion right
after it. ci/tests/test-mirror-strip.sh asserts the two lists cannot drift
apart, so a tree added to one and not the other fails the suite rather than
leaking quietly. It also asserts the old docs/qa name survives nowhere in
that file, which is what covers the third mention — the comment explaining
why the tree is stripped, which no list-parsing check can see.
docs/changes/ is stripped for the same reason as the rest: change records
describe gating and remote-config behaviour in terms only the team should read.
docs/crashes/ is the newest member — the crash registry states crash volumes,
affected-user counts, and our written judgement that specific upstream Telegram
bugs are abandoned, which reads differently in public than inside the team.
This only stops future disclosure —
docs/superpowers/ predates this exclusion, so if the mirror was pushed while
those files existed, that content may already be public, and the next mirror
push will simply record their deletion. (The private submodule's URL still
appears in the mirror's .gitmodules by necessity, since the release build
needs it to resolve; that is unchanged and already documented above.) Any new
fork-internal-only tree added later needs the same rm -rf plus a staged-path
assertion in bitbucket-pipelines.yml — otherwise it quietly starts shipping
to the public mirror. This paragraph is what an upstream merge is resolved
against, so a tree missing from it here is a tree that gets dropped there.
Use the merge-to-develop skill. It merges the assistant first, then bumps and
merges the host, verifying before each branch deletion that the merged develop
tree matches the branch being deleted.
The order is not a preference: the host records a submodule SHA, so a host PR
merged while pointing at an unmerged assistant commit leaves develop
referencing a commit nobody else can resolve.
- Full app:
ci/generate-project.shin the worktree generates the project and opens it in Xcode, without closing any Xcode window. This is a human's step. An agent never opens Xcode: it passes--no-openwhen it needs the project regenerated, and its compile check isci/verify-build.sh. Generation itself is always headless, because thegenerate_projectlane passes--headless, and--no-openstops the script right there. That is whyci/verify-build.shcan run it itself whenxcodeproj.bazelrcis missing. Upstream'sgenerateProjectwithout that flag runskillall Xcode, closing every window of every checkout, and then opens the project. An earlier version of this document denied that on the strength ofgrep -rln "killall Xcode", which cannot match:Make.pypasses argv as a list,['killall', 'Xcode']. - Assistant only: the
Demo/app inside the submodule — a plain SwiftPM build, no Bazel. See itsREADME.md.
The rules in .claude/rules/ auto-attach by path for your session. A subagent
you dispatch does not inherit your context, so whatever you paste into its
prompt becomes its entire rulebook.
Never hand a subagent a hand-written summary of these conventions. A summary silently replaces the real rules with your recollection of them, and the subagent has no way to know something is missing. Instead, name the files:
Binding conventions: read
packages/nicegram-assistant-ios/.claude/rules/swift-conventions.mdandmodule-structure.mdbefore writing code. The constraints below are supplementary to those files, never a replacement.
The same applies to reviewers — a reviewer never asked to check against
swift-conventions.md will not check against it. Give every reviewer the rules
files that match the paths in its diff as a named check. Naming gets one more,
because no rules file can show a reviewer that a name misreads: the reviewer
lists each name the diff or plan introduces with what it reads as on its own,
and flags each whose reading misses what it is, then reads them together and flags
a word that names different things in two of them (packages/nicegram-assistant-ios/AGENTS.md,
"Module taxonomy").
A name the plan or spec chose gets the same check: a plan's choice is not a reading
(LinkRoute and isNcgLink passed every review because the plan had named them).
Function bodies get one more, because "readable top to bottom" (swift-conventions.md)
was missed twice: the reviewer lists each function the diff adds to or lengthens and
flags one that runs several steps inline where a helper per step would read
(NGEntryPoint.onAppLaunch grew a registration block).
Fallbacks get one more, because unwrap() and one do/catch (swift-conventions.md) was
corrected four times: the reviewer lists each guard or if the diff adds that returns a fallback
value, and flags one that more than one step can reach (NicegramLinkHandler.adapt) — but not one
that decides whether the input is this code's at all, which stays a guard above the do
(AuthImportDeeplink's scheme and host).
Consistency with the surrounding code never outranks a written convention — in either direction. Do not triage a reviewer's finding away as "pre-existing pattern", and do not introduce a violation because the neighbouring files already have it. If the neighbours are wrong, follow the rule and say so.
Both directions have already failed once. Dismissing a finding as pre-existing
let a hand-written initializer ship in a package whose rules say to use
@MemberwiseInit. In the other direction, an implementer added a redundant
@available(iOS 15.0, *) "to match the four sibling formatters", disclosed it
honestly as a judgment call — and the task reviewer approved it, because the
siblings really did look like that. 471 files in the package carry the same
redundant attribute. A majority is not a convention.
.claude/rules/ attach by the path of a file in context. A spec or a plan is
markdown, so no Swift rule ever attaches while you write one — and a plan is
exactly where type shape, field order, initializers and DI wiring get decided.
Every implementer then transcribes it verbatim.
This is not hypothetical. The CoreRemoteConfig migration plan specified a
hand-written init, non-alphabetical stored properties, a computed var on a
class whose other members were functions, a service constructing its own
HttpClient instead of receiving it from the container, and redundant
transitive dependencies. Every one reached the code, and the human caught all of
them in review. Note that module-structure.md — which is always loaded — says
"Build initializers with @MemberwiseInit" and was in context the whole time.
Presence in context is not application. The check has to be deliberate.
The same gate then missed again on the speech-to-text design: the naming rule it
violated lives in packages/nicegram-assistant-ios/AGENTS.md, not in
.claude/rules/, and the names were decided in a module-layout tree rather than
a code block — hence the two widenings below.
So, before a spec or plan is shown to the human — whenever it contains code blocks or names any type, file or module:
- List the paths the plan will create or modify.
- Read every
.claude/rules/*.mdwhosepaths:match them, in both repos, plus the always-on ones, plus both repos'AGENTS.mdandCLAUDE.md— conventions live there too, not only in.claude/rules/. - Go rule by rule through the files you just read, checking the plan against
each — not dimension by dimension from a remembered list. Naming, field order,
initializers, access modifiers, DI wiring, dependency declarations and error
handling are examples, not the set: both rules missed on the speech-to-text
design (
Polymorphism, "keep a type's public surface uniform") were in a file already read but absent from an earlier version of this list. - Then ask what the rule-by-rule pass cannot: for every type or helper the plan
invents, and every call it spells out into Telegram's machinery, does the
codebase already provide the shape it should take? A hand-written
storage type breaks no style rule and is still wrong where
data-layer.mdnamesUDRepositoryand{Name}Repository.publicis the same trap: it is correct only with a consumer outside the package — a fact about the tree, not about the block. So is a link opened withopenExternalUrland hand-picked arguments:CoreContainer.shared.urlOpener().open(url)already passes them, and the work-account row's plan and its reviewer missed it while step 4 asked about types only. - Then dispatch a plan conventions reviewer: a subagent given the plan and those rules files, asked 3 and 4 as a named checklist rather than open prose — which code blocks or names violate these? Self-review does not catch your own blind spots — the self-review on that same plan passed while all eight violations sat in it.
This gate has failed five times, each differently — not run because a rule
could not attach, not run at all, run but scoped to style while a hand-rolled
UserDefaults store and 77 unjustified public symbols passed, run against
.claude/rules/ alone while the naming rule it needed sat in AGENTS.md, and
run with a reviewer that still passed three existing rules. A mechanical check
was proposed after the fifth and declined — the human's review is the backstop;
keep running the gate as written.
A plan carries its inputs; it does not tell the implementer to go and get
them. This is a separate axis from the gate above, which checks conventions —
design values are inputs, so it would not have caught this even had it run. The
remove-crypto-wallet-ui plan said "spacing, padding, corner radii and exact
shades come from the Figma frames — open the named frame rather than inventing
them", in a preamble bullet, above tasks whose code blocks already held invented
numbers. Nobody opened the frame: an implementer executes tasks, and a sentence
that names no tool, produces no artifact and fails nothing when skipped is not a
task. If a value is needed to write the code, the planning session fetches it and
writes it in. For a design, that is read-figma-design's extraction: every UI
task cites the frames it implements and carries every visual value in its code,
and the skill's design-inputs check fails a plan that defers one to "take it from
Figma".
Every feature plan ends with a change-record task. The document is
docs/changes/YYYY-MM-DD-<slug>.md, in English, following
docs/changes/TEMPLATE.md, and it is written during implementation — not at
planning time — because it describes what was actually built. start-feature
may already have created it as a stub when a ticket key or a design artifact was
given — or read-figma-design may have, when a design arrived later — in which
case the task completes that file rather than creating one; either way it
ends with this feature's key, when there is one, in the ## Delivery table's
pending row, and with the template's instruction comment deleted — a record
that still carries it halts the next build under halt (l). It carries a
Tickets: header line naming a real ticket, or none at all when there is no
ticket — never a placeholder — keeps an existing ## Design section byte for
byte, and meets the five obligations start-feature states in
full: orientation, sufficiency for both another platform and the full test
spectrum, reachability (the gates in evaluation order), known-and-intentional
behaviour, and reference-don't-duplicate. This requirement lives here, and in
start-feature, deliberately: a .claude/rules/ file keyed on
docs/changes/** would never attach while a plan is being written, which is
the same failure this section already documents.
A design artifact is whatever Figma links are handed over for a feature — a
page, a section, a frame, several of them — at any stage, including after the
logic has shipped. It is recorded in the feature's change record under
## Design the moment it arrives, so no later session has to ask for it again.
The read-figma-design skill owns everything from there: intake and recording,
extraction with read-only scripts, the design-inputs check on a plan, the
fidelity check on code, and what to do when a Figma call fails. The mapping from
Figma names to our code — colours, text styles, icons, geometry — lives beside
that code, in packages/nicegram-assistant-ios/.claude/reference/figma-to-code.md.
Creating or changing mockups in our file is the edit-figma-design skill's job,
and the prompt hook that fires on a Figma link names both skills.
Two rules bind all new and changed UI code, with a design or without one:
design system only — text styles and colours the design system defines,
nothing else — and no value without a source — nothing by eye, nothing from a
screenshot. Both are written out in the package's swiftui-views.md.
With no design yet — logic first, the design as a later iteration — the UI uses only existing components and design-system tokens and styles, and any new visual value is a human decision recorded in the spec as "interim, no design". No link exists then, so the skill never loads; this paragraph is what carries the rule.
When a newer system API makes the code clearly simpler, use it and mark that
feature @available(iOS N, *), gating its entry point so older versions simply
do not see it. Clean, simple code outranks reaching older iOS versions. Do not
quietly hand-roll an uglier shape to preserve a floor.
Propose the trade-off and get agreement first — except UIHostingConfiguration
(iOS 16), which is pre-approved and is the prescribed UIKit-interop shape in
presentation-layer.md.
packages/nicegram-assistant-ios has a test target and a ~10-40s test loop, so
"this repo has no test framework" is no longer a reason to skip TDD. It was the
standing, never-negotiated excuse through the whole CoreRemoteConfig
migration, and it expired.
A plan task touching pure logic — a use case, parsing or mapping, a cache,
value resolution — states its test first and its implementation second, so the
implementer can watch it fail before making it pass. A task touching UI, DI
wiring, a TelegramBridge or network transport does not: a test there asserts a
mock and proves nothing, and the review rubric counts one as a defect.
See "Testing" in packages/nicegram-assistant-ios/AGENTS.md for the framework,
the run command, and the two ways a test run can look green without having run.
Tests go in packages/nicegram-assistant-ios only. This repository gets no
test target. Tests/AllTests already fails to build (it references a dangling
//submodules/TgVoipWebrtc:TgCallsTests), nothing runs app-side tests routinely,
and a plan that adds one here is adding infrastructure with no consumer. Host
changes are verified by ci/verify-build.sh and by reading the build's own
output — a generated entitlement, a generated source.
Prefer the simple, clean implementation. When a requirement can only be met by building something intricate — a bespoke mechanism, a workaround for a platform limit, state threaded through several layers — stop and propose the trade-off rather than building it quietly. We are often willing to give up the requirement to keep the code simple: a reduced version of the affordance, the affordance only where it is cheap to provide, or not shipping it at all.
The same goes for an edge case nobody asked about. A rare path — a second link while the first is mid-flow, a repeat of something already under way — handled with types, references or state of its own is a trade-off to put to the human, not a default to build; the plain answer, doing what the first time did, is often enough.
Gating a feature behind @available(iOS N, *) because the newer API is the
clean one is a standard instance of this, and so is showing a nicety only on the
OS versions where it costs nothing.
"The design says so" does not exempt a requirement from that conversation. A mockup is a proposal about what the user sees, not a budget for how much machinery we build to show it.
When the human gives feedback on a spec, a plan, or code, they may ask you to
invoke the learn-from-feedback skill. It applies the corrections and then
repairs whatever let each one through, so the same correction is not needed
twice.
Never invoke it without the human's go-ahead. Not all feedback should change
the instructions — corrections during brainstorming are the design converging,
not a rule failing. The human decides: they ask for it, or approve a code-review
or self-test reply that proposed it for an item
(.claude/reference/human-review.md). The skill never commits an instruction
change without showing it for approval first.
Feedback on mockups in our Figma file is the exception: edit-figma-design
runs its own learning step, which offers after each approved round and writes
nothing without approval.
Comment only what the code cannot say — a non-obvious constraint, or a decision
a reader would otherwise undo. Do not restate the code, and do not doc-comment a
member whose name already says it. This holds for every file we write, in
both repositories and whatever the language: Swift, BUILD, .bzl, the
Fastfile, shell.
The second half is the one that gets skipped. A hook that looks redundant with
another carries its reason beside it: nb-delegation-client's
continue userActivity hook runs ahead of openUrl because openUrl drops a
link when no account is signed in. That reason sat only in the spec, so review
asked to delete the hook — no reader of the code opens the spec.
It overrides CLAUDE.md's "Document public APIs with comments", which is
upstream Telegram's convention and stays in force for upstream code. Do not
restyle upstream comments — and the // Nicegram … markers are not commentary,
they are required by telegram-interop and stay whatever this says.
It lives here, not in a .claude/rules/ file, because no such file can reach
it: rules attach by path, and Telegram/BUILD, Nicegram/**/*.bzl and ci/**
match none of them — which is where the worst of it accumulated.
telegram-interop.md— editingsubmodules/**: marker syntax + SSignalKit bridges.nicegram-modules.md—Nicegram/**modules,NGUtils, resources.swift-conventions.md— Swift style for our code.assistant-package.md—packages/**— vendored submodule, read the assistant's own rules.
CLAUDE.md at the repo root is upstream Telegram's own file, not ours — except
for three fork-owned spots: its marked "Nicegram branding overrides" subsection
(hand-maintained, preserved across every upstream merge), the three-line import at
the top that pulls in this file and AGENTS.md, and the <!-- Nicegram: … --> build-values
marker comment near the top of the file, flagging that its Build section's
values are upstream's, not this fork's. Aside from those fork-owned spots,
CLAUDE.md stays the authority on the embedded watch app, the Postbox →
TelegramEngine refactor, and the tgcalls testbench — but its Build section's
cache dir, config path,
codesigning repo, and password source are upstream's own values and don't work
here; see "Build" above for the ones that do. This file covers what the fork
adds.