feat(runner): add channel, kvLabels, schemaBlocks, and resultSchemaRef parity to native task tools (#23406)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner agents coordinate tasks, progress updates, and
searches through semantic protocol tools (`create_task`,
`report_progress`, `search_tasks`, `get_task_context`, and
`get_task_history`)
> - Headless API clients already use channels, key-value labels
(`kvLabels`), validated `<name>@<version>` schema blocks
(`schemaBlocks`), and required completion schemas (`resultSchemaRef`),
while native Runner tools omitted those fields
> - Because native Runner tools omitted those fields, native agents
could not file tasks into channels, filter task searches by channel or
label, attach structured schema blocks to progress updates, or verify
`resultSchemaRef` before completion
> - This pull request adds channel, `kvLabels`, `schemaBlocks`, and
`resultSchemaRef` support across native Runner tool schemas, authority
handlers, completion validation, and `skills/paperclip/SKILL.md`
> - The benefit is full structured-metadata and channel parity for
native Runner agents while preserving strict provider tool schemas,
private channel boundaries, and upgrade-safe receipt replay

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Native Runner task tools (`create_task`, `report_progress`,
`search_tasks`, `get_task_context`, and `get_task_history`), native
deliverable completion checks (`validateNativeDeliverableEvidence`), and
`skills/paperclip/SKILL.md`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Currently, native Runner semantic tools (`create_task`,
`report_progress`, and `search_tasks`) do not accept `kvLabels`,
`channel`, `labelFilter`, `schemaBlocks`, or `resultSchemaRef`. Read
tools (`get_task_context`, `get_task_history`, and `search_tasks`) omit
`channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`. In addition, `validateNativeDeliverableEvidence` does
not check `issues.resultSchemaRef` before a native run marks a task
`done`.

**Proposed behavior**
`create_task` accepts optional `kvLabels`, `resultSchemaRef`, and
`channel` inputs and returns `channelId`, `channelPath`, `kvLabels`, and
`resultSchemaRef` on `result.task`. `report_progress` accepts optional
`kvLabels` and `schemaBlocks` inputs and extracts `json
schema=<name>@<version>` fenced blocks from `body` with a single-pass
`O(N)` line scanner. `search_tasks` accepts optional `labelFilter` and
`channel` filters (exact path, subtree prefix, or UUID) while preserving
cursor pagination and private channel access checks. `get_task_context`
and `search_tasks` return `channelId`, `channelPath`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`, and `get_task_history` returns
`actorProfile`, `kvLabels`, and `schemaBlocks` (clearing metadata on
quarantined comments for higher-trust readers). When
`issues.resultSchemaRef` is set, `validateNativeDeliverableEvidence`
requires a valid matching JSON payload before completion, and final
reply comments persist valid fenced schema blocks onto
`issue_comments.schema_blocks`.

**Reason and benefit**
Agents running on the native Runner protocol need the same channel
routing, key-value metadata, and structured JSON schema contracts that
REST and headless workflows use. Enforcing `resultSchemaRef` at the
native deliverable gate prevents native runs from closing tasks without
valid structured output.

**Breaking changes**
None. All new tool input and output properties are optional. Existing
tool calls and saved mutation receipts without the new fields continue
to validate and replay without change.

**Additional context**
Tool input schemas use strict provider-portable array entries for
`kvLabels` (`{ key, value }`) and `schemaBlocks` (`{ schema, version,
dataJson }`) so OpenAI/Codex dynamic tools, AgentCore inline schemas,
Ajv strict mode, and RE2 checks all pass without open object maps.

## What Changed

- Extend `create_task`, `report_progress`, and `search_tasks` in
`packages/paperclip-runner/src/protocol-actions/` and
`src/catalog/semantic-action-catalog.ts`, and regenerate contract
manifests, capability YAML/Markdown, capability inventory, and seeded
eval fixtures.
- Add `native-schema-fences.ts`, `native-task-channels.ts`, and
`native-result-schema-gate.ts` (re-exported by
`native-task-metadata.ts`) with a linear `O(N)` single-pass CommonMark
fence scanner (`scanFencedSchemaBlocks`), `kvLabels` normalization,
transactional `schemaBlocks` persistence, a 128 KiB response-wide
`schemaBlocks` budget with truncation metadata, private-channel
authorization helpers, and run-scoped
`assertNativeResultSchemaSatisfied`.
- Update `PaperclipRunnerToolAuthority` (`get_task_context`,
`get_task_history`, `search_tasks`, `#reportProgress`, and
`#createTask`) for read/write parity, private-channel redaction,
quarantined comment `actorProfile`/`kvLabels`/`schemaBlocks` redaction,
and `channel` scope inclusion on filtered searches.
- Wire `assertNativeResultSchemaSatisfied` into
`validateNativeDeliverableEvidence` and persist valid fenced schema
blocks on final reply comments in `native-run-finalizer.ts` and
`run-completion.ts`.
- Document `kvLabels`, `channelPath`, `schemaBlocks`, `resultSchemaRef`,
and `PATCH /api/issues/{issueId}/kv-labels` in
`skills/paperclip/SKILL.md`.
- Add unit, ReDoS linear-time (`< 50ms` on 5,000 unclosed fences),
integration, private-channel, completion-gate, and upgrade-cutover
receipt replay tests.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner typecheck:typescript`
- `pnpm --filter @paperclipai/paperclip-runner check:protocol-manifest`
- `pnpm --filter @paperclipai/paperclip-runner
check:capability-contract`
- `pnpm --filter @paperclipai/paperclip-runner check:semantic-contracts`
- `pnpm --filter @paperclipai/paperclip-runner
check:semantic-action-catalog`
- `pnpm --filter @paperclipai/paperclip-runner check:replay-goldens`
- `pnpm --filter @paperclipai/paperclip-runner test:typescript:prep`
- `pnpm --filter @paperclipai/paperclip-runner check:static`
- `pnpm --filter @paperclipai/paperclip-runner check:api-authority`
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/protocol-actions/collaboration-contracts.test.ts
src/protocol-actions/core-contracts.test.ts
src/catalog/semantic-action-catalog.test.ts
src/contracts/provider-tool-schema-shape.test.ts
src/drivers/runner-tool-bridge.schemas.test.ts
src/evals/native-execution.test.ts
src/semantic-tools/semantic-tools.test.ts
src/mock-core/capability-mock-control-plane-adapter.test.ts`
- `node
packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs`
- `(cd server && node scripts/typecheck-layers.mjs)`
- `node scripts/check-test-budget.mjs`
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/native-task-metadata.test.ts
src/services/native-runtime/tool-input-variant-admission.test.ts
src/services/native-runtime/native-completion-feedback.test.ts
src/services/native-runtime/paperclip-runner-tool-authority.test.ts`

## Risks

- **Upgrade-safe run state carry-forward
(`rules/upgrade-safe-run-state.mdc`)**: In-flight native runs started on
a previous release may carry saved `semanticToolReceipts` in
`heartbeat_runs.result_json` for `create_task` and `report_progress`
without `kvLabels`, `resultSchemaRef`, `channel`, or `schemaBlocks`. All
new fields are optional, `#withMutationReceipt` hashes raw caller
`input` without mutating missing keys, and `create_task`
`outputSchema.properties.task.required` is unchanged. Previous-release
receipts replay identically on `recover()` and `execute()` without
re-running effects, verified by a dedicated cutover test in
`paperclip-runner-tool-authority.test.ts`.
- **Markdown scanning safety**: Fenced schema extraction uses a bounded
`O(N)` line scanner (512 KiB max markdown scan, 64 KiB max fence body,
64 max candidate fences, zero multi-line backreference regular
expressions) so untrusted or malformed markdown cannot cause quadratic
backtracking.

## Model Used

