medplum-rules

medplum-rules:针对 Medplum(FHIR 医疗)的编码规范集合,包含风格、模式、安全性与测试相关要求。触发条件:medplum.config.mts、medplum.config.ts、FHIR、Medplum、Bot、Subscription、Questionnaire。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "medplum-rules":https://skillpi.com/zh/skills/deepskill-20f3f11e9579c5274c594d5497083072da8883027eed516575f034dedae9e193。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

medplum-rules:针对 Medplum(FHIR 医疗)的编码规范集合,包含风格、模式、安全性与测试相关要求。触发条件:medplum.config.mts、medplum.config.ts、FHIR、Medplum、Bot、Subscription、Questionnaire。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: medplum-rules
description: "Medplum (FHIR healthcare) coding rules: style, patterns, security, testing. Triggers: medplum.config.mts, medplum.config.ts, FHIR, Medplum, Bot, Subscription, Questionnaire."
effort: medium
user-invocable: false
allowed-tools: Read

Medplum (FHIR healthcare) Rules

These rules come from app/rules/medplum/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Medplum (FHIR healthcare). Apply them when writing or reviewing Medplum (FHIR healthcare) code.

Medplum / FHIR Coding Style

Resource Structure

  • Every FHIR object must include resourceType as first field.
  • Use PascalCase for resource types (Patient, ServiceRequest), camelCase for fields (birthDate, valueQuantity).
  • Never hardcode resource IDs. Let the server assign them on create.
  • Include meta.profile when creating resources that must conform to a StructureDefinition.

References

  • Use createReference(resource) from @medplum/core to build Reference objects.
  • Always include display on references for human readability.
  • Use getReferenceString(resource) for comparisons and logging — returns ResourceType/id.
  • Use parseReference(ref) to extract resourceType and id from a reference string.
  • Never concatenate strings to build references manually.

CodeableConcepts & Coding

  • Always include system, code, and display in every Coding element.
  • Use standard terminology URIs: http://loinc.org, http://snomed.info/sct, http://hl7.org/fhir/sid/icd-10-cm.
  • Use getCodeBySystem(cc, system) to find codes; setCodeBySystem(cc, system, code) to set them.
  • Prefer CodeableConcept over plain Coding when the FHIR spec allows both — it supports multiple codings and free text.

