# Repository collaboration rules ## Task boundaries and efficient execution - Before editing, confirm the active repository, worktree, claimed paths, and existing changes. Honor path claims; never use `--override` to bypass another task's ownership. - Read only the files needed for the request. Batch independent local inspections; keep commands bounded and avoid duplicate searches, broad output, unnecessary network calls, polling, retries, and downloads. - Use the narrowest checks required by the task, report exactly what ran, and stop when the requested outcome is complete. Do not continue into adjacent cleanup or release work. - Keep task-owned processes bounded, stop those no longer needed, and verify they stopped. Never stop user-owned or pre-existing processes. - Editing files does not authorize commits, pushes, PR creation or merge, deployment, migrations, or other external writes. Perform release or external actions only when the user explicitly requests them. ## Parallel agent work (mandatory) - One task = one unique branch and worktree. Declare paths with `npm run wt -- create --type --paths "..." --goal "..."`; if a claim is refused, coordinate instead of overriding it. - Keep the primary checkout untouched for task work. Never run shared-state commands there (`git checkout`, `git stash`, `git reset --hard`, `git clean`, `git add`, `git gc`, or `git repack`); do not move or discard another session's branch or changes. - Exactly one agent/session is the write owner of a worktree at a time. Other agents on that task may review or research read-only. If multiple agents need to write, give each a separate task branch and worktree with declared, non-overlapping paths; never share a writable checkout or Git index. - Parallelize only tasks with independently mergeable scopes. Give one owner any shared files, especially dependency manifests and lockfiles, migrations, cron bundles, and release/deployment configuration. Keep concurrency within integration and review capacity; do not add agents only to increase the count. - Before changing a dependency manifest or lockfile, run `npm run wt -- deps --isolate`. Never install through shared or symlinked dependencies. Dependency manifests, cron bundles, and migrations are serial claim categories. - Use the allocated ports and `npm run wt:dev` / `npm run wt:e2e` wrappers. Use `handoff` before a long pause and `resume` when taking over. - After confirming the change is merged on the target remote, check whether `ship` already removed this worktree. If it remains, confirm there are no uncommitted changes or handoff material to retain, then run `npm run wt -- remove --delete-branch` to release the task claim and remove its worktree and local branch. Never clean another task's worktree. - `ship` is the only commit, push, PR, and auto-merge path; use it only after explicit release authorization. - Before a manual rebase, reset, branch replacement/deletion, force push, or forced worktree removal, record the old `HEAD`, preserve dirty files, and create and verify a durable recovery ref such as `codex/rescue--`. A reflog-only commit is at risk and is not a backup. Prefer the managed `ship`/`finish` flow over manual branch surgery. - Remove a worktree or branch only after confirming it is clean and its unique commits are merged into the intended base or protected by a durable recovery ref. Do not force-remove unreviewed work. - If GitHub/remote PR, CI, or merge state cannot be read, treat it as unknown; do not infer absence from a blank status or network error, and defer cleanup or branch replacement until verified. ## Protected PRs and parallel merging - `ship` returns after opening or updating a PR and enabling auto-merge by default. Continue independent work while required checks run; use `ship --wait` only when a coordinator needs the merge result in the current session. - Use `queue` as a status view, not as a manually enforced merge order. GitHub auto-merge and branch protection decide when each PR is ready to land. - Keep required checks and strict branch protection enabled. If a PR becomes `BEHIND`, rerun `ship` for that task from its own worktree; the tool syncs the latest base into only that branch, checks for collisions again, and refreshes CI without rewriting the remote branch. - Resolve a real conflict or overlapping hunk in the worktree that owns the change. Shared serial resources such as dependency manifests, migrations, and generated cron bundles remain serialized; unrelated tasks continue in parallel. ## Database migrations - Migration numbers are one global four-digit sequence; do not reuse numbers. `0076` is the only documented historical gap. - Before writing or applying a migration, run `node --import tsx scripts/check-migration-drift.mts --linked` and reconcile both directions of the ledger. AHEAD means the database has versions missing from the repository; do not reuse them. BEHIND means code may depend on a migration not applied to the database. ## Database resource consumption - For every change that reads, writes, scans, batches, retries, or schedules database work, assess the resource dimensions it affects: rows examined and returned, query count, index/scan shape, page depth or cursor use, bytes read and written, batch size, transaction duration, concurrency/fanout, retries, storage growth, compute time, network egress, and schedule frequency. Bound per-request and per-run work where appropriate. A SQL `LIMIT` caps returned rows, not necessarily scanned or billed rows. - Prefer index-backed filters, keyset pagination for sequential history reads, bounded batches, and idempotent writes. Preserve the user-required collection cadence and product capabilities; account for fallback and failover paths when assessing load. - Before introducing provider quotas or hard limits, assess whether exhaustion can suspend service or redirect load to another database. Do not treat application-side row counts as provider-billed usage. - Support resource-savings claims with provider usage metrics and timestamps. Label estimates and application-level counters separately; do not claim a reduction until comparable before/after usage data exists. ## Measurement provenance - Any capacity, row-count or byte-size number written into code comments, docs, PR descriptions or reports must say where it came from and when: a query (`count(*)`, `pg_database_size()`, `pg_total_relation_size()`, `pgstatindex`/`pgstattuple`, `EXPLAIN (ANALYZE, BUFFERS)`), or an explicit estimate. - Estimates must be labelled as estimates (`estimate`/`推算`) and state the inputs and assumptions. Never present an extrapolation (for example "archive adds 20–25 MB per archived day", "the database will fall back to X", "hourly steady state is 300 MB") as an observed measurement. - A value with no source must be treated as unknown, not as a baseline. When a previously published figure turns out to be an estimate, correct it in a dated change record rather than silently editing it. ## Cleanup and retention changes - Every new or changed cleanup step must be able to prove its real impact: record the affected row count from `DELETE ... RETURNING`/`GET DIAGNOSTICS`, or the before/after `pg_stat_user_tables.n_tup_del` delta, plus the scheduled run result. "It ran without error" is not evidence that it deleted anything. - Deleting zero rows is ambiguous. Distinguish **no data** from **failure**: compare the predicate's `count(*)` with the measured deleted count; if due rows exist but the delta is zero, inspect `cron.job`, `cron.job_run_details` (`status`, `return_message`) and lock/permission errors before calling it a success. A retention-window change (for example 90 → 120 days) must update the rule, the verification query and the evidence in the same change. ## Local Node.js version - This repository pins Node.js **22.23.2** in `.node-version` and `.nvmrc`; `engines.node` remains `22.x` for runtime compatibility. All three are enforced by `scripts/check-workflow-security.ts`. - Run `nvm use` (or `fnm use`) in the repository root before install/build. With `nvm` on zsh, auto-switch on directory change is one hook away: ```zsh autoload -U add-zsh-hook load-nvmrc() { [[ -f .nvmrc ]] && nvm use --silent >/dev/null 2>&1 } add-zsh-hook chpwd load-nvmrc load-nvmrc ``` - Do **not** change the machine-wide default Node (`nvm alias default ...`, Homebrew `node`, or `fnm default`) for this repository: that affects every other project on the machine. If a global default is preferred anyway, the command is `nvm alias default 22.23.2` (or `fnm default 22.23.2`); it applies to all new shells everywhere, not just this repository. ## Local builds - `npm run build` uses Next.js Turbopack by default. Sandboxed local environments that cannot create Turbopack CSS worker processes must use `npm run build:webpack` (or run builds with `env -u NODE_OPTIONS` outside the sandbox). - `npm run ci:local` runs the full suite including `next build`; in sandboxed environments substitute the webpack build for the turbopack step before running it. ## Production hosting and credentials - Insight production runs on Cloudflare Workers (`insight-web`), with GitHub Actions as the only production release controller. Do not deploy through another provider or bypass the repository's release workflow. - Keep the Cloudflare API token in the GitHub `Production` environment. Runtime application secrets are provisioned to the Worker through the deployment workflow's reviewed allowlist in `scripts/write-cloudflare-worker-secrets.mts`; never print, commit, or expose secret values to browser code. - Do not use retired Vercel credentials or project settings for current Insight production operations. Historical deployment records may retain Vercel identifiers as evidence of the platform used at that time. ## GitHub CLI device authorization - If GitHub CLI authentication has expired and the standard `gh auth login --hostname github.com --web --git-protocol https` flow is needed, start the flow only when authorized. As soon as GitHub returns a one-time device code, tell the user the code and `https://github.com/login/device` before asking them to authorize, opening the browser, or waiting for completion. - Never store a one-time device code in workspace memory, repository files, or logs. Never ask the user to paste a GitHub token into chat. ## Partner joint-run instructions - For partner integration preparation, rehearsal, fresh bundles, live execution, post-run verification, or replies, first read `/Users/imokokok/Documents/partnerships/AGENTS.md`, then `/Users/imokokok/Documents/partnerships/COLLABORATION-DOCS-STANDARD.md`, then `/Users/imokokok/Documents/partnerships/JOINT-RUN-PLAYBOOK.md`. Continue with the partnerships root README, the partner README, and the current stage fact sources. These rules supplement this repository's rules. - Apply this read order at a new joint-run task/window or context resumption. Within an unchanged continuous task, reuse already-read rules and recheck changed rules and the latest partner status. Dated retrospectives explain historical lessons; current partner facts determine scope, permissions and protocol conditions. - Follow the user's order for rehearsals and live runs: perform the authorized work and preserve raw evidence immediately; deliver complete English and Chinese replies in the conversation, explicitly stating required attachments and final files or no attachment; update formal collaboration documents last. Preserve existing authorization and required per-bundle GO or single-send gates; do not mark a draft as sent. ## This is NOT the Next.js you know This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.