[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69BW0D2HDW3YFJJX4QEYJF2":3,"skill-same:01M69BW0D2HDW3YFJJX4QEYJF2":80},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":50,"linkOnly":51,"markdownContent":52,"markdownBody":53,"frontMatter":54,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":61,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M69BW0D2HDW3YFJJX4QEYJF2","state","Microsoft 托管应用状态与附件管理","Store and query a Microsoft Managed App's built-in state and file attachments with `ms project state` CLI schema commands and generated TypeScript clients. First, with the user signed in to the CLI, run `ms feature status --name state --json`; if `feature.enabled` is not `true`, recommend an alternative connector or data source.","使用 `ms project state` CLI schema 命令和生成的 TypeScript 客户端，存储与查询 Microsoft 托管应用的内置状态和文件附件。首先，在用户登录 CLI 后运行 `ms feature status --name state --json`；如果 `feature.enabled` 不为 `true`，则推荐替代的连接器或数据源。","microsoft\u002Fmanaged-apps","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69BTSR13CCGCPK40C03N7CN",36,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fstate\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BWKS60NTYJHFE9FQSXGDKS","低代码应用开发","SCENARIO","使用场景",[5,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"Bash","feature","source","data","commands","recommend","edit","write","read","Connector","query","generated","project","ms","app","typescript","run","cli","status","2026-11-10 10:12:30",false,"---\nname: state\ndescription: Store and query a Microsoft Managed App's built-in state and file attachments with `ms project state` CLI schema commands and generated TypeScript clients. First, with the user signed in to the CLI, run `ms feature status --name state --json`; if `feature.enabled` is not `true`, recommend an alternative connector or data source.\nallowed-tools: Read Edit Write Grep Glob Bash AskUserQuestion\n---\n\n**? Shared Instructions: [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md)** — Cross-cutting concerns.\n\n# Managed Apps State with CLI schema + generated client\n\nEvery Microsoft Managed App can use built-in app state when the `state` feature is enabled for the\ncurrent CLI\u002Fenvironment: a NoSQL store the app calls directly (no middle-tier function, connector,\nor SDK; the host attaches auth). Records are grouped into collections by an item type name; the\nserver assigns each record an `itemId`.\n\nFor schema-backed state, **do not edit schema JSON by hand.** Use `ms project state ...` to change\nthe schema, run `ms project state generate-code`, then call the generated TypeScript services from\napp code.\n\n## Mandatory feature gate\n\nBefore using any guidance in this skill, it is recommended that the user is signed in to the CLI. Run\n`ms auth status`, and if it reports no signed-in account, ask the user to run `ms auth login`.\n`ms feature status` never prompts for sign-in, and features that are on by default for the user's\norganization only apply once they are signed in, so a signed-out check can report `state` as\ndisabled even when it is available to them.\n\nThen run:\n\n```bash\nms feature status --name state --json\n```\n\nContinue only when the output has `\"success\": true` and `feature.enabled` is `true`. Read the JSON\nrather than the human-readable output, which lists several settings that can each say \"enabled\". If\nthe command fails (non-zero exit or `\"success\": false`), the feature is not found, or\n`feature.enabled` is `false`, stop and do **not** run any `ms project state ...` command.\n\nWhen state is not enabled, recommend an alternative data-source path based on the user's need:\n\n- Durable relational\u002Fbusiness data: use `\u002Fadd-dataverse`.\n- SharePoint lists or document-backed collaboration data: use `\u002Fadd-sharepoint`.\n- Workbook-backed tabular data: use `\u002Fadd-excel`.\n- Mail, calendar, user profile, Teams, Azure DevOps, OneDrive, Copilot Studio, or Work IQ scenarios:\n  use the matching `\u002Fadd-*` skill.\n- Anything else: use `\u002Fadd-data-source` to discover and bind the appropriate connector.\n\nDo not suggest manual schema edits or custom proxy workarounds as a substitute for the disabled\nfeature.\n\n## ⚠️ Local testing requires local gateway mode\n\nGenerated state services require the Managed Apps local gateway path during local development.\nBefore testing data behavior locally, make sure the app has `@microsoft\u002Fmanaged-apps-vite-plugin`\n0.4.2 or later (the version that added `devMode: 'localGateway'`; older versions won't start the\nlocal gateway), then opt the app into local gateway mode.\n\nCheck the installed version first, for example with `npm ls @microsoft\u002Fmanaged-apps-vite-plugin`\n(or read `version` in `node_modules\u002F@microsoft\u002Fmanaged-apps-vite-plugin\u002Fpackage.json`). If it is\n0.4.2 or later, skip the install. If it is missing or older, install the latest with the app's\npackage manager:\n\n```bash\nnpm install -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: bun add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: pnpm add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: yarn add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n```\n\nThen update the app's `vite.config.ts` so the `managedApps()` plugin call enables the local gateway,\npreserving any existing options:\n\n```ts\nmanagedApps({\n  ...existingOptions,\n  devMode: 'localGateway',\n})\n```\n\nNow run local dev normally:\n\n```bash\nms app dev\n```\n\nDo not change the app architecture just to work around local data failures (no middle-tier\nfunctions, proxies, or CORS\u002Fauth workarounds). Fix the Vite plugin\u002Flocal gateway setup instead.\n\n## Contract\n\n| Surface | Use | Don't use |\n| --- | --- | --- |\n| Feature gate | `ms feature status --name state --json` (`feature.enabled`), with the user signed in, before any state work | assuming the feature is available |\n| Schema edits | `ms project state add`, `alter`, `remove`, `set-setting` | manual edits to `state\u002Fschema.json`, `ms.schema.json`, or another configured schema file |\n| Code generation | `ms project state generate-code` | handwritten model\u002Fservice\u002Fvalidator files in the generated output folder |\n| App data access | generated services, models, validators, and typed query helpers | treating direct state requests as the default when codegen covers the scenario |\n| File attachments | direct upload to `\u002F.ms\u002Fstate\u002Fattachments`, then save the returned URL through a generated service | storing file bytes inside items |\n| Testing data behavior | Vite plugin 0.4.2+ + `managedApps({ devMode: 'localGateway' })` + `ms app dev`; Preview for pre-deploy validation | local dev without local gateway mode |\n\nThe generated services own request shapes, ETags, typed filters, paging, validation hooks, per-user\nscope behavior, and service route details. App code should compose those services with UI\u002Fbusiness\nlogic instead of duplicating transport behavior.\n\n## Workflow\n\n1. Make sure the user is signed in (`ms auth status`; ask them to run `ms auth login` if not), then\n   run `ms feature status --name state --json`. Stop and recommend a connector alternative unless\n   `feature.enabled` is `true`.\n2. Find the app root (`ms.config.json`) and the configured schema path.\n3. Inspect existing state schema\u002Fsettings with `ms project state list-schema` and\n   `ms project state list-settings`.\n4. For each new collection, decide up front whether records are per-user (see below).\n5. Make schema changes only with `ms project state ...` commands.\n6. Run `ms project state generate-code` after every successful schema change.\n7. Import and use the generated TypeScript services from app code.\n8. Configure local gateway mode before local data testing.\n9. Build\u002Ftypecheck and verify that generated services are used for behavior covered by codegen.\n\n## Schema setup\n\nFind the app root (`ms.config.json`) and the configured schema path. Prefer `state.schemaPath`; older\napps may use `data.schemaPath` or legacy `db.schemaPath`.\n\n```json\n{\n  \"state\": {\n    \"schemaPath\": \"state\u002Fschema.json\",\n    \"enabled\": true\n  }\n}\n```\n\nIf no schema path exists yet, start by adding the first collection with the CLI. It writes\n`state.schemaPath: \"state\u002Fschema.json\"`, creates the schema file, and sets `enabled: true` unless the\nconfig already sets `enabled`; don't ask the user to hand-configure schema wiring first. The app\nserves no state while `enabled` is `false`, so confirm with the user before changing an explicit\n`false`. New schemas take the machine's locale (or `en-US`); match the app's users with\n`ms project state set-setting --locale \u003Ctag>`.\n\nInspect the current schema:\n\n```bash\nms project state list-schema\nms project state list-settings\n```\n\n## CLI schema commands\n\n### Add a collection\n\n```bash\nms project state add --collection task\n```\n\n### Add properties\n\n```bash\nms project state add --collection task --property name --type string --required true --max-length 200 --index true --index-ignore-case true\nms project state add --collection task --property done --type boolean\nms project state add --collection task --property dueDate --type datetime --index true\nms project state add --collection task --property attachment --type binary --kind binary\n```\n\n- **Types:** `string`, `number`, `integer`, `boolean`, `datetime`, `guid`, `binary`.\n- **Boolean flags take values:** `--required true`, `--index false`, etc. They are not bare\n  switches.\n- **Indexes:** at most four custom indexed properties per collection, top-level scalars only. Only\n  indexed properties (plus `itemId`, `name`, `createdTime`, `modifiedTime`) can be filtered or sorted.\n- **Name property:** prefer a human-readable `name` property for each item (put a single-string\n  item's text there). It is writable, indexed, sortable\u002Ffilterable, and generated services treat it\n  as the display\u002Ftitle field.\n\n### Alter a property\n\n```bash\nms project state alter --collection task --property name --max-length 200\nms project state alter --collection task --property done --required false\nms project state alter --collection task --property name --max-length \"\"\n```\n\nOnly pass the flags you intend to change. Empty string clears a type-specific constraint where the\nCLI supports clearing.\n\nIndexes are add-only. Removing an index or changing its options (including the platform index on\n`name`) is rejected even before the first deploy, so choose `--index-ignore-case` and\n`--index-ignore-accents` when you add the property. Adding an index to an already-deployed property\nis allowed, but validate it in Preview first.\n\n### Remove a property\n\n```bash\nms project state remove --collection task --property obsoleteField\n```\n\nUse `--force` only when non-interactive automation is necessary and the user already approved the\nremoval. Stored values are not deleted. Collection removal is intentionally rejected; do not work\naround it by editing the schema file.\n\n### Change schema settings\n\nSet exactly one setting per command:\n\n```bash\nms project state set-setting --locale en-US\nms project state set-setting --validation true\nms project state set-setting --validation false\n```\n\n`--validation false` keeps declared indexes active but makes writes index-only\u002Funvalidated.\n\n### Per-user collections\n\nMake a collection per-user when a record belongs to one person (drafts, preferences, personal\nnotes); skip it for catalogs, reference data, and anything collaborative. **Decide before it holds\nrecords:** ownership is immutable and can't be added to a collection that has data. The CLI has no\nownership flag, so this is the one schema edit allowed by hand, and only after the user agrees: add\n`\"x-ms-ownership\": \"perUser\"` to the collection's root object (not a property), change nothing\nelse, and regenerate.\n\nGenerated services then take a `scope` option: `private` writes\u002Freads only the caller's records,\n`shared` writes\u002Freads records visible to all users, and omitting it writes private and reads both.\nPass it explicitly on writes. The owner always comes from the caller's token; reads include a\nplatform-managed `@ms.scope` that you must not send back.\n\n## Generate the typed client\n\nRun this after every successful schema change:\n\n```bash\nms project state generate-code\n```\n\nFor automation or precise diagnostics:\n\n```bash\nms project state generate-code --json\n```\n\nOutput is written to `generated-typescript\u002F` beside the configured schema file. For\n`state.schemaPath: \"state\u002Fschema.json\"`, output is `state\u002Fgenerated-typescript\u002F`.\n\nTreat that folder as generator-owned:\n\n- first generation accepts a missing or empty directory;\n- replacement requires the ownership manifest and no untracked handwritten files;\n- move handwritten wrappers\u002Fhooks outside the generated directory;\n- never edit generated models, services, validators, query helpers, or manifests by hand.\n\n## App code\n\nImport from the generated barrel. Each collection gets a service class with static methods,\nread\u002Fwrite types, and a validator: `task` gives `TaskService`, `TaskRead`, `TaskWrite`, and\n`validateTask(item)`, which returns `ValidationError[]` for form errors (services validate on write).\n\n```ts\nimport { TaskService, type TaskRead, type TaskWrite } from '..\u002Fstate\u002Fgenerated-typescript';\n\nexport async function createTask(input: TaskWrite): Promise\u003CTaskRead> {\n  \u002F\u002F With validation on, invalid input fails with error.kind === 'validation'.\n  const result = await TaskService.create(input);\n  if (!result.success) {\n    throw new Error(`Could not create the task: ${result.error.message}`);\n  }\n  return result.data;\n}\n\nexport async function listUpcomingTasks(): Promise\u003CTaskRead[]> {\n  const q = TaskService.query;\n  const result = await TaskService.getAll({\n    filter: q.ge('dueDate', new Date().toISOString()),\n    orderBy: q.orderBy('dueDate', 'asc'),\n    maxItems: 50,\n  });\n  if (!result.success) {\n    throw new Error(`Could not load tasks: ${result.error.message}`);\n  }\n  return result.data;\n}\n```\n\nDirect requests to `\u002F.ms\u002Fstate\u002F{collection}\u002Fitems[\u002F{itemId}]` are acceptable only with a deliberate\nreason to bypass the generated services. They follow the same contract: send `@odata.etag`\nverbatim as `If-Match`, follow `@odata.nextLink` to page (`$skip` is rejected), sort with\n`$orderby=\u003Cfield> asc|desc`, and quote string and date literals in `$filter` (URL-encode both).\n\n## Generated-service behavior\n\n- **Results, not exceptions:** service calls return `{ success: true, data }` or\n  `{ success: false, error }` (`error.kind`, `message`, `status`, `validationErrors`). Check\n  `success` before using `data`.\n- **Create\u002Fupdate validation:** generated validators enforce the declared schema when validation is\n  enabled. `update` is a full-document PUT\u002Fupsert, not a partial patch.\n- **Edit with concurrency:** generated edit helpers read the item, shallow-merge callback changes,\n  validate, and send the exact quoted ETag in `If-Match`. Only `412` is retried.\n- **Delete is idempotent:** deleting a missing item succeeds, so retries are safe.\n- **Server-owned fields:** `itemId`, `createdTime`, `modifiedTime`, and `@odata.etag` are read-only.\n  Do not send them in write models.\n- **Queries:** `getAll` follows every page (cap it with `maxItems`); `getPage` returns one page and\n  a `nextLink` (`top` sets the page size). Build `filter` and `orderBy` with the typed `query`\n  builder (`eq`, `ne`, `gt`, `lt`, `le`, `ge`, `and`, `or`, `orderBy(field, 'asc' | 'desc')`); both\n  accept only indexed fields. `rawFilter(expr)` is the explicit escape hatch for raw OData filters.\n- **Per-user data:** for `x-ms-ownership: \"perUser\"`, generated services expose scope-aware reads\n  and writes. Do not send scope to non-per-user collections; the service rejects it with `400`.\n\n## File attachments\n\nGenerated services don't upload files. Declare a reference property\n(`ms project state add --collection note --property photo --type binary --kind image`), regenerate,\nthen upload the bytes and save the returned URL through the generated service:\n\n```ts\nconst uploaded = await fetch('\u002F.ms\u002Fstate\u002Fattachments', {\n  method: 'POST',\n  headers: { 'Content-Type': file.type || 'application\u002Foctet-stream' }, \u002F\u002F required\n  body: file,\n}).then((response) => response.json()); \u002F\u002F { id, url, contentType, size }\n\nconst saved = await NoteService.update(note.itemId, { ...noteFields, photo: uploaded.url });\n```\n\nDisplay it with `\u003Cimg src={note.photo} \u002F>`.\n\n- Save within **15 minutes**, or the unreferenced upload is garbage-collected. Store `url` verbatim.\n- Attachments have no DELETE or PUT: save the property as `null` (or delete the item) to remove one,\n  and upload a new file to replace it. A file belongs to one item (`409` otherwise).\n- No filename is stored; add a separate property if needed. Limits: 10 MiB per file, 10,000 files\n  and 1 GiB per app. Use a real image `Content-Type` for `\u003Cimg>`; SVG is always downloaded.\n\n## Preview has its own state\n\n`ms app play --mode preview --commit \u003Csha>` (full SHA, after `ms app build --commit \u003Csha>`) runs the\napp against a **separate Preview store**: same collections, different records. Test writes,\nvalidation, and schema\u002Findex changes there before `ms app deploy`. Preview only engages when the\npreviewed commit differs from the deployed one. After deploying, click **Refresh** on the app's\n*New version available* banner before testing schema changes; a plain reload keeps the old schema.\n\nTo purge Preview records (with the user's explicit approval, see rules), run\n`ms project state clear --force --json --non-interactive` in the app folder. `isComplete: false` is\nnormal because deletion finishes in the background; don't retry, and wait a minute or two before\nrelaunching Preview or deploying.\n\n## Rules \u002F gotchas\n\n- **Feature gate first.** Never use this skill's state workflow before\n  `ms feature status --name state --json` reports `feature.enabled: true`.\n- **Schema changes are CLI-only.** Never patch the schema JSON to add properties, constraints,\n  indexes, locale, or validation settings. The only exception is per-user ownership, as described\n  above.\n- **Unsupported schema shapes need a decision.** If the requested design needs nested objects,\n  arrays, enums, `$ref`, composition keywords, `pattern`, or defaults and the CLI cannot represent\n  it, stop and ask. Do not silently switch to manual schema editing.\n- **Indexes are add-only.** The CLI rejects removing an index or changing its options, deployed or\n  not. Decide index options when adding a property, and Preview any index added to a deployed\n  property before live deploy.\n- **Never drop a declared collection\u002Fitem type** by hand. Collection removal is not a supported CLI\n  write.\n- **Do not run `ms project state clear`** unless the user explicitly asks to discard all Preview\n  state for the app\u002Fenvironment. It is not part of schema editing or code generation.\n- **CLI attribution is automatic.** Do not tell users to export `MS_CLI_ORIGIN`; the host hook adds\n  it for `ms` invocations unless the user already set a value.\n\n## Verification\n\n```bash\nms feature status --name state --json\nms project state list-schema\nms project state list-settings\nms project state generate-code --json\n```\n\nThen:\n\n- confirm `ms.config.json` has `enabled: true` on its state (or `data`\u002F`db`) section;\n- confirm the app has `@microsoft\u002Fmanaged-apps-vite-plugin` 0.4.2 or later;\n- confirm `vite.config.ts` calls `managedApps({ devMode: 'localGateway' })` or preserves existing\n  options while adding `devMode: 'localGateway'`;\n- run the narrowest relevant build\u002Ftypecheck\u002Flint for the app or package;\n- prefer generated services for schema-backed state behavior covered by codegen;\n- run local gateway dev with `ms app dev` and verify generated-service behavior locally;\n- preview the committed build with `ms app play --mode preview --commit \u003Csha>` before deploying.\n","**? Shared Instructions: [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md)** — Cross-cutting concerns.\n\n# Managed Apps State with CLI schema + generated client\n\nEvery Microsoft Managed App can use built-in app state when the `state` feature is enabled for the\ncurrent CLI\u002Fenvironment: a NoSQL store the app calls directly (no middle-tier function, connector,\nor SDK; the host attaches auth). Records are grouped into collections by an item type name; the\nserver assigns each record an `itemId`.\n\nFor schema-backed state, **do not edit schema JSON by hand.** Use `ms project state ...` to change\nthe schema, run `ms project state generate-code`, then call the generated TypeScript services from\napp code.\n\n## Mandatory feature gate\n\nBefore using any guidance in this skill, it is recommended that the user is signed in to the CLI. Run\n`ms auth status`, and if it reports no signed-in account, ask the user to run `ms auth login`.\n`ms feature status` never prompts for sign-in, and features that are on by default for the user's\norganization only apply once they are signed in, so a signed-out check can report `state` as\ndisabled even when it is available to them.\n\nThen run:\n\n```bash\nms feature status --name state --json\n```\n\nContinue only when the output has `\"success\": true` and `feature.enabled` is `true`. Read the JSON\nrather than the human-readable output, which lists several settings that can each say \"enabled\". If\nthe command fails (non-zero exit or `\"success\": false`), the feature is not found, or\n`feature.enabled` is `false`, stop and do **not** run any `ms project state ...` command.\n\nWhen state is not enabled, recommend an alternative data-source path based on the user's need:\n\n- Durable relational\u002Fbusiness data: use `\u002Fadd-dataverse`.\n- SharePoint lists or document-backed collaboration data: use `\u002Fadd-sharepoint`.\n- Workbook-backed tabular data: use `\u002Fadd-excel`.\n- Mail, calendar, user profile, Teams, Azure DevOps, OneDrive, Copilot Studio, or Work IQ scenarios:\n  use the matching `\u002Fadd-*` skill.\n- Anything else: use `\u002Fadd-data-source` to discover and bind the appropriate connector.\n\nDo not suggest manual schema edits or custom proxy workarounds as a substitute for the disabled\nfeature.\n\n## ⚠️ Local testing requires local gateway mode\n\nGenerated state services require the Managed Apps local gateway path during local development.\nBefore testing data behavior locally, make sure the app has `@microsoft\u002Fmanaged-apps-vite-plugin`\n0.4.2 or later (the version that added `devMode: 'localGateway'`; older versions won't start the\nlocal gateway), then opt the app into local gateway mode.\n\nCheck the installed version first, for example with `npm ls @microsoft\u002Fmanaged-apps-vite-plugin`\n(or read `version` in `node_modules\u002F@microsoft\u002Fmanaged-apps-vite-plugin\u002Fpackage.json`). If it is\n0.4.2 or later, skip the install. If it is missing or older, install the latest with the app's\npackage manager:\n\n```bash\nnpm install -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: bun add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: pnpm add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n# or: yarn add -D @microsoft\u002Fmanaged-apps-vite-plugin@latest\n```\n\nThen update the app's `vite.config.ts` so the `managedApps()` plugin call enables the local gateway,\npreserving any existing options:\n\n```ts\nmanagedApps({\n  ...existingOptions,\n  devMode: 'localGateway',\n})\n```\n\nNow run local dev normally:\n\n```bash\nms app dev\n```\n\nDo not change the app architecture just to work around local data failures (no middle-tier\nfunctions, proxies, or CORS\u002Fauth workarounds). Fix the Vite plugin\u002Flocal gateway setup instead.\n\n## Contract\n\n| Surface | Use | Don't use |\n| --- | --- | --- |\n| Feature gate | `ms feature status --name state --json` (`feature.enabled`), with the user signed in, before any state work | assuming the feature is available |\n| Schema edits | `ms project state add`, `alter`, `remove`, `set-setting` | manual edits to `state\u002Fschema.json`, `ms.schema.json`, or another configured schema file |\n| Code generation | `ms project state generate-code` | handwritten model\u002Fservice\u002Fvalidator files in the generated output folder |\n| App data access | generated services, models, validators, and typed query helpers | treating direct state requests as the default when codegen covers the scenario |\n| File attachments | direct upload to `\u002F.ms\u002Fstate\u002Fattachments`, then save the returned URL through a generated service | storing file bytes inside items |\n| Testing data behavior | Vite plugin 0.4.2+ + `managedApps({ devMode: 'localGateway' })` + `ms app dev`; Preview for pre-deploy validation | local dev without local gateway mode |\n\nThe generated services own request shapes, ETags, typed filters, paging, validation hooks, per-user\nscope behavior, and service route details. App code should compose those services with UI\u002Fbusiness\nlogic instead of duplicating transport behavior.\n\n## Workflow\n\n1. Make sure the user is signed in (`ms auth status`; ask them to run `ms auth login` if not), then\n   run `ms feature status --name state --json`. Stop and recommend a connector alternative unless\n   `feature.enabled` is `true`.\n2. Find the app root (`ms.config.json`) and the configured schema path.\n3. Inspect existing state schema\u002Fsettings with `ms project state list-schema` and\n   `ms project state list-settings`.\n4. For each new collection, decide up front whether records are per-user (see below).\n5. Make schema changes only with `ms project state ...` commands.\n6. Run `ms project state generate-code` after every successful schema change.\n7. Import and use the generated TypeScript services from app code.\n8. Configure local gateway mode before local data testing.\n9. Build\u002Ftypecheck and verify that generated services are used for behavior covered by codegen.\n\n## Schema setup\n\nFind the app root (`ms.config.json`) and the configured schema path. Prefer `state.schemaPath`; older\napps may use `data.schemaPath` or legacy `db.schemaPath`.\n\n```json\n{\n  \"state\": {\n    \"schemaPath\": \"state\u002Fschema.json\",\n    \"enabled\": true\n  }\n}\n```\n\nIf no schema path exists yet, start by adding the first collection with the CLI. It writes\n`state.schemaPath: \"state\u002Fschema.json\"`, creates the schema file, and sets `enabled: true` unless the\nconfig already sets `enabled`; don't ask the user to hand-configure schema wiring first. The app\nserves no state while `enabled` is `false`, so confirm with the user before changing an explicit\n`false`. New schemas take the machine's locale (or `en-US`); match the app's users with\n`ms project state set-setting --locale \u003Ctag>`.\n\nInspect the current schema:\n\n```bash\nms project state list-schema\nms project state list-settings\n```\n\n## CLI schema commands\n\n### Add a collection\n\n```bash\nms project state add --collection task\n```\n\n### Add properties\n\n```bash\nms project state add --collection task --property name --type string --required true --max-length 200 --index true --index-ignore-case true\nms project state add --collection task --property done --type boolean\nms project state add --collection task --property dueDate --type datetime --index true\nms project state add --collection task --property attachment --type binary --kind binary\n```\n\n- **Types:** `string`, `number`, `integer`, `boolean`, `datetime`, `guid`, `binary`.\n- **Boolean flags take values:** `--required true`, `--index false`, etc. They are not bare\n  switches.\n- **Indexes:** at most four custom indexed properties per collection, top-level scalars only. Only\n  indexed properties (plus `itemId`, `name`, `createdTime`, `modifiedTime`) can be filtered or sorted.\n- **Name property:** prefer a human-readable `name` property for each item (put a single-string\n  item's text there). It is writable, indexed, sortable\u002Ffilterable, and generated services treat it\n  as the display\u002Ftitle field.\n\n### Alter a property\n\n```bash\nms project state alter --collection task --property name --max-length 200\nms project state alter --collection task --property done --required false\nms project state alter --collection task --property name --max-length \"\"\n```\n\nOnly pass the flags you intend to change. Empty string clears a type-specific constraint where the\nCLI supports clearing.\n\nIndexes are add-only. Removing an index or changing its options (including the platform index on\n`name`) is rejected even before the first deploy, so choose `--index-ignore-case` and\n`--index-ignore-accents` when you add the property. Adding an index to an already-deployed property\nis allowed, but validate it in Preview first.\n\n### Remove a property\n\n```bash\nms project state remove --collection task --property obsoleteField\n```\n\nUse `--force` only when non-interactive automation is necessary and the user already approved the\nremoval. Stored values are not deleted. Collection removal is intentionally rejected; do not work\naround it by editing the schema file.\n\n### Change schema settings\n\nSet exactly one setting per command:\n\n```bash\nms project state set-setting --locale en-US\nms project state set-setting --validation true\nms project state set-setting --validation false\n```\n\n`--validation false` keeps declared indexes active but makes writes index-only\u002Funvalidated.\n\n### Per-user collections\n\nMake a collection per-user when a record belongs to one person (drafts, preferences, personal\nnotes); skip it for catalogs, reference data, and anything collaborative. **Decide before it holds\nrecords:** ownership is immutable and can't be added to a collection that has data. The CLI has no\nownership flag, so this is the one schema edit allowed by hand, and only after the user agrees: add\n`\"x-ms-ownership\": \"perUser\"` to the collection's root object (not a property), change nothing\nelse, and regenerate.\n\nGenerated services then take a `scope` option: `private` writes\u002Freads only the caller's records,\n`shared` writes\u002Freads records visible to all users, and omitting it writes private and reads both.\nPass it explicitly on writes. The owner always comes from the caller's token; reads include a\nplatform-managed `@ms.scope` that you must not send back.\n\n## Generate the typed client\n\nRun this after every successful schema change:\n\n```bash\nms project state generate-code\n```\n\nFor automation or precise diagnostics:\n\n```bash\nms project state generate-code --json\n```\n\nOutput is written to `generated-typescript\u002F` beside the configured schema file. For\n`state.schemaPath: \"state\u002Fschema.json\"`, output is `state\u002Fgenerated-typescript\u002F`.\n\nTreat that folder as generator-owned:\n\n- first generation accepts a missing or empty directory;\n- replacement requires the ownership manifest and no untracked handwritten files;\n- move handwritten wrappers\u002Fhooks outside the generated directory;\n- never edit generated models, services, validators, query helpers, or manifests by hand.\n\n## App code\n\nImport from the generated barrel. Each collection gets a service class with static methods,\nread\u002Fwrite types, and a validator: `task` gives `TaskService`, `TaskRead`, `TaskWrite`, and\n`validateTask(item)`, which returns `ValidationError[]` for form errors (services validate on write).\n\n```ts\nimport { TaskService, type TaskRead, type TaskWrite } from '..\u002Fstate\u002Fgenerated-typescript';\n\nexport async function createTask(input: TaskWrite): Promise\u003CTaskRead> {\n  \u002F\u002F With validation on, invalid input fails with error.kind === 'validation'.\n  const result = await TaskService.create(input);\n  if (!result.success) {\n    throw new Error(`Could not create the task: ${result.error.message}`);\n  }\n  return result.data;\n}\n\nexport async function listUpcomingTasks(): Promise\u003CTaskRead[]> {\n  const q = TaskService.query;\n  const result = await TaskService.getAll({\n    filter: q.ge('dueDate', new Date().toISOString()),\n    orderBy: q.orderBy('dueDate', 'asc'),\n    maxItems: 50,\n  });\n  if (!result.success) {\n    throw new Error(`Could not load tasks: ${result.error.message}`);\n  }\n  return result.data;\n}\n```\n\nDirect requests to `\u002F.ms\u002Fstate\u002F{collection}\u002Fitems[\u002F{itemId}]` are acceptable only with a deliberate\nreason to bypass the generated services. They follow the same contract: send `@odata.etag`\nverbatim as `If-Match`, follow `@odata.nextLink` to page (`$skip` is rejected), sort with\n`$orderby=\u003Cfield> asc|desc`, and quote string and date literals in `$filter` (URL-encode both).\n\n## Generated-service behavior\n\n- **Results, not exceptions:** service calls return `{ success: true, data }` or\n  `{ success: false, error }` (`error.kind`, `message`, `status`, `validationErrors`). Check\n  `success` before using `data`.\n- **Create\u002Fupdate validation:** generated validators enforce the declared schema when validation is\n  enabled. `update` is a full-document PUT\u002Fupsert, not a partial patch.\n- **Edit with concurrency:** generated edit helpers read the item, shallow-merge callback changes,\n  validate, and send the exact quoted ETag in `If-Match`. Only `412` is retried.\n- **Delete is idempotent:** deleting a missing item succeeds, so retries are safe.\n- **Server-owned fields:** `itemId`, `createdTime`, `modifiedTime`, and `@odata.etag` are read-only.\n  Do not send them in write models.\n- **Queries:** `getAll` follows every page (cap it with `maxItems`); `getPage` returns one page and\n  a `nextLink` (`top` sets the page size). Build `filter` and `orderBy` with the typed `query`\n  builder (`eq`, `ne`, `gt`, `lt`, `le`, `ge`, `and`, `or`, `orderBy(field, 'asc' | 'desc')`); both\n  accept only indexed fields. `rawFilter(expr)` is the explicit escape hatch for raw OData filters.\n- **Per-user data:** for `x-ms-ownership: \"perUser\"`, generated services expose scope-aware reads\n  and writes. Do not send scope to non-per-user collections; the service rejects it with `400`.\n\n## File attachments\n\nGenerated services don't upload files. Declare a reference property\n(`ms project state add --collection note --property photo --type binary --kind image`), regenerate,\nthen upload the bytes and save the returned URL through the generated service:\n\n```ts\nconst uploaded = await fetch('\u002F.ms\u002Fstate\u002Fattachments', {\n  method: 'POST',\n  headers: { 'Content-Type': file.type || 'application\u002Foctet-stream' }, \u002F\u002F required\n  body: file,\n}).then((response) => response.json()); \u002F\u002F { id, url, contentType, size }\n\nconst saved = await NoteService.update(note.itemId, { ...noteFields, photo: uploaded.url });\n```\n\nDisplay it with `\u003Cimg src={note.photo} \u002F>`.\n\n- Save within **15 minutes**, or the unreferenced upload is garbage-collected. Store `url` verbatim.\n- Attachments have no DELETE or PUT: save the property as `null` (or delete the item) to remove one,\n  and upload a new file to replace it. A file belongs to one item (`409` otherwise).\n- No filename is stored; add a separate property if needed. Limits: 10 MiB per file, 10,000 files\n  and 1 GiB per app. Use a real image `Content-Type` for `\u003Cimg>`; SVG is always downloaded.\n\n## Preview has its own state\n\n`ms app play --mode preview --commit \u003Csha>` (full SHA, after `ms app build --commit \u003Csha>`) runs the\napp against a **separate Preview store**: same collections, different records. Test writes,\nvalidation, and schema\u002Findex changes there before `ms app deploy`. Preview only engages when the\npreviewed commit differs from the deployed one. After deploying, click **Refresh** on the app's\n*New version available* banner before testing schema changes; a plain reload keeps the old schema.\n\nTo purge Preview records (with the user's explicit approval, see rules), run\n`ms project state clear --force --json --non-interactive` in the app folder. `isComplete: false` is\nnormal because deletion finishes in the background; don't retry, and wait a minute or two before\nrelaunching Preview or deploying.\n\n## Rules \u002F gotchas\n\n- **Feature gate first.** Never use this skill's state workflow before\n  `ms feature status --name state --json` reports `feature.enabled: true`.\n- **Schema changes are CLI-only.** Never patch the schema JSON to add properties, constraints,\n  indexes, locale, or validation settings. The only exception is per-user ownership, as described\n  above.\n- **Unsupported schema shapes need a decision.** If the requested design needs nested objects,\n  arrays, enums, `$ref`, composition keywords, `pattern`, or defaults and the CLI cannot represent\n  it, stop and ask. Do not silently switch to manual schema editing.\n- **Indexes are add-only.** The CLI rejects removing an index or changing its options, deployed or\n  not. Decide index options when adding a property, and Preview any index added to a deployed\n  property before live deploy.\n- **Never drop a declared collection\u002Fitem type** by hand. Collection removal is not a supported CLI\n  write.\n- **Do not run `ms project state clear`** unless the user explicitly asks to discard all Preview\n  state for the app\u002Fenvironment. It is not part of schema editing or code generation.\n- **CLI attribution is automatic.** Do not tell users to export `MS_CLI_ORIGIN`; the host hook adds\n  it for `ms` invocations unless the user already set a value.\n\n## Verification\n\n```bash\nms feature status --name state --json\nms project state list-schema\nms project state list-settings\nms project state generate-code --json\n```\n\nThen:\n\n- confirm `ms.config.json` has `enabled: true` on its state (or `data`\u002F`db`) section;\n- confirm the app has `@microsoft\u002Fmanaged-apps-vite-plugin` 0.4.2 or later;\n- confirm `vite.config.ts` calls `managedApps({ devMode: 'localGateway' })` or preserves existing\n  options while adding `devMode: 'localGateway'`;\n- run the narrowest relevant build\u002Ftypecheck\u002Flint for the app or package;\n- prefer generated services for schema-backed state behavior covered by codegen;\n- run local gateway dev with `ms app dev` and verify generated-service behavior locally;\n- preview the committed build with `ms app play --mode preview --commit \u003Csha>` before deploying.\n",{"name":5,"description":7,"allowed-tools":55},"Read Edit Write Grep Glob Bash AskUserQuestion","main","5e4bd47de38c9ae0327efb7c0003d250afff31b6","plugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fstate",12,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FCopilot-Managed-Runtime","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-06 04:02:23",{"source":9,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add microsoft\u002Fmanaged-apps --skill state",{"tool":72,"command":73},"bunx","bunx skills add microsoft\u002Fmanaged-apps --skill state",{"tool":75,"command":76},"pnpm","pnpm dlx skills add microsoft\u002Fmanaged-apps --skill state","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fstate\u002FSKILL.md",true,[],[81,104,125,148,170,187],{"skillNo":82,"name":83,"nameZh":84,"description":85,"descriptionZh":86,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":87,"categories":88,"keywords":95,"publishedAt":50},"01M69BVYVZ0YYRMDY1WPVJ98VV","share","Microsoft 应用共享与访问控制","Shares (or unshares) a Microsoft App with users via `ms app share` \u002F `ms app unshare`. Use when updating app access control.","通过 `ms app share` \u002F `ms app unshare` 与用户共享（或取消共享）Microsoft 应用。在需要更新应用访问控制时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fshare\u002FSKILL.md",[89,92],{"categoryNo":90,"categoryName":91,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BTFDX7M21YT75733H52N36","身份与访问管理",{"categoryNo":93,"categoryName":94,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8C6RQ852C9AEJFCBGG1YA7S","IT 管理员",[83,96,31,97,98,45,99,100,44,101,39,102,103,10],"with","users","via","control","Access Control","use","grep","access",{"skillNo":105,"name":106,"nameZh":107,"description":108,"descriptionZh":109,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":110,"categories":111,"keywords":114,"publishedAt":50},"01M69BVX6TTS1A17ZA2BDP13KP","share-link","Microsoft App 共享链接管理","Manages tenant-wide share links for a Microsoft App via `ms app share link create`, `ms app share link list`, and `ms app share link revoke`. Use when you want to distribute app access via a URL instead of named principals.","通过 `ms app share link create`、`ms app share link list` 和 `ms app share link revoke` 管理 Microsoft App 的租户级共享链接。适用于希望通过 URL（而非指定主体）来分发应用访问权限的场景。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fshare-link\u002FSKILL.md",[112,113],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":90,"categoryName":91,"taxonomyType":28,"taxonomyTypeDesc":29},[115,83,116,39,102,103,31,117,10,118,119,120,121,122,123,98,45,124,44,101],"link","share link","create","list","for","wide","links","you","URL","distribute",{"skillNo":126,"name":127,"nameZh":128,"description":129,"descriptionZh":130,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":131,"categories":132,"keywords":137,"publishedAt":50},"01M69BVVFK3WFDMJW2R5CYCRD4","play","Microsoft App 浏览器预览","Opens a Microsoft App in the browser via `ms app play`. Use when opening the live deployed version or a cloud-hosted preview (main branch or specific commit SHA) without starting a local dev server.","通过 `ms app play` 在浏览器中打开 Microsoft App。适用于打开已部署的线上版本或云端托管的预览版本（主分支或特定提交 SHA），而无需启动本地开发服务器。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fplay\u002FSKILL.md",[133,134],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":135,"categoryName":136,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSTR9G4A4GZ0VB2DFN9490","开发环境与工具链管理",[127,138,39,101,139,140,44,141,56,98,45,142,31,143,144,145,146,10,147,102],"preview","version","local dev server","branch","local","server","browser","dev","commit","local dev",{"skillNo":149,"name":150,"nameZh":151,"description":152,"descriptionZh":153,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":154,"categories":155,"keywords":160,"publishedAt":50},"01M69BVSSESTPDA4Z5WP8WEN01","list-connectors","可用连接器列表查询","Lists connectors available in the active environment — including whether each is allowed or blocked by your organization's policy — plus the connection-bound data sources already wired into a Microsoft App. Use when discovering connectors and their operations before adding data sources.","列出当前活动环境中可用的连接器——包括每个连接器是被组织策略允许还是阻止——以及已接入 Microsoft App 的连接绑定数据源。适用于在添加数据源之前发现可用的连接器及其操作。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Flist-connectors\u002FSKILL.md",[156,157],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":158,"categoryName":159,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BWDNFEHJCBZX47YY896K05","应用连接器集成",[161,162,118,163,164,165,45,166,101,167,168,39,31,34,10,169],"connectors","list connectors","active","connection","sources","organization","operations","environment","policy",{"skillNo":171,"name":172,"nameZh":173,"description":174,"descriptionZh":175,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":176,"categories":177,"keywords":182,"publishedAt":50},"01M69BVRDCYENNS8XXM1E5RBYQ","list-apps","Microsoft 应用列表查询","Discovers managed apps in the active environment via `ms app list --json` and optional `ms app show --json`. Use when listing or locating apps.","通过 `ms app list --json` 以及可选的 `ms app show --json` 发现活动环境中的受管理应用。在列出或定位应用时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Flist-apps\u002FSKILL.md",[178,179],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":180,"categoryName":181,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C6RHQSB2BGY8CHB7AN49N9","Microsoft 应用生命周期管理",[183,184,118,163,185,44,101,168,39,102,186,31,45,98],"list apps","apps","show","json",{"skillNo":188,"name":145,"nameZh":189,"description":190,"descriptionZh":191,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":192,"categories":193,"keywords":196,"publishedAt":50},"01M69BVPVP9SPEY44ZG7PBDPQF","Microsoft 应用本地运行","Runs a Microsoft App locally with hot reload via `ms app dev`. Use when starting or restarting local development and surfacing the App Player URL.","通过 `ms app dev` 在本地运行 Microsoft 应用并支持热重载。在开始或重启本地开发、展示 App Player URL 时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fmanaged-apps\u002Fblob\u002Fmain\u002Fplugins\u002Fmicrosoft-managed-apps\u002Fskills\u002Fdev\u002FSKILL.md",[194,195],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":180,"categoryName":181,"taxonomyType":28,"taxonomyTypeDesc":29},[145,10,96,197,123,198,98,45,142,44,101,39,102,31,199],"player","local development","development"]