From fdd6aa5456fdc5638245f08e2b78ac9c6129c398 Mon Sep 17 00:00:00 2001 From: rithviknishad Date: Sun, 22 Nov 2026 15:59:07 +0530 Subject: [PATCH 1/3] Replace the docs agents with the local Ezhuthachan skill. The product team runs it in their own IDE chat, so the GitHub agentic workflows and the old agent files are no longer needed. Co-authored-by: Cursor --- .claude/skills/ezhuthachan/SKILL.md | 121 ++ .../assets/recording/example.demo.ts | 33 + .../ezhuthachan/assets/recording/kit.ts | 160 ++ .../assets/recording/login.setup.ts | 21 + .../assets/recording/playwright.config.ts | 47 + .../ezhuthachan/assets/recording/pointer.ts | 207 ++ .../ezhuthachan/references/existing-docs.md | 77 + .../skills/ezhuthachan/references/issues.md | 51 + .../skills/ezhuthachan/references/media.md | 186 ++ .../ezhuthachan/references/permissions.md | 115 + .../skills/ezhuthachan/references/probes.md | 34 + .../ezhuthachan/references/publishing.md | 139 ++ .../ezhuthachan/references/questions.md | 115 + .../skills/ezhuthachan/references/research.md | 160 ++ .../skills/ezhuthachan/references/setup.md | 254 +++ .../skills/ezhuthachan/references/writing.md | 141 ++ .github/agents/agentic-workflows.md | 233 -- .github/agents/care-code-fixer.agent.md | 77 - .github/agents/care-docs-recorder.agent.md | 87 - .github/agents/care-docs-researcher.agent.md | 67 - .github/agents/care-docs-reviewer.agent.md | 72 - .github/agents/care-docs-writer.agent.md | 76 - .github/agents/docs-pr-reviewer.agent.md | 45 - .github/agents/ezhuthachan.agent.md | 173 -- .../agents/references/codebase-navigation.md | 178 -- .github/agents/references/flow-recording.md | 256 --- .github/aw/actions-lock.json | 19 - .github/skills/agentic-workflows/SKILL.md | 104 - .github/workflows/agentics-maintenance.yml | 633 ------ .github/workflows/daily-doc-updater.lock.yml | 1706 --------------- .github/workflows/daily-doc-updater.md | 202 -- .github/workflows/docs-reviewer.lock.yml | 1663 -------------- .github/workflows/docs-reviewer.md | 132 -- .github/workflows/ezhuthachan.lock.yml | 1929 ----------------- .github/workflows/ezhuthachan.md | 380 ---- 35 files changed, 1861 insertions(+), 8032 deletions(-) create mode 100644 .claude/skills/ezhuthachan/SKILL.md create mode 100644 .claude/skills/ezhuthachan/assets/recording/example.demo.ts create mode 100644 .claude/skills/ezhuthachan/assets/recording/kit.ts create mode 100644 .claude/skills/ezhuthachan/assets/recording/login.setup.ts create mode 100644 .claude/skills/ezhuthachan/assets/recording/playwright.config.ts create mode 100644 .claude/skills/ezhuthachan/assets/recording/pointer.ts create mode 100644 .claude/skills/ezhuthachan/references/existing-docs.md create mode 100644 .claude/skills/ezhuthachan/references/issues.md create mode 100644 .claude/skills/ezhuthachan/references/media.md create mode 100644 .claude/skills/ezhuthachan/references/permissions.md create mode 100644 .claude/skills/ezhuthachan/references/probes.md create mode 100644 .claude/skills/ezhuthachan/references/publishing.md create mode 100644 .claude/skills/ezhuthachan/references/questions.md create mode 100644 .claude/skills/ezhuthachan/references/research.md create mode 100644 .claude/skills/ezhuthachan/references/setup.md create mode 100644 .claude/skills/ezhuthachan/references/writing.md delete mode 100644 .github/agents/agentic-workflows.md delete mode 100644 .github/agents/care-code-fixer.agent.md delete mode 100644 .github/agents/care-docs-recorder.agent.md delete mode 100644 .github/agents/care-docs-researcher.agent.md delete mode 100644 .github/agents/care-docs-reviewer.agent.md delete mode 100644 .github/agents/care-docs-writer.agent.md delete mode 100644 .github/agents/docs-pr-reviewer.agent.md delete mode 100644 .github/agents/ezhuthachan.agent.md delete mode 100644 .github/agents/references/codebase-navigation.md delete mode 100644 .github/agents/references/flow-recording.md delete mode 100644 .github/aw/actions-lock.json delete mode 100644 .github/skills/agentic-workflows/SKILL.md delete mode 100644 .github/workflows/agentics-maintenance.yml delete mode 100644 .github/workflows/daily-doc-updater.lock.yml delete mode 100644 .github/workflows/daily-doc-updater.md delete mode 100644 .github/workflows/docs-reviewer.lock.yml delete mode 100644 .github/workflows/docs-reviewer.md delete mode 100644 .github/workflows/ezhuthachan.lock.yml delete mode 100644 .github/workflows/ezhuthachan.md diff --git a/.claude/skills/ezhuthachan/SKILL.md b/.claude/skills/ezhuthachan/SKILL.md new file mode 100644 index 00000000..6ee055c0 --- /dev/null +++ b/.claude/skills/ezhuthachan/SKILL.md @@ -0,0 +1,121 @@ +--- +name: ezhuthachan +description: Researches the Care codebases and writes user-facing documentation for a Care module (concept pages, task flows, annotated screenshots, demo videos), delivered as a pull request to the Care docs site. Use when someone asks to document a Care module or feature, generate or update Care docs, record a flow, fact-check an existing Care doc against the code, find docs that went stale, or continue an earlier Ezhuthachan session. +--- + +# Ezhuthachan + +You write the user-facing documentation for Care, the open-source hospital system from the Open Healthcare Network. Someone on the Care product team names a module ("generate documentation for the workspace module"), and you take it from that sentence to a pull request on the docs site: research, questions, pages, screenshots and videos. + +Everything is done by you, in the conversation, with ordinary tools: a shell, git, file reads and edits, and a browser driver when media is wanted. There is no separate program to install. The files in `references/` tell you how to do each part, and `assets/recording/` holds the helpers for recordings. + +You are normally started inside the docs repository, `ohcnetwork/docs`, which is the site at docs.ohc.network. This skill lives there, at `.claude/skills/ezhuthachan/`, next to the other docs skills. Run it in the local IDE chat. There is no GitHub agentic workflow for it. + +## Who this is for + +Two groups matter, and they are different people. + +The person talking to you is on the product team. They know Care as a product, often better than the code does. They may not be an engineer, so do the git and tooling work yourself and say what you did in plain words. Be good company: say where you are in the work, bring them decisions and not chores, and make your questions easy to answer. + +The people who read what you write are doctors, nurses, front-desk staff and facility administrators using Care at work. If a page tells a nurse she can do something her role cannot do, or names a button that is not there, she loses time on a ward and stops trusting the docs. + +A superuser is not one of those readers. Do not write a procedure, a variant, or a permission row for something only a superuser can do, and do not describe what a superuser sees. Leave that screen out of the plan. If the exception looks like a bug, file it. The page stays with what a product user can do. + +## The one rule + +Never write something you have not verified. When you cannot verify it, ask. + +This outranks speed, completeness and politeness. A page with a gap and an open question is a good result. A fluent page with one invented detail is a bad one, because nobody can tell which detail it is. The team has said plainly that many questions are welcome and wrong information is not. + +Three things count as verified: + +- **Code.** You read it in the checkout pinned for this session, and you can cite the file and lines. +- **Runtime.** You saw it in a running Care instance the user approved, and you kept the screenshot or the response. +- **Human.** A named person told you, in this session or in a recorded standing answer. + +Everything else is a lead to follow up, not evidence: your own memory of Care, an older docs page, a file in the user's working clone, what similar modules do, what the name of a function suggests. When two kinds of evidence disagree, that is a question for the user, and usually a product bug worth reporting. + +## How a session runs + +Work through the stages in order. Read the reference for a stage when you reach it; each one is written to be read at that moment. + +| Stage | What happens | Read | +| --- | --- | --- | +| 1. Set up | Open the state folder, read memory, start or resume a session, see what the machine has | `references/setup.md` | +| 2. Intake | Ask which Care version, which branches, how to get the code, which pages and media. Pin the code to exact commits. Check that the module exists there. See which pages the site already has | `references/setup.md`, `references/existing-docs.md` | +| 3. Research | Read the pinned code and the existing pages. Record facts with their evidence. Find the user tasks. Trace the permission path of each. Probe what a run can settle, and file what you find | `references/research.md`, `references/permissions.md`, `references/probes.md`, `references/issues.md`, `references/existing-docs.md` | +| 4. Confirm | Show the proposed pages and every open question. Wait for the user | `references/questions.md` | +| 5. Write | Draft each page from confirmed facts only, then review it with fresh eyes | `references/writing.md` | +| 6. Media | If wanted: agree on an environment, record the flows, take screenshots, confirm permissions at runtime | `references/media.md` | +| 7. Publish | Place the pages in a docs checkout, pass the build, open a pull request | `references/publishing.md` | +| 8. Wrap up | Report, propose what to remember, close the session | below | + +Four points need the user's go-ahead before you continue: the version and commits (stage 2), the page list (stage 4), the environment for media (stage 6), and opening the pull request (stage 7). Between those points, keep working without asking for permission to proceed. + +Say where you are whenever the stage changes, in one line: "Research is done. 7 flows proposed, 4 questions open. Moving to confirm." + +Other ways in: + +- **"Continue" or "pick up where we left off".** Resume the session; see `references/setup.md`. +- **"Redo flow 3, the second step is wrong."** One page is redone without touching the rest; see `references/writing.md`. +- **"Check this page against the code."** See "Verify an existing page" in `references/publishing.md`. +- **"What went stale?"** See "Drift" in `references/publishing.md`. + +## State on disk + +Everything that must survive the conversation lives in one folder, so a session can continue after a context reset, on another day, or in a different tool. + +```text +~/.ezhuthachan/ + memory.md capped at 200 lines; preferences, version-to-branch map, standing answers + answers/ standing answers for one module, read only when that module is the subject + personas.md the invented people used in every recording + repos/ one shared mirror per repository + provenance/ what each published page was built from + locks/ which session is recording against which environment + sessions// + session.md stage, version, pinned commits, environment, log + src/ the code, pinned to those commits + facts.md every fact with its evidence, numbered E1, E2, ... + plan.md the pages, in order; the user can edit it + questions.md open and answered questions; the user can answer in the file + terms.md the one word used for each thing + drafts/ one file per page + probes/ scripts you wrote to check a fact, and their output + issues/ the GitHub issue bodies you filed + media/ recording specs and their output + report.md what was written, what was left out, findings and their issue links +``` + +Keep `session.md` current. Update it at every stage change and whenever something is decided. It is the only thing a later you will have. + +## Rules that hold throughout + +- **The user's own clones are read-only to you.** Never check out, switch, stash, pull, fetch or commit in them. People are in the middle of other work there. +- **Documentation is written only in the docs repository.** You may also edit this skill, in the copy you were started from. You never commit or push to `care` or `care_fe`. A finding becomes a GitHub issue, as `references/issues.md` describes. You fix product code only when the user asks, and then in a separate checkout. +- **The backend decides what a page says.** When the frontend and the backend disagree, document the backend and file the disagreement. Ask the user only when the backend itself can be read two ways. +- **Patient data.** Do not open, record or screenshot a Care instance until a person confirms it holds no real patient data. Whatever is on screen stays in the image forever. +- **Credentials.** Ask for them when needed and pass them as environment variables. Never write them into memory, a session file or a spec. +- **Scope.** Document the module you were asked for. Note what you notice about neighbours; do not write their pages. +- **Memory is for preferences and decisions.** It can tell you how this person likes to work or what a product owner decided. It can never tell you what the code does today. + +## Working in different tools + +- **Keep this conversation small.** Research, probing, issue filing, writing and review happen in subagents. This conversation keeps the stage, the decisions, and the short conclusion of each subagent. It does not keep file listings, script output, draft text or a researcher's notes. Hand a subagent the session folder and the reference it needs, and ask it to write its results into the session and return a summary. +- **Subagents.** Where your tool has them: one researcher for the backend and one for the frontend, in parallel; one for probes; one for filing issues; one writer per page; a reviewer that starts with no knowledge of the drafts. Where it does not, do the same work in sequence, and review only after all drafts are finished. A subagent that only reads code returns facts. One that can run commands does the probes and the `gh` calls. +- **Questions.** Use your tool's structured question prompt when it has one. Otherwise ask numbered questions in chat. +- **Sandboxes.** The state folder is outside the project folder. If your tool blocks writes there, ask the user once to allow `~/.ezhuthachan`. Checking out Care creates `.cursor/` and `.vscode/` folders, which some sandboxes refuse; run that command with full permissions. +- **Shell.** The recipes are written for a POSIX shell. On Windows, use Git Bash or WSL. + +## The skill changes when a lesson is worth sharing + +Personal preferences stay in `memory.md`. A lesson that would help anyone on the team goes into this skill: a path in the code map that has moved, a lookup that failed, a convention the site no longer follows, a rule the user stated for every module. + +Edit the skill in the copy you were started from. Put the edit in the pull request you are already opening, in its own commit, and say in the pull request body what the skill learned. If there is no documentation pull request, ask once and open one for the skill. Do not put a fact about one module's current code, a credential, or one person's preference into the skill. + +## Wrap up + +1. Write `report.md`: the pages written and where they went, what you left out and why, questions still open, the pinned commits, and the findings with their issue links. +2. Tell the user the same thing in a few lines, with the pull request link first. +3. Propose what to remember. Show the exact lines you would add to memory and add only what they approve. See "Memory" in `references/setup.md`. +4. Mark the session done in `session.md`. Offer to remove the checkouts of sessions closed more than 14 days ago. diff --git a/.claude/skills/ezhuthachan/assets/recording/example.demo.ts b/.claude/skills/ezhuthachan/assets/recording/example.demo.ts new file mode 100644 index 00000000..28f04a34 --- /dev/null +++ b/.claude/skills/ezhuthachan/assets/recording/example.demo.ts @@ -0,0 +1,33 @@ +import { expect, test } from "@playwright/test"; + +import { startRecording, t } from "./kit"; + +// Shape of a flow recording. Copy this file to .demo.ts and replace the body. +// The label keys and the URL below are placeholders: take the real ones from your facts. +// +// - The name passed to startRecording is the flow slug. Every output file starts with it. +// - Each step title is the step heading from the flow page, word for word. The captions and +// the written page then say the same thing. +// - Find elements by translation key with t(), never by typed-in English text. +// - One page.goto, at the start. After that, reach every screen the way a person does. +test("Create a workspace", async ({ page }) => { + const rec = await startRecording(page, "create-a-workspace"); + const { pointer } = rec; + + await rec.step("1. Open the workspace list", async () => { + await page.goto("/facility/FACILITY_ID/settings/workspaces"); + const create = page.getByRole("button", { name: t("create_workspace") }); + await expect(create).toBeVisible(); + await pointer.reset(); + await rec.shot({ highlight: create }); + await pointer.click(create); + }); + + await rec.step("2. Name the workspace", async () => { + const name = page.getByLabel(t("name")); + await pointer.type(name, "Ward round"); + await rec.shot({ highlight: name }); + }); + + await rec.finish(); +}); diff --git a/.claude/skills/ezhuthachan/assets/recording/kit.ts b/.claude/skills/ezhuthachan/assets/recording/kit.ts new file mode 100644 index 00000000..a8350a22 --- /dev/null +++ b/.claude/skills/ezhuthachan/assets/recording/kit.ts @@ -0,0 +1,160 @@ +// Recording kit for Ezhuthachan flow recordings. +// +// One recording run of a flow produces, in the output folder: +// .mp4 the demo video (H.264, plays in every browser) +// .poster.png the poster frame for the video +// .vtt captions, one cue per step, kept outside the video so they can be translated +// .api.json every API call the flow made, used to confirm the permission path +// -.png step screenshots, with the target outlined +// +// Settings come from environment variables so the same spec runs against any environment: +// EZ_FE_URL frontend URL (read by playwright.config.ts) +// EZ_API_URL backend URL; API calls are recognised by this prefix +// EZ_LOCALE_FILE path to the locale file in the pinned care_fe checkout, e.g. .../public/locale/en.json +// EZ_OUT output folder (default ./out) +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { test, type Locator, type Page } from "@playwright/test"; + +import { installCursor, Pointer } from "./pointer"; + +export const OUT = path.resolve(process.env.EZ_OUT ?? "out"); +const API_URL = (process.env.EZ_API_URL ?? "").replace(/\/+$/, ""); + +// ---------------------------------------------------------------- labels + +let labels: Record | null = null; + +/** + * The text of a UI label, looked up by its translation key in the pinned locale file. + * Finding elements by key keeps the recording tied to the same source as the written page, + * and lets the same spec record in another language by pointing EZ_LOCALE_FILE at it. + * An unknown key throws, so a wrong label fails loudly instead of recording the wrong thing. + */ +export function t(key: string, vars: Record = {}): string { + if (!labels) { + const file = process.env.EZ_LOCALE_FILE; + if (!file) throw new Error("EZ_LOCALE_FILE is not set. Point it at public/locale/en.json in the pinned care_fe checkout."); + labels = JSON.parse(fs.readFileSync(file, "utf8")) as Record; + } + const value = labels[key]; + if (value === undefined) throw new Error(`No label with key "${key}" in ${process.env.EZ_LOCALE_FILE}. Check the key against the pinned commit.`); + return value.replace(/\{\{\s*(\w+)\s*\}\}/g, (whole, name: string) => (name in vars ? String(vars[name]) : whole)); +} + +// ---------------------------------------------------------------- recording + +type ApiCall = { method: string; path: string; status: number; count: number }; +type Cue = { from: number; to: number; title: string }; + +const ID_SEGMENT = /\/(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\d+)(?=\/|$)/gi; + +function ffmpeg(args: string[]): void { + try { + execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args]); + } catch (error) { + const reason = (error as { code?: string }).code === "ENOENT" ? "ffmpeg is not installed" : String((error as Error).message); + throw new Error(`ffmpeg failed: ${reason}`); + } +} + +const vttTime = (ms: number) => { + const pad = (n: number, width = 2) => String(Math.floor(n)).padStart(width, "0"); + return `${pad(ms / 3600000)}:${pad((ms / 60000) % 60)}:${pad((ms / 1000) % 60)}.${pad(ms % 1000, 3)}`; +}; + +export class Recording { + readonly pointer: Pointer; + private readonly startedAt = Date.now(); + private readonly cues: Cue[] = []; + private readonly calls = new Map(); + private shots = 0; + + constructor( + private readonly page: Page, + private readonly name: string, + ) { + this.pointer = new Pointer(page); + page.on("response", (response) => { + const url = response.url(); + // The frontend and the API can share an origin, so the /api/v/ path decides, not the host alone. + if ((API_URL && !url.startsWith(API_URL)) || !/\/api\/v\d+\//.test(url)) return; + const method = response.request().method(); + if (method === "OPTIONS") return; + const pathname = new URL(url).pathname.replace(ID_SEGMENT, "/{id}"); + const key = `${method} ${pathname} ${response.status()}`; + const seen = this.calls.get(key); + if (seen) seen.count += 1; + else this.calls.set(key, { method, path: pathname, status: response.status(), count: 1 }); + }); + } + + /** One step of the flow. Use the step heading from the flow page as the title, word for word. */ + async step(title: string, body: () => Promise): Promise { + const from = Date.now() - this.startedAt; + await test.step(title, body); + this.cues.push({ from, to: Date.now() - this.startedAt, title }); + } + + /** + * A screenshot of the page as it is now. The outline around `highlight` is drawn onto the image + * afterwards, so nothing extra ever appears on screen or in the video. + */ + async shot(options: { highlight?: Locator; name?: string } = {}): Promise { + fs.mkdirSync(OUT, { recursive: true }); + this.shots += 1; + const file = path.join(OUT, `${options.name ?? `${this.name}-${this.shots}`}.png`); + const box = options.highlight ? await options.highlight.boundingBox() : null; + if (options.highlight && !box) throw new Error(`The element to highlight is not visible (${file}).`); + await this.page.screenshot({ path: file }); + if (box) { + const scale = await this.page.evaluate(() => window.devicePixelRatio); + const pad = 6; + const [x, y, w, h] = [box.x - pad, box.y - pad, box.width + pad * 2, box.height + pad * 2].map((v) => Math.max(0, Math.round(v * scale))); + const outlined = `${file}.tmp.png`; + ffmpeg(["-i", file, "-vf", `drawbox=x=${x}:y=${y}:w=${w}:h=${h}:color=0x2563EB:t=${Math.round(3 * scale)}`, "-frames:v", "1", "-update", "1", outlined]); + fs.renameSync(outlined, file); + } + return file; + } + + /** Holds the final screen, then writes the video, poster, captions and API log. */ + async finish(holdMs = 2500): Promise { + await this.page.waitForTimeout(holdMs); + const video = this.page.video(); + await this.page.close(); + fs.mkdirSync(OUT, { recursive: true }); + const base = path.join(OUT, this.name); + + fs.writeFileSync(`${base}.api.json`, `${JSON.stringify([...this.calls.values()], null, 2)}\n`); + fs.writeFileSync( + `${base}.vtt`, + `WEBVTT\n\n${this.cues.map((cue, i) => `${i + 1}\n${vttTime(cue.from)} --> ${vttTime(cue.to)}\n${cue.title}\n`).join("\n")}`, + ); + + // Video is off in a screenshots-only run. + if (!video) return; + const webm = `${base}.webm`; + await video.saveAs(webm); + // yuv420p is required by Safari and QuickTime. A constant 30 fps removes the stutter of + // Playwright's variable frame rate. faststart lets playback begin before the download ends. + ffmpeg(["-i", webm, "-vf", "fps=30", "-c:v", "libx264", "-profile:v", "high", "-pix_fmt", "yuv420p", "-crf", "22", "-preset", "slow", "-movflags", "+faststart", "-an", `${base}.mp4`]); + const duration = Number( + execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", `${base}.mp4`]).toString().trim(), + ); + // Early frames are loading skeletons, so take the poster from later in the clip. + ffmpeg(["-ss", (duration * 0.6).toFixed(2), "-i", `${base}.mp4`, "-frames:v", "1", "-update", "1", `${base}.poster.png`]); + fs.rmSync(webm); + } +} + +/** + * Call this first in a spec, before any navigation: the cursor overlay has to be installed + * before the first page loads, or the video has no visible cursor. + */ +export async function startRecording(page: Page, name: string): Promise { + await installCursor(page); + return new Recording(page, name); +} diff --git a/.claude/skills/ezhuthachan/assets/recording/login.setup.ts b/.claude/skills/ezhuthachan/assets/recording/login.setup.ts new file mode 100644 index 00000000..febc07a1 --- /dev/null +++ b/.claude/skills/ezhuthachan/assets/recording/login.setup.ts @@ -0,0 +1,21 @@ +import { test as setup } from "@playwright/test"; + +// Signs in through the login page and saves the session for the flow recordings. +// Credentials come from the environment and are never written to a file: +// EZ_USERNAME, EZ_PASSWORD +// +// The selectors below mirror tests/setup/auth.setup.ts in care_fe as of November 2026. +// Compare them with that file in the pinned checkout before the first run, and follow it if it differs. +setup("sign in", async ({ page }) => { + const username = process.env.EZ_USERNAME; + const password = process.env.EZ_PASSWORD; + if (!username || !password) throw new Error("Set EZ_USERNAME and EZ_PASSWORD for the account the user gave you."); + + await page.goto("/login"); + await page.getByRole("textbox", { name: /username/i }).fill(username); + await page.getByLabel(/^password$/i).fill(password); + await page.getByRole("button", { name: /^sign in$/i }).click(); + await page.waitForURL((url) => !url.pathname.includes("login"), { timeout: 20_000 }); + + await page.context().storageState({ path: ".auth/user.json" }); +}); diff --git a/.claude/skills/ezhuthachan/assets/recording/playwright.config.ts b/.claude/skills/ezhuthachan/assets/recording/playwright.config.ts new file mode 100644 index 00000000..f1aea0ff --- /dev/null +++ b/.claude/skills/ezhuthachan/assets/recording/playwright.config.ts @@ -0,0 +1,47 @@ +import fs from "node:fs"; + +import { defineConfig, devices } from "@playwright/test"; + +// Every setting that differs between environments comes from the environment, so the same +// specs record against a local stack or a provisioned instance without edits. +const feUrl = process.env.EZ_FE_URL; +if (!feUrl) throw new Error("EZ_FE_URL is not set. Set it to the frontend URL of the environment the user approved."); + +const AUTH = ".auth/user.json"; +// EZ_SHOTS_ONLY=1 takes the screenshots without recording video, which is much faster. +const video = process.env.EZ_SHOTS_ONLY ? "off" : { mode: "on" as const, size: { width: 1440, height: 900 } }; + +export default defineConfig({ + testDir: ".", + timeout: 180_000, + // One at a time by default. Recordings share one application and one database, and video + // capture drops frames under load. Raise EZ_WORKERS only when every flow creates its own data. + workers: Number(process.env.EZ_WORKERS ?? 1), + fullyParallel: false, + retries: 0, + reporter: "list", + outputDir: "./test-results", + use: { + ...devices["Desktop Chrome"], + baseURL: feUrl, + // 16:10. The video size must equal the viewport: Playwright captures the viewport at CSS + // pixel size and pads a larger frame with grey instead of sharpening it. + viewport: { width: 1440, height: 900 }, + deviceScaleFactor: 2, + video, + // No slowMo: it would delay every step of an eased mouse path. The pointer helper sets the pace. + navigationTimeout: 30_000, + actionTimeout: 15_000, + }, + projects: [ + { name: "login", testMatch: /login\.setup\.ts/ }, + { + name: "flows", + testMatch: /.*\.demo\.ts/, + // The example is a template with placeholder keys, never a flow to run. + testIgnore: /example\.demo\.ts/, + dependencies: ["login"], + use: { storageState: fs.existsSync(AUTH) ? AUTH : undefined }, + }, + ], +}); diff --git a/.claude/skills/ezhuthachan/assets/recording/pointer.ts b/.claude/skills/ezhuthachan/assets/recording/pointer.ts new file mode 100644 index 00000000..953c2b70 --- /dev/null +++ b/.claude/skills/ezhuthachan/assets/recording/pointer.ts @@ -0,0 +1,207 @@ +import type { Locator, Page } from "@playwright/test"; + +// Playwright never renders the OS cursor into the video, so draw a synthetic one that +// follows the real input events and reacts to clicks. +function cursorOverlay(): void { + const ID = "__demo_cursor__"; + + // Init scripts run at document-start, when documentElement may not exist yet, so + // every DOM touch has to be lazy. + const ensure = (): HTMLElement | null => { + const root = document.documentElement; + if (!root) return null; + + if (!document.getElementById("__demo_cursor_style__")) { + const style = document.createElement("style"); + style.id = "__demo_cursor_style__"; + style.textContent = `@keyframes __demo_ripple__ { + from { transform: translate(-50%,-50%) scale(.3); opacity:.55; } + to { transform: translate(-50%,-50%) scale(1); opacity:0; } + }`; + root.appendChild(style); + } + + let el = document.getElementById(ID); + if (el) return el; + + el = document.createElement("div"); + el.id = ID; + el.setAttribute( + "style", + [ + "position:fixed", + "top:0", + "left:0", + "width:24px", + "height:24px", + "z-index:2147483647", + "pointer-events:none", + "will-change:transform", + "transform:translate(-100px,-100px)", + ].join(";"), + ); + el.innerHTML = ` + + + `; + root.appendChild(el); + return el; + }; + + addEventListener( + "mousemove", + (e) => { + const el = ensure(); + if (el) el.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`; + }, + true, + ); + + addEventListener( + "mousedown", + (e) => { + const root = document.documentElement; + if (!root) return; + ensure(); + const ring = document.createElement("div"); + ring.setAttribute( + "style", + [ + "position:fixed", + `left:${e.clientX}px`, + `top:${e.clientY}px`, + "width:44px", + "height:44px", + "border-radius:50%", + "background:rgba(37,99,235,.35)", + "border:2px solid rgba(37,99,235,.9)", + "z-index:2147483646", + "pointer-events:none", + "animation:__demo_ripple__ .45s ease-out forwards", + ].join(";"), + ); + root.appendChild(ring); + setTimeout(() => ring.remove(), 500); + }, + true, + ); +} + +export const installCursor = (page: Page) => page.addInitScript(cursorOverlay); + +const easeInOutCubic = (t: number) => + t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; + +/** Moves the mouse along eased paths so the recording looks hand-driven. */ +export class Pointer { + private x = 0; + private y = 0; + + constructor(private readonly page: Page) {} + + async reset(): Promise { + const vp = this.page.viewportSize(); + this.x = (vp?.width ?? 1440) / 2; + this.y = (vp?.height ?? 900) * 0.8; + await this.page.mouse.move(this.x, this.y); + } + + /** Scrolls with animation and waits for it to settle, so the frame never jumps. */ + private async smoothScrollIntoView(target: Locator): Promise { + const offscreen = await target.evaluate((el) => { + const r = el.getBoundingClientRect(); + const margin = 32; + return ( + r.top < margin || + r.bottom > window.innerHeight - margin || + r.left < margin || + r.right > window.innerWidth - margin + ); + }); + if (!offscreen) return; + + await target.evaluate((el) => + el.scrollIntoView({ + behavior: "smooth", + block: "center", + inline: "center", + }), + ); + + // Poll until the element stops moving rather than guessing a duration. + let previous = Number.NaN; + for (let i = 0; i < 40; i += 1) { + const box = await target.boundingBox(); + const y = box?.y ?? 0; + if (Math.abs(y - previous) < 0.5) return; + previous = y; + await this.page.waitForTimeout(50); + } + } + + async moveTo(target: Locator, durationMs = 700): Promise { + await this.smoothScrollIntoView(target); + const box = await target.boundingBox(); + if (!box) throw new Error("Cannot move to a target with no bounding box."); + + const toX = box.x + box.width / 2; + const toY = box.y + box.height / 2; + const fromX = this.x; + const fromY = this.y; + + const steps = Math.max(24, Math.round(durationMs / 16)); + for (let i = 1; i <= steps; i += 1) { + const t = easeInOutCubic(i / steps); + await this.page.mouse.move( + fromX + (toX - fromX) * t, + fromY + (toY - fromY) * t, + ); + await this.page.waitForTimeout(durationMs / steps); + } + + this.x = toX; + this.y = toY; + } + + async click(target: Locator, durationMs = 700): Promise { + await this.moveTo(target, durationMs); + // Small settle so the viewer sees the cursor land before it presses. + await this.page.waitForTimeout(180); + await this.page.mouse.down(); + await this.page.waitForTimeout(110); + await this.page.mouse.up(); + } + + /** + * Clicks the field, then types one character at a time with jittered delays, so the + * text appears the way a person types it instead of landing in a single frame. + */ + async type( + target: Locator, + text: string, + options: { clear?: boolean; delayMs?: number } = {}, + ): Promise { + const { clear = false, delayMs = 45 } = options; + + await this.click(target); + await this.page.waitForTimeout(150); + + if (clear) { + await this.page.keyboard.press("ControlOrMeta+A"); + await this.page.waitForTimeout(120); + await this.page.keyboard.press("Backspace"); + await this.page.waitForTimeout(180); + } + + for (const character of text) { + await this.page.keyboard.type(character); + // Jitter keeps the rhythm irregular; a pause after word breaks reads as thinking. + const pause = delayMs * (0.6 + Math.random() * 0.8); + await this.page.waitForTimeout( + /[\s,.;:]/.test(character) ? pause + delayMs : pause, + ); + } + } +} diff --git a/.claude/skills/ezhuthachan/references/existing-docs.md b/.claude/skills/ezhuthachan/references/existing-docs.md new file mode 100644 index 00000000..8f1b29fb --- /dev/null +++ b/.claude/skills/ezhuthachan/references/existing-docs.md @@ -0,0 +1,77 @@ +# Existing docs + +Read this before you propose pages. The docs site already has a concept, a flow, or a reference for most of Care. Those pages are how you learn the words the site uses, and they are what you link to. Do not explain a neighbouring module again when a page for it exists. + +The code is still the source of truth for what Care does. An existing page can be wrong. When it disagrees with the pinned code, the code wins, the page is a lead, and you say so. + +## Where the pages are + +The site is Docusaurus. Product pages are versioned. `versions.json` lists the versions. `docusaurus.config.js` sets `lastVersion` and `includeCurrentVersion: false`, so the site the reader sees is `versioned_docs/`, not the `docs/` folder at the repository root. On 21 Nov 2026 the latest version was 3.1 and 3.0 carried an unmaintained banner. Read the config again. Do not trust this sentence over it. + +The sidebar the reader sees is `versioned_sidebars/version--sidebars.json`. The root `sidebars.js` is a leftover. Do not edit it and do not learn the site's shape from it. + +These are separate, unversioned sections. A module page does not go in them: + +| Folder | What it is | +| --- | --- | +| `contributing/` | How to contribute | +| `deployment/` | How to deploy Care | +| `deployments/hmis/`, `deployments/palliative/` | Playbooks for one deployment | +| `blog/` | Blog | + +`versioned_docs/version-/intro.mdx` is the reader's map of the four layers: concepts, flows, references, playbooks. Read it. A sentence in it can be stale. The templates in `.claude/skills/` win where they disagree. + +## Find a page + +Run this in the docs checkout. Use the session pin (`$S/src/docs`) when the session has one, so you match the commit you will publish to. If you were started inside the docs repository and there is no session pin yet, use that repository. + +```bash +V=versioned_docs/version-3.1 # the version you are writing +find "$V" -name '*.mdx' | grep -i encounter +grep -l -i workspace -r "$V" --include='*.mdx' +``` + +Then open the page. For the module itself, and for each thing the module touches (patient, encounter, facility, department), read: + +- its concept, if there is one +- the flow titles already listed for it +- its reference only for the terms and the links, not to copy into a concept or a flow + +Record in `plan.md` which of your pages already exist and which are new. An existing page is an update. Read it before you replace it. + +## Domains + +List the folders rather than remembering them: + +```bash +ls versioned_docs/version-3.1/concepts +ls versioned_docs/version-3.1/flows +ls versioned_docs/version-3.1/references +``` + +On 21 Nov 2026 the concept folders were `clinical`, `definitions`, `facility`, `medications`, `scheduling`, `billing`, `supply`, `access-governance` and `platform`. References also has `foundation`. Put the module beside the existing concept it most resembles, and link that concept. Read the folder's `_category_.json` for the label readers see. Ask the user only when two existing sections fit equally well. + +`.claude/skills/care-concept-doc/references/conventions.md` explains the grouping. The folders win when that file is stale. One known case: it says the versions are kept byte-identical and authored in 3.0. They are not. `publishing.md` is the rule for versions. + +## Links + +A link is a relative path with `.mdx`. From a flow at `flows///.mdx`: + +| Target | Path | +| --- | --- | +| Its concept | `../../../concepts//.mdx` | +| A sibling flow | `./other-flow.mdx` | +| A concept in another domain | `../../../concepts//.mdx` | +| A reference | `../../../references//.mdx` | + +Check the file exists before you link it. Never invent a path. + +Pages that have a Malayalam translation are linked without `.mdx`. The list is whoever has a file under `i18n/ml/docusaurus-plugin-content-docs/version-/`. List that folder. Do not trust a remembered list. On 21 Nov 2026, version 3.1 had translations for `intro`, `concepts/clinical/patient` and `references/clinical/patient` only. + +Concepts and references show up on their own: their sidebar entry is autogenerated from the folder. A flow shows up only when its id, such as `flows/clinical/encounter/create-encounter`, is in the versioned sidebar under its module. `publishing.md` says how to add one. + +## What you write, and what you link + +You write concept and flow pages into the versioned docs. You do not write a reference page unless the user asks. You do not write a playbook. If a deployment playbook already walks through this module, link it. + +Use the heading and the terms the existing page uses, where the pinned code still supports them. One term for one thing includes the pages already on the site. diff --git a/.claude/skills/ezhuthachan/references/issues.md b/.claude/skills/ezhuthachan/references/issues.md new file mode 100644 index 00000000..4eb2cf45 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/issues.md @@ -0,0 +1,51 @@ +# Product issues + +A finding from the research is filed as a GitHub issue, not left only in `report.md`. This covers suspected bugs, and every place the frontend shows, hides or allows something the backend does not. + +The backend is what a page describes. When the frontend disagrees with it, write the page from the backend and file the disagreement. Do not ask the user which side to document. Ask only when the backend itself can be read two ways. + +## File with the user's GitHub CLI + +```bash +gh auth status +``` + +They almost always have `gh` and are signed in. Use it. File the issue yourself; do not hand them a draft to paste. + +If `gh` is missing or not signed in, ask a subagent to do the filing once they have signed in. If that also fails, leave the issue text in `report.md` and tell them in one line. + +## Before you file + +Search, so you do not open a duplicate: + +```bash +gh search issues --repo ohcnetwork/care --repo ohcnetwork/care_fe "" --state open +``` + +An existing issue gets a comment with the pinned commit and the files, not a second issue. + +## Where it goes + +| Finding | Repository | +| --- | --- | +| The frontend shows, hides or mislabels something | `ohcnetwork/care_fe` | +| The backend allows, refuses or returns the wrong thing | `ohcnetwork/care` | +| The two disagree | the repository whose behaviour looks wrong, and name the other side in the body | + +```bash +gh issue create --repo ohcnetwork/care_fe --title "" --body-file "$S/issues/.md" +``` + +Write the body to `$S/issues/.md` first, so it is reviewable. It says: + +- what a user sees, in product words +- what the backend does +- the file and lines, and the pinned commit +- how sure you are, and what you have not run +- the link to the other issue when a finding needs both repositories + +Say "potential" in the title when you are sure of the behaviour and unsure it was unintended. + +## After + +Add the issue URL under the finding in `report.md`. Never put patient data, tokens or credentials in an issue. File what you actually read or ran. A finding you did not check stays in `report.md` until you have. diff --git a/.claude/skills/ezhuthachan/references/media.md b/.claude/skills/ezhuthachan/references/media.md new file mode 100644 index 00000000..0b178140 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/media.md @@ -0,0 +1,186 @@ +# Media + +Stage 6, when the user asked for screenshots or videos. A recording does three jobs at once: it produces the media, it proves the written steps can really be followed, and it shows which API calls the flow makes, which completes the permission path. + +Every recording drives a real Care instance and creates real records in it. So the first part of this stage is a conversation, not a command. + +## Agree on an environment + +People run Care in different ways, and some do not run it at all. Ask; do not pick. Offer what you saw in the setup check as context ("something is listening on ports 9000 and 4000; is that a Care you want me to use?"). + +The options: + +- **A stack you start for this session**, from the pinned checkouts, natively or in Docker, whichever they prefer. It matches the researched commit exactly, and you can reset its database. It takes the longest to set up. +- **A stack they already run locally.** +- **A provisioned instance**, a hosted Care kept for demos and testing. + +For any instance you did not start yourself, settle two things before you open it. + +**1. Which commit is it running?** If the instance runs different code from what you researched, the screenshots will contradict the text. Look at what it reports: + +```bash +curl -s https:///app_version/ # {"version": ""} when the deployment sets it; "unknown" otherwise +curl -s https:///build-meta.json # when the frontend was built; it does not say which commit +``` + +The frontend never reports its commit, and the backend does only when the deployment was built to. Whatever is missing, ask the user. If the instance differs from your pin, tell them what that means and let them decide: record anyway and accept the risk, point you at another instance, or move the pin to match the instance and re-verify the facts. + +**2. What may you do there?** Get a clear answer from a person, by name, to both of these: + +- Does this instance hold any real patient data? If yes, or if nobody can say, do not use it. +- Which data policy applies? + - **Disposable.** You may create, change and delete anything, and the database can be reset. + - **Create allowed.** You may create records, named so they are recognisable as yours. You do not change or delete anything you did not create. + - **Read only.** You save nothing. Only flows that end before a save can be recorded; say which flows that excludes. + +Also ask for an account to sign in with, and what role it has. Pass the credentials as environment variables for the run. Do not write them down anywhere. + +Write the environment into `session.md`: the kind, both URLs, the commit it runs and how you know, the data policy, and who approved it and when. At wrap-up, offer to remember the instance and its policy, never the credentials. + +### Starting a stack yourself + +Do not follow remembered commands; the repositories document how to run themselves and that changes between versions. Read these at the pinned commit and follow them: + +```text +$S/src/care/README.md and $S/src/care/Makefile +$S/src/care_fe/README.md, $S/src/care_fe/tests/README.md and $S/src/care_fe/scripts/playwright-db.sh +``` + +Before you start a service, install dependencies, or reset a database, tell the user what you are about to run and get their agreement. Installing frontend dependencies takes about 1 GB. + +One trap to check every time: the frontend decides which backend to call from its own configuration (`REACT_CARE_API_URL` in its env files, read in `care.config.ts`), and the default in the repository points at a shared hosted backend. A frontend started without changing that talks to the hosted backend, not to your local one. After signing in, confirm which backend the app is calling before you create anything. + +### One recording at a time per environment + +Two sessions recording against the same database spoil each other's data. Take a lock before recording and release it after: + +```bash +mkdir -p "$EZ/locks" && mkdir "$EZ/locks/" && echo "$ID" > "$EZ/locks//owner" +# ... record ... +rm -r "$EZ/locks/" +``` + +If `mkdir` fails, another session holds it. Read `owner`, tell the user, and wait or ask. + +## Set up the recording kit + +Copy the kit into the session and install Playwright at the version the product uses, so the two agree on browser builds: + +```bash +cp "/assets/recording/"*.ts "$S/media/" +cd "$S/media" +grep '"@playwright/test"' "$S/src/care_fe/package.json" # the version to install +npm init -y >/dev/null && npm install --save-dev @playwright/test@ +npx playwright install chromium +``` + +`ffmpeg` and `ffprobe` must be installed; the kit uses them for the video and the screenshot outlines. + +The kit takes its settings from the environment: + +```bash +export EZ_FE_URL= +export EZ_API_URL= +export EZ_LOCALE_FILE="$S/src/care_fe/public/locale/en.json" +export EZ_USERNAME= EZ_PASSWORD= +``` + +What is in the kit: + +- `kit.ts`: `startRecording(page, slug)` returns a recording with `step()`, `shot()`, `pointer` and `finish()`. `t(key)` gives the text of a label from the pinned locale file and fails on an unknown key. +- `pointer.ts`: a visible cursor that moves along eased paths, clicks with a ripple, and types at human speed. +- `login.setup.ts`: signs in through the login page. Compare its selectors with `tests/setup/auth.setup.ts` in the pinned `care_fe` before the first run. +- `playwright.config.ts`: 1440 by 900, video on, one worker. +- `example.demo.ts`: the shape of a flow spec. Its keys and URL are placeholders. + +## Write one spec per flow + +Name it `.demo.ts`. Start from `example.demo.ts`. + +**Keep the spec and the page in step.** + +- Each `rec.step()` title is the step heading from the flow page, word for word. The captions come from these titles. +- Find elements by label key with `t()`, taken from your facts. Never type the English text into the spec. The same spec can then record in another language by pointing `EZ_LOCALE_FILE` at that locale file. +- Take a screenshot at each step that a reader would want to see, with `rec.shot({ highlight: })`. + +**Record only what a person can do.** A viewer must be able to repeat everything they see. + +- One `page.goto`, at the start, to the screen where the flow begins. Reach every later screen by clicking: the sidebar, a tab, a row, a breadcrumb. +- Use `pointer.click()` and `pointer.type()`, so the cursor travels and text appears as typed. Plain `click()` and `fill()` are for setup the camera never sees. +- Never use `page.evaluate` or a direct API call to do a step of the flow. +- After typing into a search or picker, wait for the options and click one. Do not press Enter blind. +- Use only keyboard shortcuts that the page documents. + +**Own your data.** + +- Do the preparation off camera: if the flow needs a record that another flow creates, make it before the recorded page opens, in a separate browser context or through the API. +- Each flow creates what it changes. Do not rely on what another recording left behind. +- Respect the data policy. Under "create allowed", name records so they are recognisably yours. +- Use invented people, the same small cast in every recording. If `$EZ/personas.md` exists, use it. If not, propose a few clearly fictional names that suit the deployment's region, get the user's agreement, and save them there. + +**Keep it watchable.** Aim for under a minute per flow; split a longer flow into two pages. Assert only what you need in order to wait for the screen to settle. + +## Run and inspect + +```bash +npx playwright test # all flows +npx playwright test create-a-workspace # one flow +EZ_SHOTS_ONLY=1 npx playwright test # screenshots only, no video, faster +``` + +Each flow writes to `$S/media/out/`: + +| File | What it is | +| --- | --- | +| `.mp4` | The video | +| `.poster.png` | Its poster frame | +| `.vtt` | Captions, one cue per step | +| `.api.json` | The API calls the flow made, with status codes | +| `-1.png`, `-2.png`, ... | Step screenshots, with the target outlined | + +Look at the results before you call them done. Open every screenshot. Pull frames from the video at a few caption times and look at those too: + +```bash +ffmpeg -loglevel error -y -ss 4 -i out/.mp4 -frames:v 1 out/check.png +``` + +Check that the cursor is visible, the right element is outlined, nothing is half-loaded, and no real-looking personal data is on screen. + +An empty `api.json` after a flow that clearly loaded data means the app is calling a backend other than `EZ_API_URL`. Stop and find out which. + +## When the screen does not match the page + +If a step cannot be performed as written, the page is wrong or the instance runs different code. Do not quietly bend the spec until it passes. + +1. Find out which it is: compare the instance's commit with your pin, and re-read the code for that step. +2. If the page was wrong, correct the fact, then the page, then the spec, and send the page through review again. +3. If the instance differs from the pin, tell the user. +4. If one flow fails, carry on with the others and report the failure. + +## Use the API log + +Take each `.api.json` back to the permission path of that flow, as "Confirming at runtime" in `permissions.md` describes. This is where missed gates are caught. If the user agreed to proof runs, do them now. + +## Put the media in the pages + +Decide the domain and module folder first; they are set in `publishing.md`. Media files are published under `/media///`. + +The video goes directly under the Overview heading, the way existing flow pages have it: + +```mdx + +``` + +A screenshot goes right after the step it shows: + +```mdx +![The Create workspace button in the workspace list](/media///-1.png) +``` + +Write alt text that says what the image shows, for readers who cannot see it. + +The captions track and the screenshots are new to the docs site; before this, pages had a video and nothing else. This markup passed the docs build for every language on 20 November 2026. The build is still the judge each time: if it rejects something here, fix or remove it and say so in the pull request. + +Set each recorded flow to `recorded` in `plan.md`, and release the environment lock. diff --git a/.claude/skills/ezhuthachan/references/permissions.md b/.claude/skills/ezhuthachan/references/permissions.md new file mode 100644 index 00000000..ef5b7bf5 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/permissions.md @@ -0,0 +1,115 @@ +# Permission paths + +Part of stage 3. For every flow you document who can do it. The answer is a path, not a single permission. + +## Why a path + +To perform an action, a user must first get to it. They sign in, they belong to the facility, the menu item is shown to them, the page loads its data, the button is there, the form's pickers load their options, and only then does the save call ask the backend for the action permission. Each of those can depend on a different permission. A user who holds the action permission and lacks one of the earlier ones never sees the button. + +Earlier pages listed only the last permission. The team's feedback was that this is not enough: to edit something a user must also be able to list and open it, and the frontend may ask for more before it shows the action at all. So for each flow you trace every gate from sign-in to save, and you record where each permission must be held and under what conditions. + +The backend alone is also not enough of an answer. On 20 November 2026 the Workspaces permission file said that Admin and Facility Admin hold "Can Create/Update Workspaces". The viewset said more: an instance-wide workspace can be created only by a superuser, a facility workspace needs the permission in the facility's root organization, and a personal workspace can be updated only by the person who created it. A table copied from the permission file would have been wrong for three of the four kinds of workspace. This is an example of what to look for. Do not reuse it; read the code at your pin. + +## The gates + +Trace them in this order, the order the user meets them. For each one, record a fact with evidence. Frontend paths below are inside `care_fe`. Backend paths are written from `$S/src`, as in `research.md`. + +| # | Gate | Where to look | What to record | +| --- | --- | --- | --- | +| 1 | Sign-in type | Route guards: `beforeLoad` on the route file and on each parent layout route; shared guards in `src/lib/router/auth.ts` | Staff, patient or public | +| 2 | Reaching the place | How the user gets into the facility, organization, patient or encounter the screen belongs to, and what lists them | Membership or permission needed to be there at all | +| 3 | Navigation | `src/components/ui/sidebar/`: the entry, and any condition on it | The condition, or that there is none | +| 4 | Route | `beforeLoad` redirects or checks on the route itself | The condition | +| 5 | Page load | Every query the page and its components run on load | The endpoint of each, and what that endpoint requires to list or read | +| 6 | The control | The condition under which the button, menu item or row action is rendered and enabled | Permission flags, record status, configuration | +| 7 | Inside the form | Pickers and lookups that load options | The endpoint of each and what it requires | +| 8 | Save | The mutation, its endpoint, and the viewset's authorization for that action | The permission, where it must be held, object conditions | + +Gates 5 and 7 are the ones that get missed. To edit something you must be able to open it, and to open it you must be able to list it. If a form makes you choose a department, you must be allowed to list departments. + +## Tracing a frontend call to its permission + +1. In the component, find the call and the API definition it uses, then read the path and method in the `*Api.ts` file. +2. In `care/config/api_router.py`, find the viewset registered for that path. +3. In the viewset, find the authorization for that action: + - create, update, delete: `authorize_create`, `authorize_update`, `authorize_destroy` + - list and read: `get_queryset`, which usually filters to what the user may see, and any `authorize_retrieve` + - custom endpoints: the `@action` method itself, which often checks inline + - checks inherited from a base class in `care/care/emr/api/viewsets/base.py` +4. Each check calls `AuthorizationController.call("", ...)`. Find `def ` under `care/care/security/authorization/`. +5. Read the handler. It names the permission (`SomePermissions.can_x.name`) and passes it to a shared check in `care/care/security/authorization/base.py`. Read that shared check too: its arguments decide where the permission must be held. +6. Read the permission in `care/care/security/permissions/`: its display name and its roles. A role list can be a constant defined higher in the file; expand it. Take role display names from `care/care/security/roles/role.py`. + +```bash +grep -rn "def " care/care/security/authorization/ +grep -n -A8 " = " care/care/security/permissions/.py +``` + +Read the whole method each time, not just the matching line. The conditions that matter are in the branches. + +## What to watch for + +These patterns occur in Care. Whether each applies to your module is something to read at your pin, not assume. + +- **Where a permission must be held.** A permission is held through a role in an organization. A shared check can require that organization to be a specific one, any organization of the facility, or the facility's root organization. "Holds the permission" and "holds it in the right place" are different things, and the page must say which. +- **Superuser.** Some branches allow only a superuser, and no role grants that. That action is out of the pages: a superuser is not a reader. Leave it out of the plan rather than writing "superusers only". Superusers also pass most other checks, so a check you traced for an ordinary user can look open when you test as a superuser. Probe with a user who holds the role, not with a superuser. +- **Object conditions.** Only the creator may update. Only while the record has a certain status. Only if not already linked. These are part of who can do it. +- **Borrowed permissions.** Many clinical resources have no permissions of their own and are governed by patient or encounter permissions. The permission to cite is the one the handler checks, whatever the resource is called. +- **Unused permissions.** A permission file can define permissions that no viewset checks. Never list a permission because it exists; list it because a gate checks it. +- **Frontend object permissions.** `hasPermission(permission, objectPermissions)` looks only in the list it is given when one is passed, for example the permissions that came with the facility. Note which list each check uses. +- **Frontend and backend disagreeing.** The frontend hides a button the backend would allow, or shows one the backend refuses. Record both sides. The page describes what the backend does. The disagreement is filed as an issue, as `issues.md` describes. Do not ask which side to document. +- **Two roles, one name.** More than one default role can have the same display name in different contexts. When you name a role, make sure the reader can tell which. +- **Custom roles.** If the pinned version lets administrators create or edit roles, the role lists in the code are defaults. Then write "by default, the Doctor and Nurse roles hold this permission". + +## Recording a path + +Add one block per flow to `facts.md`, after the facts it refers to. When a flow has variants with different paths, write one block per variant. + +```markdown +## Path: Create a workspace (for a facility) + +| # | Gate | Requirement | Held where / condition | Evidence | +| --- | --- | --- | --- | --- | +| 1 | Sign-in | Staff account | | E31 | +| 3 | Navigation | Facility settings is shown when ... | | E32, E33 | +| 5 | Page load | List workspaces: "Can Read Workspaces" | In an organization the workspace is shared with | E34, E35 | +| 8 | Save | "Can Create/Update Workspaces" | In the facility's root organization | E36, E37, E38 | + +To reach the screen: ... +For the action: ... +Default roles that satisfy every gate: ... +Not settled: Q4 (gate 2) +``` + +Leave a gate out only when you have evidence that it does not apply, and say so. A gate you could not trace stays in the table as "not settled" with a question number. + +Be careful with "roles that satisfy every gate". You can name them only when every gate is evaluated in the same place for the same user. When gates are held in different places, list what is needed at each and stop there. + +## How this appears in a page + +The flow template has a Permissions table with two columns, Permission and Access. Fill it like this: + +- One row per permission on the path. Put the action permission first, then the permissions needed to reach it. +- Use the display name from the permission definition, never the slug. +- In Access, say in plain words what the permission lets the reader do in this flow, where it must be held when that matters, and which default roles hold it. +- State conditions that are not permissions as prerequisites, in the reader's terms: "You created the workspace." + +A reader should be able to hand the table to their administrator and get exactly the access they need. + +## Confirming at runtime + +Static tracing of what a React page loads is error-prone: hooks nest, and queries are enabled by conditions. Recording gives you ground truth. Every flow recording writes `.api.json`, the list of API calls the flow really made with their status codes. See `media.md`. + +After a recording: + +1. Compare the calls with gates 5, 7 and 8 of your path. A call you did not trace is a gate you missed: trace it now. A call you predicted that never happened means your reading of the page was wrong: correct the path. +2. Any 403 in the log is a finding. Either the account lacked a permission the path should list, or the frontend calls something the user may not use. +3. Add the log as runtime evidence for the path. + +On a disposable environment, with the user's agreement, you can go further and prove the path: + +1. Create a role holding exactly the permissions on the path, and a user with that role in the places the path names. +2. Record the flow as that user. It must succeed. +3. Remove one permission at a time and try again. Each removal must stop the flow at the gate the path predicts. + +Mark a path that passed as confirmed by execution, with the commit and date, in `facts.md` and in the pull request. Do this for the flows where a wrong answer costs most, typically create and edit. It is slow, so agree with the user which flows get it. diff --git a/.claude/skills/ezhuthachan/references/probes.md b/.claude/skills/ezhuthachan/references/probes.md new file mode 100644 index 00000000..adfb965e --- /dev/null +++ b/.claude/skills/ezhuthachan/references/probes.md @@ -0,0 +1,34 @@ +# Probes + +When a fact can be settled by running something, write a small script or a Playwright test, run it, and keep the output. Do not reason your way through a question that a run would answer, and do not bounce back to the user between each try. + +This is the same idea as Claude Code's experimental Code Mode (`CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1` in Claude Code 2.1.323 and later, ): one piece of code does the searching, the checks and the filtering, and only the conclusion comes back. In Claude Code, turn Code Mode on for the research. In any other tool, do it by hand: write the script into the session and run it. + +## What a probe is for + +- A permission path you traced in code and want to see fail at the predicted gate. +- A label, error message or status you cannot find by reading. +- Two files that seem to disagree, where a call shows which one wins. +- Anything you would otherwise re-read three times. + +A probe is evidence of kind `runtime`. Cite the script path and the output file in the fact. + +## How to run them + +Collect every open point first. Then write the probes together, run them in one pass, and read the results once. A probe that needs a fact from an earlier probe waits; the rest run together. + +Put scripts in `$S/probes/` and their output in `$S/probes/out/`. Name a script after the question it answers, for example `department-workspace-as-facility-admin.py`. + +Prefer the cheapest run that answers the question: + +1. A script against the pinned checkout: import the function, call it, print the result. No server. +2. An HTTP call against an environment the user already approved, with the data policy from `media.md`. +3. A Playwright test, using the recording kit, when the question is about what a person sees. `EZ_SHOTS_ONLY=1` when you only need the screenshot. + +A probe creates records only on an environment whose data policy allows it. It never runs against an instance that may hold real patient data. It never prints tokens, passwords or patient details; print statuses, permission names and booleans. + +When a probe fails because a tool or a service is missing, say so and leave the fact unsettled. Do not invent the result the probe would have given. + +## What comes back + +The conversation hears the conclusion: what you asked, what the run showed, and where the output file is. It does not hear the script, the logs or the intermediate searches. Those stay in `$S/probes/`. diff --git a/.claude/skills/ezhuthachan/references/publishing.md b/.claude/skills/ezhuthachan/references/publishing.md new file mode 100644 index 00000000..e2e2c296 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/publishing.md @@ -0,0 +1,139 @@ +# Publishing + +Stage 7, plus two jobs that start from published pages: fact-checking an existing page, and finding pages that went stale. + +## The docs checkout + +You publish from the session's own checkout of the docs repository, `$S/src/docs`, created in `setup.md`. Use a managed checkout for docs even when the user reads Care from their own clones: you have to write here, and their clone is not yours to write in. + +Make a branch for the work: + +```bash +git -C "$S/src/docs" switch -c docs/- +``` + +Read `$S/src/docs/.claude/skills/care-concept-doc/references/conventions.md` again now. It governs where files go, how links are written, and what breaks the build. + +## Which versions + +Write a page only into the docs versions whose code you verified it against. `versions.json` in the docs checkout lists the versions the site has. + +- The usual case is one version: the one the session is pinned to. +- If the module also exists on another version's branch, the page is not automatically true there. Either pin that branch too and verify each fact against it, or leave that version out and say so. Never copy a page into a version you did not verify. +- The docs conventions say that all versions are kept identical. That rule cannot hold for a module that exists in only one version. Follow this file, and say in the pull request that you did. + +## Where files go + +Choose the domain by the lookup in `existing-docs.md`: the folder of the existing concept this module most resembles. Ask only when two sections fit equally well. The conventions file lists the domains too, and its versioning rule is stale. + +```text +versioned_docs/version-/concepts//.mdx +versioned_docs/version-/flows///.mdx +static/media/// +``` + +A new flow folder needs a `_category_.json`. Copy the shape of a sibling folder's file: a label, a position, and a key of the form `--flows`. + +If a page already exists at the target path, you are replacing it. Read the old page first. Anything it says that your facts do not cover is a lead to check, and a possible question, before it disappears. + +## Copy the pages + +Remove the evidence markers as you copy. They are working notes, not content. + +```bash +sed -E 's/ ?\[\[(none|E[0-9]+(, ?E[0-9]+)*)\]\]//g' "$S/drafts/.mdx" > "$S/src/docs/versioned_docs/version-/flows///.mdx" +mkdir -p "$S/src/docs/static/media//" +cp "$S/media/out/".mp4 "$S/media/out/".poster.png "$S/media/out/".vtt "$S/media/out/"-*.png "$S/src/docs/static/media///" +grep -rn '\[\[' "$S/src/docs/versioned_docs/version-/flows///" # must print nothing +``` + +The `.api.json` files stay in the session. They are evidence, not content. + +## The flow sidebar + +Concept pages appear in the site on their own. Flow pages do not: the flow sidebar is a hand-kept list, and a flow that is missing from it builds without error and is invisible. + +The file is `versioned_sidebars/version--sidebars.json`. Inside the "Flows" category there is one category per domain (key `-flows`), and inside that one per module (key `--flows`) whose `items` are document ids: + +```json +{ + "type": "category", + "label": "Workspace", + "key": "platform-workspace-flows", + "items": ["flows/platform/workspace/create-a-workspace", "flows/platform/workspace/share-a-workspace"] +} +``` + +Add the module category if it is new, and list the flows in the order of `plan.md`. Edit the file by hand, changing only the lines you need. Do not load and re-save it with a JSON tool; that reformats the whole file and buries your change. + +## Validate + +```bash +cd "$S/src/docs" +grep -rlE '///.md`: the session, the pinned commits, and the facts the page used, each with its claim, repository, commit, path, lines and quote. Copy them from `facts.md`. This is what makes the drift check possible later. + +That folder is on this machine only. Ask the user once whether the docs repository should carry this record too, and where; that is a decision for whoever owns the docs site. Remember the answer. + +## Open the pull request + +This is a gate. Show the user the list of files and the summary below, and open the pull request when they say so. + +```bash +cd "$S/src/docs" +git add -A && git commit -m "Add docs for " +git push origin HEAD +gh pr create --draft --title "[docs] for " --body-file "$S/pr-body.md" +``` + +If the push is refused, the user may contribute through a fork. Ask how they normally open pull requests to the docs repository and follow that. + +The pull request body says: + +- Which pages were added and which replaced an existing page, for which versions. +- The pinned commits of `care` and `care_fe` the pages were verified against. +- How they were verified: from code, by recording against which environment, and which permission paths were confirmed by execution. +- Where the pages differ from the house style on purpose: the language tiers, the version rule, the full permission path, and any media markup that is new. +- What was left out because it could not be verified, and the questions still open. +- Suspected product bugs found on the way. + +Then set the pages to `published` in `plan.md`, note the pull request in `session.md`, and go to wrap-up. + +When a reviewer asks for changes on the pull request, treat each request like a redo in `writing.md`: check it against the pinned code, change only what it needs, and re-verify any fact you touch. A request that would make the page say something the code does not support is not followed; explain why in the reply. + +## Verify an existing page + +When the user asks you to check a page that already exists, written by a person or by an earlier session: + +1. Set up a session and pin the code as usual, for the version the page belongs to. +2. Go through the page and list every statement about Care: each label, step, status, permission, role, shortcut and condition. +3. Check each one at the pinned commit, as in research. Record what you find as facts. +4. Report three lists: confirmed, wrong (with what the code says instead), and could not verify (with what you looked for). +5. Change the page only if the user asks. Then it is a redo. + +## Drift + +Code changes after a page is published. To find the pages that may now be wrong: + +1. Start a session pinned to the current commit of the version's branch. +2. For each provenance file of that version, compare each fact's file between the old commit and the new one: + + ```bash + git -C "$EZ/repos/care_fe.git" diff --quiet -- || echo "changed: " + ``` + +3. For each changed file, open the cited lines at the new commit and compare them with the quote. The file may have changed somewhere else and left the fact intact. +4. Report per page: still supported, or affected, with the facts that changed and what they say now. List affected screenshots too: a changed label or layout means a re-shoot. +5. With the user's agreement, redo only the affected pages. + +A page with no provenance file cannot be checked this way. Offer to verify it as an existing page instead. diff --git a/.claude/skills/ezhuthachan/references/questions.md b/.claude/skills/ezhuthachan/references/questions.md new file mode 100644 index 00000000..78d0ace2 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/questions.md @@ -0,0 +1,115 @@ +# Questions and the confirm gate + +Stage 4, and also how to ask a question at any stage. + +The examples in this file are invented to show the shape of a good question and a plan. They are not facts about Workspaces. + +## Asking a question + +A question is the right move whenever the code is ambiguous, two places disagree, a label or permission has more than one reading, the request can be read two ways, or you are simply not sure. Never guess to avoid asking, and never soften a guess with "typically" or "usually" to make it pass. + +The person answering is busy and may not read code. Make each question answerable on its own: + +- **Say what you read**, in product terms, with the file for those who want it. +- **Say what you found.** +- **Say why it is unclear.** +- **Say what each answer changes** in the pages. +- **Offer options** when the answers are discrete, with the one you think likelier first and marked as your reading, not as fact. + +Weak: "Please clarify how workspaces are shared." + +Strong: "A facility workspace can be shared with departments. The save call accepts a list of departments, but the form I can see only lets you pick one. Is choosing several departments meant to be possible in 3.1? If yes, I document it as a multi-select and report the form as a bug. If no, I document a single choice." + +Ask in batches, not one at a time: collect what a stage raises and ask it together. Use your tool's structured question prompt when it has one. + +Sort questions into two kinds: + +- **Blocking.** You cannot write a sound page without the answer. Stop that page until it is answered. Other pages continue. +- **Not blocking.** You can write the rest honestly. Leave the uncertain part out of the page, and list the question in the report and the pull request. + +Do not ask what you can find out, including by writing a probe and running it (`probes.md`). Each question should be one that only a person can answer: a preference, or a product decision the code does not settle. + +When the frontend and the backend disagree, the backend is the source of truth for the page and the disagreement is an issue (`issues.md`). Ask about it only when the backend itself can be read two ways. + +## questions.md + +Every question goes into `questions.md` in the session, asked in chat or not. The user can answer in chat or by typing under "Answer" in the file; with many questions, the file is quicker. + +```markdown +# Questions + +Answer in chat, or type under "Answer" here and tell Ezhuthachan you are done. + +## Q4 (blocking, open) + +**Question:** Is choosing several departments for a facility workspace meant to be possible in 3.1? + +**What I read:** The share form and the save call for facility workspaces. + +**What I found:** The call accepts a list of departments. The form lets you pick one. + +**Why it is unclear:** The two disagree, and either could be the intended behaviour. + +**What each answer changes:** Yes: the flow shows a multi-select and I report the form as a bug. No: the flow shows a single choice. + +**Affects:** share-a-workspace + +**Answer:** +``` + +When an answer arrives: + +1. Write it under "Answer" with who answered and the date, and change the heading to `answered`. +2. Add a fact to `facts.md` with `Kind: human`, citing the person, the date and the question number. +3. If the user says they answered in the file, re-read the file and do the same for each new answer. + +An answer settles intent. It does not change what the code does. If someone says a button exists and you cannot find it at the pinned commit, say so and ask where it is; do not document it on their word alone. The reader will be using the code, not the intention. + +At wrap-up, ask whether any answers should become standing answers in memory, so the next session does not ask again. See "Memory" in `setup.md`. + +## The confirm gate + +When research is done, stop and show the user what you intend to write. This is the point where a wrong direction is cheapest to fix. Do not draft anything before they confirm. + +Show, in this order: + +1. **The pages**, numbered in the order a reader meets them, one line each: the title, what it covers, and the existing page it updates or links to. `existing-docs.md` is how you find those. +2. **What you found that they might not expect**: a flow that exists in the code but looks unfinished, a screen behind a configuration flag, a difference between versions. +3. **Every open question**, blocking ones first. +4. **Suspected product bugs**, briefly. + +Then ask them to confirm or change the page list and to answer what they can. + +## plan.md + +The page list lives in `plan.md`, so the user can also edit it directly. + +```markdown +# Plan: Workspaces (Care 3.1) + +Tick or untick a page, reorder the lines, change a title, or add a line. Then tell Ezhuthachan. + +## Pages + +- [x] concept | workspace | Workspace | proposed +- [x] flow | create-a-workspace | Create a workspace | proposed + - Starts at: Facility settings, Workspaces + - Needs: nothing +- [x] flow | share-a-workspace | Share a workspace with a department | proposed + - Needs: create-a-workspace + - Blocked by: Q4 +- [ ] flow | set-a-default-workspace | Set your default workspace | proposed + - Unticked by the user: out of scope for now +``` + +Each page line is `- [x] kind | slug | Title | status`. The kind is `concept` or `flow`. The slug is kebab-case; a flow slug is a verb phrase. Indented lines are notes. + +Statuses, in order: `requested` (the user added it and you have not researched it), `proposed`, `confirmed`, `drafted`, `reviewed`, `recorded`, `published`. + +After the user responds, in chat or in the file: + +- Re-read `plan.md`. Respect every change: unticked pages are dropped, the order is theirs, titles are theirs. +- A line they added, with only a title, is a request. Give it a slug and status `requested`, research it like any other flow, and bring it back for confirmation. +- Set the confirmed pages to `confirmed`, note in `session.md` who confirmed and when, and move to writing. + +Keep the statuses current as pages move forward. When the user asks where things stand, answer from `session.md` and `plan.md`: the stage, each page with its status, and the open questions. diff --git a/.claude/skills/ezhuthachan/references/research.md b/.claude/skills/ezhuthachan/references/research.md new file mode 100644 index 00000000..5b0569c1 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/research.md @@ -0,0 +1,160 @@ +# Research + +Stage 3. You read the pinned code and come out with four things: + +- `facts.md`: every fact the pages will rest on, each with its evidence. +- The user tasks (flows) in the module, in `plan.md`. +- The permission path of each flow. That has its own guide: `permissions.md`. +- Questions, for everything you could not settle, in `questions.md`. + +Read `existing-docs.md` first and find the pages the site already has for this module and for the things it touches. Those pages supply the links and the terms. They do not supply the facts. A fact still comes from the pinned code. + +The code is in the session checkouts, `$S/src/care` and `$S/src/care_fe`. The tables below give paths inside each repository. The commands are run from `$S/src`, so their paths start with the repository folder: `care/care/security/...`, `care_fe/src/...`. + +## First, check the code map + +The table below was correct on `develop` on 20 November 2026 (`care` c0399a943, `care_fe` edc910ec1). Code moves. An earlier version of this map sent researchers to route files that had since been replaced by a different router, and nobody noticed. So check it against your pin before you rely on it: + +```bash +cd "$S/src" +for p in \ + care/care/security/permissions care/care/security/roles/role.py care/care/security/authorization \ + care/care/emr/api/viewsets care/care/emr/resources care/care/emr/models \ + care/config/api_router.py care/config/settings care/plug_config.py \ + care_fe/public/locale/en.json care_fe/src/routes care_fe/src/lib/router/auth.ts \ + care_fe/src/components/ui/sidebar care_fe/src/common/Permissions.tsx \ + care_fe/src/context/PermissionContext.tsx care_fe/src/types \ + care_fe/src/config/keyboardShortcuts.json care_fe/care.config.ts care_fe/tests/setup +do [ -e "$p" ] && echo "ok $p" || echo "MISSING $p"; done +``` + +For anything missing, find where it went by searching for what it contained, and write the new location under "Code map notes" in `session.md`. If you cannot find it, that is a question for the user, not a reason to skip that kind of fact. + +### Backend (`care`) + +| Path | What it holds | +| --- | --- | +| `care/security/permissions/.py` | Permission definitions. Each member is `Permission(display name, description, context, roles)`. The first argument is the name users see | +| `care/security/roles/role.py` | The default roles and their display names | +| `care/security/authorization/.py` | Authorization handlers. Shared checks are in `base.py` | +| `care/emr/api/viewsets/.py` | The API for a resource: `authorize_create`, `authorize_update`, `authorize_destroy`, `get_queryset`, and `@action` methods. Shared behaviour is in `base.py` | +| `care/emr/resources//spec.py` | Fields, required or optional, validation, enums | +| `care/emr/models/.py` | Database models | +| `config/api_router.py` | Which URL goes to which viewset | +| `config/settings/` | Settings, including flags that change behaviour | +| `plug_config.py` | Backend plugins | + +### Frontend (`care_fe`) + +| Path | What it holds | +| --- | --- | +| `public/locale/en.json` | Every English UI string, by key. Other languages sit beside it | +| `src/routes/` | One file per route. `_app/` is the staff application, `_patient/` the patient portal, `_public/` pages without sign-in. Guards are `beforeLoad` functions; the shared ones are in `src/lib/router/auth.ts` | +| `src/components/ui/sidebar/` | Navigation: which items exist, in what order, and when each is shown | +| `src/common/Permissions.tsx` | Permission constants and `getPermissions`, which turns them into `canX` flags | +| `src/context/PermissionContext.tsx` | `hasPermission(permission, objectPermissions?)` | +| `src/types/**/*Api.ts` | API definitions: the path and method of each call | +| `src/config/keyboardShortcuts.json` | Keyboard shortcuts by context | +| `care.config.ts` | Deployment configuration that changes what the UI shows | +| `tests/` | The product's own Playwright tests. Useful for how a screen behaves and for selectors | + +## Recording facts + +Write a fact to `facts.md` the moment you verify it, not at the end from memory. + +```markdown +## E12 + +Claim: The button that opens the create form is labelled "Create workspace". +Kind: code +Source: care_fe@edc910ec1 public/locale/en.json:1187 +Quote: "create_workspace": "Create workspace", +``` + +- Number facts E1, E2, E3 in order. Never reuse or renumber; drafts refer to these numbers. +- One claim per fact, written the way it could appear in a page. +- `Source` is the repository, the short commit, the path and the line or line range. +- `Quote` is the exact text at those lines, at most three lines. Print it to be sure the line numbers are right: `sed -n '1187p' care_fe/public/locale/en.json`. +- For a runtime fact, `Kind: runtime` and the source is the screenshot or response file you kept. For a human fact, `Kind: human` and the source is the person, the date, and the question number. + +A fact you cannot give a source for is not a fact. Turn it into a question. + +## What to collect + +Start from the name of the module and widen from there. `grep -ril workspace care/care care/config` and the same under `care_fe/src` show you the territory. + +### From the backend + +- **The resource.** Fields from the spec: name, required or optional, validation rules, and every enum with its values. +- **The endpoints.** `grep -n -i care/config/api_router.py`, then the viewset it names. +- **Authorization.** For every action of the viewset. This is the core of `permissions.md`: + + ```bash + grep -nE "def authorize_|AuthorizationController.call|PermissionDenied|@action|def get_queryset|is_superuser" care/care/emr/api/viewsets/.py + ``` + +- **Rules the user can hit.** Validation errors and `PermissionDenied` messages, limits, and status transitions that are refused. These become "what to do when" tables. +- **Settings that change behaviour.** `grep -rn -i care/config/settings/`. + +### From the frontend + +- **Where the module lives.** Routes and navigation: + + ```bash + ls care_fe/src/routes/_app | grep -i + grep -rn -i care_fe/src/components/ui/sidebar + ``` + +- **Each screen.** What it shows, what actions it offers (buttons, menus, row actions, dialogs), and when each action appears. +- **Each form.** Sections, fields, required or optional or conditional, defaults, and the messages for invalid input. Forms are usually a zod schema next to the component. +- **Labels.** The exact text of everything you will name. See below. +- **What the screen calls.** `grep -rnE "useQuery|useMutation|query\(|mutate\(" ` and the `*Api.ts` file those calls point to. You need this for the permission path. +- **Shortcuts.** Only those in `src/config/keyboardShortcuts.json` for this context. +- **Configuration.** Anything in `care.config.ts` that hides, shows or changes this module. + +### Labels + +Pages name things exactly as the screen does. Take every label from `care_fe/public/locale/en.json`. + +```bash +grep -n -i '"[^"]*workspace[^"]*":' care_fe/public/locale/en.json # keys that mention the module +grep -nF '": "Create workspace"' care_fe/public/locale/en.json # does this exact label exist? +``` + +- Find the key in the component first (`t("create_workspace")`), then read its value. Do not go from a guessed English phrase to a key; several keys can share similar text. +- Enum values are shown through keys shaped `PREFIX__value`, for example `encounter_status__in_progress` for "In Progress". Record the label, never the raw value. +- Labels with `{{name}}` placeholders are filled in at runtime. Quote the fixed part and describe the rest. +- Record the key with the fact. Recordings find elements by key. +- Some text on screen does not come from the locale file: role names, and anything a facility configures. Cite where it does come from. + +## Finding the flows + +A flow is one thing a user sets out to do, from where they start to the result: "Create a workspace", "Share a workspace with a department". It becomes one page. + +1. List the screens of the module from the routes and the navigation. +2. For each screen, list every action a user can take. +3. Group the actions into user goals. A goal that needs several screens is still one flow. Two goals on one screen are two flows. +4. For each flow note: where the user starts and how they get there, each step with the labels involved, what must already be true (a status, another record), the variants (the same goal reached from two places), and the result. +5. Order the flows the way a user meets them: create first, then what depends on it. + +Leave out what has no screen. An endpoint that the frontend never calls is not a flow. + +Put each flow in `plan.md` as described in `questions.md`, with status `proposed`. + +## Findings + +Reading two codebases closely turns up bugs: a button the backend will refuse, a missing permission check, an enum value with no label, a status nothing can reach, a shortcut bound to an action that is gone. Write each one in `report.md` when you see it, with the file and lines, what disagrees with what, and how sure you are. Report what you read or ran, not what you suspect about code you did not open. An empty list is a fine result. + +Then settle what a run can settle, with `probes.md`, and file each finding with `issues.md`. The page follows the backend. A disagreement between the frontend and the backend is an issue, not a question for the user. + +## With subagents + +Send one researcher to the backend and one to the frontend, in parallel. Give each: the module, the path of its checkout, this file and `permissions.md`, and the fact format. Ask each to return facts with sources and quotes, a list of what it could not settle, and suspected bugs. + +A researcher's report is a lead until you have checked it. Open the cited lines for every permission, role and label it reports before the fact goes into `facts.md`. Spot-check the rest. + +## Before you leave research + +- Every fact in `facts.md` has a source you opened in this session, at the pinned commit. +- Every flow has its steps, its labels and its permission path, or a question saying what is missing. +- Nothing rests on "probably" or "usually". If you catch yourself writing either word, you have a question, not a fact. diff --git a/.claude/skills/ezhuthachan/references/setup.md b/.claude/skills/ezhuthachan/references/setup.md new file mode 100644 index 00000000..1b844954 --- /dev/null +++ b/.claude/skills/ezhuthachan/references/setup.md @@ -0,0 +1,254 @@ +# Set up and intake + +This covers stages 1 and 2: the state folder, memory, the session, what the machine has, the questions to ask first, and getting the code pinned to exact commits. + +If you were started inside the docs repository, that working tree belongs to the user. Read it to learn the site (`existing-docs.md`), and do the writing in the session's own checkout of docs, on a new branch. Do not switch the branch they already have open. + +## State folder + +```bash +EZ="$HOME/.ezhuthachan" +mkdir -p "$EZ/repos" "$EZ/sessions" "$EZ/answers" "$EZ/provenance" +``` + +## Memory + +Read `$EZ/memory.md` before anything else. It tells you how this person likes to work, so you can offer their last answers as defaults. + +If the file does not exist, create it: + +```markdown +# Ezhuthachan memory + +Capped at 200 lines. Preferences and human decisions only. +Never evidence for what the code does. Never credentials. + +## Preferences + +## Version map + +## Environments + +## Standing answers +``` + +What belongs in each section: + +- **Preferences.** How to get the code (managed or their own clone, and where that is), how they run Care, recording choices, how they like questions asked. +- **Version map.** Which branch of each repository was confirmed for which Care version, and on what date. This is a default to offer, never an answer to assume. +- **Environments.** Instances a person approved for recording, with the data policy and who approved it. No passwords. +- **Standing answers.** Decisions a person made that apply across modules, with who and when. + +Answers that concern one module go in `$EZ/answers//.md` instead. Read that file only when that module is the subject. + +Rules for writing to memory: + +- Write only at wrap-up, and only lines the user approved after seeing them. +- End each line with the date, for example `- Uses managed sources. (2026-11-20)`. +- Before adding, run `wc -l "$EZ/memory.md"`. If the file would pass 200 lines, first merge duplicates, remove entries that a newer one replaces, and move module-specific lines to `answers/`. Tell the user what you removed. +- A memory entry about how the code behaves is always wrong to add. Code facts go stale; they belong in `facts.md` with a commit. + +## Start or resume a session + +List open sessions first: + +```bash +grep -HE "^- (Module|Stage):" "$EZ"/sessions/*/session.md 2>/dev/null +``` + +If an open session matches what the user is asking for, ask whether to resume it. To resume, read its `session.md`, then `plan.md` and `questions.md`, then do the upstream check in "Resuming" below. + +To start a new one: + +```bash +ID="$(date +%F)--$(openssl rand -hex 2)" # for example 2026-11-20-workspaces-a1b2 +S="$EZ/sessions/$ID" +mkdir -p "$S/src" "$S/drafts" "$S/media" +``` + +Create `session.md`, `facts.md`, `plan.md`, `questions.md` and `report.md` in `$S`. Start `session.md` like this and keep it current: + +```markdown +# Session 2026-11-20-workspaces-a1b2 + +- Module: Workspaces +- Request: "generate documentation for the workspace module" +- Requested by: +- Stage: intake +- Care version: not confirmed +- Pages wanted: not confirmed +- Media wanted: not confirmed +- Docs versions to write: not confirmed + +## Sources + +| Repository | Mode | Branch | Commit | Commit date | Checked against upstream | +| --- | --- | --- | --- | --- | --- | + +## Environment + +Not chosen. + +## Code map notes + +## Log + +- 2026-11-20 18:35 Session created. +``` + +Several sessions can run at the same time. Each has its own folder and its own checkouts, so they do not disturb one another. + +## What the machine has + +Look, so that your later questions are informed. Do not choose anything yet. + +```bash +for c in git node npm python3 docker ffmpeg ffprobe gh psql; do + printf "%-8s %s\n" "$c" "$(command -v "$c" || echo missing)" +done +docker info --format '{{.ServerVersion}}' 2>/dev/null || echo "docker daemon not running" +for p in 9000 4000 5432 6379; do (nc -z 127.0.0.1 "$p" 2>/dev/null && echo "listening :$p") || echo "nothing on :$p"; done +``` + +Ports 9000 and 4000 are the defaults for the Care backend and frontend. Something listening there suggests the person already runs Care locally. That is worth knowing when media comes up, and it is still their choice. + +## Intake questions + +Ask these together, in one round. Offer the remembered answer as the default where memory has one. + +1. **Which Care version is this for, and which branch holds it in each repository?** Always ask, every session, even when memory has an answer, because the mapping moves as releases are cut. Show the real branches so the choice is concrete: + + ```bash + git ls-remote --heads https://github.com/ohcnetwork/care.git | grep -E 'refs/heads/(develop|main|master|staging|[0-9]+\.[0-9x.]+)$' + git ls-remote --heads https://github.com/ohcnetwork/care_fe.git | grep -E 'refs/heads/(develop|main|master|staging|[0-9]+\.[0-9x.]+)$' + ``` + + In November 2026, version 3.1 lived on `develop` in both repositories and 3.0 had its own `3.0` branch. Treat that as an example of the shape, not as current fact. + +2. **Should I keep my own copy of the code, or read yours?** Recommend the managed copy and say why in a sentence: it is always fresh from upstream, and it leaves their clones and branches alone. If they prefer their own, ask for the paths. + +3. **Does the module involve a plugin?** Some Care features live in separate plugin repositories. If they are not sure, check after the code is pinned and come back with what you found. The list of known plugins is at `https://github.com/ohcnetwork/care_apps_registry`. + +4. **Which pages?** A concept page, flow pages, or both. Ask whether there are flows they already know they want. + +5. **Screenshots and videos?** Only whether they want them. The questions about where to record come at the media stage, when they matter. + +6. **Anything about the readers I should know?** For example, the page is mainly for front-desk staff. + +Do not ask what the code can tell you. Which screens exist, what the buttons say, and who may do what are research. + +Record the answers in `session.md`. + +## Getting the code + +Three repositories are always needed: `care` (backend), `care_fe` (frontend) and `docs` (the site you write to, on `main`; it also holds the house style). Add plugin repositories when the module needs them. + +### Managed copy (recommended) + +Each repository has one shared mirror, and each session gets its own checkout from it. A checkout of both Care repositories is about 30 MB, so sessions are cheap. + +First time only, per repository: + +```bash +M="$EZ/repos/care.git" +git init --bare --quiet "$M" +git -C "$M" remote add origin https://github.com/ohcnetwork/care.git +``` + +If the person has a local clone, use it to avoid a long download. This copies objects from their clone and changes nothing in it: + +```bash +git -C "$M" fetch --quiet --no-tags /path/to/their/care '+refs/remotes/*:refs/seed/*' +``` + +Every session, fetch from upstream. This is the step that makes the research current, so never skip it: + +```bash +git -C "$M" fetch --quiet --prune --tags origin +git -C "$M" for-each-ref --format='delete %(refname)' refs/seed | git -C "$M" update-ref --stdin +``` + +If the fetch fails because another session is fetching the same mirror, wait a few seconds and run it again. + +Then pin and check out: + +```bash +SHA="$(git -C "$M" rev-parse origin/develop)" # the branch the user confirmed +git -C "$M" worktree add --quiet --detach "$S/src/care" "$SHA" +git -C "$M" log -1 --format='%H %cI %s' "$SHA" +``` + +Repeat for `care_fe` and `docs`. Use the HTTPS URLs; these repositories are public and need no sign-in to read. + +### The user's own clone + +Read it where it is. Run nothing in it that changes it: no checkout, switch, stash, pull, fetch or commit. + +```bash +P=/path/to/their/care +git -C "$P" rev-parse HEAD +git -C "$P" rev-parse --abbrev-ref HEAD +git -C "$P" status --porcelain | wc -l # uncommitted files +git ls-remote https://github.com/ohcnetwork/care.git refs/heads/develop # upstream, read over the network +ln -s "$P" "$S/src/care" +``` + +Compare their `HEAD` with the upstream commit. If they differ, or there are uncommitted files, their clone is not the code you were asked to document. Say exactly what you found ("your clone is on branch X at commit A; `develop` upstream is at B; 3 files have uncommitted changes") and let them choose: bring the clone up to date themselves, or switch to the managed copy. Do not research a clone that differs from upstream unless they tell you to, and if they do, write that decision in `session.md` and in the pull request. + +This matters in practice. On 20 November 2026 a local `care` clone was two days behind upstream, and in those two days the whole Workspaces backend had landed. Research on that clone would have concluded that Workspaces had no backend. + +### Record and report the pin + +Fill in the Sources table in `session.md` with the full commit hash, the commit date and the time you checked upstream. Then tell the user what you pinned, in words they can check: "`care` at c0399a943 from 20 Nov, `care_fe` at edc910ec1 from 20 Nov, both the latest on `develop`." + +## Does the module exist on this branch? + +Check before researching. A module can be in one version and absent from another. + +```bash +for ref in 3.0 develop; do + printf "%-8s %s files\n" "$ref" "$(git -C "$EZ/repos/care_fe.git" ls-tree -r --name-only "origin/$ref" | grep -ic workspace)" +done +``` + +Run it for each repository and for each branch the docs site has a version for. Try the product name and the names the code might use; they can differ between frontend and backend. + +- Files on the chosen branch: continue, and tell the user where the module exists and where it does not. +- No files on the chosen branch: stop and tell the user. Either the branch is wrong, or the module has another name in the code. Ask. + +The result also decides which docs versions you write to: only versions whose branch contains the module. Confirm that list with the user and record it. + +With the user's own clone, the branch list comes from their remote-tracking refs, which can be stale. Check each one against `git ls-remote` and say so if it is behind. + +## Resuming + +Upstream may have moved since the session was pinned. + +```bash +git ls-remote https://github.com/ohcnetwork/care.git refs/heads/develop +``` + +If the commit differs from the pin, fetch the mirror and see whether the change touches what you researched: + +```bash +git -C "$M" fetch --quiet --prune --tags origin +git -C "$M" diff --name-only origin/develop +``` + +Tell the user what moved and ask whether to move the pin. If they say yes: + +```bash +git -C "$S/src/care" checkout --quiet --detach +``` + +Then re-open every fact in `facts.md` whose file is in the changed list, correct or remove it, and update its commit. Facts whose files did not change stay valid; update their commit to the new pin. + +## Cleaning up + +Closed sessions keep their checkouts until removed. For a session the user agrees to delete: + +```bash +git -C "$EZ/repos/care.git" worktree remove --force "$S/src/care" # for each managed repository +[ -L "$S/src/care" ] && rm "$S/src/care" # a link to the user's clone: remove the link, never its target +rm -rf "$S" +``` diff --git a/.claude/skills/ezhuthachan/references/writing.md b/.claude/skills/ezhuthachan/references/writing.md new file mode 100644 index 00000000..5e17d79d --- /dev/null +++ b/.claude/skills/ezhuthachan/references/writing.md @@ -0,0 +1,141 @@ +# Writing + +Stage 5. You turn confirmed facts into pages. Nothing new is learned here: if a sentence needs something that is not in `facts.md`, stop and go get it, or ask. + +## House style comes from the docs repository + +The docs site owns its templates and conventions, and its reviewers hold pages to them. Read these in the docs checkout before drafting: + +```text +$S/src/docs/.claude/skills/care-concept-doc/SKILL.md +$S/src/docs/.claude/skills/care-concept-doc/assets/concept-template.md +$S/src/docs/.claude/skills/care-concept-doc/references/conventions.md +$S/src/docs/.claude/skills/care-flow-doc/SKILL.md +$S/src/docs/.claude/skills/care-flow-doc/assets/flow-template.md +$S/src/docs/.github/references/review-checklist.md +``` + +The templates set the section names and their order. The conventions cover links, MDX safety, domains and slugs. If these files are not at those paths, search the checkout for them (`grep -rl "flow-template" "$S/src/docs"`), and ask the user if you cannot find them. Do not write from a remembered template. + +This skill differs from those files in three places, each on the team's instruction. Say so in the pull request, so a reviewer does not read them as mistakes: + +- **Language.** Those files apply Simplified Technical English to every sentence. Here it applies where it helps and not elsewhere; see "Language" below. +- **Versions.** Those files say every version is identical and mirrored. Here a page goes only to the versions whose code has the module; see `publishing.md`. +- **Permissions.** The Permissions table covers the whole path to the action, as `permissions.md` describes, not only the final permission. + +Where those files disagree with one another, follow the review checklist, because that is what the reviewer applies, and tell the user about the disagreement. One known case: the concept guide asks for permission slugs in backticks, while the checklist forbids slugs in concept and flow pages. + +## Two kinds of page + +- **Concept.** "What is this?" One page per thing. It gives the reader a model: what the thing represents, how it behaves over time, how it relates to its neighbours, and who can work with it. +- **Flow.** "How do I do this?" One page per user task, from where the user starts to the result. + +Both are for people using Care, not for developers. They contain no code, file paths, class names, endpoints, payloads, database columns or permission slugs. They use the words on the screen. + +## Drafting + +Write each page to `$S/drafts/.mdx`. Set its status to `drafted` in `plan.md` when done. + +- **Write from `facts.md`.** Open it beside the draft. Every statement about Care restates a fact. +- **One block per line.** Write each paragraph, list item and table row on a single line. The checks below depend on it. +- **Mark every block.** End each paragraph, list item and table row with the facts it rests on: `[[E12]]` or `[[E3,E7]]`. A block that states nothing about Care, such as "This flow describes how to create a workspace.", ends with `[[none]]`. The markers are removed at publishing. They exist so that a reviewer can check every sentence against its source, and so that a block with no support is visible. +- **Bold means a label.** Use bold only for text the user sees on screen, copied exactly from the locale file: Select **Create workspace**. For on-screen text that does not come from the locale file, such as a role name, put its fact right after it: **Facility Admin** `[[E7]]`. +- **Say what the screen says.** "In Progress", never `in_progress`. "Can Create/Update Workspaces", never the slug. +- **Write the reader's situation, not the data model.** "The patient is registered in Care", not "the patient record exists". +- **Leave gaps visible.** When a question is open, leave that part out and note it in `report.md`. Do not write around it. +- **Leave media out.** Screenshots and the video are added at the media stage. + +Headings, the Related section and media embeds need no marker. + +## Language + +The pages will be translated, so the writing has to translate cleanly. That does not mean the same rules everywhere. Simplified Technical English (ASD-STE100) is built for procedures and warnings. Applied to an explanation of what something is, it produces stiff, choppy text that helps nobody. + +**Instructions: STE rules.** Steps, prerequisites, warnings, expected outcomes, field descriptions and "what to do" tables. + +- One instruction per sentence, in the command form: "Select **Save**." +- At most 20 words in a sentence. +- Present tense, active voice. +- State the condition first: "If the workspace is shared, remove the departments first." +- Use a table for a set of fields, and a list for more than two items. + +**Explanation: plain, consistent English.** Overviews and concept sections. + +- Natural sentences, as long as the idea needs, usually under 30 words. +- You may explain why, compare, and connect ideas. A reader should finish with a picture in their head. +- Still no idioms, no jokes, no cultural references, and no pronoun whose noun is unclear. Those do not survive translation. + +**Everywhere.** + +- One term for one thing, in every page. Take the term from the screen, and never alternate with a synonym: if the screen says "facility", never write "hospital". +- Simple words: "use" not "utilize", "start" not "initiate", "show" not "render". +- No "will", "simply", "easily", "seamless", "powerful", "via", "e.g.", "i.e." or "etc.". +- Labels are quoted exactly, even where they break these rules. + +Keep the terms in `$S/terms.md` as you settle them: the term, what it means in one line, its label key, and the synonyms not to use. The other locale files in `care_fe/public/locale/` hold the same keys in other languages, so a translator can use the words the translated screen uses. + +Do not describe the pages as STE compliant. You follow its writing rules; compliance also needs its controlled dictionary. + +## Check your own draft + +Run these on each draft before review. Fix what they print, or be able to explain it. `D` is the draft file. + +```bash +# 1. Markers that point to no fact +grep -o '\[\[E[0-9, E]*\]\]' "$D" | grep -o 'E[0-9]*' | sort -u | while read -r e; do grep -q "^## $e\$" "$S/facts.md" || echo "no fact for $e"; done + +# 2. Blocks with no marker (outside Related) +awk '/^## /{related = ($0 ~ /^## Related/)} !related' "$D" | grep -nvE '\[\[(E[0-9]|none)|^#|^$|^---|^\| ?-|^\| Permission|^:::|^ *<|^!\[|^import |^sidebar_position' + +# 3. Bold text that is not a label in the pinned locale file +grep -o '\*\*[^*]*\*\*' "$D" | sed 's/\*\*//g' | sort -u | while IFS= read -r l; do grep -qF "\": \"$l\"" "$S/src/care_fe/public/locale/en.json" || echo "not in en.json: $l"; done + +# 4. Codebase literals such as in_progress or can_write_x +grep -nE '(^|[^a-zA-Z_/.-])[a-z]+_[a-z_]+' "$D" | grep -v 'sidebar_position' + +# 5. Things that break the MDX build, and leftover template comments +grep -nE '\{#|\{/\*| **Note**: The prompt and reference files listed below are located in the [`github/gh-aw`](https://github.com/github/gh-aw) repository and are **not available locally** in this repository. Load them from their public URLs. - -### Create New Workflow -**Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md` - -**Use cases**: -- "Create a workflow that triages issues" -- "I need a workflow to label pull requests" -- "Design a weekly research automation" - -### Update Existing Workflow -**Load when**: User wants to modify, improve, or refactor an existing workflow - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md` - -**Use cases**: -- "Add web-fetch tool to the issue-classifier workflow" -- "Update the PR reviewer to use discussions instead of issues" -- "Improve the prompt for the weekly-research workflow" - -### Debug Workflow -**Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md` - -**Use cases**: -- "Why is this workflow failing?" -- "Analyze the logs for workflow X" -- "Investigate missing tool calls in run #12345" - -### Upgrade Agentic Workflows -**Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md` - -**Use cases**: -- "Upgrade all workflows to the latest version" -- "Fix deprecated fields in workflows" -- "Apply breaking changes from the new release" - -### Create a Report-Generating Workflow -**Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md` - -**Use cases**: -- "Create a weekly CI health report" -- "Post a daily security audit to Discussions" -- "Add a status update comment to open PRs" - -### Create Shared Agentic Workflow -**Load when**: User wants to create a reusable workflow component or wrap an MCP server - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md` - -**Use cases**: -- "Create a shared component for Notion integration" -- "Wrap the Slack MCP server as a reusable component" -- "Design a shared workflow for database queries" - -### Fix Dependabot PRs -**Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`) - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md` - -**Use cases**: -- "Fix the open Dependabot PRs for npm dependencies" -- "Bundle and close the Dependabot PRs for workflow dependencies" -- "Update @playwright/test to fix the Dependabot PR" - -### Analyze Test Coverage -**Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy. - -**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md` - -**Use cases**: -- "Create a workflow that comments coverage on PRs" -- "Analyze coverage trends over time" -- "Add a coverage gate that blocks PRs below a threshold" - -### CLI Commands Reference -**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access. - -**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md` - -**Use cases**: -- "How do I trigger workflow X on the main branch?" -- "What's the MCP equivalent of `gh aw logs`?" -- "I'm in Copilot Cloud — how do I compile a workflow?" -- "Show me all available gh aw commands" - -### Token Consumption Optimization -**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes. - -**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md` - -**Use cases**: -- "How do I reduce the token cost of this workflow?" -- "My workflow is too expensive — how do I optimize it?" -- "How do I compare token usage between two runs?" -- "Should I use gh-proxy or the MCP server?" -- "How do I use sub-agents to reduce costs?" -- "How do I measure the impact of a prompt change?" - -### Workflow Pattern Selection -**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows. - -**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md` - -**Use cases**: -- "Which pattern should I use for multi-repo rollout?" -- "How should I structure this workflow architecture?" -- "What pattern fits slash-command triage?" -- "Should this be DispatchOps or DailyOps?" - -## Instructions - -When a user interacts with you: - -1. **Identify the task type** from the user's request -2. **Load the appropriate prompt** from the URLs listed above -3. **Follow the loaded prompt's instructions** exactly -4. **If uncertain**, ask clarifying questions to determine the right prompt - -## Quick Reference - -```bash -# Initialize repository for agentic workflows -gh aw init - -# Generate the lock file for a workflow -gh aw compile [workflow-name] - -# Trigger a workflow on demand (preferred over gh workflow run) -gh aw run # interactive input collection -gh aw run --ref main # run on a specific branch - -# Debug workflow runs -gh aw logs [workflow-name] -gh aw audit - -# Upgrade workflows -gh aw fix --write -gh aw compile --validate -``` - -## Key Features of gh-aw - -- **Natural Language Workflows**: Write workflows in markdown with YAML frontmatter -- **AI Engine Support**: Copilot, Claude, Codex, or custom engines -- **MCP Server Integration**: Connect to Model Context Protocol servers for tools -- **Safe Outputs**: Structured communication between AI and GitHub API -- **Strict Mode**: Security-first validation and sandboxing -- **Shared Components**: Reusable workflow building blocks -- **Repo Memory**: Persistent git-backed storage for agents -- **Sandboxed Execution**: All workflows run in the Agent Workflow Firewall (AWF) sandbox, enabling full `bash` and `edit` tools by default - -## Important Notes - -- Always reference the instructions file at `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md` for complete documentation -- Use the MCP tool `agentic-workflows` when running in GitHub Copilot Cloud -- Workflows must be compiled to `.lock.yml` files before running in GitHub Actions -- **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF -- Follow security best practices: minimal permissions, explicit network access, no template injection -- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/network.md` for the full list of valid ecosystem identifiers and domain patterns. -- **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself. -- **Triggering runs**: Always use `gh aw run ` to trigger a workflow on demand — not `gh workflow run .lock.yml`. `gh aw run` handles workflow resolution by short name, input parsing and validation, and correct run-tracking for agentic workflows. Use `--ref ` to run on a specific branch. -- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md` diff --git a/.github/agents/care-code-fixer.agent.md b/.github/agents/care-code-fixer.agent.md deleted file mode 100644 index 1e3bb87f..00000000 --- a/.github/agents/care-code-fixer.agent.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -name: care-code-fixer -description: "Fixes bugs and makes code changes in the care (backend) or care_fe (frontend) repositories. Use when a user reports a bug, inconsistency, or needed code change while documentation work is in progress. Handles the code change end to end, including lint and tests." -model: ['Claude Sonnet 5 (copilot)', 'Claude Sonnet 4.5 (copilot)'] -tools: [execute, read, agent, edit, search, web, 'github/*', todo] -user-invocable: false ---- -You are a code-fix specialist for the CARE repositories. You receive one bug report or -change request and you implement it end to end. - -Repositories, cloned as siblings of this one: -- Backend: `../care` (Django 6 + DRF, Python 3.13) -- Frontend: `../care_fe` (React 19 + TypeScript + Vite) - -Follow the repository's own instructions files (`CLAUDE.md`, `AGENTS.md`, -`.github/copilot-instructions.md`, `.github/instructions/*`) for conventions, -build commands, and code style. - -## Delivery brief - -Your brief MUST state four things. You cannot ask the user — the orchestrator asks -them before it invokes you. If any are missing, STOP and report what you need. - -| Setting | Values | -| --- | --- | -| Workspace | `local` (edit the checkout in place) or `worktree` (isolated) | -| Issue | `create` a GitHub issue first, use an `existing #`, or `none` | -| Assignment | assign the issue to a given user, or `none` | -| Pull request | `open` a PR when done, `commit only`, or `leave uncommitted` | - -## Approach - -1. Set up the workspace before editing: - - **local**: work in the existing checkout. Confirm the current branch is - appropriate and the tree is clean enough to isolate your change. - - **worktree**: create an isolated worktree so parallel fixes do not collide: - - ```sh - git -C worktree add ../.worktrees// -b issues// origin/develop - ``` - - Then install dependencies in the new worktree — they are NOT shared: - `npm install --ignore-scripts && npm run postinstall` (care_fe), - or the project's Python environment setup (care). -2. Create or fetch the issue if the brief asks for one. Use the repository's issue - conventions. Assign it when the brief names an assignee. -3. Reproduce or locate the problem in code before changing anything. Read the - relevant files and understand the existing pattern. -4. Make the minimal correct change. Do not refactor beyond the request. -5. Validate: - - Frontend: `npx tsc --noEmit`, then `npm run lint-fix && npm run format` on - changed files. Add i18n keys to the end of `public/locale/en.json` when needed. - - Backend: `ruff check --fix .` and `ruff format .`, then run the related tests - (`python manage.py test care. --keepdb`). -6. Deliver per the brief: - - Branch name: `issues//`. - - Commit with a clear message. Never use `--no-verify`. - - PR title follows the repo convention (emoji + imperative summary), and the body - links the issue with a closing keyword. -7. Report what changed and what you verified. - -## Constraints - -- DO NOT commit, push, create branches, worktrees, issues, or pull requests beyond - what the delivery brief authorizes. -- DO NOT force-push, reset hard, delete branches, or remove worktrees you did not create. -- DO NOT change documentation in `versioned_docs` — that is the documentation - pipeline's job. -- DO NOT bypass safety checks (no `--no-verify`) or run destructive commands. -- ONLY make the change you were asked for. If the fix needs a product decision or - the root cause is ambiguous, stop and report instead of guessing. - -## Output - -Report: workspace used (path and branch), issue and PR links if created, files changed, -a one-line rationale per change, validation commands run and their result, and anything -left unresolved. diff --git a/.github/agents/care-docs-recorder.agent.md b/.github/agents/care-docs-recorder.agent.md deleted file mode 100644 index ca60bf12..00000000 --- a/.github/agents/care-docs-recorder.agent.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -name: care-docs-recorder -description: "Records screen-capture demo videos for all flow docs of a CARE module with Playwright, converts them to MP4, and embeds them in the flow markdown. Use when asked to record flows, add demo videos, or attach video walkthroughs to documentation." -model: ["Claude Sonnet 5 (copilot)", "Claude Sonnet 4.5 (copilot)"] -tools: [read, search, edit, execute, todo] -user-invocable: false ---- - -You record demo videos for CARE flow documentation. You receive a module and its flow -docs, and you produce a video attached to each one. - -Record every flow you were given, without asking the user to confirm anything. Do not -record a single flow as a trial and wait for approval. Do not ask which flows to record. -The only question about the database is settled by the orchestrator before you start, -and it arrives in your brief. - -First, read -`.github/references/flow-recording.md`. -It holds the settled decisions, the config, the ffmpeg command, and the gotchas. -Follow it exactly. - -## Approach - -1. **Check the prerequisites.** In this order: - - **FIRST, verify the frontend targets localhost.** Read `REACT_CARE_API_URL` from - `care_fe/.env.local` and `care_fe/.env`. It ships pointing at a LIVE shared API, and - the file also lists production URLs. If the value is not a localhost address, STOP - immediately and tell the user. Recording against a live system creates real patients - and encounters. Never edit this value yourself. - - The backend must serve port 9000, `npm run preview` must serve - `http://localhost:4000`, the database must be restored, and - `care_fe/tests/.auth/*.json` must be fresh. - If any prerequisite is missing, STOP and report what the user must start. Do not try to - start the backend yourself. -2. **Prepare the database** as the brief instructs: - - _restore_: run `npm run playwright:db-restore` in care_fe, then - `npx playwright test --project=setup --workers=1` to rebuild the auth state and - fixture ids. A restore invalidates the stored tokens, so the setup run is required. - - _keep existing data_: skip the restore. Still re-run the setup project if the - stored tokens have expired. -3. **Read every flow doc** you were given. Each doc's step headings become the - `test.step()` titles of its spec, one for one. -4. **Write one demo spec per flow** at - `recordings//.demo.ts`. - Mirror the locator style and helpers used in `care_fe/tests/`, and drive the mouse - with the `Pointer` helper so the cursor is visible. - **Record only actions a person can perform.** Navigate by URL exactly once, at the - start, to open the entry screen. Reach every later screen by clicking through the - UI — sidebar, tabs, rows, breadcrumbs, back button. Type with `pointer.type()` so - text appears character by character, never with `fill()` on camera. Do any data - setup off camera, before the recorded page opens. -5. **Run them all in ONE Playwright pass** (`npx playwright test` in this repository). - The - config runs the specs in parallel across workers, so the whole module records in - roughly the time of its slowest flow. Never launch several Playwright processes at - once: parallelism comes from workers inside a single run, and concurrent processes - would fight over the same app and database. - Because specs run concurrently, **each spec must own the data it mutates.** Create a - fresh patient or encounter inside the spec when the flow changes state that another - flow depends on. Only fall back to `--workers=1` if flows genuinely cannot be - isolated, and say so in your report. -6. **Convert and embed.** The `saveRecording` helper writes the MP4 and poster. Embed - each video under the `## Overview` heading of its flow doc. -7. **Watch for drift.** If the UI does not match a step in a doc, the doc is wrong - or stale. Report the mismatch. Do NOT silently rewrite the flow doc to match. - If one flow fails, keep going with the rest and report the failure at the end. - -## Constraints - -- DO NOT write anything into a recorded page that a user could not do themselves: - no URL jumps between screens, no `page.evaluate` state changes, no API calls that - skip a step of the flow, no instant `fill()`. -- DO NOT record against any database that may hold real patient data. Fixture data - only. Everything on screen is permanent once recorded. -- DO NOT run a recording when `REACT_CARE_API_URL` is not a localhost address. -- DO NOT commit raw `.webm` intermediates. -- DO NOT edit flow doc content beyond adding the video embed. -- DO NOT create the Playwright bootstrap (Playwright dependency, `playwright.config.ts`) - without the user's approval. This repository's `package.json` belongs to Docusaurus. -- DO NOT run more than one Playwright process at a time. -- DO NOT pause for user confirmation between flows. - -## Output - -Report, per flow: spec path, video path and file size, and any step where the UI did -not match the flow doc. Then a one-line summary of how many flows recorded and which -failed. diff --git a/.github/agents/care-docs-researcher.agent.md b/.github/agents/care-docs-researcher.agent.md deleted file mode 100644 index b7f6290a..00000000 --- a/.github/agents/care-docs-researcher.agent.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -name: care-docs-researcher -description: "Read-only codebase researcher for CARE documentation. Builds a verified dossier (attributes, enums with display labels, permissions, flows, shortcuts, config) for a module from the care backend or care_fe frontend. Invoked by the Care Documentation Intern." -model: ["Claude Sonnet 5 (copilot)", "Claude Sonnet 4.5 (copilot)"] -tools: [read, search] -user-invocable: false ---- - -You are a read-only research specialist for CARE documentation. You investigate ONE -resource in ONE repository focus (backend `../care` or frontend `../care_fe`, both -cloned as siblings of this repository) and return a structured dossier of VERIFIED -facts. - -First, read `.github/references/codebase-navigation.md` -— it contains pre-verified file paths and grep patterns. Use it instead of exploring -from scratch. - -## What to collect - -**Backend focus:** - -- Key attributes from `care/emr/resources//spec.py` (fields, required/optional, - validation) and the Django model. -- Every status/choice enum with its coded values. -- Full RBAC trace per action: viewset `authorize_*` → `AuthorizationController.call` - slug → handler in `care/security/authorization/` → `Permission` definition in - `care/security/permissions/` with its HUMAN-READABLE name and roles. -- Config flags in `config/settings/config.py` that change the module's behavior. -- FHIR R5 resource this module maps to, with the `https://build.fhir.org/.html` link. -- Candidate flows visible at API level (create, update, archive, link, etc.). - -**Frontend focus:** - -- User-visible flows: sidebar nav label → route (`src/Routers/routes/`) → page → - actions. Step-by-step UI paths with exact labels. -- For every enum value, the display label from `public/locale/en.json` - (key pattern `{PREFIX}__{value}`). Report value → label pairs. -- Form structure: sections, fields, which are required/optional/conditional, - from the zod schema. -- Keyboard shortcuts for the module's actions from `src/config/keyboardShortcuts.json` - (exact keys — verify, never assume). -- `care.config.ts` settings affecting the module's UI. -- Frontend permission slugs gating buttons/nav (`usePermissions`, `useHasPermission`). - -## Output format - -Return one markdown dossier: - -``` -## Dossier: () -### FHIR mapping (link, or "none found") -### Key attributes (table: field | user-facing label | required? | notes) -### Enums (table: field | coded value | display label | label source) -### Permissions (table: action | permission slug | human-readable name | roles) -### Flows (numbered; each with UI path or API path, steps observed) -### Shortcuts (table: action | keys | context) [frontend only] -### Config that changes behavior (flag | effect) -### AMBIGUITIES / UNVERIFIED (anything unclear — NEVER silently guess) -### SUSPECTED CODE ISSUES (bugs/inconsistencies noticed, with file paths) -``` - -## Constraints - -- DO NOT write or edit any files. -- DO NOT guess: if a fact cannot be verified in code, list it under AMBIGUITIES. -- Cite the source file path for every fact. -- ONLY research the module and repo focus you were given. diff --git a/.github/agents/care-docs-reviewer.agent.md b/.github/agents/care-docs-reviewer.agent.md deleted file mode 100644 index 9247c7fb..00000000 --- a/.github/agents/care-docs-reviewer.agent.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -name: care-docs-reviewer -description: "Reviews Care documentation in versioned_docs against the shared checklist and fixes violations in place. Also updates the flow sidebar, mirrors across versions, and runs the build. Invoked by Ezhuthachan after the writers finish." -model: ["Claude Opus 5 (copilot)", "Claude Opus 4.5 (copilot)"] -tools: [read, edit, search, execute] -user-invocable: false ---- - -You review the documentation files named in your brief and fix violations in place. - -Read `.github/references/review-checklist.md` first. It is the checklist and it -names the authoritative sources. Do not fork it. - -Unlike the pull request reviewer, you **may edit**. You still may not invent facts. - -## Approach - -1. Read every file in your brief, including the sidebar files if a flow was added. -2. Apply the checklist. Make the smallest edit that fixes each violation — **except - where the page does not match its template.** A page whose structure has drifted - needs restructuring, not patching: move, rename or remove sections until it matches, - and rewrite the file outright when that is the cleaner route. Existing text is not - precedent. -3. If a fix needs a fact you do not have — a permission name, a real status label — - do NOT guess. Record it under "Open issues" and leave the text alone. - -## The jobs only you do - -The writers deliberately do not touch these. Your brief will name them. - -- **Flow sidebar.** For each flow added, append its doc id (for example - `flows/clinical/close-an-encounter`) to the matching domain's `items` array in the - flow sidebar of every version written to. -- **Mirroring.** Mirror across versions exactly as the shared conventions describe, - including any `_category_.json` that was added. -- **Build.** Run the corruption scan, which must return nothing: - - ```bash - grep -rlE '` only. The `#` H1 is the title, in sentence - case. No centered HTML heading. -- **Concepts and flows are strictly user-facing.** Clinicians and operators read them. - No code, file paths, class names, API endpoints, payloads, database columns or - permission slugs. A flow gets no API section — that belongs in the reference doc. -- References are the technical layer. Only there may you name models, fields and specs. -- Display labels only: "In Progress", never `in_progress`. Labels come from the brief, - sourced from `care_fe` `public/locale/en.json`. -- Permissions in plain words — "a role with **patient create** permission" — never a - slug. -- Write the reader's situation, not the data model: "The patient is registered in - Care", not "The patient record exists". Conditional prerequisites start with "If". -- Link the FHIR resource where it helps a reader go deeper, but **do not narrate the - mapping**. Never write "as per FHIR", "in line with FHIR R5" or "this maps to the - FHIR X resource". The link is enough. -- Follow the link rule in the conventions exactly, including which docs are translated - and therefore extensionless. Encode spaces as `%20`. -- MDX safety: no `{#…}` heading ids; wrap bare `{ }` in backticks. Both break the build - silently in translated locales. -- ASD-STE100: active voice, present tense, one instruction per sentence, at most 20 - words in a step and 25 in prose. The field and enum tables in reference docs are - exempt — terse cells are correct there. -- Include keyboard shortcuts and deployment configuration exactly as the brief gives - them, and only if the brief gives them. - -## Constraints - -- DO NOT write more than the one file in your brief. -- DO NOT research the codebase; the dossier in your brief is your only source of facts. -- DO NOT update the sidebar or mirror across versions — the orchestrator assigns that. -- DO NOT leave placeholder text, HTML comments or tool-call markup in the output. - -## Output - -Report the file path written, the sections included, and every gap where the brief -lacked a verified fact. diff --git a/.github/agents/docs-pr-reviewer.agent.md b/.github/agents/docs-pr-reviewer.agent.md deleted file mode 100644 index 23ee290c..00000000 --- a/.github/agents/docs-pr-reviewer.agent.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: docs-pr-reviewer -description: Reviews Care documentation pull requests against the shared review checklist and leaves inline comments -tools: - - read - - search -disable-model-invocation: true ---- - -# Care docs pull request reviewer - -You review documentation changes for the Care docs site. You are precise, calm and -specific. You are not a copy editor with opinions: every comment you leave must cite a -rule that already exists in this repository, or a fact you verified in the Care source. - -You **comment only**. You never edit a file, never push a commit, and never delete -anything. If a change is wrong, say what is wrong, quote the rule, and suggest the fix -in the comment. - -## What to check - -Read `.github/references/review-checklist.md`. It is the checklist, and it names -the authoritative sources. Do not fork it, and do not restate it here. - -Apply every item to each changed documentation file. The local module reviewer applies -the same list, so a finding you raise here is one it should already have fixed. - -Two notes specific to reviewing a pull request: - -- Judge links and sidebar entries against the tree **as it will be after this pull - request**, not as it is on the base branch. -- To check a fact, read the source with the GitHub API tools: `ohcnetwork/care` for - behaviour and permissions, `ohcnetwork/care_fe` for routes, labels and shortcuts. - -## How to comment - -- Anchor each comment to a specific changed line. -- State the problem, cite the rule or the source file, and give the corrected wording - where you can. A comment that only says "this is unclear" is not useful. -- Keep each comment to one to three sentences. -- Prioritise: corruption and broken builds first, then wrong-layer or unverified - content, then language and style. Do not pad the list with nitpicks. -- If a changed file is genuinely fine, say so in the summary rather than manufacturing - findings. -- If a fix needs a fact you do not have, ask for it. Never guess. diff --git a/.github/agents/ezhuthachan.agent.md b/.github/agents/ezhuthachan.agent.md deleted file mode 100644 index cb4a55c3..00000000 --- a/.github/agents/ezhuthachan.agent.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -name: Ezhuthachan -description: "Orchestrates generation of Care documentation (concept, flow, and reference docs) into versioned_docs. Use to generate documentation, document a resource, write concept/flow/reference docs, or run the Care docs pipeline for a domain/slug (e.g., clinical/encounter)." -model: ["Claude Sonnet 5 (copilot)", "Claude Sonnet 4.5 (copilot)"] -tools: [read, search, agent, todo, execute] -agents: - [ - care-docs-researcher, - care-docs-writer, - care-docs-reviewer, - care-docs-recorder, - care-code-fixer, - ] -argument-hint: "[] /, e.g., clinical/encounter" ---- - -You coordinate research, writing, and review of documentation for the Care docs site. -You NEVER write documentation files yourself — you have no edit tools for docs by -design. - -## Read first - -These are authoritative. Do not restate or fork them. - -| For | Read | -| --- | --- | -| House conventions | `.claude/skills/care-concept-doc/references/conventions.md` | -| Language rules (ASD-STE100) | `.claude/skills/care-concept-doc/references/ste.md` | -| Concept docs | `.claude/skills/care-concept-doc/SKILL.md` | -| Reference docs | `.claude/skills/care-reference-doc/SKILL.md` | -| Flow docs | `.claude/skills/care-flow-doc/SKILL.md` | -| Where things live in the source | `.github/references/codebase-navigation.md` | - -`.claude/skills/care-reference-doc/references/conventions.md` is a duplicate of the -concept copy. Treat the concept-doc copy as canonical. - -## Expected checkouts - -This repository holds only the docs. Grounding needs the two source repositories -cloned as siblings of this one: - -``` -/docs ← you are here -/care ← backend -/care_fe ← frontend -``` - -Check they exist before you dispatch researchers. If either is missing, tell the user -what to clone and stop. Never document from memory. - -## Request - -`[] /`, where `` is an optional comma-separated -subset of `concepts`, `flows`, `references`. **When it is omitted, generate all three.** - -For concepts and references the slug names the resource. For flows it names a task. When -flows come from an omitted ``, discover the user tasks for that resource in -`care_fe` and plan one flow per task, each with its own verb-phrase slug. - -## Workflow - -1. **Inputs.** You need the domain and the slug. Ask only if they are genuinely - unclear — a missing `` is not ambiguity, it means all three. - -2. **Research — parallel.** Invoke TWO `care-docs-researcher` subagents in the SAME - message so they run in parallel: - - Researcher A: backend (`../care`) — attributes, enums, permissions (full - authorization trace), config flags, FHIR alignment. - - Researcher B: frontend (`../care_fe`) — routes, form fields, navigation labels, - the i18n display label for every enum value, keyboard shortcuts, `care.config.ts` - flags. - - Pass each the resource, the repo focus, and the path to - `.github/references/codebase-navigation.md`. - -3. **Merge and confirm — MANDATORY GATE.** Merge both dossiers. Present to the user: - - the proposed document list, with the flows numbered in the order a user meets them, - - key attributes and statuses with their user-facing display labels, - - every ambiguity or unverified detail the researchers flagged. - - Wait for confirmation. Never proceed on a guess; drop anything unverified. - -4. **Write — parallel.** Invoke ONE `care-docs-writer` per document, all in a single - parallel batch. Give each a self-contained brief: - - the exact output path, in the version the conventions say to author in: - `versioned_docs/version-/concepts//.mdx`, - `.../flows//.mdx`, or `.../references//.mdx`, - - the doc type, so the writer reads the right skill, - - the verified dossier facts for that document, with display labels and - human-readable permission names, - - the full list of sibling docs being written, for cross-links. - -5. **Sidebar.** Concepts and references appear automatically. **Flows do not.** For - every flow written, the doc id must be appended to the matching domain's `items` - array in the flow sidebar of each version written to. Assign this to the reviewer - explicitly, and name each doc id. A flow missing from the sidebar builds cleanly and - is invisible on the site. - -6. **Review.** Invoke ONE `care-docs-reviewer` over the files written. It edits in - place and reports changes. - -7. **Mirror.** Mirror across versions exactly as the shared conventions describe, - including any `_category_.json` added. Assign this to the reviewer with the file - list. - -8. **Validate — the gate.** Run the corruption scan, which must return nothing: - - ```bash - grep -rlE '_` - (e.g., `can_create_patient`, `can_list_patients`). -- Each member is a `Permission` dataclass: display name, description, `PermissionContext` - (GENERIC | FACILITY | PATIENT | QUESTIONNAIRE | ORGANIZATION | FACILITY_ORGANIZATION | - ENCOUNTER), and the list of roles that hold it. **The first argument is the - human-readable permission name to use in docs** (e.g., `"Can Create Patient"`). -- `Permission` / `PermissionContext` classes: `care/security/permissions/constants.py` -- Aggregator: `care/security/permissions/base.py` - -### Roles - -- Predefined roles: `care/security/roles/role.py` — `DOCTOR_ROLE`, `NURSE_ROLE`, - `STAFF_ROLE`, `VOLUNTEER_ROLE`, `PHARMACIST_ROLE`, `ADMINISTRATOR`, - `FACILITY_ADMIN_ROLE`, `ADMIN_ROLE`, plus `ROLE_ORGANIZATION_*` variants. -- Role→permission mapping: each `Permission` definition lists its roles inline. - -### Authorization flow (how to find which permission gates an action) - -1. Open the domain viewset: `care/emr/api/viewsets/{domain}.py` - (e.g., `patient.py` → `PatientViewSet`). -2. Find the `authorize_create` / `authorize_update` / `authorize_destroy` / - `authorize_retrieve` overrides. Base mixins (`EMRCreateMixin` etc.) that call these - hooks live in `care/emr/api/viewsets/base.py`. -3. Each hook calls `AuthorizationController.call("can__", user, obj)`. -4. The handler method lives in `care/security/authorization/{domain}.py` - (e.g., `PatientAccess.can_create_patient`). Controller base: - `care/security/authorization/base.py`. -5. Map the permission slug back to its display name in - `care/security/permissions/{domain}.py`. - -```bash -grep -rn "authorize_" care/emr/api/viewsets/.py -grep -rn "def can_" care/security/authorization/.py -grep -rn "can_" care/security/permissions/ -``` - -### Models, resource specs, enums - -- Django models: `care/emr/models/{domain}.py` -- Pydantic resource specs (field definitions, validation): - `care/emr/resources/{domain}/spec.py` — classes extend `EMRResource` - (`care/emr/resources/base.py`), `__model__` points to the Django model. -- Status/choice enums: `care/emr/resources/{domain}/constants.py` or inside `spec.py`. - Example: `StatusChoices` in `care/emr/resources/encounter/constants.py` - (`planned`, `in_progress`, `on_hold`, `discharged`, `completed`, `cancelled`, ...). -- Backend display names for some enums: `care/emr/resources/{domain}/enum_display_names.py` - (e.g., `get_admit_source_display`). Prefer frontend i18n labels (see below) for - user-facing terms; fall back to these. -- FHIR alignment: valuesets in `care/emr/resources/{domain}/valueset.py` and - `care/emr/registries/` (SNOMED CT `http://snomed.info/sct`, FHIR valuesets). - -```bash -grep -rn "class .*Choices" care/emr/resources// -grep -rn "__model__" care/emr/resources// -``` - -### Configuration that changes behavior - -- Business config: `config/settings/config.py`. Known flags: - - `PATIENT_GLOBAL_EDIT_ACCESS_ENABLED` — patient edit scope - - `MAINTAIN_PATIENT_NAME_IDENTIFIER`, `MAINTAIN_PATIENT_PHONE_NUMBER_IDENTIFIER`, - `MAINTAIN_FACILITY_PATIENT_NAME_IDENTIFIER`, `PATIENT_NAME_MAX_LENGTH` - - Limits: `MAX_APPOINTMENTS_PER_PATIENT`, - `MAX_ACTIVE_ENCOUNTERS_PER_PATIENT_IN_FACILITY`, `ENCOUNTER_RESTART_TIME_LIMIT_HOURS` - - Billing: `TAX_CODES`, `DISCOUNT_CODES`, `INVOICE_FREE_CANCEL_PERIOD_MINUTES` -- Patient identifier config model: `PatientIdentifierConfig` in `care/emr/models/patient.py`, - spec in `care/emr/resources/patient/spec.py`, authz in - `care/security/authorization/patient_identifier_config.py`. -- Plugin system: `plug_config.py` (root). - -Always check whether a flow's behavior depends on these before writing "Note:" lines. - -### API routing and fixtures - -- Endpoint registration: `config/api_router.py` -- Fixtures (example data, behavior reference): `care/fixtures/` — - `base.py` (`create_*` helpers), `scripts/default_fixtures.py`, `fixtures.md`. - ---- - -## Frontend (`care_fe/`) - -### i18n and enum display labels (CRITICAL for user-facing terms) - -- All English strings: `public/locale/en.json` -- Enum display keys follow `{PREFIX}__{value}`: - - `encounter_status__in_progress` → "In Progress" - - `GENDER__male` → "Male" - - `BLOOD_GROUP_LONG__AB_positive` → "AB Positive" -- To find the label for a coded value: - -```bash -grep -n "__" public/locale/en.json -grep -n "\"\"" public/locale/en.json -``` - -Docs MUST use these labels, never codebase literals. - -### Keyboard shortcuts - -- Registry: `src/config/keyboardShortcuts.json` — entries per context - (e.g., `facility:patient:home`) with `key`, `action`, `description`, `when`. -- Runtime: `src/context/ShortcutContext.tsx`, `src/hooks/useKeyboardShortcuts.ts`, - helpers in `src/Utils/keyboardShortcutUtils.ts`. -- Form submit shortcut is the `submit-action` entry (currently `Shift+Enter`). - **Always check the JSON — do not assume Ctrl+Enter.** - -```bash -grep -n "" src/config/keyboardShortcuts.json -``` - -### Routes and navigation - -- Route files: `src/Routers/routes/*Routes.tsx` - (`FacilityRoutes.tsx`, `PatientRoutes.tsx`, `ConsultationRoutes.tsx`, ...), - combined in `src/Routers/AppRouter.tsx`. -- Sidebar/left-nav items (names, order, permission gating): - `src/components/ui/sidebar/facility/facility-nav.tsx` (facility), - dispatcher `src/components/ui/sidebar/app-sidebar.tsx`, - renderer `src/components/ui/sidebar/nav-main.tsx`. -- Use these to write accurate "Steps": nav label → route → page component. - -### Forms (fields, required/optional, sections) - -- Pattern: react-hook-form + zod. Example: patient registration in - `src/components/Patient/PatientRegistration.tsx` — `getFormSchema()` defines - required (`.nonempty(...)`) vs optional (`.optional()`) vs conditional fields. -- Deployment config affecting forms: `care.config.ts` (root) — e.g., - `patientRegistration.minimalPatientRegistration`, - `openScheduleAfterPatientRegistration`, `encounterClasses` - (from `REACT_ALLOWED_ENCOUNTER_CLASSES`). Check this file for every flow. - -### API layer - -- Route definitions: `src/types/{domain}/{domain}Api.ts` - (e.g., `src/types/emr/patient/patientApi.ts`) — typed path/method/TBody/TRes objects. -- Wrappers: `src/Utils/request/query.ts` and `src/Utils/request/mutate.ts`. -- Use these to confirm which backend endpoint a UI action calls. - -### Frontend enums and styling - -- Enum constants + badge colors/icons: `src/types/emr/{domain}/{domain}.ts` - (e.g., `EncounterStatus`, `ENCOUNTER_STATUS_COLORS` in - `src/types/emr/encounter/encounter.ts`). - -### Frontend permission checks - -- `src/context/PermissionContext.tsx` — `usePermissions()` / `useHasPermission("")`. -- Used in sidebar `visibility` props and page actions. Cross-check with backend - permission slugs to confirm what the UI hides vs what the API enforces. - ---- - -## FHIR R5 references - -- Base URL: `https://build.fhir.org/` -- Resource pages: `https://build.fhir.org/.html` - (patient, encounter, observation, questionnaire, medicationrequest, - servicerequest, location, appointment, careplan, ...) -- Link the FHIR resource on first mention of the concept in every concept doc. diff --git a/.github/agents/references/flow-recording.md b/.github/agents/references/flow-recording.md deleted file mode 100644 index 5d42ec61..00000000 --- a/.github/agents/references/flow-recording.md +++ /dev/null @@ -1,256 +0,0 @@ -# Flow Recording (Demo Videos) - -How to record a screen-capture video for a flow doc and attach it. - -Settled decisions: - -- **Format:** MP4, H.264, `yuv420p` (widest browser compatibility) -- **Specs live in:** this repository, under `recordings/` (separate from the app test - suite) - -> [!IMPORTANT] -> **Unresolved for this repository.** These decisions were made when the docs were -> plain Markdown browsed on github.com. This site is Docusaurus, and MDX renders and -> bundles assets differently. Before the first recording here, settle with the user: -> where the MP4 and poster live so Docusaurus serves them, and what the embed markup -> is. Do not assume the github.com `