- Anthropic Claude Opus 4.6 (`claude-opus-4-6`, extended thinking
enabled, agentic tool use and local command execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-01 15:53:37 -06:00
1 parent d884e4e877
commit 3833e1c8e8
24 files changed
+3102 -234

No files matched your search

@@ -47,39 +47,39 @@ The skill/reference inventory and eval cases are the only normative behavior sou
| skill:skills/paperclip/SKILL.md:conversation-tasks:32 | optional_agent_tool | skills/paperclip/SKILL.md:32 |
| skill:skills/paperclip/SKILL.md:server-verified-external-chat-turns:54 | control_plane_owned | skills/paperclip/SKILL.md:54 |
| skill:skills/paperclip/SKILL.md:the-heartbeat-procedure:94 | optional_agent_tool | skills/paperclip/SKILL.md:94 |
| skill:skills/paperclip/SKILL.md:generated-artifacts-and-work-products:206 | always_agent_tool | skills/paperclip/SKILL.md:206 |
| skill:skills/paperclip/SKILL.md:offer-a-routine-after-recurring-work:252 | optional_agent_tool | skills/paperclip/SKILL.md:252 |
| skill:skills/paperclip/SKILL.md:areas-and-responsibilities:275 | optional_agent_tool | skills/paperclip/SKILL.md:275 |
| skill:skills/paperclip/SKILL.md:propose-a-bar-in-a-bar-conversation:294 | optional_agent_tool | skills/paperclip/SKILL.md:294 |
| skill:skills/paperclip/SKILL.md:propose-an-automation-in-an-automation-conversation:298 | optional_agent_tool | skills/paperclip/SKILL.md:298 |
| skill:skills/paperclip/SKILL.md:write-a-responsibility-s-status:302 | optional_agent_tool | skills/paperclip/SKILL.md:302 |
| skill:skills/paperclip/SKILL.md:status-quick-guide:308 | control_plane_owned | skills/paperclip/SKILL.md:308 |
| skill:skills/paperclip/SKILL.md:monitors-and-watchers-say-only-what-you-actually-scheduled:318 | optional_agent_tool | skills/paperclip/SKILL.md:318 |
| skill:skills/paperclip/SKILL.md:delegating-review-tasks:339 | always_agent_tool | skills/paperclip/SKILL.md:339 |
| skill:skills/paperclip/SKILL.md:managing-a-user-s-inbox:350 | control_plane_owned | skills/paperclip/SKILL.md:350 |
| skill:skills/paperclip/SKILL.md:issue-dependencies-blockers:358 | control_plane_owned | skills/paperclip/SKILL.md:358 |
| skill:skills/paperclip/SKILL.md:requesting-board-approval:383 | optional_agent_tool | skills/paperclip/SKILL.md:383 |
| skill:skills/paperclip/SKILL.md:issue-thread-interactions:404 | optional_agent_tool | skills/paperclip/SKILL.md:404 |
| skill:skills/paperclip/SKILL.md:standalone-decisions:434 | optional_agent_tool | skills/paperclip/SKILL.md:434 |
| skill:skills/paperclip/SKILL.md:mcp-tool-approval-gates:538 | optional_agent_tool | skills/paperclip/SKILL.md:538 |
| skill:skills/paperclip/SKILL.md:niche-workflow-pointers:580 | optional_agent_tool | skills/paperclip/SKILL.md:580 |
| skill:skills/paperclip/SKILL.md:cases:590 | optional_agent_tool | skills/paperclip/SKILL.md:590 |
| skill:skills/paperclip/SKILL.md:company-skills-workflow:595 | optional_agent_tool | skills/paperclip/SKILL.md:595 |
| skill:skills/paperclip/SKILL.md:routines:606 | optional_agent_tool | skills/paperclip/SKILL.md:606 |
| skill:skills/paperclip/SKILL.md:task-files-and-workspace-choices:618 | optional_agent_tool | skills/paperclip/SKILL.md:618 |
| skill:skills/paperclip/SKILL.md:issue-workspace-runtime-controls:626 | optional_agent_tool | skills/paperclip/SKILL.md:626 |
| skill:skills/paperclip/SKILL.md:proposing-credentials-safely:633 | optional_agent_tool | skills/paperclip/SKILL.md:633 |
| skill:skills/paperclip/SKILL.md:reading-granted-secrets:640 | optional_agent_tool | skills/paperclip/SKILL.md:640 |
| skill:skills/paperclip/SKILL.md:critical-rules:666 | optional_agent_tool | skills/paperclip/SKILL.md:666 |
| skill:skills/paperclip/SKILL.md:comment-style-required:687 | always_agent_tool | skills/paperclip/SKILL.md:687 |
| skill:skills/paperclip/SKILL.md:update:723 | optional_agent_tool | skills/paperclip/SKILL.md:723 |
| skill:skills/paperclip/SKILL.md:task-documents-and-deliverables:733 | always_agent_tool | skills/paperclip/SKILL.md:733 |
| skill:skills/paperclip/SKILL.md:planning-required-when-planning-requested:747 | optional_agent_tool | skills/paperclip/SKILL.md:747 |
| skill:skills/paperclip/SKILL.md:key-endpoints-hot-routes:778 | optional_agent_tool | skills/paperclip/SKILL.md:778 |
| skill:skills/paperclip/SKILL.md:searching-issues:808 | optional_agent_tool | skills/paperclip/SKILL.md:808 |
| skill:skills/paperclip/SKILL.md:full-reference:818 | optional_agent_tool | skills/paperclip/SKILL.md:818 |
| skill:skills/paperclip/SKILL.md:conversational-confirmation-answers:822 | always_agent_tool | skills/paperclip/SKILL.md:822 |
| skill:skills/paperclip/SKILL.md:incidental-feedback:839 | optional_agent_tool | skills/paperclip/SKILL.md:839 |
| skill:skills/paperclip/SKILL.md:generated-artifacts-and-work-products:208 | always_agent_tool | skills/paperclip/SKILL.md:208 |
| skill:skills/paperclip/SKILL.md:offer-a-routine-after-recurring-work:254 | optional_agent_tool | skills/paperclip/SKILL.md:254 |
| skill:skills/paperclip/SKILL.md:areas-and-responsibilities:277 | optional_agent_tool | skills/paperclip/SKILL.md:277 |
| skill:skills/paperclip/SKILL.md:propose-a-bar-in-a-bar-conversation:296 | optional_agent_tool | skills/paperclip/SKILL.md:296 |
| skill:skills/paperclip/SKILL.md:propose-an-automation-in-an-automation-conversation:300 | optional_agent_tool | skills/paperclip/SKILL.md:300 |
| skill:skills/paperclip/SKILL.md:write-a-responsibility-s-status:304 | optional_agent_tool | skills/paperclip/SKILL.md:304 |
| skill:skills/paperclip/SKILL.md:status-quick-guide:310 | control_plane_owned | skills/paperclip/SKILL.md:310 |
| skill:skills/paperclip/SKILL.md:monitors-and-watchers-say-only-what-you-actually-scheduled:320 | optional_agent_tool | skills/paperclip/SKILL.md:320 |
| skill:skills/paperclip/SKILL.md:delegating-review-tasks:341 | always_agent_tool | skills/paperclip/SKILL.md:341 |
| skill:skills/paperclip/SKILL.md:managing-a-user-s-inbox:352 | control_plane_owned | skills/paperclip/SKILL.md:352 |
| skill:skills/paperclip/SKILL.md:issue-dependencies-blockers:360 | control_plane_owned | skills/paperclip/SKILL.md:360 |
| skill:skills/paperclip/SKILL.md:requesting-board-approval:385 | optional_agent_tool | skills/paperclip/SKILL.md:385 |
| skill:skills/paperclip/SKILL.md:issue-thread-interactions:406 | optional_agent_tool | skills/paperclip/SKILL.md:406 |
| skill:skills/paperclip/SKILL.md:standalone-decisions:436 | optional_agent_tool | skills/paperclip/SKILL.md:436 |
| skill:skills/paperclip/SKILL.md:mcp-tool-approval-gates:540 | optional_agent_tool | skills/paperclip/SKILL.md:540 |
| skill:skills/paperclip/SKILL.md:niche-workflow-pointers:582 | optional_agent_tool | skills/paperclip/SKILL.md:582 |
| skill:skills/paperclip/SKILL.md:cases:592 | optional_agent_tool | skills/paperclip/SKILL.md:592 |
| skill:skills/paperclip/SKILL.md:company-skills-workflow:597 | optional_agent_tool | skills/paperclip/SKILL.md:597 |
| skill:skills/paperclip/SKILL.md:routines:608 | optional_agent_tool | skills/paperclip/SKILL.md:608 |
| skill:skills/paperclip/SKILL.md:task-files-and-workspace-choices:620 | optional_agent_tool | skills/paperclip/SKILL.md:620 |
| skill:skills/paperclip/SKILL.md:issue-workspace-runtime-controls:628 | optional_agent_tool | skills/paperclip/SKILL.md:628 |
| skill:skills/paperclip/SKILL.md:proposing-credentials-safely:635 | optional_agent_tool | skills/paperclip/SKILL.md:635 |
| skill:skills/paperclip/SKILL.md:reading-granted-secrets:642 | optional_agent_tool | skills/paperclip/SKILL.md:642 |
| skill:skills/paperclip/SKILL.md:critical-rules:668 | optional_agent_tool | skills/paperclip/SKILL.md:668 |
| skill:skills/paperclip/SKILL.md:comment-style-required:689 | always_agent_tool | skills/paperclip/SKILL.md:689 |
| skill:skills/paperclip/SKILL.md:update:725 | optional_agent_tool | skills/paperclip/SKILL.md:725 |
| skill:skills/paperclip/SKILL.md:task-documents-and-deliverables:735 | always_agent_tool | skills/paperclip/SKILL.md:735 |
| skill:skills/paperclip/SKILL.md:planning-required-when-planning-requested:749 | optional_agent_tool | skills/paperclip/SKILL.md:749 |
| skill:skills/paperclip/SKILL.md:key-endpoints-hot-routes:780 | optional_agent_tool | skills/paperclip/SKILL.md:780 |
| skill:skills/paperclip/SKILL.md:searching-issues:810 | optional_agent_tool | skills/paperclip/SKILL.md:810 |
| skill:skills/paperclip/SKILL.md:full-reference:820 | optional_agent_tool | skills/paperclip/SKILL.md:820 |
| skill:skills/paperclip/SKILL.md:conversational-confirmation-answers:824 | always_agent_tool | skills/paperclip/SKILL.md:824 |
| skill:skills/paperclip/SKILL.md:incidental-feedback:841 | optional_agent_tool | skills/paperclip/SKILL.md:841 |
| skill:skills/paperclip/references/api-reference.md:paperclip-api-reference:1 | optional_agent_tool | skills/paperclip/references/api-reference.md:1 |
| skill:skills/paperclip/references/api-reference.md:response-schemas:9 | optional_agent_tool | skills/paperclip/references/api-reference.md:9 |
| skill:skills/paperclip/references/api-reference.md:agent-record-get-api-agents-me-or-get-api-agents-agentid:11 | optional_agent_tool | skills/paperclip/references/api-reference.md:11 |
@@ -56,297 +56,297 @@
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:206",
"id": "skill:skills/paperclip/SKILL.md:208",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L206:generated-artifacts-and-work-products",
"sourceAnchor": "skills/paperclip/SKILL.md#L208:generated-artifacts-and-work-products",
"heading": "Generated Artifacts and Work Products",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "register_deliverable",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:252",
"id": "skill:skills/paperclip/SKILL.md:254",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L252:offer-a-routine-after-recurring-work",
"sourceAnchor": "skills/paperclip/SKILL.md#L254:offer-a-routine-after-recurring-work",
"heading": "Offer a routine after recurring work",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:275",
"id": "skill:skills/paperclip/SKILL.md:277",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L275:areas-and-responsibilities",
"sourceAnchor": "skills/paperclip/SKILL.md#L277:areas-and-responsibilities",
"heading": "Areas and responsibilities",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:294",
"id": "skill:skills/paperclip/SKILL.md:296",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L294:propose-a-bar-in-a-bar-conversation",
"sourceAnchor": "skills/paperclip/SKILL.md#L296:propose-a-bar-in-a-bar-conversation",
"heading": "Propose a bar in a bar conversation",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:298",
"id": "skill:skills/paperclip/SKILL.md:300",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L298:propose-an-automation-in-an-automation-conversation",
"sourceAnchor": "skills/paperclip/SKILL.md#L300:propose-an-automation-in-an-automation-conversation",
"heading": "Propose an automation in an automation conversation",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:302",
"id": "skill:skills/paperclip/SKILL.md:304",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L302:write-a-responsibility-s-status",
"sourceAnchor": "skills/paperclip/SKILL.md#L304:write-a-responsibility-s-status",
"heading": "Write a responsibility's status",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:308",
"id": "skill:skills/paperclip/SKILL.md:310",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L308:status-quick-guide",
"sourceAnchor": "skills/paperclip/SKILL.md#L310:status-quick-guide",
"heading": "Status Quick Guide",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:318",
"id": "skill:skills/paperclip/SKILL.md:320",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L318:monitors-and-watchers-say-only-what-you-actually-scheduled",
"sourceAnchor": "skills/paperclip/SKILL.md#L320:monitors-and-watchers-say-only-what-you-actually-scheduled",
"heading": "Monitors and Watchers (say only what you actually scheduled)",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:339",
"id": "skill:skills/paperclip/SKILL.md:341",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L339:delegating-review-tasks",
"sourceAnchor": "skills/paperclip/SKILL.md#L341:delegating-review-tasks",
"heading": "Delegating review tasks",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:350",
"id": "skill:skills/paperclip/SKILL.md:352",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L350:managing-a-user-s-inbox",
"sourceAnchor": "skills/paperclip/SKILL.md#L352:managing-a-user-s-inbox",
"heading": "Managing A User's Inbox",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:358",
"id": "skill:skills/paperclip/SKILL.md:360",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L358:issue-dependencies-blockers",
"sourceAnchor": "skills/paperclip/SKILL.md#L360:issue-dependencies-blockers",
"heading": "Issue Dependencies (Blockers)",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:383",
"id": "skill:skills/paperclip/SKILL.md:385",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L383:requesting-board-approval",
"sourceAnchor": "skills/paperclip/SKILL.md#L385:requesting-board-approval",
"heading": "Requesting Board Approval",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:404",
"id": "skill:skills/paperclip/SKILL.md:406",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L404:issue-thread-interactions",
"sourceAnchor": "skills/paperclip/SKILL.md#L406:issue-thread-interactions",
"heading": "Issue-Thread Interactions",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "request_human_input",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:434",
"id": "skill:skills/paperclip/SKILL.md:436",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L434:standalone-decisions",
"sourceAnchor": "skills/paperclip/SKILL.md#L436:standalone-decisions",
"heading": "Standalone Decisions",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:538",
"id": "skill:skills/paperclip/SKILL.md:540",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L538:mcp-tool-approval-gates",
"sourceAnchor": "skills/paperclip/SKILL.md#L540:mcp-tool-approval-gates",
"heading": "MCP Tool Approval Gates",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:580",
"id": "skill:skills/paperclip/SKILL.md:582",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L580:niche-workflow-pointers",
"sourceAnchor": "skills/paperclip/SKILL.md#L582:niche-workflow-pointers",
"heading": "Niche Workflow Pointers",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:590",
"id": "skill:skills/paperclip/SKILL.md:592",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L590:cases",
"sourceAnchor": "skills/paperclip/SKILL.md#L592:cases",
"heading": "Cases",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:595",
"id": "skill:skills/paperclip/SKILL.md:597",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L595:company-skills-workflow",
"sourceAnchor": "skills/paperclip/SKILL.md#L597:company-skills-workflow",
"heading": "Company Skills Workflow",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:606",
"id": "skill:skills/paperclip/SKILL.md:608",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L606:routines",
"sourceAnchor": "skills/paperclip/SKILL.md#L608:routines",
"heading": "Routines",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:618",
"id": "skill:skills/paperclip/SKILL.md:620",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L618:task-files-and-workspace-choices",
"sourceAnchor": "skills/paperclip/SKILL.md#L620:task-files-and-workspace-choices",
"heading": "Task Files and Workspace Choices",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:626",
"id": "skill:skills/paperclip/SKILL.md:628",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L626:issue-workspace-runtime-controls",
"sourceAnchor": "skills/paperclip/SKILL.md#L628:issue-workspace-runtime-controls",
"heading": "Issue Workspace Runtime Controls",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:633",
"id": "skill:skills/paperclip/SKILL.md:635",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L633:proposing-credentials-safely",
"sourceAnchor": "skills/paperclip/SKILL.md#L635:proposing-credentials-safely",
"heading": "Proposing Credentials Safely",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:640",
"id": "skill:skills/paperclip/SKILL.md:642",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L640:reading-granted-secrets",
"sourceAnchor": "skills/paperclip/SKILL.md#L642:reading-granted-secrets",
"heading": "Reading Granted Secrets",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:666",
"id": "skill:skills/paperclip/SKILL.md:668",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L666:critical-rules",
"sourceAnchor": "skills/paperclip/SKILL.md#L668:critical-rules",
"heading": "Critical Rules",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:687",
"id": "skill:skills/paperclip/SKILL.md:689",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L687:comment-style-required",
"sourceAnchor": "skills/paperclip/SKILL.md#L689:comment-style-required",
"heading": "Comment Style (Required)",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "report_progress",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:723",
"id": "skill:skills/paperclip/SKILL.md:725",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L723:update",
"sourceAnchor": "skills/paperclip/SKILL.md#L725:update",
"heading": "Update",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:733",
"id": "skill:skills/paperclip/SKILL.md:735",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L733:task-documents-and-deliverables",
"sourceAnchor": "skills/paperclip/SKILL.md#L735:task-documents-and-deliverables",
"heading": "Task Documents and Deliverables",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "write_document",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:747",
"id": "skill:skills/paperclip/SKILL.md:749",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L747:planning-required-when-planning-requested",
"sourceAnchor": "skills/paperclip/SKILL.md#L749:planning-required-when-planning-requested",
"heading": "Planning (Required when planning requested)",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "write_document",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:778",
"id": "skill:skills/paperclip/SKILL.md:780",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L778:key-endpoints-hot-routes",
"sourceAnchor": "skills/paperclip/SKILL.md#L780:key-endpoints-hot-routes",
"heading": "Key Endpoints (Hot Routes)",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:808",
"id": "skill:skills/paperclip/SKILL.md:810",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L808:searching-issues",
"sourceAnchor": "skills/paperclip/SKILL.md#L810:searching-issues",
"heading": "Searching Issues",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:818",
"id": "skill:skills/paperclip/SKILL.md:820",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L818:full-reference",
"sourceAnchor": "skills/paperclip/SKILL.md#L820:full-reference",
"heading": "Full Reference",
"primaryDisposition": "control_plane_owned",
"semanticOperation": "runtime_reconciliation",
"expectedMockState": "runtime_decision_record"
},
{
"id": "skill:skills/paperclip/SKILL.md:822",
"id": "skill:skills/paperclip/SKILL.md:824",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L822:conversational-confirmation-answers",
"sourceAnchor": "skills/paperclip/SKILL.md#L824:conversational-confirmation-answers",
"heading": "Conversational confirmation answers",
"primaryDisposition": "always_agent_tool",
"semanticOperation": "call_api",
"expectedMockState": "operation_result"
},
{
"id": "skill:skills/paperclip/SKILL.md:839",
"id": "skill:skills/paperclip/SKILL.md:841",
"kind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md#L839:incidental-feedback",
"sourceAnchor": "skills/paperclip/SKILL.md#L841:incidental-feedback",
"heading": "Incidental feedback",
"primaryDisposition": "optional_agent_tool",
"semanticOperation": "scoped_discovery",
@@ -5,6 +5,6 @@ Generated by `scripts/generate-capability-contract.mjs`; do not edit generated f
- Skill/reference headings: 177
- Legacy MCP tools: 42
- Eval cases: 106 across 16 groups
- Deterministic content SHA-256: `dd7574b1a482ef12d5c5adc4cd038efb95b278e6c5f66520b8fa3151808ae35f`
- Deterministic content SHA-256: `570c13b5d4b0dd6ef75b73737ad0baa0cc95d50479abd5d976097259d361ddc1`
Every row has exactly one primary disposition, a source anchor, a semantic operation, and a mock-state expectation.
@@ -1 +1 @@
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active task only. Calling get_task does not change the active task. This is not a status or assignment audit. For progress chronology and handoff actors, use search_api to discover the company timeline or issue activity, then call_api.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"report_progress","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"answer_status_question","requiredClaims":[],"semanticContract":"paperclip.Line truncated
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active task only. Calling get_task does not change the active task. This is not a status or assignment audit. For progress chronology and handoff actors, use search_api to discover the company timeline or issue activity, then call_api.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update. Fenced ```json schema=<name>@<version> blocks in body are automatically extracted and validated against company and built-in JSON schemas.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"kvLabels":{"description":"Optional key-value metadata attached to the progress comment (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.","items":{"additionalProperties":false,"properties":{"key":{"maxLength":64,"minLength":1,"pattern":"^[a-z0-9][a-z0-9_.-]{0,63}$","type":"string"},"value":{"maxLength":256,"minLength":1,"type":"string"}},"required":["key","value"],"type":"object"},"maxItems":64,"type":"array"},"schemaBlocks":{"description":"Optional structured <name>@<version> blocks validated against company or built-in JSON schemas.","items":{"additionalProperties":false,"properties":{"dataJson":{"description":"JSON-encoded object matching the schema.","maxLength":65536,"minLength":2,"type":"strLine truncated
@@ -461,7 +461,7 @@
"additionalProperties": false,
"properties": {
"body": {
"description": "Multiline progress update.",
"description": "Multiline progress update. Fenced ```json schema=<name>@<version> blocks in body are automatically extracted and validated against company and built-in JSON schemas.",
"maxLength": 20000,
"minLength": 1,
"type": "string"
@@ -471,6 +471,66 @@
"maxLength": 240,
"minLength": 1,
"type": "string"
},
"kvLabels": {
"description": "Optional key-value metadata attached to the progress comment (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
"items": {
"additionalProperties": false,
"properties": {
"key": {
"maxLength": 64,
"minLength": 1,
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"type": "string"
},
"value": {
"maxLength": 256,
"minLength": 1,
"type": "string"
}
},
"required": [
"key",
"value"
],
"type": "object"
},
"maxItems": 64,
"type": "array"
},
"schemaBlocks": {
"description": "Optional structured <name>@<version> blocks validated against company or built-in JSON schemas.",
"items": {
"additionalProperties": false,
"properties": {
"dataJson": {
"description": "JSON-encoded object matching the schema.",
"maxLength": 65536,
"minLength": 2,
"type": "string"
},
"schema": {
"description": "Schema name without @version (for example 'test-report').",
"maxLength": 64,
"minLength": 1,
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}$",
"type": "string"
},
"version": {
"description": "Positive integer schema version (for example 1).",
"minimum": 1,
"type": "integer"
}
},
"required": [
"schema",
"version",
"dataJson"
],
"type": "object"
},
"maxItems": 64,
"type": "array"
}
},
"required": [
@@ -1443,6 +1503,23 @@
"inputSchema": {
"additionalProperties": false,
"properties": {
"channel": {
"description": "Optional channel path (for example 'build/auth'), subtree prefix ('build/*' or 'build/'), or channel UUID.",
"maxLength": 140,
"minLength": 1,
"type": "string"
},
"cursor": {
"description": "The nextCursor from the previous page. Keep query, statuses, labelFilter, and channel unchanged. Omit for the first page.",
"pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
"type": "string"
},
"labelFilter": {
"description": "Optional task label filter: 'key=value', 'key=v1|v2', or 'key' (exists on kvLabels or tag labels).",
"maxLength": 256,
"minLength": 1,
"type": "string"
},
"limit": {
"default": 50,
"maximum": 200,
@@ -4140,6 +4217,15 @@
"type": "array",
"uniqueItems": true
},
"channel": {
"description": "Optional channel path (for example 'build/auth') or channel UUID.",
"maxLength": 140,
"minLength": 1,
"type": [
"string",
"null"
]
},
"description": {
"description": "Task description.",
"maxLength": 20000,
@@ -4162,6 +4248,32 @@
"null"
]
},
"kvLabels": {
"description": "Optional key-value metadata attached to the created task (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
"items": {
"additionalProperties": false,
"properties": {
"key": {
"maxLength": 64,
"minLength": 1,
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"type": "string"
},
"value": {
"maxLength": 256,
"minLength": 1,
"type": "string"
}
},
"required": [
"key",
"value"
],
"type": "object"
},
"maxItems": 64,
"type": "array"
},
"priority": {
"enum": [
"critical",
@@ -4218,6 +4330,15 @@
],
"type": "object"
},
"resultSchemaRef": {
"description": "Optional required completion schema reference (<name>@<version>, for example 'test-report@1').",
"maxLength": 80,
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}@[1-9][0-9]*$",
"type": [
"string",
"null"
]
},
"status": {
"description": "Initial status. Use backlog to save work without execution. Defaults to todo (blocked when dependencies are unresolved).",
"enum": [
@@ -24,7 +24,7 @@
"prpVersion": 1,
"nativeExecutionVersion": 1,
"catalogVersion": 1,
"catalogSha256": "sha256:80d82c265c75f6f4625a949024bf2342586112781942452fbd06c07a2d46c77e",
"catalogSha256": "sha256:b036946867cdde7890de28dea40112f892387740e8f505d692b45863914ef033",
"driverContractVersion": 1,
"driverKind": "paperclip-deterministic",
"driverVersion": "1.0.0"
@@ -190,7 +190,7 @@
},
{
"path": "fixtures/evals/native-execution-seeded.json",
"sha256": "f2a455abf93a792598ae5361acde8ec05b3d9b61ade935698c800204f216b012",
"sha256": "efcba3756640a7a51146dc1715da640381ce7fb16cf5cbc0e23b5e83e6d71743",
"expectation": "accept",
"compatibilityCase": "canonical"
},
@@ -105,9 +105,9 @@
]
},
{
"id": "skill:skills/paperclip/SKILL.md:generated-artifacts-and-work-products:206",
"id": "skill:skills/paperclip/SKILL.md:generated-artifacts-and-work-products:208",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:206",
"sourceAnchor": "skills/paperclip/SKILL.md:208",
"title": "Generated Artifacts and Work Products",
"expectedSemantics": "Skill guidance headed “Generated Artifacts and Work Products”.",
"primaryDisposition": "always_agent_tool",
@@ -116,13 +116,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:206"
"skill:skills/paperclip/SKILL.md:208"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:offer-a-routine-after-recurring-work:252",
"id": "skill:skills/paperclip/SKILL.md:offer-a-routine-after-recurring-work:254",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:252",
"sourceAnchor": "skills/paperclip/SKILL.md:254",
"title": "Offer a routine after recurring work",
"expectedSemantics": "Skill guidance headed “Offer a routine after recurring work”.",
"primaryDisposition": "optional_agent_tool",
@@ -131,13 +131,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:252"
"skill:skills/paperclip/SKILL.md:254"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:areas-and-responsibilities:275",
"id": "skill:skills/paperclip/SKILL.md:areas-and-responsibilities:277",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:275",
"sourceAnchor": "skills/paperclip/SKILL.md:277",
"title": "Areas and responsibilities",
"expectedSemantics": "Skill guidance headed “Areas and responsibilities”.",
"primaryDisposition": "optional_agent_tool",
@@ -146,13 +146,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:275"
"skill:skills/paperclip/SKILL.md:277"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:propose-a-bar-in-a-bar-conversation:294",
"id": "skill:skills/paperclip/SKILL.md:propose-a-bar-in-a-bar-conversation:296",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:294",
"sourceAnchor": "skills/paperclip/SKILL.md:296",
"title": "Propose a bar in a bar conversation",
"expectedSemantics": "Skill guidance headed “Propose a bar in a bar conversation”.",
"primaryDisposition": "optional_agent_tool",
@@ -161,13 +161,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:294"
"skill:skills/paperclip/SKILL.md:296"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:propose-an-automation-in-an-automation-conversation:298",
"id": "skill:skills/paperclip/SKILL.md:propose-an-automation-in-an-automation-conversation:300",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:298",
"sourceAnchor": "skills/paperclip/SKILL.md:300",
"title": "Propose an automation in an automation conversation",
"expectedSemantics": "Skill guidance headed “Propose an automation in an automation conversation”.",
"primaryDisposition": "optional_agent_tool",
@@ -176,13 +176,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:298"
"skill:skills/paperclip/SKILL.md:300"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:write-a-responsibility-s-status:302",
"id": "skill:skills/paperclip/SKILL.md:write-a-responsibility-s-status:304",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:302",
"sourceAnchor": "skills/paperclip/SKILL.md:304",
"title": "Write a responsibility's status",
"expectedSemantics": "Skill guidance headed “Write a responsibility's status”.",
"primaryDisposition": "optional_agent_tool",
@@ -191,13 +191,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:302"
"skill:skills/paperclip/SKILL.md:304"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:status-quick-guide:308",
"id": "skill:skills/paperclip/SKILL.md:status-quick-guide:310",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:308",
"sourceAnchor": "skills/paperclip/SKILL.md:310",
"title": "Status Quick Guide",
"expectedSemantics": "Skill guidance headed “Status Quick Guide”.",
"primaryDisposition": "control_plane_owned",
@@ -206,13 +206,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:308"
"skill:skills/paperclip/SKILL.md:310"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:monitors-and-watchers-say-only-what-you-actually-scheduled:318",
"id": "skill:skills/paperclip/SKILL.md:monitors-and-watchers-say-only-what-you-actually-scheduled:320",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:318",
"sourceAnchor": "skills/paperclip/SKILL.md:320",
"title": "Monitors and Watchers (say only what you actually scheduled)",
"expectedSemantics": "Skill guidance headed “Monitors and Watchers (say only what you actually scheduled)”.",
"primaryDisposition": "optional_agent_tool",
@@ -221,13 +221,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:318"
"skill:skills/paperclip/SKILL.md:320"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:delegating-review-tasks:339",
"id": "skill:skills/paperclip/SKILL.md:delegating-review-tasks:341",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:339",
"sourceAnchor": "skills/paperclip/SKILL.md:341",
"title": "Delegating review tasks",
"expectedSemantics": "Skill guidance headed “Delegating review tasks”.",
"primaryDisposition": "always_agent_tool",
@@ -236,13 +236,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:339"
"skill:skills/paperclip/SKILL.md:341"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:managing-a-user-s-inbox:350",
"id": "skill:skills/paperclip/SKILL.md:managing-a-user-s-inbox:352",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:350",
"sourceAnchor": "skills/paperclip/SKILL.md:352",
"title": "Managing A User's Inbox",
"expectedSemantics": "Skill guidance headed “Managing A User's Inbox”.",
"primaryDisposition": "control_plane_owned",
@@ -251,13 +251,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:350"
"skill:skills/paperclip/SKILL.md:352"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:issue-dependencies-blockers:358",
"id": "skill:skills/paperclip/SKILL.md:issue-dependencies-blockers:360",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:358",
"sourceAnchor": "skills/paperclip/SKILL.md:360",
"title": "Issue Dependencies (Blockers)",
"expectedSemantics": "Skill guidance headed “Issue Dependencies (Blockers)”.",
"primaryDisposition": "control_plane_owned",
@@ -266,13 +266,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:358"
"skill:skills/paperclip/SKILL.md:360"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:requesting-board-approval:383",
"id": "skill:skills/paperclip/SKILL.md:requesting-board-approval:385",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:383",
"sourceAnchor": "skills/paperclip/SKILL.md:385",
"title": "Requesting Board Approval",
"expectedSemantics": "Skill guidance headed “Requesting Board Approval”.",
"primaryDisposition": "optional_agent_tool",
@@ -281,13 +281,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:383"
"skill:skills/paperclip/SKILL.md:385"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:issue-thread-interactions:404",
"id": "skill:skills/paperclip/SKILL.md:issue-thread-interactions:406",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:404",
"sourceAnchor": "skills/paperclip/SKILL.md:406",
"title": "Issue-Thread Interactions",
"expectedSemantics": "Skill guidance headed “Issue-Thread Interactions”.",
"primaryDisposition": "optional_agent_tool",
@@ -296,13 +296,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:404"
"skill:skills/paperclip/SKILL.md:406"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:standalone-decisions:434",
"id": "skill:skills/paperclip/SKILL.md:standalone-decisions:436",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:434",
"sourceAnchor": "skills/paperclip/SKILL.md:436",
"title": "Standalone Decisions",
"expectedSemantics": "Skill guidance headed “Standalone Decisions”.",
"primaryDisposition": "optional_agent_tool",
@@ -311,13 +311,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:434"
"skill:skills/paperclip/SKILL.md:436"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:mcp-tool-approval-gates:538",
"id": "skill:skills/paperclip/SKILL.md:mcp-tool-approval-gates:540",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:538",
"sourceAnchor": "skills/paperclip/SKILL.md:540",
"title": "MCP Tool Approval Gates",
"expectedSemantics": "Skill guidance headed “MCP Tool Approval Gates”.",
"primaryDisposition": "optional_agent_tool",
@@ -326,13 +326,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:538"
"skill:skills/paperclip/SKILL.md:540"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:niche-workflow-pointers:580",
"id": "skill:skills/paperclip/SKILL.md:niche-workflow-pointers:582",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:580",
"sourceAnchor": "skills/paperclip/SKILL.md:582",
"title": "Niche Workflow Pointers",
"expectedSemantics": "Skill guidance headed “Niche Workflow Pointers”.",
"primaryDisposition": "optional_agent_tool",
@@ -341,13 +341,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:580"
"skill:skills/paperclip/SKILL.md:582"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:cases:590",
"id": "skill:skills/paperclip/SKILL.md:cases:592",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:590",
"sourceAnchor": "skills/paperclip/SKILL.md:592",
"title": "Cases",
"expectedSemantics": "Skill guidance headed “Cases”.",
"primaryDisposition": "optional_agent_tool",
@@ -356,13 +356,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:590"
"skill:skills/paperclip/SKILL.md:592"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:company-skills-workflow:595",
"id": "skill:skills/paperclip/SKILL.md:company-skills-workflow:597",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:595",
"sourceAnchor": "skills/paperclip/SKILL.md:597",
"title": "Company Skills Workflow",
"expectedSemantics": "Skill guidance headed “Company Skills Workflow”.",
"primaryDisposition": "optional_agent_tool",
@@ -371,13 +371,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:595"
"skill:skills/paperclip/SKILL.md:597"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:routines:606",
"id": "skill:skills/paperclip/SKILL.md:routines:608",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:606",
"sourceAnchor": "skills/paperclip/SKILL.md:608",
"title": "Routines",
"expectedSemantics": "Skill guidance headed “Routines”.",
"primaryDisposition": "optional_agent_tool",
@@ -386,13 +386,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:606"
"skill:skills/paperclip/SKILL.md:608"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:task-files-and-workspace-choices:618",
"id": "skill:skills/paperclip/SKILL.md:task-files-and-workspace-choices:620",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:618",
"sourceAnchor": "skills/paperclip/SKILL.md:620",
"title": "Task Files and Workspace Choices",
"expectedSemantics": "Skill guidance headed “Task Files and Workspace Choices”.",
"primaryDisposition": "optional_agent_tool",
@@ -401,13 +401,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:618"
"skill:skills/paperclip/SKILL.md:620"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:issue-workspace-runtime-controls:626",
"id": "skill:skills/paperclip/SKILL.md:issue-workspace-runtime-controls:628",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:626",
"sourceAnchor": "skills/paperclip/SKILL.md:628",
"title": "Issue Workspace Runtime Controls",
"expectedSemantics": "Skill guidance headed “Issue Workspace Runtime Controls”.",
"primaryDisposition": "optional_agent_tool",
@@ -416,13 +416,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:626"
"skill:skills/paperclip/SKILL.md:628"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:proposing-credentials-safely:633",
"id": "skill:skills/paperclip/SKILL.md:proposing-credentials-safely:635",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:633",
"sourceAnchor": "skills/paperclip/SKILL.md:635",
"title": "Proposing Credentials Safely",
"expectedSemantics": "Skill guidance headed “Proposing Credentials Safely”.",
"primaryDisposition": "optional_agent_tool",
@@ -431,13 +431,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:633"
"skill:skills/paperclip/SKILL.md:635"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:reading-granted-secrets:640",
"id": "skill:skills/paperclip/SKILL.md:reading-granted-secrets:642",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:640",
"sourceAnchor": "skills/paperclip/SKILL.md:642",
"title": "Reading Granted Secrets",
"expectedSemantics": "Skill guidance headed “Reading Granted Secrets”.",
"primaryDisposition": "optional_agent_tool",
@@ -446,13 +446,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:640"
"skill:skills/paperclip/SKILL.md:642"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:critical-rules:666",
"id": "skill:skills/paperclip/SKILL.md:critical-rules:668",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:666",
"sourceAnchor": "skills/paperclip/SKILL.md:668",
"title": "Critical Rules",
"expectedSemantics": "Skill guidance headed “Critical Rules”.",
"primaryDisposition": "optional_agent_tool",
@@ -461,13 +461,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:666"
"skill:skills/paperclip/SKILL.md:668"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:comment-style-required:687",
"id": "skill:skills/paperclip/SKILL.md:comment-style-required:689",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:687",
"sourceAnchor": "skills/paperclip/SKILL.md:689",
"title": "Comment Style (Required)",
"expectedSemantics": "Skill guidance headed “Comment Style (Required)”.",
"primaryDisposition": "always_agent_tool",
@@ -476,13 +476,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:687"
"skill:skills/paperclip/SKILL.md:689"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:update:723",
"id": "skill:skills/paperclip/SKILL.md:update:725",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:723",
"sourceAnchor": "skills/paperclip/SKILL.md:725",
"title": "Update",
"expectedSemantics": "Skill guidance headed “Update”.",
"primaryDisposition": "optional_agent_tool",
@@ -491,13 +491,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:723"
"skill:skills/paperclip/SKILL.md:725"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:task-documents-and-deliverables:733",
"id": "skill:skills/paperclip/SKILL.md:task-documents-and-deliverables:735",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:733",
"sourceAnchor": "skills/paperclip/SKILL.md:735",
"title": "Task Documents and Deliverables",
"expectedSemantics": "Skill guidance headed “Task Documents and Deliverables”.",
"primaryDisposition": "always_agent_tool",
@@ -506,13 +506,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:733"
"skill:skills/paperclip/SKILL.md:735"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:planning-required-when-planning-requested:747",
"id": "skill:skills/paperclip/SKILL.md:planning-required-when-planning-requested:749",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:747",
"sourceAnchor": "skills/paperclip/SKILL.md:749",
"title": "Planning (Required when planning requested)",
"expectedSemantics": "Skill guidance headed “Planning (Required when planning requested)”.",
"primaryDisposition": "optional_agent_tool",
@@ -521,13 +521,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:747"
"skill:skills/paperclip/SKILL.md:749"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:key-endpoints-hot-routes:778",
"id": "skill:skills/paperclip/SKILL.md:key-endpoints-hot-routes:780",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:778",
"sourceAnchor": "skills/paperclip/SKILL.md:780",
"title": "Key Endpoints (Hot Routes)",
"expectedSemantics": "Skill guidance headed “Key Endpoints (Hot Routes)”.",
"primaryDisposition": "optional_agent_tool",
@@ -536,13 +536,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:778"
"skill:skills/paperclip/SKILL.md:780"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:searching-issues:808",
"id": "skill:skills/paperclip/SKILL.md:searching-issues:810",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:808",
"sourceAnchor": "skills/paperclip/SKILL.md:810",
"title": "Searching Issues",
"expectedSemantics": "Skill guidance headed “Searching Issues”.",
"primaryDisposition": "optional_agent_tool",
@@ -551,13 +551,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:808"
"skill:skills/paperclip/SKILL.md:810"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:full-reference:818",
"id": "skill:skills/paperclip/SKILL.md:full-reference:820",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:818",
"sourceAnchor": "skills/paperclip/SKILL.md:820",
"title": "Full Reference",
"expectedSemantics": "Skill guidance headed “Full Reference”.",
"primaryDisposition": "optional_agent_tool",
@@ -566,13 +566,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:818"
"skill:skills/paperclip/SKILL.md:820"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:conversational-confirmation-answers:822",
"id": "skill:skills/paperclip/SKILL.md:conversational-confirmation-answers:824",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:822",
"sourceAnchor": "skills/paperclip/SKILL.md:824",
"title": "Conversational confirmation answers",
"expectedSemantics": "Skill guidance headed “Conversational confirmation answers”.",
"primaryDisposition": "always_agent_tool",
@@ -581,13 +581,13 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:822"
"skill:skills/paperclip/SKILL.md:824"
]
},
{
"id": "skill:skills/paperclip/SKILL.md:incidental-feedback:839",
"id": "skill:skills/paperclip/SKILL.md:incidental-feedback:841",
"sourceKind": "skill_heading",
"sourceAnchor": "skills/paperclip/SKILL.md:839",
"sourceAnchor": "skills/paperclip/SKILL.md:841",
"title": "Incidental feedback",
"expectedSemantics": "Skill guidance headed “Incidental feedback”.",
"primaryDisposition": "optional_agent_tool",
@@ -596,7 +596,7 @@
"control_plane_invariant"
],
"evidenceIds": [
"skill:skills/paperclip/SKILL.md:839"
"skill:skills/paperclip/SKILL.md:841"
]
},
{
@@ -201,7 +201,35 @@ const descriptors: readonly PaperclipSemanticActionDescriptor[] = [
description: "Append a durable progress comment to the active task.",
effect: "write",
inputSchema: object(
{ ...idempotency, body: text("Multiline progress update.") },
{
...idempotency,
body: text("Multiline progress update. Fenced ```json schema=<name>@<version> blocks in body are automatically extracted and validated against company and built-in JSON schemas."),
kvLabels: {
type: "array",
description: "Optional key-value metadata attached to the progress comment (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
maxItems: 64,
items: object(
{
key: { type: "string", pattern: "^[a-z0-9][a-z0-9_.-]{0,63}$", minLength: 1, maxLength: 64 },
value: { type: "string", minLength: 1, maxLength: 256 },
},
["key", "value"],
),
},
schemaBlocks: {
type: "array",
description: "Optional structured <name>@<version> blocks validated against company or built-in JSON schemas.",
maxItems: 64,
items: object(
{
schema: { type: "string", pattern: "^[a-z0-9][a-z0-9_-]{0,63}$", minLength: 1, maxLength: 64, description: "Schema name without @version (for example 'test-report')." },
version: { type: "integer", minimum: 1, description: "Positive integer schema version (for example 1)." },
dataJson: { type: "string", minLength: 2, maxLength: 65_536, description: "JSON-encoded object matching the schema." },
},
["schema", "version", "dataJson"],
),
},
},
["idempotencyKey", "body"],
),
outputSchema: operationReceipt,
@@ -423,6 +451,23 @@ const descriptors: readonly PaperclipSemanticActionDescriptor[] = [
uniqueItems: true,
},
limit: { type: "integer", minimum: 1, maximum: 200, default: 50 },
cursor: {
type: "string",
pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
description: "The nextCursor from the previous page. Keep query, statuses, labelFilter, and channel unchanged. Omit for the first page.",
},
labelFilter: {
type: "string",
minLength: 1,
maxLength: 256,
description: "Optional task label filter: 'key=value', 'key=v1|v2', or 'key' (exists on kvLabels or tag labels).",
},
channel: {
type: "string",
minLength: 1,
maxLength: 140,
description: "Optional channel path (for example 'build/auth'), subtree prefix ('build/*' or 'build/'), or channel UUID.",
},
}),
}),
descriptor({
@@ -585,6 +630,30 @@ const descriptors: readonly PaperclipSemanticActionDescriptor[] = [
status: { enum: ["backlog", "todo"], description: "Initial status. Use backlog to save work without execution. Defaults to todo (blocked when dependencies are unresolved)." },
priority: { enum: ["critical", "high", "medium", "low"] },
blockedByTaskIds: stringArray("Initial blocker task identifiers."),
kvLabels: {
type: "array",
description: "Optional key-value metadata attached to the created task (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
maxItems: 64,
items: object(
{
key: { type: "string", pattern: "^[a-z0-9][a-z0-9_.-]{0,63}$", minLength: 1, maxLength: 64 },
value: { type: "string", minLength: 1, maxLength: 256 },
},
["key", "value"],
),
},
resultSchemaRef: {
type: ["string", "null"],
pattern: "^[a-z0-9][a-z0-9_-]{0,63}@[1-9][0-9]*$",
maxLength: 80,
description: "Optional required completion schema reference (<name>@<version>, for example 'test-report@1').",
},
channel: {
type: ["string", "null"],
minLength: 1,
maxLength: 140,
description: "Optional channel path (for example 'build/auth') or channel UUID.",
},
},
["idempotencyKey", "title"],
),
@@ -167,6 +167,50 @@ export const createTaskAction = {
],
"maxLength": 200000,
"description": "Relevant markdown plan saved on the new task before execution starts."
},
"kvLabels": {
"type": "array",
"description": "Optional key-value metadata attached to the created task (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"minLength": 1,
"maxLength": 64
},
"value": {
"type": "string",
"minLength": 1,
"maxLength": 256
}
},
"required": [
"key",
"value"
],
"additionalProperties": false
}
},
"resultSchemaRef": {
"type": [
"string",
"null"
],
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}@[1-9][0-9]*$",
"maxLength": 80,
"description": "Optional required completion schema reference (<name>@<version>, for example 'test-report@1')."
},
"channel": {
"type": [
"string",
"null"
],
"minLength": 1,
"maxLength": 140,
"description": "Optional channel path (for example 'build/auth') or channel UUID."
}
},
"required": [
@@ -235,6 +279,24 @@ export const createTaskAction = {
"type": ["string", "null"],
"minLength": 1
},
"channelId": {
"type": ["string", "null"],
"minLength": 1
},
"channelPath": {
"type": ["string", "null"],
"minLength": 1
},
"kvLabels": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"resultSchemaRef": {
"type": ["string", "null"],
"minLength": 1
},
"status": {
"type": "string",
"minLength": 1
@@ -304,6 +366,47 @@ export const createTaskAction = {
"items": {
"type": "string"
}
},
"kvLabels": {
"type": "array",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"minLength": 1,
"maxLength": 64
},
"value": {
"type": "string",
"minLength": 1,
"maxLength": 256
}
},
"required": [
"key",
"value"
],
"additionalProperties": false
}
},
"resultSchemaRef": {
"type": [
"string",
"null"
],
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}@[1-9][0-9]*$",
"maxLength": 80
},
"channel": {
"type": [
"string",
"null"
],
"minLength": 1,
"maxLength": 140
}
},
"required": [
@@ -90,9 +90,69 @@ export const reportProgressAction = {
},
"body": {
"type": "string",
"description": "Multiline progress update.",
"description": "Multiline progress update. Fenced ```json schema=<name>@<version> blocks in body are automatically extracted and validated against company and built-in JSON schemas.",
"minLength": 1,
"maxLength": 20000
},
"kvLabels": {
"type": "array",
"description": "Optional key-value metadata attached to the progress comment (max 64 entries). Keys must match ^[a-z0-9][a-z0-9_.-]{0,63}$ and cannot start with 'paperclip.'.",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"minLength": 1,
"maxLength": 64
},
"value": {
"type": "string",
"minLength": 1,
"maxLength": 256
}
},
"required": [
"key",
"value"
],
"additionalProperties": false
}
},
"schemaBlocks": {
"type": "array",
"description": "Optional structured <name>@<version> blocks validated against company or built-in JSON schemas.",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"schema": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}$",
"minLength": 1,
"maxLength": 64,
"description": "Schema name without @version (for example 'test-report')."
},
"version": {
"type": "integer",
"minimum": 1,
"description": "Positive integer schema version (for example 1)."
},
"dataJson": {
"type": "string",
"minLength": 2,
"maxLength": 65536,
"description": "JSON-encoded object matching the schema."
}
},
"required": [
"schema",
"version",
"dataJson"
],
"additionalProperties": false
}
}
},
"required": [
@@ -180,6 +240,61 @@ export const reportProgressAction = {
"body": {
"type": "string",
"minLength": 1
},
"kvLabels": {
"type": "array",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
"minLength": 1,
"maxLength": 64
},
"value": {
"type": "string",
"minLength": 1,
"maxLength": 256
}
},
"required": [
"key",
"value"
],
"additionalProperties": false
}
},
"schemaBlocks": {
"type": "array",
"maxItems": 64,
"items": {
"type": "object",
"properties": {
"schema": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}$",
"minLength": 1,
"maxLength": 64
},
"version": {
"type": "integer",
"minimum": 1
},
"dataJson": {
"type": "string",
"minLength": 2,
"maxLength": 65536
}
},
"required": [
"schema",
"version",
"dataJson"
],
"additionalProperties": false
}
}
},
"required": [
@@ -95,7 +95,19 @@ export const searchTasksAction = {
"cursor": {
"type": "string",
"format": "uuid",
"description": "The nextCursor from the previous page. Keep query and statuses unchanged. Omit for the first page."
"description": "The nextCursor from the previous page. Keep query, statuses, labelFilter, and channel unchanged. Omit for the first page."
},
"labelFilter": {
"type": "string",
"minLength": 1,
"maxLength": 256,
"description": "Optional task label filter: 'key=value', 'key=v1|v2', or 'key' (exists on kvLabels or tag labels)."
},
"channel": {
"type": "string",
"minLength": 1,
"maxLength": 140,
"description": "Optional channel path (for example 'build/auth'), subtree prefix ('build/*' or 'build/'), or channel UUID."
}
},
"required": [],
@@ -130,6 +142,16 @@ export const searchTasksAction = {
},
"status": {
"type": "string"
},
"labelFilter": {
"type": "string",
"minLength": 1,
"maxLength": 256
},
"channel": {
"type": "string",
"minLength": 1,
"maxLength": 140
}
},
"required": [],
@@ -20,6 +20,7 @@ import {
import { nativeTaskSessionPublicationHandled } from "../native-runtime/native-task-session-publication.js";
import { boundOriginalMessage, describeRefusedExactResume, interruptedExactResumeCause } from "../native-runtime/native-exact-resume-failure.js";
import { settledResponsePublicationSql } from "../native-runtime/native-response-publication-receipt.js";
import { persistValidFencedSchemaBlocksOnComment } from "../native-runtime/native-task-metadata.js";
import { notifyChatRunMilestones } from "../chat-run-milestone-notifications.js";
import { measureRunPhase } from "../execution-preparation-timing.js";
import { PROJECT_ACCESS_DENIED, ProjectAccessDeniedError } from "../project-access-denial.js";
@@ -981,6 +982,12 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
{ agentId: agent.id, runId: livenessRun.id },
{ authorizationReason: presentationAuthorizationReason, completionReply: true },
));
await persistValidFencedSchemaBlocksOnComment(
db,
livenessRun.companyId,
comment.id,
resolved.text!,
);
presentationDecision = {
...presentationDecision,
commentId: comment.id,
@@ -2,7 +2,7 @@ import { createServer } from "node:http";
import { createHash, randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, approvals, companies, createDb, documentRevisions, executionWorkspaces, executionWorkspaceRepositories, heartbeatRuns, issueExecutionDecisions, issues, issueApprovals, issueThreadInteractions, issueTreeHolds, issueDocuments, issueWorkProducts } from "@paperclipai/db";
import { activityLog, agents, approvals, companies, companySchemas, createDb, documentRevisions, executionWorkspaces, executionWorkspaceRepositories, heartbeatRunEvents, heartbeatRuns, issueComments, issueExecutionDecisions, issues, issueApprovals, issueThreadInteractions, issueTreeHolds, issueDocuments, issueWorkProducts } from "@paperclipai/db";
import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js";
import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js";
import { documentService } from "../documents.js";
@@ -12,7 +12,9 @@ import { nativePullRequestCompletionReferences, verifyNativePullRequestCompletio
import { workProductService } from "../work-products.js";
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
import { executionStageApprovedByRun } from "./native-run-finalizer.js";
import { persistValidFencedSchemaBlocksOnComment } from "./native-task-metadata.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
import { buildLowTrustSourceTrust, buildPromotedSourceTrust } from "../source-trust.js";
const done: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Document saved.",
@@ -641,4 +643,272 @@ describe("native final-response feedback", () => {
expect(feedback).toBe("Blocker report accepted. Explain why work cannot continue, name the blocker owner and give the unblock action in your final response; do not describe the task as completed.");
expect(feedback).not.toContain("Describe the completed work");
});
it("gates completion on resultSchemaRef across summary, report_progress, description, agentMessage, and persisted final comments", async () => {
const value = await fixture();
await db.insert(companySchemas).values({
companyId: value.companyId,
name: "deploy-summary",
version: 1,
description: "Deployment outcome",
jsonSchema: {
type: "object",
required: ["environment", "healthy"],
additionalProperties: false,
properties: {
environment: { type: "string", minLength: 1 },
healthy: { type: "boolean" },
},
},
});
await db
.update(issues)
.set({ resultSchemaRef: "deploy-summary@1" })
.where(eq(issues.id, value.issueId));
// 1. Missing matching block fails with actionable instructions naming deploy-summary@1
await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(
/deploy-summary@1[\s\S]*report_progress/,
);
// 2. Quarantined low-trust comment, prior-run comment, or requester example in description
// cannot satisfy resultSchemaRef even after updatedAt advances on checkout
await db
.update(issues)
.set({
description:
'Format example:\n```json schema=deploy-summary@1\n{"environment":"staging","healthy":true}\n```',
updatedAt: new Date(Date.now() + 60_000),
})
.where(eq(issues.id, value.issueId));
await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(
/deploy-summary@1[\s\S]*report_progress/,
);
// A no-op PATCH that logs top-level details.description without details.changes.description is still rejected
await db.insert(activityLog).values({
companyId: value.companyId,
actorType: "agent",
actorId: value.agentId,
agentId: value.agentId,
runId: value.runId,
action: "issue.updated",
entityType: "issue",
entityId: value.issueId,
details: { description: "unchanged prompt", changes: {} },
});
await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(
/deploy-summary@1[\s\S]*report_progress/,
);
// When this run records a real details.changes.description edit (even alongside >20 other updates), it counts
await db.insert(activityLog).values([
{
companyId: value.companyId,
actorType: "agent",
actorId: value.agentId,
agentId: value.agentId,
runId: value.runId,
action: "issue.updated",
entityType: "issue",
entityId: value.issueId,
details: {
description: "updated by run",
changes: { description: { from: null, to: "updated by run", updated: true } },
},
},
...Array.from({ length: 25 }, (_, idx) => ({
companyId: value.companyId,
actorType: "agent" as const,
actorId: value.agentId,
agentId: value.agentId,
runId: value.runId,
action: "issue.updated",
entityType: "issue",
entityId: value.issueId,
details: { priority: idx % 2 === 0 ? "high" : "medium", changes: { priority: { from: "low", to: "high" } } },
})),
]);
await expect(nativeCompletionFeedback(db, value.runId, done)).resolves.toContain(
"Completion report accepted",
);
await db.delete(activityLog).where(eq(activityLog.entityId, value.issueId));
await db.update(issues).set({ description: null }).where(eq(issues.id, value.issueId));
const priorRunId = randomUUID();
await db.insert(heartbeatRuns).values({
id: priorRunId,
companyId: value.companyId,
agentId: value.agentId,
nativeIssueId: value.issueId,
status: "succeeded",
runtimeMode: "native",
});
const [priorRunComment] = await db
.insert(issueComments)
.values({
companyId: value.companyId,
issueId: value.issueId,
authorAgentId: value.agentId,
createdByRunId: priorRunId,
body: '```json schema=deploy-summary@1\n{"environment":"staging","healthy":true}\n```',
})
.returning();
await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(
/produced by this run/,
);
await db.delete(issueComments).where(eq(issueComments.id, priorRunComment.id));
const [quarantinedComment] = await db
.insert(issueComments)
.values({
companyId: value.companyId,
issueId: value.issueId,
body: '```json schema=deploy-summary@1\n{"environment":"staging","healthy":true}\n```',
schemaBlocks: [
{
schema: "deploy-summary",
version: 1,
data: { environment: "staging", healthy: true },
},
],
sourceTrust: buildLowTrustSourceTrust({ issueId: value.issueId }),
})
.returning();
await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(
/produced by this run/,
);
await db
.update(issueComments)
.set({
sourceTrust: buildPromotedSourceTrust({
sourceIssueId: value.issueId,
sourceArtifactKind: "comment",
sourceArtifactId: quarantinedComment.id,
promotedByActorType: "user",
promotedByActorId: "operator",
}),
})
.where(eq(issueComments.id, quarantinedComment.id));
await expect(nativeCompletionFeedback(db, value.runId, done)).resolves.toContain(
"Completion report accepted",
);
await db.delete(issueComments).where(eq(issueComments.id, quarantinedComment.id));
// 2b. Candidate block with schema validation error names the validation failure
await expect(
nativeCompletionFeedback(db, value.runId, {
...done,
summary: '```json schema=deploy-summary@1\n{"environment":"staging","healthy":"yes"}\n```',
}),
).rejects.toThrow(/deploy-summary@1[\s\S]*healthy/);
// 3. Valid fenced block in result.summary passes pre-comment completion check
await expect(
nativeCompletionFeedback(db, value.runId, {
...done,
summary: 'Deployed cleanly.\n```json schema=deploy-summary@1\n{"environment":"staging","healthy":true}\n```',
}),
).resolves.toContain("Completion report accepted");
// 4. Persisting final reply comment extracts valid fenced schema block onto issueComments.schemaBlocks
// so authoritativeDone: true under lockSources: true sees it on issue_comments even with plain result.summary
const [replyComment] = await db
.insert(issueComments)
.values({
companyId: value.companyId,
issueId: value.issueId,
authorAgentId: value.agentId,
createdByRunId: value.runId,
body: [
"Deployment finished.",
"```json",
"{not-valid-json-ignored-without-failing}",
"```",
"```json schema=deploy-summary@1",
'{"environment":"production","healthy":true}',
"```",
].join("\n"),
})
.returning();
const schemaCache = new Map<string, Record<string, unknown> | null>();
const persisted = await persistValidFencedSchemaBlocksOnComment(
db,
value.companyId,
replyComment.id,
replyComment.body,
{ schemaCache },
);
expect(persisted).toEqual([
{
schema: "deploy-summary",
version: 1,
data: { environment: "production", healthy: true },
},
]);
expect(schemaCache.has("deploy-summary@1")).toBe(true);
// Second pass with unchanged existingSchemaBlocks reuses cache and performs zero DB writes
const noWriteDb = new Proxy(db, {
get(target, prop, receiver) {
if (prop === "update" || prop === "select") {
throw new Error(`unexpected ${String(prop)} query when schemaBlocks are unchanged`);
}
return Reflect.get(target, prop, receiver);
},
});
await expect(
persistValidFencedSchemaBlocksOnComment(
noWriteDb,
value.companyId,
replyComment.id,
replyComment.body,
{ existingSchemaBlocks: persisted, schemaCache },
),
).resolves.toEqual(persisted);
await expect(
db.transaction((tx) =>
validateNativeDeliverableEvidence(
tx as unknown as typeof db,
{
companyId: value.companyId,
issueId: value.issueId,
runId: value.runId,
objective: "Deploy service",
semanticToolReceipts: {},
lockSources: true,
authoritativeDone: true,
},
done,
),
),
).resolves.toBeUndefined();
// 5. Built-in test-report@1 satisfied via completed agentMessage run event before comment insertion
const eventValue = await fixture(value.companyId);
await db
.update(issues)
.set({ resultSchemaRef: "test-report@1" })
.where(eq(issues.id, eventValue.issueId));
await expect(nativeCompletionFeedback(db, eventValue.runId, done)).rejects.toThrow(
/test-report@1/,
);
await db.insert(heartbeatRunEvents).values({
companyId: eventValue.companyId,
runId: eventValue.runId,
agentId: eventValue.agentId,
seq: 1,
eventType: "item.completed",
stream: "stdout",
level: "info",
payload: {
prpEvent: {
payload: {
kind: "agentMessage",
text: 'Tests passed:\n```json schema=test-report@1\n{"passed":true,"total":8,"failed":0}\n```',
},
},
},
});
await expect(nativeCompletionFeedback(db, eventValue.runId, done)).resolves.toContain(
"Completion report accepted",
);
});
});
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
import { assets, companies, completionContracts, documents, documentRevisions, heartbeatRuns, issueDocuments, issueAttachments, issues, issueThreadInteractions, issueWorkProducts, mcpAttachmentUploads, dotRunnerAssignments, type Db } from "@paperclipai/db";
import { projectHumanInteractionResponse } from "../execution-continuation.js";
import { isCommittedToolReceiptResult } from "../heartbeat-run-summary.js";
import { assertNativeResultSchemaSatisfied } from "./native-task-metadata.js";
export class NativeDeliverableEvidenceError extends Error {}
@@ -440,4 +441,10 @@ export async function validateNativeDeliverableEvidence(
});
if (!accessibleProduct) throw new NativeDeliverableEvidenceError("The requested file has no accessible delivery evidence. Use register_deliverable and cite deliverable:<attachmentId>, or cite an accessible work product registered by this run for this task. Empty evidence, prior-run output, and a verification result cannot substitute for the requested file. Continue publishing or report a concrete blocker; no human completion approval was created.");
}
await assertNativeResultSchemaSatisfied(
db,
binding,
result,
(message) => new NativeDeliverableEvidenceError(message),
);
}
@@ -0,0 +1,337 @@
import { and, desc, eq, isNull, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
heartbeatRunEvents,
heartbeatRuns,
issueComments,
issues,
} from "@paperclipai/db";
import {
parseSchemaRef,
validateAgainstJsonSchema,
type ParsedSchemaRef,
type SchemaBlock,
} from "@paperclipai/shared";
import { getCompanySchema } from "../headless-schemas.js";
import {
isLowTrustQuarantined,
resolveActorSourceTrustForIssue,
} from "../source-trust.js";
import {
isPlainRecord,
MAX_SCHEMA_FENCE_BODY_CHARS,
scanFencedSchemaBlocks,
} from "./native-schema-fences.js";
type CandidatePayloadOutcome =
| { kind: "valid" }
| { kind: "invalid"; errors: string[] };
function evaluateStructuredBlocksForRef(
blocks: SchemaBlock[] | null | undefined,
parsedRef: ParsedSchemaRef,
jsonSchema: Record<string, unknown>,
): CandidatePayloadOutcome | null {
if (!Array.isArray(blocks) || blocks.length === 0) return null;
let firstInvalid: string[] | null = null;
for (const block of blocks) {
if (
!block ||
block.schema !== parsedRef.name ||
block.version !== parsedRef.version
) {
continue;
}
const validation = validateAgainstJsonSchema(jsonSchema, block.data);
if (validation.valid) return { kind: "valid" };
firstInvalid ??= validation.errors;
}
return firstInvalid ? { kind: "invalid", errors: firstInvalid } : null;
}
function evaluateFencedMarkdownForRef(
markdown: string | null | undefined,
parsedRef: ParsedSchemaRef,
jsonSchema: Record<string, unknown>,
): CandidatePayloadOutcome | null {
if (typeof markdown !== "string" || markdown.length === 0) return null;
const scanned = scanFencedSchemaBlocks(markdown);
let firstInvalid: string[] | null = null;
for (const fence of scanned) {
let fenceRef: ParsedSchemaRef;
try {
fenceRef = parseSchemaRef(fence.rawSchemaRef);
} catch {
continue;
}
if (fenceRef.ref !== parsedRef.ref) continue;
if (fence.oversized) {
firstInvalid ??= [
`fenced block exceeds maximum size of ${MAX_SCHEMA_FENCE_BODY_CHARS} characters`,
];
continue;
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(fence.rawJson);
} catch (err) {
firstInvalid ??= [
`invalid JSON: ${err instanceof Error ? err.message : "parse error"}`,
];
continue;
}
if (!isPlainRecord(parsedJson)) {
firstInvalid ??= ["expected a JSON object payload"];
continue;
}
const validation = validateAgainstJsonSchema(jsonSchema, parsedJson);
if (validation.valid) return { kind: "valid" };
firstInvalid ??= validation.errors;
}
return firstInvalid ? { kind: "invalid", errors: firstInvalid } : null;
}
export async function assertNativeResultSchemaSatisfied<E extends Error>(
db: Db,
binding: {
companyId: string;
issueId: string;
runId: string;
lockSources?: boolean;
},
result: unknown,
createError: (message: string) => E,
): Promise<void> {
const [issueRow] = await db
.select({
resultSchemaRef: issues.resultSchemaRef,
schemaBlocks: issues.schemaBlocks,
description: issues.description,
conversationAgentId: issues.conversationAgentId,
projectId: issues.projectId,
executionPolicy: issues.executionPolicy,
sourceTrust: issues.sourceTrust,
})
.from(issues)
.where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId)))
.limit(1);
if (!issueRow?.resultSchemaRef || issueRow.conversationAgentId) return;
let parsedRef: ParsedSchemaRef;
try {
parsedRef = parseSchemaRef(issueRow.resultSchemaRef);
} catch {
throw createError(
`Task specifies an invalid resultSchemaRef '${issueRow.resultSchemaRef}'. Update resultSchemaRef to <name>@<version> before completing.`,
);
}
let schemaJson: Record<string, unknown>;
try {
const schemaView = await getCompanySchema(db, binding.companyId, parsedRef.ref);
schemaJson = schemaView.jsonSchema;
} catch {
throw createError(
`Task requires result schema '${parsedRef.ref}', which is not registered in this company. Register '${parsedRef.ref}' before completing this task.`,
);
}
const [runRow] = await db
.select({
agentId: heartbeatRuns.agentId,
contextSnapshot: heartbeatRuns.contextSnapshot,
})
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId)))
.limit(1);
const continuation = isPlainRecord(runRow?.contextSnapshot)
? runRow.contextSnapshot.executionContinuation
: null;
const continuationTrigger = isPlainRecord(continuation) ? continuation.trigger : null;
const continuationSourceRunId =
isPlainRecord(continuationTrigger) && typeof continuationTrigger.sourceRunId === "string"
? continuationTrigger.sourceRunId
: null;
const readerSourceTrust = runRow?.agentId
? await resolveActorSourceTrustForIssue({
db,
issue: {
id: binding.issueId,
companyId: binding.companyId,
projectId: issueRow.projectId,
executionPolicy: issueRow.executionPolicy,
},
actor: {
actorType: "agent",
actorId: runRow.agentId,
agentId: runRow.agentId,
runId: binding.runId,
},
})
: null;
const hideQuarantined = !isLowTrustQuarantined(readerSourceTrust);
const invalidHolder: { errors: string[] | null; untrustedOrPriorSkipped: boolean } = {
errors: null,
untrustedOrPriorSkipped: false,
};
const recordOutcome = (outcome: CandidatePayloadOutcome | null): boolean => {
if (!outcome) return false;
if (outcome.kind === "valid") return true;
invalidHolder.errors ??= outcome.errors;
return false;
};
// 1. Run's final completion summary text (when checked before final comment insertion).
const resultSummary =
isPlainRecord(result) && typeof result.summary === "string"
? result.summary
: null;
if (recordOutcome(evaluateFencedMarkdownForRef(resultSummary, parsedRef, schemaJson))) {
return;
}
// 2. Non-deleted comments produced by this run (or bound continuation run / promoted trust).
const commentQuery = db
.select({
body: issueComments.body,
schemaBlocks: issueComments.schemaBlocks,
sourceTrust: issueComments.sourceTrust,
authorAgentId: issueComments.authorAgentId,
createdByRunId: issueComments.createdByRunId,
})
.from(issueComments)
.where(
and(
eq(issueComments.companyId, binding.companyId),
eq(issueComments.issueId, binding.issueId),
isNull(issueComments.deletedAt),
),
)
.orderBy(desc(issueComments.createdAt), desc(issueComments.id));
const comments = await (binding.lockSources
? commentQuery.for("share", { of: [issueComments], noWait: true })
: commentQuery);
for (const comment of comments) {
const producedByBoundContinuation =
Boolean(continuationSourceRunId) &&
comment.createdByRunId === continuationSourceRunId &&
Boolean(runRow?.agentId) &&
comment.authorAgentId === runRow?.agentId;
const ownedOrPromoted =
comment.createdByRunId === binding.runId ||
producedByBoundContinuation ||
comment.sourceTrust?.disposition === "promoted";
if ((hideQuarantined && isLowTrustQuarantined(comment.sourceTrust)) || !ownedOrPromoted) {
if (
evaluateStructuredBlocksForRef(comment.schemaBlocks, parsedRef, schemaJson)?.kind === "valid" ||
evaluateFencedMarkdownForRef(comment.body, parsedRef, schemaJson)?.kind === "valid"
) {
invalidHolder.untrustedOrPriorSkipped = true;
}
continue;
}
if (
recordOutcome(
evaluateStructuredBlocksForRef(comment.schemaBlocks, parsedRef, schemaJson),
)
) {
return;
}
if (recordOutcome(evaluateFencedMarkdownForRef(comment.body, parsedRef, schemaJson))) {
return;
}
}
// 3. Task-level schemaBlocks or description ONLY when explicitly written by this run (or promoted),
// never from requester-seeded prompt examples or pre-existing task fields.
const [runFieldEdits] = await db
.select({
updatedSchemaBlocks: sql<boolean>`coalesce(bool_or(jsonb_typeof(${activityLog.details}) = 'object' and jsonb_typeof(${activityLog.details}->'changes') = 'object' and (${activityLog.details}->'changes' ? 'schemaBlocks')), false)`,
updatedDescription: sql<boolean>`coalesce(bool_or(jsonb_typeof(${activityLog.details}) = 'object' and jsonb_typeof(${activityLog.details}->'changes') = 'object' and (${activityLog.details}->'changes' ? 'description')), false)`,
})
.from(activityLog)
.where(
and(
eq(activityLog.companyId, binding.companyId),
eq(activityLog.entityType, "issue"),
eq(activityLog.entityId, binding.issueId),
eq(activityLog.action, "issue.updated"),
eq(activityLog.runId, binding.runId),
),
);
const runUpdatedSchemaBlocks = Boolean(runFieldEdits?.updatedSchemaBlocks);
const runUpdatedDescription = Boolean(runFieldEdits?.updatedDescription);
const issuePromoted = issueRow.sourceTrust?.disposition === "promoted";
if (hideQuarantined && isLowTrustQuarantined(issueRow.sourceTrust)) {
if (
evaluateStructuredBlocksForRef(issueRow.schemaBlocks, parsedRef, schemaJson)?.kind === "valid" ||
evaluateFencedMarkdownForRef(issueRow.description, parsedRef, schemaJson)?.kind === "valid"
) {
invalidHolder.untrustedOrPriorSkipped = true;
}
} else {
if (
(runUpdatedSchemaBlocks || issuePromoted) &&
recordOutcome(
evaluateStructuredBlocksForRef(issueRow.schemaBlocks, parsedRef, schemaJson),
)
) {
return;
}
if (
(runUpdatedDescription || issuePromoted) &&
recordOutcome(
evaluateFencedMarkdownForRef(issueRow.description, parsedRef, schemaJson),
)
) {
return;
}
}
// 4. Completed final assistant messages on this run (when evaluated before finalizer persists reply comment).
const eventQuery = db
.select({ payload: heartbeatRunEvents.payload })
.from(heartbeatRunEvents)
.where(
and(
eq(heartbeatRunEvents.companyId, binding.companyId),
eq(heartbeatRunEvents.runId, binding.runId),
eq(heartbeatRunEvents.eventType, "item.completed"),
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,payload,kind}' = 'agentMessage'`,
),
)
.orderBy(desc(heartbeatRunEvents.seq))
.limit(50);
const messageEvents = await (binding.lockSources
? eventQuery.for("share", { of: [heartbeatRunEvents], noWait: true })
: eventQuery);
for (const row of messageEvents) {
const payload = isPlainRecord(row.payload) ? row.payload : null;
const prpEvent = payload && isPlainRecord(payload.prpEvent) ? payload.prpEvent : null;
const inner = prpEvent && isPlainRecord(prpEvent.payload) ? prpEvent.payload : null;
const text = inner && typeof inner.text === "string" ? inner.text : null;
if (recordOutcome(evaluateFencedMarkdownForRef(text, parsedRef, schemaJson))) {
return;
}
}
if (invalidHolder.errors) {
throw createError(
`Task requires a valid structured result matching schema '${parsedRef.ref}', but validation failed: ${invalidHolder.errors.join("; ")}. Post a valid \`\`\`json schema=${parsedRef.ref} block via report_progress or include it in your completion reply before finishing.`,
);
}
if (invalidHolder.untrustedOrPriorSkipped) {
throw createError(
`Task requires a valid structured result matching schema '${parsedRef.ref}' produced by this run (untrusted, quarantined, or prior-run blocks cannot satisfy completion unless promoted). Post a valid \`\`\`json schema=${parsedRef.ref} block via report_progress or include it in your completion reply before finishing.`,
);
}
throw createError(
`Task requires a valid structured result matching schema '${parsedRef.ref}', but no matching block was found. Post a valid \`\`\`json schema=${parsedRef.ref} block via report_progress or include it in your completion reply before finishing.`,
);
}
@@ -16,6 +16,7 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre
import { notifyInstructionCollection } from "../instruction-collection-notifications.js";
import { readRequiredQualityReview } from "../required-quality-review.js";
import { NativeDeliverableEvidenceError, validateNativeDeliverableEvidence } from "./native-deliverable-feedback.js";
import { persistValidFencedSchemaBlocksOnComment } from "./native-task-metadata.js";
import { OWN_QUESTION_UNANSWERED_REASON, pendingOwnQuestionId, reportsOnlyProviderMessage } from "./own-question-wait.js";
import { conversationTurnPresentsAnswer, pendingNativeGovernance } from "./native-governance.js";
import { notifyChatRunMilestones } from "../chat-run-milestone-notifications.js";
@@ -903,7 +904,7 @@ async function materializeNativeReviewResponse(db: Db, runId: string, dbOrTx: Db
}))
)
return null;
await issueService(db).addComment(
const comment = await issueService(db).addComment(
run.nativeIssueId,
summary,
{ agentId: run.agentId, runId },
@@ -912,6 +913,7 @@ async function materializeNativeReviewResponse(db: Db, runId: string, dbOrTx: Db
},
dbOrTx,
);
await persistValidFencedSchemaBlocksOnComment(dbOrTx, run.companyId, comment.id, summary);
return run;
}
@@ -1201,6 +1203,7 @@ async function recoverCommittedNativeChatResponseInScope(
await notifyChatRunMilestones(tx, input);
const comment = await issueService(db).addComment(input.issueId, resolved.text,
{ agentId: run.agentId, runId: run.id }, { authorizationReason, completionReply: true }, tx);
await persistValidFencedSchemaBlocksOnComment(tx, input.companyId, comment.id, resolved.text);
await tx.update(heartbeatRuns).set({
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${JSON.stringify({
presentationDecision: { ...resolved.decision, commentId: comment.id,
@@ -1307,6 +1310,9 @@ async function recoverCommittedNativeChatResponseInScope(
existingComment?.body.trim() !== preferredText?.trim(),
});
if (resolved.decision.commentAction === "reuse" && typeof resolved.decision.commentId === "string") {
if (existingComment?.body) {
await persistValidFencedSchemaBlocksOnComment(tx, input.companyId, resolved.decision.commentId, existingComment.body);
}
// The reply is already on the task (for example, the live path wrote
// it but did not record its decision). Record it; never post again.
await tx.update(heartbeatRuns).set({
@@ -1335,6 +1341,7 @@ async function recoverCommittedNativeChatResponseInScope(
const comment = await issueService(db).addComment(input.issueId, resolved.text,
{ agentId: run.agentId, runId: run.id },
{ authorizationReason: replyAuthorization, completionReply: true }, tx);
await persistValidFencedSchemaBlocksOnComment(tx, input.companyId, comment.id, resolved.text);
await tx.update(heartbeatRuns).set({
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${JSON.stringify({
presentationDecision: { ...resolved.decision, commentId: comment.id,
@@ -1384,6 +1391,7 @@ async function recoverCommittedNativeChatResponseInScope(
{ authorizationReason: CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON, completionReply: true },
tx,
);
await persistValidFencedSchemaBlocksOnComment(tx, input.companyId, comment.id, resolved.text);
const presentationDecision = {
...resolved.decision,
commentId: comment.id,
@@ -1924,6 +1932,31 @@ export async function finalizeNativeRun(input: {
reasonCode: OWN_QUESTION_UNANSWERED_REASON, unblockDescriptor: null, effects: [{ kind: "release_checkout" }] };
}
if (proposedDecision.statusAction === "done" || proposedDecision.reasonCode === COMPLETION_REVIEW_STAGE_REASON) {
if (authoritativeIssue.resultSchemaRef) {
const priorRunComments = await input.db
.select({
id: issueComments.id,
body: issueComments.body,
schemaBlocks: issueComments.schemaBlocks,
})
.from(issueComments)
.where(and(
eq(issueComments.companyId, run.companyId),
eq(issueComments.issueId, authoritativeIssue.id),
eq(issueComments.createdByRunId, run.id),
isNull(issueComments.deletedAt),
));
const schemaCache = new Map<string, Record<string, unknown> | null>();
for (const rc of priorRunComments) {
await persistValidFencedSchemaBlocksOnComment(
input.db,
run.companyId,
rc.id,
rc.body,
{ existingSchemaBlocks: rc.schemaBlocks, schemaCache },
);
}
}
const continuation = record(run.contextSnapshot?.executionContinuation);
const objective = typeof continuation.objective === "string" ? continuation.objective
: [authoritativeIssue.title, authoritativeIssue.description].filter(Boolean).join("\n");
@@ -0,0 +1,557 @@
import { and, eq } from "drizzle-orm";
import { issueComments } from "@paperclipai/db";
import {
parseSchemaRef,
validateAgainstJsonSchema,
type ParsedSchemaRef,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest, unprocessable } from "../../errors.js";
import type { DbOrTx } from "../headless-common.js";
import { validateWritableKvLabelsOrThrow } from "../headless-channels.js";
import {
getCompanySchema,
validateSchemaBlocks,
} from "../headless-schemas.js";
export const MAX_SCANNED_SCHEMA_MARKDOWN_CHARS = 512 * 1024;
export const MAX_SCHEMA_FENCE_BODY_CHARS = 64 * 1024;
export const MAX_CANDIDATE_SCHEMA_FENCES = 64;
export const MAX_KV_LABELS_ENTRIES = 64;
export const MAX_SCHEMA_BLOCKS_ENTRIES = 64;
export const MAX_READ_SCHEMA_BLOCKS_PER_ITEM = 16;
export const MAX_READ_SCHEMA_BLOCKS_BYTES = 128 * 1024;
export const MAX_RESPONSE_SCHEMA_BLOCKS_BYTES = 128 * 1024;
export interface SchemaBlocksResponseBudget {
remainingBytes: number;
}
export function createSchemaBlocksResponseBudget(
maxBytes = MAX_RESPONSE_SCHEMA_BLOCKS_BYTES,
): SchemaBlocksResponseBudget {
return { remainingBytes: maxBytes };
}
export interface ScannedFencedSchemaBlock {
rawSchemaRef: string;
rawJson: string;
oversized: boolean;
}
function isHorizontalWhitespace(code: number): boolean {
return code === 32 || code === 9;
}
function stripOptionalQuotes(value: string): string {
if (
value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")))
) {
return value.slice(1, -1);
}
return value;
}
function extractSchemaRefFromFenceInfo(info: string): string | null {
let index = 0;
const len = info.length;
const nextToken = (): string | null => {
while (index < len && isHorizontalWhitespace(info.charCodeAt(index))) {
index += 1;
}
if (index >= len) return null;
const start = index;
while (index < len && !isHorizontalWhitespace(info.charCodeAt(index))) {
index += 1;
}
return info.slice(start, index);
};
const lang = nextToken();
if (!lang || lang.toLowerCase() !== "json") return null;
for (let token = nextToken(); token !== null; token = nextToken()) {
if (token.length > 7 && token.slice(0, 7).toLowerCase() === "schema=") {
const candidate = stripOptionalQuotes(token.slice(7).trim());
return candidate.length > 0 ? candidate : null;
}
}
return null;
}
/**
* Strictly linear O(N) single-pass CommonMark line scanner for
* ```` ```json schema=<name>@<version> ```` fenced blocks.
* Never uses multi-line regular expressions, lazy quantifiers, or backreferences,
* and consumes lines inside any opening fence linearly until a matching closing
* fence or EOF so unclosed fences never rescan quadratically.
*/
export function scanFencedSchemaBlocks(markdown: string): ScannedFencedSchemaBlock[] {
if (!markdown) return [];
const text =
markdown.length > MAX_SCANNED_SCHEMA_MARKDOWN_CHARS
? markdown.slice(0, MAX_SCANNED_SCHEMA_MARKDOWN_CHARS)
: markdown;
const candidates: ScannedFencedSchemaBlock[] = [];
let openFence: {
charCode: number;
fenceLen: number;
rawSchemaRef: string | null;
lines: string[];
bodyChars: number;
oversized: boolean;
} | null = null;
let cursor = 0;
const totalLen = text.length;
while (cursor < totalLen) {
const newlineIdx = text.indexOf("\n", cursor);
const rawLineEnd = newlineIdx === -1 ? totalLen : newlineIdx;
const lineEnd =
rawLineEnd > cursor && text.charCodeAt(rawLineEnd - 1) === 13
? rawLineEnd - 1
: rawLineEnd;
const line = text.slice(cursor, lineEnd);
cursor = newlineIdx === -1 ? totalLen : newlineIdx + 1;
if (openFence !== null) {
let pos = 0;
const lineLen = line.length;
while (pos < lineLen && isHorizontalWhitespace(line.charCodeAt(pos))) {
pos += 1;
}
let closeLen = 0;
while (pos + closeLen < lineLen && line.charCodeAt(pos + closeLen) === openFence.charCode) {
closeLen += 1;
}
if (closeLen >= openFence.fenceLen) {
let trailing = pos + closeLen;
while (trailing < lineLen && isHorizontalWhitespace(line.charCodeAt(trailing))) {
trailing += 1;
}
if (trailing === lineLen) {
if (openFence.rawSchemaRef !== null) {
candidates.push({
rawSchemaRef: openFence.rawSchemaRef,
rawJson: openFence.lines.join("\n"),
oversized: openFence.oversized,
});
}
openFence = null;
continue;
}
}
if (openFence.rawSchemaRef !== null && !openFence.oversized) {
const nextChars =
openFence.bodyChars + (openFence.lines.length > 0 ? 1 : 0) + lineLen;
if (nextChars > MAX_SCHEMA_FENCE_BODY_CHARS) {
openFence.oversized = true;
openFence.lines.length = 0;
} else {
openFence.lines.push(line);
openFence.bodyChars = nextChars;
}
}
continue;
}
let pos = 0;
const lineLen = line.length;
while (pos < lineLen && isHorizontalWhitespace(line.charCodeAt(pos))) {
pos += 1;
}
if (pos >= lineLen) continue;
const charCode = line.charCodeAt(pos);
if (charCode !== 96 && charCode !== 126) continue;
let fenceLen = 0;
while (pos + fenceLen < lineLen && line.charCodeAt(pos + fenceLen) === charCode) {
fenceLen += 1;
}
if (fenceLen < 3) continue;
const info = line.slice(pos + fenceLen);
if (charCode === 96 && info.indexOf("`") !== -1) continue;
const rawSchemaRef =
candidates.length < MAX_CANDIDATE_SCHEMA_FENCES
? extractSchemaRefFromFenceInfo(info)
: null;
openFence = {
charCode,
fenceLen,
rawSchemaRef,
lines: [],
bodyChars: 0,
oversized: false,
};
}
return candidates;
}
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function canonicalValueString(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map(canonicalValueString).join(",")}]`;
}
if (isPlainRecord(value)) {
return `{${Object.keys(value)
.sort()
.filter((key) => value[key] !== undefined)
.map((key) => `${JSON.stringify(key)}:${canonicalValueString(value[key])}`)
.join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
export function deduplicateSchemaBlocks(blocks: SchemaBlock[]): SchemaBlock[] {
const seen = new Set<string>();
const deduped: SchemaBlock[] = [];
for (const block of blocks) {
const key = `${block.schema}@${block.version}:${canonicalValueString(block.data)}`;
if (seen.has(key)) continue;
seen.add(key);
deduped.push(block);
}
return deduped;
}
export interface BoundedSchemaBlocksProjection {
schemaBlocks: SchemaBlock[];
schemaBlocksTruncated?: true;
schemaBlocksOmittedCount?: number;
schemaBlocksFullReadHint?: string;
}
/**
* Caps `schemaBlocks` returned in tool read responses (`get_task_history`,
* `get_task_context`, `search_tasks`) while guaranteeing any single valid block
* up to the 64 KiB write limit fits, and surfaces explicit truncation metadata
* plus a `call_api` recovery hint whenever additional blocks are omitted.
*/
export function projectBoundedSchemaBlocks(
blocks: SchemaBlock[] | null | undefined,
options?: {
maxBlocks?: number;
maxTotalChars?: number;
maxItemBytes?: number;
responseBudget?: SchemaBlocksResponseBudget;
fullReadHint?: string;
},
): BoundedSchemaBlocksProjection {
if (!Array.isArray(blocks) || blocks.length === 0) {
return { schemaBlocks: [] };
}
const maxBlocks = options?.maxBlocks ?? MAX_READ_SCHEMA_BLOCKS_PER_ITEM;
const maxItemBytes =
options?.maxItemBytes ?? options?.maxTotalChars ?? MAX_READ_SCHEMA_BLOCKS_BYTES;
const out: SchemaBlock[] = [];
let usedBytes = 0;
for (const block of blocks) {
if (out.length >= maxBlocks) break;
const serializedBytes = Buffer.byteLength(JSON.stringify(block) ?? "", "utf8");
const exceedsItemCap =
out.length > 0
? usedBytes + serializedBytes > maxItemBytes
: serializedBytes > Math.max(maxItemBytes, MAX_SCHEMA_FENCE_BODY_CHARS * 2);
if (exceedsItemCap) break;
if (options?.responseBudget && serializedBytes > options.responseBudget.remainingBytes) {
break;
}
out.push(block);
usedBytes += serializedBytes;
if (options?.responseBudget) {
options.responseBudget.remainingBytes -= serializedBytes;
}
}
const omittedCount = blocks.length - out.length;
if (omittedCount <= 0) {
return { schemaBlocks: out };
}
return {
schemaBlocks: out,
schemaBlocksTruncated: true,
schemaBlocksOmittedCount: omittedCount,
schemaBlocksFullReadHint:
options?.fullReadHint ??
"Use call_api with GET /api/issues/{id} or GET /api/issues/{id}/comments to read all saved schemaBlocks.",
};
}
export function boundedReadSchemaBlocks(
blocks: SchemaBlock[] | null | undefined,
options?: {
maxBlocks?: number;
maxTotalChars?: number;
maxItemBytes?: number;
responseBudget?: SchemaBlocksResponseBudget;
},
): SchemaBlock[] {
return projectBoundedSchemaBlocks(blocks, options).schemaBlocks;
}
export function normalizeRunnerKvLabelsInput(raw: unknown): Record<string, string> {
if (raw === undefined || raw === null) return {};
if (Array.isArray(raw)) {
if (raw.length > MAX_KV_LABELS_ENTRIES) {
throw badRequest(`kvLabels cannot exceed ${MAX_KV_LABELS_ENTRIES} entries`, {
error: "validation_error",
code: "validation_error",
});
}
const mapped: Record<string, unknown> = Object.create(null);
for (let i = 0; i < raw.length; i += 1) {
const entry = raw[i];
if (!isPlainRecord(entry) || typeof entry.key !== "string" || typeof entry.value !== "string") {
throw badRequest(`kvLabels[${i}] must be an object with string 'key' and 'value'`, {
error: "validation_error",
code: "validation_error",
});
}
if (Object.hasOwn(mapped, entry.key)) {
throw badRequest(`Duplicate kvLabels key '${entry.key}'`, {
error: "validation_error",
code: "validation_error",
});
}
mapped[entry.key] = entry.value;
}
return validateWritableKvLabelsOrThrow({ ...mapped });
}
if (isPlainRecord(raw)) {
if (Object.keys(raw).length > MAX_KV_LABELS_ENTRIES) {
throw badRequest(`kvLabels cannot exceed ${MAX_KV_LABELS_ENTRIES} entries`, {
error: "validation_error",
code: "validation_error",
});
}
return validateWritableKvLabelsOrThrow(raw);
}
throw badRequest("kvLabels must be an array of { key, value } entries or a string map", {
error: "validation_error",
code: "validation_error",
});
}
export async function collectAndValidateProgressSchemaBlocks(
dbOrTx: DbOrTx,
companyId: string,
options: { explicitBlocks?: unknown; body: string },
): Promise<SchemaBlock[]> {
const collected: SchemaBlock[] = [];
if (options.explicitBlocks !== undefined && options.explicitBlocks !== null) {
if (!Array.isArray(options.explicitBlocks)) {
throw unprocessable("schemaBlocks must be an array", {
error: "schema_validation_failed",
code: "schema_validation_failed",
});
}
if (options.explicitBlocks.length > MAX_SCHEMA_BLOCKS_ENTRIES) {
throw unprocessable(`schemaBlocks cannot exceed ${MAX_SCHEMA_BLOCKS_ENTRIES} entries`, {
error: "schema_validation_failed",
code: "schema_validation_failed",
});
}
for (let i = 0; i < options.explicitBlocks.length; i += 1) {
const item = options.explicitBlocks[i];
if (
!isPlainRecord(item) ||
typeof item.schema !== "string" ||
typeof item.version !== "number" ||
!Number.isInteger(item.version) ||
item.version < 1
) {
throw unprocessable(
`schemaBlocks[${i}] requires a schema name string and positive integer version`,
{ error: "schema_validation_failed", code: "schema_validation_failed" },
);
}
let dataObj: Record<string, unknown>;
if (typeof item.dataJson === "string") {
if (item.dataJson.length > MAX_SCHEMA_FENCE_BODY_CHARS) {
throw unprocessable(
`schemaBlocks[${i}].dataJson exceeds maximum size of ${MAX_SCHEMA_FENCE_BODY_CHARS} characters`,
{ error: "schema_validation_failed", code: "schema_validation_failed" },
);
}
let parsed: unknown;
try {
parsed = JSON.parse(item.dataJson);
} catch (err) {
throw unprocessable(
`schemaBlocks[${i}].dataJson is not valid JSON: ${err instanceof Error ? err.message : "parse error"}`,
{ error: "schema_validation_failed", code: "schema_validation_failed" },
);
}
if (!isPlainRecord(parsed)) {
throw unprocessable(`schemaBlocks[${i}].dataJson must encode a JSON object`, {
error: "schema_validation_failed",
code: "schema_validation_failed",
});
}
dataObj = parsed;
} else if (isPlainRecord(item.data)) {
dataObj = item.data;
} else {
throw unprocessable(
`schemaBlocks[${i}] requires dataJson (JSON-encoded object string) or data (object)`,
{ error: "schema_validation_failed", code: "schema_validation_failed" },
);
}
collected.push({ schema: item.schema, version: item.version, data: dataObj });
}
}
const scanned = scanFencedSchemaBlocks(options.body);
for (const fence of scanned) {
let parsedRef: ParsedSchemaRef;
try {
parsedRef = parseSchemaRef(fence.rawSchemaRef);
} catch (err) {
throw unprocessable(
err instanceof Error ? err.message : `Invalid schema ref '${fence.rawSchemaRef}'`,
{ error: "invalid_schema_ref", code: "invalid_schema_ref", ref: fence.rawSchemaRef },
);
}
if (fence.oversized) {
throw unprocessable(
`Fenced schema block '${parsedRef.ref}' exceeds maximum size of ${MAX_SCHEMA_FENCE_BODY_CHARS} characters`,
{ error: "schema_validation_failed", code: "schema_validation_failed", schema: parsedRef.ref },
);
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(fence.rawJson);
} catch (err) {
throw unprocessable(
`Fenced schema block '${parsedRef.ref}' contains invalid JSON: ${err instanceof Error ? err.message : "parse error"}`,
{ error: "schema_validation_failed", code: "schema_validation_failed", schema: parsedRef.ref },
);
}
if (!isPlainRecord(parsedJson)) {
throw unprocessable(`Fenced schema block '${parsedRef.ref}' must contain a JSON object`, {
error: "schema_validation_failed",
code: "schema_validation_failed",
schema: parsedRef.ref,
});
}
collected.push({ schema: parsedRef.name, version: parsedRef.version, data: parsedJson });
}
const deduped = deduplicateSchemaBlocks(collected);
if (deduped.length === 0) return [];
if (deduped.length > MAX_SCHEMA_BLOCKS_ENTRIES) {
throw unprocessable(`Total schema blocks cannot exceed ${MAX_SCHEMA_BLOCKS_ENTRIES}`, {
error: "schema_validation_failed",
code: "schema_validation_failed",
});
}
return validateSchemaBlocks(dbOrTx, companyId, deduped);
}
/**
* Extracts valid fenced schema blocks from a final reply comment body and
* atomically merges them onto `issueComments.schemaBlocks` under a row lock.
* Reuses resolved schemas across fences/comments and skips writes when unchanged.
*/
export async function persistValidFencedSchemaBlocksOnComment(
dbOrTx: DbOrTx,
companyId: string,
commentId: string,
body: string,
options?: {
existingSchemaBlocks?: SchemaBlock[] | null;
schemaCache?: Map<string, Record<string, unknown> | null>;
},
): Promise<SchemaBlock[]> {
const scanned = scanFencedSchemaBlocks(body);
if (scanned.length === 0) return (options?.existingSchemaBlocks ?? []) as SchemaBlock[];
const candidates: Array<{ parsedRef: ParsedSchemaRef; data: Record<string, unknown> }> = [];
for (const fence of scanned) {
if (fence.oversized) continue;
let parsedRef: ParsedSchemaRef;
let parsedJson: unknown;
try {
parsedRef = parseSchemaRef(fence.rawSchemaRef);
parsedJson = JSON.parse(fence.rawJson);
} catch {
continue;
}
if (!isPlainRecord(parsedJson)) continue;
candidates.push({ parsedRef, data: parsedJson });
}
if (candidates.length === 0) return (options?.existingSchemaBlocks ?? []) as SchemaBlock[];
const cache = options?.schemaCache ?? new Map<string, Record<string, unknown> | null>();
const valid: SchemaBlock[] = [];
for (const candidate of candidates) {
let jsonSchema = cache.get(candidate.parsedRef.ref);
if (jsonSchema === undefined) {
try {
const schemaView = await getCompanySchema(dbOrTx, companyId, candidate.parsedRef.ref);
jsonSchema = schemaView.jsonSchema;
} catch {
jsonSchema = null;
}
cache.set(candidate.parsedRef.ref, jsonSchema);
}
if (!jsonSchema) continue;
if (validateAgainstJsonSchema(jsonSchema, candidate.data).valid) {
valid.push({
schema: candidate.parsedRef.name,
version: candidate.parsedRef.version,
data: candidate.data,
});
}
}
if (valid.length === 0) return (options?.existingSchemaBlocks ?? []) as SchemaBlock[];
if (options?.existingSchemaBlocks !== undefined) {
const knownExisting = (options.existingSchemaBlocks ?? []) as SchemaBlock[];
const dedupedKnown = deduplicateSchemaBlocks(knownExisting).slice(0, MAX_SCHEMA_BLOCKS_ENTRIES);
const previewMerged = deduplicateSchemaBlocks([...knownExisting, ...valid]).slice(
0,
MAX_SCHEMA_BLOCKS_ENTRIES,
);
if (
previewMerged.length === knownExisting.length &&
canonicalValueString(previewMerged) === canonicalValueString(dedupedKnown)
) {
return knownExisting;
}
}
return dbOrTx.transaction(async (rawTx) => {
const tx = rawTx as unknown as DbOrTx;
const [locked] = await tx
.select({ schemaBlocks: issueComments.schemaBlocks })
.from(issueComments)
.where(and(eq(issueComments.id, commentId), eq(issueComments.companyId, companyId)))
.for("update")
.limit(1);
const currentBlocks = ((locked?.schemaBlocks ?? []) as SchemaBlock[]);
const dedupedCurrent = deduplicateSchemaBlocks(currentBlocks).slice(0, MAX_SCHEMA_BLOCKS_ENTRIES);
const merged = deduplicateSchemaBlocks([...currentBlocks, ...valid]).slice(
0,
MAX_SCHEMA_BLOCKS_ENTRIES,
);
if (
merged.length === currentBlocks.length &&
canonicalValueString(merged) === canonicalValueString(dedupedCurrent)
) {
return currentBlocks;
}
await tx
.update(issueComments)
.set({ schemaBlocks: merged })
.where(and(eq(issueComments.id, commentId), eq(issueComments.companyId, companyId)));
return merged;
});
}
@@ -0,0 +1,318 @@
import { and, eq, inArray, isNull, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { channels, issues } from "@paperclipai/db";
import { isUuidLike, parseLabelFilterExpr } from "@paperclipai/shared";
import { badRequest, notFound } from "../../errors.js";
import {
assertChannelAccess,
buildSqlIssueLabelFilterCondition,
canAccessChannel,
channelSubtreeCondition,
enforceHeadlessScopes,
findInaccessibleChannelIds,
type DbOrTx,
type HeadlessActorContext,
} from "../headless-common.js";
import {
ensureChannel,
normalizeChannelPathOrThrow,
} from "../headless-channels.js";
export function buildRunnerChannelActor(input: {
companyId: string;
agentId: string;
agentName?: string | null;
agentRole?: string | null;
responsibleUserId: string | null;
museRuntime?: boolean;
externalAuthorizingUserId?: string;
}): HeadlessActorContext {
const effectiveUserId = input.museRuntime
? (input.externalAuthorizingUserId ?? null)
: (input.responsibleUserId ?? null);
return {
companyId: input.companyId,
companyName: "",
companyPrefix: "",
agentIdentityPolicy: "strict_agent_keys",
principalType: "agent",
userId: effectiveUserId,
agentId: input.agentId,
agentName: input.agentName ?? null,
agentRole: input.agentRole ?? null,
actorProfile: input.agentName ?? null,
scopes: null,
isInstanceAdmin: false,
responsibleUserId: input.responsibleUserId,
};
}
export async function resolveAccessibleTaskChannelPaths(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
channelIds: Iterable<string | null | undefined>,
): Promise<{ accessiblePaths: Map<string, string>; inaccessibleIds: Set<string> }> {
const uniqueIds = Array.from(
new Set(
Array.from(channelIds).filter(
(id): id is string => typeof id === "string" && id.length > 0,
),
),
);
if (uniqueIds.length === 0) {
return { accessiblePaths: new Map(), inaccessibleIds: new Set() };
}
const rows = await dbOrTx
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(and(eq(channels.companyId, companyId), inArray(channels.id, uniqueIds)));
const inaccessibleList = await findInaccessibleChannelIds(
dbOrTx,
companyId,
actor,
rows,
);
const inaccessibleIds = new Set(inaccessibleList);
const accessiblePaths = new Map<string, string>();
for (const row of rows) {
if (!inaccessibleIds.has(row.id)) {
accessiblePaths.set(row.id, row.path);
}
}
return { accessiblePaths, inaccessibleIds };
}
export type AuthorizedRunnerTaskChannel =
| { kind: "existing"; channel: typeof channels.$inferSelect }
| { kind: "ensure_path"; path: string };
export async function authorizeRunnerTaskChannel(
tx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rawChannel: string,
): Promise<AuthorizedRunnerTaskChannel> {
const trimmed = rawChannel.trim();
if (isUuidLike(trimmed)) {
const [existing] = await tx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
eq(channels.id, trimmed),
isNull(channels.archivedAt),
),
)
.limit(1);
if (!existing) {
throw notFound(`Channel '${trimmed}' not found`);
}
await assertChannelAccess(tx, existing, actor);
return { kind: "existing", channel: existing };
}
const normalized = normalizeChannelPathOrThrow(trimmed, {
allowSubtreePrefix: false,
});
enforceHeadlessScopes(actor, { channelPath: normalized.path });
const [existing] = await tx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (existing) {
if (existing.archivedAt) {
throw badRequest(`Channel '${existing.path}' is archived`, {
error: "channel_archived",
code: "channel_archived",
});
}
await assertChannelAccess(tx, existing, actor);
return { kind: "existing", channel: existing };
}
const parts = normalized.path.split("/");
if (parts.length > 1) {
const ancestorPaths: string[] = [];
for (let i = 1; i < parts.length; i += 1) {
ancestorPaths.push(parts.slice(0, i).join("/"));
}
const ancestors = await tx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, ancestorPaths),
isNull(channels.archivedAt),
),
);
for (const anc of ancestors) {
if (anc.visibility === "private") {
await assertChannelAccess(tx, anc, actor);
}
}
}
return { kind: "ensure_path", path: normalized.path };
}
export async function materializeRunnerTaskChannel(
tx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
authorized: AuthorizedRunnerTaskChannel,
): Promise<typeof channels.$inferSelect> {
if (authorized.kind === "existing") {
return authorized.channel;
}
return ensureChannel(tx, companyId, actor, { path: authorized.path });
}
export async function resolveRunnerSearchChannelIds(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawChannel: unknown,
): Promise<string[]> {
if (typeof rawChannel !== "string") {
throw badRequest("channel must be a string", {
error: "invalid_channel_path",
code: "invalid_channel_path",
});
}
const trimmed = rawChannel.trim();
if (!trimmed || trimmed.length > 140) {
throw badRequest("channel must be between 1 and 140 characters", {
error: "invalid_channel_path",
code: "invalid_channel_path",
});
}
if (isUuidLike(trimmed)) {
const [row] = await db
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
eq(channels.id, trimmed),
isNull(channels.archivedAt),
),
)
.limit(1);
if (!row) return [];
try {
enforceHeadlessScopes(actor, { channelPath: row.path });
} catch {
return [];
}
return (await canAccessChannel(db, row, actor)) ? [row.id] : [];
}
const normalizedInput = trimmed.endsWith("/*")
? `${trimmed.slice(0, -2)}/`
: trimmed;
const normalized = normalizeChannelPathOrThrow(normalizedInput, {
allowSubtreePrefix: true,
});
const matched = await db
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
normalized.isSubtreePrefix
? channelSubtreeCondition(normalized.path)
: eq(channels.path, normalized.path),
),
);
const accessibleIds: string[] = [];
for (const ch of matched) {
try {
enforceHeadlessScopes(actor, { channelPath: ch.path });
} catch {
continue;
}
if (await canAccessChannel(db, ch, actor)) {
accessibleIds.push(ch.id);
}
}
return accessibleIds;
}
export async function resolveRunnerTaskSearchFilters(
db: Db,
companyId: string,
actor: HeadlessActorContext,
baseReadCondition: SQL<boolean>,
input: { labelFilter?: unknown; channel?: unknown; query?: string },
): Promise<
| { empty: true }
| {
empty: false;
readCondition: SQL<boolean>;
includeChannelScope: boolean;
}
> {
let labelFilterCondition: SQL<boolean> | null = null;
if (input.labelFilter !== undefined && input.labelFilter !== null) {
if (typeof input.labelFilter !== "string" || input.labelFilter.length > 256) {
throw badRequest("labelFilter must be a string of at most 256 characters", {
error: "invalid_label_filter",
code: "invalid_label_filter",
});
}
let parsedLabelExpr;
try {
parsedLabelExpr = parseLabelFilterExpr(input.labelFilter);
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : `Invalid labelFilter '${input.labelFilter}'`,
{ error: "invalid_label_filter", code: "invalid_label_filter" },
);
}
labelFilterCondition = buildSqlIssueLabelFilterCondition(parsedLabelExpr);
}
let channelFilterIds: string[] | null = null;
if (input.channel !== undefined && input.channel !== null) {
channelFilterIds = await resolveRunnerSearchChannelIds(
db,
companyId,
actor,
input.channel,
);
if (channelFilterIds.length === 0) {
return { empty: true };
}
}
const includeChannelScope = Boolean(
channelFilterIds || labelFilterCondition || input.query?.trim(),
);
const readCondition = and(
baseReadCondition,
...(includeChannelScope ? [isNull(issues.conversationAgentId)] : []),
...(labelFilterCondition ? [labelFilterCondition] : []),
...(channelFilterIds ? [inArray(issues.channelId, channelFilterIds)] : []),
) as SQL<boolean>;
return { empty: false, readCondition, includeChannelScope };
}
@@ -0,0 +1,239 @@
import { performance } from "node:perf_hooks";
import { describe, expect, it } from "vitest";
import type { Db } from "@paperclipai/db";
import { HttpError } from "../../errors.js";
import {
admitToolInputSchema,
providerToolSchemaShapeIssues,
runnerCodexDynamicToolsFit,
} from "../../vendor/paperclip-runner/index.js";
import {
boundedReadSchemaBlocks,
createSchemaBlocksResponseBudget,
deduplicateSchemaBlocks,
MAX_CANDIDATE_SCHEMA_FENCES,
MAX_KV_LABELS_ENTRIES,
MAX_RESPONSE_SCHEMA_BLOCKS_BYTES,
MAX_SCANNED_SCHEMA_MARKDOWN_CHARS,
MAX_SCHEMA_FENCE_BODY_CHARS,
normalizeRunnerKvLabelsInput,
projectBoundedSchemaBlocks,
scanFencedSchemaBlocks,
} from "./native-task-metadata.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
describe("scanFencedSchemaBlocks", () => {
it("extracts backtick and tilde json schema fences with quotes, extra attributes, and nested fences", () => {
const markdown = [
"Progress summary before fence:",
"```json schema=test-report@1",
'{"passed":true,"total":4,"failed":0}',
"```",
"",
' ~~~json extra=true schema="finding@1" ',
'{"severity":"high","title":"Missing lock","line":18}',
" ~~~ ",
"",
"````JSON schema='git-commit@1'",
"{",
' "sha": "abc1234",',
' "message": "Includes ``` inner backticks safely"',
"}",
"````",
].join("\n");
expect(scanFencedSchemaBlocks(markdown)).toEqual([
{
rawSchemaRef: "test-report@1",
rawJson: '{"passed":true,"total":4,"failed":0}',
oversized: false,
},
{
rawSchemaRef: "finding@1",
rawJson: '{"severity":"high","title":"Missing lock","line":18}',
oversized: false,
},
{
rawSchemaRef: "git-commit@1",
rawJson: '{\n "sha": "abc1234",\n "message": "Includes ``` inner backticks safely"\n}',
oversized: false,
},
]);
});
it("ignores ordinary code blocks, invalid backtick info strings, and unclosed fences", () => {
const markdown = [
"```json",
'{"ordinary":true}',
"```",
"```json schema=test-report@1 `disallowed-backtick`",
'{"passed":true}',
"```",
"```ts schema=test-report@1",
'{"passed":true}',
"```",
"```json schema=test-report@1",
'{"unclosed":true}',
].join("\n");
expect(scanFencedSchemaBlocks(markdown)).toEqual([]);
});
it("marks oversized fence bodies without buffering unbounded lines and caps candidate count and input length", () => {
const hugeBody = "x".repeat(MAX_SCHEMA_FENCE_BODY_CHARS + 128);
const oversizedDoc = `\`\`\`json schema=test-report@1\n${hugeBody}\n\`\`\``;
expect(scanFencedSchemaBlocks(oversizedDoc)).toEqual([
{
rawSchemaRef: "test-report@1",
rawJson: "",
oversized: true,
},
]);
const manyFences = Array.from(
{ length: MAX_CANDIDATE_SCHEMA_FENCES + 10 },
(_, idx) => `\`\`\`json schema=test-report@1\n{"passed":true,"total":${idx}}\n\`\`\``,
).join("\n");
const capped = scanFencedSchemaBlocks(manyFences);
expect(capped).toHaveLength(MAX_CANDIDATE_SCHEMA_FENCES);
expect(capped[0]?.rawJson).toBe('{"passed":true,"total":0}');
expect(capped[MAX_CANDIDATE_SCHEMA_FENCES - 1]?.rawJson).toBe(
`{"passed":true,"total":${MAX_CANDIDATE_SCHEMA_FENCES - 1}}`,
);
const beyondPrefix =
"a".repeat(MAX_SCANNED_SCHEMA_MARKDOWN_CHARS + 32) +
"\n```json schema=test-report@1\n{\"passed\":true}\n```";
expect(scanFencedSchemaBlocks(beyondPrefix)).toEqual([]);
});
it("scans 5,000 repeated unterminated ```json lines in strictly linear time (< 50ms)", () => {
// Warm up V8 bytecode before measuring linear scan wall time.
scanFencedSchemaBlocks("```json schema=test-report@1\n{\"passed\":true}\n```");
const repeatedPlain = "```json\n".repeat(5_000);
const startPlain = performance.now();
const outPlain = scanFencedSchemaBlocks(repeatedPlain);
const elapsedPlainMs = performance.now() - startPlain;
expect(outPlain).toEqual([]);
expect(elapsedPlainMs).toBeLessThan(50);
const repeatedSchema = "```json schema=test-report@1\n".repeat(5_000);
const startSchema = performance.now();
const outSchema = scanFencedSchemaBlocks(repeatedSchema);
const elapsedSchemaMs = performance.now() - startSchema;
expect(outSchema).toEqual([]);
expect(elapsedSchemaMs).toBeLessThan(50);
});
});
describe("normalizeRunnerKvLabelsInput & deduplicateSchemaBlocks", () => {
it("normalizes both { key, value } arrays and string maps while enforcing key/value rules", () => {
expect(normalizeRunnerKvLabelsInput(undefined)).toEqual({});
expect(normalizeRunnerKvLabelsInput(null)).toEqual({});
expect(
normalizeRunnerKvLabelsInput([
{ key: "env", value: "staging" },
{ key: "role", value: "scanner" },
]),
).toEqual({ env: "staging", role: "scanner" });
expect(
normalizeRunnerKvLabelsInput({
env: "production",
"team.owner": "platform",
}),
).toEqual({ env: "production", "team.owner": "platform" });
expect(() =>
normalizeRunnerKvLabelsInput([
{ key: "env", value: "a" },
{ key: "env", value: "b" },
]),
).toThrow(HttpError);
expect(() =>
normalizeRunnerKvLabelsInput([{ key: "paperclip.internal", value: "1" }]),
).toThrow(/paperclip\./);
const tooMany = Array.from({ length: MAX_KV_LABELS_ENTRIES + 1 }, (_, i) => ({
key: `k${i}`,
value: "v",
}));
expect(() => normalizeRunnerKvLabelsInput(tooMany)).toThrow(
`kvLabels cannot exceed ${MAX_KV_LABELS_ENTRIES} entries`,
);
});
it("deduplicates schema blocks with canonically equivalent JSON payloads", () => {
const blocks = deduplicateSchemaBlocks([
{ schema: "test-report", version: 1, data: { passed: true, total: 5 } },
{ schema: "test-report", version: 1, data: { total: 5, passed: true } },
{ schema: "test-report", version: 1, data: { passed: false, total: 5 } },
{ schema: "finding", version: 1, data: { severity: "low", title: "Note" } },
]);
expect(blocks).toEqual([
{ schema: "test-report", version: 1, data: { passed: true, total: 5 } },
{ schema: "test-report", version: 1, data: { passed: false, total: 5 } },
{ schema: "finding", version: 1, data: { severity: "low", title: "Note" } },
]);
const singleFortyKiB = [
{ schema: "finding", version: 1, data: { severity: "low", title: "40k", notes: "x".repeat(40 * 1024) } },
];
expect(projectBoundedSchemaBlocks(singleFortyKiB)).toEqual({ schemaBlocks: singleFortyKiB });
const largeBlocks = Array.from({ length: 24 }, (_, idx) => ({
schema: "finding",
version: 1,
data: { severity: "low", title: `item-${idx}`, notes: "x".repeat(4_096) },
}));
const projected = projectBoundedSchemaBlocks(largeBlocks, { maxBlocks: 16, maxTotalChars: 12_000 });
expect(projected.schemaBlocks.length).toBeGreaterThan(0);
expect(projected.schemaBlocks.length).toBeLessThan(largeBlocks.length);
expect(projected.schemaBlocksTruncated).toBe(true);
expect(projected.schemaBlocksOmittedCount).toBe(largeBlocks.length - projected.schemaBlocks.length);
expect(projected.schemaBlocksFullReadHint).toContain("call_api");
expect(boundedReadSchemaBlocks(largeBlocks, { maxBlocks: 16, maxTotalChars: 12_000 })).toEqual(
projected.schemaBlocks,
);
// Aggregate response budget across 9 comments x ~60 KiB stays <= 128 KiB (well below 500 KB PRP command limit)
const sharedBudget = createSchemaBlocksResponseBudget();
const nineComments = Array.from({ length: 9 }, (_, idx) => [
{ schema: "finding", version: 1, data: { severity: "low", title: `c-${idx}`, notes: "y".repeat(60 * 1024) } },
]);
const historyProjections = nineComments.map((blocks) =>
projectBoundedSchemaBlocks(blocks, { responseBudget: sharedBudget }),
);
expect(historyProjections[0]?.schemaBlocks).toHaveLength(1);
expect(historyProjections[1]?.schemaBlocks).toHaveLength(1);
expect(historyProjections.slice(2).every((p) => p.schemaBlocks.length === 0 && p.schemaBlocksTruncated === true && p.schemaBlocksOmittedCount === 1)).toBe(true);
expect(Buffer.byteLength(JSON.stringify(historyProjections), "utf8")).toBeLessThan(
MAX_RESPONSE_SCHEMA_BLOCKS_BYTES + 4_096,
);
});
});
describe("parity runner tool schema provider admission", () => {
it("admits create_task, report_progress, and search_tasks across strict provider schema checks", () => {
const dummyDb = new Proxy({} as Db, {
get() {
throw new Error("definitions() must not query the database");
},
});
const id = "00000000-0000-4000-8000-000000000101";
const authority = new PaperclipRunnerToolAuthority(dummyDb, {
companyId: id,
agentId: id,
issueId: id,
runId: id,
});
const definitions = authority.definitions();
for (const toolName of ["create_task", "report_progress", "search_tasks"] as const) {
const tool = definitions.find((entry) => entry.name === toolName);
expect(tool, `expected ${toolName} to be advertised`).toBeDefined();
expect(providerToolSchemaShapeIssues(tool!.inputSchema)).toEqual([]);
expect(admitToolInputSchema(tool!.inputSchema as Record<string, unknown>).ok).toBe(true);
}
expect(runnerCodexDynamicToolsFit(definitions)).toBe(true);
});
});
@@ -0,0 +1,3 @@
export * from "./native-schema-fences.js";
export * from "./native-task-channels.js";
export * from "./native-result-schema-gate.js";
@@ -13,6 +13,8 @@ import {
agents,
authUsers,
approvals,
channelAccessMembers,
channels,
companies,
companyMemberships,
createDb,
@@ -20,9 +22,11 @@ import {
heartbeatRuns,
issueApprovals,
issueComments,
issueLabels,
issueThreadInteractions,
issueWatchdogs,
issues,
labels,
projectWorkspaces,
projects,
} from "@paperclipai/db";
@@ -2104,6 +2108,451 @@ describe("PaperclipRunnerToolAuthority", () => {
expect(interactions.find((row) => row.title === "Approve continuation")?.sourceIdentityContextId).toBe(pending!.id);
});
it("supports kvLabels, channels, schemaBlocks, resultSchemaRef, and private-channel boundaries across task tools", async () => {
const parityIssueId = randomUUID();
const parityRunId = randomUUID();
const openRootId = randomUUID();
const openSubId = randomUUID();
const privateAllowedId = randomUUID();
const privateDeniedId = randomUUID();
const tagLabelId = randomUUID();
const createdIssueIds: string[] = [parityIssueId];
await db.insert(channels).values([
{ id: openRootId, companyId, path: "build", visibility: "open" },
{ id: openSubId, companyId, path: "build/auth", visibility: "open" },
{ id: privateAllowedId, companyId, path: "sec-allowed", visibility: "private" },
{ id: privateDeniedId, companyId, path: "sec-denied", visibility: "private" },
]);
await db.insert(channelAccessMembers).values({
companyId,
channelId: privateAllowedId,
subjectType: "agent",
subjectId: agentId,
});
await db.insert(labels).values({
id: tagLabelId,
companyId,
name: "urgent-tag",
color: "#ef4444",
});
await db.insert(issues).values({
id: parityIssueId,
companyId,
title: "Parity parent task",
status: "in_progress",
workMode: "standard",
assigneeAgentId: agentId,
channelId: openRootId,
scope: "channel",
kvLabels: { env: "staging", role: "coordinator" },
resultSchemaRef: "test-report@1",
schemaBlocks: [{ schema: "finding", version: 1, data: { severity: "low", title: "Seeded block" } }],
});
await db.insert(heartbeatRuns).values({
id: parityRunId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: parityIssueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId: parityIssueId },
});
await db.update(issues).set({ executionRunId: parityRunId }).where(eq(issues.id, parityIssueId));
try {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId: parityIssueId,
runId: parityRunId,
});
// 1. create_task with kvLabels, resultSchemaRef, and auto-created open subchannel
const createdOpen = (await authority.execute({
tool: "create_task",
callId: "create-open-channel",
arguments: {
idempotencyKey: "parity-open-child",
title: "Parity child in build/api",
kvLabels: [
{ key: "env", value: "staging" },
{ key: "role", value: "scanner" },
],
resultSchemaRef: "test-report@1",
channel: "build/api",
},
})) as {
disposition: string;
task: {
id: string;
channelId: string | null;
channelPath: string | null;
kvLabels: Record<string, string>;
resultSchemaRef: string | null;
};
};
createdIssueIds.push(createdOpen.task.id);
expect(createdOpen).toMatchObject({
disposition: "applied",
task: {
channelPath: "build/api",
kvLabels: { env: "staging", role: "scanner" },
resultSchemaRef: "test-report@1",
},
});
expect(createdOpen.task.channelId).toEqual(expect.any(String));
// Also accepts plain-object kvLabels at runtime and enforces private channel membership
const createdPrivate = (await authority.execute({
tool: "create_task",
callId: "create-private-allowed",
arguments: {
idempotencyKey: "parity-private-allowed",
title: "Parity child in allowed private channel",
kvLabels: { env: "staging", role: "worker" },
channel: privateAllowedId,
},
})) as { task: { id: string; channelId: string | null; channelPath: string | null; kvLabels: Record<string, string> } };
createdIssueIds.push(createdPrivate.task.id);
expect(createdPrivate.task).toMatchObject({
channelId: privateAllowedId,
channelPath: "sec-allowed",
kvLabels: { env: "staging", role: "worker" },
});
const [privateRow] = await db.select().from(issues).where(eq(issues.id, createdPrivate.task.id));
expect(privateRow).toMatchObject({ visibility: "private", scope: "channel" });
await db.insert(issueLabels).values({
companyId,
issueId: createdOpen.task.id,
labelId: tagLabelId,
});
// Denied on inaccessible private channel or child path under inaccessible private ancestor, and unknown schema
await expect(
authority.execute({
tool: "create_task",
callId: "create-private-denied",
arguments: {
idempotencyKey: "parity-private-denied",
title: "Should fail private channel access",
channel: "sec-denied",
},
}),
).rejects.toThrow(/access|private|forbidden|not found/i);
await expect(
authority.execute({
tool: "create_task",
callId: "create-private-sub-denied",
arguments: {
idempotencyKey: "parity-private-sub-denied",
title: "Should fail private ancestor access",
channel: "sec-denied/sub",
},
}),
).rejects.toThrow(/access|private|forbidden|not found/i);
await expect(
authority.execute({
tool: "create_task",
callId: "create-unknown-schema",
arguments: {
idempotencyKey: "parity-unknown-schema",
title: "Should fail schema check",
resultSchemaRef: "missing-schema@1",
},
}),
).rejects.toThrow(/missing-schema@1/);
// Insert a task inside the inaccessible private channel to prove neither context nor search leaks it
const secretTaskId = randomUUID();
createdIssueIds.push(secretTaskId);
await db.insert(issues).values({
id: secretTaskId,
companyId,
parentId: parityIssueId,
title: "Parity child in denied private channel",
status: "todo",
channelId: privateDeniedId,
scope: "channel",
kvLabels: { env: "staging", role: "scanner" },
});
// 2. get_task_context includes channelId, channelPath, kvLabels, resultSchemaRef, schemaBlocks and hides denied channel child
const contextResult = (await authority.execute({
tool: "get_task_context",
callId: "parity-context",
arguments: {},
})) as {
activeTask: Record<string, unknown>;
childTasks: Array<Record<string, unknown>>;
};
expect(contextResult.activeTask).toMatchObject({
id: parityIssueId,
channelId: openRootId,
channelPath: "build",
kvLabels: { env: "staging", role: "coordinator" },
resultSchemaRef: "test-report@1",
schemaBlocks: [{ schema: "finding", version: 1, data: { severity: "low", title: "Seeded block" } }],
});
expect(contextResult.childTasks.map((t) => t.id)).toContain(createdOpen.task.id);
expect(contextResult.childTasks.map((t) => t.id)).toContain(createdPrivate.task.id);
expect(contextResult.childTasks.map((t) => t.id)).not.toContain(secretTaskId);
expect(contextResult.childTasks.find((t) => t.id === createdOpen.task.id)).toMatchObject({
channelPath: "build/api",
kvLabels: { env: "staging", role: "scanner" },
resultSchemaRef: "test-report@1",
});
// 3. report_progress validates & deduplicates explicit schemaBlocks + fenced json schema blocks, and get_task_history returns & redacts them
const progress = (await authority.execute({
tool: "report_progress",
callId: "parity-progress",
arguments: {
idempotencyKey: "parity-progress-1",
kvLabels: [{ key: "stage", value: "verification" }],
schemaBlocks: [
{
schema: "test-report",
version: 1,
dataJson: JSON.stringify({ passed: true, total: 12, failed: 0 }),
},
],
body: [
"All checks green.",
"```json schema=test-report@1",
'{"total":12,"passed":true,"failed":0}',
"```",
"```json schema=finding@1",
'{"severity":"low","title":"Clean run"}',
"```",
].join("\n"),
},
})) as { commentId: string; disposition: string };
expect(progress.disposition).toBe("applied");
await expect(
authority.execute({
tool: "report_progress",
callId: "parity-progress-invalid",
arguments: {
idempotencyKey: "parity-progress-invalid",
body: "```json schema=test-report@1\n{\"passed\":\"not-a-boolean\"}\n```",
},
}),
).rejects.toThrow(/passed/);
// Add a quarantined low-trust comment with actorProfile + kvLabels + schemaBlocks to verify redaction for higher-trust reader
const quarantinedCommentId = randomUUID();
await db.insert(issueComments).values({
id: quarantinedCommentId,
companyId,
issueId: parityIssueId,
body: "Untrusted comment",
actorProfile: "Spoofed Trusted Reviewer",
kvLabels: { leaked: "secret" },
schemaBlocks: [{ schema: "finding", version: 1, data: { severity: "high", title: "Spoofed" } }],
sourceTrust: buildLowTrustSourceTrust({ issueId: parityIssueId }),
});
const history = (await authority.execute({
tool: "get_task_history",
callId: "parity-history",
arguments: {},
})) as {
comments: Array<{
id: string;
body: string;
actorProfile: string | null;
kvLabels: Record<string, string>;
schemaBlocks: unknown[];
}>;
};
const savedComment = history.comments.find((c) => c.id === progress.commentId);
expect(savedComment).toMatchObject({
actorProfile: "Runner agent",
kvLabels: { stage: "verification" },
schemaBlocks: [
{ schema: "test-report", version: 1, data: { passed: true, total: 12, failed: 0 } },
{ schema: "finding", version: 1, data: { severity: "low", title: "Clean run" } },
],
});
const redactedComment = history.comments.find((c) => c.id === quarantinedCommentId);
expect(redactedComment).toMatchObject({
body: LOW_TRUST_QUARANTINED_BODY,
actorProfile: null,
kvLabels: {},
schemaBlocks: [],
});
// 4. search_tasks with labelFilter, channel (exact, subtree build/*, UUID), private channel exclusion, and cursor pagination
const byRoleUnion = (await authority.execute({
tool: "search_tasks",
callId: "search-label-union",
arguments: { query: "Parity", labelFilter: "role=scanner|worker", limit: 1 },
})) as {
tasks: Array<{ id: string; channelPath: string | null; kvLabels: Record<string, string> }>;
hasMore: boolean;
nextCursor: string | null;
};
expect(byRoleUnion.tasks).toHaveLength(1);
expect(byRoleUnion.hasMore).toBe(true);
expect(byRoleUnion.nextCursor).toBe(byRoleUnion.tasks[0]!.id);
const secondPage = (await authority.execute({
tool: "search_tasks",
callId: "search-label-union-p2",
arguments: {
query: "Parity",
labelFilter: "role=scanner|worker",
limit: 1,
cursor: byRoleUnion.nextCursor,
},
})) as { tasks: Array<{ id: string }>; hasMore: boolean; nextCursor: string | null };
expect(secondPage.tasks).toHaveLength(1);
expect(secondPage.hasMore).toBe(false);
expect(secondPage.nextCursor).toBeNull();
const unionIds = [byRoleUnion.tasks[0]!.id, secondPage.tasks[0]!.id].sort();
expect(unionIds).toEqual([createdOpen.task.id, createdPrivate.task.id].sort());
const byTagLabel = (await authority.execute({
tool: "search_tasks",
callId: "search-tag-label",
arguments: { labelFilter: "urgent-tag" },
})) as { tasks: Array<{ id: string }> };
expect(byTagLabel.tasks.map((t) => t.id)).toEqual([createdOpen.task.id]);
const bySubtree = (await authority.execute({
tool: "search_tasks",
callId: "search-subtree",
arguments: { channel: "build/*" },
})) as { tasks: Array<{ id: string; channelPath: string | null }> };
expect(bySubtree.tasks.map((t) => t.id).sort()).toEqual([parityIssueId, createdOpen.task.id].sort());
const byDeniedPrivate = (await authority.execute({
tool: "search_tasks",
callId: "search-denied-private",
arguments: { channel: "sec-denied" },
})) as { tasks: unknown[]; hasMore: boolean; nextCursor: string | null };
expect(byDeniedPrivate).toMatchObject({ tasks: [], hasMore: false, nextCursor: null });
} finally {
await db.delete(issues).where(inArray(issues.id, createdIssueIds));
await db.delete(labels).where(eq(labels.id, tagLabelId));
await db.delete(channels).where(
and(eq(channels.companyId, companyId), inArray(channels.path, ["build", "build/auth", "build/api", "sec-allowed", "sec-denied"])),
);
}
});
it("replays previous-release create_task and report_progress receipts cleanly across upgrade recovery", async () => {
const upgradeIssueId = randomUUID();
const upgradeRunId = randomUUID();
const legacyChildId = randomUUID();
const legacyCommentId = randomUUID();
await db.insert(issues).values({
id: upgradeIssueId,
companyId,
title: "Upgrade recovery parent",
status: "in_progress",
workMode: "standard",
assigneeAgentId: agentId,
});
const legacyCreateInput = {
idempotencyKey: "legacy-create-key",
title: "Legacy child created before parity fields",
};
const legacyCreateResult = {
commandId: `create-task:${legacyChildId}`,
disposition: "applied",
stateRevision: 1,
entityRefs: [legacyChildId],
scheduledWakeIds: [],
task: {
id: legacyChildId,
identifier: "RNT-777",
parentId: upgradeIssueId,
projectId: null,
status: "todo",
assigneeActorId: agentId,
assigneeUserId: null,
},
};
const legacyProgressInput = {
idempotencyKey: "legacy-progress-key",
body: "Legacy progress comment before kvLabels and schemaBlocks",
};
const legacyProgressResult = {
commentId: legacyCommentId,
issueId: upgradeIssueId,
disposition: "applied",
};
await db.insert(heartbeatRuns).values({
id: upgradeRunId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: upgradeIssueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId: upgradeIssueId },
resultJson: {
semanticToolReceipts: {
"legacy-create-key": {
operationId: "create_task",
input: legacyCreateInput,
result: legacyCreateResult,
},
"legacy-progress-key": {
operationId: "report_progress",
input: legacyProgressInput,
result: legacyProgressResult,
},
},
},
});
await db.update(issues).set({ executionRunId: upgradeRunId }).where(eq(issues.id, upgradeIssueId));
try {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId: upgradeIssueId,
runId: upgradeRunId,
});
await expect(
authority.recover({
tool: "create_task",
callId: "recover-legacy-create",
arguments: legacyCreateInput,
}),
).resolves.toEqual({ result: legacyCreateResult });
await expect(
authority.recover({
tool: "report_progress",
callId: "recover-legacy-progress",
arguments: legacyProgressInput,
}),
).resolves.toEqual({ result: legacyProgressResult });
await expect(
authority.execute({
tool: "report_progress",
callId: "replay-legacy-progress",
arguments: legacyProgressInput,
}),
).resolves.toEqual(legacyProgressResult);
expect(
await db.select().from(issueComments).where(eq(issueComments.issueId, upgradeIssueId)),
).toHaveLength(0);
} finally {
await db.delete(issues).where(eq(issues.id, upgradeIssueId));
}
});
it("fails closed once the run is no longer active", async () => {
await db
.update(heartbeatRuns)
@@ -80,7 +80,7 @@ import { runnerApiCatalog, searchRunnerApi, withCompanyPagePaths } from "./runne
import { assertRunnerApiDispatchable, executeRunnerApi, validateRunnerApiCall, RUNNER_API_MAX_BYTES, type RunnerApiCall, type RunnerApiFile, type RunnerApiIo } from "./runner-api-client.js";
import { finishPendingRunnerApiCaptureDeletes, markRunnerApiCaptureEvictions, RUNNER_API_CAPTURE_EVICTION_PASSES, runnerApiCaptureCleanupStalled, runnerApiCaptureUsageBytes } from "./runner-api-capture-retention.js";
import { acquireRunnerApiResponseSlot, RUNNER_API_RESPONSE_DEADLINE_MS, RunnerApiCaptureReservationReclaimedError, runnerApiCompanyCaptureMaxBytes, RUNNER_API_RESPONSE_MAX_BYTES, RUNNER_API_RESPONSE_RUN_MAX_BYTES, RunnerApiResponseLimitError } from "./runner-api-response-limits.js";
import { and, desc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
import { and, desc, eq, inArray, isNull, notInArray, sql, type SQL } from "drizzle-orm";
import { AGENT_TOOL_CALL_LOOP, TOOL_CALL_LOOP_HINT, toolCallLoopContinuationKey, type ToolCallLoopError } from "./repeated-tool-failure-guard.js";
import { nativeRunHasStopRequest } from "./native-tool-receipt-limit.js";
import { enqueueWake } from "./status-decision-committer.js";
@@ -94,6 +94,7 @@ import {
runnerApiResponseReservations,
agents,
agentWakeupRequests,
channels,
chatEndpoints,
chatConversations,
companies,
@@ -145,6 +146,19 @@ import {
} from "./chat-attachment-read.js";
import { commentsArrivedDuringRun, recordTaskHistoryRead, taskHistoryHandlingGuidance } from "../queued-comment-delivery.js";
import { recordChildTaskRead } from "./native-child-completion-delivery.js";
import { assertSchemaExists } from "../headless-schemas.js";
import {
authorizeRunnerTaskChannel,
buildRunnerChannelActor,
collectAndValidateProgressSchemaBlocks,
createSchemaBlocksResponseBudget,
materializeRunnerTaskChannel,
normalizeRunnerKvLabelsInput,
projectBoundedSchemaBlocks,
resolveAccessibleTaskChannelPaths,
resolveRunnerTaskSearchFilters,
type SchemaBlocksResponseBudget,
} from "./native-task-metadata.js";
import { logger } from "../../middleware/logger.js";
// Artifacts are at most RUNNER_API_MAX_BYTES; a healthy read takes seconds.
@@ -1020,11 +1034,18 @@ export class PaperclipRunnerToolAuthority {
return apiToolResult(await this.#withWorkspacePageHref(await this.#callApi(call.callId, call.arguments)));
}
case "get_task_context": {
if (this.#apiScope(context).kind === "skill_test") return {
company: { id: this.binding.companyId }, actor: redactedActor(context.actor),
activeTask: redactedTask(context.issue), childTasks: [], childReviewOutcomes: [],
run: { id: context.run.id, status: context.run.status, invocationSource: context.run.invocationSource },
};
const channelActor = this.#channelActor(context);
const contextBlocksBudget = createSchemaBlocksResponseBudget();
if (this.#apiScope(context).kind === "skill_test") {
const { accessiblePaths, inaccessibleIds } = await resolveAccessibleTaskChannelPaths(
this.db, this.binding.companyId, channelActor, [context.issue.channelId],
);
return {
company: { id: this.binding.companyId }, actor: redactedActor(context.actor),
activeTask: redactedTask(context.issue, accessiblePaths, inaccessibleIds, contextBlocksBudget), childTasks: [], childReviewOutcomes: [],
run: { id: context.run.id, status: context.run.status, invocationSource: context.run.invocationSource },
};
}
const monitorCheckAt = !this.binding.nativeReview && context.issue.workMode === "standard" &&
context.issue.executionRunId === this.binding.runId
? eligibleIssueMonitorWait(context.issue, this.binding.agentId) : null;
@@ -1040,16 +1061,27 @@ export class PaperclipRunnerToolAuthority {
const readableChildren = this.binding.museRuntime
? await this.#readableMuseTaskIds(context.run, childTasks.map(task => task.id)) : null;
const visibleChildTasks = readableChildren ? childTasks.filter(task => readableChildren.has(task.id)) : childTasks;
const { accessiblePaths, inaccessibleIds } = await resolveAccessibleTaskChannelPaths(
this.db,
this.binding.companyId,
channelActor,
[context.issue.channelId, ...visibleChildTasks.map((task) => task.channelId)],
);
const channelVisibleChildren = visibleChildTasks.filter(
(task) => !task.channelId || !inaccessibleIds.has(task.channelId),
);
const shownChildren = channelVisibleChildren.slice(0, 100);
await recordChildTaskRead(this.db, { companyId: this.binding.companyId, agentId: this.binding.agentId,
runId: this.binding.runId, parentIssueId: this.binding.issueId, children: visibleChildTasks.slice(0, 100) }).catch(error =>
runId: this.binding.runId, parentIssueId: this.binding.issueId, children: shownChildren }).catch(error =>
logger.warn({ err: error, runId: this.binding.runId }, "could not record the child tasks a run read"));
const activeTask = redactedTask(context.issue, accessiblePaths, inaccessibleIds, contextBlocksBudget);
return {
company: { id: this.binding.companyId },
actor: redactedActor(context.actor),
taskQuestionContext: await readTaskQuestionContext(this.db, {
...this.binding, conversationMode: isConversation(context.issue),
}),
activeTask: redactedTask(context.issue),
activeTask,
completionContinuation: monitorCheckAt ? {
kind: "monitor",
summary: "Wait for the saved task monitor.",
@@ -1059,7 +1091,7 @@ export class PaperclipRunnerToolAuthority {
runId: this.binding.runId, workspaceId: context.issue.executionWorkspaceId })
?? await readPublishedGitHubReviewCompletionContinuation({ db: this.db, binding: this.binding })
: null,
childTasks: visibleChildTasks.slice(0, 100).map(redactedTask),
childTasks: shownChildren.map((child) => redactedTask(child, accessiblePaths, inaccessibleIds, contextBlocksBudget)),
childTasksTruncated: childTasks.length > 100,
delegationGuidance: "Reuse existing child tasks for delegated work. Inspect a completed child's comments and documents before creating another task for the same deliverable. Use search_tasks if the child task list is truncated.",
run: {
@@ -1090,6 +1122,9 @@ export class PaperclipRunnerToolAuthority {
sourceTrust: issueComments.sourceTrust,
authorAgentId: issueComments.authorAgentId,
authorUserId: issueComments.authorUserId,
actorProfile: issueComments.actorProfile,
kvLabels: issueComments.kvLabels,
schemaBlocks: issueComments.schemaBlocks,
createdAt: issueComments.createdAt,
updatedAt: issueComments.updatedAt,
}).from(issueComments)
@@ -1105,30 +1140,73 @@ export class PaperclipRunnerToolAuthority {
logger.warn({ err: error, runId: this.binding.runId }, "could not record the task history a run read"));
const arrived = await commentsArrivedDuringRun(this.db, { companyId: this.binding.companyId,
runId: this.binding.runId, agentId: this.binding.agentId, comments }).catch(() => [] as string[]);
return { comments: comments.reverse().map(({ updatedAt: _updatedAt, ...comment }) => {
const visible = isLowTrustQuarantined(readerSourceTrust) ? comment : sanitizeQuarantinedCommentForHigherTrust(comment);
return { ...visible, body: fastResponseHistoryBody(visible) };
}), ...taskHistoryHandlingGuidance(arrived) };
// Allocate the response-wide schemaBlocks byte budget newest-first so
// recent comments retain full blocks and older comments report truncation
// before reversing into chronological order.
const historyBlocksBudget = createSchemaBlocksResponseBudget();
const projectedNewestFirst = comments.map(({ updatedAt: _updatedAt, ...comment }) => {
const redactQuarantined = !isLowTrustQuarantined(readerSourceTrust) && isLowTrustQuarantined(comment.sourceTrust);
const visible = redactQuarantined ? sanitizeQuarantinedCommentForHigherTrust(comment) : comment;
const projectedBlocks = redactQuarantined
? { schemaBlocks: [] }
: projectBoundedSchemaBlocks(visible.schemaBlocks, {
responseBudget: historyBlocksBudget,
fullReadHint: `Use call_api with GET /api/issues/${this.binding.issueId}/comments to read all saved schemaBlocks.`,
});
return {
...visible,
body: fastResponseHistoryBody(visible),
actorProfile: redactQuarantined ? null : (visible.actorProfile ?? null),
kvLabels: redactQuarantined ? {} : (visible.kvLabels ?? {}),
...projectedBlocks,
};
});
return { comments: projectedNewestFirst.reverse(), ...taskHistoryHandlingGuidance(arrived) };
}
case "search_tasks": {
const tasks = await issueService(this.db).list(this.binding.companyId, { readCondition: await issueReadSqlCondition(this.db, this.#privacyActor(context.run)) });
const channelActor = this.#channelActor(context);
const limit = boundedLimit(input.limit, 50, 200);
const cursor = input.cursor === undefined ? null : requiredUuid(input.cursor).toLowerCase();
const query = typeof input.query === "string" ? input.query.toLowerCase() : "";
const baseReadCondition = await issueReadSqlCondition(this.db, this.#privacyActor(context.run));
const resolvedSearch = await resolveRunnerTaskSearchFilters(
this.db,
this.binding.companyId,
channelActor,
baseReadCondition,
{ labelFilter: input.labelFilter, channel: input.channel, query },
);
if (resolvedSearch.empty) {
return { tasks: [], limit, returnedCount: 0, hasMore: false, nextCursor: null };
}
const tasks = await issueService(this.db).list(this.binding.companyId, {
readCondition: resolvedSearch.readCondition,
...(resolvedSearch.includeChannelScope ? { scope: ["board", "agent", "channel"] } : {}),
});
const statuses = Array.isArray(input.statuses) ? new Set(input.statuses.filter((value): value is string => typeof value === "string")) : null;
const matching = tasks.filter((task) =>
(!query || `${task.identifier} ${task.title} ${task.description ?? ""}`.toLowerCase().includes(query))
&& (!statuses || statuses.size === 0 || statuses.has(task.status))
);
const readable = this.binding.museRuntime ? await this.#readableMuseTaskIds(context.run, matching.map(task => task.id)) : null;
const limit = boundedLimit(input.limit, 50, 200);
const cursor = input.cursor === undefined ? null : requiredUuid(input.cursor).toLowerCase();
const { accessiblePaths, inaccessibleIds } = await resolveAccessibleTaskChannelPaths(
this.db,
this.binding.companyId,
channelActor,
matching.map((task) => task.channelId),
);
// IDs keep page order stable when task activity or status changes. Every
// page still applies current company, privacy and Muse read authority.
const remaining = matching.filter(task => (!readable || readable.has(task.id)) && (!cursor || task.id > cursor))
.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
// page still applies current company, privacy, channel and Muse read authority.
const remaining = matching.filter(task =>
(!readable || readable.has(task.id))
&& (!task.channelId || !inaccessibleIds.has(task.channelId))
&& (!cursor || task.id > cursor)
).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
const page = remaining.slice(0, limit);
const hasMore = remaining.length > limit;
const searchBlocksBudget = createSchemaBlocksResponseBudget();
return {
tasks: page.map(redactedTask),
tasks: page.map((task) => redactedTask(task, accessiblePaths, inaccessibleIds, searchBlocksBudget)),
limit,
returnedCount: page.length,
hasMore,
@@ -1895,6 +1973,21 @@ export class PaperclipRunnerToolAuthority {
...(this.binding.museRuntime ? { authorizingUserId: this.binding.externalAuthorizingUserId } : {}) };
}
#channelActor(context: {
run: { responsibleUserId: string | null };
actor: { name: string; role: string };
}) {
return buildRunnerChannelActor({
companyId: this.binding.companyId,
agentId: this.binding.agentId,
agentName: context.actor.name,
agentRole: context.actor.role,
responsibleUserId: context.run.responsibleUserId,
museRuntime: this.binding.museRuntime,
externalAuthorizingUserId: this.binding.externalAuthorizingUserId,
});
}
async #boundContext(options: { includeChatWake?: boolean; tool?: string } = {}) {
if (this.binding.museRuntime && !this.binding.externalAuthorizingUserId) throw forbidden("Muse authorizer is unavailable");
const [row] = await this.db.select({ issue: issues, actor: agents, run: {
@@ -2010,12 +2103,18 @@ export class PaperclipRunnerToolAuthority {
const body = typeof input.body === "string" ? input.body.trim() : "";
const idempotencyKey = typeof input.idempotencyKey === "string" ? input.idempotencyKey.trim() : "";
if (!body || !idempotencyKey) throw new Error("paperclip_runner_tool_input_invalid");
const kvLabels = normalizeRunnerKvLabelsInput(input.kvLabels);
let publication: Awaited<ReturnType<typeof persistActivity>>["publication"] | null = null;
const result = await this.#withMutationReceipt(
"report_progress",
idempotencyKey,
input,
async (tx, context) => {
const validatedBlocks = await collectAndValidateProgressSchemaBlocks(
tx,
this.binding.companyId,
{ explicitBlocks: input.schemaBlocks, body },
);
const sourceTrust = this.binding.museRuntime ? await resolveActorSourceTrustForIssue({ db: tx, issue: context.issue,
actor: { actorType: "agent", actorId: this.binding.agentId, agentId: this.binding.agentId, runId: this.binding.runId } }) : undefined;
const comment = await issueService(tx).addComment(
@@ -2025,6 +2124,14 @@ export class PaperclipRunnerToolAuthority {
{ authorizationReason: "paperclip_runner_protocol", sourceTrust },
tx,
);
await tx
.update(issueComments)
.set({
actorProfile: context.actor.name,
...(Object.keys(kvLabels).length > 0 ? { kvLabels } : {}),
...(validatedBlocks.length > 0 ? { schemaBlocks: validatedBlocks } : {}),
})
.where(and(eq(issueComments.id, comment.id), eq(issueComments.companyId, this.binding.companyId)));
const result = { commentId: comment.id, issueId: this.binding.issueId, disposition: "applied" };
const activity = await persistActivity(tx, {
companyId: this.binding.companyId,
@@ -2139,6 +2246,9 @@ export class PaperclipRunnerToolAuthority {
const blockedByIssueIds = Array.isArray(input.blockedByTaskIds)
? input.blockedByTaskIds.map(requiredString)
: [];
const kvLabels = normalizeRunnerKvLabelsInput(input.kvLabels);
const rawResultSchemaRef = nullableProviderId(input.resultSchemaRef);
const rawChannel = nullableProviderId(input.channel);
const durableIdempotencyKey =
`paperclip-runner:create-task:${this.binding.issueId}:${idempotencyKey}`;
const inputFingerprint = createHash("sha256")
@@ -2163,6 +2273,12 @@ export class PaperclipRunnerToolAuthority {
issue: typeof issues.$inferSelect;
actor: typeof agents.$inferSelect;
}) => {
const resolvedResultSchemaRef = rawResultSchemaRef
? await assertSchemaExists(tx, this.binding.companyId, rawResultSchemaRef)
: null;
const authorizedChannel = rawChannel
? await authorizeRunnerTaskChannel(tx, this.binding.companyId, this.#channelActor(context), rawChannel)
: null;
// Default parent: the current task, or none from a conversation. An
// explicit parentTaskId names another task the run may read and change
// (for example a top-level task this conversation just created).
@@ -2215,7 +2331,14 @@ export class PaperclipRunnerToolAuthority {
}
}
}
const projectId = nullableProviderId(input.projectId) ?? parentProjectId;
const channelDefaultProjectId =
authorizedChannel?.kind === "existing"
? authorizedChannel.channel.defaultProjectId
: null;
const projectId =
nullableProviderId(input.projectId) ??
parentProjectId ??
channelDefaultProjectId;
if (this.binding.museRuntime && projectId) {
const access = await authorizationService(tx).decide({ actor: this.#privacyActor(context.run), action: "project:read",
resource: { type: "project", companyId: this.binding.companyId, projectId } });
@@ -2239,11 +2362,30 @@ export class PaperclipRunnerToolAuthority {
run: { companyId: this.binding.companyId, executionPolicy: context.run.contextSnapshot?.executionPolicy },
});
if (trust.kind === "denied") throw forbidden(trust.detail);
return { projectId, trust, parentIssueId, placedParentId, parentDepthPolicy, workspaceSourceIssueId };
return {
projectId,
trust,
parentIssueId,
placedParentId,
parentDepthPolicy,
workspaceSourceIssueId,
resolvedResultSchemaRef,
authorizedChannel,
};
};
let publication: Awaited<ReturnType<typeof persistActivity>>["publication"] | null = null;
const result = await this.#withMutationReceipt("create_task", idempotencyKey, input, async (tx, context) => {
const { projectId, trust, parentIssueId, placedParentId, parentDepthPolicy, workspaceSourceIssueId } = await authorizeCreate(tx, context);
const {
projectId,
trust,
parentIssueId,
placedParentId,
parentDepthPolicy,
workspaceSourceIssueId,
resolvedResultSchemaRef,
authorizedChannel,
} = await authorizeCreate(tx, context);
const channelActor = this.#channelActor(context);
const existingChild = await tx.select().from(issues).where(and(
eq(issues.companyId, this.binding.companyId),
eq(issues.originId, durableIdempotencyKey),
@@ -2252,6 +2394,12 @@ export class PaperclipRunnerToolAuthority {
if (existingChild.originFingerprint !== inputFingerprint) {
throw new Error("paperclip_runner_tool_idempotency_conflict");
}
const { accessiblePaths } = await resolveAccessibleTaskChannelPaths(
tx,
this.binding.companyId,
channelActor,
[existingChild.channelId],
);
return {
commandId: `create-task:${existingChild.id}`,
disposition: "duplicate",
@@ -2262,12 +2410,20 @@ export class PaperclipRunnerToolAuthority {
id: existingChild.id,
identifier: existingChild.identifier,
parentId: existingChild.parentId,
projectId: existingChild.projectId,
channelId: existingChild.channelId ?? null,
channelPath: existingChild.channelId ? (accessiblePaths.get(existingChild.channelId) ?? null) : null,
kvLabels: existingChild.kvLabels ?? {},
resultSchemaRef: existingChild.resultSchemaRef ?? null,
status: existingChild.status,
assigneeActorId: existingChild.assigneeAgentId,
assigneeUserId: existingChild.assigneeUserId,
},
};
}
const resolvedChannel = authorizedChannel
? await materializeRunnerTaskChannel(tx, this.binding.companyId, channelActor, authorizedChannel)
: null;
let deduplicated = false;
const issueId = randomUUID();
const createInput = {
@@ -2301,8 +2457,15 @@ export class PaperclipRunnerToolAuthority {
parentDepthPolicy,
...(parentIssueId ? { expectedParentId: placedParentId } : {}),
...(workspaceSourceIssueId ? { inheritExecutionWorkspaceFromIssueId: workspaceSourceIssueId } : {}),
...(context.issue.conversationAgentId && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}),
...(resolvedChannel
? { channelId: resolvedChannel.id, scope: "channel" as const }
: context.issue.conversationAgentId && !parentIssueId
? { scope: "board" as const, isExplicitBoardHandoff: true }
: {}),
...(Object.keys(kvLabels).length > 0 ? { kvLabels } : {}),
...(resolvedResultSchemaRef ? { resultSchemaRef: resolvedResultSchemaRef } : {}),
createdByAgentId: this.binding.agentId,
createdByProfile: context.actor.name,
originKind: "manual" as const,
originId: durableIdempotencyKey,
originRunId: this.binding.runId,
@@ -2320,6 +2483,23 @@ export class PaperclipRunnerToolAuthority {
if (deduplicated && child.originFingerprint !== inputFingerprint) {
throw new Error("paperclip_runner_tool_idempotency_conflict");
}
if (!deduplicated && resolvedChannel) {
const now = new Date();
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, resolvedChannel.id));
if (resolvedChannel.visibility === "private" && child.visibility !== "private") {
await tx
.update(issues)
.set({
visibility: "private",
privacyRootIssueId: child.privacyRootIssueId ?? child.id,
updatedAt: now,
})
.where(and(eq(issues.id, child.id), eq(issues.companyId, this.binding.companyId)));
}
}
let childStatus = child.status;
let childStatusVersion = child.statusVersion;
if (child.status === "blocked" && blockedByIssueIds.length > 0) {
@@ -2342,10 +2522,21 @@ export class PaperclipRunnerToolAuthority {
action: "issue.created", entityType: "issue", entityId: child.id,
details: { identifier: child.identifier, title: child.title, parentId: child.parentId,
assigneeAgentId: child.assigneeAgentId, assigneeUserId: child.assigneeUserId, status: childStatus, source: "paperclip_runner_protocol",
...(resolvedChannel ? { channel: resolvedChannel.path } : {}),
...("parentAdjusted" in child && child.parentAdjusted ? { parentAdjusted: child.parentAdjusted } : {}) },
});
publication = activity.publication;
}
let fallbackChannelPath: string | null = null;
if (!resolvedChannel && child.channelId) {
const { accessiblePaths } = await resolveAccessibleTaskChannelPaths(
tx,
this.binding.companyId,
channelActor,
[child.channelId],
);
fallbackChannelPath = accessiblePaths.get(child.channelId) ?? null;
}
const wakeId = `created-child:${child.id}`;
const shouldWake = !deduplicated && childStatus === "todo" && Boolean(child.assigneeAgentId);
return {
@@ -2359,6 +2550,10 @@ export class PaperclipRunnerToolAuthority {
identifier: child.identifier,
parentId: child.parentId,
projectId: child.projectId,
channelId: resolvedChannel?.id ?? child.channelId ?? null,
channelPath: resolvedChannel?.path ?? fallbackChannelPath,
kvLabels: Object.keys(kvLabels).length > 0 ? kvLabels : (child.kvLabels ?? {}),
resultSchemaRef: resolvedResultSchemaRef ?? child.resultSchemaRef ?? null,
status: childStatus,
assigneeActorId: child.assigneeAgentId,
assigneeUserId: child.assigneeUserId,
@@ -3555,7 +3750,20 @@ function redactedActor(actor: {
};
}
function redactedTask(task: typeof issues.$inferSelect) {
function redactedTask(
task: typeof issues.$inferSelect,
accessibleChannelPaths?: ReadonlyMap<string, string>,
inaccessibleChannelIds?: ReadonlySet<string>,
responseBudget?: SchemaBlocksResponseBudget,
) {
const channelId =
task.channelId && inaccessibleChannelIds?.has(task.channelId)
? null
: (task.channelId ?? null);
const channelPath =
channelId && accessibleChannelPaths
? (accessibleChannelPaths.get(channelId) ?? null)
: null;
return {
id: task.id,
url: publicChatTaskUrl(task.id),
@@ -3577,5 +3785,13 @@ function redactedTask(task: typeof issues.$inferSelect) {
parentId: task.parentId,
projectId: task.projectId,
goalId: task.goalId,
channelId,
channelPath,
kvLabels: task.kvLabels ?? {},
resultSchemaRef: task.resultSchemaRef ?? null,
...projectBoundedSchemaBlocks(task.schemaBlocks, {
responseBudget,
fullReadHint: `Use call_api with GET /api/issues/${task.id} to read all saved schemaBlocks on this task.`,
}),
};
}
+3 -1
View File
@@ -148,6 +148,8 @@ Use comments incrementally:
Read enough ancestor/comment context to understand _why_ the task exists and what changed. Do not reflexively reload the whole thread on every heartbeat.
Tasks and comments may also include `kvLabels` (key-value metadata), `channelPath` (when filed in an accessible channel), `schemaBlocks` (validated `<name>@<version>` JSON blocks), and `resultSchemaRef` (a required completion schema). For atomic compare-and-swap label updates, use `PATCH /api/issues/{issueId}/kv-labels` (`{ "set": { "k": "v" }, "unset": ["old"], "if": { "k": null } }`).
**Execution-policy review/approval wakes.** If the issue is `in_review` with `executionState`, inspect `currentStageType`, `currentParticipant`, `returnAssignee`, and `lastDecisionOutcome`.
If `currentParticipant` matches you, submit your decision via the normal update route — there is no separate execution-decision endpoint:
@@ -224,7 +226,7 @@ Before exiting, persist the appropriate waiting path: a saved pending interactio
Before ending any heartbeat, apply this final-disposition checklist:
- `done`: the requested work is complete, verification is recorded, and no follow-up remains on this issue.
- `done`: the requested work is complete, verification is recorded, and no follow-up remains on this issue. When `resultSchemaRef` is set on the task (for example `test-report@1`), include a valid ```` ```json schema=test-report@1 ```` block (matching `GET /api/companies/{companyId}/schemas/{ref}`) in a comment before marking the task `done`.
- `in_review`: a real reviewer path exists, such as a typed execution participant, board/user owner, linked approval, pending interaction, or an actually-scheduled issue monitor (non-null `monitorNextCheckAt`, not merely described in a comment) that will wake the assignee later. Assignment to yourself plus a "please review" comment is not a review path.
- `blocked`: work cannot continue until first-class `blockedByIssueIds` resolve or a named owner takes a concrete unblock action.
- If work is delegated, use blockers when the current issue must wait for that work. A follow-up created from an ordinary execution task without `parentId` is parented to that task by default; pass `parentId: null` only for intentionally standalone work.