Identifiers

  • Use identifier arrays with system + value for external IDs (MRN, NPI, SSN).
  • Use getIdentifier(resource, system) and setIdentifier(resource, system, value) helpers.
  • Identifier systems must be absolute URIs (e.g., http://hl7.org/fhir/sid/us-npi).
  • Use createResourceIfNoneExist(resource, 'identifier=system|value') for idempotent creates.

Extensions

  • Use the extension array with url and typed value[x] fields.
  • Prefer official HL7/US Core extensions over custom ones where they exist.
  • Use getExtension(resource, url) and getExtensionValue(resource, url) helpers.

Bundles

  • Use urn:uuid:<uuid> for internal references between entries in a transaction Bundle.
  • Every Bundle entry must have request.method (POST, PUT, DELETE) and request.url.
  • Include fullUrl on entries that are referenced by other entries.
  • Use conditional references (Practitioner?identifier=npi|123) for existing resources.

HIPAA-Aware Coding

  • Identifiers like SSN, MRN, and insurance IDs are PHI — never log raw values to console or external services.
  • Use a safe logging utility (e.g., safeLog()) for any output that might contain patient data. Never console.log raw FHIR resources.
  • Reference display strings may contain patient names — treat as PHI in logs and error messages.
  • Every new data access path or admin operation must include corresponding AuditEvent creation. No exceptions.
  • When audit logging fails (Medplum unreachable), write to a fallback store — audit events must never be silently dropped.
  • See security.md rules for full HIPAA, access policy, and PHI handling requirements.

Formatting

  • Use formatHumanName(), formatAddress(), formatDate(), formatQuantity() for display strings.
  • Use getDisplayString(resource) as a universal fallback for any resource's display name.
  • Never manually concatenate name parts — FHIR names have given[], family, prefix[], suffix[].

Medplum Frameworks

@medplum/core — SDK Client

  • Use MedplumClient for all FHIR operations. Never use raw fetch against Medplum endpoints.
  • Use medplum.createResource(), readResource(), updateResource(), deleteResource() for CRUD.
  • Use medplum.searchResources() for typed arrays. Use medplum.searchOne() when expecting a single result.
  • Use medplum.executeBatch() for transaction Bundles — groups multiple operations atomically.
  • Use medplum.upsertResource(resource, query) for atomic create-or-update.
  • Use medplum.createResourceIfNoneExist(resource, query) for idempotent creation.
  • Configure autoBatchTime on MedplumClient to auto-batch concurrent GET requests. Use Promise.all() instead of sequential await to benefit from batching.

@medplum/fhirtypes — Type Safety

  • Import FHIR types directly: import { Patient, Observation } from '@medplum/fhirtypes'.
  • Use TypeScript types for all FHIR resources — never use any for resource data.
  • Cast event.input in bot handlers: const patient = event.input as Patient.
  • Use optional chaining for nested FHIR fields: patient.name?.[0]?.given?.[0].

@medplum/react — UI Components

  • Wrap app with <MedplumProvider client={medplum}> at the root.
  • Use useMedplum() hook to access the MedplumClient instance in components.
  • Use useMedplumContext() for client + profile + loading state together.
  • Use <ResourceForm> for auto-generated CRUD forms, <ResourceTable> for display.
  • Use <SearchControl> for searchable/filterable resource lists.
  • Use <QuestionnaireForm> to render FHIR Questionnaires and capture responses.
  • Use useSubscription(criteria) for real-time WebSocket data in React components.
  • Requires Mantine 7+ and PostCSS with Mantine preset. Import @mantine/core/styles.css.

Bot Development

  • Export a single handler function: export async function handler(medplum: MedplumClient, event: BotEvent).
  • Access trigger resource via event.input. Access secrets via event.secrets.
  • Use event.contentType to determine input format (application/fhir+json, text/plain, x-application/hl7-v2+er7).
  • Deploy bots via CLI for CI/CD: medplum bot deploy <bot-name>.
  • Apply AccessPolicies to bots — restrict to minimum required resource types.
  • Use Subscriptions with channel.type: 'rest-hook' and channel.endpoint: 'Bot/<ID>' for event-driven execution.

GraphQL

  • Append List to resource type for searches: PatientList(name: "Eve").
  • Use snake_case for search parameters in GraphQL (not kebab-case): address_city, not address-city.
  • Use inline fragments for reference resolution: ... on Observation { valueQuantity { value } }.
  • Use _reference for reverse lookups: EncounterList(_reference: patient).

CLI (@medplum/cli)

  • Use medplum login for auth, medplum get/medplum post for FHIR operations.
  • Use medplum bot deploy for bot deployment in CI/CD pipelines.
  • Use medplum bulk export for bulk data operations.

Medplum / FHIR Patterns

Bundle Transactions

  • Use type: 'transaction' for atomic multi-resource operations — all-or-nothing.
  • Use type: 'batch' when operations are independent and partial failure is acceptable.
  • Use urn:uuid:<uuid> in fullUrl for forward references between entries.
  • Reference other entries via { reference: 'urn:uuid:<uuid>' }.
  • Use ifNoneExist on POST entries for conditional creation (idempotent).
  • Use ifMatch: 'W/"versionId"' on PUT entries for optimistic concurrency.
  • Use conditional references for existing resources: Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|123.
  • For large bundles (>50MB), use Prefer: respond-async header.

Search Patterns

  • Use _include=ResourceType:searchParam to fetch referenced resources in one call.
  • Use _revinclude=ResourceType:searchParam to fetch resources referencing your results.
  • Use :iterate modifier for multi-hop traversal: _include:iterate=Patient:general-practitioner.
  • Use _count + _offset for pagination; use searchResourcePages() for async iteration.
  • Use :contains modifier for substring search on string params: name:contains=eve.
  • Use :not modifier to exclude: status:not=completed.
  • Use comma-separated values for OR: status=active,on-hold.
  • Use multiple parameters for AND: name=Simpson&birthdate=1940-03-29.
  • Prefer searchResources() over search() — returns typed array, not raw Bundle.

Subscription & Bot Workflows

  • Create a Subscription resource with criteria (FHIR search query) and channel.type: 'rest-hook'.
  • Point channel.endpoint to Bot/<BOT_ID> for automated processing.
  • Use subscribeToCriteria() client-side for WebSocket real-time updates.
  • Never subscribe to AuditEvent changes — prevents notification spirals.
  • Use cron-based bots for scheduled tasks (e.g., daily reports, batch processing).

Access Policies

  • Define AccessPolicy.resource[] with resourceType and optional criteria, readonly, hiddenFields, readonlyFields.
  • Use %profile variable to scope data to the current user: Observation?performer=%profile.
  • Use %patient variable for patient-portal access: Observation?subject=%patient.
  • Use compartment-based access for patient-scoped isolation.
  • Use writeConstraint with FHIRPath for state machine enforcement (e.g., prevent status rollback).
  • Apply least privilege: start with no access, add specific resource types.

Conditional Operations

  • Use createResourceIfNoneExist(resource, query) for idempotent creates keyed on identifier.
  • Use upsertResource(resource, query) for atomic create-or-update in a single request.
  • Use If-None-Exist header on POST for server-side conditional creation.

Patient Deduplication

  • Match on identifier systems (MRN, SSN, insurance ID) for deterministic matching.
  • Use probabilistic matching on name + birthdate + address for fuzzy matches.
  • Use Patient link field with type: 'replaced-by' for merge workflows.
  • Prefer createResourceIfNoneExist() at ingestion to prevent duplicates.

Questionnaire Workflows

  • Create Questionnaire resources for form definitions. Use linkId for question identification.
  • Use QuestionnaireResponse for captured answers. Link to Questionnaire via questionnaire field.
  • Use getQuestionnaireAnswers(response) to extract answers as a map keyed by linkId.
  • Automate post-submission processing with a Bot subscribed to QuestionnaireResponse creation.
  • Use SDC (Structured Data Capture) extensions for advanced rendering and extraction.

Medplum / FHIR Security

Authentication

  • Use client credentials flow (startClientLogin) for backend services and integrations.
  • Use authorization code flow (startLogin + processCode) for user-facing web apps.
  • Never store tokens in localStorage in production — use secure HTTP-only cookies or server-side sessions.
  • Use refreshIfExpired() before critical operations. Set gracePeriod to refresh proactively.
  • Use setBasicAuth(clientId, clientSecret) only for server-side code, never in browser.
  • Rotate client secrets via $rotate-client-secret operation periodically.

Access Policies

  • Every non-admin user must have an AccessPolicy. Never leave users with default full access.
  • Scope to specific resource types: list only the types the user needs.
  • Use readonly: true or explicit interaction arrays to restrict write access.
  • Use criteria with FHIR search syntax to filter visible resources (e.g., Patient?organization=Organization/123).
  • Use hiddenFields to prevent sensitive fields from being returned (e.g., SSN).
  • Use readonlyFields to allow viewing but prevent modification of specific fields.
  • Use writeConstraint FHIRPath expressions for business rules (e.g., prevent status rollback on finalized resources).
  • Test access policies by logging in as a test user with the policy applied.

HIPAA & Audit Logging

  • Medplum automatically creates AuditEvent resources for all FHIR operations.
  • Never log PHI (patient names, identifiers, health data) to application console or external services.
  • Use structured audit references: reference the Patient and the accessing Practitioner in audit records.
  • For custom audit trails, create AuditEvent resources with type, agent, entity, and outcome.
  • Ensure audit events are never silently dropped — if Medplum is unreachable, write to a fallback store.

PHI Handling

  • Never include PHI in URLs, query parameters, or HTTP headers.
  • Use POST-based search for queries containing sensitive criteria.
  • Use Binary resources with securityContext for sensitive file attachments.
  • Encrypt data at rest and in transit (TLS 1.2+). Medplum hosted handles this automatically.
  • Apply data retention policies — use $expunge operation for permanent deletion when required.

SMART Scopes

  • Use patient/*.read style scopes for patient-facing apps.
  • Use user/*.read style scopes for practitioner-facing apps.
  • Validate scopes server-side on every request — do not trust client-side scope claims.
  • Use launch/patient context for apps launched within a patient context.
  • Define minimal scopes: request only the resource types and operations needed.

Multi-Tenant Isolation

  • Use Medplum Projects for tenant isolation — each project is a separate data silo.
  • Never share AccessPolicies across projects/tenants.
  • Validate meta.project on operations when building multi-tenant middleware.
  • Use separate ClientApplications per tenant for backend integrations.

Secrets Management

  • Use Bot secrets (event.secrets) for API keys, connection strings, and credentials.
  • Never hardcode secrets in bot source code or resource data.
  • Use Medplum project-level secrets storage — accessible only by project admins.
  • Rotate secrets on a regular schedule and after any suspected compromise.

Medplum / FHIR Testing

MockClient

  • Use MockClient from @medplum/mock for unit tests — it simulates the full MedplumClient API in memory.
  • Pre-populate test data with mockClient.createResource() before running test assertions.
  • MockClient supports search, searchResources, searchOne, readResource, updateResource, deleteResource.
  • MockClient does not require network access — tests run fast and offline.
  • Use new MockClient() per test to ensure isolation between test cases.

Bot Unit Testing

  • Test the handler function directly: await handler(mockClient, mockEvent).
  • Create mock BotEvent objects with input, contentType, secrets, and bot fields.
  • Verify resource creation: call mockClient.searchResources() after handler execution.
  • Test error paths: pass invalid input resources and assert the handler throws or returns errors.
  • Test different content types: application/fhir+json, text/plain, x-application/hl7-v2+er7.
  • Mock event.secrets for bots that depend on external API keys.

Resource Validation

  • Use validateResource(resource) from @medplum/core to check resources against StructureDefinitions.
  • Test that required fields produce OperationOutcome errors when missing.
  • Test custom profiles: create a StructureDefinition resource, then validate resources against it.
  • Use the $validate operation for server-side validation in integration tests.
  • Test the Data Absent Reason extension when required fields may legitimately be empty.

Search Testing

  • Test search parameter behavior: exact match vs prefix match vs substring (name, name:exact, name:contains).
  • Verify _include returns related resources in the Bundle.
  • Test pagination with _count and _offset parameters.
  • Test token search with and without system namespace: identifier=value vs identifier=system|value.
  • Test date range searches with comparison prefixes: ge, le, gt, lt.

Integration Testing

  • Use Medplum Docker image (medplum/medplum-server) for local integration tests.
  • Test full workflows end-to-end: create patient → create observation → search → verify.
  • Verify Bundle transactions are atomic: intentionally fail one entry and confirm rollback.
  • Test access policies by authenticating as users with different policies.
  • Test Subscription triggers: create a Subscription, modify a matching resource, verify Bot execution.

Test Data Factories

  • Create typed factory functions: createTestPatient(overrides?), createTestObservation(overrides?).
  • Use realistic but synthetic data — never use real patient data in tests.
  • Include only minimal required fields by default. Let tests add specific fields via overrides.
  • Use generateId() from @medplum/core for unique test identifiers.
  • Use standard test identifier systems: http://example.com/test-mrn to avoid collision with real systems.

Assertions

  • Assert on OperationOutcome for error responses: check issue[].severity, issue[].code, issue[].expression.
  • Use isOk(outcome) and isNotFound(outcome) from @medplum/core for status checks.
  • Use deepEquals(a, b) for resource comparison (ignores meta.versionId and meta.lastUpdated).
  • Assert reference integrity: verify subject.reference matches expected Patient/id format.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供 Medplum(FHIR 医疗)全栈编码规范,涵盖风格、框架、模式、安全与测试
  • 面向医疗健康开发者,解决 FHIR 资源建模、HIPAA 合规、Bot 开发等核心痛点
触发精准90/100

亮点

  • 触发词精准覆盖 Medplum 配置文件、FHIR 资源类型及核心组件(Bot/Subscription)
结构规范95/100

待提升项

  • description 内容重复 原报告严重程度:轻微

    顶层 frontmatter 和 skill_body 内部均包含相同 description,存在轻微冗余

    改进建议:建议保留一处 description,避免重复

亮点

  • 文档结构清晰,分五大模块,条目化呈现,便于查阅
  • frontmatter 完整,单文件长度适中(约 450 行)
执行可靠90/100

亮点

  • 引用官方 @medplum 工具包,参数与模式描述准确
  • 作为静态规范文档,无动态执行风险,可靠性高
证据可验 (前四项均值)92/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 172, 217 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • example.com
  • hl7.org
  • loinc.org
  • snomed.info

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。