Files
multica/server/migrations/101_task_usage_hourly_schema.up.sql
Jiayuan Zhang c1ec1f4646 docs: cut docs/ to design + product-overview, English by default (MUL-5698) (#6364)
* docs: delete completed plan docs and fix stale repo documentation (MUL-5698)

Ten repo docs were verifiably out of date against the code. Completed
plans are deleted outright rather than archived — they are dead weight in
every agent's context and their decisions already live in the code.

Deleted (all describe work that has shipped):
- docs/agent-quick-create-plan.md — marked "未动工", but agenttmpl
  templates (Phase 1) and the AI-create-agent page (Phase 3) are live
- docs/docs-outline.md — tracker planning "Chinese only, 25 pages"; the
  doc site is 39 pages x 4 languages
- docs/docs-rewrite-plan.md — plans 55 mdx, lists webhook autopilot
  triggers as unrouted; both superseded by what shipped
- docs/docs-onboarding-optimization-plan.md — work log for #5714, which
  landed the four languages and screenshots it lists as pending
- docs/onboarding-refactor-plan.md — v3 shipped (welcome-store,
  welcome-after-onboarding, onboarding_shim)
- apps/mobile/docs/project-v1-{plan,gap-audit}.md — marked
  "pre-implementation"; the picker files they scope no longer exist
- docs/plans/* + docs/ideation/* — implementation plans for agent
  access-scope (agent.visibility) and issue-table server query
  (/api/issues/grouped), both shipped

Fixed:
- docs/codex-sandbox-troubleshooting.md — the decision matrix claimed
  non-darwin gets workspace-write. Linux is danger-full-access (MUL-5578)
  and Windows is danger-full-access (MUL-4957); Windows had no row at all
- apps/mobile/docs/rnr-migration.md — Phase 1 is complete, not "not
  started"; every checklist item is in the tree
- AGENTS.md — architecture list was missing apps/mobile, apps/docs,
  packages/eslint-config
- docs/ui-consistency-audit.md — §3.2 status column is a mid-PR snapshot;
  #5263 and #5258 have merged
- server/internal/agenttmpl/loader.go — drop reference to a deleted doc

Co-authored-by: multica-agent <github@multica.ai>

* docs: reduce docs/ to design + product-overview, English by default (MUL-5698)

docs/ now holds two documents, each with an English default and a .zh.md
translation. Everything else was engineering scratch that agents load as
context on every run without ever being read by a human.

Deleted:
- docs/analytics.md, docs/feature-flags.md, docs/timezone-architecture-rfc.md,
  docs/codex-sandbox-troubleshooting.md, docs/codex-usage-cache-backfill.md,
  docs/custom-runtimes.md, docs/ui-consistency-audit.md

Language convention — English is the default filename, translations carry
a language suffix:
- docs/design.md (new English) + docs/design.zh.md (was design.md)
- docs/product-overview.md (new English) + docs/product-overview.zh.md
  (was product-overview.md)

While translating product-overview, three facts were corrected against the
code rather than carried over from the 2026-04-21 survey: the provider list
now matches README, onboarding is the shipped three-step
about_you/workspace/runtime sequence with Helper creation moved after exit
(packages/core/onboarding/step-order.ts), and the stale "28 tables" total
was dropped.

Reference cleanup so no comment points at a deleted file — .env.example,
server/internal/analytics/{client,events}.go, packages/core/analytics/index.ts,
server/cmd/server/main.go, server/pkg/featureflag/doc.go,
server/cmd/backfill_task_usage_hourly/main.go, and the doc pointers in
migrations 100/101/103/104. Migration edits are comment-only; the runner
tracks applied versions by filename, not by checksum.

docs/assets/ is kept — README.md and README.zh-CN.md embed those images.

Co-authored-by: multica-agent <github@multica.ai>

* docs: drop product-overview, fix rnr body and CLAUDE/AGENTS drift (MUL-5698)

Addresses all four blockers from review.

1+2. Delete docs/product-overview.md and docs/product-overview.zh.md.
The review found the doc carried facts that would make an agent do the
wrong thing — skill injection claimed a .agent_context/skills fallback for
providers that now have native paths in execenv/context.go, and it
documented `multica skill create --title` when the CLI only registers
--name. Rather than chase those, the document goes: it is derived from
code and can be regenerated from code when it is actually wanted. That
also removes the zh-as-historical-snapshot problem, since neither
language survives.

docs/ is now design.md + design.zh.md + assets/. design.zh.md is a
faithful translation of the English, not a snapshot, so blocker 1 does
not apply to it.

3. apps/mobile/docs/rnr-migration.md: the body contradicted its own
status line. §1 asserted in present tense that there is no theming
infrastructure, hardcoded tailwind hex, and a three-line global.css;
§5.2 said the same. Both are now marked as the pre-Phase-1 baseline with
the shipped state noted, §6's Phase 0/1 checklists are backfilled as
complete, and Phase 2 is labelled not started.

4. CLAUDE.md gains apps/docs/ and packages/eslint-config/, so the
authoritative Project Shape list matches the pointer list in AGENTS.md.
The two lists are now identical.

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Lambda <lambda@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
2026-08-04 17:31:45 +08:00

134 lines
6.7 KiB
SQL

-- Hourly rollup table for `task_usage`, materialised in **UTC**. Replaces
-- both per-runtime `task_usage_daily` (073, 082) and per-workspace
-- `task_usage_dashboard_daily` (084) as the single source of truth for
-- all token-usage reports.
--
-- WHY HOURLY + UTC:
-- The two existing rollups materialise on a `DATE` bucket — one in the
-- runtime's IANA tz, the other in UTC — which forces every report to
-- either accept the materialised tz or scan raw `task_usage`. Hourly
-- UTC buckets are tz-neutral: any viewer-side tz can be applied at
-- query time via `DATE(bucket_hour AT TIME ZONE @tz)` without losing
-- precision and without crossing midnight in the wrong direction.
--
-- WHY ONE TABLE INSTEAD OF TWO:
-- The two existing rollups share the same source rows and the same
-- invalidation surface (atq, task_usage, issue.project_id); maintaining
-- them separately is duplicative. The unified PK carries runtime_id,
-- agent_id, AND project_id, so:
-- * Runtime-detail views filter on runtime_id (covered by
-- idx_..._runtime_time).
-- * Workspace-dashboard views filter on workspace_id + group by
-- agent_id / project_id (covered by the three workspace indexes).
-- * The hour-of-day heatmap groups by EXTRACT(HOUR FROM ... AT TIME
-- ZONE <viewer's tz>) over the same rows — no separate aggregate.
--
-- WHY PROVIDER+MODEL IN THE PK:
-- Per-model breakdowns are a primary read dimension (cost per model,
-- trend per model). Keeping them in the PK keeps the rollup pre-grouped
-- along the same axis the UI uses.
--
-- WHY `UNIQUE NULLS NOT DISTINCT`:
-- `project_id` is nullable — tasks linked to issues without a project,
-- and the quick-create path's "no issue yet" state, both produce
-- no-project usage. PG15's `UNIQUE NULLS NOT DISTINCT` lets ON CONFLICT
-- upsert the no-project bucket the same way it handles a concrete
-- project. (Same pattern as 084.)
CREATE TABLE task_usage_hourly (
bucket_hour TIMESTAMPTZ NOT NULL, -- UTC, truncated to hour boundary
workspace_id UUID NOT NULL,
runtime_id UUID NOT NULL,
agent_id UUID NOT NULL,
project_id UUID, -- nullable; see above
provider TEXT NOT NULL,
model TEXT NOT NULL,
input_tokens BIGINT NOT NULL DEFAULT 0,
output_tokens BIGINT NOT NULL DEFAULT 0,
cache_read_tokens BIGINT NOT NULL DEFAULT 0,
cache_write_tokens BIGINT NOT NULL DEFAULT 0,
task_count BIGINT NOT NULL DEFAULT 0,
event_count BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_task_usage_hourly_key
UNIQUE NULLS NOT DISTINCT
(bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
);
-- Workspace-wide trend (no other filter): /{slug}/dashboard. The leading
-- workspace_id matches every dashboard query; bucket_hour DESC avoids an
-- extra sort when the report walks "last 7/30/90 days" backwards.
CREATE INDEX idx_task_usage_hourly_workspace_time
ON task_usage_hourly (workspace_id, bucket_hour DESC);
-- Runtime detail page — trend + hour-of-day heatmap on a single runtime.
-- The heatmap groups by `EXTRACT(HOUR FROM bucket_hour AT TIME ZONE
-- <viewer's tz>)` over this range, so we want the rows pre-clustered
-- by runtime.
CREATE INDEX idx_task_usage_hourly_runtime_time
ON task_usage_hourly (runtime_id, bucket_hour DESC);
-- Workspace dashboard "by agent" panel.
CREATE INDEX idx_task_usage_hourly_workspace_agent_time
ON task_usage_hourly (workspace_id, agent_id, bucket_hour DESC);
-- Workspace dashboard "by project" panel. Partial because no-project
-- buckets aggregate into a separate bucket and the panel filters them
-- out; this keeps the index small.
CREATE INDEX idx_task_usage_hourly_workspace_project_time
ON task_usage_hourly (workspace_id, project_id, bucket_hour DESC)
WHERE project_id IS NOT NULL;
-- Single-row state table tracking the rollup worker's watermark. Same
-- shape as 073's `task_usage_rollup_state` and 084's
-- `task_usage_dashboard_rollup_state` — a SMALLINT(1) PK is the easiest
-- way to enforce "exactly one row" without a CHECK trigger.
CREATE TABLE task_usage_hourly_rollup_state (
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
watermark_at TIMESTAMPTZ NOT NULL DEFAULT '1970-01-01 00:00:00+00',
last_run_started_at TIMESTAMPTZ,
last_run_finished_at TIMESTAMPTZ,
last_run_rows BIGINT NOT NULL DEFAULT 0,
last_error TEXT
);
INSERT INTO task_usage_hourly_rollup_state (id) VALUES (1) ON CONFLICT DO NOTHING;
-- Dirty queue for invalidations the `updated_at` watermark cannot see:
-- * DELETE on `task_usage` (no row left for the watermark to catch).
-- * Cascade DELETE through `agent_task_queue` (task_usage rows gone).
-- * UPDATE of `issue.project_id` — moves the bucket to a new key,
-- OLD bucket needs to shrink, NEW bucket needs to appear.
-- * UPDATE of `agent_task_queue.runtime_id` / `agent_task_queue.issue_id`
-- — same re-attribution problem on different dimensions.
--
-- bucket_hour is computed in UTC at trigger time, so dirty keys match
-- the rollup table byte-for-byte and the window function can UNION the
-- queue into `dirty_keys` without translation.
--
-- TTL: rows in this queue MUST be pruned (see prune_task_usage_hourly_dirty
-- in the rollup-pipeline migration). Without TTL, dense workloads grow the queue
-- unboundedly — every retouched
-- bucket leaves a row behind. The window function deletes rows whose
-- enqueued_at < p_to as part of each tick, which keeps the steady state
-- bounded; the explicit prune is a belt-and-braces guarantee for rows
-- that somehow escape the window (e.g. crash mid-tick).
CREATE TABLE task_usage_hourly_dirty (
bucket_hour TIMESTAMPTZ NOT NULL,
workspace_id UUID NOT NULL,
runtime_id UUID NOT NULL,
agent_id UUID NOT NULL,
project_id UUID,
provider TEXT NOT NULL,
model TEXT NOT NULL,
enqueued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_task_usage_hourly_dirty_key
UNIQUE NULLS NOT DISTINCT
(bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
);
-- The window function drains rows with enqueued_at < p_to; the prune
-- helper (prune_task_usage_hourly_dirty) deletes rows
-- whose enqueued_at falls outside the retention horizon. Both scans
-- use this index.
CREATE INDEX idx_task_usage_hourly_dirty_enqueued_at
ON task_usage_hourly_dirty (enqueued_at);