{"data":{"slug":"github-lobehub-lobehub-agents-skills-agent-work-65e906708a9f","title":"Register Agent Work for Tracking and Versioning","summary":"Register Work records for agent outputs like GitHub PRs, Linear issues, and files. Tracks versions and scopes for access control.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-work-65e906708a9f","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-agent-work-65e906708a9f","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-work-65e906708a9f.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-work-65e906708a9f\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"To use this skill, ensure the client has opted in to the `file` Work type by setting `includeFileWorks: true` in the request. Additionally, when registering Works from a visitor run, the `WorkAccessScope` must be resolved via `resolveRunWorkAccessScope` to avoid unscoped registrations.","instructions":"---\nname: agent-work\ndescription: 'Use for the Agent Work output registry: registration, deduplication, cards, skill providers, CLI scanners and Work types.'\nuser-invocable: false\n---\n\n# Agent Works\n\nA **Work** is a durable record of something an agent produced or touched \u2014 a GitHub PR\/issue, a Linear issue, an entity file (pptx\/xlsx\/docx\/pdf), a document, a task. Works render as cards under the assistant message that produced them and accumulate **versions** across operations, so the same PR edited twice shows one card with history.\n\nTwo tables (`packages\/database\/src\/schemas\/work.ts`):\n\n- `works` \u2014 one row per resource. Identity\/dedup key: `(resourceType, resourceId)` within the user\/workspace scope and the share scope (see below). `currentVersionId` soft-references the latest version.\n- `work_versions` \u2014 one row per registration event. Dedup: unique `(workId, toolCallId)`, so a retried registration with the same real tool call id is a no-op. Versions carry provenance (source message, producing tool) and operation-level `cumulativeCost` \/ `cumulativeUsage`.\n\n## Type registry\n\n`packages\/database\/src\/models\/work\/registry.ts` is the single registry of Work types (`document` \/ `external` \/ `file` \/ `task`): `WORK_TYPE_ADAPTERS` is `satisfies Record<WorkType, WorkTypeAdapter>`, so a type added to `@lobechat\/types` without an adapter is a compile error.\n\n**Read-path compatibility gate**: `OPT_IN_WORK_TYPES` (currently `{'file'}`) hides newer types from clients that did not opt in (`includeFileWorks`). Released Electron clients lag by weeks and crash on unknown type descriptors (`descriptor.getIcon` on `undefined`), so a request without the opt-in receives exactly the pre-`file` set. Any NEW Work type must ship behind the same kind of opt-in.\n\nThe gate has two kinds of emission points, and both must honor the client's declaration:\n\n- **Pulled reads** (`message.getMessages`, `work.*` lists, `shareChat.getMessages`): the client service passes `includeFileWorks: true` on the request.\n- **Pushed payloads** (the `uiMessages` snapshots and `message_patch` revisions built by `AgentRuntimeService.queryUiMessages`): no request carries the opt-in, so the starting client declares the `file_works` stream feature and the run stores it as `state.host.acceptsFileWorks`; approval continuations and group members inherit it. A pushed path that skips this check drops the card until the user reloads the page.\n\n## Access scope (Agent Share visitors)\n\nA share visitor's run executes as the creator, so owner scope alone cannot separate its Works. Every Work read and write takes a `WorkAccessScope` (`packages\/types\/src\/work.ts`): `ordinary` sees only rows without share provenance; `agentShare` sees only rows stamped in `works.metadata.agentShare` with exactly that share\/topic\/visitor.\n\n- `workOwnership` applies the scope on every path, so a new query built on it inherits the fence. Do not query `works` without it.\n- Any registration path reachable from a visitor run (skill results, completion scans, anchor stamping) must build its `WorkModel` with the run's scope via `resolveRunWorkAccessScope`. A visitor run without a topic yields `null`: skip registration (fail closed) rather than registering unscoped into the creator's lists.\n- The resource unique indexes include the visitor topic id, so the creator and each visitor topic keep separate rows for the same external resource.\n- Visitor read payloads drop the creator's `userId` \/ `workspaceId` and gate spend on `showModelInfo` (`toVisitorMessage`).\n\n## Orphaned Works (backing resource deleted)\n\n`works.resourceId` has no FK, and deleting a document, task, or file never cascades into its Work (LOBE-13917). Deleting the Work would also drop its version history and its project and goal references. Each read surface handles orphans itself:\n\n- **Resource-page galleries hide orphans.** These are `listByWorkspace` surfaces: `\/resource`, `\/resource\/works`, and the project dashboard. They filter orphans out with `resourceLiveFilter` (`packages\/database\/src\/models\/work\/internal.ts`). A task or document must still exist and not be trashed. A file Work's current-version `fileId` must point to a `files` row that exists and is not trashed. Restoring the resource brings the card back. Any new gallery-style Work list must apply the same filter.\n- **Conversation surfaces keep the card.** These are `listByConversation` and the cards under messages; the conversation did produce the Work. `resourceDeleted` drives a click-time prompt (`useResourceDeletedPrompt`) that lets the user remove it.\n\n## Registration write paths\n\nFour write paths, two timing classes:\n\n| Path                                                                    | When                                | Where                                                                                                                                                               |\n| ----------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Skill structured tools + sandbox `runCommand` (github \/ linear)         | at tool execution                   | `WorkModel.handleSkillToolResult`, called from server `toolExecution` and the client executor (`registerClientWorkFromIntent.ts` on the legacy non-gateway runtime) |\n| Shell Work scan (hetero codex\/claude-code + device `lobe-local-system`) | at operation completion             | `apps\/server\/src\/services\/workRegistration\/shellWorkRegistration.ts` via `registerWorksForOperation`                                                                |\n| File Work scan (sandbox entity files)                                   | at operation completion             | `apps\/server\/src\/services\/workRegistration\/registerWorksForOperation.ts`                                                                                            |\n| Task \/ document works                                                   | at creation by their owning feature | `WorkModel.registerTask` \/ `registerDocument`                                                                                                                       |\n\n### Execution-time: skill providers\n\n`SKILL_TOOL_RESULT_NORMALIZERS` in `packages\/database\/src\/models\/work\/index.ts` maps `WorkSkillProvider` (`github`, `linear`; vocabulary in `packages\/types\/src\/work.ts`) to a normalizer. Both `satisfies` a `Record<WorkSkillProvider, \u2026>`, so provider list and normalizer map cannot drift.\n\nA normalizer turns one tool result into `ExternalToolWorkOperation | null` \u2014 null means \"not Work-worthy\", which is the common case and never an error.\n\n### Completion-time: the shell Work scan framework\n\nHeterogeneous CLI agents (codex, claude-code) and the device `lobe-local-system` tool run CLIs like `gh` through their own shell surfaces, which never pass the skill-tool hook. `registerWorksForOperation` recovers their Works at completion from the persisted command text + stdout. Layering:\n\n```\nregisterWorksForOperation (registerWorksForOperation.ts)\n  \u251c\u2500 collectOperationRecords         one pass over the operation tree, shared by both scans\n  \u251c\u2500 registerShellWorks              (shellWorkRegistration.ts \u2014 the ENGINE, command-agnostic)\n  \u2502    \u251c\u2500 SHELL_COMMAND_SOURCES      identifier\u2192apiName scoping of shell surfaces\n  \u2502    \u251c\u2500 success gate               plugin error \/ state.success===false \/ state.error \u2192 skip\n  \u2502    \u251c\u2500 extract {command, exitCode, output}   from arguments \/ state \/ message content\n  \u2502    \u2514\u2500 shellWorkScanners\/         one file per CLI family\n  \u2502         \u251c\u2500 types.ts              ShellWorkScanner = { matches, name, register }\n  \u2502         \u251c\u2500 github.ts             matches: includes('gh ') \u2192 workModel.registerShellGithubResult\n  \u2502         \u2514\u2500 index.ts              SHELL_WORK_SCANNERS registry\n  \u2514\u2500 file Work scan                  aggregate per-path fold + sandbox export pipeline (NOT a scanner)\n```\n\nCommand parsing is split the same way: `packages\/database\/src\/models\/work\/shellCommandParsing.ts` holds the command-agnostic layer (POSIX-ish tokenizer, control-operator segmenting, codex `\/bin\/zsh -lc` wrapper expansion \u2014 `parseShellCommandSegments`), while `githubToolResult.ts` holds only the gh-specific `parseGhSegment` + field mapping.\n\n### Cost granularity: execution-time vs completion-time\n\n`cumulativeCost` \/ `cumulativeUsage` are per-version SNAPSHOTS (\"spend up to this version\"), never deltas \u2014 summing them across versions double-counts on every path.\n\n- **Execution-time registrations** (skill providers) snapshot right after `UsageCounter.accumulateTool` for that call, so create + edit + edit within one run carries an INCREASING series (e.g. $0.30 \u2192 $0.70 \u2192 $1.20) and step deltas are recoverable.\n- **Completion-time registrations** (shell scan, file scan) attach one OPERATION-LEVEL figure \u2014 the completing run's terminal total plus terminal child-op totals \u2014 to EVERY version registered that round: the scan only has persisted command text + stdout, no per-call intermediate snapshots (hetero CLI usage is aggregated per step by the trace recorder, not per tool call). The same create + edit + edit therefore yields three versions all carrying $1.20, indistinguishable per step.\n- Cross-operation is independent: a later run editing the same resource appends a version with THAT run's total only.\n\n**Why file Works are not a scanner**: their unit is a file path folded across ALL records (multi-edit merge, renames, last-edit provenance), the registration is a heavy IO pipeline (idempotency probe \u2192 sandbox export \u2192 upload \u2192 version \u2192 redeploy, bounded concurrency), hetero records are deliberately EXCLUDED (the file lives on the executing device, not the exportable sandbox), and the version key is the synthetic `op:${operationId}` instead of a real toolCallId. Shoehorning that into `ShellWorkScanner` would break the interface. If a second aggregate-style scan ever appears, extract an aggregate layer then.\n\n## Display anchor & completion marker\n\nA Works card renders only under an assistant message stamped with `metadata.work.rootOperationId` (the \"anchor\"). Who stamps it:\n\n- **In-process runs**: `callLlmFinalizer` stamps the round's final assistant message.\n- **Hetero runs** never pass that executor, so `registerWorksForOperation` stamps the anchor itself when the shell scan registered anything \u2014 using the completion's `assistantMessageId`, falling back to the `parentId` of the last registered tool message (hetero single-step runs persist no final-assistant pointer at all; see `heteroFinish`).\n\nThe whole scan returns `{attempted, failed}` and the completion backstop (`CompletionLifecycle`) writes its idempotency marker only when `failed === 0`. Anything that must be retried \u2014 a thrown registration, a `{success: false}` anchor stamp, an unresolvable anchor \u2014 counts into `failed`. Registration is retry-safe end to end (probe short-circuits, `(workId, toolCallId)` guard backs it up), so counting a failure is always the right move.\n\n## Key decisions (from the Work PRs)\n\n- **Only successful create\/edit results become Works** (LOBE-10967). Read-only queries, comments, merges\/closes, and branch\/repo operations are excluded \u2014 `gh pr view` printing an entity URL must NOT register.\n- **`owner\/repo#number` is the canonical github identity**, not node_id: the gh CLI surface never returns node_id, and the same entity touched via REST tools and CLI must land on one Work row.\n- **stdout is the source of truth for identity** on the CLI path (`gh \u2026 create\/edit` prints the entity URL); the command's edit target is the fallback. The LAST gh create\/edit segment of a chained command owns the trailing URL.\n- **Persisted URLs are http(s)-allowlisted** (`sanitizeExternalUrl`): gh stdout \/ tool results are member-controlled and the URL reaches `shell.openExternal` on desktop.\n- **Partial registrations merge version metadata too.** With `patchFields`, `registerWorkVersion` spreads the new `metadata` over the current version's, so a GitHub PR's `headBranch` \/ `baseBranch` (from `--head` \/ `--base` or REST `head.ref` \/ `base.ref`) survive an edit that names neither. A key cannot be cleared on that path; a provider that needs to unset one must send a complete registration.\n- **GitHub state is drawn, not written.** The card's icon carries open \/ draft \/ merged \/ closed (`GITHUB_STATES` in `src\/features\/Work\/descriptors.tsx`), so GitHub descriptions never fall back to the status word. The stored status only changes on create\/edit registrations; a merge does not register, so a merged PR keeps its last registered state.\n- **The tokenizer is deliberately hand-rolled** (no `shell-quote` dep): a real parser would expand what must stay literal, and the worst failure mode is skipping a bookkeeping registration.\n- **Error-terminated runs skip the completion scan** (same success gate as file Works): a `gh` create that succeeds before a later terminal failure registers no Work that round. Accepted \u2014 bounded cost, missing card only.\n- **Hetero Works register after the terminal snapshot** (`agent_runtime_end` publishes before `completeOperation`), so a hetero-created card appears on the next refetch, not in the terminal snapshot. Accepted for now.\n- **PRs pushed via codex's own GitHub integration are not covered** \u2014 no shell record exists; text-mention parsing was rejected as too false-positive-prone.\n\n## Extension recipes\n\n**New skill provider (structured tools), e.g. Notion:**\n\n1. `packages\/types\/src\/work.ts` \u2014 extend `WORK_SKILL_PROVIDERS` + `WORK_PROVIDER_RESOURCE_TYPES` (+ resource-type unions).\n2. `packages\/database\/src\/models\/work\/<provider>ToolResult.ts` \u2014 write the normalizer; mirror `linearToolResult.ts`.\n3. `packages\/database\/src\/models\/work\/index.ts` \u2014 add it to `SKILL_TOOL_RESULT_NORMALIZERS` (the `satisfies` forces this).\n4. Pick a stable cross-surface `resourceId` (the github lesson: choose the identity every surface can produce).\n\n**New shell CLI scanner, e.g. `linear` CLI or `vercel deploy`:**\n\n1. Add a normalizer in `packages\/database\/src\/models\/work\/` reusing `parseShellCommandSegments`, plus a `WorkModel.registerShell<X>Result` facade method.\n2. Add `apps\/server\/src\/services\/workRegistration\/shellWorkScanners\/<name>.ts` with `{ matches, name, register }` \u2014 `matches` stays a cheap substring check.\n3. Append it to `SHELL_WORK_SCANNERS` in `shellWorkScanners\/index.ts`. The engine needs zero changes.\n4. Pin the parsing edge cases in `packages\/database\/src\/models\/work\/__tests__\/` (wrapper unwrap, chained segments, failed\/read-only commands must not register).\n\n**New Work type (new card kind):**\n\n1. `@lobechat\/types` \u2014 extend `WorkType` and related unions.\n2. `packages\/database\/src\/models\/work\/` \u2014 new adapter module + `WORK_TYPE_ADAPTERS` entry (compile-enforced).\n3. Client \u2014 add the type descriptor for the card UI.\n4. **Add the type to the read-path opt-in gate** (`OPT_IN_WORK_TYPES` pattern) \u2014 released clients throw on unknown types; never ship a new type into the legacy result set.\n\n## File map\n\n| Concern                                              | Path                                                                     |\n| ---------------------------------------------------- | ------------------------------------------------------------------------ |\n| Schema                                               | `packages\/database\/src\/schemas\/work.ts`                                  |\n| Type registry + read gate                            | `packages\/database\/src\/models\/work\/registry.ts`                          |\n| WorkModel facade + provider normalizer map           | `packages\/database\/src\/models\/work\/index.ts`                             |\n| gh CLI + structured github normalizer                | `packages\/database\/src\/models\/work\/githubToolResult.ts`                  |\n| Command-agnostic shell parsing                       | `packages\/database\/src\/models\/work\/shellCommandParsing.ts`               |\n| Completion scan orchestrator (file + shell + anchor) | `apps\/server\/src\/services\/workRegistration\/registerWorksForOperation.ts` |\n| Shell scan engine                                    | `apps\/server\/src\/services\/workRegistration\/shellWorkRegistration.ts`     |\n| Desktop-local run scan (client-reported)             | `apps\/server\/src\/services\/workRegistration\/localRunWorkRegistration.ts`  |\n| Per-CLI scanners                                     | `apps\/server\/src\/services\/workRegistration\/shellWorkScanners\/`           |\n| Client (non-gateway) registration                    | `src\/store\/chat\/agents\/registerClientWorkFromIntent.ts`                  |\n","use_cases":["Register a GitHub PR as a Work record with version tracking","Track changes to a Linear issue through multiple edits","Register a file Work with version history and access scopes"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/agent-work\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T10:57:11.000000Z","updated_at":"2026-11-22T11:17:05.000000Z","seo_title":"Register Agent Work for Tracking","seo_description":"Register Work records for agent outputs like GitHub PRs, Linear issues, and files. Tracks versions and scopes for access control.","seo_keywords":["register agent work","track agent outputs","version work records","access control works","github pr work","linear issue tracking"]}}