Merge branch 'master' into feat/evals-promptfoo-bootstrap

This commit is contained in:
Dotta
2026-03-21 07:28:51 -05:00
committed by GitHub
578 changed files with 225878 additions and 5400 deletions

View File

@@ -0,0 +1,269 @@
---
name: company-creator
description: >
Create agent company packages conforming to the Agent Companies specification
(agentcompanies/v1). Use when a user wants to create a new agent company from
scratch, build a company around an existing git repo or skills collection, or
scaffold a team/department of agents. Triggers on: "create a company", "make me
a company", "build a company from this repo", "set up an agent company",
"create a team of agents", "hire some agents", or when given a repo URL and
asked to turn it into a company. Do NOT use for importing an existing company
package (use the CLI import command instead) or for modifying a company that
is already running in Paperclip.
---
# Company Creator
Create agent company packages that conform to the Agent Companies specification.
Spec references:
- Normative spec: `docs/companies/companies-spec.md` (read this before generating files)
- Web spec: https://agentcompanies.io/specification
- Protocol site: https://agentcompanies.io/
## Two Modes
### Mode 1: Company From Scratch
The user describes what they want. Interview them to flesh out the vision, then generate the package.
### Mode 2: Company From a Repo
The user provides a git repo URL, local path, or tweet. Analyze the repo, then create a company that wraps it.
See [references/from-repo-guide.md](references/from-repo-guide.md) for detailed repo analysis steps.
## Process
### Step 1: Gather Context
Determine which mode applies:
- **From scratch**: What kind of company or team? What domain? What should the agents do?
- **From repo**: Clone/read the repo. Scan for existing skills, agent configs, README, source structure.
### Step 2: Interview (Use AskUserQuestion)
Do not skip this step. Use AskUserQuestion to align with the user before writing any files.
**For from-scratch companies**, ask about:
- Company purpose and domain (1-2 sentences is fine)
- What agents they need - propose a hiring plan based on what they described
- Whether this is a full company (needs a CEO) or a team/department (no CEO required)
- Any specific skills the agents should have
- How work flows through the organization (see "Workflow" below)
- Whether they want projects and starter tasks
**For from-repo companies**, present your analysis and ask:
- Confirm the agents you plan to create and their roles
- Whether to reference or vendor any discovered skills (default: reference)
- Any additional agents or skills beyond what the repo provides
- Company name and any customization
- Confirm the workflow you inferred from the repo (see "Workflow" below)
**Workflow — how does work move through this company?**
A company is not just a list of agents with skills. It's an organization that takes ideas and turns them into work products. You need to understand the workflow so each agent knows:
- Who gives them work and in what form (a task, a branch, a question, a review request)
- What they do with it
- Who they hand off to when they're done, and what that handoff looks like
- What "done" means for their role
**Not every company is a pipeline.** Infer the right workflow pattern from context:
- **Pipeline** — sequential stages, each agent hands off to the next. Use when the repo/domain has a clear linear process (e.g. plan → build → review → ship → QA, or content ideation → draft → edit → publish).
- **Hub-and-spoke** — a manager delegates to specialists who report back independently. Use when agents do different kinds of work that don't feed into each other (e.g. a CEO who dispatches to a researcher, a marketer, and an analyst).
- **Collaborative** — agents work together on the same things as peers. Use for small teams where everyone contributes to the same output (e.g. a design studio, a brainstorming team).
- **On-demand** — agents are summoned as needed with no fixed flow. Use when agents are more like a toolbox of specialists the user calls directly.
For from-scratch companies, propose a workflow pattern based on what they described and ask if it fits.
For from-repo companies, infer the pattern from the repo's structure. If skills have a clear sequential dependency (like `plan-ceo-review → plan-eng-review → review → ship → qa`), that's a pipeline. If skills are independent capabilities, it's more likely hub-and-spoke or on-demand. State your inference in the interview so the user can confirm or adjust.
**Key interviewing principles:**
- Propose a concrete hiring plan. Don't ask open-ended "what agents do you want?" - suggest specific agents based on context and let the user adjust.
- Keep it lean. Most users are new to agent companies. A few agents (3-5) is typical for a startup. Don't suggest 10+ agents unless the scope demands it.
- From-scratch companies should start with a CEO who manages everyone. Teams/departments don't need one.
- Ask 2-3 focused questions per round, not 10.
### Step 3: Read the Spec
Before generating any files, read the normative spec:
```
docs/companies/companies-spec.md
```
Also read the quick reference: [references/companies-spec.md](references/companies-spec.md)
And the example: [references/example-company.md](references/example-company.md)
### Step 4: Generate the Package
Create the directory structure and all files. Follow the spec's conventions exactly.
**Directory structure:**
```
<company-slug>/
├── COMPANY.md
├── agents/
│ └── <slug>/AGENTS.md
├── teams/
│ └── <slug>/TEAM.md (if teams are needed)
├── projects/
│ └── <slug>/PROJECT.md (if projects are needed)
├── tasks/
│ └── <slug>/TASK.md (if tasks are needed)
├── skills/
│ └── <slug>/SKILL.md (if custom skills are needed)
└── .paperclip.yaml (Paperclip vendor extension)
```
**Rules:**
- Slugs must be URL-safe, lowercase, hyphenated
- COMPANY.md gets `schema: agentcompanies/v1` - other files inherit it
- Agent instructions go in the AGENTS.md body, not in .paperclip.yaml
- Skills referenced by shortname in AGENTS.md resolve to `skills/<shortname>/SKILL.md`
- For external skills, use `sources` with `usage: referenced` (see spec section 12)
- Do not export secrets, machine-local paths, or database IDs
- Omit empty/default fields
- For companies generated from a repo, add a references footer at the bottom of COMPANY.md body:
`Generated from [repo-name](repo-url) with the company-creator skill from [Paperclip](https://github.com/paperclipai/paperclip)`
**Reporting structure:**
- Every agent except the CEO should have `reportsTo` set to their manager's slug
- The CEO has `reportsTo: null`
- For teams without a CEO, the top-level agent has `reportsTo: null`
**Writing workflow-aware agent instructions:**
Each AGENTS.md body should include not just what the agent does, but how they fit into the organization's workflow. Include:
1. **Where work comes from** — "You receive feature ideas from the user" or "You pick up tasks assigned to you by the CTO"
2. **What you produce** — "You produce a technical plan with architecture diagrams" or "You produce a reviewed, approved branch ready for shipping"
3. **Who you hand off to** — "When your plan is locked, hand off to the Staff Engineer for implementation" or "When review passes, hand off to the Release Engineer to ship"
4. **What triggers you** — "You are activated when a new feature idea needs product-level thinking" or "You are activated when a branch is ready for pre-landing review"
This turns a collection of agents into an organization that actually works together. Without workflow context, agents operate in isolation — they do their job but don't know what happens before or after them.
### Step 5: Confirm Output Location
Ask the user where to write the package. Common options:
- A subdirectory in the current repo
- A new directory the user specifies
- The current directory (if it's empty or they confirm)
### Step 6: Write README.md and LICENSE
**README.md** — every company package gets a README. It should be a nice, readable introduction that someone browsing GitHub would appreciate. Include:
- Company name and what it does
- The workflow / how the company operates
- Org chart as a markdown list or table showing agents, titles, reporting structure, and skills
- Brief description of each agent's role
- Citations and references: link to the source repo (if from-repo), link to the Agent Companies spec (https://agentcompanies.io/specification), and link to Paperclip (https://github.com/paperclipai/paperclip)
- A "Getting Started" section explaining how to import: `paperclipai company import --from <path>`
**LICENSE** — include a LICENSE file. The copyright holder is the user creating the company, not the upstream repo author (they made the skills, the user is making the company). Use the same license type as the source repo (if from-repo) or ask the user (if from-scratch). Default to MIT if unclear.
### Step 7: Write Files and Summarize
Write all files, then give a brief summary:
- Company name and what it does
- Agent roster with roles and reporting structure
- Skills (custom + referenced)
- Projects and tasks if any
- The output path
## .paperclip.yaml Guidelines
The `.paperclip.yaml` file is the Paperclip vendor extension. It configures adapters and env inputs per agent.
### Adapter Rules
**Do not specify an adapter unless the repo or user context warrants it.** If you don't know what adapter the user wants, omit the adapter block entirely — Paperclip will use its default. Specifying an unknown adapter type causes an import error.
Paperclip's supported adapter types (these are the ONLY valid values):
- `claude_local` — Claude Code CLI
- `codex_local` — Codex CLI
- `opencode_local` — OpenCode CLI
- `pi_local` — Pi CLI
- `cursor` — Cursor
- `gemini_local` — Gemini CLI
- `openclaw_gateway` — OpenClaw gateway
Only set an adapter when:
- The repo or its skills clearly target a specific runtime (e.g. gstack is built for Claude Code, so `claude_local` is appropriate)
- The user explicitly requests a specific adapter
- The agent's role requires a specific runtime capability
### Env Inputs Rules
**Do not add boilerplate env variables.** Only add env inputs that the agent actually needs based on its skills or role:
- `GH_TOKEN` for agents that push code, create PRs, or interact with GitHub
- API keys only when a skill explicitly requires them
- Never set `ANTHROPIC_API_KEY` as a default empty env variable — the runtime handles this
Example with adapter (only when warranted):
```yaml
schema: paperclip/v1
agents:
release-engineer:
adapter:
type: claude_local
config:
model: claude-sonnet-4-6
inputs:
env:
GH_TOKEN:
kind: secret
requirement: optional
```
Example — only agents with actual overrides appear:
```yaml
schema: paperclip/v1
agents:
release-engineer:
inputs:
env:
GH_TOKEN:
kind: secret
requirement: optional
```
In this example, only `release-engineer` appears because it needs `GH_TOKEN`. The other agents (ceo, cto, etc.) have no overrides, so they are omitted entirely from `.paperclip.yaml`.
## External Skill References
When referencing skills from a GitHub repo, always use the references pattern:
```yaml
metadata:
sources:
- kind: github-file
repo: owner/repo
path: path/to/SKILL.md
commit: <full SHA from git ls-remote or the repo>
attribution: Owner or Org Name
license: <from the repo's LICENSE>
usage: referenced
```
Get the commit SHA with:
```bash
git ls-remote https://github.com/owner/repo HEAD
```
Do NOT copy external skill content into the package unless the user explicitly asks.

View File

@@ -0,0 +1,144 @@
# Agent Companies Specification Reference
The normative specification lives at:
- Web: https://agentcompanies.io/specification
- Local: docs/companies/companies-spec.md
Read the local spec file before generating any package files. The spec defines the canonical format and all frontmatter fields. Below is a quick-reference summary for common authoring tasks.
## Package Kinds
| File | Kind | Purpose |
| ---------- | ------- | ------------------------------------------------- |
| COMPANY.md | company | Root entrypoint, org boundary and defaults |
| TEAM.md | team | Reusable org subtree |
| AGENTS.md | agent | One role, instructions, and attached skills |
| PROJECT.md | project | Planned work grouping |
| TASK.md | task | Portable starter task |
| SKILL.md | skill | Agent Skills capability package (do not redefine) |
## Directory Layout
```
company-package/
├── COMPANY.md
├── agents/
│ └── <slug>/AGENTS.md
├── teams/
│ └── <slug>/TEAM.md
├── projects/
│ └── <slug>/
│ ├── PROJECT.md
│ └── tasks/
│ └── <slug>/TASK.md
├── tasks/
│ └── <slug>/TASK.md
├── skills/
│ └── <slug>/SKILL.md
├── assets/
├── scripts/
├── references/
└── .paperclip.yaml (optional vendor extension)
```
## Common Frontmatter Fields
```yaml
schema: agentcompanies/v1
kind: company | team | agent | project | task
slug: url-safe-stable-identity
name: Human Readable Name
description: Short description for discovery
version: 0.1.0
license: MIT
authors:
- name: Jane Doe
tags: []
metadata: {}
sources: []
```
- `schema` usually appears only at package root
- `kind` is optional when filename makes it obvious
- `slug` must be URL-safe and stable
- exporters should omit empty or default-valued fields
## COMPANY.md Required Fields
```yaml
name: Company Name
description: What this company does
slug: company-slug
schema: agentcompanies/v1
```
Optional: `version`, `license`, `authors`, `goals`, `includes`, `requirements.secrets`
## AGENTS.md Key Fields
```yaml
name: Agent Name
title: Role Title
reportsTo: <agent-slug or null>
skills:
- skill-shortname
```
- Body content is the agent's default instructions
- Skills resolve by shortname: `skills/<shortname>/SKILL.md`
- Do not export machine-specific paths or secrets
## TEAM.md Key Fields
```yaml
name: Team Name
description: What this team does
slug: team-slug
manager: ../agent-slug/AGENTS.md
includes:
- ../agent-slug/AGENTS.md
- ../../skills/skill-slug/SKILL.md
```
## PROJECT.md Key Fields
```yaml
name: Project Name
description: What this project delivers
owner: agent-slug
```
## TASK.md Key Fields
```yaml
name: Task Name
assignee: agent-slug
project: project-slug
schedule:
timezone: America/Chicago
startsAt: 2026-03-16T09:00:00-05:00
recurrence:
frequency: weekly
interval: 1
weekdays: [monday]
time: { hour: 9, minute: 0 }
```
## Source References (for external skills/content)
```yaml
sources:
- kind: github-file
repo: owner/repo
path: path/to/SKILL.md
commit: <full-sha>
sha256: <hash>
attribution: Owner Name
license: MIT
usage: referenced
```
Usage modes: `vendored` (bytes included), `referenced` (pointer only), `mirrored` (cached locally)
Default to `referenced` for third-party content.

View File

@@ -0,0 +1,184 @@
# Example Company Package
A minimal but complete example of an agent company package.
## Directory Structure
```
lean-dev-shop/
├── COMPANY.md
├── agents/
│ ├── ceo/AGENTS.md
│ ├── cto/AGENTS.md
│ └── engineer/AGENTS.md
├── teams/
│ └── engineering/TEAM.md
├── projects/
│ └── q2-launch/
│ ├── PROJECT.md
│ └── tasks/
│ └── monday-review/TASK.md
├── tasks/
│ └── weekly-standup/TASK.md
├── skills/
│ └── code-review/SKILL.md
└── .paperclip.yaml
```
## COMPANY.md
```markdown
---
name: Lean Dev Shop
description: Small engineering-focused AI company that builds and ships software products
slug: lean-dev-shop
schema: agentcompanies/v1
version: 1.0.0
license: MIT
authors:
- name: Example Org
goals:
- Build and ship software products
- Maintain high code quality
---
Lean Dev Shop is a small, focused engineering company. The CEO oversees strategy and coordinates work. The CTO leads the engineering team. Engineers build and ship code.
```
## agents/ceo/AGENTS.md
```markdown
---
name: CEO
title: Chief Executive Officer
reportsTo: null
skills:
- paperclip
---
You are the CEO of Lean Dev Shop. You oversee company strategy, coordinate work across the team, and ensure projects ship on time.
Your responsibilities:
- Review and prioritize work across projects
- Coordinate with the CTO on technical decisions
- Ensure the company goals are being met
```
## agents/cto/AGENTS.md
```markdown
---
name: CTO
title: Chief Technology Officer
reportsTo: ceo
skills:
- code-review
- paperclip
---
You are the CTO of Lean Dev Shop. You lead the engineering team and make technical decisions.
Your responsibilities:
- Set technical direction and architecture
- Review code and ensure quality standards
- Mentor engineers and unblock technical challenges
```
## agents/engineer/AGENTS.md
```markdown
---
name: Engineer
title: Software Engineer
reportsTo: cto
skills:
- code-review
- paperclip
---
You are a software engineer at Lean Dev Shop. You write code, fix bugs, and ship features.
Your responsibilities:
- Implement features and fix bugs
- Write tests and documentation
- Participate in code reviews
```
## teams/engineering/TEAM.md
```markdown
---
name: Engineering
description: Product and platform engineering team
slug: engineering
schema: agentcompanies/v1
manager: ../../agents/cto/AGENTS.md
includes:
- ../../agents/engineer/AGENTS.md
- ../../skills/code-review/SKILL.md
tags:
- engineering
---
The engineering team builds and maintains all software products.
```
## projects/q2-launch/PROJECT.md
```markdown
---
name: Q2 Launch
description: Ship the Q2 product launch
slug: q2-launch
owner: cto
---
Deliver all features planned for the Q2 launch, including the new dashboard and API improvements.
```
## projects/q2-launch/tasks/monday-review/TASK.md
```markdown
---
name: Monday Review
assignee: ceo
project: q2-launch
schedule:
timezone: America/Chicago
startsAt: 2026-03-16T09:00:00-05:00
recurrence:
frequency: weekly
interval: 1
weekdays:
- monday
time:
hour: 9
minute: 0
---
Review the status of Q2 Launch project. Check progress on all open tasks, identify blockers, and update priorities for the week.
```
## skills/code-review/SKILL.md (with external reference)
```markdown
---
name: code-review
description: Thorough code review skill for pull requests and diffs
metadata:
sources:
- kind: github-file
repo: anthropics/claude-code
path: skills/code-review/SKILL.md
commit: abc123def456
sha256: 3b7e...9a
attribution: Anthropic
license: MIT
usage: referenced
---
Review code changes for correctness, style, and potential issues.
```

View File

@@ -0,0 +1,79 @@
# Creating a Company From an Existing Repository
When a user provides a git repo (URL, local path, or tweet linking to a repo), analyze it and create a company package that wraps its content.
## Analysis Steps
1. **Clone or read the repo** - Use `git clone` for URLs, read directly for local paths
2. **Scan for existing agent/skill files** - Look for SKILL.md, AGENTS.md, CLAUDE.md, .claude/ directories, or similar agent configuration
3. **Understand the repo's purpose** - Read README, package.json, main source files to understand what the project does
4. **Identify natural agent roles** - Based on the repo's structure and purpose, determine what agents would be useful
## Handling Existing Skills
Many repos already contain skills (SKILL.md files). When you find them:
**Default behavior: use references, not copies.**
Instead of copying skill content into your company package, create a source reference:
```yaml
metadata:
sources:
- kind: github-file
repo: owner/repo
path: path/to/SKILL.md
commit: <get the current HEAD commit SHA>
attribution: <repo owner or org name>
license: <from repo's LICENSE file>
usage: referenced
```
To get the commit SHA:
```bash
git ls-remote https://github.com/owner/repo HEAD
```
Only vendor (copy) skills when:
- The user explicitly asks to copy them
- The skill is very small and tightly coupled to the company
- The source repo is private or may become unavailable
## Handling Existing Agent Configurations
If the repo has agent configs (CLAUDE.md, .claude/ directories, codex configs, etc.):
- Use them as inspiration for AGENTS.md instructions
- Don't copy them verbatim - adapt them to the Agent Companies format
- Preserve the intent and key instructions
## Repo-Only Skills (No Agents)
When a repo contains only skills and no agents:
- Create agents that would naturally use those skills
- The agents should be minimal - just enough to give the skills a runtime context
- A single agent may use multiple skills from the repo
- Name agents based on the domain the skills cover
Example: A repo with `code-review`, `testing`, and `deployment` skills might become:
- A "Lead Engineer" agent with all three skills
- Or separate "Reviewer", "QA Engineer", and "DevOps" agents if the skills are distinct enough
## Common Repo Patterns
### Developer Tools / CLI repos
- Create agents for the tool's primary use cases
- Reference any existing skills
- Add a project maintainer or lead agent
### Library / Framework repos
- Create agents for development, testing, documentation
- Skills from the repo become agent capabilities
### Full Application repos
- Map to departments: engineering, product, QA
- Create a lean team structure appropriate to the project size
### Skills Collection repos (e.g. skills.sh repos)
- Each skill or skill group gets an agent
- Create a lightweight company or team wrapper
- Keep the agent count proportional to the skill diversity

View File

@@ -0,0 +1,201 @@
---
name: doc-maintenance
description: >
Audit top-level documentation (README, SPEC, PRODUCT) against recent git
history to find drift — shipped features missing from docs or features
listed as upcoming that already landed. Proposes minimal edits, creates
a branch, and opens a PR. Use when asked to review docs for accuracy,
after major feature merges, or on a periodic schedule.
---
# Doc Maintenance Skill
Detect documentation drift and fix it via PR — no rewrites, no churn.
## When to Use
- Periodic doc review (e.g. weekly or after releases)
- After major feature merges
- When asked "are our docs up to date?"
- When asked to audit README / SPEC / PRODUCT accuracy
## Target Documents
| Document | Path | What matters |
|----------|------|-------------|
| README | `README.md` | Features table, roadmap, quickstart, "what is" accuracy, "works with" table |
| SPEC | `doc/SPEC.md` | No false "not supported" claims, major model/schema accuracy |
| PRODUCT | `doc/PRODUCT.md` | Core concepts, feature list, principles accuracy |
Out of scope: DEVELOPING.md, DATABASE.md, CLI.md, doc/plans/, skill files,
release notes. These are dev-facing or ephemeral — lower risk of user-facing
confusion.
## Workflow
### Step 1 — Detect what changed
Find the last review cursor:
```bash
# Read the last-reviewed commit SHA
CURSOR_FILE=".doc-review-cursor"
if [ -f "$CURSOR_FILE" ]; then
LAST_SHA=$(cat "$CURSOR_FILE" | head -1)
else
# First run: look back 60 days
LAST_SHA=$(git log --format="%H" --after="60 days ago" --reverse | head -1)
fi
```
Then gather commits since the cursor:
```bash
git log "$LAST_SHA"..HEAD --oneline --no-merges
```
### Step 2 — Classify changes
Scan commit messages and changed files. Categorize into:
- **Feature** — new capabilities (keywords: `feat`, `add`, `implement`, `support`)
- **Breaking** — removed/renamed things (keywords: `remove`, `breaking`, `drop`, `rename`)
- **Structural** — new directories, config changes, new adapters, new CLI commands
**Ignore:** refactors, test-only changes, CI config, dependency bumps, doc-only
changes, style/formatting commits. These don't affect doc accuracy.
For borderline cases, check the actual diff — a commit titled "refactor: X"
that adds a new public API is a feature.
### Step 3 — Build a change summary
Produce a concise list like:
```
Since last review (<sha>, <date>):
- FEATURE: Plugin system merged (runtime, SDK, CLI, slots, event bridge)
- FEATURE: Project archiving added
- BREAKING: Removed legacy webhook adapter
- STRUCTURAL: New .agents/skills/ directory convention
```
If there are no notable changes, skip to Step 7 (update cursor and exit).
### Step 4 — Audit each target doc
For each target document, read it fully and cross-reference against the change
summary. Check for:
1. **False negatives** — major shipped features not mentioned at all
2. **False positives** — features listed as "coming soon" / "roadmap" / "planned"
/ "not supported" / "TBD" that already shipped
3. **Quickstart accuracy** — install commands, prereqs, and startup instructions
still correct (README only)
4. **Feature table accuracy** — does the features section reflect current
capabilities? (README only)
5. **Works-with accuracy** — are supported adapters/integrations listed correctly?
Use `references/audit-checklist.md` as the structured checklist.
Use `references/section-map.md` to know where to look for each feature area.
### Step 5 — Create branch and apply minimal edits
```bash
# Create a branch for the doc updates
BRANCH="docs/maintenance-$(date +%Y%m%d)"
git checkout -b "$BRANCH"
```
Apply **only** the edits needed to fix drift. Rules:
- **Minimal patches only.** Fix inaccuracies, don't rewrite sections.
- **Preserve voice and style.** Match the existing tone of each document.
- **No cosmetic changes.** Don't fix typos, reformat tables, or reorganize
sections unless they're part of a factual fix.
- **No new sections.** If a feature needs a whole new section, note it in the
PR description as a follow-up — don't add it in a maintenance pass.
- **Roadmap items:** Move shipped features out of Roadmap. Add a brief mention
in the appropriate existing section if there isn't one already. Don't add
long descriptions.
### Step 6 — Open a PR
Commit the changes and open a PR:
```bash
git add README.md doc/SPEC.md doc/PRODUCT.md .doc-review-cursor
git commit -m "docs: update documentation for accuracy
- [list each fix briefly]
Co-Authored-By: Paperclip <noreply@paperclip.ing>"
git push -u origin "$BRANCH"
gh pr create \
--title "docs: periodic documentation accuracy update" \
--body "$(cat <<'EOF'
## Summary
Automated doc maintenance pass. Fixes documentation drift detected since
last review.
### Changes
- [list each fix]
### Change summary (since last review)
- [list notable code changes that triggered doc updates]
## Review notes
- Only factual accuracy fixes — no style/cosmetic changes
- Preserves existing voice and structure
- Larger doc additions (new sections, tutorials) noted as follow-ups
🤖 Generated by doc-maintenance skill
EOF
)"
```
### Step 7 — Update the cursor
After a successful audit (whether or not edits were needed), update the cursor:
```bash
git rev-parse HEAD > .doc-review-cursor
```
If edits were made, this is already committed in the PR branch. If no edits
were needed, commit the cursor update to the current branch.
## Change Classification Rules
| Signal | Category | Doc update needed? |
|--------|----------|-------------------|
| `feat:`, `add`, `implement`, `support` in message | Feature | Yes if user-facing |
| `remove`, `drop`, `breaking`, `!:` in message | Breaking | Yes |
| New top-level directory or config file | Structural | Maybe |
| `fix:`, `bugfix` | Fix | No (unless it changes behavior described in docs) |
| `refactor:`, `chore:`, `ci:`, `test:` | Maintenance | No |
| `docs:` | Doc change | No (already handled) |
| Dependency bumps only | Maintenance | No |
## Patch Style Guide
- Fix the fact, not the prose
- If removing a roadmap item, don't leave a gap — remove the bullet cleanly
- If adding a feature mention, match the format of surrounding entries
(e.g. if features are in a table, add a table row)
- Keep README changes especially minimal — it shouldn't churn often
- For SPEC/PRODUCT, prefer updating existing statements over adding new ones
(e.g. change "not supported in V1" to "supported via X" rather than adding
a new section)
## Output
When the skill completes, report:
- How many commits were scanned
- How many notable changes were found
- How many doc edits were made (and to which files)
- PR link (if edits were made)
- Any follow-up items that need larger doc work

View File

@@ -0,0 +1,85 @@
# Doc Maintenance Audit Checklist
Use this checklist when auditing each target document. For each item, compare
against the change summary from git history.
## README.md
### Features table
- [ ] Each feature card reflects a shipped capability
- [ ] No feature cards for things that don't exist yet
- [ ] No major shipped features missing from the table
### Roadmap
- [ ] Nothing listed as "planned" or "coming soon" that already shipped
- [ ] No removed/cancelled items still listed
- [ ] Items reflect current priorities (cross-check with recent PRs)
### Quickstart
- [ ] `npx paperclipai onboard` command is correct
- [ ] Manual install steps are accurate (clone URL, commands)
- [ ] Prerequisites (Node version, pnpm version) are current
- [ ] Server URL and port are correct
### "What is Paperclip" section
- [ ] High-level description is accurate
- [ ] Step table (Define goal / Hire team / Approve and run) is correct
### "Works with" table
- [ ] All supported adapters/runtimes are listed
- [ ] No removed adapters still listed
- [ ] Logos and labels match current adapter names
### "Paperclip is right for you if"
- [ ] Use cases are still accurate
- [ ] No claims about capabilities that don't exist
### "Why Paperclip is special"
- [ ] Technical claims are accurate (atomic execution, governance, etc.)
- [ ] No features listed that were removed or significantly changed
### FAQ
- [ ] Answers are still correct
- [ ] No references to removed features or outdated behavior
### Development section
- [ ] Commands are accurate (`pnpm dev`, `pnpm build`, etc.)
- [ ] Link to DEVELOPING.md is correct
## doc/SPEC.md
### Company Model
- [ ] Fields match current schema
- [ ] Governance model description is accurate
### Agent Model
- [ ] Adapter types match what's actually supported
- [ ] Agent configuration description is accurate
- [ ] No features described as "not supported" or "not V1" that shipped
### Task Model
- [ ] Task hierarchy description is accurate
- [ ] Status values match current implementation
### Extensions / Plugins
- [ ] If plugins are shipped, no "not in V1" or "future" language
- [ ] Plugin model description matches implementation
### Open Questions
- [ ] Resolved questions removed or updated
- [ ] No "TBD" items that have been decided
## doc/PRODUCT.md
### Core Concepts
- [ ] Company, Employees, Task Management descriptions accurate
- [ ] Agent Execution modes described correctly
- [ ] No missing major concepts
### Principles
- [ ] Principles haven't been contradicted by shipped features
- [ ] No principles referencing removed capabilities
### User Flow
- [ ] Dream scenario still reflects actual onboarding
- [ ] Steps are achievable with current features

View File

@@ -0,0 +1,22 @@
# Section Map
Maps feature areas to specific document sections so the skill knows where to
look when a feature ships or changes.
| Feature Area | README Section | SPEC Section | PRODUCT Section |
|-------------|---------------|-------------|----------------|
| Plugins / Extensions | Features table, Roadmap | Extensions, Agent Model | Core Concepts |
| Adapters (new runtimes) | "Works with" table, FAQ | Agent Model, Agent Configuration | Employees & Agents, Agent Execution |
| Governance / Approvals | Features table, "Why special" | Board Governance, Board Approval Gates | Principles |
| Budget / Cost Control | Features table, "Why special" | Budget Delegation | Company (revenue & expenses) |
| Task Management | Features table | Task Model | Task Management |
| Org Chart / Hierarchy | Features table | Agent Model (reporting) | Employees & Agents |
| Multi-Company | Features table, FAQ | Company Model | Company |
| Heartbeats | Features table, FAQ | Agent Execution | Agent Execution |
| CLI Commands | Development section | — | — |
| Onboarding / Quickstart | Quickstart, FAQ | — | User Flow |
| Skills / Skill Injection | "Why special" | — | — |
| Company Templates | "Why special", Roadmap (ClipMart) | — | — |
| Mobile / UI | Features table | — | — |
| Project Archiving | — | — | — |
| OpenClaw Integration | "Works with" table, FAQ | Agent Model | Agent Execution |

View File

@@ -1,7 +1,7 @@
---
name: release-changelog
description: >
Generate the stable Paperclip release changelog at releases/v{version}.md by
Generate the stable Paperclip release changelog at releases/vYYYY.MDD.P.md by
reading commits, changesets, and merged PR context since the last stable tag.
---
@@ -9,20 +9,33 @@ description: >
Generate the user-facing changelog for the **stable** Paperclip release.
## Versioning Model
Paperclip uses **calendar versioning (calver)**:
- Stable releases: `YYYY.MDD.P` (e.g. `2026.318.0`)
- Canary releases: `YYYY.MDD.P-canary.N` (e.g. `2026.318.1-canary.0`)
- Git tags: `vYYYY.MDD.P` for stable, `canary/vYYYY.MDD.P-canary.N` for canary
There are no major/minor/patch bumps. The stable version is derived from the
intended release date (UTC) plus the next same-day stable patch slot.
Output:
- `releases/v{version}.md`
- `releases/vYYYY.MDD.P.md`
Important rule:
Important rules:
- even if there are canary releases such as `1.2.3-canary.0`, the changelog file stays `releases/v1.2.3.md`
- even if there are canary releases such as `2026.318.1-canary.0`, the changelog file stays `releases/v2026.318.1.md`
- do not derive versions from semver bump types
- do not create canary changelog files
## Step 0 — Idempotency Check
Before generating anything, check whether the file already exists:
```bash
ls releases/v{version}.md 2>/dev/null
ls releases/vYYYY.MDD.P.md 2>/dev/null
```
If it exists:
@@ -41,13 +54,14 @@ git tag --list 'v*' --sort=-version:refname | head -1
git log v{last}..HEAD --oneline --no-merges
```
The planned stable version comes from one of:
The stable version comes from one of:
- an explicit maintainer request
- the chosen bump type applied to the last stable tag
- `./scripts/release.sh stable --date YYYY-MM-DD --print-version`
- the release plan already agreed in `doc/RELEASING.md`
Do not derive the changelog version from a canary tag or prerelease suffix.
Do not derive major/minor/patch bumps from API intent — calver uses the date and same-day stable slot.
## Step 2 — Gather the Raw Inputs
@@ -73,7 +87,6 @@ Look for:
- destructive migrations
- removed or changed API fields/endpoints
- renamed or removed config keys
- `major` changesets
- `BREAKING:` or `BREAKING CHANGE:` commit signals
Key commands:
@@ -85,7 +98,8 @@ git diff v{last}..HEAD -- server/src/routes/ server/src/api/
git log v{last}..HEAD --format="%s" | rg -n 'BREAKING CHANGE|BREAKING:|^[a-z]+!:' || true
```
If the requested bump is lower than the minimum required bump, flag that before the release proceeds.
If breaking changes are detected, flag them prominently — they must appear in the
Breaking Changes section with an upgrade path.
## Step 4 — Categorize for Users
@@ -130,9 +144,9 @@ Rules:
Template:
```markdown
# v{version}
# vYYYY.MDD.P
> Released: {YYYY-MM-DD}
> Released: YYYY-MM-DD
## Breaking Changes

View File

@@ -2,23 +2,21 @@
name: release
description: >
Coordinate a full Paperclip release across engineering verification, npm,
GitHub, website publishing, and announcement follow-up. Use when leadership
asks to ship a release, not merely to discuss version bumps.
GitHub, smoke testing, and announcement follow-up. Use when leadership asks
to ship a release, not merely to discuss versioning.
---
# Release Coordination Skill
Run the full Paperclip release as a maintainer workflow, not just an npm publish.
Run the full Paperclip maintainer release workflow, not just an npm publish.
This skill coordinates:
- stable changelog drafting via `release-changelog`
- release-train setup via `scripts/release-start.sh`
- prerelease canary publishing via `scripts/release.sh --canary`
- canary verification and publish status from `master`
- Docker smoke testing via `scripts/docker-onboard-smoke.sh`
- stable publishing via `scripts/release.sh`
- pushing the stable branch commit and tag
- GitHub Release creation via `scripts/create-github-release.sh`
- manual stable promotion from a chosen source ref
- GitHub Release creation
- website / announcement follow-up tasks
## Trigger
@@ -26,8 +24,9 @@ This skill coordinates:
Use this skill when leadership asks for:
- "do a release"
- "ship the next patch/minor/major"
- "release vX.Y.Z"
- "ship the release"
- "promote this canary to stable"
- "cut the stable release"
## Preconditions
@@ -35,10 +34,10 @@ Before proceeding, verify all of the following:
1. `.agents/skills/release-changelog/SKILL.md` exists and is usable.
2. The repo working tree is clean, including untracked files.
3. There are commits since the last stable tag.
4. The release SHA has passed the verification gate or is about to.
5. If package manifests changed, the CI-owned `pnpm-lock.yaml` refresh is already merged on `master` before the release branch is cut.
6. npm publish rights are available locally, or the GitHub release workflow is being used with trusted publishing.
3. There is at least one canary or candidate commit since the last stable tag.
4. The candidate SHA has passed the verification gate or is about to.
5. If manifests changed, the CI-owned `pnpm-lock.yaml` refresh is already merged on `master`.
6. npm publish rights are available through GitHub trusted publishing, or through local npm auth for emergency/manual use.
7. If running through Paperclip, you have issue context for status updates and follow-up task creation.
If any precondition fails, stop and report the blocker.
@@ -47,78 +46,67 @@ If any precondition fails, stop and report the blocker.
Collect these inputs up front:
- requested bump: `patch`, `minor`, or `major`
- whether this run is a dry run or live release
- whether the release is being run locally or from GitHub Actions
- whether the target is a canary check or a stable promotion
- the candidate `source_ref` for stable
- whether the stable run is dry-run or live
- release issue / company context for website and announcement follow-up
## Step 0 — Release Model
Paperclip now uses this release model:
Paperclip now uses a commit-driven release model:
1. Start or resume `release/X.Y.Z`
2. Draft the **stable** changelog as `releases/vX.Y.Z.md`
3. Publish one or more **prerelease canaries** such as `X.Y.Z-canary.0`
4. Smoke test the canary via Docker
5. Publish the stable version `X.Y.Z`
6. Push the stable branch commit and tag
7. Create the GitHub Release
8. Merge `release/X.Y.Z` back to `master` without squash or rebase
9. Complete website and announcement surfaces
1. every push to `master` publishes a canary automatically
2. canaries use `YYYY.MDD.P-canary.N`
3. stable releases use `YYYY.MDD.P`
4. the middle slot is `MDD`, where `M` is the UTC month and `DD` is the zero-padded UTC day
5. the stable patch slot increments when more than one stable ships on the same UTC date
6. stable releases are manually promoted from a chosen tested commit or canary source commit
7. only stable releases get `releases/vYYYY.MDD.P.md`, git tag `vYYYY.MDD.P`, and a GitHub Release
Critical consequence:
Critical consequences:
- Canaries do **not** use promote-by-dist-tag anymore.
- The changelog remains stable-only. Do not create `releases/vX.Y.Z-canary.N.md`.
- do not use release branches as the default path
- do not derive major/minor/patch bumps
- do not create canary changelog files
- do not create canary GitHub Releases
## Step 1 — Decide the Stable Version
## Step 1 — Choose the Candidate
Start the release train first:
For canary validation:
- inspect the latest successful canary run on `master`
- record the canary version and source SHA
For stable promotion:
1. choose the tested source ref
2. confirm it is the exact SHA you want to promote
3. resolve the target stable version with `./scripts/release.sh stable --date YYYY-MM-DD --print-version`
Useful commands:
```bash
./scripts/release-start.sh {patch|minor|major}
git tag --list 'v*' --sort=-version:refname | head -1
git log --oneline --no-merges
npm view paperclipai@canary version
```
Then run release preflight:
```bash
./scripts/release-preflight.sh canary {patch|minor|major}
# or
./scripts/release-preflight.sh stable {patch|minor|major}
```
Then use the last stable tag as the base:
```bash
LAST_TAG=$(git tag --list 'v*' --sort=-version:refname | head -1)
git log "${LAST_TAG}..HEAD" --oneline --no-merges
git diff --name-only "${LAST_TAG}..HEAD" -- packages/db/src/migrations/
git diff "${LAST_TAG}..HEAD" -- packages/db/src/schema/
git log "${LAST_TAG}..HEAD" --format="%s" | rg -n 'BREAKING CHANGE|BREAKING:|^[a-z]+!:' || true
```
Bump policy:
- destructive migrations, removed APIs, breaking config changes -> `major`
- additive migrations or clearly user-visible features -> at least `minor`
- fixes only -> `patch`
If the requested bump is too low, escalate it and explain why.
## Step 2 — Draft the Stable Changelog
Invoke `release-changelog` and generate:
Stable changelog files live at:
- `releases/vX.Y.Z.md`
- `releases/vYYYY.MDD.P.md`
Invoke `release-changelog` and generate or update the stable notes only.
Rules:
- review the draft with a human before publish
- preserve manual edits if the file already exists
- keep the heading and filename stable-only, for example `v1.2.3`
- do not create a separate canary changelog file
- keep the filename stable-only
- do not create a canary changelog file
## Step 3 — Verify the Release SHA
## Step 3 — Verify the Candidate SHA
Run the standard gate:
@@ -128,41 +116,27 @@ pnpm test:run
pnpm build
```
If the release will be run through GitHub Actions, the workflow can rerun this gate. Still report whether the local tree currently passes.
If the GitHub release workflow will run the publish, it can rerun this gate. Still report local status if you checked it.
The GitHub Actions release workflow installs with `pnpm install --frozen-lockfile`. Treat that as a release invariant, not a nuisance: if manifests changed and the lockfile refresh PR has not landed yet, stop and wait for `master` to contain the committed lockfile before shipping.
For PRs that touch release logic, the repo also runs a canary release dry-run in CI. That is a release-specific guard, not a substitute for the standard gate.
## Step 4 — Publish a Canary
## Step 4 — Validate the Canary
Run from the `release/X.Y.Z` branch:
The normal canary path is automatic from `master` via:
```bash
./scripts/release.sh {patch|minor|major} --canary --dry-run
./scripts/release.sh {patch|minor|major} --canary
```
- `.github/workflows/release.yml`
What this means:
Confirm:
- npm receives `X.Y.Z-canary.N` under dist-tag `canary`
- `latest` remains unchanged
- no git tag is created
- the script cleans the working tree afterward
1. verification passed
2. npm canary publish succeeded
3. git tag `canary/vYYYY.MDD.P-canary.N` exists
Guard:
- if the current stable is `0.2.7`, the next patch canary is `0.2.8-canary.0`
- the tooling must never publish `0.2.7-canary.N` after `0.2.7` is already stable
After publish, verify:
Useful checks:
```bash
npm view paperclipai@canary version
```
The user install path is:
```bash
npx paperclipai@canary onboard
git tag --list 'canary/v*' --sort=-version:refname | head -5
```
## Step 5 — Smoke Test the Canary
@@ -173,60 +147,70 @@ Run:
PAPERCLIPAI_VERSION=canary ./scripts/docker-onboard-smoke.sh
```
Useful isolated variant:
```bash
HOST_PORT=3232 DATA_DIR=./data/release-smoke-canary PAPERCLIPAI_VERSION=canary ./scripts/docker-onboard-smoke.sh
```
Confirm:
1. install succeeds
2. onboarding completes
3. server boots
4. UI loads
5. basic company/dashboard flow works
2. onboarding completes without crashes
3. the server boots
4. the UI loads
5. basic company creation and dashboard load work
If smoke testing fails:
- stop the stable release
- fix the issue
- publish another canary
- repeat the smoke test
- fix the issue on `master`
- wait for the next automatic canary
- rerun smoke testing
Each retry should create a higher canary ordinal, while the stable target version can stay the same.
## Step 6 — Preview or Publish Stable
## Step 6 — Publish Stable
The normal stable path is manual `workflow_dispatch` on:
Once the SHA is vetted, run:
- `.github/workflows/release.yml`
Inputs:
- `source_ref`
- `stable_date`
- `dry_run`
Before live stable:
1. resolve the target stable version with `./scripts/release.sh stable --date YYYY-MM-DD --print-version`
2. ensure `releases/vYYYY.MDD.P.md` exists on the source ref
3. run the stable workflow in dry-run mode first when practical
4. then run the real stable publish
The stable workflow:
- re-verifies the exact source ref
- computes the next stable patch slot for the chosen UTC date
- publishes `YYYY.MDD.P` under dist-tag `latest`
- creates git tag `vYYYY.MDD.P`
- creates or updates the GitHub Release from `releases/vYYYY.MDD.P.md`
Local emergency/manual commands:
```bash
./scripts/release.sh {patch|minor|major} --dry-run
./scripts/release.sh {patch|minor|major}
./scripts/release.sh stable --dry-run
./scripts/release.sh stable
git push public-gh refs/tags/vYYYY.MDD.P
./scripts/create-github-release.sh YYYY.MDD.P
```
Stable publish does this:
- publishes `X.Y.Z` to npm under `latest`
- creates the local release commit
- creates the local git tag `vX.Y.Z`
Stable publish does **not** push the release for you.
## Step 7 — Push and Create GitHub Release
After stable publish succeeds:
```bash
git push public-gh HEAD --follow-tags
./scripts/create-github-release.sh X.Y.Z
```
Use the stable changelog file as the GitHub Release notes source.
Then open the PR from `release/X.Y.Z` back to `master` and merge without squash or rebase.
## Step 8 — Finish the Other Surfaces
## Step 7 — Finish the Other Surfaces
Create or verify follow-up work for:
- website changelog publishing
- launch post / social announcement
- any release summary in Paperclip issue context
- release summary in Paperclip issue context
These should reference the stable release, not the canary.
@@ -236,9 +220,9 @@ If the canary is bad:
- publish another canary, do not ship stable
If stable npm publish succeeds but push or GitHub release creation fails:
If stable npm publish succeeds but tag push or GitHub release creation fails:
- fix the git/GitHub issue immediately from the same checkout
- fix the git/GitHub issue immediately from the same release result
- do not republish the same version
If `latest` is bad after stable publish:
@@ -247,15 +231,17 @@ If `latest` is bad after stable publish:
./scripts/rollback-latest.sh <last-good-version>
```
Then fix forward with a new patch release.
Then fix forward with a new stable release.
## Output
When the skill completes, provide:
- stable version and, if relevant, the final canary version tested
- candidate SHA and tested canary version, if relevant
- stable version, if promoted
- verification status
- npm status
- smoke-test status
- git tag / GitHub Release status
- website / announcement follow-up status
- rollback recommendation if anything is still partially complete

View File

@@ -1,8 +0,0 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets).
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md).

View File

@@ -1,11 +0,0 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.3/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [["@paperclipai/*", "paperclipai"]],
"linked": [],
"access": "public",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": ["@paperclipai/ui"]
}

View File

@@ -0,0 +1 @@
../../.agents/skills/company-creator

10
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,10 @@
# Replace @cryppadotta if a different maintainer or team should own release infrastructure.
.github/** @cryppadotta @devinfoley
scripts/release*.sh @cryppadotta @devinfoley
scripts/release-*.mjs @cryppadotta @devinfoley
scripts/create-github-release.sh @cryppadotta @devinfoley
scripts/rollback-latest.sh @cryppadotta @devinfoley
doc/RELEASING.md @cryppadotta @devinfoley
doc/PUBLISHING.md @cryppadotta @devinfoley
doc/RELEASE-AUTOMATION-SETUP.md @cryppadotta @devinfoley

View File

@@ -1,49 +0,0 @@
name: PR Policy
on:
pull_request:
branches:
- master
concurrency:
group: pr-policy-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
policy:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Block manual lockfile edits
if: github.head_ref != 'chore/refresh-lockfile'
run: |
changed="$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}")"
if printf '%s\n' "$changed" | grep -qx 'pnpm-lock.yaml'; then
echo "Do not commit pnpm-lock.yaml in pull requests. CI owns lockfile updates."
exit 1
fi
- name: Validate dependency resolution when manifests change
run: |
changed="$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}")"
manifest_pattern='(^|/)package\.json$|^pnpm-workspace\.yaml$|^\.npmrc$|^pnpmfile\.(cjs|js|mjs)$'
if printf '%s\n' "$changed" | grep -Eq "$manifest_pattern"; then
pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile
fi

View File

@@ -1,42 +0,0 @@
name: PR Verify
on:
pull_request:
branches:
- master
concurrency:
group: pr-verify-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: pnpm
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Typecheck
run: pnpm -r typecheck
- name: Run tests
run: pnpm test:run
- name: Build
run: pnpm build

146
.github/workflows/pr.yml vendored Normal file
View File

@@ -0,0 +1,146 @@
name: PR
on:
pull_request:
branches:
- master
concurrency:
group: pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
policy:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Block manual lockfile edits
if: github.head_ref != 'chore/refresh-lockfile'
run: |
changed="$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}")"
if printf '%s\n' "$changed" | grep -qx 'pnpm-lock.yaml'; then
echo "Do not commit pnpm-lock.yaml in pull requests. CI owns lockfile updates."
exit 1
fi
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
- name: Validate dependency resolution when manifests change
run: |
changed="$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}")"
manifest_pattern='(^|/)package\.json$|^pnpm-workspace\.yaml$|^\.npmrc$|^pnpmfile\.(cjs|js|mjs)$'
if printf '%s\n' "$changed" | grep -Eq "$manifest_pattern"; then
pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile
fi
verify:
needs: [policy]
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Typecheck
run: pnpm -r typecheck
- name: Run tests
run: pnpm test:run
- name: Build
run: pnpm build
- name: Release canary dry run
run: |
git checkout -B master HEAD
git checkout -- pnpm-lock.yaml
./scripts/release.sh canary --skip-verify --dry-run
e2e:
needs: [policy]
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build
run: pnpm build
- name: Install Playwright
run: npx playwright install --with-deps chromium
- name: Generate Paperclip config
run: |
mkdir -p ~/.paperclip/instances/default
cat > ~/.paperclip/instances/default/config.json << 'CONF'
{
"$meta": { "version": 1, "updatedAt": "2026-01-01T00:00:00.000Z", "source": "onboard" },
"database": { "mode": "embedded-postgres" },
"logging": { "mode": "file" },
"server": { "deploymentMode": "local_trusted", "host": "127.0.0.1", "port": 3100 },
"auth": { "baseUrlMode": "auto" },
"storage": { "provider": "local_disk" },
"secrets": { "provider": "local_encrypted", "strictMode": false }
}
CONF
- name: Run e2e tests
env:
PAPERCLIP_E2E_SKIP_LLM: "true"
run: pnpm run test:e2e
- name: Upload Playwright report
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: |
tests/e2e/playwright-report/
tests/e2e/test-results/
retention-days: 14

View File

@@ -51,11 +51,13 @@ jobs:
fi
- name: Create or update pull request
id: upsert-pr
env:
GH_TOKEN: ${{ github.token }}
run: |
if git diff --quiet -- pnpm-lock.yaml; then
echo "Lockfile unchanged, nothing to do."
echo "pr_created=false" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -79,3 +81,17 @@ jobs:
else
echo "PR #$existing already exists, branch updated via force push."
fi
echo "pr_created=true" >> "$GITHUB_OUTPUT"
- name: Enable auto-merge for lockfile PR
if: steps.upsert-pr.outputs.pr_created == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
pr_url="$(gh pr list --head chore/refresh-lockfile --json url --jq '.[0].url')"
if [ -z "$pr_url" ]; then
echo "Error: lockfile PR was not found." >&2
exit 1
fi
gh pr merge --auto --squash --delete-branch "$pr_url"

118
.github/workflows/release-smoke.yml vendored Normal file
View File

@@ -0,0 +1,118 @@
name: Release Smoke
on:
workflow_dispatch:
inputs:
paperclip_version:
description: Published Paperclip dist-tag to test
required: true
default: canary
type: choice
options:
- canary
- latest
host_port:
description: Host port for the Docker smoke container
required: false
default: "3232"
type: string
artifact_name:
description: Artifact name for uploaded diagnostics
required: false
default: release-smoke
type: string
workflow_call:
inputs:
paperclip_version:
required: true
type: string
host_port:
required: false
default: "3232"
type: string
artifact_name:
required: false
default: release-smoke
type: string
jobs:
smoke:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Install Playwright browser
run: npx playwright install --with-deps chromium
- name: Launch Docker smoke harness
run: |
metadata_file="$RUNNER_TEMP/release-smoke.env"
HOST_PORT="${{ inputs.host_port }}" \
DATA_DIR="$RUNNER_TEMP/release-smoke-data" \
PAPERCLIPAI_VERSION="${{ inputs.paperclip_version }}" \
SMOKE_DETACH=true \
SMOKE_METADATA_FILE="$metadata_file" \
./scripts/docker-onboard-smoke.sh
set -a
source "$metadata_file"
set +a
{
echo "SMOKE_BASE_URL=$SMOKE_BASE_URL"
echo "SMOKE_ADMIN_EMAIL=$SMOKE_ADMIN_EMAIL"
echo "SMOKE_ADMIN_PASSWORD=$SMOKE_ADMIN_PASSWORD"
echo "SMOKE_CONTAINER_NAME=$SMOKE_CONTAINER_NAME"
echo "SMOKE_DATA_DIR=$SMOKE_DATA_DIR"
echo "SMOKE_IMAGE_NAME=$SMOKE_IMAGE_NAME"
echo "SMOKE_PAPERCLIPAI_VERSION=$SMOKE_PAPERCLIPAI_VERSION"
echo "SMOKE_METADATA_FILE=$metadata_file"
} >> "$GITHUB_ENV"
- name: Run release smoke Playwright suite
env:
PAPERCLIP_RELEASE_SMOKE_BASE_URL: ${{ env.SMOKE_BASE_URL }}
PAPERCLIP_RELEASE_SMOKE_EMAIL: ${{ env.SMOKE_ADMIN_EMAIL }}
PAPERCLIP_RELEASE_SMOKE_PASSWORD: ${{ env.SMOKE_ADMIN_PASSWORD }}
run: pnpm run test:release-smoke
- name: Capture Docker logs
if: always()
run: |
if [[ -n "${SMOKE_CONTAINER_NAME:-}" ]]; then
docker logs "$SMOKE_CONTAINER_NAME" >"$RUNNER_TEMP/docker-onboard-smoke.log" 2>&1 || true
fi
- name: Upload diagnostics
if: always()
uses: actions/upload-artifact@v4
with:
name: ${{ inputs.artifact_name }}
path: |
${{ runner.temp }}/docker-onboard-smoke.log
${{ env.SMOKE_METADATA_FILE }}
tests/release-smoke/playwright-report/
tests/release-smoke/test-results/
retention-days: 14
- name: Stop Docker smoke container
if: always()
run: |
if [[ -n "${SMOKE_CONTAINER_NAME:-}" ]]; then
docker rm -f "$SMOKE_CONTAINER_NAME" >/dev/null 2>&1 || true
fi

View File

@@ -1,38 +1,33 @@
name: Release
on:
push:
branches:
- master
workflow_dispatch:
inputs:
channel:
description: Release channel
source_ref:
description: Commit SHA, branch, or tag to publish as stable
required: true
type: choice
default: canary
options:
- canary
- stable
bump:
description: Semantic version bump
required: true
type: choice
default: patch
options:
- patch
- minor
- major
type: string
default: master
stable_date:
description: Enter a UTC date in YYYY-MM-DD format, for example 2026-03-18. Do not enter a version string. The workflow will resolve that date to a stable version such as 2026.318.0, then 2026.318.1 for the next same-day stable.
required: false
type: string
dry_run:
description: Preview the release without publishing
description: Preview the stable release without publishing
required: true
type: boolean
default: true
default: false
concurrency:
group: release-${{ github.ref }}
group: release-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: false
jobs:
verify:
if: startsWith(github.ref, 'refs/heads/release/')
verify_canary:
if: github.event_name == 'push'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
@@ -56,7 +51,7 @@ jobs:
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
run: pnpm install --no-frozen-lockfile
- name: Typecheck
run: pnpm -r typecheck
@@ -67,12 +62,12 @@ jobs:
- name: Build
run: pnpm build
publish:
if: startsWith(github.ref, 'refs/heads/release/')
needs: verify
publish_canary:
if: github.event_name == 'push'
needs: verify_canary
runs-on: ubuntu-latest
timeout-minutes: 45
environment: npm-release
environment: npm-canary
permissions:
contents: write
id-token: write
@@ -95,34 +90,168 @@ jobs:
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
run: pnpm install --no-frozen-lockfile
- name: Restore tracked install-time changes
run: git checkout -- pnpm-lock.yaml
- name: Configure git author
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Run release script
- name: Publish canary
env:
GITHUB_ACTIONS: "true"
run: ./scripts/release.sh canary --skip-verify
- name: Push canary tag
run: |
tag="$(git tag --points-at HEAD | grep '^canary/v' | head -1)"
if [ -z "$tag" ]; then
echo "Error: no canary tag points at HEAD after release." >&2
exit 1
fi
git push origin "refs/tags/${tag}"
verify_stable:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ inputs.source_ref }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Typecheck
run: pnpm -r typecheck
- name: Run tests
run: pnpm test:run
- name: Build
run: pnpm build
preview_stable:
if: github.event_name == 'workflow_dispatch' && inputs.dry_run
needs: verify_stable
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ inputs.source_ref }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Dry-run stable release
env:
GITHUB_ACTIONS: "true"
run: |
args=("${{ inputs.bump }}")
if [ "${{ inputs.channel }}" = "canary" ]; then
args+=("--canary")
fi
if [ "${{ inputs.dry_run }}" = "true" ]; then
args+=("--dry-run")
args=(stable --skip-verify --dry-run)
if [ -n "${{ inputs.stable_date }}" ]; then
args+=(--date "${{ inputs.stable_date }}")
fi
./scripts/release.sh "${args[@]}"
- name: Push stable release branch commit and tag
if: inputs.channel == 'stable' && !inputs.dry_run
run: git push origin "HEAD:${GITHUB_REF_NAME}" --follow-tags
publish_stable:
if: github.event_name == 'workflow_dispatch' && !inputs.dry_run
needs: verify_stable
runs-on: ubuntu-latest
timeout-minutes: 45
environment: npm-stable
permissions:
contents: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ inputs.source_ref }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.15.4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Restore tracked install-time changes
run: git checkout -- pnpm-lock.yaml
- name: Configure git author
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Publish stable
env:
GITHUB_ACTIONS: "true"
run: |
args=(stable --skip-verify)
if [ -n "${{ inputs.stable_date }}" ]; then
args+=(--date "${{ inputs.stable_date }}")
fi
./scripts/release.sh "${args[@]}"
- name: Push stable tag
run: |
tag="$(git tag --points-at HEAD | grep '^v' | head -1)"
if [ -z "$tag" ]; then
echo "Error: no stable tag points at HEAD after release." >&2
exit 1
fi
git push origin "refs/tags/${tag}"
- name: Create GitHub Release
if: inputs.channel == 'stable' && !inputs.dry_run
env:
GH_TOKEN: ${{ github.token }}
PUBLISH_REMOTE: origin
run: |
version="$(git tag --points-at HEAD | grep '^v' | head -1 | sed 's/^v//')"
if [ -z "$version" ]; then

11
.gitignore vendored
View File

@@ -37,7 +37,16 @@ tmp/
.vscode/
.claude/settings.local.json
.paperclip-local/
/.idea/
/.agents/
# Doc maintenance cursor
.doc-review-cursor
# Playwright
tests/e2e/test-results/
tests/e2e/playwright-report/
tests/e2e/playwright-report/
tests/release-smoke/test-results/
tests/release-smoke/playwright-report/
.superset/
.claude/worktrees/

View File

@@ -7,6 +7,7 @@ We really appreciate both small fixes and thoughtful larger changes.
## Two Paths to Get Your Pull Request Accepted
### Path 1: Small, Focused Changes (Fastest way to get merged)
- Pick **one** clear thing to fix/improve
- Touch the **smallest possible number of files**
- Make sure the change is very targeted and easy to review
@@ -16,6 +17,7 @@ We really appreciate both small fixes and thoughtful larger changes.
These almost always get merged quickly when they're clean.
### Path 2: Bigger or Impactful Changes
- **First** talk about it in Discord → #dev channel
→ Describe what you're trying to solve
→ Share rough ideas / approach
@@ -30,12 +32,43 @@ These almost always get merged quickly when they're clean.
PRs that follow this path are **much** more likely to be accepted, even when they're large.
## General Rules (both paths)
- Write clear commit messages
- Keep PR title + description meaningful
- One PR = one logical change (unless it's a small related group)
- Run tests locally first
- Be kind in discussions 😄
## Writing a Good PR message
Please include a "thinking path" at the top of your PR message that explains from the top of the project down to what you fixed. E.g.:
### Thinking Path Example 1:
> - Paperclip orchestrates ai-agents for zero-human companies
> - There are many types of adapters for each LLM model provider
> - But LLM's have a context limit and not all agents can automatically compact their context
> - So we need to have an adapter-specific configuration for which adapters can and cannot automatically compact their context
> - This pull request adds per-adapter configuration of compaction, either auto or paperclip managed
> - That way we can get optimal performance from any adapter/provider in Paperclip
### Thinking Path Example 2:
> - Paperclip orchestrates ai-agents for zero-human companies
> - But humans want to watch the agents and oversee their work
> - Human users also operate in teams and so they need their own logins, profiles, views etc.
> - So we have a multi-user system for humans
> - But humans want to be able to update their own profile picture and avatar
> - But the avatar upload form wasn't saving the avatar to the file storage system
> - So this PR fixes the avatar upload form to use the file storage service
> - The benefit is we don't have a one-off file storage for just one aspect of the system, which would cause confusion and extra configuration
Then have the rest of your normal PR message after the Thinking Path.
This should include details about what you did, why you did it, why it matters & the benefits, how we can verify it works, and any risks.
Please include screenshots if possible if you have a visible change. (use something like the [agent-browser skill](https://github.com/vercel-labs/agent-browser/blob/main/skills/agent-browser/SKILL.md) or similar to take screenshots). Ideally, you include before and after screenshots.
Questions? Just ask in #dev — we're happy to help.
Happy hacking!

View File

@@ -239,7 +239,7 @@ See [doc/DEVELOPING.md](doc/DEVELOPING.md) for the full development guide.
- ⚪ ClipMart - buy and sell entire agent companies
- ⚪ Easy agent configurations / easier to understand
- ⚪ Better support for harness engineering
- Plugin system (e.g. if you want to add a knowledgebase, custom tracing, queues, etc)
- 🟢 Plugin system (e.g. if you want to add a knowledgebase, custom tracing, queues, etc)
- ⚪ Better docs
<br/>

View File

@@ -1,5 +1,23 @@
# paperclipai
## 0.3.1
### Patch Changes
- Stable release preparation for 0.3.1
- Updated dependencies
- @paperclipai/adapter-utils@0.3.1
- @paperclipai/adapter-claude-local@0.3.1
- @paperclipai/adapter-codex-local@0.3.1
- @paperclipai/adapter-cursor-local@0.3.1
- @paperclipai/adapter-gemini-local@0.3.1
- @paperclipai/adapter-openclaw-gateway@0.3.1
- @paperclipai/adapter-opencode-local@0.3.1
- @paperclipai/adapter-pi-local@0.3.1
- @paperclipai/db@0.3.1
- @paperclipai/shared@0.3.1
- @paperclipai/server@0.3.1
## 0.3.0
### Minor Changes

View File

@@ -1,6 +1,6 @@
{
"name": "paperclipai",
"version": "0.3.0",
"version": "0.3.1",
"description": "Paperclip CLI — orchestrate AI agent teams to run a business",
"type": "module",
"bin": {
@@ -16,10 +16,13 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip.git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "cli"
},
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"files": [
"dist"
],

View File

@@ -8,12 +8,16 @@ function makeCompany(overrides: Partial<Company>): Company {
name: "Alpha",
description: null,
status: "active",
pauseReason: null,
pausedAt: null,
issuePrefix: "ALP",
issueCounter: 1,
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
requireBoardApprovalForNewAgents: false,
brandColor: null,
logoAssetId: null,
logoUrl: null,
createdAt: new Date(),
updatedAt: new Date(),
...overrides,

View File

@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { isHttpUrl, isGithubUrl } from "../commands/client/company.js";
describe("isHttpUrl", () => {
it("matches http URLs", () => {
expect(isHttpUrl("http://example.com/foo")).toBe(true);
});
it("matches https URLs", () => {
expect(isHttpUrl("https://example.com/foo")).toBe(true);
});
it("rejects local paths", () => {
expect(isHttpUrl("/tmp/my-company")).toBe(false);
expect(isHttpUrl("./relative")).toBe(false);
});
});
describe("isGithubUrl", () => {
it("matches GitHub URLs", () => {
expect(isGithubUrl("https://github.com/org/repo")).toBe(true);
});
it("rejects non-GitHub HTTP URLs", () => {
expect(isGithubUrl("https://example.com/foo")).toBe(false);
});
it("rejects local paths", () => {
expect(isGithubUrl("/tmp/my-company")).toBe(false);
});
});

View File

@@ -0,0 +1,392 @@
import { describe, expect, it } from "vitest";
import { buildWorktreeMergePlan, parseWorktreeMergeScopes } from "../commands/worktree-merge-history-lib.js";
function makeIssue(overrides: Record<string, unknown> = {}) {
return {
id: "issue-1",
companyId: "company-1",
projectId: null,
projectWorkspaceId: null,
goalId: "goal-1",
parentId: null,
title: "Issue",
description: null,
status: "todo",
priority: "medium",
assigneeAgentId: null,
assigneeUserId: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
createdByAgentId: null,
createdByUserId: "local-board",
issueNumber: 1,
identifier: "PAP-1",
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: null,
executionWorkspacePreference: null,
executionWorkspaceSettings: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
createdAt: new Date("2026-03-20T00:00:00.000Z"),
updatedAt: new Date("2026-03-20T00:00:00.000Z"),
...overrides,
} as any;
}
function makeComment(overrides: Record<string, unknown> = {}) {
return {
id: "comment-1",
companyId: "company-1",
issueId: "issue-1",
authorAgentId: null,
authorUserId: "local-board",
body: "hello",
createdAt: new Date("2026-03-20T00:00:00.000Z"),
updatedAt: new Date("2026-03-20T00:00:00.000Z"),
...overrides,
} as any;
}
function makeIssueDocument(overrides: Record<string, unknown> = {}) {
return {
id: "issue-document-1",
companyId: "company-1",
issueId: "issue-1",
documentId: "document-1",
key: "plan",
linkCreatedAt: new Date("2026-03-20T00:00:00.000Z"),
linkUpdatedAt: new Date("2026-03-20T00:00:00.000Z"),
title: "Plan",
format: "markdown",
latestBody: "# Plan",
latestRevisionId: "revision-1",
latestRevisionNumber: 1,
createdByAgentId: null,
createdByUserId: "local-board",
updatedByAgentId: null,
updatedByUserId: "local-board",
documentCreatedAt: new Date("2026-03-20T00:00:00.000Z"),
documentUpdatedAt: new Date("2026-03-20T00:00:00.000Z"),
...overrides,
} as any;
}
function makeDocumentRevision(overrides: Record<string, unknown> = {}) {
return {
id: "revision-1",
companyId: "company-1",
documentId: "document-1",
revisionNumber: 1,
body: "# Plan",
changeSummary: null,
createdByAgentId: null,
createdByUserId: "local-board",
createdAt: new Date("2026-03-20T00:00:00.000Z"),
...overrides,
} as any;
}
function makeAttachment(overrides: Record<string, unknown> = {}) {
return {
id: "attachment-1",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
assetId: "asset-1",
provider: "local_disk",
objectKey: "company-1/issues/issue-1/2026/03/20/asset.png",
contentType: "image/png",
byteSize: 12,
sha256: "deadbeef",
originalFilename: "asset.png",
createdByAgentId: null,
createdByUserId: "local-board",
assetCreatedAt: new Date("2026-03-20T00:00:00.000Z"),
assetUpdatedAt: new Date("2026-03-20T00:00:00.000Z"),
attachmentCreatedAt: new Date("2026-03-20T00:00:00.000Z"),
attachmentUpdatedAt: new Date("2026-03-20T00:00:00.000Z"),
...overrides,
} as any;
}
describe("worktree merge history planner", () => {
it("parses default scopes", () => {
expect(parseWorktreeMergeScopes(undefined)).toEqual(["issues", "comments"]);
expect(parseWorktreeMergeScopes("issues")).toEqual(["issues"]);
});
it("dedupes nested worktree issues by preserved source uuid", () => {
const sharedIssue = makeIssue({ id: "issue-a", identifier: "PAP-10", title: "Shared" });
const branchOneIssue = makeIssue({
id: "issue-b",
identifier: "PAP-22",
title: "Branch one issue",
createdAt: new Date("2026-03-20T01:00:00.000Z"),
});
const branchTwoIssue = makeIssue({
id: "issue-c",
identifier: "PAP-23",
title: "Branch two issue",
createdAt: new Date("2026-03-20T02:00:00.000Z"),
});
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 500,
scopes: ["issues", "comments"],
sourceIssues: [sharedIssue, branchOneIssue, branchTwoIssue],
targetIssues: [sharedIssue, branchOneIssue],
sourceComments: [],
targetComments: [],
targetAgents: [],
targetProjects: [],
targetProjectWorkspaces: [],
targetGoals: [{ id: "goal-1" }] as any,
});
expect(plan.counts.issuesToInsert).toBe(1);
expect(plan.issuePlans.filter((item) => item.action === "insert").map((item) => item.source.id)).toEqual(["issue-c"]);
expect(plan.issuePlans.find((item) => item.source.id === "issue-c" && item.action === "insert")).toMatchObject({
previewIdentifier: "PAP-501",
});
});
it("clears missing references and coerces in_progress without an assignee", () => {
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 10,
scopes: ["issues"],
sourceIssues: [
makeIssue({
id: "issue-x",
identifier: "PAP-99",
status: "in_progress",
assigneeAgentId: "agent-missing",
projectId: "project-missing",
projectWorkspaceId: "workspace-missing",
goalId: "goal-missing",
}),
],
targetIssues: [],
sourceComments: [],
targetComments: [],
targetAgents: [],
targetProjects: [],
targetProjectWorkspaces: [],
targetGoals: [],
});
const insert = plan.issuePlans[0] as any;
expect(insert.targetStatus).toBe("todo");
expect(insert.targetAssigneeAgentId).toBeNull();
expect(insert.targetProjectId).toBeNull();
expect(insert.targetProjectWorkspaceId).toBeNull();
expect(insert.targetGoalId).toBeNull();
expect(insert.adjustments).toEqual([
"clear_assignee_agent",
"clear_project",
"clear_project_workspace",
"clear_goal",
"coerce_in_progress_to_todo",
]);
});
it("applies an explicit project mapping override instead of clearing the project", () => {
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 10,
scopes: ["issues"],
sourceIssues: [
makeIssue({
id: "issue-project-map",
identifier: "PAP-77",
projectId: "source-project-1",
projectWorkspaceId: "source-workspace-1",
}),
],
targetIssues: [],
sourceComments: [],
targetComments: [],
targetAgents: [],
targetProjects: [{ id: "target-project-1", name: "Mapped project", status: "in_progress" }] as any,
targetProjectWorkspaces: [],
targetGoals: [{ id: "goal-1" }] as any,
projectIdOverrides: {
"source-project-1": "target-project-1",
},
});
const insert = plan.issuePlans[0] as any;
expect(insert.targetProjectId).toBe("target-project-1");
expect(insert.projectResolution).toBe("mapped");
expect(insert.mappedProjectName).toBe("Mapped project");
expect(insert.targetProjectWorkspaceId).toBeNull();
expect(insert.adjustments).toEqual(["clear_project_workspace"]);
});
it("imports comments onto shared or newly imported issues while skipping existing comments", () => {
const sharedIssue = makeIssue({ id: "issue-a", identifier: "PAP-10" });
const newIssue = makeIssue({
id: "issue-b",
identifier: "PAP-11",
createdAt: new Date("2026-03-20T01:00:00.000Z"),
});
const existingComment = makeComment({ id: "comment-existing", issueId: "issue-a" });
const sharedIssueComment = makeComment({ id: "comment-shared", issueId: "issue-a" });
const newIssueComment = makeComment({
id: "comment-new-issue",
issueId: "issue-b",
authorAgentId: "missing-agent",
createdAt: new Date("2026-03-20T01:05:00.000Z"),
});
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 10,
scopes: ["issues", "comments"],
sourceIssues: [sharedIssue, newIssue],
targetIssues: [sharedIssue],
sourceComments: [existingComment, sharedIssueComment, newIssueComment],
targetComments: [existingComment],
targetAgents: [],
targetProjects: [],
targetProjectWorkspaces: [],
targetGoals: [{ id: "goal-1" }] as any,
});
expect(plan.counts.commentsToInsert).toBe(2);
expect(plan.counts.commentsExisting).toBe(1);
expect(plan.commentPlans.filter((item) => item.action === "insert").map((item) => item.source.id)).toEqual([
"comment-shared",
"comment-new-issue",
]);
expect(plan.adjustments.clear_author_agent).toBe(1);
});
it("merges document revisions onto an existing shared document and renumbers conflicts", () => {
const sharedIssue = makeIssue({ id: "issue-a", identifier: "PAP-10" });
const sourceDocument = makeIssueDocument({
issueId: "issue-a",
documentId: "document-a",
latestBody: "# Branch plan",
latestRevisionId: "revision-branch-2",
latestRevisionNumber: 2,
documentUpdatedAt: new Date("2026-03-20T02:00:00.000Z"),
linkUpdatedAt: new Date("2026-03-20T02:00:00.000Z"),
});
const targetDocument = makeIssueDocument({
issueId: "issue-a",
documentId: "document-a",
latestBody: "# Main plan",
latestRevisionId: "revision-main-2",
latestRevisionNumber: 2,
documentUpdatedAt: new Date("2026-03-20T01:00:00.000Z"),
linkUpdatedAt: new Date("2026-03-20T01:00:00.000Z"),
});
const sourceRevisionOne = makeDocumentRevision({ documentId: "document-a", id: "revision-1" });
const sourceRevisionTwo = makeDocumentRevision({
documentId: "document-a",
id: "revision-branch-2",
revisionNumber: 2,
body: "# Branch plan",
createdAt: new Date("2026-03-20T02:00:00.000Z"),
});
const targetRevisionOne = makeDocumentRevision({ documentId: "document-a", id: "revision-1" });
const targetRevisionTwo = makeDocumentRevision({
documentId: "document-a",
id: "revision-main-2",
revisionNumber: 2,
body: "# Main plan",
createdAt: new Date("2026-03-20T01:00:00.000Z"),
});
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 10,
scopes: ["issues", "comments"],
sourceIssues: [sharedIssue],
targetIssues: [sharedIssue],
sourceComments: [],
targetComments: [],
sourceDocuments: [sourceDocument],
targetDocuments: [targetDocument],
sourceDocumentRevisions: [sourceRevisionOne, sourceRevisionTwo],
targetDocumentRevisions: [targetRevisionOne, targetRevisionTwo],
sourceAttachments: [],
targetAttachments: [],
targetAgents: [],
targetProjects: [],
targetProjectWorkspaces: [],
targetGoals: [{ id: "goal-1" }] as any,
});
expect(plan.counts.documentsToMerge).toBe(1);
expect(plan.counts.documentRevisionsToInsert).toBe(1);
expect(plan.documentPlans[0]).toMatchObject({
action: "merge_existing",
latestRevisionId: "revision-branch-2",
latestRevisionNumber: 3,
});
const mergePlan = plan.documentPlans[0] as any;
expect(mergePlan.revisionsToInsert).toHaveLength(1);
expect(mergePlan.revisionsToInsert[0]).toMatchObject({
source: { id: "revision-branch-2" },
targetRevisionNumber: 3,
});
});
it("imports attachments while clearing missing comment and author references", () => {
const sharedIssue = makeIssue({ id: "issue-a", identifier: "PAP-10" });
const attachment = makeAttachment({
issueId: "issue-a",
issueCommentId: "comment-missing",
createdByAgentId: "agent-missing",
});
const plan = buildWorktreeMergePlan({
companyId: "company-1",
companyName: "Paperclip",
issuePrefix: "PAP",
previewIssueCounterStart: 10,
scopes: ["issues"],
sourceIssues: [sharedIssue],
targetIssues: [sharedIssue],
sourceComments: [],
targetComments: [],
sourceDocuments: [],
targetDocuments: [],
sourceDocumentRevisions: [],
targetDocumentRevisions: [],
sourceAttachments: [attachment],
targetAttachments: [],
targetAgents: [],
targetProjects: [],
targetProjectWorkspaces: [],
targetGoals: [{ id: "goal-1" }] as any,
});
expect(plan.counts.attachmentsToInsert).toBe(1);
expect(plan.adjustments.clear_attachment_agent).toBe(1);
expect(plan.attachmentPlans[0]).toMatchObject({
action: "insert",
targetIssueCommentId: null,
targetCreatedByAgentId: null,
});
});
});

View File

@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
copyGitHooksToWorktreeGitDir,
copySeededSecretsKey,
readSourceAttachmentBody,
rebindWorkspaceCwd,
resolveSourceConfigPath,
resolveGitWorktreeAddArgs,
@@ -195,6 +196,43 @@ describe("worktree helpers", () => {
expect(formatShellExports(env)).toContain("export PAPERCLIP_INSTANCE_ID='feature-worktree-support'");
});
it("falls back across storage roots before skipping a missing attachment object", async () => {
const missingErr = Object.assign(new Error("missing"), { code: "ENOENT" });
const expected = Buffer.from("image-bytes");
await expect(
readSourceAttachmentBody(
[
{
getObject: vi.fn().mockRejectedValue(missingErr),
},
{
getObject: vi.fn().mockResolvedValue(expected),
},
],
"company-1",
"company-1/issues/issue-1/missing.png",
),
).resolves.toEqual(expected);
});
it("returns null when an attachment object is missing from every lookup storage", async () => {
const missingErr = Object.assign(new Error("missing"), { code: "ENOENT" });
await expect(
readSourceAttachmentBody(
[
{
getObject: vi.fn().mockRejectedValue(missingErr),
},
{
getObject: vi.fn().mockRejectedValue(Object.assign(new Error("missing"), { status: 404 })),
},
],
"company-1",
"company-1/issues/issue-1/missing.png",
),
).resolves.toBeNull();
});
it("generates vivid worktree colors as hex", () => {
expect(generateWorktreeColor()).toMatch(/^#[0-9a-f]{6}$/);
});

View File

@@ -1,11 +1,12 @@
import { Command } from "commander";
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import * as p from "@clack/prompts";
import type {
Company,
CompanyPortabilityFileEntry,
CompanyPortabilityExportResult,
CompanyPortabilityInclude,
CompanyPortabilityManifest,
CompanyPortabilityPreviewResult,
CompanyPortabilityImportResult,
} from "@paperclipai/shared";
@@ -33,6 +34,11 @@ interface CompanyDeleteOptions extends BaseClientOptions {
interface CompanyExportOptions extends BaseClientOptions {
out?: string;
include?: string;
skills?: string;
projects?: string;
issues?: string;
projectIssues?: string;
expandReferencedSkills?: boolean;
}
interface CompanyImportOptions extends BaseClientOptions {
@@ -46,6 +52,30 @@ interface CompanyImportOptions extends BaseClientOptions {
dryRun?: boolean;
}
const binaryContentTypeByExtension: Record<string, string> = {
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".webp": "image/webp",
};
function readPortableFileEntry(filePath: string, contents: Buffer): CompanyPortabilityFileEntry {
const contentType = binaryContentTypeByExtension[path.extname(filePath).toLowerCase()];
if (!contentType) return contents.toString("utf8");
return {
encoding: "base64",
data: contents.toString("base64"),
contentType,
};
}
function portableFileEntryToWriteValue(entry: CompanyPortabilityFileEntry): string | Uint8Array {
if (typeof entry === "string") return entry;
return Buffer.from(entry.data, "base64");
}
function isUuidLike(value: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
}
@@ -55,14 +85,17 @@ function normalizeSelector(input: string): string {
}
function parseInclude(input: string | undefined): CompanyPortabilityInclude {
if (!input || !input.trim()) return { company: true, agents: true };
if (!input || !input.trim()) return { company: true, agents: true, projects: false, issues: false, skills: false };
const values = input.split(",").map((part) => part.trim().toLowerCase()).filter(Boolean);
const include = {
company: values.includes("company"),
agents: values.includes("agents"),
projects: values.includes("projects"),
issues: values.includes("issues") || values.includes("tasks"),
skills: values.includes("skills"),
};
if (!include.company && !include.agents) {
throw new Error("Invalid --include value. Use one or both of: company,agents");
if (!include.company && !include.agents && !include.projects && !include.issues && !include.skills) {
throw new Error("Invalid --include value. Use one or more of: company,agents,projects,issues,tasks,skills");
}
return include;
}
@@ -76,50 +109,95 @@ function parseAgents(input: string | undefined): "all" | string[] {
return Array.from(new Set(values));
}
function isHttpUrl(input: string): boolean {
function parseCsvValues(input: string | undefined): string[] {
if (!input || !input.trim()) return [];
return Array.from(new Set(input.split(",").map((part) => part.trim()).filter(Boolean)));
}
export function isHttpUrl(input: string): boolean {
return /^https?:\/\//i.test(input.trim());
}
function isGithubUrl(input: string): boolean {
export function isGithubUrl(input: string): boolean {
return /^https?:\/\/github\.com\//i.test(input.trim());
}
async function collectPackageFiles(
root: string,
current: string,
files: Record<string, CompanyPortabilityFileEntry>,
): Promise<void> {
const entries = await readdir(current, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".git")) continue;
const absolutePath = path.join(current, entry.name);
if (entry.isDirectory()) {
await collectPackageFiles(root, absolutePath, files);
continue;
}
if (!entry.isFile()) continue;
const isMarkdown = entry.name.endsWith(".md");
const isPaperclipYaml = entry.name === ".paperclip.yaml" || entry.name === ".paperclip.yml";
const contentType = binaryContentTypeByExtension[path.extname(entry.name).toLowerCase()];
if (!isMarkdown && !isPaperclipYaml && !contentType) continue;
const relativePath = path.relative(root, absolutePath).replace(/\\/g, "/");
files[relativePath] = readPortableFileEntry(relativePath, await readFile(absolutePath));
}
}
async function resolveInlineSourceFromPath(inputPath: string): Promise<{
manifest: CompanyPortabilityManifest;
files: Record<string, string>;
rootPath: string;
files: Record<string, CompanyPortabilityFileEntry>;
}> {
const resolved = path.resolve(inputPath);
const resolvedStat = await stat(resolved);
const manifestPath = resolvedStat.isDirectory()
? path.join(resolved, "paperclip.manifest.json")
: resolved;
const manifestBaseDir = path.dirname(manifestPath);
const manifestRaw = await readFile(manifestPath, "utf8");
const manifest = JSON.parse(manifestRaw) as CompanyPortabilityManifest;
const files: Record<string, string> = {};
if (manifest.company?.path) {
const companyPath = manifest.company.path.replace(/\\/g, "/");
files[companyPath] = await readFile(path.join(manifestBaseDir, companyPath), "utf8");
}
for (const agent of manifest.agents ?? []) {
const agentPath = agent.path.replace(/\\/g, "/");
files[agentPath] = await readFile(path.join(manifestBaseDir, agentPath), "utf8");
}
return { manifest, files };
const rootDir = resolvedStat.isDirectory() ? resolved : path.dirname(resolved);
const files: Record<string, CompanyPortabilityFileEntry> = {};
await collectPackageFiles(rootDir, rootDir, files);
return {
rootPath: path.basename(rootDir),
files,
};
}
async function writeExportToFolder(outDir: string, exported: CompanyPortabilityExportResult): Promise<void> {
const root = path.resolve(outDir);
await mkdir(root, { recursive: true });
const manifestPath = path.join(root, "paperclip.manifest.json");
await writeFile(manifestPath, JSON.stringify(exported.manifest, null, 2), "utf8");
for (const [relativePath, content] of Object.entries(exported.files)) {
const normalized = relativePath.replace(/\\/g, "/");
const filePath = path.join(root, normalized);
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(filePath, content, "utf8");
const writeValue = portableFileEntryToWriteValue(content);
if (typeof writeValue === "string") {
await writeFile(filePath, writeValue, "utf8");
} else {
await writeFile(filePath, writeValue);
}
}
}
async function confirmOverwriteExportDirectory(outDir: string): Promise<void> {
const root = path.resolve(outDir);
const stats = await stat(root).catch(() => null);
if (!stats) return;
if (!stats.isDirectory()) {
throw new Error(`Export output path ${root} exists and is not a directory.`);
}
const entries = await readdir(root);
if (entries.length === 0) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error(`Export output directory ${root} already contains files. Re-run interactively or choose an empty directory.`);
}
const confirmed = await p.confirm({
message: `Overwrite existing files in ${root}?`,
initialValue: false,
});
if (p.isCancel(confirmed) || !confirmed) {
throw new Error("Export cancelled.");
}
}
@@ -257,27 +335,42 @@ export function registerCompanyCommands(program: Command): void {
addCommonClientOptions(
company
.command("export")
.description("Export a company into portable manifest + markdown files")
.description("Export a company into a portable markdown package")
.argument("<companyId>", "Company ID")
.requiredOption("--out <path>", "Output directory")
.option("--include <values>", "Comma-separated include set: company,agents", "company,agents")
.option("--include <values>", "Comma-separated include set: company,agents,projects,issues,tasks,skills", "company,agents")
.option("--skills <values>", "Comma-separated skill slugs/keys to export")
.option("--projects <values>", "Comma-separated project shortnames/ids to export")
.option("--issues <values>", "Comma-separated issue identifiers/ids to export")
.option("--project-issues <values>", "Comma-separated project shortnames/ids whose issues should be exported")
.option("--expand-referenced-skills", "Vendor skill contents instead of exporting upstream references", false)
.action(async (companyId: string, opts: CompanyExportOptions) => {
try {
const ctx = resolveCommandContext(opts);
const include = parseInclude(opts.include);
const exported = await ctx.api.post<CompanyPortabilityExportResult>(
`/api/companies/${companyId}/export`,
{ include },
{
include,
skills: parseCsvValues(opts.skills),
projects: parseCsvValues(opts.projects),
issues: parseCsvValues(opts.issues),
projectIssues: parseCsvValues(opts.projectIssues),
expandReferencedSkills: Boolean(opts.expandReferencedSkills),
},
);
if (!exported) {
throw new Error("Export request returned no data");
}
await confirmOverwriteExportDirectory(opts.out!);
await writeExportToFolder(opts.out!, exported);
printOutput(
{
ok: true,
out: path.resolve(opts.out!),
filesWritten: Object.keys(exported.files).length + 1,
rootPath: exported.rootPath,
filesWritten: Object.keys(exported.files).length,
paperclipExtensionPath: exported.paperclipExtensionPath,
warningCount: exported.warnings.length,
},
{ json: ctx.json },
@@ -296,9 +389,9 @@ export function registerCompanyCommands(program: Command): void {
addCommonClientOptions(
company
.command("import")
.description("Import a portable company package from local path, URL, or GitHub")
.description("Import a portable markdown company package from local path, URL, or GitHub")
.requiredOption("--from <pathOrUrl>", "Source path or URL")
.option("--include <values>", "Comma-separated include set: company,agents", "company,agents")
.option("--include <values>", "Comma-separated include set: company,agents,projects,issues,tasks,skills", "company,agents")
.option("--target <mode>", "Target mode: new | existing")
.option("-C, --company-id <id>", "Existing target company ID")
.option("--new-company-name <name>", "Name override for --target new")
@@ -343,19 +436,22 @@ export function registerCompanyCommands(program: Command): void {
}
let sourcePayload:
| { type: "inline"; manifest: CompanyPortabilityManifest; files: Record<string, string> }
| { type: "url"; url: string }
| { type: "inline"; rootPath?: string | null; files: Record<string, CompanyPortabilityFileEntry> }
| { type: "github"; url: string };
if (isHttpUrl(from)) {
sourcePayload = isGithubUrl(from)
? { type: "github", url: from }
: { type: "url", url: from };
if (!isGithubUrl(from)) {
throw new Error(
"Only GitHub URLs and local paths are supported for import. " +
"Generic HTTP URLs are not supported. Use a GitHub URL (https://github.com/...) or a local directory path.",
);
}
sourcePayload = { type: "github", url: from };
} else {
const inline = await resolveInlineSourceFromPath(from);
sourcePayload = {
type: "inline",
manifest: inline.manifest,
rootPath: inline.rootPath,
files: inline.files,
};
}

View File

@@ -0,0 +1,374 @@
import path from "node:path";
import { Command } from "commander";
import pc from "picocolors";
import {
addCommonClientOptions,
handleCommandError,
printOutput,
resolveCommandContext,
type BaseClientOptions,
} from "./common.js";
// ---------------------------------------------------------------------------
// Types mirroring server-side shapes
// ---------------------------------------------------------------------------
interface PluginRecord {
id: string;
pluginKey: string;
packageName: string;
version: string;
status: string;
displayName?: string;
lastError?: string | null;
installedAt: string;
updatedAt: string;
}
// ---------------------------------------------------------------------------
// Option types
// ---------------------------------------------------------------------------
interface PluginListOptions extends BaseClientOptions {
status?: string;
}
interface PluginInstallOptions extends BaseClientOptions {
local?: boolean;
version?: string;
}
interface PluginUninstallOptions extends BaseClientOptions {
force?: boolean;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Resolve a local path argument to an absolute path so the server can find the
* plugin on disk regardless of where the user ran the CLI.
*/
function resolvePackageArg(packageArg: string, isLocal: boolean): string {
if (!isLocal) return packageArg;
// Already absolute
if (path.isAbsolute(packageArg)) return packageArg;
// Expand leading ~ to home directory
if (packageArg.startsWith("~")) {
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
return path.resolve(home, packageArg.slice(1).replace(/^[\\/]/, ""));
}
return path.resolve(process.cwd(), packageArg);
}
function formatPlugin(p: PluginRecord): string {
const statusColor =
p.status === "ready"
? pc.green(p.status)
: p.status === "error"
? pc.red(p.status)
: p.status === "disabled"
? pc.dim(p.status)
: pc.yellow(p.status);
const parts = [
`key=${pc.bold(p.pluginKey)}`,
`status=${statusColor}`,
`version=${p.version}`,
`id=${pc.dim(p.id)}`,
];
if (p.lastError) {
parts.push(`error=${pc.red(p.lastError.slice(0, 80))}`);
}
return parts.join(" ");
}
// ---------------------------------------------------------------------------
// Command registration
// ---------------------------------------------------------------------------
export function registerPluginCommands(program: Command): void {
const plugin = program.command("plugin").description("Plugin lifecycle management");
// -------------------------------------------------------------------------
// plugin list
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("list")
.description("List installed plugins")
.option("--status <status>", "Filter by status (ready, error, disabled, installed, upgrade_pending)")
.action(async (opts: PluginListOptions) => {
try {
const ctx = resolveCommandContext(opts);
const qs = opts.status ? `?status=${encodeURIComponent(opts.status)}` : "";
const plugins = await ctx.api.get<PluginRecord[]>(`/api/plugins${qs}`);
if (ctx.json) {
printOutput(plugins, { json: true });
return;
}
const rows = plugins ?? [];
if (rows.length === 0) {
console.log(pc.dim("No plugins installed."));
return;
}
for (const p of rows) {
console.log(formatPlugin(p));
}
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin install <package-or-path>
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("install <package>")
.description(
"Install a plugin from a local path or npm package.\n" +
" Examples:\n" +
" paperclipai plugin install ./my-plugin # local path\n" +
" paperclipai plugin install @acme/plugin-linear # npm package\n" +
" paperclipai plugin install @acme/plugin-linear@1.2 # pinned version",
)
.option("-l, --local", "Treat <package> as a local filesystem path", false)
.option("--version <version>", "Specific npm version to install (npm packages only)")
.action(async (packageArg: string, opts: PluginInstallOptions) => {
try {
const ctx = resolveCommandContext(opts);
// Auto-detect local paths: starts with . or / or ~ or is an absolute path
const isLocal =
opts.local ||
packageArg.startsWith("./") ||
packageArg.startsWith("../") ||
packageArg.startsWith("/") ||
packageArg.startsWith("~");
const resolvedPackage = resolvePackageArg(packageArg, isLocal);
if (!ctx.json) {
console.log(
pc.dim(
isLocal
? `Installing plugin from local path: ${resolvedPackage}`
: `Installing plugin: ${resolvedPackage}${opts.version ? `@${opts.version}` : ""}`,
),
);
}
const installedPlugin = await ctx.api.post<PluginRecord>("/api/plugins/install", {
packageName: resolvedPackage,
version: opts.version,
isLocalPath: isLocal,
});
if (ctx.json) {
printOutput(installedPlugin, { json: true });
return;
}
if (!installedPlugin) {
console.log(pc.dim("Install returned no plugin record."));
return;
}
console.log(
pc.green(
`✓ Installed ${pc.bold(installedPlugin.pluginKey)} v${installedPlugin.version} (${installedPlugin.status})`,
),
);
if (installedPlugin.lastError) {
console.log(pc.red(` Warning: ${installedPlugin.lastError}`));
}
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin uninstall <plugin-key-or-id>
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("uninstall <pluginKey>")
.description(
"Uninstall a plugin by its plugin key or database ID.\n" +
" Use --force to hard-purge all state and config.",
)
.option("--force", "Purge all plugin state and config (hard delete)", false)
.action(async (pluginKey: string, opts: PluginUninstallOptions) => {
try {
const ctx = resolveCommandContext(opts);
const purge = opts.force === true;
const qs = purge ? "?purge=true" : "";
if (!ctx.json) {
console.log(
pc.dim(
purge
? `Uninstalling and purging plugin: ${pluginKey}`
: `Uninstalling plugin: ${pluginKey}`,
),
);
}
const result = await ctx.api.delete<PluginRecord | null>(
`/api/plugins/${encodeURIComponent(pluginKey)}${qs}`,
);
if (ctx.json) {
printOutput(result, { json: true });
return;
}
console.log(pc.green(`✓ Uninstalled ${pc.bold(pluginKey)}${purge ? " (purged)" : ""}`));
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin enable <plugin-key-or-id>
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("enable <pluginKey>")
.description("Enable a disabled or errored plugin")
.action(async (pluginKey: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const result = await ctx.api.post<PluginRecord>(
`/api/plugins/${encodeURIComponent(pluginKey)}/enable`,
);
if (ctx.json) {
printOutput(result, { json: true });
return;
}
console.log(pc.green(`✓ Enabled ${pc.bold(pluginKey)} — status: ${result?.status ?? "unknown"}`));
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin disable <plugin-key-or-id>
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("disable <pluginKey>")
.description("Disable a running plugin without uninstalling it")
.action(async (pluginKey: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const result = await ctx.api.post<PluginRecord>(
`/api/plugins/${encodeURIComponent(pluginKey)}/disable`,
);
if (ctx.json) {
printOutput(result, { json: true });
return;
}
console.log(pc.dim(`Disabled ${pc.bold(pluginKey)} — status: ${result?.status ?? "unknown"}`));
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin inspect <plugin-key-or-id>
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("inspect <pluginKey>")
.description("Show full details for an installed plugin")
.action(async (pluginKey: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const result = await ctx.api.get<PluginRecord>(
`/api/plugins/${encodeURIComponent(pluginKey)}`,
);
if (ctx.json) {
printOutput(result, { json: true });
return;
}
if (!result) {
console.log(pc.red(`Plugin not found: ${pluginKey}`));
process.exit(1);
}
console.log(formatPlugin(result));
if (result.lastError) {
console.log(`\n${pc.red("Last error:")}\n${result.lastError}`);
}
} catch (err) {
handleCommandError(err);
}
}),
);
// -------------------------------------------------------------------------
// plugin examples
// -------------------------------------------------------------------------
addCommonClientOptions(
plugin
.command("examples")
.description("List bundled example plugins available for local install")
.action(async (opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const examples = await ctx.api.get<
Array<{
packageName: string;
pluginKey: string;
displayName: string;
description: string;
localPath: string;
tag: string;
}>
>("/api/plugins/examples");
if (ctx.json) {
printOutput(examples, { json: true });
return;
}
const rows = examples ?? [];
if (rows.length === 0) {
console.log(pc.dim("No bundled examples available."));
return;
}
for (const ex of rows) {
console.log(
`${pc.bold(ex.displayName)} ${pc.dim(ex.pluginKey)}\n` +
` ${ex.description}\n` +
` ${pc.cyan(`paperclipai plugin install ${ex.localPath}`)}`,
);
}
} catch (err) {
handleCommandError(err);
}
}),
);
}

View File

@@ -0,0 +1,709 @@
import {
agents,
assets,
documentRevisions,
goals,
issueAttachments,
issueComments,
issueDocuments,
issues,
projects,
projectWorkspaces,
} from "@paperclipai/db";
type IssueRow = typeof issues.$inferSelect;
type CommentRow = typeof issueComments.$inferSelect;
type AgentRow = typeof agents.$inferSelect;
type ProjectRow = typeof projects.$inferSelect;
type ProjectWorkspaceRow = typeof projectWorkspaces.$inferSelect;
type GoalRow = typeof goals.$inferSelect;
type IssueDocumentLinkRow = typeof issueDocuments.$inferSelect;
type DocumentRevisionTableRow = typeof documentRevisions.$inferSelect;
type IssueAttachmentTableRow = typeof issueAttachments.$inferSelect;
type AssetRow = typeof assets.$inferSelect;
export const WORKTREE_MERGE_SCOPES = ["issues", "comments"] as const;
export type WorktreeMergeScope = (typeof WORKTREE_MERGE_SCOPES)[number];
export type ImportAdjustment =
| "clear_assignee_agent"
| "clear_project"
| "clear_project_workspace"
| "clear_goal"
| "clear_author_agent"
| "coerce_in_progress_to_todo"
| "clear_document_agent"
| "clear_document_revision_agent"
| "clear_attachment_agent";
export type IssueMergeAction = "skip_existing" | "insert";
export type CommentMergeAction = "skip_existing" | "skip_missing_parent" | "insert";
export type PlannedIssueInsert = {
source: IssueRow;
action: "insert";
previewIssueNumber: number;
previewIdentifier: string;
targetStatus: string;
targetAssigneeAgentId: string | null;
targetCreatedByAgentId: string | null;
targetProjectId: string | null;
targetProjectWorkspaceId: string | null;
targetGoalId: string | null;
projectResolution: "preserved" | "cleared" | "mapped";
mappedProjectName: string | null;
adjustments: ImportAdjustment[];
};
export type PlannedIssueSkip = {
source: IssueRow;
action: "skip_existing";
driftKeys: string[];
};
export type PlannedCommentInsert = {
source: CommentRow;
action: "insert";
targetAuthorAgentId: string | null;
adjustments: ImportAdjustment[];
};
export type PlannedCommentSkip = {
source: CommentRow;
action: "skip_existing" | "skip_missing_parent";
};
export type IssueDocumentRow = {
id: IssueDocumentLinkRow["id"];
companyId: IssueDocumentLinkRow["companyId"];
issueId: IssueDocumentLinkRow["issueId"];
documentId: IssueDocumentLinkRow["documentId"];
key: IssueDocumentLinkRow["key"];
linkCreatedAt: IssueDocumentLinkRow["createdAt"];
linkUpdatedAt: IssueDocumentLinkRow["updatedAt"];
title: string | null;
format: string;
latestBody: string;
latestRevisionId: string | null;
latestRevisionNumber: number;
createdByAgentId: string | null;
createdByUserId: string | null;
updatedByAgentId: string | null;
updatedByUserId: string | null;
documentCreatedAt: Date;
documentUpdatedAt: Date;
};
export type DocumentRevisionRow = {
id: DocumentRevisionTableRow["id"];
companyId: DocumentRevisionTableRow["companyId"];
documentId: DocumentRevisionTableRow["documentId"];
revisionNumber: DocumentRevisionTableRow["revisionNumber"];
body: DocumentRevisionTableRow["body"];
changeSummary: DocumentRevisionTableRow["changeSummary"];
createdByAgentId: string | null;
createdByUserId: string | null;
createdAt: Date;
};
export type IssueAttachmentRow = {
id: IssueAttachmentTableRow["id"];
companyId: IssueAttachmentTableRow["companyId"];
issueId: IssueAttachmentTableRow["issueId"];
issueCommentId: IssueAttachmentTableRow["issueCommentId"];
assetId: IssueAttachmentTableRow["assetId"];
provider: AssetRow["provider"];
objectKey: AssetRow["objectKey"];
contentType: AssetRow["contentType"];
byteSize: AssetRow["byteSize"];
sha256: AssetRow["sha256"];
originalFilename: AssetRow["originalFilename"];
createdByAgentId: string | null;
createdByUserId: string | null;
assetCreatedAt: Date;
assetUpdatedAt: Date;
attachmentCreatedAt: Date;
attachmentUpdatedAt: Date;
};
export type PlannedDocumentRevisionInsert = {
source: DocumentRevisionRow;
targetRevisionNumber: number;
targetCreatedByAgentId: string | null;
adjustments: ImportAdjustment[];
};
export type PlannedIssueDocumentInsert = {
source: IssueDocumentRow;
action: "insert";
targetCreatedByAgentId: string | null;
targetUpdatedByAgentId: string | null;
latestRevisionId: string | null;
latestRevisionNumber: number;
revisionsToInsert: PlannedDocumentRevisionInsert[];
adjustments: ImportAdjustment[];
};
export type PlannedIssueDocumentMerge = {
source: IssueDocumentRow;
action: "merge_existing";
targetCreatedByAgentId: string | null;
targetUpdatedByAgentId: string | null;
latestRevisionId: string | null;
latestRevisionNumber: number;
revisionsToInsert: PlannedDocumentRevisionInsert[];
adjustments: ImportAdjustment[];
};
export type PlannedIssueDocumentSkip = {
source: IssueDocumentRow;
action: "skip_existing" | "skip_missing_parent" | "skip_conflicting_key";
};
export type PlannedAttachmentInsert = {
source: IssueAttachmentRow;
action: "insert";
targetIssueCommentId: string | null;
targetCreatedByAgentId: string | null;
adjustments: ImportAdjustment[];
};
export type PlannedAttachmentSkip = {
source: IssueAttachmentRow;
action: "skip_existing" | "skip_missing_parent";
};
export type WorktreeMergePlan = {
companyId: string;
companyName: string;
issuePrefix: string;
previewIssueCounterStart: number;
scopes: WorktreeMergeScope[];
issuePlans: Array<PlannedIssueInsert | PlannedIssueSkip>;
commentPlans: Array<PlannedCommentInsert | PlannedCommentSkip>;
documentPlans: Array<PlannedIssueDocumentInsert | PlannedIssueDocumentMerge | PlannedIssueDocumentSkip>;
attachmentPlans: Array<PlannedAttachmentInsert | PlannedAttachmentSkip>;
counts: {
issuesToInsert: number;
issuesExisting: number;
issueDrift: number;
commentsToInsert: number;
commentsExisting: number;
commentsMissingParent: number;
documentsToInsert: number;
documentsToMerge: number;
documentsExisting: number;
documentsConflictingKey: number;
documentsMissingParent: number;
documentRevisionsToInsert: number;
attachmentsToInsert: number;
attachmentsExisting: number;
attachmentsMissingParent: number;
};
adjustments: Record<ImportAdjustment, number>;
};
function compareIssueCoreFields(source: IssueRow, target: IssueRow): string[] {
const driftKeys: string[] = [];
if (source.title !== target.title) driftKeys.push("title");
if ((source.description ?? null) !== (target.description ?? null)) driftKeys.push("description");
if (source.status !== target.status) driftKeys.push("status");
if (source.priority !== target.priority) driftKeys.push("priority");
if ((source.parentId ?? null) !== (target.parentId ?? null)) driftKeys.push("parentId");
if ((source.projectId ?? null) !== (target.projectId ?? null)) driftKeys.push("projectId");
if ((source.projectWorkspaceId ?? null) !== (target.projectWorkspaceId ?? null)) driftKeys.push("projectWorkspaceId");
if ((source.goalId ?? null) !== (target.goalId ?? null)) driftKeys.push("goalId");
if ((source.assigneeAgentId ?? null) !== (target.assigneeAgentId ?? null)) driftKeys.push("assigneeAgentId");
if ((source.assigneeUserId ?? null) !== (target.assigneeUserId ?? null)) driftKeys.push("assigneeUserId");
return driftKeys;
}
function incrementAdjustment(
counts: Record<ImportAdjustment, number>,
adjustment: ImportAdjustment,
): void {
counts[adjustment] += 1;
}
function groupBy<T>(rows: T[], keyFor: (row: T) => string): Map<string, T[]> {
const out = new Map<string, T[]>();
for (const row of rows) {
const key = keyFor(row);
const existing = out.get(key);
if (existing) {
existing.push(row);
} else {
out.set(key, [row]);
}
}
return out;
}
function sameDate(left: Date, right: Date): boolean {
return left.getTime() === right.getTime();
}
function sortDocumentRows(rows: IssueDocumentRow[]): IssueDocumentRow[] {
return [...rows].sort((left, right) => {
const createdDelta = left.documentCreatedAt.getTime() - right.documentCreatedAt.getTime();
if (createdDelta !== 0) return createdDelta;
const linkDelta = left.linkCreatedAt.getTime() - right.linkCreatedAt.getTime();
if (linkDelta !== 0) return linkDelta;
return left.documentId.localeCompare(right.documentId);
});
}
function sortDocumentRevisions(rows: DocumentRevisionRow[]): DocumentRevisionRow[] {
return [...rows].sort((left, right) => {
const revisionDelta = left.revisionNumber - right.revisionNumber;
if (revisionDelta !== 0) return revisionDelta;
const createdDelta = left.createdAt.getTime() - right.createdAt.getTime();
if (createdDelta !== 0) return createdDelta;
return left.id.localeCompare(right.id);
});
}
function sortAttachments(rows: IssueAttachmentRow[]): IssueAttachmentRow[] {
return [...rows].sort((left, right) => {
const createdDelta = left.attachmentCreatedAt.getTime() - right.attachmentCreatedAt.getTime();
if (createdDelta !== 0) return createdDelta;
return left.id.localeCompare(right.id);
});
}
function sortIssuesForImport(sourceIssues: IssueRow[]): IssueRow[] {
const byId = new Map(sourceIssues.map((issue) => [issue.id, issue]));
const memoDepth = new Map<string, number>();
const depthFor = (issue: IssueRow, stack = new Set<string>()): number => {
const memoized = memoDepth.get(issue.id);
if (memoized !== undefined) return memoized;
if (!issue.parentId) {
memoDepth.set(issue.id, 0);
return 0;
}
if (stack.has(issue.id)) {
memoDepth.set(issue.id, 0);
return 0;
}
const parent = byId.get(issue.parentId);
if (!parent) {
memoDepth.set(issue.id, 0);
return 0;
}
stack.add(issue.id);
const depth = depthFor(parent, stack) + 1;
stack.delete(issue.id);
memoDepth.set(issue.id, depth);
return depth;
};
return [...sourceIssues].sort((left, right) => {
const depthDelta = depthFor(left) - depthFor(right);
if (depthDelta !== 0) return depthDelta;
const createdDelta = left.createdAt.getTime() - right.createdAt.getTime();
if (createdDelta !== 0) return createdDelta;
return left.id.localeCompare(right.id);
});
}
export function parseWorktreeMergeScopes(rawValue: string | undefined): WorktreeMergeScope[] {
if (!rawValue || rawValue.trim().length === 0) {
return ["issues", "comments"];
}
const parsed = rawValue
.split(",")
.map((value) => value.trim().toLowerCase())
.filter((value): value is WorktreeMergeScope =>
(WORKTREE_MERGE_SCOPES as readonly string[]).includes(value),
);
if (parsed.length === 0) {
throw new Error(
`Invalid scope "${rawValue}". Expected a comma-separated list of: ${WORKTREE_MERGE_SCOPES.join(", ")}.`,
);
}
return [...new Set(parsed)];
}
export function buildWorktreeMergePlan(input: {
companyId: string;
companyName: string;
issuePrefix: string;
previewIssueCounterStart: number;
scopes: WorktreeMergeScope[];
sourceIssues: IssueRow[];
targetIssues: IssueRow[];
sourceComments: CommentRow[];
targetComments: CommentRow[];
sourceDocuments?: IssueDocumentRow[];
targetDocuments?: IssueDocumentRow[];
sourceDocumentRevisions?: DocumentRevisionRow[];
targetDocumentRevisions?: DocumentRevisionRow[];
sourceAttachments?: IssueAttachmentRow[];
targetAttachments?: IssueAttachmentRow[];
targetAgents: AgentRow[];
targetProjects: ProjectRow[];
targetProjectWorkspaces: ProjectWorkspaceRow[];
targetGoals: GoalRow[];
projectIdOverrides?: Record<string, string | null | undefined>;
}): WorktreeMergePlan {
const targetIssuesById = new Map(input.targetIssues.map((issue) => [issue.id, issue]));
const targetCommentIds = new Set(input.targetComments.map((comment) => comment.id));
const targetAgentIds = new Set(input.targetAgents.map((agent) => agent.id));
const targetProjectIds = new Set(input.targetProjects.map((project) => project.id));
const targetProjectsById = new Map(input.targetProjects.map((project) => [project.id, project]));
const targetProjectWorkspaceIds = new Set(input.targetProjectWorkspaces.map((workspace) => workspace.id));
const targetGoalIds = new Set(input.targetGoals.map((goal) => goal.id));
const scopes = new Set(input.scopes);
const adjustmentCounts: Record<ImportAdjustment, number> = {
clear_assignee_agent: 0,
clear_project: 0,
clear_project_workspace: 0,
clear_goal: 0,
clear_author_agent: 0,
coerce_in_progress_to_todo: 0,
clear_document_agent: 0,
clear_document_revision_agent: 0,
clear_attachment_agent: 0,
};
const issuePlans: Array<PlannedIssueInsert | PlannedIssueSkip> = [];
let nextPreviewIssueNumber = input.previewIssueCounterStart;
for (const issue of sortIssuesForImport(input.sourceIssues)) {
const existing = targetIssuesById.get(issue.id);
if (existing) {
issuePlans.push({
source: issue,
action: "skip_existing",
driftKeys: compareIssueCoreFields(issue, existing),
});
continue;
}
nextPreviewIssueNumber += 1;
const adjustments: ImportAdjustment[] = [];
const targetAssigneeAgentId =
issue.assigneeAgentId && targetAgentIds.has(issue.assigneeAgentId) ? issue.assigneeAgentId : null;
if (issue.assigneeAgentId && !targetAssigneeAgentId) {
adjustments.push("clear_assignee_agent");
incrementAdjustment(adjustmentCounts, "clear_assignee_agent");
}
const targetCreatedByAgentId =
issue.createdByAgentId && targetAgentIds.has(issue.createdByAgentId) ? issue.createdByAgentId : null;
let targetProjectId =
issue.projectId && targetProjectIds.has(issue.projectId) ? issue.projectId : null;
let projectResolution: PlannedIssueInsert["projectResolution"] = targetProjectId ? "preserved" : "cleared";
let mappedProjectName: string | null = null;
const overrideProjectId =
issue.projectId && input.projectIdOverrides
? input.projectIdOverrides[issue.projectId] ?? null
: null;
if (!targetProjectId && overrideProjectId && targetProjectIds.has(overrideProjectId)) {
targetProjectId = overrideProjectId;
projectResolution = "mapped";
mappedProjectName = targetProjectsById.get(overrideProjectId)?.name ?? null;
}
if (issue.projectId && !targetProjectId) {
adjustments.push("clear_project");
incrementAdjustment(adjustmentCounts, "clear_project");
}
const targetProjectWorkspaceId =
targetProjectId
&& targetProjectId === issue.projectId
&& issue.projectWorkspaceId
&& targetProjectWorkspaceIds.has(issue.projectWorkspaceId)
? issue.projectWorkspaceId
: null;
if (issue.projectWorkspaceId && !targetProjectWorkspaceId) {
adjustments.push("clear_project_workspace");
incrementAdjustment(adjustmentCounts, "clear_project_workspace");
}
const targetGoalId =
issue.goalId && targetGoalIds.has(issue.goalId) ? issue.goalId : null;
if (issue.goalId && !targetGoalId) {
adjustments.push("clear_goal");
incrementAdjustment(adjustmentCounts, "clear_goal");
}
let targetStatus = issue.status;
if (
targetStatus === "in_progress"
&& !targetAssigneeAgentId
&& !(issue.assigneeUserId && issue.assigneeUserId.trim().length > 0)
) {
targetStatus = "todo";
adjustments.push("coerce_in_progress_to_todo");
incrementAdjustment(adjustmentCounts, "coerce_in_progress_to_todo");
}
issuePlans.push({
source: issue,
action: "insert",
previewIssueNumber: nextPreviewIssueNumber,
previewIdentifier: `${input.issuePrefix}-${nextPreviewIssueNumber}`,
targetStatus,
targetAssigneeAgentId,
targetCreatedByAgentId,
targetProjectId,
targetProjectWorkspaceId,
targetGoalId,
projectResolution,
mappedProjectName,
adjustments,
});
}
const issueIdsAvailableAfterImport = new Set<string>([
...input.targetIssues.map((issue) => issue.id),
...issuePlans.filter((plan): plan is PlannedIssueInsert => plan.action === "insert").map((plan) => plan.source.id),
]);
const commentPlans: Array<PlannedCommentInsert | PlannedCommentSkip> = [];
if (scopes.has("comments")) {
const sortedComments = [...input.sourceComments].sort((left, right) => {
const createdDelta = left.createdAt.getTime() - right.createdAt.getTime();
if (createdDelta !== 0) return createdDelta;
return left.id.localeCompare(right.id);
});
for (const comment of sortedComments) {
if (targetCommentIds.has(comment.id)) {
commentPlans.push({ source: comment, action: "skip_existing" });
continue;
}
if (!issueIdsAvailableAfterImport.has(comment.issueId)) {
commentPlans.push({ source: comment, action: "skip_missing_parent" });
continue;
}
const adjustments: ImportAdjustment[] = [];
const targetAuthorAgentId =
comment.authorAgentId && targetAgentIds.has(comment.authorAgentId) ? comment.authorAgentId : null;
if (comment.authorAgentId && !targetAuthorAgentId) {
adjustments.push("clear_author_agent");
incrementAdjustment(adjustmentCounts, "clear_author_agent");
}
commentPlans.push({
source: comment,
action: "insert",
targetAuthorAgentId,
adjustments,
});
}
}
const sourceDocuments = input.sourceDocuments ?? [];
const targetDocuments = input.targetDocuments ?? [];
const sourceDocumentRevisions = input.sourceDocumentRevisions ?? [];
const targetDocumentRevisions = input.targetDocumentRevisions ?? [];
const targetDocumentsById = new Map(targetDocuments.map((document) => [document.documentId, document]));
const targetDocumentsByIssueKey = new Map(targetDocuments.map((document) => [`${document.issueId}:${document.key}`, document]));
const sourceRevisionsByDocumentId = groupBy(sourceDocumentRevisions, (revision) => revision.documentId);
const targetRevisionsByDocumentId = groupBy(targetDocumentRevisions, (revision) => revision.documentId);
const commentIdsAvailableAfterImport = new Set<string>([
...input.targetComments.map((comment) => comment.id),
...commentPlans.filter((plan): plan is PlannedCommentInsert => plan.action === "insert").map((plan) => plan.source.id),
]);
const documentPlans: Array<PlannedIssueDocumentInsert | PlannedIssueDocumentMerge | PlannedIssueDocumentSkip> = [];
for (const document of sortDocumentRows(sourceDocuments)) {
if (!issueIdsAvailableAfterImport.has(document.issueId)) {
documentPlans.push({ source: document, action: "skip_missing_parent" });
continue;
}
const existingDocument = targetDocumentsById.get(document.documentId);
const conflictingIssueKeyDocument = targetDocumentsByIssueKey.get(`${document.issueId}:${document.key}`);
if (!existingDocument && conflictingIssueKeyDocument && conflictingIssueKeyDocument.documentId !== document.documentId) {
documentPlans.push({ source: document, action: "skip_conflicting_key" });
continue;
}
const adjustments: ImportAdjustment[] = [];
const targetCreatedByAgentId =
document.createdByAgentId && targetAgentIds.has(document.createdByAgentId) ? document.createdByAgentId : null;
const targetUpdatedByAgentId =
document.updatedByAgentId && targetAgentIds.has(document.updatedByAgentId) ? document.updatedByAgentId : null;
if (
(document.createdByAgentId && !targetCreatedByAgentId)
|| (document.updatedByAgentId && !targetUpdatedByAgentId)
) {
adjustments.push("clear_document_agent");
incrementAdjustment(adjustmentCounts, "clear_document_agent");
}
const sourceRevisions = sortDocumentRevisions(sourceRevisionsByDocumentId.get(document.documentId) ?? []);
const targetRevisions = sortDocumentRevisions(targetRevisionsByDocumentId.get(document.documentId) ?? []);
const existingRevisionIds = new Set(targetRevisions.map((revision) => revision.id));
const usedRevisionNumbers = new Set(targetRevisions.map((revision) => revision.revisionNumber));
let nextRevisionNumber = targetRevisions.reduce(
(maxValue, revision) => Math.max(maxValue, revision.revisionNumber),
0,
) + 1;
const targetRevisionNumberById = new Map<string, number>(
targetRevisions.map((revision) => [revision.id, revision.revisionNumber]),
);
const revisionsToInsert: PlannedDocumentRevisionInsert[] = [];
for (const revision of sourceRevisions) {
if (existingRevisionIds.has(revision.id)) continue;
let targetRevisionNumber = revision.revisionNumber;
if (usedRevisionNumbers.has(targetRevisionNumber)) {
while (usedRevisionNumbers.has(nextRevisionNumber)) {
nextRevisionNumber += 1;
}
targetRevisionNumber = nextRevisionNumber;
nextRevisionNumber += 1;
}
usedRevisionNumbers.add(targetRevisionNumber);
targetRevisionNumberById.set(revision.id, targetRevisionNumber);
const revisionAdjustments: ImportAdjustment[] = [];
const targetCreatedByAgentId =
revision.createdByAgentId && targetAgentIds.has(revision.createdByAgentId) ? revision.createdByAgentId : null;
if (revision.createdByAgentId && !targetCreatedByAgentId) {
revisionAdjustments.push("clear_document_revision_agent");
incrementAdjustment(adjustmentCounts, "clear_document_revision_agent");
}
revisionsToInsert.push({
source: revision,
targetRevisionNumber,
targetCreatedByAgentId,
adjustments: revisionAdjustments,
});
}
const latestRevisionId = document.latestRevisionId ?? existingDocument?.latestRevisionId ?? null;
const latestRevisionNumber =
(latestRevisionId ? targetRevisionNumberById.get(latestRevisionId) : undefined)
?? document.latestRevisionNumber
?? existingDocument?.latestRevisionNumber
?? 0;
if (!existingDocument) {
documentPlans.push({
source: document,
action: "insert",
targetCreatedByAgentId,
targetUpdatedByAgentId,
latestRevisionId,
latestRevisionNumber,
revisionsToInsert,
adjustments,
});
continue;
}
const documentAlreadyMatches =
existingDocument.key === document.key
&& existingDocument.title === document.title
&& existingDocument.format === document.format
&& existingDocument.latestBody === document.latestBody
&& (existingDocument.latestRevisionId ?? null) === latestRevisionId
&& existingDocument.latestRevisionNumber === latestRevisionNumber
&& (existingDocument.updatedByAgentId ?? null) === targetUpdatedByAgentId
&& (existingDocument.updatedByUserId ?? null) === (document.updatedByUserId ?? null)
&& sameDate(existingDocument.documentUpdatedAt, document.documentUpdatedAt)
&& sameDate(existingDocument.linkUpdatedAt, document.linkUpdatedAt)
&& revisionsToInsert.length === 0;
if (documentAlreadyMatches) {
documentPlans.push({ source: document, action: "skip_existing" });
continue;
}
documentPlans.push({
source: document,
action: "merge_existing",
targetCreatedByAgentId,
targetUpdatedByAgentId,
latestRevisionId,
latestRevisionNumber,
revisionsToInsert,
adjustments,
});
}
const sourceAttachments = input.sourceAttachments ?? [];
const targetAttachmentIds = new Set((input.targetAttachments ?? []).map((attachment) => attachment.id));
const attachmentPlans: Array<PlannedAttachmentInsert | PlannedAttachmentSkip> = [];
for (const attachment of sortAttachments(sourceAttachments)) {
if (targetAttachmentIds.has(attachment.id)) {
attachmentPlans.push({ source: attachment, action: "skip_existing" });
continue;
}
if (!issueIdsAvailableAfterImport.has(attachment.issueId)) {
attachmentPlans.push({ source: attachment, action: "skip_missing_parent" });
continue;
}
const adjustments: ImportAdjustment[] = [];
const targetCreatedByAgentId =
attachment.createdByAgentId && targetAgentIds.has(attachment.createdByAgentId)
? attachment.createdByAgentId
: null;
if (attachment.createdByAgentId && !targetCreatedByAgentId) {
adjustments.push("clear_attachment_agent");
incrementAdjustment(adjustmentCounts, "clear_attachment_agent");
}
attachmentPlans.push({
source: attachment,
action: "insert",
targetIssueCommentId:
attachment.issueCommentId && commentIdsAvailableAfterImport.has(attachment.issueCommentId)
? attachment.issueCommentId
: null,
targetCreatedByAgentId,
adjustments,
});
}
const counts = {
issuesToInsert: issuePlans.filter((plan) => plan.action === "insert").length,
issuesExisting: issuePlans.filter((plan) => plan.action === "skip_existing").length,
issueDrift: issuePlans.filter((plan) => plan.action === "skip_existing" && plan.driftKeys.length > 0).length,
commentsToInsert: commentPlans.filter((plan) => plan.action === "insert").length,
commentsExisting: commentPlans.filter((plan) => plan.action === "skip_existing").length,
commentsMissingParent: commentPlans.filter((plan) => plan.action === "skip_missing_parent").length,
documentsToInsert: documentPlans.filter((plan) => plan.action === "insert").length,
documentsToMerge: documentPlans.filter((plan) => plan.action === "merge_existing").length,
documentsExisting: documentPlans.filter((plan) => plan.action === "skip_existing").length,
documentsConflictingKey: documentPlans.filter((plan) => plan.action === "skip_conflicting_key").length,
documentsMissingParent: documentPlans.filter((plan) => plan.action === "skip_missing_parent").length,
documentRevisionsToInsert: documentPlans.reduce(
(sum, plan) =>
sum + (plan.action === "insert" || plan.action === "merge_existing" ? plan.revisionsToInsert.length : 0),
0,
),
attachmentsToInsert: attachmentPlans.filter((plan) => plan.action === "insert").length,
attachmentsExisting: attachmentPlans.filter((plan) => plan.action === "skip_existing").length,
attachmentsMissingParent: attachmentPlans.filter((plan) => plan.action === "skip_missing_parent").length,
};
return {
companyId: input.companyId,
companyName: input.companyName,
issuePrefix: input.issuePrefix,
previewIssueCounterStart: input.previewIssueCounterStart,
scopes: input.scopes,
issuePlans,
commentPlans,
documentPlans,
attachmentPlans,
counts,
adjustments: adjustmentCounts,
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -18,6 +18,7 @@ import { registerDashboardCommands } from "./commands/client/dashboard.js";
import { applyDataDirOverride, type DataDirOptionLike } from "./config/data-dir.js";
import { loadPaperclipEnvFile } from "./config/env.js";
import { registerWorktreeCommands } from "./commands/worktree.js";
import { registerPluginCommands } from "./commands/client/plugin.js";
const program = new Command();
const DATA_DIR_OPTION_HELP =
@@ -136,6 +137,7 @@ registerApprovalCommands(program);
registerActivityCommands(program);
registerDashboardCommands(program);
registerWorktreeCommands(program);
registerPluginCommands(program);
const auth = program.command("auth").description("Authentication and bootstrap utilities");

View File

@@ -0,0 +1,114 @@
# Agent Companies Spec Inventory
This document indexes every part of the Paperclip codebase that touches the [Agent Companies Specification](docs/companies/companies-spec.md) (`agentcompanies/v1-draft`).
Use it when you need to:
1. **Update the spec** — know which implementation code must change in lockstep.
2. **Change code that involves the spec** — find all related files quickly.
3. **Keep things aligned** — audit whether implementation matches the spec.
---
## 1. Specification & Design Documents
| File | Role |
|---|---|
| `docs/companies/companies-spec.md` | **Normative spec** — defines the markdown-first package format (COMPANY.md, TEAM.md, AGENTS.md, PROJECT.md, TASK.md, SKILL.md), reserved files, frontmatter schemas, and vendor extension conventions (`.paperclip.yaml`). |
| `doc/plans/2026-03-13-company-import-export-v2.md` | Implementation plan for the markdown-first package model cutover — phases, API changes, UI plan, and rollout strategy. |
| `doc/SPEC-implementation.md` | V1 implementation contract; references the portability system and `.paperclip.yaml` sidecar format. |
| `docs/specs/cliphub-plan.md` | Earlier blueprint bundle plan; partially superseded by the markdown-first spec (noted in the v2 plan). |
| `doc/plans/2026-02-16-module-system.md` | Module system plan; JSON-only company template sections superseded by the markdown-first model. |
| `doc/plans/2026-03-14-skills-ui-product-plan.md` | Skills UI plan; references portable skill files and `.paperclip.yaml`. |
| `doc/plans/2026-03-14-adapter-skill-sync-rollout.md` | Adapter skill sync rollout; companion to the v2 import/export plan. |
## 2. Shared Types & Validators
These define the contract between server, CLI, and UI.
| File | What it defines |
|---|---|
| `packages/shared/src/types/company-portability.ts` | TypeScript interfaces: `CompanyPortabilityManifest`, `CompanyPortabilityFileEntry`, `CompanyPortabilityEnvInput`, export/import/preview request and result types, manifest entry types for agents, skills, projects, issues, companies. |
| `packages/shared/src/validators/company-portability.ts` | Zod schemas for all portability request/response shapes — used by both server routes and CLI. |
| `packages/shared/src/types/index.ts` | Re-exports portability types. |
| `packages/shared/src/validators/index.ts` | Re-exports portability validators. |
## 3. Server — Services
| File | Responsibility |
|---|---|
| `server/src/services/company-portability.ts` | **Core portability service.** Export (manifest generation, markdown file emission, `.paperclip.yaml` sidecars), import (graph resolution, collision handling, entity creation), preview (planned-action summary). Handles skill key derivation, task recurrence parsing, and package README generation. References `agentcompanies/v1` version string. |
| `server/src/services/company-export-readme.ts` | Generates `README.md` and Mermaid org-chart for exported company packages. |
| `server/src/services/index.ts` | Re-exports `companyPortabilityService`. |
## 4. Server — Routes
| File | Endpoints |
|---|---|
| `server/src/routes/companies.ts` | `POST /api/companies/:companyId/export` — legacy export bundle<br>`POST /api/companies/:companyId/exports/preview` — export preview<br>`POST /api/companies/:companyId/exports` — export package<br>`POST /api/companies/import/preview` — import preview<br>`POST /api/companies/import` — perform import |
Route registration lives in `server/src/app.ts` via `companyRoutes(db, storage)`.
## 5. Server — Tests
| File | Coverage |
|---|---|
| `server/src/__tests__/company-portability.test.ts` | Unit tests for the portability service (export, import, preview, manifest shape, `agentcompanies/v1` version). |
| `server/src/__tests__/company-portability-routes.test.ts` | Integration tests for the portability HTTP endpoints. |
## 6. CLI
| File | Commands |
|---|---|
| `cli/src/commands/client/company.ts` | `company export` — exports a company package to disk (flags: `--out`, `--include`, `--projects`, `--issues`, `--projectIssues`).<br>`company import` — imports a company package from a file or folder (flags: `--from`, `--include`, `--target`, `--companyId`, `--newCompanyName`, `--agents`, `--collision`, `--dryRun`).<br>Reads/writes portable file entries and handles `.paperclip.yaml` filtering. |
## 7. UI — Pages
| File | Role |
|---|---|
| `ui/src/pages/CompanyExport.tsx` | Export UI: preview, manifest display, file tree visualization, ZIP archive creation and download. Filters `.paperclip.yaml` based on selection. Shows manifest and README in editor. |
| `ui/src/pages/CompanyImport.tsx` | Import UI: source input (upload/folder/GitHub URL/generic URL), ZIP reading, preview pane with dependency tree, entity selection checkboxes, trust/licensing warnings, secrets requirements, collision strategy, adapter config. |
## 8. UI — Components
| File | Role |
|---|---|
| `ui/src/components/PackageFileTree.tsx` | Reusable file tree component for both import and export. Builds tree from `CompanyPortabilityFileEntry` items, parses frontmatter, shows action indicators (create/update/skip), and maps frontmatter field labels. |
## 9. UI — Libraries
| File | Role |
|---|---|
| `ui/src/lib/portable-files.ts` | Helpers for portable file entries: `getPortableFileText`, `getPortableFileDataUrl`, `getPortableFileContentType`, `isPortableImageFile`. |
| `ui/src/lib/zip.ts` | ZIP archive creation (`createZipArchive`) and reading (`readZipArchive`) — implements ZIP format from scratch for company packages. CRC32, DOS date/time encoding. |
| `ui/src/lib/zip.test.ts` | Tests for ZIP utilities; exercises round-trip with portability file entries and `.paperclip.yaml` content. |
## 10. UI — API Client
| File | Functions |
|---|---|
| `ui/src/api/companies.ts` | `companiesApi.exportBundle`, `companiesApi.exportPreview`, `companiesApi.exportPackage`, `companiesApi.importPreview`, `companiesApi.importBundle` — typed fetch wrappers for the portability endpoints. |
## 11. Skills & Agent Instructions
| File | Relevance |
|---|---|
| `skills/paperclip/references/company-skills.md` | Reference doc for company skill library workflow — install, inspect, update, assign. Skill packages are a subset of the agent companies spec. |
| `server/src/services/company-skills.ts` | Company skill management service — handles SKILL.md-based imports and company-level skill library. |
| `server/src/services/agent-instructions.ts` | Agent instructions service — resolves AGENTS.md paths for agent instruction loading. |
## 12. Quick Cross-Reference by Spec Concept
| Spec concept | Primary implementation files |
|---|---|
| `COMPANY.md` frontmatter & body | `company-portability.ts` (export emitter + import parser) |
| `AGENTS.md` frontmatter & body | `company-portability.ts`, `agent-instructions.ts` |
| `PROJECT.md` frontmatter & body | `company-portability.ts` |
| `TASK.md` frontmatter & body | `company-portability.ts` |
| `SKILL.md` packages | `company-portability.ts`, `company-skills.ts` |
| `.paperclip.yaml` vendor sidecar | `company-portability.ts`, `CompanyExport.tsx`, `company.ts` (CLI) |
| `manifest.json` | `company-portability.ts` (generation), shared types (schema) |
| ZIP package format | `zip.ts` (UI), `company.ts` (CLI file I/O) |
| Collision resolution | `company-portability.ts` (server), `CompanyImport.tsx` (UI) |
| Env/secrets declarations | shared types (`CompanyPortabilityEnvInput`), `CompanyImport.tsx` (UI) |
| README + org chart | `company-export-readme.ts` |

View File

@@ -39,6 +39,8 @@ This starts:
`pnpm dev` runs the server in watch mode and restarts on changes from workspace packages (including adapter packages). Use `pnpm dev:once` to run without file watching.
`pnpm dev:once` now tracks backend-relevant file changes and pending migrations. When the current boot is stale, the board UI shows a `Restart required` banner. You can also enable guarded auto-restart in `Instance Settings > Experimental`, which waits for queued/running local agent runs to finish before restarting the dev server.
Tailscale/private-auth dev mode:
```sh
@@ -89,6 +91,10 @@ docker compose -f docker-compose.quickstart.yml up --build
See `doc/DOCKER.md` for API key wiring (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY`) and persistence details.
## Docker For Untrusted PR Review
For a separate review-oriented container that keeps `codex`/`claude` login state in Docker volumes and checks out PRs into an isolated scratch workspace, see `doc/UNTRUSTED-PR-REVIEW.md`.
## Database in Dev (Auto-Handled)
For local development, leave `DATABASE_URL` unset.
@@ -124,6 +130,10 @@ When a local agent run has no resolved project/session workspace, Paperclip fall
This path honors `PAPERCLIP_HOME` and `PAPERCLIP_INSTANCE_ID` in non-default setups.
For `codex_local`, Paperclip also manages a per-company Codex home under the instance root and seeds it from the shared Codex login/config home (`$CODEX_HOME` or `~/.codex`):
- `~/.paperclip/instances/default/companies/<company-id>/codex-home`
## Worktree-local Instances
When developing from multiple git worktrees, do not point two Paperclip servers at the same embedded PostgreSQL data directory.

View File

@@ -93,6 +93,12 @@ Notes:
- Without API keys, the app still runs normally.
- Adapter environment checks in Paperclip will surface missing auth/CLI prerequisites.
## Untrusted PR Review Container
If you want a separate Docker environment for reviewing untrusted pull requests with `codex` or `claude`, use the dedicated review workflow in `doc/UNTRUSTED-PR-REVIEW.md`.
That setup keeps CLI auth state in Docker volumes instead of your host home directory and uses a separate scratch workspace for PR checkouts and preview runs.
## Onboard Smoke Test (Ubuntu + npm only)
Use this when you want to mimic a fresh machine that only has Ubuntu + npm and verify:
@@ -114,6 +120,7 @@ Useful overrides:
```sh
HOST_PORT=3200 PAPERCLIPAI_VERSION=latest ./scripts/docker-onboard-smoke.sh
PAPERCLIP_DEPLOYMENT_MODE=authenticated PAPERCLIP_DEPLOYMENT_EXPOSURE=private ./scripts/docker-onboard-smoke.sh
SMOKE_DETACH=true SMOKE_METADATA_FILE=/tmp/paperclip-smoke.env PAPERCLIPAI_VERSION=latest ./scripts/docker-onboard-smoke.sh
```
Notes:
@@ -125,4 +132,5 @@ Notes:
- Smoke script also defaults `PAPERCLIP_PUBLIC_URL` to `http://localhost:<HOST_PORT>` so bootstrap invite URLs and auth callbacks use the reachable host port instead of the container's internal `3100`.
- In authenticated mode, the smoke script defaults `SMOKE_AUTO_BOOTSTRAP=true` and drives the real bootstrap path automatically: it signs up a real user, runs `paperclipai auth bootstrap-ceo` inside the container to mint a real bootstrap invite, accepts that invite over HTTP, and verifies board session access.
- Run the script in the foreground to watch the onboarding flow; stop with `Ctrl+C` after validation.
- Set `SMOKE_DETACH=true` to leave the container running for automation and optionally write shell-ready metadata to `SMOKE_METADATA_FILE`.
- The image definition is in `Dockerfile.onboard-smoke`.

View File

@@ -1,18 +1,19 @@
# Publishing to npm
Low-level reference for how Paperclip packages are built for npm.
Low-level reference for how Paperclip packages are prepared and published to npm.
For the maintainer release workflow, use [doc/RELEASING.md](RELEASING.md). This document is only about packaging internals and the scripts that produce publishable artifacts.
For the maintainer workflow, use [doc/RELEASING.md](RELEASING.md). This document focuses on packaging internals.
## Current Release Entry Points
Use these scripts instead of older one-off publish commands:
Use these scripts:
- [`scripts/release-start.sh`](../scripts/release-start.sh) to create or resume `release/X.Y.Z`
- [`scripts/release-preflight.sh`](../scripts/release-preflight.sh) before any canary or stable release
- [`scripts/release.sh`](../scripts/release.sh) for canary and stable npm publishes
- [`scripts/rollback-latest.sh`](../scripts/rollback-latest.sh) to repoint `latest` during rollback
- [`scripts/create-github-release.sh`](../scripts/create-github-release.sh) after pushing the stable branch tag
- [`scripts/release.sh`](../scripts/release.sh) for canary and stable publish flows
- [`scripts/create-github-release.sh`](../scripts/create-github-release.sh) after pushing a stable tag
- [`scripts/rollback-latest.sh`](../scripts/rollback-latest.sh) to repoint `latest`
- [`scripts/build-npm.sh`](../scripts/build-npm.sh) for the CLI packaging build
Paperclip no longer uses release branches or Changesets for publishing.
## Why the CLI needs special packaging
@@ -23,7 +24,7 @@ The CLI package, `paperclipai`, imports code from workspace packages such as:
- `@paperclipai/shared`
- adapter packages under `packages/adapters/`
Those workspace references use `workspace:*` during development. npm cannot install those references directly for end users, so the release build has to transform the CLI into a publishable standalone package.
Those workspace references are valid in development but not in a publishable npm package. The release flow rewrites versions temporarily, then builds a publishable CLI bundle.
## `build-npm.sh`
@@ -33,89 +34,107 @@ Run:
./scripts/build-npm.sh
```
This script does six things:
This script:
1. Runs the forbidden token check unless `--skip-checks` is supplied
2. Runs `pnpm -r typecheck`
3. Bundles the CLI entrypoint with esbuild into `cli/dist/index.js`
4. Verifies the bundled entrypoint with `node --check`
5. Rewrites `cli/package.json` into a publishable npm manifest and stores the dev copy as `cli/package.dev.json`
6. Copies the repo `README.md` into `cli/README.md` for npm package metadata
1. runs the forbidden token check unless `--skip-checks` is supplied
2. runs `pnpm -r typecheck`
3. bundles the CLI entrypoint with esbuild into `cli/dist/index.js`
4. verifies the bundled entrypoint with `node --check`
5. rewrites `cli/package.json` into a publishable npm manifest and stores the dev copy as `cli/package.dev.json`
6. copies the repo `README.md` into `cli/README.md` for npm metadata
`build-npm.sh` is used by the release script so that npm users install a real package rather than unresolved workspace dependencies.
After the release script exits, the dev manifest and temporary files are restored automatically.
## Publishable CLI layout
## Package discovery and versioning
During development, [`cli/package.json`](../cli/package.json) contains workspace references.
During release preparation:
- `cli/package.json` becomes a publishable manifest with external npm dependency ranges
- `cli/package.dev.json` stores the development manifest temporarily
- `cli/dist/index.js` contains the bundled CLI entrypoint
- `cli/README.md` is copied in for npm metadata
After release finalization, the release script restores the development manifest and removes the temporary README copy.
## Package discovery
The release tooling scans the workspace for public packages under:
Public packages are discovered from:
- `packages/`
- `server/`
- `cli/`
`ui/` remains ignored for npm publishing because it is private.
`ui/` is ignored because it is private.
This matters because all public packages are versioned and published together as one release unit.
The version rewrite step now uses [`scripts/release-package-map.mjs`](../scripts/release-package-map.mjs), which:
## Canary packaging model
- finds all public packages
- sorts them topologically by internal dependencies
- rewrites each package version to the target release version
- rewrites internal `workspace:*` dependency references to the exact target version
- updates the CLI's displayed version string
Canaries are published as semver prereleases such as:
Those rewrites are temporary. The working tree is restored after publish or dry-run.
- `1.2.3-canary.0`
- `1.2.3-canary.1`
## Version formats
They are published under the npm dist-tag `canary`.
Paperclip uses calendar versions:
This means:
- stable: `YYYY.MDD.P`
- canary: `YYYY.MDD.P-canary.N`
- `npx paperclipai@canary onboard` can install them explicitly
- `npx paperclipai onboard` continues to resolve `latest`
- the stable changelog can stay at `releases/v1.2.3.md`
Examples:
## Stable packaging model
- stable: `2026.318.0`
- canary: `2026.318.1-canary.2`
Stable releases publish normal semver versions such as `1.2.3` under the npm dist-tag `latest`.
## Publish model
The stable publish flow also creates the local release commit and git tag on `release/X.Y.Z`. Pushing that branch commit/tag, creating the GitHub Release, and merging the release branch back to `master` happen afterward as separate maintainer steps.
### Canary
Canaries publish under the npm dist-tag `canary`.
Example:
- `paperclipai@2026.318.1-canary.2`
This keeps the default install path unchanged while allowing explicit installs with:
```bash
npx paperclipai@canary onboard
```
### Stable
Stable publishes use the npm dist-tag `latest`.
Example:
- `paperclipai@2026.318.0`
Stable publishes do not create a release commit. Instead:
- package versions are rewritten temporarily
- packages are published from the chosen source commit
- git tag `vYYYY.MDD.P` points at that original commit
## Trusted publishing
The intended CI model is npm trusted publishing through GitHub OIDC.
That means:
- no long-lived `NPM_TOKEN` in repository secrets
- GitHub Actions obtains short-lived publish credentials
- trusted publisher rules are configured per workflow file
See [doc/RELEASE-AUTOMATION-SETUP.md](RELEASE-AUTOMATION-SETUP.md) for the GitHub/npm setup steps.
## Rollback model
Rollback does not unpublish packages.
Rollback does not unpublish anything.
Instead, the maintainer should move the `latest` dist-tag back to the previous good stable version with:
It repoints the `latest` dist-tag to a prior stable version:
```bash
./scripts/rollback-latest.sh <stable-version>
./scripts/rollback-latest.sh 2026.318.0
```
That keeps history intact while restoring the default install path quickly.
## Notes for CI
The repo includes a manual GitHub Actions release workflow at [`.github/workflows/release.yml`](../.github/workflows/release.yml).
Recommended CI release setup:
- use npm trusted publishing via GitHub OIDC
- require approval through the `npm-release` environment
- run releases from `release/X.Y.Z`
- use canary first, then stable
This is the fastest way to restore the default install path if a stable release is bad.
## Related Files
- [`scripts/build-npm.sh`](../scripts/build-npm.sh)
- [`scripts/generate-npm-package-json.mjs`](../scripts/generate-npm-package-json.mjs)
- [`scripts/release-package-map.mjs`](../scripts/release-package-map.mjs)
- [`cli/esbuild.config.mjs`](../cli/esbuild.config.mjs)
- [`doc/RELEASING.md`](RELEASING.md)

View File

@@ -0,0 +1,281 @@
# Release Automation Setup
This document covers the GitHub and npm setup required for the current Paperclip release model:
- automatic canaries from `master`
- manual stable promotion from a chosen source ref
- npm trusted publishing via GitHub OIDC
- protected release infrastructure in a public repository
Repo-side files that depend on this setup:
- `.github/workflows/release.yml`
- `.github/CODEOWNERS`
Note:
- the release workflows intentionally use `pnpm install --no-frozen-lockfile`
- this matches the repo's current policy where `pnpm-lock.yaml` is refreshed by GitHub automation after manifest changes land on `master`
- the publish jobs then restore `pnpm-lock.yaml` before running `scripts/release.sh`, so the release script still sees a clean worktree
## 1. Merge the Repo Changes First
Before touching GitHub or npm settings, merge the release automation code so the referenced workflow filenames already exist on the default branch.
Required files:
- `.github/workflows/release.yml`
- `.github/CODEOWNERS`
## 2. Configure npm Trusted Publishing
Do this for every public package that Paperclip publishes.
At minimum that includes:
- `paperclipai`
- `@paperclipai/server`
- public packages under `packages/`
### 2.1. In npm, open each package settings page
For each package:
1. open npm as an owner of the package
2. go to the package settings / publishing access area
3. add a trusted publisher for the GitHub repository `paperclipai/paperclip`
### 2.2. Add one trusted publisher entry per package
npm currently allows one trusted publisher configuration per package.
Configure:
- workflow: `.github/workflows/release.yml`
Repository:
- `paperclipai/paperclip`
Environment name:
- leave the npm trusted-publisher environment field blank
Why:
- the single `release.yml` workflow handles both canary and stable publishing
- GitHub environments `npm-canary` and `npm-stable` still enforce different approval rules on the GitHub side
### 2.3. Verify trusted publishing before removing old auth
After the workflows are live:
1. run a canary publish
2. confirm npm publish succeeds without any `NPM_TOKEN`
3. run a stable dry-run
4. run one real stable publish
Only after that should you remove old token-based access.
## 3. Remove Legacy npm Tokens
After trusted publishing works:
1. revoke any repository or organization `NPM_TOKEN` secrets used for publish
2. revoke any personal automation token that used to publish Paperclip
3. if npm offers a package-level setting to restrict publishing to trusted publishers, enable it
Goal:
- no long-lived npm publishing token should remain in GitHub Actions
## 4. Create GitHub Environments
Create two environments in the GitHub repository:
- `npm-canary`
- `npm-stable`
Path:
1. GitHub repository
2. `Settings`
3. `Environments`
4. `New environment`
## 5. Configure `npm-canary`
Recommended settings for `npm-canary`:
- environment name: `npm-canary`
- required reviewers: none
- wait timer: none
- deployment branches and tags:
- selected branches only
- allow `master`
Reasoning:
- every push to `master` should be able to publish a canary automatically
- no human approval should be required for canaries
## 6. Configure `npm-stable`
Recommended settings for `npm-stable`:
- environment name: `npm-stable`
- required reviewers: at least one maintainer other than the person triggering the workflow when possible
- prevent self-review: enabled
- admin bypass: disabled if your team can tolerate it
- wait timer: optional
- deployment branches and tags:
- selected branches only
- allow `master`
Reasoning:
- stable publishes should require an explicit human approval gate
- the workflow is manual, but the environment should still be the real control point
## 7. Protect `master`
Open the branch protection settings for `master`.
Recommended rules:
1. require pull requests before merging
2. require status checks to pass before merging
3. require review from code owners
4. dismiss stale approvals when new commits are pushed
5. restrict who can push directly to `master`
At minimum, make sure workflow and release script changes cannot land without review.
## 8. Enforce CODEOWNERS Review
This repo now includes `.github/CODEOWNERS`, but GitHub only enforces it if branch protection requires code owner reviews.
In branch protection for `master`, enable:
- `Require review from Code Owners`
Then verify the owner entries are correct for your actual maintainer set.
Current file:
- `.github/CODEOWNERS`
If `@cryppadotta` is not the right reviewer identity in the public repo, change it before enabling enforcement.
## 9. Protect Release Infrastructure Specifically
These files should always trigger code owner review:
- `.github/workflows/release.yml`
- `scripts/release.sh`
- `scripts/release-lib.sh`
- `scripts/release-package-map.mjs`
- `scripts/create-github-release.sh`
- `scripts/rollback-latest.sh`
- `doc/RELEASING.md`
- `doc/PUBLISHING.md`
If you want stronger controls, add a repository ruleset that explicitly blocks direct pushes to:
- `.github/workflows/**`
- `scripts/release*`
## 10. Do Not Store a Claude Token in GitHub Actions
Do not add a personal Claude or Anthropic token for automatic changelog generation.
Recommended policy:
- stable changelog generation happens locally from a trusted maintainer machine
- canaries never generate changelogs
This keeps LLM spending intentional and avoids a high-value token sitting in Actions.
## 11. Verify the Canary Workflow
After setup:
1. merge a harmless commit to `master`
2. open the `Release` workflow run triggered by that push
3. confirm it passes verification
4. confirm publish succeeds under the `npm-canary` environment
5. confirm npm now shows a new `canary` release
6. confirm a git tag named `canary/vYYYY.MDD.P-canary.N` was pushed
Install-path check:
```bash
npx paperclipai@canary onboard
```
## 12. Verify the Stable Workflow
After at least one good canary exists:
1. resolve the target stable version with `./scripts/release.sh stable --date YYYY-MM-DD --print-version`
2. prepare `releases/vYYYY.MDD.P.md` on the source commit you want to promote
3. open `Actions` -> `Release`
4. run it with:
- `source_ref`: the tested commit SHA or canary tag source commit
- `stable_date`: leave blank or set the intended UTC date like `2026-03-18`
do not enter a version like `2026.318.0`; the workflow computes that from the date
- `dry_run`: `true`
5. confirm the dry-run succeeds
6. rerun with `dry_run: false`
7. approve the `npm-stable` environment when prompted
8. confirm npm `latest` points to the new stable version
9. confirm git tag `vYYYY.MDD.P` exists
10. confirm the GitHub Release was created
Implementation note:
- the GitHub Actions stable workflow calls `create-github-release.sh` with `PUBLISH_REMOTE=origin`
- local maintainer usage can still pass `PUBLISH_REMOTE=public-gh` explicitly when needed
## 13. Suggested Maintainer Policy
Use this policy going forward:
- canaries are automatic and cheap
- stables are manual and approved
- only stables get public notes and announcements
- release notes are committed before stable publish
- rollback uses `npm dist-tag`, not unpublish
## 14. Troubleshooting
### Trusted publishing fails with an auth error
Check:
1. the workflow filename on GitHub exactly matches the filename configured in npm
2. the package has the trusted publisher entry for the correct repository
3. the job has `id-token: write`
4. the job is running from the expected repository, not a fork
### Stable workflow runs but never asks for approval
Check:
1. the `publish` job uses environment `npm-stable`
2. the environment actually has required reviewers configured
3. the workflow is running in the canonical repository, not a fork
### CODEOWNERS does not trigger
Check:
1. `.github/CODEOWNERS` is on the default branch
2. branch protection on `master` requires code owner review
3. the owner identities in the file are valid reviewers with repository access
## Related Docs
- [doc/RELEASING.md](RELEASING.md)
- [doc/PUBLISHING.md](PUBLISHING.md)
- [doc/plans/2026-03-17-release-automation-and-versioning.md](plans/2026-03-17-release-automation-and-versioning.md)

View File

@@ -1,220 +1,174 @@
# Releasing Paperclip
Maintainer runbook for shipping a full Paperclip release across npm, GitHub, and the website-facing changelog surface.
Maintainer runbook for shipping Paperclip across npm, GitHub, and the website-facing changelog surface.
The release model is branch-driven:
The release model is now commit-driven:
1. Start a release train on `release/X.Y.Z`
2. Draft the stable changelog on that branch
3. Publish one or more canaries from that branch
4. Publish stable from that same branch head
5. Push the branch commit and tag
6. Create the GitHub Release
7. Merge `release/X.Y.Z` back to `master` without squash or rebase
1. Every push to `master` publishes a canary automatically.
2. Stable releases are manually promoted from a chosen tested commit or canary tag.
3. Stable release notes live in `releases/vYYYY.MDD.P.md`.
4. Only stable releases get GitHub Releases.
## Versioning Model
Paperclip uses calendar versions that still fit semver syntax:
- stable: `YYYY.MDD.P`
- canary: `YYYY.MDD.P-canary.N`
Examples:
- first stable on March 18, 2026: `2026.318.0`
- second stable on March 18, 2026: `2026.318.1`
- fourth canary for the `2026.318.1` line: `2026.318.1-canary.3`
Important constraints:
- the middle numeric slot is `MDD`, where `M` is the UTC month and `DD` is the zero-padded UTC day
- use `2026.303.0` for March 3, not `2026.33.0`
- do not use leading zeroes such as `2026.0318.0`
- do not use four numeric segments such as `2026.3.18.1`
- the semver-safe canary form is `2026.318.0-canary.1`
## Release Surfaces
Every release has four separate surfaces:
Every stable release has four separate surfaces:
1. **Verification** — the exact git SHA passes typecheck, tests, and build
2. **npm**`paperclipai` and public workspace packages are published
3. **GitHub** — the stable release gets a git tag and GitHub Release
4. **Website / announcements** — the stable changelog is published externally and announced
A release is done only when all four surfaces are handled.
A stable release is done only when all four surfaces are handled.
Canaries only cover the first two surfaces plus an internal traceability tag.
## Core Invariants
- Canary and stable for `X.Y.Z` must come from the same `release/X.Y.Z` branch.
- The release scripts must run from the matching `release/X.Y.Z` branch.
- Once `vX.Y.Z` exists locally, on GitHub, or on npm, that release train is frozen.
- Do not squash-merge or rebase-merge a release branch PR back to `master`.
- The stable changelog is always `releases/vX.Y.Z.md`. Never create canary changelog files.
The reason for the merge rule is simple: the tag must keep pointing at the exact published commit. Squash or rebase breaks that property.
- canaries publish from `master`
- stables publish from an explicitly chosen source ref
- tags point at the original source commit, not a generated release commit
- stable notes are always `releases/vYYYY.MDD.P.md`
- canaries never create GitHub Releases
- canaries never require changelog generation
## TL;DR
### 1. Start the release train
### Canary
Use this to compute the next version, create or resume the branch, create or resume a dedicated worktree, and push the branch to GitHub.
Every push to `master` runs the canary path inside [`.github/workflows/release.yml`](../.github/workflows/release.yml).
```bash
./scripts/release-start.sh patch
```
It:
That script:
- fetches the release remote and tags
- computes the next stable version from the latest `v*` tag
- creates or resumes `release/X.Y.Z`
- creates or resumes a dedicated worktree
- pushes the branch to the remote by default
- refuses to reuse a frozen release train
### 2. Draft the stable changelog
From the release worktree:
```bash
VERSION=X.Y.Z
claude --print --output-format stream-json --verbose --dangerously-skip-permissions --model claude-opus-4-6 "Use the release-changelog skill to draft or update releases/v${VERSION}.md for Paperclip. Read doc/RELEASING.md and .agents/skills/release-changelog/SKILL.md, then generate the stable changelog for v${VERSION} from commits since the last stable tag. Do not create a canary changelog."
```
### 3. Verify and publish a canary
```bash
./scripts/release-preflight.sh canary patch
./scripts/release.sh patch --canary --dry-run
./scripts/release.sh patch --canary
PAPERCLIPAI_VERSION=canary ./scripts/docker-onboard-smoke.sh
```
- verifies the pushed commit
- computes the canary version for the current UTC date
- publishes under npm dist-tag `canary`
- creates a git tag `canary/vYYYY.MDD.P-canary.N`
Users install canaries with:
```bash
npx paperclipai@canary onboard
```
### 4. Publish stable
```bash
./scripts/release-preflight.sh stable patch
./scripts/release.sh patch --dry-run
./scripts/release.sh patch
git push public-gh HEAD --follow-tags
./scripts/create-github-release.sh X.Y.Z
```
Then open a PR from `release/X.Y.Z` to `master` and merge without squash or rebase.
## Release Branches
Paperclip uses one release branch per target stable version:
- `release/0.3.0`
- `release/0.3.1`
- `release/1.0.0`
Do not create separate per-canary branches like `canary/0.3.0-1`. A canary is just a prerelease snapshot of the same stable train.
## Script Entry Points
- [`scripts/release-start.sh`](../scripts/release-start.sh) — create or resume the release train branch/worktree
- [`scripts/release-preflight.sh`](../scripts/release-preflight.sh) — validate branch, version plan, git/npm state, and verification gate
- [`scripts/release.sh`](../scripts/release.sh) — publish canary or stable from the release branch
- [`scripts/create-github-release.sh`](../scripts/create-github-release.sh) — create or update the GitHub Release after pushing the tag
- [`scripts/rollback-latest.sh`](../scripts/rollback-latest.sh) — repoint `latest` to the last good stable version
## Detailed Workflow
### 1. Start or resume the release train
Run:
```bash
./scripts/release-start.sh <patch|minor|major>
```
Useful options:
```bash
./scripts/release-start.sh patch --dry-run
./scripts/release-start.sh minor --worktree-dir ../paperclip-release-0.4.0
./scripts/release-start.sh patch --no-push
```
The script is intentionally idempotent:
- if `release/X.Y.Z` already exists locally, it reuses it
- if the branch already exists on the remote, it resumes it locally
- if the branch is already checked out in another worktree, it points you there
- if `vX.Y.Z` already exists locally, remotely, or on npm, it refuses to reuse that train
### 2. Write the stable changelog early
Create or update:
- `releases/vX.Y.Z.md`
That file is for the eventual stable release. It should not include `-canary` in the filename or heading.
Recommended structure:
- `Breaking Changes` when needed
- `Highlights`
- `Improvements`
- `Fixes`
- `Upgrade Guide` when needed
- `Contributors` — @-mention every contributor by GitHub username (no emails)
Package-level `CHANGELOG.md` files are generated as part of the release mechanics. They are not the main release narrative.
### 3. Run release preflight
From the `release/X.Y.Z` worktree:
```bash
./scripts/release-preflight.sh canary <patch|minor|major>
# or
./scripts/release-preflight.sh stable <patch|minor|major>
npx paperclipai@canary onboard --data-dir "$(mktemp -d /tmp/paperclip-canary.XXXXXX)"
```
The preflight script now checks all of the following before it runs the verification gate:
### Stable
- the worktree is clean, including untracked files
- the current branch matches the computed `release/X.Y.Z`
- the release train is not frozen
- the target version is still free on npm
- the target tag does not already exist locally or remotely
- whether the remote release branch already exists
- whether `releases/vX.Y.Z.md` is present
Use [`.github/workflows/release.yml`](../.github/workflows/release.yml) from the Actions tab with the manual `workflow_dispatch` inputs.
Then it runs:
[Run the action here](https://github.com/paperclipai/paperclip/actions/workflows/release.yml)
Inputs:
- `source_ref`
- commit SHA, branch, or tag
- `stable_date`
- optional UTC date override in `YYYY-MM-DD`
- enter a date like `2026-03-18`, not a version like `2026.318.0`
- `dry_run`
- preview only when true
Before running stable:
1. pick the canary commit or tag you trust
2. resolve the target stable version with `./scripts/release.sh stable --date "$(date +%F)" --print-version`
3. create or update `releases/vYYYY.MDD.P.md` on that source ref
4. run the stable workflow from that source ref
Example:
- `source_ref`: `master`
- `stable_date`: `2026-03-18`
- resulting stable version: `2026.318.0`
The workflow:
- re-verifies the exact source ref
- computes the next stable patch slot for the chosen UTC date
- publishes `YYYY.MDD.P` under npm dist-tag `latest`
- creates git tag `vYYYY.MDD.P`
- creates or updates the GitHub Release from `releases/vYYYY.MDD.P.md`
## Local Commands
### Preview a canary locally
```bash
pnpm -r typecheck
pnpm test:run
pnpm build
./scripts/release.sh canary --dry-run
```
### 4. Publish one or more canaries
Run:
### Preview a stable locally
```bash
./scripts/release.sh <patch|minor|major> --canary --dry-run
./scripts/release.sh <patch|minor|major> --canary
./scripts/release.sh stable --dry-run
```
Result:
### Publish a stable locally
- npm gets a prerelease such as `1.2.3-canary.0` under dist-tag `canary`
- `latest` is unchanged
- no git tag is created
- no GitHub Release is created
- the worktree returns to clean after the script finishes
This is mainly for emergency/manual use. The normal path is the GitHub workflow.
Guardrails:
```bash
./scripts/release.sh stable
git push public-gh refs/tags/vYYYY.MDD.P
PUBLISH_REMOTE=public-gh ./scripts/create-github-release.sh YYYY.MDD.P
```
- the script refuses to run from the wrong branch
- the script refuses to publish from a frozen train
- the canary is always derived from the next stable version
- if the stable notes file is missing, the script warns before you forget it
## Stable Changelog Workflow
Concrete example:
Stable changelog files live at:
- if the latest stable is `0.2.7`, a patch canary targets `0.2.8-canary.0`
- `0.2.7-canary.N` is invalid because `0.2.7` is already stable
- `releases/vYYYY.MDD.P.md`
### 5. Smoke test the canary
Canaries do not get changelog files.
Run the actual install path in Docker:
Recommended local generation flow:
```bash
VERSION="$(./scripts/release.sh stable --date 2026-03-18 --print-version)"
claude --print --output-format stream-json --verbose --dangerously-skip-permissions --model claude-opus-4-6 "Use the release-changelog skill to draft or update releases/v${VERSION}.md for Paperclip. Read doc/RELEASING.md and .agents/skills/release-changelog/SKILL.md, then generate the stable changelog for v${VERSION} from commits since the last stable tag. Do not create a canary changelog."
```
The repo intentionally does not run this through GitHub Actions because:
- canaries are too frequent
- stable notes are the only public narrative surface that needs LLM help
- maintainer LLM tokens should not live in Actions
## Smoke Testing
For a canary:
```bash
PAPERCLIPAI_VERSION=canary ./scripts/docker-onboard-smoke.sh
```
For the current stable:
```bash
PAPERCLIPAI_VERSION=latest ./scripts/docker-onboard-smoke.sh
```
Useful isolated variants:
```bash
@@ -222,201 +176,76 @@ HOST_PORT=3232 DATA_DIR=./data/release-smoke-canary PAPERCLIPAI_VERSION=canary .
HOST_PORT=3233 DATA_DIR=./data/release-smoke-stable PAPERCLIPAI_VERSION=latest ./scripts/docker-onboard-smoke.sh
```
If you want to exercise onboarding from the current committed ref instead of npm, use:
Automated browser smoke is also available:
```bash
./scripts/clean-onboard-ref.sh
PAPERCLIP_PORT=3234 ./scripts/clean-onboard-ref.sh
./scripts/clean-onboard-ref.sh HEAD
gh workflow run release-smoke.yml -f paperclip_version=canary
gh workflow run release-smoke.yml -f paperclip_version=latest
```
Minimum checks:
- `npx paperclipai@canary onboard` installs
- onboarding completes without crashes
- the server boots
- the UI loads
- basic company creation and dashboard load work
- authenticated login works with the smoke credentials
- the browser lands in onboarding on a fresh instance
- company creation succeeds
- the first CEO agent is created
- the first CEO heartbeat run is triggered
If smoke testing fails:
## Rollback
1. stop the stable release
2. fix the issue on the same `release/X.Y.Z` branch
3. publish another canary
4. rerun smoke testing
Rollback does not unpublish versions.
### 6. Publish stable from the same release branch
Once the branch head is vetted, run:
It only moves the `latest` dist-tag back to a previous stable:
```bash
./scripts/release.sh <patch|minor|major> --dry-run
./scripts/release.sh <patch|minor|major>
./scripts/rollback-latest.sh 2026.318.0 --dry-run
./scripts/rollback-latest.sh 2026.318.0
```
Stable publish:
- publishes `X.Y.Z` to npm under `latest`
- creates the local release commit
- creates the local tag `vX.Y.Z`
Stable publish refuses to proceed if:
- the current branch is not `release/X.Y.Z`
- the remote release branch does not exist yet
- the stable notes file is missing
- the target tag already exists locally or remotely
- the stable version already exists on npm
Those checks intentionally freeze the train after stable publish.
### 7. Push the stable branch commit and tag
After stable publish succeeds:
```bash
git push public-gh HEAD --follow-tags
./scripts/create-github-release.sh X.Y.Z
```
The GitHub Release notes come from:
- `releases/vX.Y.Z.md`
### 8. Merge the release branch back to `master`
Open a PR:
- base: `master`
- head: `release/X.Y.Z`
Merge rule:
- allowed: merge commit or fast-forward
- forbidden: squash merge
- forbidden: rebase merge
Post-merge verification:
```bash
git fetch public-gh --tags
git merge-base --is-ancestor "vX.Y.Z" "public-gh/master"
```
That command must succeed. If it fails, the published tagged commit is not reachable from `master`, which means the merge strategy was wrong.
### 9. Finish the external surfaces
After GitHub is correct:
- publish the changelog on the website
- write and send the announcement copy
- ensure public docs and install guidance point to the stable version
## GitHub Actions Release
There is also a manual workflow at [`.github/workflows/release.yml`](../.github/workflows/release.yml).
Use it from the Actions tab on the relevant `release/X.Y.Z` branch:
1. Choose `Release`
2. Choose `channel`: `canary` or `stable`
3. Choose `bump`: `patch`, `minor`, or `major`
4. Choose whether this is a `dry_run`
5. Run it from the release branch, not from `master`
The workflow:
- reruns `typecheck`, `test:run`, and `build`
- gates publish behind the `npm-release` environment
- can publish canaries without touching `latest`
- can publish stable, push the stable branch commit and tag, and create the GitHub Release
It does not merge the release branch back to `master` for you.
## Release Checklist
### Before any publish
- [ ] The release train exists on `release/X.Y.Z`
- [ ] The working tree is clean, including untracked files
- [ ] If package manifests changed, the CI-owned `pnpm-lock.yaml` refresh is already merged on `master` before the train is cut
- [ ] The required verification gate passed on the exact branch head you want to publish
- [ ] The bump type is correct for the user-visible impact
- [ ] The stable changelog file exists or is ready at `releases/vX.Y.Z.md`
- [ ] You know which previous stable version you would roll back to if needed
### Before a stable
- [ ] The candidate has already passed smoke testing
- [ ] The remote `release/X.Y.Z` branch exists
- [ ] You are ready to push the stable branch commit and tag immediately after npm publish
- [ ] You are ready to create the GitHub Release immediately after the push
- [ ] You are ready to open the PR back to `master`
### After a stable
- [ ] `npm view paperclipai@latest version` matches the new stable version
- [ ] The git tag exists on GitHub
- [ ] The GitHub Release exists and uses `releases/vX.Y.Z.md`
- [ ] `vX.Y.Z` is reachable from `master`
- [ ] The website changelog is updated
- [ ] Announcement copy matches the stable release, not the canary
Then fix forward with a new stable patch slot or release date.
## Failure Playbooks
### If the canary publishes but the smoke test fails
### If the canary publishes but smoke testing fails
Do not publish stable.
Do not run stable.
Instead:
1. fix the issue on `release/X.Y.Z`
2. publish another canary
3. rerun smoke testing
1. fix the issue on `master`
2. merge the fix
3. wait for the next automatic canary
4. rerun smoke testing
### If stable npm publish succeeds but push or GitHub release creation fails
### If stable npm publish succeeds but tag push or GitHub release creation fails
This is a partial release. npm is already live.
Do this immediately:
1. fix the git or GitHub issue from the same checkout
2. push the stable branch commit and tag
3. create the GitHub Release
1. push the missing tag
2. rerun `PUBLISH_REMOTE=public-gh ./scripts/create-github-release.sh YYYY.MDD.P`
3. verify the GitHub Release notes point at `releases/vYYYY.MDD.P.md`
Do not republish the same version.
### If `latest` is broken after stable publish
Preview:
Roll back the dist-tag:
```bash
./scripts/rollback-latest.sh X.Y.Z --dry-run
./scripts/rollback-latest.sh YYYY.MDD.P
```
Roll back:
Then fix forward with a new stable release.
```bash
./scripts/rollback-latest.sh X.Y.Z
```
## Related Files
This does not unpublish anything. It only moves the `latest` dist-tag back to the last good stable release.
Then fix forward with a new patch release.
### If the GitHub Release notes are wrong
Re-run:
```bash
./scripts/create-github-release.sh X.Y.Z
```
If the release already exists, the script updates it.
## Related Docs
- [doc/PUBLISHING.md](PUBLISHING.md) — low-level npm build and packaging internals
- [.agents/skills/release/SKILL.md](../.agents/skills/release/SKILL.md) — maintainer release coordination workflow
- [.agents/skills/release-changelog/SKILL.md](../.agents/skills/release-changelog/SKILL.md) — stable changelog drafting workflow
- [`scripts/release.sh`](../scripts/release.sh)
- [`scripts/release-package-map.mjs`](../scripts/release-package-map.mjs)
- [`scripts/create-github-release.sh`](../scripts/create-github-release.sh)
- [`scripts/rollback-latest.sh`](../scripts/rollback-latest.sh)
- [`doc/PUBLISHING.md`](PUBLISHING.md)
- [`doc/RELEASE-AUTOMATION-SETUP.md`](RELEASE-AUTOMATION-SETUP.md)

View File

@@ -330,6 +330,34 @@ Operational policy:
- `asset_id` uuid fk not null
- `issue_comment_id` uuid fk null
## 7.15 `documents` + `document_revisions` + `issue_documents`
- `documents` stores editable text-first documents:
- `id` uuid pk
- `company_id` uuid fk not null
- `title` text null
- `format` text not null (`markdown`)
- `latest_body` text not null
- `latest_revision_id` uuid null
- `latest_revision_number` int not null
- `created_by_agent_id` uuid fk null
- `created_by_user_id` uuid/text fk null
- `updated_by_agent_id` uuid fk null
- `updated_by_user_id` uuid/text fk null
- `document_revisions` stores append-only history:
- `id` uuid pk
- `company_id` uuid fk not null
- `document_id` uuid fk not null
- `revision_number` int not null
- `body` text not null
- `change_summary` text null
- `issue_documents` links documents to issues with a stable workflow key:
- `id` uuid pk
- `company_id` uuid fk not null
- `issue_id` uuid fk not null
- `document_id` uuid fk not null
- `key` text not null (`plan`, `design`, `notes`, etc.)
## 8. State Machines
## 8.1 Agent Status
@@ -413,6 +441,7 @@ All endpoints are under `/api` and return JSON.
- `POST /companies`
- `GET /companies/:companyId`
- `PATCH /companies/:companyId`
- `PATCH /companies/:companyId/branding`
- `POST /companies/:companyId/archive`
## 10.2 Goals
@@ -441,6 +470,11 @@ All endpoints are under `/api` and return JSON.
- `POST /companies/:companyId/issues`
- `GET /issues/:issueId`
- `PATCH /issues/:issueId`
- `GET /issues/:issueId/documents`
- `GET /issues/:issueId/documents/:key`
- `PUT /issues/:issueId/documents/:key`
- `GET /issues/:issueId/documents/:key/revisions`
- `DELETE /issues/:issueId/documents/:key`
- `POST /issues/:issueId/checkout`
- `POST /issues/:issueId/release`
- `POST /issues/:issueId/comments`
@@ -810,20 +844,27 @@ V1 is complete only when all criteria are true:
V1 supports company import/export using a portable package contract:
- exactly one JSON entrypoint: `paperclip.manifest.json`
- all other package files are markdown with frontmatter
- agent convention:
- `agents/<slug>/AGENTS.md` (required for V1 export/import)
- `agents/<slug>/HEARTBEAT.md` (optional, import accepted)
- `agents/<slug>/*.md` (optional, import accepted)
- markdown-first package rooted at `COMPANY.md`
- implicit folder discovery by convention
- `.paperclip.yaml` sidecar for Paperclip-specific fidelity
- canonical base package is vendor-neutral and aligned with `docs/companies/companies-spec.md`
- common conventions:
- `agents/<slug>/AGENTS.md`
- `teams/<slug>/TEAM.md`
- `projects/<slug>/PROJECT.md`
- `projects/<slug>/tasks/<slug>/TASK.md`
- `tasks/<slug>/TASK.md`
- `skills/<slug>/SKILL.md`
Export/import behavior in V1:
- export includes company metadata and/or agents based on selection
- export strips environment-specific paths (`cwd`, local instruction file paths)
- export never includes secret values; secret requirements are reported
- export emits a clean vendor-neutral markdown package plus `.paperclip.yaml`
- projects and starter tasks are opt-in export content rather than default package content
- export strips environment-specific paths (`cwd`, local instruction file paths, inline prompt duplication)
- export never includes secret values; env inputs are reported as portable declarations instead
- import supports target modes:
- create a new company
- import into an existing company
- import supports collision strategies: `rename`, `skip`, `replace`
- import supports preview (dry-run) before apply
- GitHub imports warn on unpinned refs instead of blocking

View File

@@ -188,12 +188,15 @@ The heartbeat is a protocol, not a runtime. Paperclip defines how to initiate an
Agent configuration includes an **adapter** that defines how Paperclip invokes the agent. Initial adapters:
| Adapter | Mechanism | Example |
| --------- | ----------------------- | --------------------------------------------- |
| `process` | Execute a child process | `python run_agent.py --agent-id {id}` |
| `http` | Send an HTTP request | `POST https://openclaw.example.com/hook/{id}` |
| Adapter | Mechanism | Example |
| -------------------- | ----------------------- | --------------------------------------------- |
| `process` | Execute a child process | `python run_agent.py --agent-id {id}` |
| `http` | Send an HTTP request | `POST https://openclaw.example.com/hook/{id}` |
| `openclaw_gateway` | OpenClaw gateway API | Managed OpenClaw agent via gateway |
| `gemini_local` | Gemini CLI process | Local Gemini CLI with sandbox and approval |
| `hermes_local` | Hermes agent process | Local Hermes agent |
The `process` and `http` adapters ship as defaults. Additional adapters can be added via the plugin system (see Plugin / Extension Architecture).
The `process` and `http` adapters ship as defaults. Additional adapters have been added for specific agent runtimes (see list above), and new adapter types can be registered via the plugin system (see Plugin / Extension Architecture).
### Adapter Interface
@@ -429,7 +432,7 @@ The core Paperclip system must be extensible. Features like knowledge bases, ext
- **Agent Adapter plugins** — new Adapter types can be registered via the plugin system
- Plugin-registrable UI components (future)
This isn't a V1 deliverable (we're not building a plugin framework upfront), but the architecture should not paint us into a corner. Keep boundaries clean so extensions are possible.
The plugin framework has shipped. Plugins can register new adapter types, hook into lifecycle events, and contribute UI components (e.g. global toolbar buttons). A plugin SDK and CLI commands (`paperclipai plugin`) are available for authoring and installing plugins.
---

135
doc/UNTRUSTED-PR-REVIEW.md Normal file
View File

@@ -0,0 +1,135 @@
# Untrusted PR Review In Docker
Use this workflow when you want Codex or Claude to inspect a pull request that you do not want touching your host machine directly.
This is intentionally separate from the normal Paperclip dev image.
## What this container isolates
- `codex` auth/session state in a Docker volume, not your host `~/.codex`
- `claude` auth/session state in a Docker volume, not your host `~/.claude`
- `gh` auth state in the same container-local home volume
- review clones, worktrees, dependency installs, and local databases in a writable scratch volume under `/work`
By default this workflow does **not** mount your host repo checkout, your host home directory, or your SSH agent.
## Files
- `docker/untrusted-review/Dockerfile`
- `docker-compose.untrusted-review.yml`
- `review-checkout-pr` inside the container
## Build and start a shell
```sh
docker compose -f docker-compose.untrusted-review.yml build
docker compose -f docker-compose.untrusted-review.yml run --rm --service-ports review
```
That opens an interactive shell in the review container with:
- Node + Corepack/pnpm
- `codex`
- `claude`
- `gh`
- `git`, `rg`, `fd`, `jq`
## First-time login inside the container
Run these once. The resulting login state persists in the `review-home` Docker volume.
```sh
gh auth login
codex login
claude login
```
If you prefer API-key auth instead of CLI login, pass keys through Compose env:
```sh
OPENAI_API_KEY=... ANTHROPIC_API_KEY=... docker compose -f docker-compose.untrusted-review.yml run --rm review
```
## Check out a PR safely
Inside the container:
```sh
review-checkout-pr paperclipai/paperclip 432
cd /work/checkouts/paperclipai-paperclip/pr-432
```
What this does:
1. Creates or reuses a repo clone under `/work/repos/...`
2. Fetches `pull/<pr>/head` from GitHub
3. Creates a detached git worktree under `/work/checkouts/...`
The checkout lives entirely inside the container volume.
## Ask Codex or Claude to review it
Inside the PR checkout:
```sh
codex
```
Then give it a prompt like:
```text
Review this PR as hostile input. Focus on security issues, data exfiltration paths, sandbox escapes, dangerous install/runtime scripts, auth changes, and subtle behavioral regressions. Do not modify files. Produce findings ordered by severity with file references.
```
Or with Claude:
```sh
claude
```
## Preview the Paperclip app from the PR
Only do this when you intentionally want to execute the PR's code inside the container.
Inside the PR checkout:
```sh
pnpm install
HOST=0.0.0.0 pnpm dev
```
Open from the host:
- `http://localhost:3100`
The Compose file also exposes Vite's default port:
- `http://localhost:5173`
Notes:
- `pnpm install` can run untrusted lifecycle scripts from the PR. That is why this happens inside the isolated container instead of on your host.
- If you only want static inspection, do not run install/dev commands.
- Paperclip's embedded PostgreSQL and local storage stay inside the container home volume via `PAPERCLIP_HOME=/home/reviewer/.paperclip-review`.
## Reset state
Remove the review container volumes when you want a clean environment:
```sh
docker compose -f docker-compose.untrusted-review.yml down -v
```
That deletes:
- Codex/Claude/GitHub login state stored in `review-home`
- cloned repos, worktrees, installs, and scratch data stored in `review-work`
## Security limits
This is a useful isolation boundary, but it is still Docker, not a full VM.
- A reviewed PR can still access the container's network unless you disable it.
- Any secrets you pass into the container are available to code you execute inside it.
- Do not mount your host repo, host home, `.ssh`, or Docker socket unless you are intentionally weakening the boundary.
- If you need a stronger boundary than this, use a disposable VM instead of Docker.

172
doc/memory-landscape.md Normal file
View File

@@ -0,0 +1,172 @@
# Memory Landscape
Date: 2026-03-17
This document summarizes the memory systems referenced in task `PAP-530` and extracts the design patterns that matter for Paperclip.
## What Paperclip Needs From This Survey
Paperclip is not trying to become a single opinionated memory engine. The more useful target is a control-plane memory surface that:
- stays company-scoped
- lets each company choose a default memory provider
- lets specific agents override that default
- keeps provenance back to Paperclip runs, issues, comments, and documents
- records memory-related cost and latency the same way the rest of the control plane records work
- works with plugin-provided providers, not only built-ins
The question is not "which memory project wins?" The question is "what is the smallest Paperclip contract that can sit above several very different memory systems without flattening away the useful differences?"
## Quick Grouping
### Hosted memory APIs
- `mem0`
- `supermemory`
- `Memori`
These optimize for a simple application integration story: send conversation/content plus an identity, then query for relevant memory or user context later.
### Agent-centric memory frameworks / memory OSes
- `MemOS`
- `memU`
- `EverMemOS`
- `OpenViking`
These treat memory as an agent runtime subsystem, not only as a search index. They usually add task memory, profiles, filesystem-style organization, async ingestion, or skill/resource management.
### Local-first memory stores / indexes
- `nuggets`
- `memsearch`
These emphasize local persistence, inspectability, and low operational overhead. They are useful because Paperclip is local-first today and needs at least one zero-config path.
## Per-Project Notes
| Project | Shape | Notable API / model | Strong fit for Paperclip | Main mismatch |
|---|---|---|---|---|
| [nuggets](https://github.com/NeoVertex1/nuggets) | local memory engine + messaging gateway | topic-scoped HRR memory with `remember`, `recall`, `forget`, fact promotion into `MEMORY.md` | good example of lightweight local memory and automatic promotion | very specific architecture; not a general multi-tenant service |
| [mem0](https://github.com/mem0ai/mem0) | hosted + OSS SDK | `add`, `search`, `getAll`, `get`, `update`, `delete`, `deleteAll`; entity partitioning via `user_id`, `agent_id`, `run_id`, `app_id` | closest to a clean provider API with identities and metadata filters | provider owns extraction heavily; Paperclip should not assume every backend behaves like mem0 |
| [MemOS](https://github.com/MemTensor/MemOS) | memory OS / framework | unified add-retrieve-edit-delete, memory cubes, multimodal memory, tool memory, async scheduler, feedback/correction | strong source for optional capabilities beyond plain search | much broader than the minimal contract Paperclip should standardize first |
| [supermemory](https://github.com/supermemoryai/supermemory) | hosted memory + context API | `add`, `profile`, `search.memories`, `search.documents`, document upload, settings; automatic profile building and forgetting | strong example of "context bundle" rather than raw search results | heavily productized around its own ontology and hosted flow |
| [memU](https://github.com/NevaMind-AI/memU) | proactive agent memory framework | file-system metaphor, proactive loop, intent prediction, always-on companion model | good source for when memory should trigger agent behavior, not just retrieval | proactive assistant framing is broader than Paperclip's task-centric control plane |
| [Memori](https://github.com/MemoriLabs/Memori) | hosted memory fabric + SDK wrappers | registers against LLM SDKs, attribution via `entity_id` + `process_id`, sessions, cloud + BYODB | strong example of automatic capture around model clients | wrapper-centric design does not map 1:1 to Paperclip's run / issue / comment lifecycle |
| [EverMemOS](https://github.com/EverMind-AI/EverMemOS) | conversational long-term memory system | MemCell extraction, structured narratives, user profiles, hybrid retrieval / reranking | useful model for provenance-rich structured memories and evolving profiles | focused on conversational memory rather than generalized control-plane events |
| [memsearch](https://github.com/zilliztech/memsearch) | markdown-first local memory index | markdown as source of truth, `index`, `search`, `watch`, transcript parsing, plugin hooks | excellent baseline for a local built-in provider and inspectable provenance | intentionally simple; no hosted service semantics or rich correction workflow |
| [OpenViking](https://github.com/volcengine/OpenViking) | context database | filesystem-style organization of memories/resources/skills, tiered loading, visualized retrieval trajectories | strong source for browse/inspect UX and context provenance | treats "context database" as a larger product surface than Paperclip should own |
## Common Primitives Across The Landscape
Even though the systems disagree on architecture, they converge on a few primitives:
- `ingest`: add memory from text, messages, documents, or transcripts
- `query`: search or retrieve memory given a task, question, or scope
- `scope`: partition memory by user, agent, project, process, or session
- `provenance`: carry enough metadata to explain where a memory came from
- `maintenance`: update, forget, dedupe, compact, or correct memories over time
- `context assembly`: turn raw memories into a prompt-ready bundle for the agent
If Paperclip does not expose these, it will not adapt well to the systems above.
## Where The Systems Differ
These differences are exactly why Paperclip needs a layered contract instead of a single hard-coded engine.
### 1. Who owns extraction?
- `mem0`, `supermemory`, and `Memori` expect the provider to infer memories from conversations.
- `memsearch` expects the host to decide what markdown to write, then indexes it.
- `MemOS`, `memU`, `EverMemOS`, and `OpenViking` sit somewhere in between and often expose richer memory construction pipelines.
Paperclip should support both:
- provider-managed extraction
- Paperclip-managed extraction with provider-managed storage / retrieval
### 2. What is the source of truth?
- `memsearch` and `nuggets` make the source inspectable on disk.
- hosted APIs often make the provider store canonical.
- filesystem-style systems like `OpenViking` and `memU` treat hierarchy itself as part of the memory model.
Paperclip should not require a single storage shape. It should require normalized references back to Paperclip entities.
### 3. Is memory just search, or also profile and planning state?
- `mem0` and `memsearch` center search and CRUD.
- `supermemory` adds user profiles as a first-class output.
- `MemOS`, `memU`, `EverMemOS`, and `OpenViking` expand into tool traces, task memory, resources, and skills.
Paperclip should make plain search the minimum contract and richer outputs optional capabilities.
### 4. Is memory synchronous or asynchronous?
- local tools often work synchronously in-process.
- larger systems add schedulers, background indexing, compaction, or sync jobs.
Paperclip needs both direct request/response operations and background maintenance hooks.
## Paperclip-Specific Takeaways
### Paperclip should own these concerns
- binding a provider to a company and optionally overriding it per agent
- mapping Paperclip entities into provider scopes
- provenance back to issue comments, documents, runs, and activity
- cost / token / latency reporting for memory work
- browse and inspect surfaces in the Paperclip UI
- governance on destructive operations
### Providers should own these concerns
- extraction heuristics
- embedding / indexing strategy
- ranking and reranking
- profile synthesis
- contradiction resolution and forgetting logic
- storage engine details
### The control-plane contract should stay small
Paperclip does not need to standardize every feature from every provider. It needs:
- a required portable core
- optional capability flags for richer providers
- a way to record provider-native ids and metadata without pretending all providers are equivalent internally
## Recommended Direction
Paperclip should adopt a two-layer memory model:
1. `Memory binding + control plane layer`
Paperclip decides which provider key is in effect for a company, agent, or project, and it logs every memory operation with provenance and usage.
2. `Provider adapter layer`
A built-in or plugin-supplied adapter turns Paperclip memory requests into provider-specific calls.
The portable core should cover:
- ingest / write
- search / recall
- browse / inspect
- get by provider record handle
- forget / correction
- usage reporting
Optional capabilities can cover:
- profile synthesis
- async ingestion
- multimodal content
- tool / resource / skill memory
- provider-native graph browsing
That is enough to support:
- a local markdown-first baseline similar to `memsearch`
- hosted services similar to `mem0`, `supermemory`, or `Memori`
- richer agent-memory systems like `MemOS` or `OpenViking`
without forcing Paperclip itself to become a monolithic memory engine.

View File

@@ -1,5 +1,7 @@
# Paperclip Module System
> Supersession note: the company-template/package-format direction in this document is no longer current. For the current markdown-first company import/export plan, see `doc/plans/2026-03-13-company-import-export-v2.md` and `docs/companies/companies-spec.md`.
## Overview
Paperclip's module system lets you extend the control plane with new capabilities — revenue tracking, observability, notifications, dashboards — without forking core. Modules are self-contained packages that register routes, UI pages, database tables, and lifecycle hooks.

View File

@@ -0,0 +1,644 @@
# 2026-03-13 Company Import / Export V2 Plan
Status: Proposed implementation plan
Date: 2026-03-13
Audience: Product and engineering
Supersedes for package-format direction:
- `doc/plans/2026-02-16-module-system.md` sections that describe company templates as JSON-only
- `docs/specs/cliphub-plan.md` assumptions about blueprint bundle shape where they conflict with the markdown-first package model
## 1. Purpose
This document defines the next-stage plan for Paperclip company import/export.
The core shift is:
- move from a Paperclip-specific JSON-first portability package toward a markdown-first package format
- make GitHub repositories first-class package sources
- treat the company package model as an extension of the existing Agent Skills ecosystem instead of inventing a separate skill format
- support company, team, agent, and skill reuse without requiring a central registry
The normative package format draft lives in:
- `docs/companies/companies-spec.md`
This plan is about implementation and rollout inside Paperclip.
Adapter-wide skill rollout details live in:
- `doc/plans/2026-03-14-adapter-skill-sync-rollout.md`
## 2. Executive Summary
Paperclip already has portability primitives in the repo:
- server import/export/preview APIs
- CLI import/export commands
- shared portability types and validators
Those primitives are being cut over to the new package model rather than extended for backward compatibility.
The new direction is:
1. markdown-first package authoring
2. GitHub repo or local folder as the default source of truth
3. a vendor-neutral base package spec for agent-company runtimes, not just Paperclip
4. the company package model is explicitly an extension of Agent Skills
5. no future dependency on `paperclip.manifest.json`
6. implicit folder discovery by convention for the common case
7. an always-emitted `.paperclip.yaml` sidecar for high-fidelity Paperclip-specific details
8. package graph resolution at import time
9. entity-level import UI with dependency-aware tree selection
10. `skills.sh` compatibility is a V1 requirement for skill packages and skill installation flows
11. adapter-aware skill sync surfaces so Paperclip can read, diff, enable, disable, and reconcile skills where the adapter supports it
## 3. Product Goals
### 3.1 Goals
- A user can point Paperclip at a local folder or GitHub repo and import a company package without any registry.
- A package is readable and writable by humans with normal git workflows.
- A package can contain:
- company definition
- org subtree / team definition
- agent definitions
- optional starter projects and tasks
- reusable skills
- V1 skill support is compatible with the existing `skills.sh` / Agent Skills ecosystem.
- A user can import into:
- a new company
- an existing company
- Import preview shows:
- what will be created
- what will be updated
- what is skipped
- what is referenced externally
- what needs secrets or approvals
- Export preserves attribution, licensing, and pinned upstream references.
- Export produces a clean vendor-neutral package plus a Paperclip sidecar.
- `companies.sh` can later act as a discovery/index layer over repos implementing this format.
### 3.2 Non-Goals
- No central registry is required for package validity.
- This is not full database backup/restore.
- This does not attempt to export runtime state like:
- heartbeat runs
- API keys
- spend totals
- run sessions
- transient workspaces
- This does not require a first-class runtime `teams` table before team portability ships.
## 4. Current State In Repo
Current implementation exists here:
- shared types: `packages/shared/src/types/company-portability.ts`
- shared validators: `packages/shared/src/validators/company-portability.ts`
- server routes: `server/src/routes/companies.ts`
- server service: `server/src/services/company-portability.ts`
- CLI commands: `cli/src/commands/client/company.ts`
Current product limitations:
1. Import/export UX still needs deeper tree-selection and skill/package management polish.
2. Adapter-specific skill sync remains uneven across adapters and must degrade cleanly when unsupported.
3. Projects and starter tasks should stay opt-in on export rather than default package content.
4. Import/export still needs stronger coverage around attribution, pin verification, and executable-package warnings.
5. The current markdown frontmatter parser is intentionally lightweight and should stay constrained to the documented shape.
## 5. Canonical Package Direction
### 5.1 Canonical Authoring Format
The canonical authoring format becomes a markdown-first package rooted in one of:
- `COMPANY.md`
- `TEAM.md`
- `AGENTS.md`
- `PROJECT.md`
- `TASK.md`
- `SKILL.md`
The normative draft is:
- `docs/companies/companies-spec.md`
### 5.2 Relationship To Agent Skills
Paperclip must not redefine `SKILL.md`.
Rules:
- `SKILL.md` stays Agent Skills compatible
- the company package model is an extension of Agent Skills
- the base package is vendor-neutral and intended for any agent-company runtime
- Paperclip-specific fidelity lives in `.paperclip.yaml`
- Paperclip may resolve and install `SKILL.md` packages, but it must not require a Paperclip-only skill format
- `skills.sh` compatibility is a V1 requirement, not a future nice-to-have
### 5.3 Agent-To-Skill Association
`AGENTS.md` should associate skills by skill shortname or slug, not by verbose path in the common case.
Preferred example:
- `skills: [review, react-best-practices]`
Resolution model:
- `review` resolves to `skills/review/SKILL.md` by package convention
- if the skill is external or referenced, the skill package owns that complexity
- exporters should prefer shortname-based associations in `AGENTS.md`
- importers should resolve the shortname against local package skills first, then referenced or installed company skills
### 5.4 Base Package Vs Paperclip Extension
The repo format should have two layers:
- base package:
- minimal, readable, social, vendor-neutral
- implicit folder discovery by convention
- no Paperclip-only runtime fields by default
- Paperclip extension:
- `.paperclip.yaml`
- adapter/runtime/permissions/budget/workspace fidelity
- emitted by Paperclip tools as a sidecar while the base package stays readable
### 5.5 Relationship To Current V1 Manifest
`paperclip.manifest.json` is not part of the future package direction.
This should be treated as a hard cutover in product direction.
- markdown-first repo layout is the target
- no new work should deepen investment in the old manifest model
- future portability APIs and UI should target the markdown-first model only
## 6. Package Graph Model
### 6.1 Entity Kinds
Paperclip import/export should support these entity kinds:
- company
- team
- agent
- project
- task
- skill
### 6.2 Team Semantics
`team` is a package concept first, not a database-table requirement.
In Paperclip V2 portability:
- a team is an importable org subtree
- it is rooted at a manager agent
- it can be attached under a target manager in an existing company
This avoids blocking portability on a future runtime `teams` model.
Imported-team tracking should initially be package/provenance-based:
- if a team package was imported, the imported agents should carry enough provenance to reconstruct that grouping
- Paperclip can treat “this set of agents came from team package X” as the imported-team model
- provenance grouping is the intended near- and medium-term team model for import/export
- only add a first-class runtime `teams` table later if product needs move beyond what provenance grouping can express
### 6.3 Dependency Graph
Import should operate on an entity graph, not raw file selection.
Examples:
- selecting an agent auto-selects its required docs and skill refs
- selecting a team auto-selects its subtree
- selecting a company auto-selects all included entities by default
- selecting a project auto-selects its starter tasks
The preview output should reflect graph resolution explicitly.
## 7. External References, Pinning, And Attribution
### 7.1 Why This Matters
Some packages will:
- reference upstream files we do not want to republish
- include third-party work where attribution must remain visible
- need protection from branch hot-swapping
### 7.2 Policy
Paperclip should support source references in package metadata with:
- repo
- path
- commit sha
- optional blob sha
- optional sha256
- attribution
- license
- usage mode
Usage modes:
- `vendored`
- `referenced`
- `mirrored`
Default exporter behavior for third-party content should be:
- prefer `referenced`
- preserve attribution
- do not silently inline third-party content into exports
### 7.3 Trust Model
Imported package content should be classified by trust level:
- markdown-only
- markdown + assets
- markdown + scripts/executables
The UI and CLI should surface this clearly before apply.
## 8. Import Behavior
### 8.1 Supported Sources
- local folder
- local package root file
- GitHub repo URL
- GitHub subtree URL
- direct URL to markdown/package root
Registry-based discovery may be added later, but must remain optional.
### 8.2 Import Targets
- new company
- existing company
For existing company imports, the preview must support:
- collision handling
- attach-point selection for team imports
- selective entity import
### 8.3 Collision Strategy
Current `rename | skip | replace` support remains, but matching should improve over time.
Preferred matching order:
1. prior install provenance
2. stable package entity identity
3. slug
4. human name as weak fallback
Slug-only matching is acceptable only as a transitional strategy.
### 8.4 Required Preview Output
Every import preview should surface:
- target company action
- entity-level create/update/skip plan
- referenced external content
- missing files
- hash mismatch or pinning issues
- env inputs, including required vs optional and default values when present
- unsupported content types
- trust/licensing warnings
### 8.5 Adapter Skill Sync Surface
People want skill management in the UI, but skills are adapter-dependent.
That means portability and UI planning must include an adapter capability model for skills.
Paperclip should define a new adapter surface area around skills:
- list currently enabled skills for an agent
- report how those skills are represented by the adapter
- install or enable a skill
- disable or remove a skill
- report sync state between desired package config and actual adapter state
Examples:
- Claude Code / Codex style adapters may manage skills as local filesystem packages or adapter-owned skill directories
- OpenClaw-style adapters may expose currently enabled skills through an API or a reflected config surface
- some adapters may be read-only and only report what they have
Planned adapter capability shape:
- `supportsSkillRead`
- `supportsSkillWrite`
- `supportsSkillRemove`
- `supportsSkillSync`
- `skillStorageKind` such as `filesystem`, `remote_api`, `inline_config`, or `unknown`
Baseline adapter interface:
- `listSkills(agent)`
- `applySkills(agent, desiredSkills)`
- `removeSkill(agent, skillId)` optional
- `getSkillSyncState(agent, desiredSkills)` optional
Planned Paperclip behavior:
- if an adapter supports read, Paperclip should show current skills in the UI
- if an adapter supports write, Paperclip should let the user enable/disable imported skills
- if an adapter supports sync, Paperclip should compute desired vs actual state and offer reconcile actions
- if an adapter does not support these capabilities, the UI should still show the package-level desired skills but mark them unmanaged
## 9. Export Behavior
### 9.1 Default Export Target
Default export target should become a markdown-first folder structure.
Example:
```text
my-company/
├── COMPANY.md
├── agents/
├── teams/
└── skills/
```
### 9.2 Export Rules
Exports should:
- omit machine-local ids
- omit timestamps and counters unless explicitly needed
- omit secret values
- omit local absolute paths
- omit duplicated inline prompt content from `.paperclip.yaml` when `AGENTS.md` already carries the instructions
- preserve references and attribution
- emit `.paperclip.yaml` alongside the base package
- express adapter env/secrets as portable env input declarations rather than exported secret binding ids
- preserve compatible `SKILL.md` content as-is
Projects and issues should not be exported by default.
They should be opt-in through selectors such as:
- `--projects project-shortname-1,project-shortname-2`
- `--issues PAP-1,PAP-3`
- `--project-issues project-shortname-1,project-shortname-2`
This supports “clean public company package” workflows where a maintainer exports a follower-facing company package without bundling active work items every time.
### 9.3 Export Units
Initial export units:
- company package
- team package
- single agent package
Later optional units:
- skill pack export
- seed projects/tasks bundle
## 10. Storage Model Inside Paperclip
### 10.1 Short-Term
In the first phase, imported entities can continue mapping onto current runtime tables:
- company -> companies
- agent -> agents
- team -> imported agent subtree attachment plus package provenance grouping
- skill -> company-scoped reusable package metadata plus agent-scoped desired-skill attachment state where supported
### 10.2 Medium-Term
Paperclip should add managed package/provenance records so imports are not anonymous one-off copies.
Needed capabilities:
- remember install origin
- support re-import / upgrade
- distinguish local edits from upstream package state
- preserve external refs and package-level metadata
- preserve imported team grouping without requiring a runtime `teams` table immediately
- preserve desired-skill state separately from adapter runtime state
- support both company-scoped reusable skills and agent-scoped skill attachments
Suggested future tables:
- package_installs
- package_install_entities
- package_sources
- agent_skill_desires
- adapter_skill_snapshots
This is not required for phase 1 UI, but it is required for a robust long-term system.
## 11. API Plan
### 11.1 Keep Existing Endpoints Initially
Retain:
- `POST /api/companies/:companyId/export`
- `POST /api/companies/import/preview`
- `POST /api/companies/import`
But evolve payloads toward the markdown-first graph model.
### 11.2 New API Capabilities
Add support for:
- package root resolution from local/GitHub inputs
- graph resolution preview
- source pin and hash verification results
- entity-level selection
- team attach target selection
- provenance-aware collision planning
### 11.3 Parsing Changes
Replace the current ad hoc markdown frontmatter parser with a real parser that can handle:
- nested YAML
- arrays/objects reliably
- consistent round-tripping
This is a prerequisite for the new package model.
## 12. CLI Plan
The CLI should continue to support direct import/export without a registry.
Target commands:
- `paperclipai company export <company-id> --out <path>`
- `paperclipai company import --from <path-or-url> --dry-run`
- `paperclipai company import --from <path-or-url> --target existing -C <company-id>`
Planned additions:
- `--package-kind company|team|agent`
- `--attach-under <agent-id-or-slug>` for team imports
- `--strict-pins`
- `--allow-unpinned`
- `--materialize-references`
- `--sync-skills`
## 13. UI Plan
### 13.1 Company Settings Import / Export
Add a real import/export section to Company Settings.
Export UI:
- export package kind selector
- include options
- local download/export destination guidance
- attribution/reference summary
Import UI:
- source entry:
- upload/folder where supported
- GitHub URL
- generic URL
- preview pane with:
- resolved package root
- dependency tree
- checkboxes by entity
- trust/licensing warnings
- secrets requirements
- collision plan
### 13.2 Team Import UX
If importing a team into an existing company:
- show the subtree structure
- require the user to choose where to attach it
- preview manager/reporting updates before apply
- preserve imported-team provenance so the UI can later say “these agents came from team package X”
### 13.3 Skills UX
See also:
- `doc/plans/2026-03-14-skills-ui-product-plan.md`
If importing skills:
- show whether each skill is local, vendored, or referenced
- show whether it contains scripts/assets
- preserve Agent Skills compatibility in presentation and export
- preserve `skills.sh` compatibility in both import and install flows
- show agent skill attachments by shortname/slug rather than noisy file paths
- treat agent skills as a dedicated agent tab, not just another subsection of configuration
- show current adapter-reported skills when supported
- show desired package skills separately from actual adapter state
- offer reconcile actions when the adapter supports sync
## 14. Rollout Phases
### Phase 1: Stabilize Current V1 Portability
- add tests for current portability flows
- replace the frontmatter parser
- add Company Settings UI for current import/export capabilities
- start cutover work toward the markdown-first package reader
### Phase 2: Markdown-First Package Reader
- support `COMPANY.md` / `TEAM.md` / `AGENTS.md` root detection
- build internal graph from markdown-first packages
- support local folder and GitHub repo inputs natively
- support agent skill references by shortname/slug
- resolve local `skills/<slug>/SKILL.md` packages by convention
- support `skills.sh`-compatible skill repos as V1 package sources
### Phase 3: Graph-Based Import UX And Skill Surfaces
- entity tree preview
- checkbox selection
- team subtree attach flow
- licensing/trust/reference warnings
- company skill library groundwork
- dedicated agent `Skills` tab groundwork
- adapter skill read/sync UI groundwork
### Phase 4: New Export Model
- export markdown-first folder structure by default
### Phase 5: Provenance And Upgrades
- persist install provenance
- support package-aware re-import and upgrades
- improve collision matching beyond slug-only
- add imported-team provenance grouping
- add desired-vs-actual skill sync state
### Phase 6: Optional Seed Content
- goals
- projects
- starter issues/tasks
This phase is intentionally after the structural model is stable.
## 15. Documentation Plan
Primary docs:
- `docs/companies/companies-spec.md` as the package-format draft
- this implementation plan for rollout sequencing
Docs to update later as implementation lands:
- `doc/SPEC-implementation.md`
- `docs/api/companies.md`
- `docs/cli/control-plane-commands.md`
- board operator docs for Company Settings import/export
## 16. Open Questions
1. Should imported skill packages be stored as managed package files in Paperclip storage, or only referenced at import time?
Decision: managed package files should support both company-scoped reuse and agent-scoped attachment.
2. What is the minimum adapter skill interface needed to make the UI useful across Claude Code, Codex, OpenClaw, and future adapters?
Decision: use the baseline interface in section 8.5.
3. Should Paperclip support direct local folder selection in the web UI, or keep that CLI-only initially?
4. Do we want optional generated lock files in phase 2, or defer them until provenance work?
5. How strict should pinning be by default for GitHub references:
- warn on unpinned
- or block in normal mode
6. Is package-provenance grouping enough for imported teams, or do we expect product requirements soon that would justify a first-class runtime `teams` table?
Decision: provenance grouping is enough for the import/export product model for now.
## 17. Recommendation
Engineering should treat this as the current plan of record for company import/export beyond the existing V1 portability feature.
Immediate next steps:
1. accept `docs/companies/companies-spec.md` as the package-format draft
2. implement phase 1 stabilization work
3. build phase 2 markdown-first package reader before expanding ClipHub or `companies.sh`
4. treat the old manifest-based format as deprecated and not part of the future surface
This keeps Paperclip aligned with:
- GitHub-native distribution
- Agent Skills compatibility
- a registry-optional ecosystem model

View File

@@ -0,0 +1,699 @@
# Kitchen Sink Plugin Plan
## Goal
Add a new first-party example plugin, `Kitchen Sink (Example)`, that demonstrates every currently implemented Paperclip plugin API surface in one place.
This plugin is meant to be:
- a living reference implementation for contributors
- a manual test harness for the plugin runtime
- a discoverable demo of what plugins can actually do today
It is not meant to be a polished end-user product plugin.
## Why
The current plugin system has a real API surface, but it is spread across:
- SDK docs
- SDK types
- plugin spec prose
- two example plugins that each show only a narrow slice
That makes it hard to answer basic questions like:
- what can plugins render?
- what can plugin workers actually do?
- which surfaces are real versus aspirational?
- how should a new plugin be structured in this repo?
The kitchen-sink plugin should answer those questions by example.
## Success Criteria
The plugin is successful if a contributor can install it and, without reading the SDK first, discover and exercise the current plugin runtime surface area from inside Paperclip.
Concretely:
- it installs from the bundled examples list
- it exposes at least one demo for every implemented worker API surface
- it exposes at least one demo for every host-mounted UI surface
- it clearly labels local-only / trusted-only demos
- it is safe enough for local development by default
- it doubles as a regression harness for plugin runtime changes
## Constraints
- Keep it instance-installed, not company-installed.
- Treat this as a trusted/local example plugin.
- Do not rely on cloud-safe runtime assumptions.
- Avoid destructive defaults.
- Avoid irreversible mutations unless they are clearly labeled and easy to undo.
## Source Of Truth For This Plan
This plan is based on the currently implemented SDK/types/runtime, not only the long-horizon spec.
Primary references:
- `packages/plugins/sdk/README.md`
- `packages/plugins/sdk/src/types.ts`
- `packages/plugins/sdk/src/ui/types.ts`
- `packages/shared/src/constants.ts`
- `packages/shared/src/types/plugin.ts`
## Current Surface Inventory
### Worker/runtime APIs to demonstrate
These are the concrete `ctx` clients currently exposed by the SDK:
- `ctx.config`
- `ctx.events`
- `ctx.jobs`
- `ctx.launchers`
- `ctx.http`
- `ctx.secrets`
- `ctx.assets`
- `ctx.activity`
- `ctx.state`
- `ctx.entities`
- `ctx.projects`
- `ctx.companies`
- `ctx.issues`
- `ctx.agents`
- `ctx.goals`
- `ctx.data`
- `ctx.actions`
- `ctx.streams`
- `ctx.tools`
- `ctx.metrics`
- `ctx.logger`
### UI surfaces to demonstrate
Surfaces defined in the SDK:
- `page`
- `settingsPage`
- `dashboardWidget`
- `sidebar`
- `sidebarPanel`
- `detailTab`
- `taskDetailView`
- `projectSidebarItem`
- `toolbarButton`
- `contextMenuItem`
- `commentAnnotation`
- `commentContextMenuItem`
### Current host confidence
Confirmed or strongly indicated as mounted in the current app:
- `page`
- `settingsPage`
- `dashboardWidget`
- `detailTab`
- `projectSidebarItem`
- comment surfaces
- launcher infrastructure
Need explicit validation before claiming full demo coverage:
- `sidebar`
- `sidebarPanel`
- `taskDetailView`
- `toolbarButton` as direct slot, distinct from launcher placement
- `contextMenuItem` as direct slot, distinct from comment menu and launcher placement
The implementation should keep a small validation checklist for these before we call the plugin "complete".
## Plugin Concept
The plugin should be named:
- display name: `Kitchen Sink (Example)`
- package: `@paperclipai/plugin-kitchen-sink-example`
- plugin id: `paperclip.kitchen-sink-example` or `paperclip-kitchen-sink-example`
Recommendation: use `paperclip-kitchen-sink-example` to match current in-repo example naming style.
Category mix:
- `ui`
- `automation`
- `workspace`
- `connector`
That is intentionally broad because the point is coverage.
## UX Shape
The plugin should have one main full-page demo console plus smaller satellites on other surfaces.
### 1. Plugin page
Primary route: the plugin `page` surface should be the central dashboard for all demos.
Recommended page sections:
- `Overview`
- what this plugin demonstrates
- current capabilities granted
- current host context
- `UI Surfaces`
- links explaining where each other surface should appear
- `Data + Actions`
- buttons and forms for bridge-driven worker demos
- `Events + Streams`
- emit event
- watch event log
- stream demo output
- `Paperclip Domain APIs`
- companies
- projects/workspaces
- issues
- goals
- agents
- `Local Workspace + Process`
- file listing
- file read/write scratch area
- child process demo
- `Jobs + Webhooks + Tools`
- job status
- webhook URL and recent deliveries
- declared tools
- `State + Entities + Assets`
- scoped state editor
- plugin entity inspector
- upload/generated asset demo
- `Observability`
- metrics written
- activity log samples
- latest worker logs
### 2. Dashboard widget
A compact widget on the main dashboard should show:
- plugin health
- count of demos exercised
- recent event/stream activity
- shortcut to the full plugin page
### 3. Project sidebar item
Add a `Kitchen Sink` link under each project that deep-links into a project-scoped plugin tab.
### 4. Detail tabs
Use detail tabs to demonstrate entity-context rendering on:
- `project`
- `issue`
- `agent`
- `goal`
Each tab should show:
- the host context it received
- the relevant entity fetch via worker bridge
- one small action scoped to that entity
### 5. Comment surfaces
Use issue comment demos to prove comment-specific extension points:
- `commentAnnotation`
- render parsed metadata below each comment
- show comment id, issue id, and a small derived status
- `commentContextMenuItem`
- add a menu action like `Copy Context To Kitchen Sink`
- action writes a plugin entity or state record for later inspection
### 6. Settings page
Custom `settingsPage` should be intentionally simple and operational:
- `About`
- `Danger / Trust Model`
- demo toggles
- local process defaults
- workspace scratch-path behavior
- secret reference inputs
- event/job/webhook sample config
This plugin should also keep the generic plugin settings `Status` tab useful by writing health, logs, and metrics.
## Feature Matrix
Each implemented worker API should have a visible demo.
### `ctx.config`
Demo:
- read live config
- show config JSON
- react to config changes without restart where possible
### `ctx.events`
Demos:
- emit a plugin event
- subscribe to plugin events
- subscribe to a core Paperclip event such as `issue.created`
- show recent received events in a timeline
### `ctx.jobs`
Demos:
- one scheduled heartbeat-style demo job
- one manual run button from the UI if host supports manual job trigger
- show last run result and timestamps
### `ctx.launchers`
Demos:
- declare launchers in manifest
- optionally register one runtime launcher from the worker
- show launcher metadata on the plugin page
### `ctx.http`
Demo:
- make a simple outbound GET request to a safe endpoint
- show status code, latency, and JSON result
Recommendation: default to a Paperclip-local endpoint or a stable public echo endpoint to avoid flaky docs.
### `ctx.secrets`
Demo:
- operator enters a secret reference in config
- plugin resolves it on demand
- UI only shows masked result length / success status, never raw secret
### `ctx.assets`
Demos:
- generate a text asset from the UI
- optionally upload a tiny JSON blob or screenshot-like text file
- show returned asset URL
### `ctx.activity`
Demo:
- button to write a plugin activity log entry against current company/entity
### `ctx.state`
Demos:
- instance-scoped state
- company-scoped state
- project-scoped state
- issue-scoped state
- delete/reset controls
Use a small state inspector/editor on the plugin page.
### `ctx.entities`
Demos:
- create plugin-owned sample records
- list/filter them
- show one realistic use case such as "copied comments" or "demo sync records"
### `ctx.projects`
Demos:
- list projects
- list project workspaces
- resolve primary workspace
- resolve workspace for issue
### `ctx.companies`
Demo:
- list companies and show current selected company
### `ctx.issues`
Demos:
- list issues in current company
- create issue
- update issue status/title
- list comments
- create comment
### `ctx.agents`
Demos:
- list agents
- invoke one agent with a test prompt
- pause/resume where safe
Agent mutation controls should be behind an explicit warning.
### `ctx.agents.sessions`
Demos:
- create agent chat session
- send message
- stream events back to the UI
- close session
This is a strong candidate for the best "wow" demo on the plugin page.
### `ctx.goals`
Demos:
- list goals
- create goal
- update status/title
### `ctx.data`
Use throughout the plugin for all read-side bridge demos.
### `ctx.actions`
Use throughout the plugin for all mutation-side bridge demos.
### `ctx.streams`
Demos:
- live event log stream
- token-style stream from an agent session relay
- fake progress stream for a long-running action
### `ctx.tools`
Demos:
- declare 2-3 simple agent tools
- tool 1: echo/diagnostics
- tool 2: project/workspace summary
- tool 3: create issue or write plugin state
The plugin page should list declared tools and show example input payloads.
### `ctx.metrics`
Demo:
- write a sample metric on each major demo action
- surface a small recent metrics table in the plugin page
### `ctx.logger`
Demo:
- every action logs structured entries
- plugin settings `Status` page then doubles as the log viewer
## Local Workspace And Process Demos
The plugin SDK intentionally leaves file/process operations to the plugin itself once it has workspace metadata.
The kitchen-sink plugin should demonstrate that explicitly.
### Workspace demos
- list files from a selected workspace
- read a file
- write to a plugin-owned scratch file
- optionally search files with `rg` if available
### Process demos
- run a short-lived command like `pwd`, `ls`, or `git status`
- stream stdout/stderr back to UI
- show exit code and timing
Important safeguards:
- default commands must be read-only
- no shell interpolation from arbitrary free-form input in v1
- provide a curated command list or a strongly validated command form
- clearly label this area as local-only and trusted-only
## Proposed Manifest Coverage
The plugin should aim to declare:
- `page`
- `settingsPage`
- `dashboardWidget`
- `detailTab` for `project`, `issue`, `agent`, `goal`
- `projectSidebarItem`
- `commentAnnotation`
- `commentContextMenuItem`
Then, after host validation, add if supported:
- `sidebar`
- `sidebarPanel`
- `taskDetailView`
- `toolbarButton`
- `contextMenuItem`
It should also declare one or more `ui.launchers` entries to exercise launcher behavior independently of slot rendering.
## Proposed Package Layout
New package:
- `packages/plugins/examples/plugin-kitchen-sink-example/`
Expected files:
- `package.json`
- `README.md`
- `tsconfig.json`
- `src/index.ts`
- `src/manifest.ts`
- `src/worker.ts`
- `src/ui/index.tsx`
- `src/ui/components/...`
- `src/ui/hooks/...`
- `src/lib/...`
- optional `scripts/build-ui.mjs` if UI bundling needs esbuild
## Proposed Internal Architecture
### Worker modules
Recommended split:
- `src/worker.ts`
- plugin definition and wiring
- `src/worker/data.ts`
- `ctx.data.register(...)`
- `src/worker/actions.ts`
- `ctx.actions.register(...)`
- `src/worker/events.ts`
- event subscriptions and event log buffer
- `src/worker/jobs.ts`
- scheduled job handlers
- `src/worker/tools.ts`
- tool declarations and handlers
- `src/worker/local-runtime.ts`
- file/process demos
- `src/worker/demo-store.ts`
- helpers for state/entities/assets/metrics
### UI modules
Recommended split:
- `src/ui/index.tsx`
- exported slot components
- `src/ui/page/KitchenSinkPage.tsx`
- `src/ui/settings/KitchenSinkSettingsPage.tsx`
- `src/ui/widgets/KitchenSinkDashboardWidget.tsx`
- `src/ui/tabs/ProjectKitchenSinkTab.tsx`
- `src/ui/tabs/IssueKitchenSinkTab.tsx`
- `src/ui/tabs/AgentKitchenSinkTab.tsx`
- `src/ui/tabs/GoalKitchenSinkTab.tsx`
- `src/ui/comments/KitchenSinkCommentAnnotation.tsx`
- `src/ui/comments/KitchenSinkCommentMenuItem.tsx`
- `src/ui/shared/...`
## Configuration Schema
The plugin should have a substantial but understandable `instanceConfigSchema`.
Recommended config fields:
- `enableDangerousDemos`
- `enableWorkspaceDemos`
- `enableProcessDemos`
- `showSidebarEntry`
- `showSidebarPanel`
- `showProjectSidebarItem`
- `showCommentAnnotation`
- `showCommentContextMenuItem`
- `showToolbarLauncher`
- `defaultDemoCompanyId` optional
- `secretRefExample`
- `httpDemoUrl`
- `processAllowedCommands`
- `workspaceScratchSubdir`
Defaults should keep risky behavior off.
## Safety Defaults
Default posture:
- UI and read-only demos on
- mutating domain demos on but explicitly labeled
- process demos off by default
- no arbitrary shell input by default
- no raw secret rendering ever
## Phased Build Plan
### Phase 1: Core plugin skeleton
- scaffold package
- add manifest, worker, UI entrypoints
- add README
- make it appear in bundled examples list
### Phase 2: Core, confirmed UI surfaces
- plugin page
- settings page
- dashboard widget
- project sidebar item
- detail tabs
### Phase 3: Core worker APIs
- config
- state
- entities
- companies/projects/issues/goals
- data/actions
- metrics/logger/activity
### Phase 4: Real-time and automation APIs
- streams
- events
- jobs
- webhooks
- agent sessions
- tools
### Phase 5: Local trusted runtime demos
- workspace file demos
- child process demos
- guarded by config
### Phase 6: Secondary UI surfaces
- comment annotation
- comment context menu item
- launchers
### Phase 7: Validation-only surfaces
Validate whether the current host truly mounts:
- `sidebar`
- `sidebarPanel`
- `taskDetailView`
- direct-slot `toolbarButton`
- direct-slot `contextMenuItem`
If mounted, add demos.
If not mounted, document them as SDK-defined but host-pending.
## Documentation Deliverables
The plugin should ship with a README that includes:
- what it demonstrates
- which surfaces are local-only
- how to install it
- where each UI surface should appear
- a mapping from demo card to SDK API
It should also be referenced from plugin docs as the "reference everything plugin".
## Testing And Verification
Minimum verification:
- package typecheck/build
- install from bundled example list
- page loads
- widget appears
- project tab appears
- comment surfaces render
- settings page loads
- key actions succeed
Recommended manual checklist:
- create issue from plugin
- create goal from plugin
- emit and receive plugin event
- stream action output
- open agent session and receive streamed reply
- upload an asset
- write plugin activity log
- run a safe local process demo
## Open Questions
1. Should the process demo remain curated-command-only in the first pass?
Recommendation: yes.
2. Should the plugin create throwaway "kitchen sink demo" issues/goals automatically?
Recommendation: no. Make creation explicit.
3. Should we expose unsupported-but-typed surfaces in the UI even if host mounting is not wired?
Recommendation: yes, but label them as `SDK-defined / host validation pending`.
4. Should agent mutation demos include pause/resume by default?
Recommendation: probably yes, but behind a warning block.
5. Should this plugin be treated as a supported regression harness in CI later?
Recommendation: yes. Long term, this should be the plugin-runtime smoke test package.
## Recommended Next Step
If this plan looks right, the next implementation pass should start by building only:
- package skeleton
- page
- settings page
- dashboard widget
- one project detail tab
- one issue detail tab
- the basic worker/action/data/state/event scaffolding
That is enough to lock the architecture before filling in every demo surface.

View File

@@ -0,0 +1,399 @@
# 2026-03-14 Adapter Skill Sync Rollout
Status: Proposed
Date: 2026-03-14
Audience: Product and engineering
Related:
- `doc/plans/2026-03-14-skills-ui-product-plan.md`
- `doc/plans/2026-03-13-company-import-export-v2.md`
- `docs/companies/companies-spec.md`
## 1. Purpose
This document defines the rollout plan for adapter-wide skill support in Paperclip.
The goal is not just “show a skills tab.” The goal is:
- every adapter has a deliberate skill-sync truth model
- the UI tells the truth for that adapter
- Paperclip stores desired skill state consistently even when the adapter cannot fully reconcile it
- unsupported adapters degrade clearly and safely
## 2. Current Adapter Matrix
Paperclip currently has these adapters:
- `claude_local`
- `codex_local`
- `cursor_local`
- `gemini_local`
- `opencode_local`
- `pi_local`
- `openclaw_gateway`
The current skill API supports:
- `unsupported`
- `persistent`
- `ephemeral`
Current implementation state:
- `codex_local`: implemented, `persistent`
- `claude_local`: implemented, `ephemeral`
- `cursor_local`: not yet implemented, but technically suited to `persistent`
- `gemini_local`: not yet implemented, but technically suited to `persistent`
- `pi_local`: not yet implemented, but technically suited to `persistent`
- `opencode_local`: not yet implemented; likely `persistent`, but with special handling because it currently injects into Claudes shared skills home
- `openclaw_gateway`: not yet implemented; blocked on gateway protocol support, so `unsupported` for now
## 3. Product Principles
1. Desired skills live in Paperclip for every adapter.
2. Adapters may expose different truth models, and the UI must reflect that honestly.
3. Persistent adapters should read and reconcile actual installed state.
4. Ephemeral adapters should report effective runtime state, not pretend they own a persistent install.
5. Shared-home adapters need stronger safeguards than isolated-home adapters.
6. Gateway or cloud adapters must not fake local filesystem sync.
## 4. Adapter Classification
### 4.1 Persistent local-home adapters
These adapters have a stable local skills directory that Paperclip can read and manage.
Candidates:
- `codex_local`
- `cursor_local`
- `gemini_local`
- `pi_local`
- `opencode_local` with caveats
Expected UX:
- show actual installed skills
- show managed vs external skills
- support `sync`
- support stale removal
- preserve unknown external skills
### 4.2 Ephemeral mount adapters
These adapters do not have a meaningful Paperclip-owned persistent install state.
Current adapter:
- `claude_local`
Expected UX:
- show desired Paperclip skills
- show any discoverable external dirs if available
- say “mounted on next run” instead of “installed”
- do not imply a persistent adapter-owned install state
### 4.3 Unsupported / remote adapters
These adapters cannot support skill sync without new external capabilities.
Current adapter:
- `openclaw_gateway`
Expected UX:
- company skill library still works
- agent attachment UI still works at the desired-state level
- actual adapter state is `unsupported`
- sync button is disabled or replaced with explanatory text
## 5. Per-Adapter Plan
### 5.1 Codex Local
Target mode:
- `persistent`
Current state:
- already implemented
Requirements to finish:
- keep as reference implementation
- tighten tests around external custom skills and stale removal
- ensure imported company skills can be attached and synced without manual path work
Success criteria:
- list installed managed and external skills
- sync desired skills into `CODEX_HOME/skills`
- preserve external user-managed skills
### 5.2 Claude Local
Target mode:
- `ephemeral`
Current state:
- already implemented
Requirements to finish:
- polish status language in UI
- clearly distinguish “desired” from “mounted on next run”
- optionally surface configured external skill dirs if Claude exposes them
Success criteria:
- desired skills stored in Paperclip
- selected skills mounted per run
- no misleading “installed” language
### 5.3 Cursor Local
Target mode:
- `persistent`
Technical basis:
- runtime already injects Paperclip skills into `~/.cursor/skills`
Implementation work:
1. Add `listSkills` for Cursor.
2. Add `syncSkills` for Cursor.
3. Reuse the same managed-symlink pattern as Codex.
4. Distinguish:
- managed Paperclip skills
- external skills already present
- missing desired skills
- stale managed skills
Testing:
- unit tests for discovery
- unit tests for sync and stale removal
- verify shared auth/session setup is not disturbed
Success criteria:
- Cursor agents show real installed state
- syncing from the agent Skills tab works
### 5.4 Gemini Local
Target mode:
- `persistent`
Technical basis:
- runtime already injects Paperclip skills into `~/.gemini/skills`
Implementation work:
1. Add `listSkills` for Gemini.
2. Add `syncSkills` for Gemini.
3. Reuse managed-symlink conventions from Codex/Cursor.
4. Verify auth remains untouched while skills are reconciled.
Potential caveat:
- if Gemini treats that skills directory as shared user state, the UI should warn before removing stale managed skills
Success criteria:
- Gemini agents can reconcile desired vs actual skill state
### 5.5 Pi Local
Target mode:
- `persistent`
Technical basis:
- runtime already injects Paperclip skills into `~/.pi/agent/skills`
Implementation work:
1. Add `listSkills` for Pi.
2. Add `syncSkills` for Pi.
3. Reuse managed-symlink helpers.
4. Verify session-file behavior remains independent from skill sync.
Success criteria:
- Pi agents expose actual installed skill state
- Paperclip can sync desired skills into Pis persistent home
### 5.6 OpenCode Local
Target mode:
- `persistent`
Special case:
- OpenCode currently injects Paperclip skills into `~/.claude/skills`
This is product-risky because:
- it shares state with Claude
- Paperclip may accidentally imply the skills belong only to OpenCode when the home is shared
Plan:
Phase 1:
- implement `listSkills` and `syncSkills`
- treat it as `persistent`
- explicitly label the home as shared in UI copy
- only remove stale managed Paperclip skills that are clearly marked as Paperclip-managed
Phase 2:
- investigate whether OpenCode supports its own isolated skills home
- if yes, migrate to an adapter-specific home and remove the shared-home caveat
Success criteria:
- OpenCode agents show real state
- shared-home risk is visible and bounded
### 5.7 OpenClaw Gateway
Target mode:
- `unsupported` until gateway protocol support exists
Required external work:
- gateway API to list installed/available skills
- gateway API to install/remove or otherwise reconcile skills
- gateway metadata for whether state is persistent or ephemeral
Until then:
- Paperclip stores desired skills only
- UI shows unsupported actual state
- no fake sync implementation
Future target:
- likely a fourth truth model eventually, such as remote-managed persistent state
- for now, keep the current API and treat gateway as unsupported
## 6. API Plan
## 6.1 Keep the current minimal adapter API
Near-term adapter contract remains:
- `listSkills(ctx)`
- `syncSkills(ctx, desiredSkills)`
This is enough for all local adapters.
## 6.2 Optional extension points
Add only if needed after the first broad rollout:
- `skillHomeLabel`
- `sharedHome: boolean`
- `supportsExternalDiscovery: boolean`
- `supportsDestructiveSync: boolean`
These should be optional metadata additions to the snapshot, not required new adapter methods.
## 7. UI Plan
The company-level skill library can stay adapter-neutral.
The agent-level Skills tab must become adapter-aware by copy and status:
- `persistent`: installed / missing / stale / external
- `ephemeral`: mounted on next run / external / desired only
- `unsupported`: desired only, adapter cannot report actual state
Additional UI requirement for shared-home adapters:
- show a small warning that the adapter uses a shared user skills home
- avoid destructive wording unless Paperclip can prove a skill is Paperclip-managed
## 8. Rollout Phases
### Phase 1: Finish the local filesystem family
Ship:
- `cursor_local`
- `gemini_local`
- `pi_local`
Rationale:
- these are the closest to Codex in architecture
- they already inject into stable local skill homes
### Phase 2: OpenCode shared-home support
Ship:
- `opencode_local`
Rationale:
- technically feasible now
- needs slightly more careful product language because of the shared Claude skills home
### Phase 3: Gateway support decision
Decide:
- keep `openclaw_gateway` unsupported for V1
- or extend the gateway protocol for remote skill management
My recommendation:
- do not block V1 on gateway support
- keep it explicitly unsupported until the remote protocol exists
## 9. Definition Of Done
Adapter-wide skill support is ready when all are true:
1. Every adapter has an explicit truth model:
- `persistent`
- `ephemeral`
- `unsupported`
2. The UI copy matches that truth model.
3. All local persistent adapters implement:
- `listSkills`
- `syncSkills`
4. Tests cover:
- desired-state storage
- actual-state discovery
- managed vs external distinctions
- stale managed-skill cleanup where supported
5. `openclaw_gateway` is either:
- explicitly unsupported with clean UX
- or backed by a real remote skill API
## 10. Recommendation
The recommended immediate order is:
1. `cursor_local`
2. `gemini_local`
3. `pi_local`
4. `opencode_local`
5. defer `openclaw_gateway`
That gets Paperclip from “skills work for Codex and Claude” to “skills work for the whole local-adapter family,” which is the meaningful V1 milestone.

View File

@@ -0,0 +1,468 @@
# Billing Ledger and Reporting
## Context
Paperclip currently stores model spend in `cost_events` and operational run state in `heartbeat_runs`.
That split is fine, but the current reporting code tries to infer billing semantics by mixing both tables:
- `cost_events` knows provider, model, tokens, and dollars
- `heartbeat_runs.usage_json` knows some per-run billing metadata
- `heartbeat_runs.usage_json` does **not** currently carry enough normalized billing dimensions to support honest provider-level reporting
This becomes incorrect as soon as a company uses more than one provider, more than one billing channel, or more than one billing mode.
Examples:
- direct OpenAI API usage
- Claude subscription usage with zero marginal dollars
- subscription overage with dollars and tokens
- OpenRouter billing where the biller is OpenRouter but the upstream provider is Anthropic or OpenAI
The system needs to support:
- dollar reporting
- token reporting
- subscription-included usage
- subscription overage
- direct metered API usage
- future aggregator billing such as OpenRouter
## Product Decision
`cost_events` becomes the canonical billing and usage ledger for reporting.
`heartbeat_runs` remains an operational execution log. It may keep mirrored billing metadata for debugging and transcripts, but reporting must not reconstruct billing semantics from `heartbeat_runs.usage_json`.
## Decision: One Ledger Or Two
We do **not** need two tables to solve the current PR's problem.
For request-level inference reporting, `cost_events` is enough if it carries the right dimensions:
- upstream provider
- biller
- billing type
- model
- token fields
- billed amount
That is why the first implementation pass extends `cost_events` instead of introducing a second table immediately.
However, if Paperclip needs to account for the full billing surface of aggregators and managed AI platforms, then `cost_events` alone is not enough.
Some charges are not cleanly representable as a single model inference event:
- account top-ups and credit purchases
- platform fees charged at purchase time
- BYOK platform fees that are account-level or threshold-based
- prepaid credit expirations, refunds, and adjustments
- provisioned throughput commitments
- fine-tuning, training, model import, and storage charges
- gateway logging or other platform overhead that is not attributable to one prompt/response pair
So the decision is:
- near term: keep `cost_events` as the inference and usage ledger
- next phase: add `finance_events` for non-inference financial events
This is a deliberate split between:
- usage and inference accounting
- account-level and platform-level financial accounting
That separation keeps request reporting honest without forcing us to fake invoice semantics onto rows that were never request-scoped.
## External Motivation And Sources
The need for this model is not theoretical.
It follows directly from the billing systems of providers and aggregators Paperclip needs to support.
### OpenRouter
Source URLs:
- https://openrouter.ai/docs/faq#credit-and-billing-systems
- https://openrouter.ai/pricing
Relevant billing behavior as of March 14, 2026:
- OpenRouter passes through underlying inference pricing and deducts request cost from purchased credits.
- OpenRouter charges a 5.5% fee with a $0.80 minimum when purchasing credits.
- Crypto payments are charged a 5% fee.
- BYOK has its own fee model after a free request threshold.
- OpenRouter billing is aggregated at the OpenRouter account level even when the upstream provider is Anthropic, OpenAI, Google, or another provider.
Implication for Paperclip:
- request usage belongs in `cost_events`
- credit purchases, purchase fees, BYOK fees, refunds, and expirations belong in `finance_events`
- `biller=openrouter` must remain distinct from `provider=anthropic|openai|google|...`
### Cloudflare AI Gateway Unified Billing
Source URL:
- https://developers.cloudflare.com/ai-gateway/features/unified-billing/
Relevant billing behavior as of March 14, 2026:
- Unified Billing lets users call multiple upstream providers while receiving a single Cloudflare bill.
- Usage is paid from Cloudflare-loaded credits.
- Cloudflare supports manual top-ups and auto top-up thresholds.
- Spend limits can stop request processing on daily, weekly, or monthly boundaries.
- Unified Billing traffic can use Cloudflare-managed credentials rather than the user's direct provider key.
Implication for Paperclip:
- request usage needs `biller=cloudflare`
- upstream provider still needs to be preserved separately
- Cloudflare credit loads and related account-level events are not inference rows and should not be forced into `cost_events`
- quota and limits reporting must support biller-level controls, not just upstream provider limits
### Amazon Bedrock
Source URL:
- https://aws.amazon.com/bedrock/pricing/
Relevant billing behavior as of March 14, 2026:
- Bedrock supports on-demand and batch pricing.
- Bedrock pricing varies by region.
- some pricing tiers add premiums or discounts relative to standard pricing
- provisioned throughput is commitment-based rather than request-based
- custom model import uses Custom Model Units billed per minute, with monthly storage charges
- imported model copies are billed in 5-minute windows once active
- customization and fine-tuning introduce training and hosted-model charges beyond normal inference
Implication for Paperclip:
- normal tokenized inference fits in `cost_events`
- provisioned throughput, custom model unit charges, training, and storage charges require `finance_events`
- region and pricing tier need to be first-class dimensions in the financial model
## Ledger Boundary
To keep the system coherent, the table boundary should be explicit.
### `cost_events`
Use `cost_events` for request-scoped usage and inference charges:
- one row per billable or usage-bearing run event
- provider/model/biller/billingType/tokens/cost
- optionally tied to `heartbeat_run_id`
- supports direct APIs, subscriptions, overage, OpenRouter-routed inference, Cloudflare-routed inference, and Bedrock on-demand inference
### `finance_events`
Use `finance_events` for account-scoped or platform-scoped financial events:
- credit purchase
- top-up
- refund
- fee
- expiry
- provisioned capacity
- training
- model import
- storage
- invoice adjustment
These rows may or may not have a related model, provider, or run id.
Trying to force them into `cost_events` would either create fake request rows or create null-heavy rows that mean something fundamentally different from inference usage.
## Canonical Billing Dimensions
Every persisted billing event should model four separate axes:
1. Usage provider
The upstream provider whose model performed the work.
Examples: `openai`, `anthropic`, `google`.
2. Biller
The system that charged for the usage.
Examples: `openai`, `anthropic`, `openrouter`, `cursor`, `chatgpt`.
3. Billing type
The pricing mode applied to the event.
Initial canonical values:
- `metered_api`
- `subscription_included`
- `subscription_overage`
- `credits`
- `fixed`
- `unknown`
4. Measures
Usage and billing must both be storable:
- `input_tokens`
- `output_tokens`
- `cached_input_tokens`
- `cost_cents`
These dimensions are independent.
For example, an event may be:
- provider: `anthropic`
- biller: `openrouter`
- billing type: `metered_api`
- tokens: non-zero
- cost cents: non-zero
Or:
- provider: `anthropic`
- biller: `anthropic`
- billing type: `subscription_included`
- tokens: non-zero
- cost cents: `0`
## Schema Changes
Extend `cost_events` with:
- `heartbeat_run_id uuid null references heartbeat_runs.id`
- `biller text not null default 'unknown'`
- `billing_type text not null default 'unknown'`
- `cached_input_tokens int not null default 0`
Keep `provider` as the upstream usage provider.
Do not overload `provider` to mean biller.
Add a future `finance_events` table for account-level financial events with fields along these lines:
- `company_id`
- `occurred_at`
- `event_kind`
- `direction`
- `biller`
- `provider nullable`
- `execution_adapter_type nullable`
- `pricing_tier nullable`
- `region nullable`
- `model nullable`
- `quantity nullable`
- `unit nullable`
- `amount_cents`
- `currency`
- `estimated`
- `related_cost_event_id nullable`
- `related_heartbeat_run_id nullable`
- `external_invoice_id nullable`
- `metadata_json nullable`
Add indexes:
- `(company_id, biller, occurred_at)`
- `(company_id, provider, occurred_at)`
- `(company_id, heartbeat_run_id)` if distinct-run reporting remains common
## Shared Contract Changes
### Shared types
Add a shared billing type union and enrich cost types with:
- `heartbeatRunId`
- `biller`
- `billingType`
- `cachedInputTokens`
Update reporting response types so the provider breakdown reflects the ledger directly rather than inferred run metadata.
### Validators
Extend `createCostEventSchema` to accept:
- `heartbeatRunId`
- `biller`
- `billingType`
- `cachedInputTokens`
Defaults:
- `biller` defaults to `provider`
- `billingType` defaults to `unknown`
- `cachedInputTokens` defaults to `0`
## Adapter Contract Changes
Extend adapter execution results so they can report:
- `biller`
- richer billing type values
Backwards compatibility:
- existing adapter values `api` and `subscription` are treated as legacy aliases
- map `api -> metered_api`
- map `subscription -> subscription_included`
Future adapters may emit the canonical values directly.
OpenRouter support will use:
- `provider` = upstream provider when known
- `biller` = `openrouter`
- `billingType` = `metered_api` unless OpenRouter later exposes another billing mode
Cloudflare Unified Billing support will use:
- `provider` = upstream provider when known
- `biller` = `cloudflare`
- `billingType` = `credits` or `metered_api` depending on the normalized request billing contract
Bedrock support will use:
- `provider` = upstream provider or `aws_bedrock` depending on adapter shape
- `biller` = `aws_bedrock`
- `billingType` = request-scoped mode for inference rows
- `finance_events` for provisioned, training, import, and storage charges
## Write Path Changes
### Heartbeat-created events
When a heartbeat run produces usage or spend:
1. normalize adapter billing metadata
2. write a ledger row to `cost_events`
3. attach `heartbeat_run_id`
4. set `provider`, `biller`, `billing_type`, token fields, and `cost_cents`
The write path should no longer depend on later inference from `heartbeat_runs`.
### Manual API-created events
Manual cost event creation remains supported.
These events may have `heartbeatRunId = null`.
Rules:
- `provider` remains required
- `biller` defaults to `provider`
- `billingType` defaults to `unknown`
## Reporting Changes
### Server
Refactor reporting queries to use `cost_events` only.
#### `summary`
- sum `cost_cents`
#### `by-agent`
- sum costs and token fields from `cost_events`
- use `count(distinct heartbeat_run_id)` filtered by billing type for run counts
- use token sums filtered by billing type for subscription usage
#### `by-provider`
- group by `provider`, `model`
- sum costs and token fields directly from the ledger
- derive billing-type slices from `cost_events.billing_type`
- never pro-rate from unrelated `heartbeat_runs`
#### future `by-biller`
- group by `biller`
- this is the right view for invoice and subscription accountability
#### `window-spend`
- continue to use `cost_events`
#### project attribution
Keep current project attribution logic for now, but prefer `cost_events.heartbeat_run_id` as the join anchor whenever possible.
## UI Changes
### Principles
- Spend, usage, and quota are related but distinct
- a missing quota fetch is not the same as “no quota”
- provider and biller are different dimensions
### Immediate UI changes
1. Keep the current costs page structure.
2. Make the provider cards accurate by reading only ledger-backed values.
3. Show provider quota fetch errors explicitly instead of dropping them.
### Follow-up UI direction
The long-term board UI should expose:
- Spend
Dollars by biller, provider, model, agent, project
- Usage
Tokens by provider, model, agent, project
- Quotas
Live provider or biller limits, credits, and reset windows
- Financial events
Credit purchases, top-ups, fees, refunds, commitments, storage, and other non-inference charges
## Migration Plan
Migration behavior:
- add new non-destructive columns with defaults
- backfill existing rows:
- `biller = provider`
- `billing_type = 'unknown'`
- `cached_input_tokens = 0`
- `heartbeat_run_id = null`
Do **not** attempt to backfill historical provider-level subscription attribution from `heartbeat_runs`.
That data was never stored with the required dimensions.
## Testing Plan
Add or update tests for:
1. heartbeat-created ledger rows persist `heartbeatRunId`, `biller`, `billingType`, and cached tokens
2. legacy adapter billing values map correctly
3. provider reporting uses ledger data only
4. mixed-provider companies do not cross-attribute subscription usage
5. zero-dollar subscription usage still appears in token reporting
6. quota fetch failures render explicit UI state
7. manual cost events still validate and write correctly
8. biller reporting keeps upstream provider breakdowns separate
9. OpenRouter-style rows can show `biller=openrouter` with non-OpenRouter upstream providers
10. Cloudflare-style rows can show `biller=cloudflare` with preserved upstream provider identity
11. future `finance_events` aggregation handles non-request charges without requiring a model or run id
## Delivery Plan
### Step 1
- land the ledger contract and query rewrite
- make the current costs page correct
### Step 2
- add biller-oriented reporting endpoints and UI
### Step 3
- wire OpenRouter and any future aggregator adapters to the same contract
### Step 4
- add `executionAdapterType` to persisted cost reporting if adapter-level grouping becomes a product requirement
### Step 5
- introduce `finance_events`
- add non-inference accounting endpoints
- add UI for platform/account charges alongside inference spend and usage
## Non-Goals For This Change
- multi-currency support
- invoice reconciliation
- provider-specific cost estimation beyond persisted billed cost
- replacing `heartbeat_runs` as the operational run record

View File

@@ -0,0 +1,611 @@
# Budget Policies and Enforcement
## Context
Paperclip already treats budgets as a core control-plane responsibility:
- `doc/SPEC.md` gives the Board authority to set budgets, pause agents, pause work, and override any budget.
- `doc/SPEC-implementation.md` says V1 must support monthly UTC budget windows, soft alerts, and hard auto-pause.
- the current code only partially implements that intent.
Today the system has narrow money-budget behavior:
- companies track `budgetMonthlyCents` and `spentMonthlyCents`
- agents track `budgetMonthlyCents` and `spentMonthlyCents`
- `cost_events` ingestion increments those counters
- when an agent exceeds its monthly budget, the agent is paused
That leaves major product gaps:
- no project budget model
- no approval generated when budget is hit
- no generic budget policy system
- no project pause semantics tied to budget
- no durable incident tracking to prevent duplicate alerts
- no separation between enforceable spend budgets and advisory usage quotas
This plan defines the concrete budgeting model Paperclip should implement next.
## Product Goals
Paperclip should let operators:
1. Set budgets on agents and projects.
2. Understand whether a budget is based on money or usage.
3. Be warned before a budget is exhausted.
4. Automatically pause work when a hard budget is hit.
5. Approve, raise, or resume from a budget stop using obvious UI.
6. See budget state on the dashboard, `/costs`, and scope detail pages.
The system should make one thing very clear:
- budgets are policy controls
- quotas are usage visibility
They are related, but they are not the same concept.
## Product Decisions
### V1 Budget Defaults
For the next implementation pass, Paperclip should enforce these defaults:
- agent budgets are recurring monthly budgets
- project budgets are lifetime total budgets
- hard-stop enforcement uses billed dollars, not tokens
- monthly windows use UTC calendar months
- project total budgets do not reset automatically
This gives a clean mental model:
- agents are ongoing workers, so monthly recurring budget is natural
- projects are bounded workstreams, so lifetime cap is natural
### Metric To Enforce First
The first enforceable metric should be `billed_cents`.
Reasoning:
- it works across providers, billers, and models
- it maps directly to real financial risk
- it handles overage and metered usage consistently
- it avoids cross-provider token normalization problems
- it applies cleanly even when future finance events are not token-based
Token budgets should not be the first hard-stop policy.
They should come later as advisory usage controls once the money-based system is solid.
### Subscription Usage Decision
Paperclip should separate subscription-included usage from billed spend:
- `subscription_included`
- visible in reporting
- visible in usage summaries
- does not count against money budget
- `subscription_overage`
- visible in reporting
- counts against money budget
- `metered_api`
- visible in reporting
- counts against money budget
This keeps the budget system honest:
- users should not see "spend" rise for usage that did not incur marginal billed cost
- users should still see the token usage and provider quota state
### Soft Alert Versus Hard Stop
Paperclip should have two threshold classes:
- soft alert
- creates visible notification state
- does not create an approval
- does not pause work
- hard stop
- pauses the affected scope automatically
- creates an approval requiring human resolution
- prevents additional heartbeats or task pickup in that scope
Default thresholds:
- soft alert at `80%`
- hard stop at `100%`
These should be configurable per policy later, but they are good defaults now.
## Scope Model
### Supported Scope Types
Budget policies should support:
- `company`
- `agent`
- `project`
This plan focuses on finishing `agent` and `project` first while preserving the existing company budget behavior.
### Recommended V1.5 Policy Presets
- Company
- metric: `billed_cents`
- window: `calendar_month_utc`
- Agent
- metric: `billed_cents`
- window: `calendar_month_utc`
- Project
- metric: `billed_cents`
- window: `lifetime`
Future extensions can add:
- token advisory policies
- daily or weekly spend windows
- provider- or biller-scoped budgets
- inherited delegated budgets down the org tree
## Current Implementation Baseline
The current codebase is not starting from zero, but the existing shape is too ad hoc to extend safely.
### What Exists Today
- company and agent monthly cents counters
- cost ingestion that updates those counters
- agent hard-stop pause on monthly budget overrun
### What Is Missing
- project budgets
- generic budget policy persistence
- generic threshold crossing detection
- incident deduplication per scope/window
- approval creation on hard-stop
- project execution blocking
- budget timeline and incident UI
- distinction between advisory quota and enforceable budget
## Proposed Data Model
### 1. `budget_policies`
Create a new table for canonical budget definitions.
Suggested fields:
- `id`
- `company_id`
- `scope_type`
- `scope_id`
- `metric`
- `window_kind`
- `amount`
- `warn_percent`
- `hard_stop_enabled`
- `notify_enabled`
- `is_active`
- `created_by_user_id`
- `updated_by_user_id`
- `created_at`
- `updated_at`
Notes:
- `scope_type` is one of `company | agent | project`
- `scope_id` is nullable only for company-level policy if company is implied; otherwise keep it explicit
- `metric` should start with `billed_cents`
- `window_kind` starts with `calendar_month_utc | lifetime`
- `amount` is stored in the natural unit of the metric
### 2. `budget_incidents`
Create a durable record of threshold crossings.
Suggested fields:
- `id`
- `company_id`
- `policy_id`
- `scope_type`
- `scope_id`
- `metric`
- `window_kind`
- `window_start`
- `window_end`
- `threshold_type`
- `amount_limit`
- `amount_observed`
- `status`
- `approval_id` nullable
- `activity_id` nullable
- `resolved_at` nullable
- `created_at`
- `updated_at`
Notes:
- `threshold_type`: `soft | hard`
- `status`: `open | acknowledged | resolved | dismissed`
- one open incident per policy per threshold per window prevents duplicate approvals and alert spam
### 3. Project Pause State
Projects need explicit pause semantics.
Recommended approach:
- extend project status or add a pause field so a project can be blocked by budget
- preserve whether the project is paused due to budget versus manually paused
Preferred shape:
- keep project workflow status as-is
- add execution-state fields:
- `execution_status`: `active | paused | archived`
- `pause_reason`: `manual | budget | system | null`
If that is too large for the immediate pass, a smaller version is:
- add `paused_at`
- add `pause_reason`
The key requirement is behavioral, not cosmetic:
Paperclip must know that a project is budget-paused and enforce it.
### 4. Compatibility With Existing Budget Columns
Existing company and agent monthly budget columns should remain temporarily for compatibility.
Migration plan:
1. keep reading existing columns during transition
2. create equivalent `budget_policies` rows
3. switch enforcement and UI to policies
4. later remove or deprecate legacy columns
## Budget Engine
Budget enforcement should move into a dedicated service.
Current logic is buried inside cost ingestion.
That is too narrow because budget checks must apply at more than one execution boundary.
### Responsibilities
New service: `budgetService`
Responsibilities:
- resolve applicable policies for a cost event
- compute current window totals
- detect threshold crossings
- create incidents, activities, and approvals
- pause affected scopes on hard-stop
- provide preflight enforcement checks for execution entry points
### Canonical Evaluation Flow
When a new `cost_event` is written:
1. persist the `cost_event`
2. identify affected scopes
- company
- agent
- project
3. fetch active policies for those scopes
4. compute current observed amount for each policy window
5. compare to thresholds
6. create soft incident if soft threshold crossed for first time in window
7. create hard incident if hard threshold crossed for first time in window
8. if hard incident:
- pause the scope
- create approval
- create activity event
- emit notification state
### Preflight Enforcement Checks
Budget enforcement cannot rely only on post-hoc cost ingestion.
Paperclip must also block execution before new work starts.
Add budget checks to:
- scheduler heartbeat dispatch
- manual invoke endpoints
- assignment-driven wakeups
- queued run promotion
- issue checkout or pickup paths where applicable
If a scope is budget-paused:
- do not start a new heartbeat
- do not let the agent pick up additional work
- present a clear reason in API and UI
### Active Run Behavior
When a hard-stop is triggered while a run is already active:
- mark scope paused immediately for future work
- request graceful cancellation of the current run
- allow normal cancellation timeout behavior
- write activity explaining that pause came from budget enforcement
This mirrors the general pause semantics already expected by the product.
## Approval Model
Budget hard-stops should create a first-class approval.
### New Approval Type
Add approval type:
- `budget_override_required`
Payload should include:
- `scopeType`
- `scopeId`
- `scopeName`
- `metric`
- `windowKind`
- `thresholdType`
- `budgetAmount`
- `observedAmount`
- `windowStart`
- `windowEnd`
- `topDrivers`
- `paused`
### Resolution Actions
The approval UI should support:
- raise budget and resume
- resume once without changing policy
- keep paused
Optional later action:
- disable budget policy
### Soft Alerts Do Not Need Approval
Soft alerts should create:
- activity event
- dashboard alert
- inbox notification or similar board-visible signal
They should not create an approval by default.
## Notification And Activity Model
Budget events need obvious operator visibility.
Required outputs:
- activity log entry on threshold crossings
- dashboard surface for active budget incidents
- detail page banner on paused agent or project
- `/costs` summary of active incidents and policy health
Later channels:
- email
- webhook
- Slack or other integrations
## API Plan
### Policy Management
Add routes for:
- list budget policies for company
- create budget policy
- update budget policy
- archive or disable budget policy
### Incident Surfaces
Add routes for:
- list active budget incidents
- list incident history
- get incident detail for a scope
### Approval Resolution
Budget approvals should use the existing approval system once the new approval type is added.
Expected flows:
- create approval on hard-stop
- resolve approval by changing policy and resuming
- resolve approval by resuming once
### Execution Errors
When work is blocked by budget, the API should return explicit errors.
Examples:
- agent invocation blocked because agent budget is paused
- issue execution blocked because project budget is paused
Do not silently no-op.
## UI Plan
Budgeting should be visible in the places where operators make decisions.
### `/costs`
Add a budget section that includes:
- active budget incidents
- policy list with scope, window, metric, and threshold state
- progress bars for current period or total
- clear distinction between:
- spend budget
- subscription quota
- quick actions:
- raise budget
- open approval
- resume scope if permitted
The page should make this visual distinction obvious:
- Budget
- enforceable spend policy
- Quota
- provider or subscription usage window
### Agent Detail
Add an agent budget card:
- monthly budget amount
- current month spend
- remaining spend
- status
- warning or paused banner
- link to approval if blocked
### Project Detail
Add a project budget card:
- total budget amount
- total spend to date
- remaining spend
- pause status
- approval link
Project detail should also show if issue execution is blocked because the project is budget-paused.
### Dashboard
Add a high-signal budget section:
- active budget breaches
- upcoming soft alerts
- counts of paused agents and paused projects due to budget
The operator should not have to visit `/costs` to learn that work has stopped.
## Budget Math
### What Counts Toward Budget
For V1.5 enforcement, include:
- `metered_api` cost events
- `subscription_overage` cost events
- any future request-scoped cost event with non-zero billed cents
Do not include:
- `subscription_included` cost events with zero billed cents
- advisory quota rows
- account-level finance events unless and until company-level financial budgets are added explicitly
### Why Not Tokens First
Token budgets should not be the first hard-stop because:
- providers count tokens differently
- cached tokens complicate simple totals
- some future charges are not token-based
- subscription tokens do not necessarily imply spend
- money remains the cleanest cross-provider enforcement metric
### Future Budget Metrics
Future policy metrics can include:
- `total_tokens`
- `input_tokens`
- `output_tokens`
- `requests`
- `finance_amount_cents`
But they should enter only after the money-budget path is stable.
## Migration Plan
### Phase 1: Foundation
- add `budget_policies`
- add `budget_incidents`
- add new approval type
- add project pause metadata
### Phase 2: Compatibility
- backfill policies from existing company and agent monthly budget columns
- keep legacy columns readable during migration
### Phase 3: Enforcement
- move budget logic into dedicated service
- add hard-stop incident creation
- add activity and approval creation
- add execution guards on heartbeat and invoke paths
### Phase 4: UI
- `/costs` budget section
- agent detail budget card
- project detail budget card
- dashboard incident summary
### Phase 5: Cleanup
- move all reads/writes to `budget_policies`
- reduce legacy column reliance
- decide whether to remove old budget columns
## Tests
Required coverage:
- agent monthly budget soft alert at 80%
- agent monthly budget hard-stop at 100%
- project lifetime budget soft alert
- project lifetime budget hard-stop
- `subscription_included` usage does not consume money budget
- `subscription_overage` does consume money budget
- hard-stop creates one incident per threshold per window
- hard-stop creates approval and pauses correct scope
- paused project blocks new issue execution
- paused agent blocks new heartbeat dispatch
- policy update and resume clears or resolves active incident correctly
- dashboard and `/costs` surface active incidents
## Open Questions
These should be explicitly deferred unless they block implementation:
- Should project budgets also support monthly mode, or is lifetime enough for the first release?
- Should company-level budgets eventually include `finance_events` such as OpenRouter top-up fees and Bedrock provisioned charges?
- Should delegated budget editing be limited by org hierarchy in V1, or remain board-only in the UI even if the data model can support delegation later?
- Do we need "resume once" immediately, or can first approval resolution be "raise budget and resume" plus "keep paused"?
## Recommendation
Implement the first coherent budgeting system with these rules:
- Agent budget = monthly billed dollars
- Project budget = lifetime billed dollars
- Hard-stop = auto-pause + approval
- Soft alert = visible warning, no approval
- Subscription usage = visible quota and token reporting, not money-budget enforcement
This solves the real operator problem without mixing together spend control, provider quota windows, and token accounting.

View File

@@ -0,0 +1,729 @@
# 2026-03-14 Skills UI Product Plan
Status: Proposed
Date: 2026-03-14
Audience: Product and engineering
Related:
- `doc/plans/2026-03-13-company-import-export-v2.md`
- `doc/plans/2026-03-14-adapter-skill-sync-rollout.md`
- `docs/companies/companies-spec.md`
- `ui/src/pages/AgentDetail.tsx`
## 1. Purpose
This document defines the product and UI plan for skill management in Paperclip.
The goal is to make skills understandable and manageable in the website without pretending that all adapters behave the same way.
This plan assumes:
- `SKILL.md` remains Agent Skills compatible
- `skills.sh` compatibility is a V1 requirement
- Paperclip company import/export can include skills as package content
- adapters may support persistent skill sync, ephemeral skill mounting, read-only skill discovery, or no skill integration at all
## 2. Current State
There is already a first-pass agent-level skill sync UI on `AgentDetail`.
Today it supports:
- loading adapter skill sync state
- showing unsupported adapters clearly
- showing managed skills as checkboxes
- showing external skills separately
- syncing desired skills for adapters that implement the new API
Current limitations:
1. There is no company-level skill library UI.
2. There is no package import flow for skills in the website.
3. There is no distinction between skill package management and per-agent skill attachment.
4. There is no multi-agent desired-vs-actual view.
5. The current UI is adapter-sync-oriented, not package-oriented.
6. Unsupported adapters degrade safely, but not elegantly.
## 2.1 V1 Decisions
For V1, this plan assumes the following product decisions are already made:
1. `skills.sh` compatibility is required.
2. Agent-to-skill association in `AGENTS.md` is by shortname or slug.
3. Company skills and agent skill attachments are separate concepts.
4. Agent skills should move to their own tab rather than living inside configuration.
5. Company import/export should eventually round-trip skill packages and agent skill attachments.
## 3. Product Principles
1. Skills are company assets first, agent attachments second.
2. Package management and adapter sync are different concerns and should not be conflated in one screen.
3. The UI must always tell the truth about what Paperclip knows:
- desired state in Paperclip
- actual state reported by the adapter
- whether the adapter can reconcile the two
4. Agent Skills compatibility must remain visible in the product model.
5. Agent-to-skill associations should be human-readable and shortname-based wherever possible.
6. Unsupported adapters should still have a useful UI, not just a dead end.
## 4. User Model
Paperclip should treat skills at two scopes:
### 4.1 Company skills
These are reusable skills known to the company.
Examples:
- imported from a GitHub repo
- added from a local folder
- installed from a `skills.sh`-compatible repo
- created locally inside Paperclip later
These should have:
- name
- description
- slug or package identity
- source/provenance
- trust level
- compatibility status
### 4.2 Agent skills
These are skill attachments for a specific agent.
Each attachment should have:
- shortname
- desired state in Paperclip
- actual state in the adapter when readable
- sync status
- origin
Agent attachments should normally reference skills by shortname or slug, for example:
- `review`
- `react-best-practices`
not by noisy relative file path.
## 4.3 Primary user jobs
The UI should support these jobs cleanly:
1. “Show me what skills this company has.”
2. “Import a skill from GitHub or a local folder.”
3. “See whether a skill is safe, compatible, and who uses it.”
4. “Attach skills to an agent.”
5. “See whether the adapter actually has those skills.”
6. “Reconcile desired vs actual skill state.”
7. “Understand what Paperclip knows vs what the adapter knows.”
## 5. Core UI Surfaces
The product should have two primary skill surfaces.
### 5.1 Company Skills page
Add a company-level page, likely:
- `/companies/:companyId/skills`
Purpose:
- manage the company skill library
- import and inspect skill packages
- understand provenance and trust
- see which agents use which skills
#### Route
- `/companies/:companyId/skills`
#### Primary actions
- import skill
- inspect skill
- attach to agents
- detach from agents
- export selected skills later
#### Empty state
When the company has no managed skills:
- explain what skills are
- explain `skills.sh` / Agent Skills compatibility
- offer `Import from GitHub` and `Import from folder`
- optionally show adapter-discovered skills as a secondary “not managed yet” section
#### A. Skill library list
Each skill row should show:
- name
- short description
- source badge
- trust badge
- compatibility badge
- number of attached agents
Suggested source states:
- local
- github
- imported package
- external reference
- adapter-discovered only
Suggested compatibility states:
- compatible
- paperclip-extension
- unknown
- invalid
Suggested trust states:
- markdown-only
- assets
- scripts/executables
Suggested list affordances:
- search by name or slug
- filter by source
- filter by trust level
- filter by usage
- sort by name, recent import, usage count
#### B. Import actions
Allow:
- import from local folder
- import from GitHub URL
- import from direct URL
Future:
- install from `companies.sh`
- install from `skills.sh`
V1 requirement:
- importing from a `skills.sh`-compatible source should work without requiring a Paperclip-specific package layout
#### C. Skill detail drawer or page
Each skill should have a detail view showing:
- rendered `SKILL.md`
- package source and pinning
- included files
- trust and licensing warnings
- who uses it
- adapter compatibility notes
Recommended route:
- `/companies/:companyId/skills/:skillId`
Recommended sections:
- Overview
- Contents
- Usage
- Source
- Trust / licensing
#### D. Usage view
Each company skill should show which agents use it.
Suggested columns:
- agent
- desired state
- actual state
- adapter
- sync mode
- last sync status
### 5.2 Agent Skills tab
Keep and evolve the existing `AgentDetail` skill sync UI, but move it out of configuration.
Purpose:
- attach/detach company skills to one agent
- inspect adapter reality for that agent
- reconcile desired vs actual state
- keep the association format readable and aligned with `AGENTS.md`
#### Route
- `/agents/:agentId/skills`
#### Agent tabs
The intended agent-level tab model becomes:
- `dashboard`
- `configuration`
- `skills`
- `runs`
This is preferable to hiding skills inside configuration because:
- skills are not just adapter config
- skills need their own sync/status language
- skills are a reusable company asset, not merely one agent field
- the screen needs room for desired vs actual state, warnings, and external skill adoption
#### Tab layout
The `Skills` tab should have three stacked sections:
1. Summary
2. Managed skills
3. External / discovered skills
Summary should show:
- adapter sync support
- sync mode
- number of managed skills
- number of external skills
- drift or warning count
#### A. Desired skills
Show company-managed skills attached to the agent.
Each row should show:
- skill name
- shortname
- sync state
- source
- last adapter observation if available
Each row should support:
- enable / disable
- open skill detail
- see source badge
- see sync badge
#### B. External or discovered skills
Show skills reported by the adapter that are not company-managed.
This matters because Codex and similar adapters may already have local skills that Paperclip did not install.
These should be clearly marked:
- external
- not managed by Paperclip
Each external row should support:
- inspect
- adopt into company library later
- attach as managed skill later if appropriate
#### C. Sync controls
Support:
- sync
- reset draft
- detach
Future:
- import external skill into company library
- promote ad hoc local skill into a managed company skill
Recommended footer actions:
- `Sync skills`
- `Reset`
- `Refresh adapter state`
## 6. Skill State Model In The UI
Each skill attachment should have a user-facing state.
Suggested states:
- `in_sync`
- `desired_only`
- `external`
- `drifted`
- `unmanaged`
- `unknown`
Definitions:
- `in_sync`: desired and actual match
- `desired_only`: Paperclip wants it, adapter does not show it yet
- `external`: adapter has it but Paperclip does not manage it
- `drifted`: adapter has a conflicting or unexpected version/location
- `unmanaged`: adapter does not support sync, Paperclip only tracks desired state
- `unknown`: adapter read failed or state cannot be trusted
Suggested badge copy:
- `In sync`
- `Needs sync`
- `External`
- `Drifted`
- `Unmanaged`
- `Unknown`
## 7. Adapter Presentation Rules
The UI should not describe all adapters the same way.
### 7.1 Persistent adapters
Example:
- Codex local
Language:
- installed
- synced into adapter home
- external skills detected
### 7.2 Ephemeral adapters
Example:
- Claude local
Language:
- will be mounted on next run
- effective runtime skills
- not globally installed
### 7.3 Unsupported adapters
Language:
- this adapter does not implement skill sync yet
- Paperclip can still track desired skills
- actual adapter state is unavailable
This state should still allow:
- attaching company skills to the agent as desired state
- export/import of those desired attachments
## 7.4 Read-only adapters
Some adapters may be able to list skills but not mutate them.
Language:
- Paperclip can see adapter skills
- this adapter does not support applying changes
- desired state can be tracked, but reconciliation is manual
## 8. Information Architecture
Recommended navigation:
- company nav adds `Skills`
- agent detail adds `Skills` as its own tab
- company skill detail gets its own route when the company library ships
Recommended separation:
- Company Skills page answers: “What skills do we have?”
- Agent Skills tab answers: “What does this agent use, and is it synced?”
## 8.1 Proposed route map
- `/companies/:companyId/skills`
- `/companies/:companyId/skills/:skillId`
- `/agents/:agentId/skills`
## 8.2 Nav and discovery
Recommended entry points:
- company sidebar: `Skills`
- agent page tabs: `Skills`
- company import preview: link imported skills to company skills page later
- agent skills rows: link to company skill detail
## 9. Import / Export Integration
Skill UI and package portability should meet in the company skill library.
Import behavior:
- importing a company package with `SKILL.md` content should create or update company skills
- agent attachments should primarily come from `AGENTS.md` shortname associations
- `.paperclip.yaml` may add Paperclip-specific fidelity, but should not replace the base shortname association model
- referenced third-party skills should keep provenance visible
Export behavior:
- exporting a company should include company-managed skills when selected
- `AGENTS.md` should emit skill associations by shortname or slug
- `.paperclip.yaml` may add Paperclip-specific skill fidelity later if needed, but should not be required for ordinary agent-to-skill association
- adapter-only external skills should not be silently exported as managed company skills
## 9.1 Import workflows
V1 workflows should support:
1. import one or more skills from a local folder
2. import one or more skills from a GitHub repo
3. import a company package that contains skills
4. attach imported skills to one or more agents
Import preview for skills should show:
- skills discovered
- source and pinning
- trust level
- licensing warnings
- whether an existing company skill will be created, updated, or skipped
## 9.2 Export workflows
V1 should support:
1. export a company with managed skills included when selected
2. export an agent whose `AGENTS.md` contains shortname skill associations
3. preserve Agent Skills compatibility for each `SKILL.md`
Out of scope for V1:
- exporting adapter-only external skills as managed packages automatically
## 10. Data And API Shape
This plan implies a clean split in backend concepts.
### 10.1 Company skill records
Paperclip should have a company-scoped skill model or managed package model representing:
- identity
- source
- files
- provenance
- trust and licensing metadata
### 10.2 Agent skill attachments
Paperclip should separately store:
- agent id
- skill identity
- desired enabled state
- optional ordering or metadata later
### 10.3 Adapter sync snapshot
Adapter reads should return:
- supported flag
- sync mode
- entries
- warnings
- desired skills
This already exists in rough form and should be the basis for the UI.
### 10.4 UI-facing API needs
The complete UI implies these API surfaces:
- list company-managed skills
- import company skills from path/URL/GitHub
- get one company skill detail
- list agents using a given skill
- attach/detach company skills for an agent
- list adapter sync snapshot for an agent
- apply desired skills for an agent
Existing agent-level skill sync APIs can remain the base for the agent tab.
The company-level library APIs still need to be designed and implemented.
## 11. Page-by-page UX
### 11.1 Company Skills list page
Header:
- title
- short explanation of compatibility with Agent Skills / `skills.sh`
- import button
Body:
- filters
- skill table or cards
- empty state when none
Secondary content:
- warnings panel for untrusted or incompatible skills
### 11.2 Company Skill detail page
Header:
- skill name
- shortname
- source badge
- trust badge
- compatibility badge
Sections:
- rendered `SKILL.md`
- files and references
- usage by agents
- source / provenance
- trust and licensing warnings
Actions:
- attach to agent
- remove from company library later
- export later
### 11.3 Agent Skills tab
Header:
- adapter support summary
- sync mode
- refresh and sync actions
Body:
- managed skills list
- external/discovered skills list
- warnings / unsupported state block
## 12. States And Empty Cases
### 12.1 Company Skills page
States:
- empty
- loading
- loaded
- import in progress
- import failed
### 12.2 Company Skill detail
States:
- loading
- not found
- incompatible
- loaded
### 12.3 Agent Skills tab
States:
- loading snapshot
- unsupported adapter
- read-only adapter
- sync-capable adapter
- sync failed
- stale draft
## 13. Permissions And Governance
Suggested V1 policy:
- board users can manage company skills
- board users can attach skills to agents
- agents themselves do not mutate company skill library by default
- later, certain agents may get scoped permissions for skill attachment or sync
## 14. UI Phases
### Phase A: Stabilize current agent skill sync UI
Goals:
- move skills to an `AgentDetail` tab
- improve status language
- support desired-only state even on unsupported adapters
- polish copy for persistent vs ephemeral adapters
### Phase B: Add Company Skills page
Goals:
- company-level skill library
- import from GitHub/local folder
- basic detail view
- usage counts by agent
- `skills.sh`-compatible import path
### Phase C: Connect skills to portability
Goals:
- importing company packages creates company skills
- exporting selected skills works cleanly
- agent attachments round-trip primarily through `AGENTS.md` shortnames
### Phase D: External skill adoption flow
Goals:
- detect adapter external skills
- allow importing them into company-managed state where possible
- make provenance explicit
### Phase E: Advanced sync and drift UX
Goals:
- desired-vs-actual diffing
- drift resolution actions
- multi-agent skill usage and sync reporting
## 15. Design Risks
1. Overloading the agent page with package management will make the feature confusing.
2. Treating unsupported adapters as broken rather than unmanaged will make the product feel inconsistent.
3. Mixing external adapter-discovered skills with company-managed skills without clear labels will erode trust.
4. If company skill records do not exist, import/export and UI will remain loosely coupled and round-trip fidelity will stay weak.
5. If agent skill associations are path-based instead of shortname-based, the format will feel too technical and too Paperclip-specific.
## 16. Recommendation
The next product step should be:
1. move skills out of agent configuration and into a dedicated `Skills` tab
2. add a dedicated company-level `Skills` page as the library and package-management surface
3. make company import/export target that company skill library, not the agent page directly
4. preserve adapter-aware truth in the UI by clearly separating:
- desired
- actual
- external
- unmanaged
5. keep agent-to-skill associations shortname-based in `AGENTS.md`
That gives Paperclip one coherent skill story instead of forcing package management, adapter sync, and agent configuration into the same screen.

View File

@@ -0,0 +1,424 @@
# Docker Release Browser E2E Plan
## Context
Today release smoke testing for published Paperclip packages is manual and shell-driven:
```sh
HOST_PORT=3232 DATA_DIR=./data/release-smoke-canary PAPERCLIPAI_VERSION=canary ./scripts/docker-onboard-smoke.sh
HOST_PORT=3233 DATA_DIR=./data/release-smoke-stable PAPERCLIPAI_VERSION=latest ./scripts/docker-onboard-smoke.sh
```
That is useful because it exercises the same public install surface users hit:
- Docker
- `npx paperclipai@canary`
- `npx paperclipai@latest`
- authenticated bootstrap flow
But it still leaves the most important release questions to a human with a browser:
- can I sign in with the smoke credentials?
- do I land in onboarding?
- can I complete onboarding?
- does the initial CEO agent actually get created and run?
The repo already has two adjacent pieces:
- `tests/e2e/onboarding.spec.ts` covers the onboarding wizard against the local source tree
- `scripts/docker-onboard-smoke.sh` boots a published Docker install and auto-bootstraps authenticated mode, but only verifies the API/session layer
What is missing is one deterministic browser test that joins those two paths.
## Goal
Add a release-grade Docker-backed browser E2E that validates the published `canary` and `latest` installs end to end:
1. boot the published package in Docker
2. sign in with known smoke credentials
3. verify the user is routed into onboarding
4. complete onboarding in the browser
5. verify the first CEO agent exists
6. verify the initial CEO run was triggered and reached a terminal or active state
Then wire that test into GitHub Actions so release validation is no longer manual-only.
## Recommendation In One Sentence
Turn the current Docker smoke script into a machine-friendly test harness, add a dedicated Playwright release-smoke spec that drives the authenticated browser flow against published Docker installs, and run it in GitHub Actions for both `canary` and `latest`.
## What We Have Today
### Existing local browser coverage
`tests/e2e/onboarding.spec.ts` already proves the onboarding wizard can:
- create a company
- create a CEO agent
- create an initial issue
- optionally observe task progress
That is a good base, but it does not validate the public npm package, Docker path, authenticated login flow, or release dist-tags.
### Existing Docker smoke coverage
`scripts/docker-onboard-smoke.sh` already does useful setup work:
- builds `Dockerfile.onboard-smoke`
- runs `paperclipai@${PAPERCLIPAI_VERSION}` inside Docker
- waits for health
- signs up or signs in a smoke admin user
- generates and accepts the bootstrap CEO invite in authenticated mode
- verifies a board session and `/api/companies`
That means the hard bootstrap problem is mostly solved already. The main gap is that the script is human-oriented and never hands control to a browser test.
### Existing CI shape
The repo already has:
- `.github/workflows/e2e.yml` for manual Playwright runs against local source
- `.github/workflows/release.yml` for canary publish on `master` and manual stable promotion
So the right move is to extend the current test/release system, not create a parallel one.
## Product Decision
### 1. The release smoke should stay deterministic and token-free
The first version should not require OpenAI, Anthropic, or external agent credentials.
Use the onboarding flow with a deterministic adapter that can run on a stock GitHub runner and inside the published Docker install. The existing `process` adapter with a trivial command is the right base path for this release gate.
That keeps this test focused on:
- release packaging
- auth/bootstrap
- UI routing
- onboarding contract
- agent creation
- heartbeat invocation plumbing
Later we can add a second credentialed smoke lane for real model-backed agents.
### 2. Smoke credentials become an explicit test contract
The current defaults in `scripts/docker-onboard-smoke.sh` should be treated as stable test fixtures:
- email: `smoke-admin@paperclip.local`
- password: `paperclip-smoke-password`
The browser test should log in with those exact values unless overridden by env vars.
### 3. Published-package smoke and source-tree E2E stay separate
Keep two lanes:
- source-tree E2E for feature development
- published Docker release smoke for release confidence
They overlap on onboarding assertions, but they guard different failure classes.
## Proposed Design
## 1. Add a CI-friendly Docker smoke harness
Refactor `scripts/docker-onboard-smoke.sh` so it can run in two modes:
- interactive mode
- current behavior
- streams logs and waits in foreground for manual inspection
- CI mode
- starts the container
- waits for health and authenticated bootstrap
- prints machine-readable metadata
- exits while leaving the container running for Playwright
Recommended shape:
- keep `scripts/docker-onboard-smoke.sh` as the public entry point
- add a `SMOKE_DETACH=true` or `--detach` mode
- emit a JSON blob or `.env` file containing:
- `SMOKE_BASE_URL`
- `SMOKE_ADMIN_EMAIL`
- `SMOKE_ADMIN_PASSWORD`
- `SMOKE_CONTAINER_NAME`
- `SMOKE_DATA_DIR`
The workflow and Playwright tests can then consume the emitted metadata instead of scraping logs.
### Why this matters
The current script always tails logs and then blocks on `wait "$LOG_PID"`. That is convenient for manual smoke testing, but it is the wrong shape for CI orchestration.
## 2. Add a dedicated Playwright release-smoke spec
Create a second Playwright entry point specifically for published Docker installs, for example:
- `tests/release-smoke/playwright.config.ts`
- `tests/release-smoke/docker-auth-onboarding.spec.ts`
This suite should not use Playwright `webServer`, because the app server will already be running inside Docker.
### Browser scenario
The first release-smoke scenario should validate:
1. open `/`
2. unauthenticated user is redirected to `/auth`
3. sign in using the smoke credentials
4. authenticated user lands on onboarding when no companies exist
5. onboarding wizard appears with the expected step labels
6. create a company
7. create the first agent using `process`
8. create the initial issue
9. finish onboarding and open the created issue
10. verify via API:
- company exists
- CEO agent exists
- issue exists and is assigned to the CEO
11. verify the first heartbeat run was triggered:
- either by checking issue status changed from initial state, or
- by checking agent/runs API shows a run for the CEO, or
- both
The test should tolerate the run completing quickly. For this reason, the assertion should accept:
- `queued`
- `running`
- `succeeded`
and similarly for issue progression if the issue status changes before the assertion runs.
### Why a separate spec instead of reusing `tests/e2e/onboarding.spec.ts`
The local-source test and release-smoke test have different assumptions:
- different server lifecycle
- different auth path
- different deployment mode
- published npm package instead of local workspace code
Trying to force both through one spec will make both worse.
## 3. Add a release-smoke workflow in GitHub Actions
Add a workflow dedicated to this surface, ideally reusable:
- `.github/workflows/release-smoke.yml`
Recommended triggers:
- `workflow_dispatch`
- `workflow_call`
Recommended inputs:
- `paperclip_version`
- `canary` or `latest`
- `host_port`
- optional, default runner-safe port
- `artifact_name`
- optional for clearer uploads
### Job outline
1. checkout repo
2. install Node/pnpm
3. install Playwright browser dependencies
4. launch Docker smoke harness in detached mode with the chosen dist-tag
5. run the release-smoke Playwright suite against the returned base URL
6. always collect diagnostics:
- Playwright report
- screenshots
- trace
- `docker logs`
- harness metadata file
7. stop and remove container
### Why a reusable workflow
This lets us:
- run the smoke manually on demand
- call it from `release.yml`
- reuse the same job for both `canary` and `latest`
## 4. Integrate it into release automation incrementally
### Phase A: Manual workflow only
First ship the workflow as manual-only so the harness and test can be stabilized without blocking releases.
### Phase B: Run automatically after canary publish
After `publish_canary` succeeds in `.github/workflows/release.yml`, call the reusable release-smoke workflow with:
- `paperclip_version=canary`
This proves the just-published public canary really boots and onboards.
### Phase C: Run automatically after stable publish
After `publish_stable` succeeds, call the same workflow with:
- `paperclip_version=latest`
This gives us post-publish confirmation that the stable dist-tag is healthy.
### Important nuance
Testing `latest` from npm cannot happen before stable publish, because the package under test does not exist under `latest` yet. So the `latest` smoke is a post-publish verification, not a pre-publish gate.
If we later want a true pre-publish stable gate, that should be a separate source-ref or locally built package smoke job.
## 5. Make diagnostics first-class
This workflow is only valuable if failures are fast to debug.
Always capture:
- Playwright HTML report
- Playwright trace on failure
- final screenshot on failure
- full `docker logs` output
- emitted smoke metadata
- optional `curl /api/health` snapshot
Without that, the test will become a flaky black box and people will stop trusting it.
## Implementation Plan
## Phase 1: Harness refactor
Files:
- `scripts/docker-onboard-smoke.sh`
- optionally `scripts/lib/docker-onboard-smoke.sh` or similar helper
- `doc/DOCKER.md`
- `doc/RELEASING.md`
Tasks:
1. Add detached/CI mode to the Docker smoke script.
2. Make the script emit machine-readable connection metadata.
3. Keep the current interactive manual mode intact.
4. Add reliable cleanup commands for CI.
Acceptance:
- a script invocation can start the published Docker app, auto-bootstrap it, and return control to the caller with enough metadata for browser automation
## Phase 2: Browser release-smoke suite
Files:
- `tests/release-smoke/playwright.config.ts`
- `tests/release-smoke/docker-auth-onboarding.spec.ts`
- root `package.json`
Tasks:
1. Add a dedicated Playwright config for external server testing.
2. Implement login + onboarding + CEO creation flow.
3. Assert a CEO run was created or completed.
4. Add a root script such as:
- `test:release-smoke`
Acceptance:
- the suite passes locally against both:
- `PAPERCLIPAI_VERSION=canary`
- `PAPERCLIPAI_VERSION=latest`
## Phase 3: GitHub Actions workflow
Files:
- `.github/workflows/release-smoke.yml`
Tasks:
1. Add manual and reusable workflow entry points.
2. Install Chromium and runner dependencies.
3. Start Docker smoke in detached mode.
4. Run the release-smoke Playwright suite.
5. Upload diagnostics artifacts.
Acceptance:
- a maintainer can run the workflow manually for either `canary` or `latest`
## Phase 4: Release workflow integration
Files:
- `.github/workflows/release.yml`
- `doc/RELEASING.md`
Tasks:
1. Trigger release smoke automatically after canary publish.
2. Trigger release smoke automatically after stable publish.
3. Document expected behavior and failure handling.
Acceptance:
- canary releases automatically produce a published-package browser smoke result
- stable releases automatically produce a `latest` browser smoke result
## Phase 5: Future extension for real model-backed agent validation
Not part of the first implementation, but this should be the next layer after the deterministic lane is stable.
Possible additions:
- a second Playwright project gated on repo secrets
- real `claude_local` or `codex_local` adapter validation in Docker-capable environments
- assertion that the CEO posts a real task/comment artifact
- stable release holdback until the credentialed lane passes
This should stay optional until the token-free lane is trustworthy.
## Acceptance Criteria
The plan is complete when the implemented system can demonstrate all of the following:
1. A published `paperclipai@canary` Docker install can be smoke-tested by Playwright in CI.
2. A published `paperclipai@latest` Docker install can be smoke-tested by Playwright in CI.
3. The test logs into authenticated mode with the smoke credentials.
4. The test sees onboarding for a fresh instance.
5. The test completes onboarding in the browser.
6. The test verifies the initial CEO agent was created.
7. The test verifies at least one CEO heartbeat run was triggered.
8. Failures produce actionable artifacts rather than just a red job.
## Risks And Decisions To Make
### 1. Fast process runs may finish before the UI visibly updates
That is expected. The assertions should prefer API polling for run existence/status rather than only visual indicators.
### 2. `latest` smoke is post-publish, not preventive
This is a real limitation of testing the published dist-tag itself. It is still valuable, but it should not be confused with a pre-publish gate.
### 3. We should not overcouple the test to cosmetic onboarding text
The important contract is flow success, created entities, and run creation. Use visible labels sparingly and prefer stable semantic selectors where possible.
### 4. Keep the smoke adapter path boring
For release safety, the first test should use the most boring runnable adapter possible. This is not the place to validate every adapter.
## Recommended First Slice
If we want the fastest path to value, ship this in order:
1. add detached mode to `scripts/docker-onboard-smoke.sh`
2. add one Playwright spec for authenticated login + onboarding + CEO run verification
3. add manual `release-smoke.yml`
4. once stable, wire canary into `release.yml`
5. after that, wire stable `latest` smoke into `release.yml`
That gives release confidence quickly without turning the first version into a large CI redesign.

View File

@@ -0,0 +1,426 @@
# Paperclip Memory Service Plan
## Goal
Define a Paperclip memory service and surface API that can sit above multiple memory backends, while preserving Paperclip's control-plane requirements:
- company scoping
- auditability
- provenance back to Paperclip work objects
- budget / cost visibility
- plugin-first extensibility
This plan is based on the external landscape summarized in `doc/memory-landscape.md` and on the current Paperclip architecture in:
- `doc/SPEC-implementation.md`
- `doc/plugins/PLUGIN_SPEC.md`
- `doc/plugins/PLUGIN_AUTHORING_GUIDE.md`
- `packages/plugins/sdk/src/types.ts`
## Recommendation In One Sentence
Paperclip should not embed one opinionated memory engine into core. It should add a company-scoped memory control plane with a small normalized adapter contract, then let built-ins and plugins implement the provider-specific behavior.
## Product Decisions
### 1. Memory is company-scoped by default
Every memory binding belongs to exactly one company.
That binding can then be:
- the company default
- an agent override
- a project override later if we need it
No cross-company memory sharing in the initial design.
### 2. Providers are selected by key
Each configured memory provider gets a stable key inside a company, for example:
- `default`
- `mem0-prod`
- `local-markdown`
- `research-kb`
Agents and services resolve the active provider by key, not by hard-coded vendor logic.
### 3. Plugins are the primary provider path
Built-ins are useful for a zero-config local path, but most providers should arrive through the existing Paperclip plugin runtime.
That keeps the core small and matches the current direction that optional knowledge-like systems live at the edges.
### 4. Paperclip owns routing, provenance, and accounting
Providers should not decide how Paperclip entities map to governance.
Paperclip core should own:
- who is allowed to call a memory operation
- which company / agent / project scope is active
- what issue / run / comment / document the operation belongs to
- how usage gets recorded
### 5. Automatic memory should be narrow at first
Automatic capture is useful, but broad silent capture is dangerous.
Initial automatic hooks should be:
- post-run capture from agent runs
- issue comment / document capture when the binding enables it
- pre-run recall for agent context hydration
Everything else should start explicit.
## Proposed Concepts
### Memory provider
A built-in or plugin-supplied implementation that stores and retrieves memory.
Examples:
- local markdown + vector index
- mem0 adapter
- supermemory adapter
- MemOS adapter
### Memory binding
A company-scoped configuration record that points to a provider and carries provider-specific config.
This is the object selected by key.
### Memory scope
The normalized Paperclip scope passed into a provider request.
At minimum:
- `companyId`
- optional `agentId`
- optional `projectId`
- optional `issueId`
- optional `runId`
- optional `subjectId` for external/user identity
### Memory source reference
The provenance handle that explains where a memory came from.
Supported source kinds should include:
- `issue_comment`
- `issue_document`
- `issue`
- `run`
- `activity`
- `manual_note`
- `external_document`
### Memory operation
A normalized write, query, browse, or delete action performed through Paperclip.
Paperclip should log every operation, whether the provider is local or external.
## Required Adapter Contract
The required core should be small enough to fit `memsearch`, `mem0`, `Memori`, `MemOS`, or `OpenViking`.
```ts
export interface MemoryAdapterCapabilities {
profile?: boolean;
browse?: boolean;
correction?: boolean;
asyncIngestion?: boolean;
multimodal?: boolean;
providerManagedExtraction?: boolean;
}
export interface MemoryScope {
companyId: string;
agentId?: string;
projectId?: string;
issueId?: string;
runId?: string;
subjectId?: string;
}
export interface MemorySourceRef {
kind:
| "issue_comment"
| "issue_document"
| "issue"
| "run"
| "activity"
| "manual_note"
| "external_document";
companyId: string;
issueId?: string;
commentId?: string;
documentKey?: string;
runId?: string;
activityId?: string;
externalRef?: string;
}
export interface MemoryUsage {
provider: string;
model?: string;
inputTokens?: number;
outputTokens?: number;
embeddingTokens?: number;
costCents?: number;
latencyMs?: number;
details?: Record<string, unknown>;
}
export interface MemoryWriteRequest {
bindingKey: string;
scope: MemoryScope;
source: MemorySourceRef;
content: string;
metadata?: Record<string, unknown>;
mode?: "append" | "upsert" | "summarize";
}
export interface MemoryRecordHandle {
providerKey: string;
providerRecordId: string;
}
export interface MemoryQueryRequest {
bindingKey: string;
scope: MemoryScope;
query: string;
topK?: number;
intent?: "agent_preamble" | "answer" | "browse";
metadataFilter?: Record<string, unknown>;
}
export interface MemorySnippet {
handle: MemoryRecordHandle;
text: string;
score?: number;
summary?: string;
source?: MemorySourceRef;
metadata?: Record<string, unknown>;
}
export interface MemoryContextBundle {
snippets: MemorySnippet[];
profileSummary?: string;
usage?: MemoryUsage[];
}
export interface MemoryAdapter {
key: string;
capabilities: MemoryAdapterCapabilities;
write(req: MemoryWriteRequest): Promise<{
records?: MemoryRecordHandle[];
usage?: MemoryUsage[];
}>;
query(req: MemoryQueryRequest): Promise<MemoryContextBundle>;
get(handle: MemoryRecordHandle, scope: MemoryScope): Promise<MemorySnippet | null>;
forget(handles: MemoryRecordHandle[], scope: MemoryScope): Promise<{ usage?: MemoryUsage[] }>;
}
```
This contract intentionally does not force a provider to expose its internal graph, filesystem, or ontology.
## Optional Adapter Surfaces
These should be capability-gated, not required:
- `browse(scope, filters)` for file-system / graph / timeline inspection
- `correct(handle, patch)` for natural-language correction flows
- `profile(scope)` when the provider can synthesize stable preferences or summaries
- `sync(source)` for connectors or background ingestion
- `explain(queryResult)` for providers that can expose retrieval traces
## What Paperclip Should Persist
Paperclip should not mirror the full provider memory corpus into Postgres unless the provider is a Paperclip-managed local provider.
Paperclip core should persist:
- memory bindings and overrides
- provider keys and capability metadata
- normalized memory operation logs
- provider record handles returned by operations when available
- source references back to issue comments, documents, runs, and activity
- usage and cost data
For external providers, the memory payload itself can remain in the provider.
## Hook Model
### Automatic hooks
These should be low-risk and easy to reason about:
1. `pre-run hydrate`
Before an agent run starts, Paperclip may call `query(... intent = "agent_preamble")` using the active binding.
2. `post-run capture`
After a run finishes, Paperclip may write a summary or transcript-derived note tied to the run.
3. `issue comment / document capture`
When enabled on the binding, Paperclip may capture selected issue comments or issue documents as memory sources.
### Explicit hooks
These should be tool- or UI-driven first:
- `memory.search`
- `memory.note`
- `memory.forget`
- `memory.correct`
- `memory.browse`
### Not automatic in the first version
- broad web crawling
- silent import of arbitrary repo files
- cross-company memory sharing
- automatic destructive deletion
- provider migration between bindings
## Agent UX Rules
Paperclip should give agents both automatic recall and explicit tools, with simple guidance:
- use `memory.search` when the task depends on prior decisions, people, projects, or long-running context that is not in the current issue thread
- use `memory.note` when a durable fact, preference, or decision should survive this run
- use `memory.correct` when the user explicitly says prior context is wrong
- rely on post-run auto-capture for ordinary session residue so agents do not have to write memory notes for every trivial exchange
This keeps memory available without forcing every agent prompt to become a memory-management protocol.
## Browse And Inspect Surface
Paperclip needs a first-class UI for memory, otherwise providers become black boxes.
The initial browse surface should support:
- active binding by company and agent
- recent memory operations
- recent write sources
- query results with source backlinks
- filters by agent, issue, run, source kind, and date
- provider usage / cost / latency summaries
When a provider supports richer browsing, the plugin can add deeper views through the existing plugin UI surfaces.
## Cost And Evaluation
Every adapter response should be able to return usage records.
Paperclip should roll up:
- memory inference tokens
- embedding tokens
- external provider cost
- latency
- query count
- write count
It should also record evaluation-oriented metrics where possible:
- recall hit rate
- empty query rate
- manual correction count
- per-binding success / failure counts
This is important because a memory system that "works" but silently burns budget is not acceptable in Paperclip.
## Suggested Data Model Additions
At the control-plane level, the likely new core tables are:
- `memory_bindings`
- company-scoped key
- provider id / plugin id
- config blob
- enabled status
- `memory_binding_targets`
- target type (`company`, `agent`, later `project`)
- target id
- binding id
- `memory_operations`
- company id
- binding id
- operation type (`write`, `query`, `forget`, `browse`, `correct`)
- scope fields
- source refs
- usage / latency / cost
- success / error
Provider-specific long-form state should stay in plugin state or the provider itself unless a built-in local provider needs its own schema.
## Recommended First Built-In
The best zero-config built-in is a local markdown-first provider with optional semantic indexing.
Why:
- it matches Paperclip's local-first posture
- it is inspectable
- it is easy to back up and debug
- it gives the system a baseline even without external API keys
The design should still treat that built-in as just another provider behind the same control-plane contract.
## Rollout Phases
### Phase 1: Control-plane contract
- add memory binding models and API types
- add plugin capability / registration surface for memory providers
- add operation logging and usage reporting
### Phase 2: One built-in + one plugin example
- ship a local markdown-first provider
- ship one hosted adapter example to validate the external-provider path
### Phase 3: UI inspection
- add company / agent memory settings
- add a memory operation explorer
- add source backlinks to issues and runs
### Phase 4: Automatic hooks
- pre-run hydrate
- post-run capture
- selected issue comment / document capture
### Phase 5: Rich capabilities
- correction flows
- provider-native browse / graph views
- project-level overrides if needed
- evaluation dashboards
## Open Questions
- Should project overrides exist in V1 of the memory service, or should we force company default + agent override first?
- Do we want Paperclip-managed extraction pipelines at all, or should built-ins be the only place where Paperclip owns extraction?
- Should memory usage extend the current `cost_events` model directly, or should memory operations keep a parallel usage log and roll up into `cost_events` secondarily?
- Do we want provider install / binding changes to require approvals for some companies?
## Bottom Line
The right abstraction is:
- Paperclip owns memory bindings, scopes, provenance, governance, and usage reporting.
- Providers own extraction, ranking, storage, and provider-native memory semantics.
That gives Paperclip a stable "memory service" without locking the product to one memory philosophy or one vendor.

View File

@@ -0,0 +1,488 @@
# Release Automation and Versioning Simplification Plan
## Context
Paperclip's current release flow is documented in `doc/RELEASING.md` and implemented through:
- `.github/workflows/release.yml`
- `scripts/release-lib.sh`
- `scripts/release-start.sh`
- `scripts/release-preflight.sh`
- `scripts/release.sh`
- `scripts/create-github-release.sh`
Today the model is:
1. pick `patch`, `minor`, or `major`
2. create `release/X.Y.Z`
3. draft `releases/vX.Y.Z.md`
4. publish one or more canaries from that release branch
5. publish stable from that same branch
6. push tag + create GitHub Release
7. merge the release branch back to `master`
That is workable, but it creates friction in exactly the places that should be cheap:
- deciding `patch` vs `minor` vs `major`
- cutting and carrying release branches
- manually publishing canaries
- thinking about changelog generation for canaries
- handling npm credentials safely in a public repo
The target state from this discussion is simpler:
- every push to `master` publishes a canary automatically
- stable releases are promoted deliberately from a vetted commit
- versioning is date-driven instead of semantics-driven
- stable publishing is secure even in a public open-source repository
- changelog generation happens only for real stable releases
## Recommendation In One Sentence
Move Paperclip to semver-compatible calendar versioning, auto-publish canaries from `master`, promote stable from a chosen tested commit, and use npm trusted publishing plus GitHub environments so no long-lived npm or LLM token needs to live in Actions.
## Core Decisions
### 1. Use calendar versions, but keep semver syntax
The repo and npm tooling still assume semver-shaped version strings in many places. That does not mean Paperclip must keep semver as a product policy. It does mean the version format should remain semver-valid.
Recommended format:
- stable: `YYYY.MDD.P`
- canary: `YYYY.MDD.P-canary.N`
Examples:
- first stable on March 17, 2026: `2026.317.0`
- third canary on the `2026.317.0` line: `2026.317.0-canary.2`
Why this shape:
- it removes `patch/minor/major` decisions
- it is valid semver syntax
- it stays compatible with npm, dist-tags, and existing semver validators
- it is close to the format you actually want
Important constraints:
- the middle numeric slot should be `MDD`, where `M` is the month and `DD` is the zero-padded day
- `2026.03.17` is not the format to use
- numeric semver identifiers do not allow leading zeroes
- `2026.3.17.1` is not the format to use
- semver has three numeric components, not four
- the practical semver-safe equivalent is `2026.317.0-canary.8`
This is effectively CalVer on semver rails.
### 2. Accept that CalVer changes the compatibility contract
This is not semver in spirit anymore. It is semver in syntax only.
That tradeoff is probably acceptable for Paperclip, but it should be explicit:
- consumers no longer infer compatibility from `major/minor/patch`
- release notes become the compatibility signal
- downstream users should prefer exact pins or deliberate upgrades
This is especially relevant for public library packages like `@paperclipai/shared`, `@paperclipai/db`, and the adapter packages.
### 3. Drop release branches for normal publishing
If every merge to `master` publishes a canary, the current `release/X.Y.Z` train model becomes more ceremony than value.
Recommended replacement:
- `master` is the only canary train
- every push to `master` can publish a canary
- stable is published from a chosen commit or canary tag on `master`
This matches the workflow you actually want:
- merge continuously
- let npm always have a fresh canary
- choose a known-good canary later and promote that commit to stable
### 4. Promote by source ref, not by "renaming" a canary
This is the most important mechanical constraint.
npm can move dist-tags, but it does not let you rename an already-published version. That means:
- you can move `latest` to `paperclipai@1.2.3`
- you cannot turn `paperclipai@2026.317.0-canary.8` into `paperclipai@2026.317.0`
So "promote canary to stable" really means:
1. choose the commit or canary tag you trust
2. rebuild from that exact commit
3. publish it again with the stable version string
Because of that, the stable workflow should take a source ref, not just a bump type.
Recommended stable input:
- `source_ref`
- commit SHA, or
- a canary git tag such as `canary/v2026.317.1-canary.8`
### 5. Only stable releases get release notes, tags, and GitHub Releases
Canaries should stay lightweight:
- publish to npm under `canary`
- optionally create a lightweight or annotated git tag
- do not create GitHub Releases
- do not require `releases/v*.md`
- do not spend LLM tokens
Stable releases should remain the public narrative surface:
- git tag `v2026.317.0`
- GitHub Release `v2026.317.0`
- stable changelog file `releases/v2026.317.0.md`
## Security Model
### Recommendation
Use npm trusted publishing with GitHub Actions OIDC, then disable token-based publishing access for the packages.
Why:
- no long-lived `NPM_TOKEN` in repo or org secrets
- no personal npm token in Actions
- short-lived credentials minted only for the authorized workflow
- automatic npm provenance for public packages in public repos
This is the cleanest answer to the open-repo security concern.
### Concrete controls
#### 1. Use one release workflow file
Use one workflow filename for both canary and stable publishing:
- `.github/workflows/release.yml`
Why:
- npm trusted publishing is configured per workflow filename
- npm currently allows one trusted publisher configuration per package
- GitHub environments can still provide separate canary/stable approval rules inside the same workflow
#### 2. Use separate GitHub environments
Recommended environments:
- `npm-canary`
- `npm-stable`
Recommended policy:
- `npm-canary`
- allowed branch: `master`
- no human reviewer required
- `npm-stable`
- allowed branch: `master`
- required reviewer enabled
- prevent self-review enabled
- admin bypass disabled
Stable should require an explicit second human gate even if the workflow is manually dispatched.
#### 3. Lock down workflow edits
Add or tighten `CODEOWNERS` coverage for:
- `.github/workflows/*`
- `scripts/release*`
- `doc/RELEASING.md`
This matters because trusted publishing authorizes a workflow file. The biggest remaining risk is not secret exfiltration from forks. It is a maintainer-approved change to the release workflow itself.
#### 4. Remove traditional npm token access after OIDC works
After trusted publishing is verified:
- set package publishing access to require 2FA and disallow tokens
- revoke any legacy automation tokens
That eliminates the "someone stole the npm token" class of failure.
### What not to do
- do not put your personal Claude or npm token in GitHub Actions
- do not run release logic from `pull_request_target`
- do not make stable publishing depend on a repo secret if OIDC can handle it
- do not create canary GitHub Releases
## Changelog Strategy
### Recommendation
Generate stable changelogs only, and keep LLM-assisted changelog generation out of CI for now.
Reasoning:
- canaries happen too often
- canaries do not need polished public notes
- putting a personal Claude token into Actions is not worth the risk
- stable release cadence is low enough that a human-in-the-loop step is acceptable
Recommended stable path:
1. pick a canary commit or tag
2. run changelog generation locally from a trusted machine
3. commit `releases/vYYYY.MDD.P.md`
4. run stable promotion
If the notes are not ready yet, a fallback is acceptable:
- publish stable
- create a minimal GitHub Release
- update `releases/vYYYY.MDD.P.md` immediately afterward
But the better steady-state is to have the stable notes committed before stable publish.
### Future option
If you later want CI-assisted changelog drafting, do it with:
- a dedicated service account
- a token scoped only for changelog generation
- a manual workflow
- a dedicated environment with required reviewers
That is phase-two hardening work, not a phase-one requirement.
## Proposed Future Workflow
### Canary workflow
Trigger:
- `push` on `master`
Steps:
1. checkout the merged `master` commit
2. run verification on that exact commit
3. compute canary version for current UTC date
4. version public packages to `YYYY.MDD.P-canary.N`
5. publish to npm with dist-tag `canary`
6. create a canary git tag for traceability
Recommended canary tag format:
- `canary/v2026.317.1-canary.4`
Outputs:
- npm canary published
- git tag created
- no GitHub Release
- no changelog file required
### Stable workflow
Trigger:
- `workflow_dispatch`
Inputs:
- `source_ref`
- optional `stable_date`
- `dry_run`
Steps:
1. checkout `source_ref`
2. run verification on that exact commit
3. compute the next stable patch slot for the UTC date or provided override
4. fail if `vYYYY.MDD.P` already exists
5. require `releases/vYYYY.MDD.P.md`
6. version public packages to `YYYY.MDD.P`
7. publish to npm under `latest`
8. create git tag `vYYYY.MDD.P`
9. push tag
10. create GitHub Release from `releases/vYYYY.MDD.P.md`
Outputs:
- stable npm release
- stable git tag
- GitHub Release
- clean public changelog surface
## Implementation Guidance
### 1. Replace bump-type version math with explicit version computation
The current release scripts depend on:
- `patch`
- `minor`
- `major`
That logic should be replaced with:
- `compute_canary_version_for_date`
- `compute_stable_version_for_date`
For example:
- `next_stable_version(2026-03-17) -> 2026.317.0`
- `next_canary_for_utc_date(2026-03-17) -> 2026.317.0-canary.0`
### 2. Stop requiring `release/X.Y.Z`
These current invariants should be removed from the happy path:
- "must run from branch `release/X.Y.Z`"
- "stable and canary for `X.Y.Z` come from the same release branch"
- `release-start.sh`
Replace them with:
- canary must run from `master`
- stable may run from a pinned `source_ref`
### 3. Keep Changesets only if it stays helpful
The current system uses Changesets to:
- rewrite package versions
- maintain package-level `CHANGELOG.md` files
- publish packages
With CalVer, Changesets may still be useful for publish orchestration, but it should no longer own version selection.
Recommended implementation order:
1. keep `changeset publish` if it works with explicitly-set versions
2. replace version computation with a small explicit versioning script
3. if Changesets keeps fighting the model, remove it from release publishing entirely
Paperclip's release problem is now "publish the whole fixed package set at one explicit version", not "derive the next semantic bump from human intent".
### 4. Add a dedicated versioning script
Recommended new script:
- `scripts/set-release-version.mjs`
Responsibilities:
- set the version in all public publishable packages
- update any internal exact-version references needed for publishing
- update CLI version strings
- avoid broad string replacement across unrelated files
This is safer than keeping a bump-oriented changeset flow and then forcing it into a date-based scheme.
### 5. Keep rollback based on dist-tags
`rollback-latest.sh` should stay, but it should stop assuming a semver meaning beyond syntax.
It should continue to:
- repoint `latest` to a prior stable version
- never unpublish
## Tradeoffs and Risks
### 1. The stable patch slot is now part of the version contract
With `YYYY.MDD.P`, same-day hotfixes are supported, but the stable patch slot is now part of the visible version format.
That is the right tradeoff because:
1. npm still gets semver-valid versions
2. same-day hotfixes stay possible
3. chronological ordering still works as long as the day is zero-padded inside `MDD`
### 2. Public package consumers lose semver intent signaling
This is the main downside of CalVer.
If that becomes a problem, one alternative is:
- use CalVer for the CLI package only
- keep semver for library packages
That is more complex operationally, so I would not start there unless package consumers actually need it.
### 3. Auto-canary means more publish traffic
Publishing on every `master` merge means:
- more npm versions
- more git tags
- more registry noise
That is acceptable if canaries stay clearly separate:
- npm dist-tag `canary`
- no GitHub Release
- no external announcement
## Rollout Plan
### Phase 1: Security foundation
1. Create `release.yml`
2. Configure npm trusted publishers for all public packages
3. Create `npm-canary` and `npm-stable` environments
4. Add `CODEOWNERS` protection for release files
5. Verify OIDC publishing works
6. Disable token-based publishing access and revoke old tokens
### Phase 2: Canary automation
1. Add canary workflow on `push` to `master`
2. Add explicit calendar-version computation
3. Add canary git tagging
4. Remove changelog requirement from canaries
5. Update `doc/RELEASING.md`
### Phase 3: Stable promotion
1. Add manual stable workflow with `source_ref`
2. Require stable notes file
3. Publish stable + tag + GitHub Release
4. Update rollback docs and scripts
5. Retire release-branch assumptions
### Phase 4: Cleanup
1. Remove `release-start.sh` from the primary path
2. Remove `patch/minor/major` from maintainer docs
3. Decide whether to keep or remove Changesets from publishing
4. Document the CalVer compatibility contract publicly
## Concrete Recommendation
Paperclip should adopt this model:
- stable versions: `YYYY.MDD.P`
- canary versions: `YYYY.MDD.P-canary.N`
- canaries auto-published on every push to `master`
- stables manually promoted from a chosen tested commit or canary tag
- no release branches in the default path
- no canary changelog files
- no canary GitHub Releases
- no Claude token in GitHub Actions
- no npm automation token in GitHub Actions
- npm trusted publishing plus GitHub environments for release security
That gets rid of the annoying part of semver without fighting npm, makes canaries cheap, keeps stables deliberate, and materially improves the security posture of the public repository.
## External References
- npm trusted publishing: https://docs.npmjs.com/trusted-publishers/
- npm dist-tags: https://docs.npmjs.com/adding-dist-tags-to-packages/
- npm semantic versioning guidance: https://docs.npmjs.com/about-semantic-versioning/
- GitHub environments and deployment protection rules: https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments
- GitHub secrets behavior for forks: https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,882 @@
# Workspace Technical Implementation Spec
## Role of This Document
This document translates [workspace-product-model-and-work-product.md](/Users/dotta/paperclip-subissues/doc/plans/workspace-product-model-and-work-product.md) into an implementation-ready engineering plan.
It is intentionally concrete:
- schema and migration shape
- shared contract updates
- route and service changes
- UI changes
- rollout and compatibility rules
This is the implementation target for the first workspace-aware delivery slice.
## Locked Decisions
These decisions are treated as settled for this implementation:
1. Add a new durable `execution_workspaces` table now.
2. Each issue has at most one current execution workspace at a time.
3. `issues` get explicit `project_workspace_id` and `execution_workspace_id`.
4. Workspace reuse is in scope for V1.
5. The feature is gated in the UI by `/instance/settings > Experimental > Workspaces`.
6. The gate is UI-only. Backend model changes and migrations always ship.
7. Existing users upgrade into compatibility-preserving defaults.
8. `project_workspaces` evolves in place rather than being replaced.
9. Work product is issue-first, with optional links to execution workspaces and runtime services.
10. GitHub is the only PR provider in the first slice.
11. Both `adapter_managed` and `cloud_sandbox` execution modes are in scope.
12. Workspace controls ship first inside existing project properties, not in a new global navigation area.
13. Subissues are out of scope for this implementation slice.
## Non-Goals
- Building a full code review system
- Solving subissue UX in this slice
- Implementing reusable shared workspace definitions across projects in this slice
- Reworking all current runtime service behavior before introducing execution workspaces
## Existing Baseline
The repo already has:
- `project_workspaces`
- `projects.execution_workspace_policy`
- `issues.execution_workspace_settings`
- runtime service persistence in `workspace_runtime_services`
- local git-worktree realization in `workspace-runtime.ts`
This implementation should build on that baseline rather than fork it.
## Terminology
- `Project workspace`: durable configured codebase/root for a project
- `Execution workspace`: actual runtime workspace used for one or more issues
- `Work product`: user-facing output such as PR, preview, branch, commit, artifact, document
- `Runtime service`: process or service owned or tracked for a workspace
- `Compatibility mode`: existing behavior preserved for upgraded installs with no explicit workspace opt-in
## Architecture Summary
The first slice should introduce three explicit layers:
1. `Project workspace`
- existing durable project-scoped codebase record
- extended to support local, git, non-git, and remote-managed shapes
2. `Execution workspace`
- new durable runtime record
- represents shared, isolated, operator-branch, or remote-managed execution context
3. `Issue work product`
- new durable output record
- stores PRs, previews, branches, commits, artifacts, and documents
The issue remains the planning and ownership unit.
The execution workspace remains the runtime unit.
The work product remains the deliverable/output unit.
## Configuration and Deployment Topology
## Important correction
This repo already uses `PAPERCLIP_DEPLOYMENT_MODE` for auth/deployment behavior (`local_trusted | authenticated`).
Do not overload that variable for workspace execution topology.
## New env var
Add a separate execution-host hint:
- `PAPERCLIP_EXECUTION_TOPOLOGY=local|cloud|hybrid`
Default:
- if unset, treat as `local`
Purpose:
- influences defaults and validation for workspace configuration
- does not change current auth/deployment semantics
- does not break existing installs
### Semantics
- `local`
- Paperclip may create host-local worktrees, processes, and paths
- `cloud`
- Paperclip should assume no durable host-local execution workspace management
- adapter-managed and cloud-sandbox flows should be treated as first-class
- `hybrid`
- both local and remote execution strategies may exist
This is a guardrail and defaulting aid, not a hard policy engine in the first slice.
## Instance Settings
Add a new `Experimental` section under `/instance/settings`.
### New setting
- `experimental.workspaces: boolean`
Rules:
- default `false`
- UI-only gate
- stored in instance config or instance settings API response
- backend routes and migrations remain available even when false
### UI behavior when off
- hide workspace-specific issue controls
- hide workspace-specific project configuration
- hide issue `Work Product` tab if it would otherwise be empty
- do not remove or invalidate any stored workspace data
## Data Model
## 1. Extend `project_workspaces`
Current table exists and should evolve in place.
### New columns
- `source_type text not null default 'local_path'`
- `local_path | git_repo | non_git_path | remote_managed`
- `default_ref text null`
- `visibility text not null default 'default'`
- `default | advanced`
- `setup_command text null`
- `cleanup_command text null`
- `remote_provider text null`
- examples: `github`, `openai`, `anthropic`, `custom`
- `remote_workspace_ref text null`
- `shared_workspace_key text null`
- reserved for future cross-project shared workspace definitions
### Backfill rules
- if existing row has `repo_url`, backfill `source_type='git_repo'`
- else if existing row has `cwd`, backfill `source_type='local_path'`
- else backfill `source_type='remote_managed'`
- copy existing `repo_ref` into `default_ref`
### Indexes
- retain current indexes
- add `(project_id, source_type)`
- add `(company_id, shared_workspace_key)` non-unique for future support
## 2. Add `execution_workspaces`
Create a new durable table.
### Columns
- `id uuid pk`
- `company_id uuid not null`
- `project_id uuid not null`
- `project_workspace_id uuid null`
- `source_issue_id uuid null`
- `mode text not null`
- `shared_workspace | isolated_workspace | operator_branch | adapter_managed | cloud_sandbox`
- `strategy_type text not null`
- `project_primary | git_worktree | adapter_managed | cloud_sandbox`
- `name text not null`
- `status text not null default 'active'`
- `active | idle | in_review | archived | cleanup_failed`
- `cwd text null`
- `repo_url text null`
- `base_ref text null`
- `branch_name text null`
- `provider_type text not null default 'local_fs'`
- `local_fs | git_worktree | adapter_managed | cloud_sandbox`
- `provider_ref text null`
- `derived_from_execution_workspace_id uuid null`
- `last_used_at timestamptz not null default now()`
- `opened_at timestamptz not null default now()`
- `closed_at timestamptz null`
- `cleanup_eligible_at timestamptz null`
- `cleanup_reason text null`
- `metadata jsonb null`
- `created_at timestamptz not null default now()`
- `updated_at timestamptz not null default now()`
### Foreign keys
- `company_id -> companies.id`
- `project_id -> projects.id`
- `project_workspace_id -> project_workspaces.id on delete set null`
- `source_issue_id -> issues.id on delete set null`
- `derived_from_execution_workspace_id -> execution_workspaces.id on delete set null`
### Indexes
- `(company_id, project_id, status)`
- `(company_id, project_workspace_id, status)`
- `(company_id, source_issue_id)`
- `(company_id, last_used_at desc)`
- `(company_id, branch_name)` non-unique
## 3. Extend `issues`
Add explicit workspace linkage.
### New columns
- `project_workspace_id uuid null`
- `execution_workspace_id uuid null`
- `execution_workspace_preference text null`
- `inherit | shared_workspace | isolated_workspace | operator_branch | reuse_existing`
### Foreign keys
- `project_workspace_id -> project_workspaces.id on delete set null`
- `execution_workspace_id -> execution_workspaces.id on delete set null`
### Backfill rules
- all existing issues get null values
- null should be interpreted as compatibility/inherit behavior
### Invariants
- if `project_workspace_id` is set, it must belong to the issue's project and company
- if `execution_workspace_id` is set, it must belong to the issue's company
- if `execution_workspace_id` is set, the referenced workspace's `project_id` must match the issue's `project_id`
## 4. Add `issue_work_products`
Create a new durable table for outputs.
### Columns
- `id uuid pk`
- `company_id uuid not null`
- `project_id uuid null`
- `issue_id uuid not null`
- `execution_workspace_id uuid null`
- `runtime_service_id uuid null`
- `type text not null`
- `preview_url | runtime_service | pull_request | branch | commit | artifact | document`
- `provider text not null`
- `paperclip | github | vercel | s3 | custom`
- `external_id text null`
- `title text not null`
- `url text null`
- `status text not null`
- `active | ready_for_review | approved | changes_requested | merged | closed | failed | archived`
- `review_state text not null default 'none'`
- `none | needs_board_review | approved | changes_requested`
- `is_primary boolean not null default false`
- `health_status text not null default 'unknown'`
- `unknown | healthy | unhealthy`
- `summary text null`
- `metadata jsonb null`
- `created_by_run_id uuid null`
- `created_at timestamptz not null default now()`
- `updated_at timestamptz not null default now()`
### Foreign keys
- `company_id -> companies.id`
- `project_id -> projects.id on delete set null`
- `issue_id -> issues.id on delete cascade`
- `execution_workspace_id -> execution_workspaces.id on delete set null`
- `runtime_service_id -> workspace_runtime_services.id on delete set null`
- `created_by_run_id -> heartbeat_runs.id on delete set null`
### Indexes
- `(company_id, issue_id, type)`
- `(company_id, execution_workspace_id, type)`
- `(company_id, provider, external_id)`
- `(company_id, updated_at desc)`
## 5. Extend `workspace_runtime_services`
This table already exists and should remain the system of record for owned/tracked services.
### New column
- `execution_workspace_id uuid null`
### Foreign key
- `execution_workspace_id -> execution_workspaces.id on delete set null`
### Behavior
- runtime services remain workspace-first
- issue UIs should surface them through linked execution workspaces and work products
## Shared Contracts
## 1. `packages/shared`
### Update project workspace types and validators
Add fields:
- `sourceType`
- `defaultRef`
- `visibility`
- `setupCommand`
- `cleanupCommand`
- `remoteProvider`
- `remoteWorkspaceRef`
- `sharedWorkspaceKey`
### Add execution workspace types and validators
New shared types:
- `ExecutionWorkspace`
- `ExecutionWorkspaceMode`
- `ExecutionWorkspaceStatus`
- `ExecutionWorkspaceProviderType`
### Add work product types and validators
New shared types:
- `IssueWorkProduct`
- `IssueWorkProductType`
- `IssueWorkProductStatus`
- `IssueWorkProductReviewState`
### Update issue types and validators
Add:
- `projectWorkspaceId`
- `executionWorkspaceId`
- `executionWorkspacePreference`
- `workProducts?: IssueWorkProduct[]`
### Extend project execution policy contract
Replace the current narrow policy with a more explicit shape:
- `enabled`
- `defaultMode`
- `shared_workspace | isolated_workspace | operator_branch | adapter_default`
- `allowIssueOverride`
- `defaultProjectWorkspaceId`
- `workspaceStrategy`
- `branchPolicy`
- `pullRequestPolicy`
- `runtimePolicy`
- `cleanupPolicy`
Do not try to encode every possible provider-specific field in V1. Keep provider-specific extensibility in nested JSON where needed.
## Service Layer Changes
## 1. Project service
Update project workspace CRUD to handle the extended schema.
### Required rules
- when setting a primary workspace, clear `is_primary` on siblings
- `source_type=remote_managed` may have null `cwd`
- local/git-backed workspaces should still require one of `cwd` or `repo_url`
- preserve current behavior for existing callers that only send `cwd/repoUrl/repoRef`
## 2. Issue service
Update create/update flows to handle explicit workspace binding.
### Create behavior
Resolve defaults in this order:
1. explicit `projectWorkspaceId` from request
2. `project.executionWorkspacePolicy.defaultProjectWorkspaceId`
3. project's primary workspace
4. null
Resolve `executionWorkspacePreference`:
1. explicit request field
2. project policy default
3. compatibility fallback to `inherit`
Do not create an execution workspace at issue creation time unless:
- `reuse_existing` is explicitly chosen and `executionWorkspaceId` is provided
Otherwise, workspace realization happens when execution starts.
### Update behavior
- allow changing `projectWorkspaceId` only if the workspace belongs to the same project
- allow setting `executionWorkspaceId` only if it belongs to the same company and project
- do not automatically destroy or relink historical work products when workspace linkage changes
## 3. Workspace realization service
Refactor `workspace-runtime.ts` so realization produces or reuses an `execution_workspaces` row.
### New flow
Input:
- issue
- project workspace
- project execution policy
- execution topology hint
- adapter/runtime configuration
Output:
- realized execution workspace record
- runtime cwd/provider metadata
### Required modes
- `shared_workspace`
- reuse a stable execution workspace representing the project primary/shared workspace
- `isolated_workspace`
- create or reuse a derived isolated execution workspace
- `operator_branch`
- create or reuse a long-lived branch workspace
- `adapter_managed`
- create an execution workspace with provider references and optional null `cwd`
- `cloud_sandbox`
- same as adapter-managed, but explicit remote sandbox semantics
### Reuse rules
When `reuse_existing` is requested:
- only list active or recently used execution workspaces
- only for the same project
- only for the same project workspace if one is specified
- exclude archived and cleanup-failed workspaces
### Shared workspace realization
For compatibility mode and shared-workspace projects:
- create a stable execution workspace per project workspace when first needed
- reuse it for subsequent runs
This avoids a special-case branch in later work product linkage.
## 4. Runtime service integration
When runtime services are started or reused:
- populate `execution_workspace_id`
- continue populating `project_workspace_id`, `project_id`, and `issue_id`
When a runtime service yields a URL:
- optionally create or update a linked `issue_work_products` row of type `runtime_service` or `preview_url`
## 5. PR and preview reporting
Add a service for creating/updating `issue_work_products`.
### Supported V1 product types
- `pull_request`
- `preview_url`
- `runtime_service`
- `branch`
- `commit`
- `artifact`
- `document`
### GitHub PR reporting
For V1, GitHub is the only provider with richer semantics.
Supported statuses:
- `draft`
- `ready_for_review`
- `approved`
- `changes_requested`
- `merged`
- `closed`
Represent these in `status` and `review_state` rather than inventing a separate PR table in V1.
## Routes and API
## 1. Project workspace routes
Extend existing routes:
- `GET /projects/:id/workspaces`
- `POST /projects/:id/workspaces`
- `PATCH /projects/:id/workspaces/:workspaceId`
- `DELETE /projects/:id/workspaces/:workspaceId`
### New accepted/returned fields
- `sourceType`
- `defaultRef`
- `visibility`
- `setupCommand`
- `cleanupCommand`
- `remoteProvider`
- `remoteWorkspaceRef`
## 2. Execution workspace routes
Add:
- `GET /companies/:companyId/execution-workspaces`
- filters:
- `projectId`
- `projectWorkspaceId`
- `status`
- `issueId`
- `reuseEligible=true`
- `GET /execution-workspaces/:id`
- `PATCH /execution-workspaces/:id`
- update status/metadata/cleanup fields only in V1
Do not add top-level navigation for these routes yet.
## 3. Work product routes
Add:
- `GET /issues/:id/work-products`
- `POST /issues/:id/work-products`
- `PATCH /work-products/:id`
- `DELETE /work-products/:id`
### V1 mutation permissions
- board can create/update/delete all
- agents can create/update for issues they are assigned or currently executing
- deletion should generally archive rather than hard-delete once linked to historical output
## 4. Issue routes
Extend existing create/update payloads to accept:
- `projectWorkspaceId`
- `executionWorkspacePreference`
- `executionWorkspaceId`
Extend `GET /issues/:id` to return:
- `projectWorkspaceId`
- `executionWorkspaceId`
- `executionWorkspacePreference`
- `currentExecutionWorkspace`
- `workProducts[]`
## 5. Instance settings routes
Add support for:
- reading/writing `experimental.workspaces`
This is a UI gate only.
If there is no generic instance settings storage yet, the first slice can store this in the existing config/instance settings mechanism used by `/instance/settings`.
## UI Changes
## 1. `/instance/settings`
Add section:
- `Experimental`
- `Enable Workspaces`
When off:
- hide new workspace-specific affordances
- do not alter existing project or issue behavior
## 2. Project properties
Do not create a separate `Code` tab yet.
Ship inside existing project properties first.
### Add or re-enable sections
- `Project Workspaces`
- `Execution Defaults`
- `Provisioning`
- `Pull Requests`
- `Previews and Runtime`
- `Cleanup`
### Display rules
- only show when `experimental.workspaces=true`
- keep wording generic enough for local and remote setups
- only show git-specific fields when `sourceType=git_repo`
- only show local-path-specific fields when not `remote_managed`
## 3. Issue create dialog
When the workspace experimental flag is on and the selected project has workspace automation or workspaces:
### Basic fields
- `Codebase`
- select from project workspaces
- default to policy default or primary workspace
- `Execution mode`
- `Project default`
- `Shared workspace`
- `Isolated workspace`
- `Operator branch`
### Advanced section
- `Reuse existing execution workspace`
This control should query only:
- same project
- same codebase if selected
- active/recent workspaces
- compact labels with branch or workspace name
Do not expose all execution workspaces in a noisy unfiltered list.
## 4. Issue detail
Add a `Work Product` tab when:
- the experimental flag is on, or
- the issue already has work products
### Show
- current execution workspace summary
- PR cards
- preview cards
- branch/commit rows
- artifacts/documents
Add compact header chips:
- codebase
- workspace
- PR count/status
- preview status
## 5. Execution workspace detail page
Add a detail route but no nav item.
Linked from:
- issue work product tab
- project workspace/execution panels
### Show
- identity and status
- project workspace origin
- source issue
- linked issues
- branch/ref/provider info
- runtime services
- work products
- cleanup state
## Runtime and Adapter Behavior
## 1. Local adapters
For local adapters:
- continue to use existing cwd/worktree realization paths
- persist the result as execution workspaces
- attach runtime services and work product to the execution workspace and issue
## 2. Remote or cloud adapters
For remote adapters:
- allow execution workspaces with null `cwd`
- require provider metadata sufficient to identify the remote workspace/session
- allow work product creation without any host-local process ownership
Examples:
- cloud coding agent opens a branch and PR on GitHub
- Vercel preview URL is reported back as a preview work product
- remote sandbox emits artifact URLs
## 3. Approval-aware PR workflow
V1 should support richer PR state tracking, but not a full review engine.
### Required actions
- `open_pr`
- `mark_ready`
### Required review states
- `draft`
- `ready_for_review`
- `approved`
- `changes_requested`
- `merged`
- `closed`
### Storage approach
- represent these as `issue_work_products` with `type='pull_request'`
- use `status` and `review_state`
- store provider-specific details in `metadata`
## Migration Plan
## 1. Existing installs
The migration posture is backward-compatible by default.
### Guarantees
- no existing project must be edited before it keeps working
- no existing issue flow should start requiring workspace input
- all new nullable columns must preserve current behavior when absent
## 2. Project workspace migration
Migrate `project_workspaces` in place.
### Backfill
- derive `source_type`
- copy `repo_ref` to `default_ref`
- leave new optional fields null
## 3. Issue migration
Do not backfill `project_workspace_id` or `execution_workspace_id` on all existing issues.
Reason:
- the safest migration is to preserve current runtime behavior and bind explicitly only when new workspace-aware flows are used
Interpret old issues as:
- `executionWorkspacePreference = inherit`
- compatibility/shared behavior
## 4. Runtime history migration
Do not attempt a perfect historical reconstruction of execution workspaces in the migration itself.
Instead:
- create execution workspace records forward from first new run
- optionally add a later backfill tool for recent runtime services if it proves valuable
## Rollout Order
## Phase 1: Schema and shared contracts
1. extend `project_workspaces`
2. add `execution_workspaces`
3. add `issue_work_products`
4. extend `issues`
5. extend `workspace_runtime_services`
6. update shared types and validators
## Phase 2: Service wiring
1. update project workspace CRUD
2. update issue create/update resolution
3. refactor workspace realization to persist execution workspaces
4. attach runtime services to execution workspaces
5. add work product service and persistence
## Phase 3: API and UI
1. add execution workspace routes
2. add work product routes
3. add instance experimental settings toggle
4. re-enable and revise project workspace UI behind the flag
5. add issue create/update controls behind the flag
6. add issue work product tab
7. add execution workspace detail page
## Phase 4: Provider integrations
1. GitHub PR reporting
2. preview URL reporting
3. runtime-service-to-work-product linking
4. remote/cloud provider references
## Acceptance Criteria
1. Existing installs continue to behave predictably with no required reconfiguration.
2. Projects can define local, git, non-git, and remote-managed project workspaces.
3. Issues can explicitly select a project workspace and execution preference.
4. Each issue can point to one current execution workspace.
5. Multiple issues can intentionally reuse the same execution workspace.
6. Execution workspaces are persisted for both local and remote execution flows.
7. Work products can be attached to issues with optional execution workspace linkage.
8. GitHub PRs can be represented with richer lifecycle states.
9. The main UI remains simple when the experimental flag is off.
10. No top-level workspace navigation is required for this first slice.
## Risks and Mitigations
## Risk: too many overlapping workspace concepts
Mitigation:
- keep issue UI to `Codebase` and `Execution mode`
- reserve execution workspace details for advanced pages
## Risk: breaking current projects on upgrade
Mitigation:
- nullable schema additions
- in-place `project_workspaces` migration
- compatibility defaults
## Risk: local-only assumptions leaking into cloud mode
Mitigation:
- make `cwd` optional for execution workspaces
- use `provider_type` and `provider_ref`
- use `PAPERCLIP_EXECUTION_TOPOLOGY` as a defaulting guardrail
## Risk: turning PRs into a bespoke subsystem too early
Mitigation:
- represent PRs as work products in V1
- keep provider-specific details in metadata
- defer a dedicated PR table unless usage proves it necessary
## Recommended First Engineering Slice
If we want the narrowest useful implementation:
1. extend `project_workspaces`
2. add `execution_workspaces`
3. extend `issues` with explicit workspace fields
4. persist execution workspaces from existing local workspace realization
5. add `issue_work_products`
6. show project workspace controls and issue workspace controls behind the experimental flag
7. add issue `Work Product` tab with PR/preview/runtime service display
This slice is enough to validate the model without yet building every provider integration or cleanup workflow.

View File

@@ -0,0 +1,155 @@
# Plugin Authoring Guide
This guide describes the current, implemented way to create a Paperclip plugin in this repo.
It is intentionally narrower than [PLUGIN_SPEC.md](./PLUGIN_SPEC.md). The spec includes future ideas; this guide only covers the alpha surface that exists now.
## Current reality
- Treat plugin workers and plugin UI as trusted code.
- Plugin UI runs as same-origin JavaScript inside the main Paperclip app.
- Worker-side host APIs are capability-gated.
- Plugin UI is not sandboxed by manifest capabilities.
- There is no host-provided shared React component kit for plugins yet.
- `ctx.assets` is not supported in the current runtime.
## Scaffold a plugin
Use the scaffold package:
```bash
pnpm --filter @paperclipai/create-paperclip-plugin build
node packages/plugins/create-paperclip-plugin/dist/index.js @yourscope/plugin-name --output ./packages/plugins/examples
```
For a plugin that lives outside the Paperclip repo:
```bash
pnpm --filter @paperclipai/create-paperclip-plugin build
node packages/plugins/create-paperclip-plugin/dist/index.js @yourscope/plugin-name \
--output /absolute/path/to/plugin-repos \
--sdk-path /absolute/path/to/paperclip/packages/plugins/sdk
```
That creates a package with:
- `src/manifest.ts`
- `src/worker.ts`
- `src/ui/index.tsx`
- `tests/plugin.spec.ts`
- `esbuild.config.mjs`
- `rollup.config.mjs`
Inside this monorepo, the scaffold uses `workspace:*` for `@paperclipai/plugin-sdk`.
Outside this monorepo, the scaffold snapshots `@paperclipai/plugin-sdk` from the local Paperclip checkout into a `.paperclip-sdk/` tarball so you can build and test a plugin without publishing anything to npm first.
## Recommended local workflow
From the generated plugin folder:
```bash
pnpm install
pnpm typecheck
pnpm test
pnpm build
```
For local development, install it into Paperclip from an absolute local path through the plugin manager or API. The server supports local filesystem installs and watches local-path plugins for file changes so worker restarts happen automatically after rebuilds.
Example:
```bash
curl -X POST http://127.0.0.1:3100/api/plugins/install \
-H "Content-Type: application/json" \
-d '{"packageName":"/absolute/path/to/your-plugin","isLocalPath":true}'
```
## Supported alpha surface
Worker:
- config
- events
- jobs
- launchers
- http
- secrets
- activity
- state
- entities
- projects and project workspaces
- companies
- issues and comments
- agents and agent sessions
- goals
- data/actions
- streams
- tools
- metrics
- logger
UI:
- `usePluginData`
- `usePluginAction`
- `usePluginStream`
- `usePluginToast`
- `useHostContext`
- typed slot props from `@paperclipai/plugin-sdk/ui`
Mount surfaces currently wired in the host include:
- `page`
- `settingsPage`
- `dashboardWidget`
- `sidebar`
- `sidebarPanel`
- `detailTab`
- `taskDetailView`
- `projectSidebarItem`
- `globalToolbarButton`
- `toolbarButton`
- `contextMenuItem`
- `commentAnnotation`
- `commentContextMenuItem`
## Company routes
Plugins may declare a `page` slot with `routePath` to own a company route like:
```text
/:companyPrefix/<routePath>
```
Rules:
- `routePath` must be a single lowercase slug
- it cannot collide with reserved host routes
- it cannot duplicate another installed plugin page route
## Publishing guidance
- Use npm packages as the deployment artifact.
- Treat repo-local example installs as a development workflow only.
- Prefer keeping plugin UI self-contained inside the package.
- Do not rely on host design-system components or undocumented app internals.
- GitHub repository installs are not a first-class workflow today. For local development, use a checked-out local path. For production, publish to npm or a private npm-compatible registry.
## Verification before handoff
At minimum:
```bash
pnpm --filter <your-plugin-package> typecheck
pnpm --filter <your-plugin-package> test
pnpm --filter <your-plugin-package> build
```
If you changed host integration too, also run:
```bash
pnpm -r typecheck
pnpm test:run
pnpm build
```

View File

@@ -8,6 +8,29 @@ It expands the brief plugin notes in [doc/SPEC.md](../SPEC.md) and should be rea
This is not part of the V1 implementation contract in [doc/SPEC-implementation.md](../SPEC-implementation.md).
It is the full target architecture for the plugin system that should follow V1.
## Current implementation caveats
The code in this repo now includes an early plugin runtime and admin UI, but it does not yet deliver the full deployment model described in this spec.
Today, the practical deployment model is:
- single-tenant
- self-hosted
- single-node or otherwise filesystem-persistent
Current limitations to keep in mind:
- Plugin UI bundles currently run as same-origin JavaScript inside the main Paperclip app. Treat plugin UI as trusted code, not a sandboxed frontend capability boundary.
- Manifest capabilities currently gate worker-side host RPC calls. They do not prevent plugin UI code from calling ordinary Paperclip HTTP APIs directly.
- Runtime installs assume a writable local filesystem for the plugin package directory and plugin data directory.
- Runtime npm installs assume `npm` is available in the running environment and that the host can reach the configured package registry.
- Published npm packages are the intended install artifact for deployed plugins.
- The repo example plugins under `packages/plugins/examples/` are development conveniences. They work from a source checkout and should not be assumed to exist in a generic published build unless they are explicitly shipped with that build.
- Dynamic plugin install is not yet cloud-ready for horizontally scaled or ephemeral deployments. There is no shared artifact store, install coordination, or cross-node distribution layer yet.
- The current runtime does not yet ship a real host-provided plugin UI component kit, and it does not support plugin asset uploads/reads. Treat those as future-scope ideas in this spec, not current implementation promises.
In practice, that means the current implementation is a good fit for local development and self-hosted persistent deployments, but not yet for multi-instance cloud plugin distribution.
## 1. Scope
This spec covers:
@@ -212,6 +235,8 @@ Suggested layout:
The package install directory and the plugin data directory are separate.
This on-disk model is the reason the current implementation expects a persistent writable host filesystem. Cloud-safe artifact replication is future work.
## 8.2 Operator Commands
Paperclip should add CLI commands:
@@ -237,6 +262,8 @@ The install process is:
7. Start plugin worker and run health/validation.
8. Mark plugin `ready` or `error`.
For the current implementation, this install flow should be read as a single-host workflow. A successful install writes packages to the local host, and other app nodes will not automatically receive that plugin unless a future shared distribution mechanism is added.
## 9. Load Order And Precedence
Load order must be deterministic.

View File

@@ -0,0 +1,33 @@
services:
review:
build:
context: .
dockerfile: docker/untrusted-review/Dockerfile
init: true
tty: true
stdin_open: true
working_dir: /work
environment:
HOME: "/home/reviewer"
CODEX_HOME: "/home/reviewer/.codex"
CLAUDE_HOME: "/home/reviewer/.claude"
PAPERCLIP_HOME: "/home/reviewer/.paperclip-review"
OPENAI_API_KEY: "${OPENAI_API_KEY:-}"
ANTHROPIC_API_KEY: "${ANTHROPIC_API_KEY:-}"
GITHUB_TOKEN: "${GITHUB_TOKEN:-}"
ports:
- "${REVIEW_PAPERCLIP_PORT:-3100}:3100"
- "${REVIEW_VITE_PORT:-5173}:5173"
volumes:
- review-home:/home/reviewer
- review-work:/work
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
tmpfs:
- /tmp:mode=1777,size=1g
volumes:
review-home:
review-work:

View File

@@ -0,0 +1,44 @@
FROM node:lts-trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
bash \
ca-certificates \
curl \
fd-find \
gh \
git \
jq \
less \
openssh-client \
procps \
ripgrep \
&& rm -rf /var/lib/apt/lists/*
RUN ln -sf /usr/bin/fdfind /usr/local/bin/fd
RUN corepack enable \
&& npm install --global --omit=dev @anthropic-ai/claude-code@latest @openai/codex@latest
RUN useradd --create-home --shell /bin/bash reviewer
ENV HOME=/home/reviewer \
CODEX_HOME=/home/reviewer/.codex \
CLAUDE_HOME=/home/reviewer/.claude \
PAPERCLIP_HOME=/home/reviewer/.paperclip-review \
PNPM_HOME=/home/reviewer/.local/share/pnpm \
PATH=/home/reviewer/.local/share/pnpm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
WORKDIR /work
COPY --chown=reviewer:reviewer docker/untrusted-review/bin/review-checkout-pr /usr/local/bin/review-checkout-pr
RUN chmod +x /usr/local/bin/review-checkout-pr \
&& mkdir -p /work \
&& chown -R reviewer:reviewer /work
USER reviewer
EXPOSE 3100 5173
CMD ["bash", "-l"]

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'EOF'
Usage: review-checkout-pr <owner/repo|github-url> <pr-number> [checkout-dir]
Examples:
review-checkout-pr paperclipai/paperclip 432
review-checkout-pr https://github.com/paperclipai/paperclip.git 432
EOF
}
if [[ $# -lt 2 || $# -gt 3 ]]; then
usage >&2
exit 1
fi
normalize_repo_slug() {
local raw="$1"
raw="${raw#git@github.com:}"
raw="${raw#ssh://git@github.com/}"
raw="${raw#https://github.com/}"
raw="${raw#http://github.com/}"
raw="${raw%.git}"
printf '%s\n' "${raw#/}"
}
repo_slug="$(normalize_repo_slug "$1")"
pr_number="$2"
if [[ ! "$repo_slug" =~ ^[^/]+/[^/]+$ ]]; then
echo "Expected GitHub repo slug like owner/repo or a GitHub repo URL, got: $1" >&2
exit 1
fi
if [[ ! "$pr_number" =~ ^[0-9]+$ ]]; then
echo "PR number must be numeric, got: $pr_number" >&2
exit 1
fi
repo_key="${repo_slug//\//-}"
mirror_dir="/work/repos/${repo_key}"
checkout_dir="${3:-/work/checkouts/${repo_key}/pr-${pr_number}}"
pr_ref="refs/remotes/origin/pr/${pr_number}"
mkdir -p "$(dirname "$mirror_dir")" "$(dirname "$checkout_dir")"
if [[ ! -d "$mirror_dir/.git" ]]; then
if command -v gh >/dev/null 2>&1; then
gh repo clone "$repo_slug" "$mirror_dir" -- --filter=blob:none
else
git clone --filter=blob:none "https://github.com/${repo_slug}.git" "$mirror_dir"
fi
fi
git -C "$mirror_dir" fetch --force origin "pull/${pr_number}/head:${pr_ref}"
if [[ -e "$checkout_dir" ]]; then
printf '%s\n' "$checkout_dir"
exit 0
fi
git -C "$mirror_dir" worktree add --detach "$checkout_dir" "$pr_ref" >/dev/null
printf '%s\n' "$checkout_dir"

View File

@@ -38,10 +38,33 @@ PATCH /api/companies/{companyId}
{
"name": "Updated Name",
"description": "Updated description",
"budgetMonthlyCents": 100000
"budgetMonthlyCents": 100000,
"logoAssetId": "b9f5e911-6de5-4cd0-8dc6-a55a13bc02f6"
}
```
## Upload Company Logo
Upload an image for a company icon and store it as that companys logo.
```
POST /api/companies/{companyId}/logo
Content-Type: multipart/form-data
```
Valid image content types:
- `image/png`
- `image/jpeg`
- `image/jpg`
- `image/webp`
- `image/gif`
- `image/svg+xml`
Company logo uploads use the normal Paperclip attachment size limit.
Then set the company logo by PATCHing the returned `assetId` into `logoAssetId`.
## Archive Company
```
@@ -58,6 +81,8 @@ Archives a company. Archived companies are hidden from default listings.
| `name` | string | Company name |
| `description` | string | Company description |
| `status` | string | `active`, `paused`, `archived` |
| `logoAssetId` | string | Optional asset id for the stored logo image |
| `logoUrl` | string | Optional Paperclip asset content path for the stored logo image |
| `budgetMonthlyCents` | number | Monthly budget limit |
| `createdAt` | string | ISO timestamp |
| `updatedAt` | string | ISO timestamp |

View File

@@ -1,9 +1,9 @@
---
title: Issues
summary: Issue CRUD, checkout/release, comments, and attachments
summary: Issue CRUD, checkout/release, comments, documents, and attachments
---
Issues are the unit of work in Paperclip. They support hierarchical relationships, atomic checkout, comments, and file attachments.
Issues are the unit of work in Paperclip. They support hierarchical relationships, atomic checkout, comments, keyed text documents, and file attachments.
## List Issues
@@ -29,6 +29,12 @@ GET /api/issues/{issueId}
Returns the issue with `project`, `goal`, and `ancestors` (parent chain with their projects and goals).
The response also includes:
- `planDocument`: the full text of the issue document with key `plan`, when present
- `documentSummaries`: metadata for all linked issue documents
- `legacyPlanDocument`: a read-only fallback when the description still contains an old `<plan>` block
## Create Issue
```
@@ -100,6 +106,54 @@ POST /api/issues/{issueId}/comments
@-mentions (`@AgentName`) in comments trigger heartbeats for the mentioned agent.
## Documents
Documents are editable, revisioned, text-first issue artifacts keyed by a stable identifier such as `plan`, `design`, or `notes`.
### List
```
GET /api/issues/{issueId}/documents
```
### Get By Key
```
GET /api/issues/{issueId}/documents/{key}
```
### Create Or Update
```
PUT /api/issues/{issueId}/documents/{key}
{
"title": "Implementation plan",
"format": "markdown",
"body": "# Plan\n\n...",
"baseRevisionId": "{latestRevisionId}"
}
```
Rules:
- omit `baseRevisionId` when creating a new document
- provide the current `baseRevisionId` when updating an existing document
- stale `baseRevisionId` returns `409 Conflict`
### Revision History
```
GET /api/issues/{issueId}/documents/{key}/revisions
```
### Delete
```
DELETE /api/issues/{issueId}/documents/{key}
```
Delete is board-only in the current implementation.
## Attachments
### Upload

View File

@@ -0,0 +1,628 @@
# Agent Companies Specification
Extension of the Agent Skills Specification
Version: `agentcompanies/v1-draft`
## 1. Purpose
An Agent Company package is a filesystem- and GitHub-native format for describing a company, team, agent, project, task, and associated skills using markdown files with YAML frontmatter.
This specification is an extension of the Agent Skills specification, not a replacement for it.
It defines how company-, team-, and agent-level package structure composes around the existing `SKILL.md` model.
This specification is vendor-neutral. It is intended to be usable by any agent-company runtime, not only Paperclip.
The format is designed to:
- be readable and writable by humans
- work directly from a local folder or GitHub repository
- require no central registry
- support attribution and pinned references to upstream files
- extend the existing Agent Skills ecosystem without redefining it
- be useful outside Paperclip
## 2. Core Principles
1. Markdown is canonical.
2. Git repositories are valid package containers.
3. Registries are optional discovery layers, not authorities.
4. `SKILL.md` remains owned by the Agent Skills specification.
5. External references must be pinnable to immutable Git commits.
6. Attribution and license metadata must survive import/export.
7. Slugs and relative paths are the portable identity layer, not database ids.
8. Conventional folder structure should work without verbose wiring.
9. Vendor-specific fidelity belongs in optional extensions, not the base package.
## 3. Package Kinds
A package root is identified by one primary markdown file:
- `COMPANY.md` for a company package
- `TEAM.md` for a team package
- `AGENTS.md` for an agent package
- `PROJECT.md` for a project package
- `TASK.md` for a task package
- `SKILL.md` for a skill package defined by the Agent Skills specification
A GitHub repo may contain one package at root or many packages in subdirectories.
## 4. Reserved Files And Directories
Common conventions:
```text
COMPANY.md
TEAM.md
AGENTS.md
PROJECT.md
TASK.md
SKILL.md
agents/<slug>/AGENTS.md
teams/<slug>/TEAM.md
projects/<slug>/PROJECT.md
projects/<slug>/tasks/<slug>/TASK.md
tasks/<slug>/TASK.md
skills/<slug>/SKILL.md
.paperclip.yaml
HEARTBEAT.md
SOUL.md
TOOLS.md
README.md
assets/
scripts/
references/
```
Rules:
- only markdown files are canonical content docs
- non-markdown directories like `assets/`, `scripts/`, and `references/` are allowed
- package tools may generate optional lock files, but lock files are not required for authoring
## 5. Common Frontmatter
Package docs may support these fields:
```yaml
schema: agentcompanies/v1
kind: company | team | agent | project | task
slug: my-slug
name: Human Readable Name
description: Short description
version: 0.1.0
license: MIT
authors:
- name: Jane Doe
homepage: https://example.com
tags:
- startup
- engineering
metadata: {}
sources: []
```
Notes:
- `schema` is optional and should usually appear only at the package root
- `kind` is optional when file path and file name already make the kind obvious
- `slug` should be URL-safe and stable
- `sources` is for provenance and external references
- `metadata` is for tool-specific extensions
- exporters should omit empty or default-valued fields
## 6. COMPANY.md
`COMPANY.md` is the root entrypoint for a whole company package.
### Required fields
```yaml
name: Lean Dev Shop
description: Small engineering-focused AI company
slug: lean-dev-shop
schema: agentcompanies/v1
```
### Recommended fields
```yaml
version: 1.0.0
license: MIT
authors:
- name: Example Org
goals:
- Build and ship software products
includes:
- https://github.com/example/shared-company-parts/blob/0123456789abcdef0123456789abcdef01234567/teams/engineering/TEAM.md
requirements:
secrets:
- OPENAI_API_KEY
```
### Semantics
- `includes` defines the package graph
- local package contents should be discovered implicitly by folder convention
- `includes` is optional and should be used mainly for external refs or nonstandard locations
- included items may be local or external references
- `COMPANY.md` may include agents directly, teams, projects, tasks, or skills
- a company importer may render `includes` as the tree/checkbox import UI
## 7. TEAM.md
`TEAM.md` defines an org subtree.
### Example
```yaml
name: Engineering
description: Product and platform engineering team
schema: agentcompanies/v1
slug: engineering
manager: ../cto/AGENTS.md
includes:
- ../platform-lead/AGENTS.md
- ../frontend-lead/AGENTS.md
- ../../skills/review/SKILL.md
tags:
- team
- engineering
```
### Semantics
- a team package is a reusable subtree, not necessarily a runtime database table
- `manager` identifies the root agent of the subtree
- `includes` may contain child agents, child teams, or shared skills
- a team package can be imported into an existing company and attached under a target manager
## 8. AGENTS.md
`AGENTS.md` defines an agent.
### Example
```yaml
name: CEO
title: Chief Executive Officer
reportsTo: null
skills:
- plan-ceo-review
- review
```
### Semantics
- body content is the canonical default instruction content for the agent
- `docs` points to sibling markdown docs when present
- `skills` references reusable `SKILL.md` packages by skill shortname or slug
- a bare skill entry like `review` should resolve to `skills/review/SKILL.md` by convention
- if a package references external skills, the agent should still refer to the skill by shortname; the skill package itself owns any source refs, pinning, or attribution details
- tools may allow path or URL entries as an escape hatch, but exporters should prefer shortname-based skill references in `AGENTS.md`
- vendor-specific adapter/runtime config should not live in the base package
- local absolute paths, machine-specific cwd values, and secret values must not be exported as canonical package data
### Skill Resolution
The preferred association standard between agents and skills is by skill shortname.
Suggested resolution order for an agent skill entry:
1. a local package skill at `skills/<shortname>/SKILL.md`
2. a referenced or included skill package whose declared slug or shortname matches
3. a tool-managed company skill library entry with the same shortname
Rules:
- exporters should emit shortnames in `AGENTS.md` whenever possible
- importers should not require full file paths for ordinary skill references
- the skill package itself should carry any complexity around external refs, vendoring, mirrors, or pinned upstream content
- this keeps `AGENTS.md` readable and consistent with `skills.sh`-style sharing
## 9. PROJECT.md
`PROJECT.md` defines a lightweight project package.
### Example
```yaml
name: Q2 Launch
description: Ship the Q2 launch plan and supporting assets
owner: cto
```
### Semantics
- a project package groups related starter tasks and supporting markdown
- `owner` should reference an agent slug when there is a clear project owner
- a conventional `tasks/` subfolder should be discovered implicitly
- `includes` may contain `TASK.md`, `SKILL.md`, or supporting docs when explicit wiring is needed
- project packages are intended to seed planned work, not represent runtime task state
## 10. TASK.md
`TASK.md` defines a lightweight starter task.
### Example
```yaml
name: Monday Review
assignee: ceo
project: q2-launch
schedule:
timezone: America/Chicago
startsAt: 2026-03-16T09:00:00-05:00
recurrence:
frequency: weekly
interval: 1
weekdays:
- monday
time:
hour: 9
minute: 0
```
### Semantics
- body content is the canonical markdown task description
- `assignee` should reference an agent slug inside the package
- `project` should reference a project slug when the task belongs to a `PROJECT.md`
- tasks are intentionally basic seed work: title, markdown body, assignee, and optional recurrence
- tools may also support optional fields like `priority`, `labels`, or `metadata`, but they should not require them in the base package
### Scheduling
The scheduling model is intentionally lightweight. It should cover common recurring patterns such as:
- every 6 hours
- every weekday at 9:00
- every Monday morning
- every month on the 1st
- every first Monday of the month
- every year on January 1
Suggested shape:
```yaml
schedule:
timezone: America/Chicago
startsAt: 2026-03-14T09:00:00-05:00
recurrence:
frequency: hourly | daily | weekly | monthly | yearly
interval: 1
weekdays:
- monday
- wednesday
monthDays:
- 1
- 15
ordinalWeekdays:
- weekday: monday
ordinal: 1
months:
- 1
- 6
time:
hour: 9
minute: 0
until: 2026-12-31T23:59:59-06:00
count: 10
```
Rules:
- `timezone` should use an IANA timezone like `America/Chicago`
- `startsAt` anchors the first occurrence
- `frequency` and `interval` are the only required recurrence fields
- `weekdays`, `monthDays`, `ordinalWeekdays`, and `months` are optional narrowing rules
- `ordinalWeekdays` uses `ordinal` values like `1`, `2`, `3`, `4`, or `-1` for “last”
- `time.hour` and `time.minute` keep common “morning / 9:00 / end of day” scheduling human-readable
- `until` and `count` are optional recurrence end bounds
- tools may accept richer calendar syntaxes such as RFC5545 `RRULE`, but exporters should prefer the structured form above
## 11. SKILL.md Compatibility
A skill package must remain a valid Agent Skills package.
Rules:
- `SKILL.md` should follow the Agent Skills spec
- Paperclip must not require extra top-level fields for skill validity
- Paperclip-specific extensions must live under `metadata.paperclip` or `metadata.sources`
- a skill directory may include `scripts/`, `references/`, and `assets/` exactly as the Agent Skills ecosystem expects
- tools implementing this spec should treat `skills.sh` compatibility as a first-class goal rather than inventing a parallel skill format
In other words, this spec extends Agent Skills upward into company/team/agent composition. It does not redefine skill package semantics.
### Example compatible extension
```yaml
---
name: review
description: Paranoid code review skill
allowed-tools:
- Read
- Grep
metadata:
paperclip:
tags:
- engineering
- review
sources:
- kind: github-file
repo: vercel-labs/skills
path: review/SKILL.md
commit: 0123456789abcdef0123456789abcdef01234567
sha256: 3b7e...9a
attribution: Vercel Labs
usage: referenced
---
```
## 12. Source References
A package may point to upstream content instead of vendoring it.
### Source object
```yaml
sources:
- kind: github-file
repo: owner/repo
path: path/to/file.md
commit: 0123456789abcdef0123456789abcdef01234567
blob: abcdef0123456789abcdef0123456789abcdef01
sha256: 3b7e...9a
url: https://github.com/owner/repo/blob/0123456789abcdef0123456789abcdef01234567/path/to/file.md
rawUrl: https://raw.githubusercontent.com/owner/repo/0123456789abcdef0123456789abcdef01234567/path/to/file.md
attribution: Owner Name
license: MIT
usage: referenced
```
### Supported kinds
- `local-file`
- `local-dir`
- `github-file`
- `github-dir`
- `url`
### Usage modes
- `vendored`: bytes are included in the package
- `referenced`: package points to upstream immutable content
- `mirrored`: bytes are cached locally but upstream attribution remains canonical
### Rules
- `commit` is required for `github-file` and `github-dir` in strict mode
- `sha256` is strongly recommended and should be verified on fetch
- branch-only refs may be allowed in development mode but must warn
- exporters should default to `referenced` for third-party content unless redistribution is clearly allowed
## 13. Resolution Rules
Given a package root, an importer resolves in this order:
1. local relative paths
2. local absolute paths if explicitly allowed by the importing tool
3. pinned GitHub refs
4. generic URLs
For pinned GitHub refs:
1. resolve `repo + commit + path`
2. fetch content
3. verify `sha256` if present
4. verify `blob` if present
5. fail closed on mismatch
An importer must surface:
- missing files
- hash mismatches
- missing licenses
- referenced upstream content that requires network fetch
- executable content in skills or scripts
## 14. Import Graph
A package importer should build a graph from:
- `COMPANY.md`
- `TEAM.md`
- `AGENTS.md`
- `PROJECT.md`
- `TASK.md`
- `SKILL.md`
- local and external refs
Suggested import UI behavior:
- render graph as a tree
- checkbox at entity level, not raw file level
- selecting an agent auto-selects required docs and referenced skills
- selecting a team auto-selects its subtree
- selecting a project auto-selects its included tasks
- selecting a recurring task should surface its schedule before import
- selecting referenced third-party content shows attribution, license, and fetch policy
## 15. Vendor Extensions
Vendor-specific data should live outside the base package shape.
For Paperclip, the preferred fidelity extension is:
```text
.paperclip.yaml
```
Example uses:
- adapter type and adapter config
- adapter env inputs and defaults
- runtime settings
- permissions
- budgets
- approval policies
- project execution workspace policies
- issue/task Paperclip-only metadata
Rules:
- the base package must remain readable without the extension
- tools that do not understand a vendor extension should ignore it
- Paperclip tools may emit the vendor extension by default as a sidecar while keeping the base markdown clean
Suggested Paperclip shape:
```yaml
schema: paperclip/v1
agents:
claudecoder:
adapter:
type: claude_local
config:
model: claude-opus-4-6
inputs:
env:
ANTHROPIC_API_KEY:
kind: secret
requirement: optional
default: ""
GH_TOKEN:
kind: secret
requirement: optional
CLAUDE_BIN:
kind: plain
requirement: optional
default: claude
```
Additional rules for Paperclip exporters:
- do not duplicate `promptTemplate` when `AGENTS.md` already contains the agent instructions
- do not export provider-specific secret bindings such as `secretId`, `version`, or `type: secret_ref`
- export env inputs as portable declarations with `required` or `optional` semantics and optional defaults
- warn on system-dependent values such as absolute commands and absolute `PATH` overrides
- omit empty and default-valued Paperclip fields when possible
## 16. Export Rules
A compliant exporter should:
- emit markdown roots and relative folder layout
- omit machine-local ids and timestamps
- omit secret values
- omit machine-specific paths
- preserve task descriptions and recurrence definitions when exporting tasks
- omit empty/default fields
- default to the vendor-neutral base package
- Paperclip exporters should emit `.paperclip.yaml` as a sidecar by default
- preserve attribution and source references
- prefer `referenced` over silent vendoring for third-party content
- preserve `SKILL.md` as-is when exporting compatible skills
## 17. Licensing And Attribution
A compliant tool must:
- preserve `license` and `attribution` metadata when importing and exporting
- distinguish vendored vs referenced content
- not silently inline referenced third-party content during export
- surface missing license metadata as a warning
- surface restrictive or unknown licenses before install/import if content is vendored or mirrored
## 18. Optional Lock File
Authoring does not require a lock file.
Tools may generate an optional lock file such as:
```text
company-package.lock.json
```
Purpose:
- cache resolved refs
- record final hashes
- support reproducible installs
Rules:
- lock files are optional
- lock files are generated artifacts, not canonical authoring input
- the markdown package remains the source of truth
## 19. Paperclip Mapping
Paperclip can map this spec to its runtime model like this:
- base package:
- `COMPANY.md` -> company metadata
- `TEAM.md` -> importable org subtree
- `AGENTS.md` -> agent identity and instructions
- `PROJECT.md` -> starter project definition
- `TASK.md` -> starter issue/task definition, or automation template when recurrence is present
- `SKILL.md` -> imported skill package
- `sources[]` -> provenance and pinned upstream refs
- Paperclip extension:
- `.paperclip.yaml` -> adapter config, runtime config, env input declarations, permissions, budgets, and other Paperclip-specific fidelity
Inline Paperclip-only metadata that must live inside a shared markdown file should use:
- `metadata.paperclip`
That keeps the base format broader than Paperclip.
This specification itself remains vendor-neutral and intended for any agent-company runtime, not only Paperclip.
## 20. Cutover
Paperclip should cut over to this markdown-first package model as the primary portability format.
`paperclip.manifest.json` does not need to be preserved as a compatibility requirement for the future package system.
For Paperclip, this should be treated as a hard cutover in product direction rather than a long-lived dual-format strategy.
## 21. Minimal Example
```text
lean-dev-shop/
├── COMPANY.md
├── agents/
│ ├── ceo/AGENTS.md
│ └── cto/AGENTS.md
├── projects/
│ └── q2-launch/
│ ├── PROJECT.md
│ └── tasks/
│ └── monday-review/
│ └── TASK.md
├── teams/
│ └── engineering/TEAM.md
├── tasks/
│ └── weekly-review/TASK.md
└── skills/
└── review/SKILL.md
Optional:
```text
.paperclip.yaml
```
```
**Recommendation**
This is the direction I would take:
- make this the human-facing spec
- define `SKILL.md` compatibility as non-negotiable
- treat this spec as an extension of Agent Skills, not a parallel format
- make `companies.sh` a discovery layer for repos implementing this spec, not a publishing authority

View File

@@ -0,0 +1,569 @@
# Issue Documents Plan
Status: Draft
Owner: Backend + UI + Agent Protocol
Date: 2026-03-13
Primary issue: `PAP-448`
## Summary
Add first-class **documents** to Paperclip as editable, revisioned, company-scoped text artifacts that can be linked to issues.
The first required convention is a document with key `plan`.
This solves the immediate workflow problem in `PAP-448`:
- plans should stop living inside issue descriptions as `<plan>` blocks
- agents and board users should be able to create/update issue documents directly
- `GET /api/issues/:id` should include the full `plan` document and expose the other available documents
- issue detail should render documents under the description
This should be built as the **text-document slice** of the broader artifact system, not as a replacement for attachments/assets.
## Recommended Product Shape
### Documents vs attachments vs artifacts
- **Documents**: editable text content with stable keys and revision history.
- **Attachments**: uploaded/generated opaque files backed by storage (`assets` + `issue_attachments`).
- **Artifacts**: later umbrella/read-model that can unify documents, attachments, previews, and workspace files.
Recommendation:
- implement **issue documents now**
- keep existing attachments as-is
- defer full artifact unification until there is a second real consumer beyond issue documents + attachments
This keeps `PAP-448` focused while still fitting the larger artifact direction.
## Goals
1. Give issues first-class keyed documents, starting with `plan`.
2. Make documents editable by board users and same-company agents with issue access.
3. Preserve change history with append-only revisions.
4. Make the `plan` document automatically available in the normal issue fetch used by agents/heartbeats.
5. Replace the current `<plan>`-in-description convention in skills/docs.
6. Keep the design compatible with a future artifact/deliverables layer.
## Non-Goals
- full collaborative doc editing
- binary-file version history
- browser IDE or workspace editor
- full artifact-system implementation in the same change
- generalized polymorphic relations for every entity type on day one
## Product Decisions
### 1. Keyed issue documents
Each issue can have multiple documents. Each document relation has a stable key:
- `plan`
- `design`
- `notes`
- `report`
- custom keys later
Key rules:
- unique per issue, case-insensitive
- normalized to lowercase slug form
- machine-oriented and stable
- title is separate and user-facing
The `plan` key is conventional and reserved by Paperclip workflow/docs.
### 2. Text-first v1
V1 documents should be text-first, not arbitrary blobs.
Recommended supported formats:
- `markdown`
- `plain_text`
- `json`
- `html`
Recommendation:
- optimize UI for `markdown`
- allow raw editing for the others
- keep PDFs/images/CSVs/etc as attachments/artifacts, not editable documents
### 3. Revision model
Every document update creates a new immutable revision.
The current document row stores the latest snapshot for fast reads.
### 4. Concurrency model
Do not use silent last-write-wins.
Updates should include `baseRevisionId`:
- create: no base revision required
- update: `baseRevisionId` must match current latest revision
- mismatch: return `409 Conflict`
This is important because both board users and agents may edit the same document.
### 5. Issue fetch behavior
`GET /api/issues/:id` should include:
- full `planDocument` when a `plan` document exists
- `documentSummaries` for all linked documents
It should not inline every document body by default.
This keeps issue fetches useful for agents without making every issue payload unbounded.
### 6. Legacy `<plan>` compatibility
If an issue has no `plan` document but its description contains a legacy `<plan>` block:
- expose that as a legacy read-only fallback in API/UI
- mark it as legacy/synthetic
- prefer a real `plan` document when both exist
Recommendation:
- do not auto-rewrite old issue descriptions in the first rollout
- provide an explicit import/migrate path later
## Proposed Data Model
Recommendation: make documents first-class, but keep issue linkage explicit via a join table.
This preserves foreign keys today and gives a clean path to future `project_documents` or `company_documents` tables later.
## Tables
### `documents`
Canonical text document record.
Suggested columns:
- `id`
- `company_id`
- `title`
- `format`
- `latest_body`
- `latest_revision_id`
- `latest_revision_number`
- `created_by_agent_id`
- `created_by_user_id`
- `updated_by_agent_id`
- `updated_by_user_id`
- `created_at`
- `updated_at`
### `document_revisions`
Append-only history.
Suggested columns:
- `id`
- `company_id`
- `document_id`
- `revision_number`
- `body`
- `change_summary`
- `created_by_agent_id`
- `created_by_user_id`
- `created_at`
Constraints:
- unique `(document_id, revision_number)`
### `issue_documents`
Issue relation + workflow key.
Suggested columns:
- `id`
- `company_id`
- `issue_id`
- `document_id`
- `key`
- `created_at`
- `updated_at`
Constraints:
- unique `(company_id, issue_id, key)`
- unique `(document_id)` to keep one issue relation per document in v1
## Why not use `assets` for this?
Because `assets` solves blob storage, not:
- stable keyed semantics like `plan`
- inline text editing
- revision history
- optimistic concurrency
- cheap inclusion in `GET /issues/:id`
Documents and attachments should remain separate primitives, then meet later in a deliverables/artifact read-model.
## Shared Types and API Contract
## New shared types
Add:
- `DocumentFormat`
- `IssueDocument`
- `IssueDocumentSummary`
- `DocumentRevision`
Recommended `IssueDocument` shape:
```ts
type DocumentFormat = "markdown" | "plain_text" | "json" | "html";
interface IssueDocument {
id: string;
companyId: string;
issueId: string;
key: string;
title: string | null;
format: DocumentFormat;
body: string;
latestRevisionId: string;
latestRevisionNumber: number;
createdByAgentId: string | null;
createdByUserId: string | null;
updatedByAgentId: string | null;
updatedByUserId: string | null;
createdAt: Date;
updatedAt: Date;
}
```
Recommended `IssueDocumentSummary` shape:
```ts
interface IssueDocumentSummary {
id: string;
key: string;
title: string | null;
format: DocumentFormat;
latestRevisionId: string;
latestRevisionNumber: number;
updatedAt: Date;
}
```
## Issue type enrichment
Extend `Issue` with:
```ts
interface Issue {
...
planDocument?: IssueDocument | null;
documentSummaries?: IssueDocumentSummary[];
legacyPlanDocument?: {
key: "plan";
body: string;
source: "issue_description";
} | null;
}
```
This directly satisfies the `PAP-448` requirement for heartbeat/API issue fetches.
## API endpoints
Recommended endpoints:
- `GET /api/issues/:issueId/documents`
- `GET /api/issues/:issueId/documents/:key`
- `PUT /api/issues/:issueId/documents/:key`
- `GET /api/issues/:issueId/documents/:key/revisions`
- `DELETE /api/issues/:issueId/documents/:key` optionally board-only in v1
Recommended `PUT` body:
```ts
{
title?: string | null;
format: "markdown" | "plain_text" | "json" | "html";
body: string;
changeSummary?: string | null;
baseRevisionId?: string | null;
}
```
Behavior:
- missing document + no `baseRevisionId`: create
- existing document + matching `baseRevisionId`: update
- existing document + stale `baseRevisionId`: `409`
## Authorization and invariants
- all document records are company-scoped
- issue relation must belong to same company
- board access follows existing issue access rules
- agent access follows existing same-company issue access rules
- every mutation writes activity log entries
Recommended delete rule for v1:
- board can delete documents
- agents can create/update, but not delete
That keeps automated systems from removing canonical docs too easily.
## UI Plan
## Issue detail
Add a new **Documents** section directly under the issue description.
Recommended behavior:
- show `plan` first when present
- show other documents below it
- render a gist-like header:
- key
- title
- last updated metadata
- revision number
- support inline edit
- support create new document by key
- support revision history drawer or sheet
Recommended presentation order:
1. Description
2. Documents
3. Attachments
4. Comments / activity / sub-issues
This matches the request that documents live under the description while still leaving attachments available.
## Editing UX
Recommendation:
- use markdown preview + raw edit toggle for markdown docs
- use raw textarea editor for non-markdown docs in v1
- show explicit save conflicts on `409`
- show a clear empty state: "No documents yet"
## Legacy plan rendering
If there is no stored `plan` document but legacy `<plan>` exists:
- show it in the Documents section
- mark it `Legacy plan from description`
- offer create/import in a later pass
## Agent Protocol and Skills
Update the Paperclip agent workflow so planning no longer edits the issue description.
Required changes:
- update `skills/paperclip/SKILL.md`
- replace the `<plan>` instructions with document creation/update instructions
- document the new endpoints in `docs/api/issues.md`
- update any internal planning docs that still teach inline `<plan>` blocks
New rule:
- when asked to make a plan for an issue, create or update the issue document with key `plan`
- leave a comment that the plan document was created/updated
- do not mark the issue done
## Relationship to the Artifact Plan
This work should explicitly feed the broader artifact/deliverables direction.
Recommendation:
- keep documents as their own primitive in this change
- add `document` to any future `ArtifactKind`
- later build a deliverables read-model that aggregates:
- issue documents
- issue attachments
- preview URLs
- workspace-file references
The artifact proposal currently has no explicit `document` kind. It should.
Recommended future shape:
```ts
type ArtifactKind =
| "document"
| "attachment"
| "workspace_file"
| "preview"
| "report_link";
```
## Implementation Phases
## Phase 1: Shared contract and schema
Files:
- `packages/db/src/schema/documents.ts`
- `packages/db/src/schema/document_revisions.ts`
- `packages/db/src/schema/issue_documents.ts`
- `packages/db/src/schema/index.ts`
- `packages/db/src/migrations/*`
- `packages/shared/src/types/issue.ts`
- `packages/shared/src/validators/issue.ts` or new document validator file
- `packages/shared/src/index.ts`
Acceptance:
- schema enforces one key per issue
- revisions are append-only
- shared types expose plan/document fields on issue fetch
## Phase 2: Server services and routes
Files:
- `server/src/services/issues.ts` or `server/src/services/documents.ts`
- `server/src/routes/issues.ts`
- `server/src/services/activity.ts` callsites
Behavior:
- list/get/upsert/delete documents
- revision listing
- `GET /issues/:id` returns `planDocument` + `documentSummaries`
- company boundary checks match issue routes
Acceptance:
- agents and board can fetch/update same-company issue documents
- stale edits return `409`
- activity timeline shows document changes
## Phase 3: UI issue documents surface
Files:
- `ui/src/api/issues.ts`
- `ui/src/lib/queryKeys.ts`
- `ui/src/pages/IssueDetail.tsx`
- new reusable document UI component if needed
Behavior:
- render plan + documents under description
- create/update by key
- open revision history
- show conflicts/errors clearly
Acceptance:
- board can create a `plan` doc from issue detail
- updated plan appears immediately
- issue detail no longer depends on description-embedded `<plan>`
## Phase 4: Skills/docs migration
Files:
- `skills/paperclip/SKILL.md`
- `docs/api/issues.md`
- `doc/SPEC-implementation.md`
- relevant plan/docs that mention `<plan>`
Acceptance:
- planning guidance references issue documents, not inline issue description tags
- API docs describe the new document endpoints and issue payload additions
## Phase 5: Legacy compatibility and follow-up
Behavior:
- read legacy `<plan>` blocks as fallback
- optionally add explicit import/migration command later
Follow-up, not required for first merge:
- deliverables/artifact read-model
- project/company documents
- comment-linked documents
- diff view between revisions
## Test Plan
### Server
- document create/read/update/delete lifecycle
- revision numbering
- `baseRevisionId` conflict handling
- company boundary enforcement
- agent vs board authorization
- issue fetch includes `planDocument` and document summaries
- legacy `<plan>` fallback behavior
- activity log mutation coverage
### UI
- issue detail shows plan document
- create/update flows invalidate queries correctly
- conflict and validation errors are surfaced
- legacy plan fallback renders correctly
### Verification
Run before implementation is declared complete:
```sh
pnpm -r typecheck
pnpm test:run
pnpm build
```
## Open Questions
1. Should v1 documents be markdown-only, with `json/html/plain_text` deferred?
Recommendation: allow all four in API, optimize UI for markdown only.
2. Should agents be allowed to create arbitrary keys, or only conventional keys?
Recommendation: allow arbitrary keys with normalized validation; reserve `plan` as special behavior only.
3. Should delete exist in v1?
Recommendation: yes, but board-only.
4. Should legacy `<plan>` blocks ever be auto-migrated?
Recommendation: no automatic mutation in the first rollout.
5. Should documents appear inside a future Deliverables section or remain a top-level Issue section?
Recommendation: keep a dedicated Documents section now; later also expose them in Deliverables if an aggregated artifact view is added.
## Final Recommendation
Ship **issue documents** as a focused, text-first primitive now.
Do not try to solve full artifact unification in the same implementation.
Use:
- first-class document tables
- issue-level keyed linkage
- append-only revisions
- `planDocument` embedded in normal issue fetches
- legacy `<plan>` fallback
- skill/docs migration away from description-embedded plans
This addresses the real planning workflow problem immediately and leaves the artifact system room to grow cleanly afterward.

View File

@@ -1,5 +1,7 @@
# ClipHub: Marketplace for Paperclip Team Configurations
> Supersession note: this marketplace plan predates the markdown-first company package direction. For the current package-format and import/export rollout plan, see `doc/plans/2026-03-13-company-import-export-v2.md` and `docs/companies/companies-spec.md`.
> The "app store" for whole-company AI teams — pre-built Paperclip configurations, agent blueprints, skills, and governance templates that ship real work from day one.
## 1. Vision & Positioning

View File

@@ -13,9 +13,19 @@ npx paperclipai onboard --yes
This walks you through setup, configures your environment, and gets Paperclip running.
To start Paperclip again later:
```sh
npx paperclipai run
```
> **Note:** If you used `npx` for setup, always use `npx paperclipai` to run commands. The `pnpm paperclipai` form only works inside a cloned copy of the Paperclip repository (see Local Development below).
## Local Development
Prerequisites: Node.js 20+ and pnpm 9+.
For contributors working on Paperclip itself. Prerequisites: Node.js 20+ and pnpm 9+.
Clone the repository, then:
```sh
pnpm install
@@ -26,7 +36,7 @@ This starts the API server and UI at [http://localhost:3100](http://localhost:31
No external database required — Paperclip uses an embedded PostgreSQL instance by default.
## One-Command Bootstrap
When working from the cloned repo, you can also use:
```sh
pnpm paperclipai run

View File

@@ -18,13 +18,11 @@
"db:backup": "./scripts/backup-db.sh",
"paperclipai": "node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts",
"build:npm": "./scripts/build-npm.sh",
"release:start": "./scripts/release-start.sh",
"release": "./scripts/release.sh",
"release:preflight": "./scripts/release-preflight.sh",
"release:canary": "./scripts/release.sh canary",
"release:stable": "./scripts/release.sh stable",
"release:github": "./scripts/create-github-release.sh",
"release:rollback": "./scripts/rollback-latest.sh",
"changeset": "changeset",
"version-packages": "changeset version",
"check:tokens": "node scripts/check-forbidden-tokens.mjs",
"docs:dev": "cd docs && npx mintlify dev",
"smoke:openclaw-join": "./scripts/smoke/openclaw-join.sh",
@@ -32,10 +30,11 @@
"smoke:openclaw-sse-standalone": "./scripts/smoke/openclaw-sse-standalone.sh",
"test:e2e": "npx playwright test --config tests/e2e/playwright.config.ts",
"test:e2e:headed": "npx playwright test --config tests/e2e/playwright.config.ts --headed",
"evals:smoke": "cd evals/promptfoo && npx promptfoo@0.103.3 eval"
"evals:smoke": "cd evals/promptfoo && npx promptfoo@0.103.3 eval",
"test:release-smoke": "npx playwright test --config tests/release-smoke/playwright.config.ts",
"test:release-smoke:headed": "npx playwright test --config tests/release-smoke/playwright.config.ts --headed"
},
"devDependencies": {
"@changesets/cli": "^2.30.0",
"cross-env": "^10.1.0",
"@playwright/test": "^1.58.2",
"esbuild": "^0.27.3",

View File

@@ -1,5 +1,11 @@
# @paperclipai/adapter-utils
## 0.3.1
### Patch Changes
- Stable release preparation for 0.3.1
## 0.3.0
### Minor Changes

View File

@@ -1,6 +1,16 @@
{
"name": "@paperclipai/adapter-utils",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapter-utils"
},
"type": "module",
"exports": {
".": "./src/index.ts",

View File

@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { inferOpenAiCompatibleBiller } from "./billing.js";
describe("inferOpenAiCompatibleBiller", () => {
it("returns openrouter when OPENROUTER_API_KEY is present", () => {
expect(
inferOpenAiCompatibleBiller({ OPENROUTER_API_KEY: "sk-or-123" } as NodeJS.ProcessEnv, "openai"),
).toBe("openrouter");
});
it("returns openrouter when OPENAI_BASE_URL points at OpenRouter", () => {
expect(
inferOpenAiCompatibleBiller(
{ OPENAI_BASE_URL: "https://openrouter.ai/api/v1" } as NodeJS.ProcessEnv,
"openai",
),
).toBe("openrouter");
});
it("returns fallback when no OpenRouter markers are present", () => {
expect(
inferOpenAiCompatibleBiller(
{ OPENAI_BASE_URL: "https://api.openai.com/v1" } as NodeJS.ProcessEnv,
"openai",
),
).toBe("openai");
});
});

View File

@@ -0,0 +1,20 @@
function readEnv(env: NodeJS.ProcessEnv, key: string): string | null {
const value = env[key];
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
export function inferOpenAiCompatibleBiller(
env: NodeJS.ProcessEnv,
fallback: string | null = "openai",
): string | null {
const explicitOpenRouterKey = readEnv(env, "OPENROUTER_API_KEY");
if (explicitOpenRouterKey) return "openrouter";
const baseUrl =
readEnv(env, "OPENAI_BASE_URL") ??
readEnv(env, "OPENAI_API_BASE") ??
readEnv(env, "OPENAI_API_BASE_URL");
if (baseUrl && /openrouter\.ai/i.test(baseUrl)) return "openrouter";
return fallback;
}

View File

@@ -12,19 +12,42 @@ export type {
AdapterEnvironmentTestStatus,
AdapterEnvironmentTestResult,
AdapterEnvironmentTestContext,
AdapterSkillSyncMode,
AdapterSkillState,
AdapterSkillOrigin,
AdapterSkillEntry,
AdapterSkillSnapshot,
AdapterSkillContext,
AdapterSessionCodec,
AdapterModel,
HireApprovedPayload,
HireApprovedHookResult,
ServerAdapterModule,
QuotaWindow,
ProviderQuotaResult,
TranscriptEntry,
StdoutLineParser,
CLIAdapterModule,
CreateConfigValues,
} from "./types.js";
export type {
SessionCompactionPolicy,
NativeContextManagement,
AdapterSessionManagement,
ResolvedSessionCompactionPolicy,
} from "./session-compaction.js";
export {
ADAPTER_SESSION_MANAGEMENT,
LEGACY_SESSIONED_ADAPTER_TYPES,
getAdapterSessionManagement,
readSessionCompactionOverride,
resolveSessionCompactionPolicy,
hasSessionCompactionThresholds,
} from "./session-compaction.js";
export {
REDACTED_HOME_PATH_USER,
redactHomePathUserSegments,
redactHomePathUserSegmentsInValue,
redactTranscriptEntryPaths,
} from "./log-redaction.js";
export { inferOpenAiCompatibleBiller } from "./billing.js";

View File

@@ -1,19 +1,29 @@
import type { TranscriptEntry } from "./types.js";
export const REDACTED_HOME_PATH_USER = "[]";
export const REDACTED_HOME_PATH_USER = "*";
export interface HomePathRedactionOptions {
enabled?: boolean;
}
function maskHomePathUserSegment(value: string) {
const trimmed = value.trim();
if (!trimmed) return REDACTED_HOME_PATH_USER;
return `${trimmed[0]}${"*".repeat(Math.max(1, Array.from(trimmed).length - 1))}`;
}
const HOME_PATH_PATTERNS = [
{
regex: /\/Users\/[^/\\\s]+/g,
replace: `/Users/${REDACTED_HOME_PATH_USER}`,
regex: /\/Users\/([^/\\\s]+)/g,
replace: (_match: string, user: string) => `/Users/${maskHomePathUserSegment(user)}`,
},
{
regex: /\/home\/[^/\\\s]+/g,
replace: `/home/${REDACTED_HOME_PATH_USER}`,
regex: /\/home\/([^/\\\s]+)/g,
replace: (_match: string, user: string) => `/home/${maskHomePathUserSegment(user)}`,
},
{
regex: /([A-Za-z]:\\Users\\)[^\\/\s]+/g,
replace: `$1${REDACTED_HOME_PATH_USER}`,
regex: /([A-Za-z]:\\Users\\)([^\\/\s]+)/g,
replace: (_match: string, prefix: string, user: string) => `${prefix}${maskHomePathUserSegment(user)}`,
},
] as const;
@@ -23,7 +33,8 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
return proto === Object.prototype || proto === null;
}
export function redactHomePathUserSegments(text: string): string {
export function redactHomePathUserSegments(text: string, opts?: HomePathRedactionOptions): string {
if (opts?.enabled === false) return text;
let result = text;
for (const pattern of HOME_PATH_PATTERNS) {
result = result.replace(pattern.regex, pattern.replace);
@@ -31,12 +42,12 @@ export function redactHomePathUserSegments(text: string): string {
return result;
}
export function redactHomePathUserSegmentsInValue<T>(value: T): T {
export function redactHomePathUserSegmentsInValue<T>(value: T, opts?: HomePathRedactionOptions): T {
if (typeof value === "string") {
return redactHomePathUserSegments(value) as T;
return redactHomePathUserSegments(value, opts) as T;
}
if (Array.isArray(value)) {
return value.map((entry) => redactHomePathUserSegmentsInValue(entry)) as T;
return value.map((entry) => redactHomePathUserSegmentsInValue(entry, opts)) as T;
}
if (!isPlainObject(value)) {
return value;
@@ -44,12 +55,12 @@ export function redactHomePathUserSegmentsInValue<T>(value: T): T {
const redacted: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(value)) {
redacted[key] = redactHomePathUserSegmentsInValue(entry);
redacted[key] = redactHomePathUserSegmentsInValue(entry, opts);
}
return redacted as T;
}
export function redactTranscriptEntryPaths(entry: TranscriptEntry): TranscriptEntry {
export function redactTranscriptEntryPaths(entry: TranscriptEntry, opts?: HomePathRedactionOptions): TranscriptEntry {
switch (entry.kind) {
case "assistant":
case "thinking":
@@ -57,23 +68,27 @@ export function redactTranscriptEntryPaths(entry: TranscriptEntry): TranscriptEn
case "stderr":
case "system":
case "stdout":
return { ...entry, text: redactHomePathUserSegments(entry.text) };
return { ...entry, text: redactHomePathUserSegments(entry.text, opts) };
case "tool_call":
return { ...entry, name: redactHomePathUserSegments(entry.name), input: redactHomePathUserSegmentsInValue(entry.input) };
return {
...entry,
name: redactHomePathUserSegments(entry.name, opts),
input: redactHomePathUserSegmentsInValue(entry.input, opts),
};
case "tool_result":
return { ...entry, content: redactHomePathUserSegments(entry.content) };
return { ...entry, content: redactHomePathUserSegments(entry.content, opts) };
case "init":
return {
...entry,
model: redactHomePathUserSegments(entry.model),
sessionId: redactHomePathUserSegments(entry.sessionId),
model: redactHomePathUserSegments(entry.model, opts),
sessionId: redactHomePathUserSegments(entry.sessionId, opts),
};
case "result":
return {
...entry,
text: redactHomePathUserSegments(entry.text),
subtype: redactHomePathUserSegments(entry.subtype),
errors: entry.errors.map((error) => redactHomePathUserSegments(error)),
text: redactHomePathUserSegments(entry.text, opts),
subtype: redactHomePathUserSegments(entry.subtype, opts),
errors: entry.errors.map((error) => redactHomePathUserSegments(error, opts)),
};
default:
return entry;

View File

@@ -1,6 +1,10 @@
import { spawn, type ChildProcess } from "node:child_process";
import { constants as fsConstants, promises as fs } from "node:fs";
import { constants as fsConstants, promises as fs, type Dirent } from "node:fs";
import path from "node:path";
import type {
AdapterSkillEntry,
AdapterSkillSnapshot,
} from "./types.js";
export interface RunProcessResult {
exitCode: number | null;
@@ -8,6 +12,8 @@ export interface RunProcessResult {
timedOut: boolean;
stdout: string;
stderr: string;
pid: number | null;
startedAt: string | null;
}
interface RunningProcess {
@@ -38,8 +44,30 @@ const PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES = [
];
export interface PaperclipSkillEntry {
name: string;
key: string;
runtimeName: string;
source: string;
required?: boolean;
requiredReason?: string | null;
}
export interface InstalledSkillTarget {
targetPath: string | null;
kind: "symlink" | "directory" | "file";
}
interface PersistentSkillSnapshotOptions {
adapterType: string;
availableEntries: PaperclipSkillEntry[];
desiredSkills: string[];
installed: Map<string, InstalledSkillTarget>;
skillsHome: string;
locationLabel?: string | null;
installedDetail?: string | null;
missingDetail: string;
externalConflictDetail: string;
externalDetail: string;
warnings?: string[];
}
function normalizePathSlashes(value: string): string {
@@ -50,6 +78,49 @@ function isMaintainerOnlySkillTarget(candidate: string): boolean {
return normalizePathSlashes(candidate).includes("/.agents/skills/");
}
function skillLocationLabel(value: string | null | undefined): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function buildManagedSkillOrigin(entry: { required?: boolean }): Pick<
AdapterSkillEntry,
"origin" | "originLabel" | "readOnly"
> {
if (entry.required) {
return {
origin: "paperclip_required",
originLabel: "Required by Paperclip",
readOnly: false,
};
}
return {
origin: "company_managed",
originLabel: "Managed by Paperclip",
readOnly: false,
};
}
function resolveInstalledEntryTarget(
skillsHome: string,
entryName: string,
dirent: Dirent,
linkedPath: string | null,
): InstalledSkillTarget {
const fullPath = path.join(skillsHome, entryName);
if (dirent.isSymbolicLink()) {
return {
targetPath: linkedPath ? path.resolve(path.dirname(fullPath), linkedPath) : null,
kind: "symlink",
};
}
if (dirent.isDirectory()) {
return { targetPath: fullPath, kind: "directory" };
}
return { targetPath: fullPath, kind: "file" };
}
export function parseObject(value: unknown): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return {};
@@ -304,23 +375,172 @@ export async function listPaperclipSkillEntries(
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => ({
name: entry.name,
key: `paperclipai/paperclip/${entry.name}`,
runtimeName: entry.name,
source: path.join(root, entry.name),
required: true,
requiredReason: "Bundled Paperclip skills are always available for local adapters.",
}));
} catch {
return [];
}
}
export async function readInstalledSkillTargets(skillsHome: string): Promise<Map<string, InstalledSkillTarget>> {
const entries = await fs.readdir(skillsHome, { withFileTypes: true }).catch(() => []);
const out = new Map<string, InstalledSkillTarget>();
for (const entry of entries) {
const fullPath = path.join(skillsHome, entry.name);
const linkedPath = entry.isSymbolicLink() ? await fs.readlink(fullPath).catch(() => null) : null;
out.set(entry.name, resolveInstalledEntryTarget(skillsHome, entry.name, entry, linkedPath));
}
return out;
}
export function buildPersistentSkillSnapshot(
options: PersistentSkillSnapshotOptions,
): AdapterSkillSnapshot {
const {
adapterType,
availableEntries,
desiredSkills,
installed,
skillsHome,
locationLabel,
installedDetail,
missingDetail,
externalConflictDetail,
externalDetail,
} = options;
const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry]));
const desiredSet = new Set(desiredSkills);
const entries: AdapterSkillEntry[] = [];
const warnings = [...(options.warnings ?? [])];
for (const available of availableEntries) {
const installedEntry = installed.get(available.runtimeName) ?? null;
const desired = desiredSet.has(available.key);
let state: AdapterSkillEntry["state"] = "available";
let managed = false;
let detail: string | null = null;
if (installedEntry?.targetPath === available.source) {
managed = true;
state = desired ? "installed" : "stale";
detail = installedDetail ?? null;
} else if (installedEntry) {
state = "external";
detail = desired ? externalConflictDetail : externalDetail;
} else if (desired) {
state = "missing";
detail = missingDetail;
}
entries.push({
key: available.key,
runtimeName: available.runtimeName,
desired,
managed,
state,
sourcePath: available.source,
targetPath: path.join(skillsHome, available.runtimeName),
detail,
required: Boolean(available.required),
requiredReason: available.requiredReason ?? null,
...buildManagedSkillOrigin(available),
});
}
for (const desiredSkill of desiredSkills) {
if (availableByKey.has(desiredSkill)) continue;
warnings.push(`Desired skill "${desiredSkill}" is not available from the Paperclip skills directory.`);
entries.push({
key: desiredSkill,
runtimeName: null,
desired: true,
managed: true,
state: "missing",
sourcePath: null,
targetPath: null,
detail: "Paperclip cannot find this skill in the local runtime skills directory.",
origin: "external_unknown",
originLabel: "External or unavailable",
readOnly: false,
});
}
for (const [name, installedEntry] of installed.entries()) {
if (availableEntries.some((entry) => entry.runtimeName === name)) continue;
entries.push({
key: name,
runtimeName: name,
desired: false,
managed: false,
state: "external",
origin: "user_installed",
originLabel: "User-installed",
locationLabel: skillLocationLabel(locationLabel),
readOnly: true,
sourcePath: null,
targetPath: installedEntry.targetPath ?? path.join(skillsHome, name),
detail: externalDetail,
});
}
entries.sort((left, right) => left.key.localeCompare(right.key));
return {
adapterType,
supported: true,
mode: "persistent",
desiredSkills,
entries,
warnings,
};
}
function normalizeConfiguredPaperclipRuntimeSkills(value: unknown): PaperclipSkillEntry[] {
if (!Array.isArray(value)) return [];
const out: PaperclipSkillEntry[] = [];
for (const rawEntry of value) {
const entry = parseObject(rawEntry);
const key = asString(entry.key, asString(entry.name, "")).trim();
const runtimeName = asString(entry.runtimeName, asString(entry.name, "")).trim();
const source = asString(entry.source, "").trim();
if (!key || !runtimeName || !source) continue;
out.push({
key,
runtimeName,
source,
required: asBoolean(entry.required, false),
requiredReason:
typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0
? entry.requiredReason.trim()
: null,
});
}
return out;
}
export async function readPaperclipRuntimeSkillEntries(
config: Record<string, unknown>,
moduleDir: string,
additionalCandidates: string[] = [],
): Promise<PaperclipSkillEntry[]> {
const configuredEntries = normalizeConfiguredPaperclipRuntimeSkills(config.paperclipRuntimeSkills);
if (configuredEntries.length > 0) return configuredEntries;
return listPaperclipSkillEntries(moduleDir, additionalCandidates);
}
export async function readPaperclipSkillMarkdown(
moduleDir: string,
skillName: string,
skillKey: string,
): Promise<string | null> {
const normalized = skillName.trim().toLowerCase();
const normalized = skillKey.trim().toLowerCase();
if (!normalized) return null;
const entries = await listPaperclipSkillEntries(moduleDir);
const match = entries.find((entry) => entry.name === normalized);
const match = entries.find((entry) => entry.key === normalized);
if (!match) return null;
try {
@@ -330,6 +550,89 @@ export async function readPaperclipSkillMarkdown(
}
}
export function readPaperclipSkillSyncPreference(config: Record<string, unknown>): {
explicit: boolean;
desiredSkills: string[];
} {
const raw = config.paperclipSkillSync;
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return { explicit: false, desiredSkills: [] };
}
const syncConfig = raw as Record<string, unknown>;
const desiredValues = syncConfig.desiredSkills;
const desired = Array.isArray(desiredValues)
? desiredValues
.filter((value): value is string => typeof value === "string")
.map((value) => value.trim())
.filter(Boolean)
: [];
return {
explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"),
desiredSkills: Array.from(new Set(desired)),
};
}
function canonicalizeDesiredPaperclipSkillReference(
reference: string,
availableEntries: Array<{ key: string; runtimeName?: string | null }>,
): string {
const normalizedReference = reference.trim().toLowerCase();
if (!normalizedReference) return "";
const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference);
if (exactKey) return exactKey.key;
const byRuntimeName = availableEntries.filter((entry) =>
typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference,
);
if (byRuntimeName.length === 1) return byRuntimeName[0]!.key;
const slugMatches = availableEntries.filter((entry) =>
entry.key.trim().toLowerCase().split("/").pop() === normalizedReference,
);
if (slugMatches.length === 1) return slugMatches[0]!.key;
return normalizedReference;
}
export function resolvePaperclipDesiredSkillNames(
config: Record<string, unknown>,
availableEntries: Array<{ key: string; runtimeName?: string | null; required?: boolean }>,
): string[] {
const preference = readPaperclipSkillSyncPreference(config);
const requiredSkills = availableEntries
.filter((entry) => entry.required)
.map((entry) => entry.key);
if (!preference.explicit) {
return Array.from(new Set(requiredSkills));
}
const desiredSkills = preference.desiredSkills
.map((reference) => canonicalizeDesiredPaperclipSkillReference(reference, availableEntries))
.filter(Boolean);
return Array.from(new Set([...requiredSkills, ...desiredSkills]));
}
export function writePaperclipSkillSyncPreference(
config: Record<string, unknown>,
desiredSkills: string[],
): Record<string, unknown> {
const next = { ...config };
const raw = next.paperclipSkillSync;
const current =
typeof raw === "object" && raw !== null && !Array.isArray(raw)
? { ...(raw as Record<string, unknown>) }
: {};
current.desiredSkills = Array.from(
new Set(
desiredSkills
.map((value) => value.trim())
.filter(Boolean),
),
);
next.paperclipSkillSync = current;
return next;
}
export async function ensurePaperclipSkillSymlink(
source: string,
target: string,
@@ -423,6 +726,7 @@ export async function runChildProcess(
graceSec: number;
onLog: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
onLogError?: (err: unknown, runId: string, message: string) => void;
onSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void>;
stdin?: string;
},
): Promise<RunProcessResult> {
@@ -455,12 +759,19 @@ export async function runChildProcess(
shell: false,
stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"],
}) as ChildProcessWithEvents;
const startedAt = new Date().toISOString();
if (opts.stdin != null && child.stdin) {
child.stdin.write(opts.stdin);
child.stdin.end();
}
if (typeof child.pid === "number" && child.pid > 0 && opts.onSpawn) {
void opts.onSpawn({ pid: child.pid, startedAt }).catch((err) => {
onLogError(err, runId, "failed to record child process metadata");
});
}
runningProcesses.set(runId, { child, graceSec: opts.graceSec });
let timedOut = false;
@@ -519,6 +830,8 @@ export async function runChildProcess(
timedOut,
stdout,
stderr,
pid: child.pid ?? null,
startedAt,
});
});
});

View File

@@ -0,0 +1,175 @@
export interface SessionCompactionPolicy {
enabled: boolean;
maxSessionRuns: number;
maxRawInputTokens: number;
maxSessionAgeHours: number;
}
export type NativeContextManagement = "confirmed" | "likely" | "unknown" | "none";
export interface AdapterSessionManagement {
supportsSessionResume: boolean;
nativeContextManagement: NativeContextManagement;
defaultSessionCompaction: SessionCompactionPolicy;
}
export interface ResolvedSessionCompactionPolicy {
policy: SessionCompactionPolicy;
adapterSessionManagement: AdapterSessionManagement | null;
explicitOverride: Partial<SessionCompactionPolicy>;
source: "adapter_default" | "agent_override" | "legacy_fallback";
}
const DEFAULT_SESSION_COMPACTION_POLICY: SessionCompactionPolicy = {
enabled: true,
maxSessionRuns: 200,
maxRawInputTokens: 2_000_000,
maxSessionAgeHours: 72,
};
// Adapters with native context management still participate in session resume,
// but Paperclip should not rotate them using threshold-based compaction.
const ADAPTER_MANAGED_SESSION_POLICY: SessionCompactionPolicy = {
enabled: true,
maxSessionRuns: 0,
maxRawInputTokens: 0,
maxSessionAgeHours: 0,
};
export const LEGACY_SESSIONED_ADAPTER_TYPES = new Set([
"claude_local",
"codex_local",
"cursor",
"gemini_local",
"opencode_local",
"pi_local",
]);
export const ADAPTER_SESSION_MANAGEMENT: Record<string, AdapterSessionManagement> = {
claude_local: {
supportsSessionResume: true,
nativeContextManagement: "confirmed",
defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY,
},
codex_local: {
supportsSessionResume: true,
nativeContextManagement: "confirmed",
defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY,
},
cursor: {
supportsSessionResume: true,
nativeContextManagement: "unknown",
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
},
gemini_local: {
supportsSessionResume: true,
nativeContextManagement: "unknown",
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
},
opencode_local: {
supportsSessionResume: true,
nativeContextManagement: "unknown",
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
},
pi_local: {
supportsSessionResume: true,
nativeContextManagement: "unknown",
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
},
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readBoolean(value: unknown): boolean | undefined {
if (typeof value === "boolean") return value;
if (typeof value === "number") {
if (value === 1) return true;
if (value === 0) return false;
return undefined;
}
if (typeof value !== "string") return undefined;
const normalized = value.trim().toLowerCase();
if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") {
return true;
}
if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") {
return false;
}
return undefined;
}
function readNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) {
return Math.max(0, Math.floor(value));
}
if (typeof value !== "string") return undefined;
const parsed = Number(value.trim());
return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : undefined;
}
export function getAdapterSessionManagement(adapterType: string | null | undefined): AdapterSessionManagement | null {
if (!adapterType) return null;
return ADAPTER_SESSION_MANAGEMENT[adapterType] ?? null;
}
export function readSessionCompactionOverride(runtimeConfig: unknown): Partial<SessionCompactionPolicy> {
const runtime = isRecord(runtimeConfig) ? runtimeConfig : {};
const heartbeat = isRecord(runtime.heartbeat) ? runtime.heartbeat : {};
const compaction = isRecord(
heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction,
)
? (heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction) as Record<string, unknown>
: {};
const explicit: Partial<SessionCompactionPolicy> = {};
const enabled = readBoolean(compaction.enabled);
const maxSessionRuns = readNumber(compaction.maxSessionRuns);
const maxRawInputTokens = readNumber(compaction.maxRawInputTokens);
const maxSessionAgeHours = readNumber(compaction.maxSessionAgeHours);
if (enabled !== undefined) explicit.enabled = enabled;
if (maxSessionRuns !== undefined) explicit.maxSessionRuns = maxSessionRuns;
if (maxRawInputTokens !== undefined) explicit.maxRawInputTokens = maxRawInputTokens;
if (maxSessionAgeHours !== undefined) explicit.maxSessionAgeHours = maxSessionAgeHours;
return explicit;
}
export function resolveSessionCompactionPolicy(
adapterType: string | null | undefined,
runtimeConfig: unknown,
): ResolvedSessionCompactionPolicy {
const adapterSessionManagement = getAdapterSessionManagement(adapterType);
const explicitOverride = readSessionCompactionOverride(runtimeConfig);
const hasExplicitOverride = Object.keys(explicitOverride).length > 0;
const fallbackEnabled = Boolean(adapterType && LEGACY_SESSIONED_ADAPTER_TYPES.has(adapterType));
const basePolicy = adapterSessionManagement?.defaultSessionCompaction ?? {
...DEFAULT_SESSION_COMPACTION_POLICY,
enabled: fallbackEnabled,
};
return {
policy: {
enabled: explicitOverride.enabled ?? basePolicy.enabled,
maxSessionRuns: explicitOverride.maxSessionRuns ?? basePolicy.maxSessionRuns,
maxRawInputTokens: explicitOverride.maxRawInputTokens ?? basePolicy.maxRawInputTokens,
maxSessionAgeHours: explicitOverride.maxSessionAgeHours ?? basePolicy.maxSessionAgeHours,
},
adapterSessionManagement,
explicitOverride,
source: hasExplicitOverride
? "agent_override"
: adapterSessionManagement
? "adapter_default"
: "legacy_fallback",
};
}
export function hasSessionCompactionThresholds(policy: Pick<
SessionCompactionPolicy,
"maxSessionRuns" | "maxRawInputTokens" | "maxSessionAgeHours"
>) {
return policy.maxSessionRuns > 0 || policy.maxRawInputTokens > 0 || policy.maxSessionAgeHours > 0;
}

View File

@@ -30,7 +30,15 @@ export interface UsageSummary {
cachedInputTokens?: number;
}
export type AdapterBillingType = "api" | "subscription" | "unknown";
export type AdapterBillingType =
| "api"
| "subscription"
| "metered_api"
| "subscription_included"
| "subscription_overage"
| "credits"
| "fixed"
| "unknown";
export interface AdapterRuntimeServiceReport {
id?: string | null;
@@ -68,6 +76,7 @@ export interface AdapterExecutionResult {
sessionParams?: Record<string, unknown> | null;
sessionDisplayId?: string | null;
provider?: string | null;
biller?: string | null;
model?: string | null;
billingType?: AdapterBillingType | null;
costUsd?: number | null;
@@ -111,6 +120,7 @@ export interface AdapterExecutionContext {
context: Record<string, unknown>;
onLog: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
onMeta?: (meta: AdapterInvocationMeta) => Promise<void>;
onSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void>;
authToken?: string;
}
@@ -138,6 +148,55 @@ export interface AdapterEnvironmentTestResult {
testedAt: string;
}
export type AdapterSkillSyncMode = "unsupported" | "persistent" | "ephemeral";
export type AdapterSkillState =
| "available"
| "configured"
| "installed"
| "missing"
| "stale"
| "external";
export type AdapterSkillOrigin =
| "company_managed"
| "paperclip_required"
| "user_installed"
| "external_unknown";
export interface AdapterSkillEntry {
key: string;
runtimeName: string | null;
desired: boolean;
managed: boolean;
required?: boolean;
requiredReason?: string | null;
state: AdapterSkillState;
origin?: AdapterSkillOrigin;
originLabel?: string | null;
locationLabel?: string | null;
readOnly?: boolean;
sourcePath?: string | null;
targetPath?: string | null;
detail?: string | null;
}
export interface AdapterSkillSnapshot {
adapterType: string;
supported: boolean;
mode: AdapterSkillSyncMode;
desiredSkills: string[];
entries: AdapterSkillEntry[];
warnings: string[];
}
export interface AdapterSkillContext {
agentId: string;
companyId: string;
adapterType: string;
config: Record<string, unknown>;
}
export interface AdapterEnvironmentTestContext {
companyId: string;
adapterType: string;
@@ -171,11 +230,45 @@ export interface HireApprovedHookResult {
detail?: Record<string, unknown>;
}
// ---------------------------------------------------------------------------
// Quota window types — used by adapters that can report provider quota/rate-limit state
// ---------------------------------------------------------------------------
/** a single rate-limit or usage window returned by a provider quota API */
export interface QuotaWindow {
/** human label, e.g. "5h", "7d", "Sonnet 7d", "Credits" */
label: string;
/** percent of the window already consumed (0-100), null when not reported */
usedPercent: number | null;
/** iso timestamp when this window resets, null when not reported */
resetsAt: string | null;
/** free-form value label for credit-style windows, e.g. "$4.20 remaining" */
valueLabel: string | null;
/** optional supporting text, e.g. reset details or provider-specific notes */
detail?: string | null;
}
/** result for one provider from getQuotaWindows() */
export interface ProviderQuotaResult {
/** provider slug, e.g. "anthropic", "openai" */
provider: string;
/** source label when the provider reports where the quota data came from */
source?: string | null;
/** true when the fetch succeeded and windows is populated */
ok: boolean;
/** error message when ok is false */
error?: string;
windows: QuotaWindow[];
}
export interface ServerAdapterModule {
type: string;
execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult>;
testEnvironment(ctx: AdapterEnvironmentTestContext): Promise<AdapterEnvironmentTestResult>;
listSkills?: (ctx: AdapterSkillContext) => Promise<AdapterSkillSnapshot>;
syncSkills?: (ctx: AdapterSkillContext, desiredSkills: string[]) => Promise<AdapterSkillSnapshot>;
sessionCodec?: AdapterSessionCodec;
sessionManagement?: import("./session-compaction.js").AdapterSessionManagement;
supportsLocalAgentJwt?: boolean;
models?: AdapterModel[];
listModels?: () => Promise<AdapterModel[]>;
@@ -188,6 +281,12 @@ export interface ServerAdapterModule {
payload: HireApprovedPayload,
adapterConfig: Record<string, unknown>,
) => Promise<HireApprovedHookResult>;
/**
* Optional: fetch live provider quota/rate-limit windows for this adapter.
* Returns a ProviderQuotaResult so the server can aggregate across adapters
* without knowing provider-specific credential paths or API shapes.
*/
getQuotaWindows?: () => Promise<ProviderQuotaResult>;
}
// ---------------------------------------------------------------------------
@@ -199,7 +298,7 @@ export type TranscriptEntry =
| { kind: "thinking"; ts: string; text: string; delta?: boolean }
| { kind: "user"; ts: string; text: string }
| { kind: "tool_call"; ts: string; name: string; input: unknown; toolUseId?: string }
| { kind: "tool_result"; ts: string; toolUseId: string; content: string; isError: boolean }
| { kind: "tool_result"; ts: string; toolUseId: string; toolName?: string; content: string; isError: boolean }
| { kind: "init"; ts: string; model: string; sessionId: string }
| { kind: "result"; ts: string; text: string; inputTokens: number; outputTokens: number; cachedTokens: number; costUsd: number; subtype: string; isError: boolean; errors: string[] }
| { kind: "stderr"; ts: string; text: string }

View File

@@ -1,5 +1,13 @@
# @paperclipai/adapter-claude-local
## 0.3.1
### Patch Changes
- Stable release preparation for 0.3.1
- Updated dependencies
- @paperclipai/adapter-utils@0.3.1
## 0.3.0
### Minor Changes

View File

@@ -1,6 +1,16 @@
{
"name": "@paperclipai/adapter-claude-local",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapters/claude-local"
},
"type": "module",
"exports": {
".": "./src/index.ts",
@@ -38,7 +48,9 @@
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"probe:quota": "pnpm exec tsx src/cli/quota-probe.ts --json",
"probe:quota:raw": "pnpm exec tsx src/cli/quota-probe.ts --json --raw-cli"
},
"dependencies": {
"@paperclipai/adapter-utils": "workspace:*",

View File

@@ -0,0 +1,124 @@
#!/usr/bin/env node
import {
captureClaudeCliUsageText,
fetchClaudeCliQuota,
fetchClaudeQuota,
getQuotaWindows,
parseClaudeCliUsageText,
readClaudeAuthStatus,
readClaudeToken,
} from "../server/quota.js";
interface ProbeArgs {
json: boolean;
includeRawCli: boolean;
oauthOnly: boolean;
cliOnly: boolean;
}
function parseArgs(argv: string[]): ProbeArgs {
return {
json: argv.includes("--json"),
includeRawCli: argv.includes("--raw-cli"),
oauthOnly: argv.includes("--oauth-only"),
cliOnly: argv.includes("--cli-only"),
};
}
function stringifyError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.oauthOnly && args.cliOnly) {
throw new Error("Choose either --oauth-only or --cli-only, not both.");
}
const authStatus = await readClaudeAuthStatus();
const token = await readClaudeToken();
const result: Record<string, unknown> = {
timestamp: new Date().toISOString(),
authStatus,
tokenAvailable: token != null,
};
if (!args.cliOnly) {
if (!token) {
result.oauth = {
ok: false,
error: "No Claude OAuth access token found in local credentials files.",
windows: [],
};
} else {
try {
result.oauth = {
ok: true,
windows: await fetchClaudeQuota(token),
};
} catch (error) {
result.oauth = {
ok: false,
error: stringifyError(error),
windows: [],
};
}
}
}
if (!args.oauthOnly) {
try {
const rawCliText = args.includeRawCli ? await captureClaudeCliUsageText() : null;
const windows = rawCliText ? parseClaudeCliUsageText(rawCliText) : await fetchClaudeCliQuota();
result.cli = rawCliText
? {
ok: true,
windows,
rawText: rawCliText,
}
: {
ok: true,
windows,
};
} catch (error) {
result.cli = {
ok: false,
error: stringifyError(error),
windows: [],
};
}
}
if (!args.oauthOnly && !args.cliOnly) {
try {
result.aggregated = await getQuotaWindows();
} catch (error) {
result.aggregated = {
ok: false,
error: stringifyError(error),
};
}
}
const oauthOk = (result.oauth as { ok?: boolean } | undefined)?.ok === true;
const cliOk = (result.cli as { ok?: boolean } | undefined)?.ok === true;
const aggregatedOk = (result.aggregated as { ok?: boolean } | undefined)?.ok === true;
const ok = oauthOk || cliOk || aggregatedOk;
if (args.json || process.stdout.isTTY === false) {
console.log(JSON.stringify({ ok, ...result }, null, 2));
} else {
console.log(`timestamp: ${result.timestamp}`);
console.log(`auth: ${JSON.stringify(authStatus)}`);
console.log(`tokenAvailable: ${token != null}`);
if (result.oauth) console.log(`oauth: ${JSON.stringify(result.oauth, null, 2)}`);
if (result.cli) console.log(`cli: ${JSON.stringify(result.cli, null, 2)}`);
if (result.aggregated) console.log(`aggregated: ${JSON.stringify(result.aggregated, null, 2)}`);
}
if (!ok) process.exitCode = 1;
}
await main();

View File

@@ -12,6 +12,7 @@ import {
parseObject,
parseJson,
buildPaperclipEnv,
readPaperclipRuntimeSkillEntries,
joinPromptSections,
redactEnvForLogs,
ensureAbsoluteDirectory,
@@ -27,40 +28,32 @@ import {
isClaudeMaxTurnsResult,
isClaudeUnknownSessionError,
} from "./parse.js";
import { resolveClaudeDesiredSkillNames } from "./skills.js";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
const PAPERCLIP_SKILLS_CANDIDATES = [
path.resolve(__moduleDir, "../../skills"), // published: <pkg>/dist/server/ -> <pkg>/skills/
path.resolve(__moduleDir, "../../../../../skills"), // dev: src/server/ -> repo root/skills/
];
async function resolvePaperclipSkillsDir(): Promise<string | null> {
for (const candidate of PAPERCLIP_SKILLS_CANDIDATES) {
const isDir = await fs.stat(candidate).then((s) => s.isDirectory()).catch(() => false);
if (isDir) return candidate;
}
return null;
}
/**
* Create a tmpdir with `.claude/skills/` containing symlinks to skills from
* the repo's `skills/` directory, so `--add-dir` makes Claude Code discover
* them as proper registered skills.
*/
async function buildSkillsDir(): Promise<string> {
async function buildSkillsDir(config: Record<string, unknown>): Promise<string> {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-skills-"));
const target = path.join(tmp, ".claude", "skills");
await fs.mkdir(target, { recursive: true });
const skillsDir = await resolvePaperclipSkillsDir();
if (!skillsDir) return tmp;
const entries = await fs.readdir(skillsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
await fs.symlink(
path.join(skillsDir, entry.name),
path.join(target, entry.name),
);
}
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const desiredNames = new Set(
resolveClaudeDesiredSkillNames(
config,
availableEntries,
),
);
for (const entry of availableEntries) {
if (!desiredNames.has(entry.key)) continue;
await fs.symlink(
entry.source,
path.join(target, entry.runtimeName),
);
}
return tmp;
}
@@ -122,6 +115,7 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise<Cl
const workspaceRepoRef = asString(workspaceContext.repoRef, "") || null;
const workspaceBranch = asString(workspaceContext.branchName, "") || null;
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "") || null;
const agentHome = asString(workspaceContext.agentHome, "") || null;
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
? context.paperclipWorkspaces.filter(
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
@@ -216,6 +210,9 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise<Cl
if (workspaceWorktreePath) {
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
}
if (agentHome) {
env.AGENT_HOME = agentHome;
}
if (workspaceHints.length > 0) {
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
}
@@ -299,7 +296,7 @@ export async function runClaudeLogin(input: {
}
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
const { runId, agent, runtime, config, context, onLog, onMeta, authToken } = ctx;
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
const promptTemplate = asString(
config.promptTemplate,
@@ -336,8 +333,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
graceSec,
extraArgs,
} = runtimeConfig;
const billingType = resolveClaudeBillingType(env);
const skillsDir = await buildSkillsDir();
const effectiveEnv = Object.fromEntries(
Object.entries({ ...process.env, ...env }).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
const billingType = resolveClaudeBillingType(effectiveEnv);
const skillsDir = await buildSkillsDir(config);
// When instructionsFilePath is configured, create a combined temp file that
// includes both the file content and the path directive, so we only need
@@ -360,7 +362,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const sessionId = canResumeSession ? runtimeSessionId : null;
if (runtimeSessionId && !canResumeSession) {
await onLog(
"stderr",
"stdout",
`[paperclip] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
);
}
@@ -446,6 +448,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
stdin: prompt,
timeoutSec,
graceSec,
onSpawn,
onLog,
});
@@ -543,6 +546,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
sessionParams: resolvedSessionParams,
sessionDisplayId: resolvedSessionId,
provider: "anthropic",
biller: "anthropic",
model: parsedStream.model || asString(parsed.model, model),
billingType,
costUsd: parsedStream.costUsd ?? asNumber(parsed.total_cost_usd, 0),
@@ -562,7 +566,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
isClaudeUnknownSessionError(initial.parsed)
) {
await onLog(
"stderr",
"stdout",
`[paperclip] Claude resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
);
const retry = await runAttempt(null);

View File

@@ -1,4 +1,5 @@
export { execute, runClaudeLogin } from "./execute.js";
export { listClaudeSkills, syncClaudeSkills } from "./skills.js";
export { testEnvironment } from "./test.js";
export {
parseClaudeStreamJson,
@@ -6,6 +7,18 @@ export {
isClaudeMaxTurnsResult,
isClaudeUnknownSessionError,
} from "./parse.js";
export {
getQuotaWindows,
readClaudeAuthStatus,
readClaudeToken,
fetchClaudeQuota,
fetchClaudeCliQuota,
captureClaudeCliUsageText,
parseClaudeCliUsageText,
toPercent,
fetchWithTimeout,
claudeConfigDir,
} from "./quota.js";
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
function readNonEmptyString(value: unknown): string | null {

View File

@@ -0,0 +1,531 @@
import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import type { ProviderQuotaResult, QuotaWindow } from "@paperclipai/adapter-utils";
const execFileAsync = promisify(execFile);
const CLAUDE_USAGE_SOURCE_OAUTH = "anthropic-oauth";
const CLAUDE_USAGE_SOURCE_CLI = "claude-cli";
export function claudeConfigDir(): string {
const fromEnv = process.env.CLAUDE_CONFIG_DIR;
if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim();
return path.join(os.homedir(), ".claude");
}
function hasNonEmptyProcessEnv(key: string): boolean {
const value = process.env[key];
return typeof value === "string" && value.trim().length > 0;
}
function createClaudeQuotaEnv(): Record<string, string> {
const env: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (typeof value !== "string") continue;
if (key.startsWith("ANTHROPIC_")) continue;
env[key] = value;
}
return env;
}
function stripBackspaces(text: string): string {
let out = "";
for (const char of text) {
if (char === "\b") {
out = out.slice(0, -1);
} else {
out += char;
}
}
return out;
}
function stripAnsi(text: string): string {
return text
.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, "")
.replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
}
function cleanTerminalText(text: string): string {
return stripAnsi(stripBackspaces(text))
.replace(/\u0000/g, "")
.replace(/\r/g, "\n");
}
function normalizeForLabelSearch(text: string): string {
return text.toLowerCase().replace(/[^a-z0-9]+/g, "");
}
function trimToLatestUsagePanel(text: string): string | null {
const lower = text.toLowerCase();
const settingsIndex = lower.lastIndexOf("settings:");
if (settingsIndex < 0) return null;
let tail = text.slice(settingsIndex);
const tailLower = tail.toLowerCase();
if (!tailLower.includes("usage")) return null;
if (!tailLower.includes("current session") && !tailLower.includes("loading usage")) return null;
const stopMarkers = [
"status dialog dismissed",
"checking for updates",
"press ctrl-c again to exit",
];
let stopIndex = -1;
for (const marker of stopMarkers) {
const markerIndex = tailLower.indexOf(marker);
if (markerIndex >= 0 && (stopIndex === -1 || markerIndex < stopIndex)) {
stopIndex = markerIndex;
}
}
if (stopIndex >= 0) {
tail = tail.slice(0, stopIndex);
}
return tail;
}
async function readClaudeTokenFromFile(credPath: string): Promise<string | null> {
let raw: string;
try {
raw = await fs.readFile(credPath, "utf8");
} catch {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const obj = parsed as Record<string, unknown>;
const oauth = obj["claudeAiOauth"];
if (typeof oauth !== "object" || oauth === null) return null;
const token = (oauth as Record<string, unknown>)["accessToken"];
return typeof token === "string" && token.length > 0 ? token : null;
}
interface ClaudeAuthStatus {
loggedIn: boolean;
authMethod: string | null;
subscriptionType: string | null;
}
export async function readClaudeAuthStatus(): Promise<ClaudeAuthStatus | null> {
try {
const { stdout } = await execFileAsync("claude", ["auth", "status"], {
env: process.env,
timeout: 5_000,
maxBuffer: 1024 * 1024,
});
const parsed = JSON.parse(stdout) as Record<string, unknown>;
return {
loggedIn: parsed.loggedIn === true,
authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null,
subscriptionType: typeof parsed.subscriptionType === "string" ? parsed.subscriptionType : null,
};
} catch {
return null;
}
}
function describeClaudeSubscriptionAuth(status: ClaudeAuthStatus | null): string | null {
if (!status?.loggedIn || status.authMethod !== "claude.ai") return null;
return status.subscriptionType
? `Claude is logged in via claude.ai (${status.subscriptionType})`
: "Claude is logged in via claude.ai";
}
export async function readClaudeToken(): Promise<string | null> {
const configDir = claudeConfigDir();
for (const filename of [".credentials.json", "credentials.json"]) {
const token = await readClaudeTokenFromFile(path.join(configDir, filename));
if (token) return token;
}
return null;
}
interface AnthropicUsageWindow {
utilization?: number | null;
resets_at?: string | null;
}
interface AnthropicExtraUsage {
is_enabled?: boolean | null;
monthly_limit?: number | null;
used_credits?: number | null;
utilization?: number | null;
currency?: string | null;
}
interface AnthropicUsageResponse {
five_hour?: AnthropicUsageWindow | null;
seven_day?: AnthropicUsageWindow | null;
seven_day_sonnet?: AnthropicUsageWindow | null;
seven_day_opus?: AnthropicUsageWindow | null;
extra_usage?: AnthropicExtraUsage | null;
}
function formatCurrencyAmount(value: number, currency: string | null | undefined): string {
const code = typeof currency === "string" && currency.trim().length > 0 ? currency.trim().toUpperCase() : "USD";
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: code,
maximumFractionDigits: 2,
}).format(value);
}
function formatExtraUsageLabel(extraUsage: AnthropicExtraUsage): string | null {
const monthlyLimit = extraUsage.monthly_limit;
const usedCredits = extraUsage.used_credits;
if (
typeof monthlyLimit !== "number" ||
!Number.isFinite(monthlyLimit) ||
typeof usedCredits !== "number" ||
!Number.isFinite(usedCredits)
) {
return null;
}
return `${formatCurrencyAmount(usedCredits, extraUsage.currency)} / ${formatCurrencyAmount(monthlyLimit, extraUsage.currency)}`;
}
/** Convert a 0-1 utilization fraction to a 0-100 integer percent. Returns null for null/undefined input. */
export function toPercent(utilization: number | null | undefined): number | null {
if (utilization == null) return null;
return Math.min(100, Math.round(utilization * 100));
}
/** fetch with an abort-based timeout so a hanging provider api doesn't block the response indefinitely */
export async function fetchWithTimeout(url: string, init: RequestInit, ms = 8000): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fetch(url, { ...init, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
export async function fetchClaudeQuota(token: string): Promise<QuotaWindow[]> {
const resp = await fetchWithTimeout("https://api.anthropic.com/api/oauth/usage", {
headers: {
Authorization: `Bearer ${token}`,
"anthropic-beta": "oauth-2025-04-20",
},
});
if (!resp.ok) throw new Error(`anthropic usage api returned ${resp.status}`);
const body = (await resp.json()) as AnthropicUsageResponse;
const windows: QuotaWindow[] = [];
if (body.five_hour != null) {
windows.push({
label: "Current session",
usedPercent: toPercent(body.five_hour.utilization),
resetsAt: body.five_hour.resets_at ?? null,
valueLabel: null,
detail: null,
});
}
if (body.seven_day != null) {
windows.push({
label: "Current week (all models)",
usedPercent: toPercent(body.seven_day.utilization),
resetsAt: body.seven_day.resets_at ?? null,
valueLabel: null,
detail: null,
});
}
if (body.seven_day_sonnet != null) {
windows.push({
label: "Current week (Sonnet only)",
usedPercent: toPercent(body.seven_day_sonnet.utilization),
resetsAt: body.seven_day_sonnet.resets_at ?? null,
valueLabel: null,
detail: null,
});
}
if (body.seven_day_opus != null) {
windows.push({
label: "Current week (Opus only)",
usedPercent: toPercent(body.seven_day_opus.utilization),
resetsAt: body.seven_day_opus.resets_at ?? null,
valueLabel: null,
detail: null,
});
}
if (body.extra_usage != null) {
windows.push({
label: "Extra usage",
usedPercent: body.extra_usage.is_enabled === false ? null : toPercent(body.extra_usage.utilization),
resetsAt: null,
valueLabel:
body.extra_usage.is_enabled === false
? "Not enabled"
: formatExtraUsageLabel(body.extra_usage),
detail:
body.extra_usage.is_enabled === false
? "Extra usage not enabled"
: "Monthly extra usage pool",
});
}
return windows;
}
function usageOutputLooksRelevant(text: string): boolean {
const normalized = normalizeForLabelSearch(text);
return normalized.includes("currentsession")
|| normalized.includes("currentweek")
|| normalized.includes("loadingusage")
|| normalized.includes("failedtoloadusagedata")
|| normalized.includes("tokenexpired")
|| normalized.includes("authenticationerror")
|| normalized.includes("ratelimited");
}
function usageOutputLooksComplete(text: string): boolean {
const normalized = normalizeForLabelSearch(text);
if (
normalized.includes("failedtoloadusagedata")
|| normalized.includes("tokenexpired")
|| normalized.includes("authenticationerror")
|| normalized.includes("ratelimited")
) {
return true;
}
return normalized.includes("currentsession")
&& (normalized.includes("currentweek") || normalized.includes("extrausage"))
&& /[0-9]{1,3}(?:\.[0-9]+)?%/i.test(text);
}
function extractUsageError(text: string): string | null {
const lower = text.toLowerCase();
const compact = lower.replace(/\s+/g, "");
if (lower.includes("token_expired") || lower.includes("token has expired")) {
return "Claude CLI token expired. Run `claude login` to refresh.";
}
if (lower.includes("authentication_error")) {
return "Claude CLI authentication error. Run `claude login`.";
}
if (lower.includes("rate_limit_error") || lower.includes("rate limited") || compact.includes("ratelimited")) {
return "Claude CLI usage endpoint is rate limited right now. Please try again later.";
}
if (lower.includes("failed to load usage data") || compact.includes("failedtoloadusagedata")) {
return "Claude CLI could not load usage data. Open the CLI and retry `/usage`.";
}
return null;
}
function percentFromLine(line: string): number | null {
const match = line.match(/([0-9]{1,3}(?:\.[0-9]+)?)\s*%/i);
if (!match) return null;
const rawValue = Number(match[1]);
if (!Number.isFinite(rawValue)) return null;
const clamped = Math.min(100, Math.max(0, rawValue));
const lower = line.toLowerCase();
if (lower.includes("remaining") || lower.includes("left") || lower.includes("available")) {
return Math.max(0, Math.min(100, Math.round(100 - clamped)));
}
return Math.round(clamped);
}
function isQuotaLabel(line: string): boolean {
const normalized = normalizeForLabelSearch(line);
return normalized === "currentsession"
|| normalized === "currentweekallmodels"
|| normalized === "currentweeksonnetonly"
|| normalized === "currentweeksonnet"
|| normalized === "currentweekopusonly"
|| normalized === "currentweekopus"
|| normalized === "extrausage";
}
function canonicalQuotaLabel(line: string): string {
switch (normalizeForLabelSearch(line)) {
case "currentsession":
return "Current session";
case "currentweekallmodels":
return "Current week (all models)";
case "currentweeksonnetonly":
case "currentweeksonnet":
return "Current week (Sonnet only)";
case "currentweekopusonly":
case "currentweekopus":
return "Current week (Opus only)";
case "extrausage":
return "Extra usage";
default:
return line;
}
}
function formatClaudeCliDetail(label: string, lines: string[]): string | null {
const normalizedLabel = normalizeForLabelSearch(label);
if (normalizedLabel === "extrausage") {
const compact = lines.join(" ").replace(/\s+/g, "").toLowerCase();
if (compact.includes("extrausagenotenabled")) {
return "Extra usage not enabled • /extra-usage to enable";
}
const firstLine = lines.find((line) => line.trim().length > 0) ?? null;
return firstLine;
}
const resetLine = lines.find((line) => /^resets/i.test(line) || normalizeForLabelSearch(line).startsWith("resets"));
if (!resetLine) return null;
return resetLine
.replace(/^Resets/i, "Resets ")
.replace(/([A-Z][a-z]{2})(\d)/g, "$1 $2")
.replace(/(\d)at(\d)/g, "$1 at $2")
.replace(/(am|pm)\(/gi, "$1 (")
.replace(/([A-Za-z])\(/g, "$1 (")
.replace(/\s+/g, " ")
.trim();
}
export function parseClaudeCliUsageText(text: string): QuotaWindow[] {
const cleaned = trimToLatestUsagePanel(cleanTerminalText(text)) ?? cleanTerminalText(text);
const usageError = extractUsageError(cleaned);
if (usageError) throw new Error(usageError);
const lines = cleaned
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const sections: Array<{ label: string; lines: string[] }> = [];
let current: { label: string; lines: string[] } | null = null;
for (const line of lines) {
if (isQuotaLabel(line)) {
if (current) sections.push(current);
current = { label: canonicalQuotaLabel(line), lines: [] };
continue;
}
if (current) current.lines.push(line);
}
if (current) sections.push(current);
const windows = sections.map<QuotaWindow>((section) => {
const usedPercent = section.lines.map(percentFromLine).find((value) => value != null) ?? null;
return {
label: section.label,
usedPercent,
resetsAt: null,
valueLabel: null,
detail: formatClaudeCliDetail(section.label, section.lines),
};
});
if (!windows.some((window) => normalizeForLabelSearch(window.label) === "currentsession")) {
throw new Error("Could not parse Claude CLI usage output.");
}
return windows;
}
function quoteForShell(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`;
}
function buildClaudeCliShellProbeCommand(): string {
const feed = "(sleep 2; printf '/usage\\r'; sleep 6; printf '\\033'; sleep 1; printf '\\003')";
const claudeCommand = "claude --tools \"\"";
if (process.platform === "darwin") {
return `${feed} | script -q /dev/null ${claudeCommand}`;
}
return `${feed} | script -q -e -f -c ${quoteForShell(claudeCommand)} /dev/null`;
}
export async function captureClaudeCliUsageText(timeoutMs = 12_000): Promise<string> {
const command = buildClaudeCliShellProbeCommand();
try {
const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
env: createClaudeQuotaEnv(),
timeout: timeoutMs,
maxBuffer: 8 * 1024 * 1024,
});
const output = `${stdout}${stderr}`;
const cleaned = cleanTerminalText(output);
if (usageOutputLooksComplete(cleaned)) return output;
throw new Error("Claude CLI usage probe ended before rendering usage.");
} catch (error) {
const stdout =
typeof error === "object" && error !== null && "stdout" in error && typeof error.stdout === "string"
? error.stdout
: "";
const stderr =
typeof error === "object" && error !== null && "stderr" in error && typeof error.stderr === "string"
? error.stderr
: "";
const output = `${stdout}${stderr}`;
const cleaned = cleanTerminalText(output);
if (usageOutputLooksComplete(cleaned)) return output;
if (usageOutputLooksRelevant(cleaned)) {
throw new Error("Claude CLI usage probe ended before rendering usage.");
}
throw error instanceof Error ? error : new Error(String(error));
}
}
export async function fetchClaudeCliQuota(): Promise<QuotaWindow[]> {
const rawText = await captureClaudeCliUsageText();
return parseClaudeCliUsageText(rawText);
}
function formatProviderError(source: string, error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return `${source}: ${message}`;
}
export async function getQuotaWindows(): Promise<ProviderQuotaResult> {
const authStatus = await readClaudeAuthStatus();
const authDescription = describeClaudeSubscriptionAuth(authStatus);
const token = await readClaudeToken();
const errors: string[] = [];
if (token) {
try {
const windows = await fetchClaudeQuota(token);
return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_OAUTH, ok: true, windows };
} catch (error) {
errors.push(formatProviderError("Anthropic OAuth usage", error));
}
}
try {
const windows = await fetchClaudeCliQuota();
return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_CLI, ok: true, windows };
} catch (error) {
errors.push(formatProviderError("Claude CLI /usage", error));
}
if (hasNonEmptyProcessEnv("ANTHROPIC_API_KEY") && !authDescription) {
return {
provider: "anthropic",
ok: false,
error:
errors[0]
?? "ANTHROPIC_API_KEY is set and no local Claude subscription session is available for quota polling",
windows: [],
};
}
if (authDescription) {
return {
provider: "anthropic",
ok: false,
error:
errors.length > 0
? `${authDescription}, but quota polling failed (${errors.join("; ")})`
: `${authDescription}, but Paperclip could not load subscription quota data`,
windows: [],
};
}
return {
provider: "anthropic",
ok: false,
error: errors[0] ?? "no local claude auth token",
windows: [],
};
}

View File

@@ -0,0 +1,121 @@
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type {
AdapterSkillContext,
AdapterSkillEntry,
AdapterSkillSnapshot,
} from "@paperclipai/adapter-utils";
import {
readPaperclipRuntimeSkillEntries,
readInstalledSkillTargets,
resolvePaperclipDesiredSkillNames,
} from "@paperclipai/adapter-utils/server-utils";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
function asString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function resolveClaudeSkillsHome(config: Record<string, unknown>) {
const env =
typeof config.env === "object" && config.env !== null && !Array.isArray(config.env)
? (config.env as Record<string, unknown>)
: {};
const configuredHome = asString(env.HOME);
const home = configuredHome ? path.resolve(configuredHome) : os.homedir();
return path.join(home, ".claude", "skills");
}
async function buildClaudeSkillSnapshot(config: Record<string, unknown>): Promise<AdapterSkillSnapshot> {
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry]));
const desiredSkills = resolvePaperclipDesiredSkillNames(config, availableEntries);
const desiredSet = new Set(desiredSkills);
const skillsHome = resolveClaudeSkillsHome(config);
const installed = await readInstalledSkillTargets(skillsHome);
const entries: AdapterSkillEntry[] = availableEntries.map((entry) => ({
key: entry.key,
runtimeName: entry.runtimeName,
desired: desiredSet.has(entry.key),
managed: true,
state: desiredSet.has(entry.key) ? "configured" : "available",
origin: entry.required ? "paperclip_required" : "company_managed",
originLabel: entry.required ? "Required by Paperclip" : "Managed by Paperclip",
readOnly: false,
sourcePath: entry.source,
targetPath: null,
detail: desiredSet.has(entry.key)
? "Will be mounted into the ephemeral Claude skill directory on the next run."
: null,
required: Boolean(entry.required),
requiredReason: entry.requiredReason ?? null,
}));
const warnings: string[] = [];
for (const desiredSkill of desiredSkills) {
if (availableByKey.has(desiredSkill)) continue;
warnings.push(`Desired skill "${desiredSkill}" is not available from the Paperclip skills directory.`);
entries.push({
key: desiredSkill,
runtimeName: null,
desired: true,
managed: true,
state: "missing",
origin: "external_unknown",
originLabel: "External or unavailable",
readOnly: false,
sourcePath: undefined,
targetPath: undefined,
detail: "Paperclip cannot find this skill in the local runtime skills directory.",
});
}
for (const [name, installedEntry] of installed.entries()) {
if (availableEntries.some((entry) => entry.runtimeName === name)) continue;
entries.push({
key: name,
runtimeName: name,
desired: false,
managed: false,
state: "external",
origin: "user_installed",
originLabel: "User-installed",
locationLabel: "~/.claude/skills",
readOnly: true,
sourcePath: null,
targetPath: installedEntry.targetPath ?? path.join(skillsHome, name),
detail: "Installed outside Paperclip management in the Claude skills home.",
});
}
entries.sort((left, right) => left.key.localeCompare(right.key));
return {
adapterType: "claude_local",
supported: true,
mode: "ephemeral",
desiredSkills,
entries,
warnings,
};
}
export async function listClaudeSkills(ctx: AdapterSkillContext): Promise<AdapterSkillSnapshot> {
return buildClaudeSkillSnapshot(ctx.config);
}
export async function syncClaudeSkills(
ctx: AdapterSkillContext,
_desiredSkills: string[],
): Promise<AdapterSkillSnapshot> {
return buildClaudeSkillSnapshot(ctx.config);
}
export function resolveClaudeDesiredSkillNames(
config: Record<string, unknown>,
availableEntries: Array<{ key: string; required?: boolean }>,
) {
return resolvePaperclipDesiredSkillNames(config, availableEntries);
}

View File

@@ -1,5 +1,13 @@
# @paperclipai/adapter-codex-local
## 0.3.1
### Patch Changes
- Stable release preparation for 0.3.1
- Updated dependencies
- @paperclipai/adapter-utils@0.3.1
## 0.3.0
### Minor Changes

View File

@@ -1,6 +1,16 @@
{
"name": "@paperclipai/adapter-codex-local",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapters/codex-local"
},
"type": "module",
"exports": {
".": "./src/index.ts",
@@ -38,7 +48,8 @@
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"probe:quota": "pnpm exec tsx src/cli/quota-probe.ts --json"
},
"dependencies": {
"@paperclipai/adapter-utils": "workspace:*",

View File

@@ -0,0 +1,112 @@
#!/usr/bin/env node
import {
fetchCodexQuota,
fetchCodexRpcQuota,
getQuotaWindows,
readCodexAuthInfo,
readCodexToken,
} from "../server/quota.js";
interface ProbeArgs {
json: boolean;
rpcOnly: boolean;
whamOnly: boolean;
}
function parseArgs(argv: string[]): ProbeArgs {
return {
json: argv.includes("--json"),
rpcOnly: argv.includes("--rpc-only"),
whamOnly: argv.includes("--wham-only"),
};
}
function stringifyError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.rpcOnly && args.whamOnly) {
throw new Error("Choose either --rpc-only or --wham-only, not both.");
}
const auth = await readCodexAuthInfo();
const token = await readCodexToken();
const result: Record<string, unknown> = {
timestamp: new Date().toISOString(),
auth,
tokenAvailable: token != null,
};
if (!args.whamOnly) {
try {
result.rpc = {
ok: true,
...(await fetchCodexRpcQuota()),
};
} catch (error) {
result.rpc = {
ok: false,
error: stringifyError(error),
windows: [],
};
}
}
if (!args.rpcOnly) {
if (!token) {
result.wham = {
ok: false,
error: "No local Codex auth token found in ~/.codex/auth.json.",
windows: [],
};
} else {
try {
result.wham = {
ok: true,
windows: await fetchCodexQuota(token.token, token.accountId),
};
} catch (error) {
result.wham = {
ok: false,
error: stringifyError(error),
windows: [],
};
}
}
}
if (!args.rpcOnly && !args.whamOnly) {
try {
result.aggregated = await getQuotaWindows();
} catch (error) {
result.aggregated = {
ok: false,
error: stringifyError(error),
};
}
}
const rpcOk = (result.rpc as { ok?: boolean } | undefined)?.ok === true;
const whamOk = (result.wham as { ok?: boolean } | undefined)?.ok === true;
const aggregatedOk = (result.aggregated as { ok?: boolean } | undefined)?.ok === true;
const ok = rpcOk || whamOk || aggregatedOk;
if (args.json || process.stdout.isTTY === false) {
console.log(JSON.stringify({ ok, ...result }, null, 2));
} else {
console.log(`timestamp: ${result.timestamp}`);
console.log(`auth: ${JSON.stringify(auth)}`);
console.log(`tokenAvailable: ${token != null}`);
if (result.rpc) console.log(`rpc: ${JSON.stringify(result.rpc, null, 2)}`);
if (result.wham) console.log(`wham: ${JSON.stringify(result.wham, null, 2)}`);
if (result.aggregated) console.log(`aggregated: ${JSON.stringify(result.aggregated, null, 2)}`);
}
if (!ok) process.exitCode = 1;
}
await main();

View File

@@ -40,7 +40,8 @@ Operational fields:
Notes:
- Prompts are piped via stdin (Codex receives "-" prompt argument).
- Paperclip auto-injects local skills into Codex personal skills dir ("$CODEX_HOME/skills" or "~/.codex/skills") when missing, so Codex can discover "$paperclip" and related skills.
- Paperclip injects desired local skills into the active workspace's ".agents/skills" directory at execution time so Codex can discover "$paperclip" and related skills without coupling them to the user's login home.
- Unless explicitly overridden in adapter config, Paperclip runs Codex with a per-company managed CODEX_HOME under the active Paperclip instance and seeds auth/config from the shared Codex home (the CODEX_HOME env var, when set, or ~/.codex).
- Some model/tool combinations reject certain effort levels (for example minimal with web search enabled).
- When Paperclip realizes a workspace/runtime for a run, it injects PAPERCLIP_WORKSPACE_* and PAPERCLIP_RUNTIME_* env vars for agent-side tooling.
`;

View File

@@ -6,6 +6,7 @@ import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
const TRUTHY_ENV_RE = /^(1|true|yes|on)$/i;
const COPIED_SHARED_FILES = ["config.json", "config.toml", "instructions.md"] as const;
const SYMLINKED_SHARED_FILES = ["auth.json"] as const;
const DEFAULT_PAPERCLIP_INSTANCE_ID = "default";
function nonEmpty(value: string | undefined): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
@@ -15,25 +16,26 @@ export async function pathExists(candidate: string): Promise<boolean> {
return fs.access(candidate).then(() => true).catch(() => false);
}
export function resolveCodexHomeDir(env: NodeJS.ProcessEnv = process.env): string {
export function resolveSharedCodexHomeDir(
env: NodeJS.ProcessEnv = process.env,
): string {
const fromEnv = nonEmpty(env.CODEX_HOME);
if (fromEnv) return path.resolve(fromEnv);
return path.join(os.homedir(), ".codex");
return fromEnv ? path.resolve(fromEnv) : path.join(os.homedir(), ".codex");
}
function isWorktreeMode(env: NodeJS.ProcessEnv): boolean {
return TRUTHY_ENV_RE.test(env.PAPERCLIP_IN_WORKTREE ?? "");
}
function resolveWorktreeCodexHomeDir(env: NodeJS.ProcessEnv): string | null {
if (!isWorktreeMode(env)) return null;
const paperclipHome = nonEmpty(env.PAPERCLIP_HOME);
if (!paperclipHome) return null;
const instanceId = nonEmpty(env.PAPERCLIP_INSTANCE_ID);
if (instanceId) {
return path.resolve(paperclipHome, "instances", instanceId, "codex-home");
}
return path.resolve(paperclipHome, "codex-home");
export function resolveManagedCodexHomeDir(
env: NodeJS.ProcessEnv,
companyId?: string,
): string {
const paperclipHome = nonEmpty(env.PAPERCLIP_HOME) ?? path.resolve(os.homedir(), ".paperclip");
const instanceId = nonEmpty(env.PAPERCLIP_INSTANCE_ID) ?? DEFAULT_PAPERCLIP_INSTANCE_ID;
return companyId
? path.resolve(paperclipHome, "instances", instanceId, "companies", companyId, "codex-home")
: path.resolve(paperclipHome, "instances", instanceId, "codex-home");
}
async function ensureParentDir(target: string): Promise<void> {
@@ -69,14 +71,14 @@ async function ensureCopiedFile(target: string, source: string): Promise<void> {
await fs.copyFile(source, target);
}
export async function prepareWorktreeCodexHome(
export async function prepareManagedCodexHome(
env: NodeJS.ProcessEnv,
onLog: AdapterExecutionContext["onLog"],
): Promise<string | null> {
const targetHome = resolveWorktreeCodexHomeDir(env);
if (!targetHome) return null;
companyId?: string,
): Promise<string> {
const targetHome = resolveManagedCodexHomeDir(env, companyId);
const sourceHome = resolveCodexHomeDir(env);
const sourceHome = resolveSharedCodexHomeDir(env);
if (path.resolve(sourceHome) === path.resolve(targetHome)) return targetHome;
await fs.mkdir(targetHome, { recursive: true });
@@ -94,8 +96,8 @@ export async function prepareWorktreeCodexHome(
}
await onLog(
"stderr",
`[paperclip] Using worktree-isolated Codex home "${targetHome}" (seeded from "${sourceHome}").\n`,
"stdout",
`[paperclip] Using ${isWorktreeMode(env) ? "worktree-isolated" : "Paperclip-managed"} Codex home "${targetHome}" (seeded from "${sourceHome}").\n`,
);
return targetHome;
}

View File

@@ -1,7 +1,7 @@
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
import { inferOpenAiCompatibleBiller, type AdapterExecutionContext, type AdapterExecutionResult } from "@paperclipai/adapter-utils";
import {
asString,
asNumber,
@@ -14,14 +14,15 @@ import {
ensureCommandResolvable,
ensurePaperclipSkillSymlink,
ensurePathInEnv,
listPaperclipSkillEntries,
removeMaintainerOnlySkillSymlinks,
readPaperclipRuntimeSkillEntries,
resolvePaperclipDesiredSkillNames,
renderTemplate,
joinPromptSections,
runChildProcess,
} from "@paperclipai/adapter-utils/server-utils";
import { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
import { pathExists, prepareWorktreeCodexHome, resolveCodexHomeDir } from "./codex-home.js";
import { pathExists, prepareManagedCodexHome, resolveManagedCodexHomeDir } from "./codex-home.js";
import { resolveCodexDesiredSkillNames } from "./skills.js";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
const CODEX_ROLLOUT_NOISE_RE =
@@ -61,6 +62,12 @@ function resolveCodexBillingType(env: Record<string, string>): "api" | "subscrip
return hasNonEmptyEnvValue(env, "OPENAI_API_KEY") ? "api" : "subscription";
}
function resolveCodexBiller(env: Record<string, string>, billingType: "api" | "subscription"): string {
const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env, "openai");
if (openAiCompatibleBiller === "openrouter") return "openrouter";
return billingType === "subscription" ? "chatgpt" : openAiCompatibleBiller ?? "openai";
}
async function isLikelyPaperclipRepoRoot(candidate: string): Promise<boolean> {
const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([
pathExists(path.join(candidate, "pnpm-workspace.yaml")),
@@ -72,11 +79,17 @@ async function isLikelyPaperclipRepoRoot(candidate: string): Promise<boolean> {
return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir;
}
async function isLikelyPaperclipRuntimeSkillSource(candidate: string, skillName: string): Promise<boolean> {
async function isLikelyPaperclipRuntimeSkillPath(
candidate: string,
skillName: string,
options: { requireSkillMarkdown?: boolean } = {},
): Promise<boolean> {
if (path.basename(candidate) !== skillName) return false;
const skillsRoot = path.dirname(candidate);
if (path.basename(skillsRoot) !== "skills") return false;
if (!(await pathExists(path.join(candidate, "SKILL.md")))) return false;
if (options.requireSkillMarkdown !== false && !(await pathExists(path.join(candidate, "SKILL.md")))) {
return false;
}
let cursor = path.dirname(skillsRoot);
for (let depth = 0; depth < 6; depth += 1) {
@@ -89,9 +102,47 @@ async function isLikelyPaperclipRuntimeSkillSource(candidate: string, skillName:
return false;
}
async function pruneBrokenUnavailablePaperclipSkillSymlinks(
skillsHome: string,
allowedSkillNames: Iterable<string>,
onLog: AdapterExecutionContext["onLog"],
) {
const allowed = new Set(Array.from(allowedSkillNames));
const entries = await fs.readdir(skillsHome, { withFileTypes: true }).catch(() => []);
for (const entry of entries) {
if (allowed.has(entry.name) || !entry.isSymbolicLink()) continue;
const target = path.join(skillsHome, entry.name);
const linkedPath = await fs.readlink(target).catch(() => null);
if (!linkedPath) continue;
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
if (await pathExists(resolvedLinkedPath)) continue;
if (
!(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.name, {
requireSkillMarkdown: false,
}))
) {
continue;
}
await fs.unlink(target).catch(() => {});
await onLog(
"stdout",
`[paperclip] Removed stale Codex skill "${entry.name}" from ${skillsHome}\n`,
);
}
}
function resolveCodexWorkspaceSkillsDir(cwd: string): string {
return path.join(cwd, ".agents", "skills");
}
type EnsureCodexSkillsInjectedOptions = {
skillsHome?: string;
skillsEntries?: Awaited<ReturnType<typeof listPaperclipSkillEntries>>;
skillsEntries?: Array<{ key: string; runtimeName: string; source: string }>;
desiredSkillNames?: string[];
linkSkill?: (source: string, target: string) => Promise<void>;
};
@@ -99,24 +150,18 @@ export async function ensureCodexSkillsInjected(
onLog: AdapterExecutionContext["onLog"],
options: EnsureCodexSkillsInjectedOptions = {},
) {
const skillsEntries = options.skillsEntries ?? await listPaperclipSkillEntries(__moduleDir);
const allSkillsEntries = options.skillsEntries ?? await readPaperclipRuntimeSkillEntries({}, __moduleDir);
const desiredSkillNames =
options.desiredSkillNames ?? allSkillsEntries.map((entry) => entry.key);
const desiredSet = new Set(desiredSkillNames);
const skillsEntries = allSkillsEntries.filter((entry) => desiredSet.has(entry.key));
if (skillsEntries.length === 0) return;
const skillsHome = options.skillsHome ?? path.join(resolveCodexHomeDir(process.env), "skills");
const skillsHome = options.skillsHome ?? resolveCodexWorkspaceSkillsDir(process.cwd());
await fs.mkdir(skillsHome, { recursive: true });
const removedSkills = await removeMaintainerOnlySkillSymlinks(
skillsHome,
skillsEntries.map((entry) => entry.name),
);
for (const skillName of removedSkills) {
await onLog(
"stderr",
`[paperclip] Removed maintainer-only Codex skill "${skillName}" from ${skillsHome}\n`,
);
}
const linkSkill = options.linkSkill;
for (const entry of skillsEntries) {
const target = path.join(skillsHome, entry.name);
const target = path.join(skillsHome, entry.runtimeName);
try {
const existing = await fs.lstat(target).catch(() => null);
@@ -128,7 +173,7 @@ export async function ensureCodexSkillsInjected(
if (
resolvedLinkedPath &&
resolvedLinkedPath !== entry.source &&
(await isLikelyPaperclipRuntimeSkillSource(resolvedLinkedPath, entry.name))
(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.runtimeName))
) {
await fs.unlink(target);
if (linkSkill) {
@@ -137,8 +182,8 @@ export async function ensureCodexSkillsInjected(
await fs.symlink(entry.source, target);
}
await onLog(
"stderr",
`[paperclip] Repaired Codex skill "${entry.name}" into ${skillsHome}\n`,
"stdout",
`[paperclip] Repaired Codex skill "${entry.runtimeName}" into ${skillsHome}\n`,
);
continue;
}
@@ -148,20 +193,26 @@ export async function ensureCodexSkillsInjected(
if (result === "skipped") continue;
await onLog(
"stderr",
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.name}" into ${skillsHome}\n`,
"stdout",
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.runtimeName}" into ${skillsHome}\n`,
);
} catch (err) {
await onLog(
"stderr",
`[paperclip] Failed to inject Codex skill "${entry.name}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
`[paperclip] Failed to inject Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
);
}
}
await pruneBrokenUnavailablePaperclipSkillSymlinks(
skillsHome,
skillsEntries.map((entry) => entry.runtimeName),
onLog,
);
}
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
const { runId, agent, runtime, config, context, onLog, onMeta, authToken } = ctx;
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
const promptTemplate = asString(
config.promptTemplate,
@@ -188,6 +239,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
const workspaceBranch = asString(workspaceContext.branchName, "");
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
const agentHome = asString(workspaceContext.agentHome, "");
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
? context.paperclipWorkspaces.filter(
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
@@ -213,20 +265,27 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0
? path.resolve(envConfig.CODEX_HOME.trim())
: null;
const codexSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const desiredSkillNames = resolveCodexDesiredSkillNames(config, codexSkillEntries);
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
const preparedWorktreeCodexHome =
configuredCodexHome ? null : await prepareWorktreeCodexHome(process.env, onLog);
const effectiveCodexHome = configuredCodexHome ?? preparedWorktreeCodexHome;
const preparedManagedCodexHome =
configuredCodexHome ? null : await prepareManagedCodexHome(process.env, onLog, agent.companyId);
const defaultCodexHome = resolveManagedCodexHomeDir(process.env, agent.companyId);
const effectiveCodexHome = configuredCodexHome ?? preparedManagedCodexHome ?? defaultCodexHome;
await fs.mkdir(effectiveCodexHome, { recursive: true });
const codexWorkspaceSkillsDir = resolveCodexWorkspaceSkillsDir(cwd);
await ensureCodexSkillsInjected(
onLog,
effectiveCodexHome ? { skillsHome: path.join(effectiveCodexHome, "skills") } : {},
{
skillsHome: codexWorkspaceSkillsDir,
skillsEntries: codexSkillEntries,
desiredSkillNames,
},
);
const hasExplicitApiKey =
typeof envConfig.PAPERCLIP_API_KEY === "string" && envConfig.PAPERCLIP_API_KEY.trim().length > 0;
const env: Record<string, string> = { ...buildPaperclipEnv(agent) };
if (effectiveCodexHome) {
env.CODEX_HOME = effectiveCodexHome;
}
env.CODEX_HOME = effectiveCodexHome;
env.PAPERCLIP_RUN_ID = runId;
const wakeTaskId =
(typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
@@ -293,6 +352,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (workspaceWorktreePath) {
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
}
if (agentHome) {
env.AGENT_HOME = agentHome;
}
if (workspaceHints.length > 0) {
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
}
@@ -311,8 +373,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (!hasExplicitApiKey && authToken) {
env.PAPERCLIP_API_KEY = authToken;
}
const billingType = resolveCodexBillingType(env);
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
const effectiveEnv = Object.fromEntries(
Object.entries({ ...process.env, ...env }).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
const billingType = resolveCodexBillingType(effectiveEnv);
const runtimeEnv = ensurePathInEnv(effectiveEnv);
await ensureCommandResolvable(command, cwd, runtimeEnv);
const timeoutSec = asNumber(config.timeoutSec, 0);
@@ -332,7 +399,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const sessionId = canResumeSession ? runtimeSessionId : null;
if (runtimeSessionId && !canResumeSession) {
await onLog(
"stderr",
"stdout",
`[paperclip] Codex session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
);
}
@@ -349,13 +416,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
`Resolve any relative file references from ${instructionsDir}.\n\n`;
instructionsChars = instructionsPrefix.length;
await onLog(
"stderr",
"stdout",
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
await onLog(
"stderr",
"stdout",
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
);
}
@@ -439,6 +506,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
stdin: prompt,
timeoutSec,
graceSec,
onSpawn,
onLog: async (stream, chunk) => {
if (stream !== "stderr") {
await onLog(stream, chunk);
@@ -504,6 +572,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
sessionParams: resolvedSessionParams,
sessionDisplayId: resolvedSessionId,
provider: "openai",
biller: resolveCodexBiller(effectiveEnv, billingType),
model,
billingType,
costUsd: null,
@@ -524,7 +593,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
isCodexUnknownSessionError(initial.proc.stdout, initial.rawStderr)
) {
await onLog(
"stderr",
"stdout",
`[paperclip] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
);
const retry = await runAttempt(null);

View File

@@ -1,6 +1,18 @@
export { execute, ensureCodexSkillsInjected } from "./execute.js";
export { listCodexSkills, syncCodexSkills } from "./skills.js";
export { testEnvironment } from "./test.js";
export { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
export {
getQuotaWindows,
readCodexAuthInfo,
readCodexToken,
fetchCodexQuota,
fetchCodexRpcQuota,
mapCodexRpcQuota,
secondsToWindowLabel,
fetchWithTimeout,
codexHomeDir,
} from "./quota.js";
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
function readNonEmptyString(value: unknown): string | null {

View File

@@ -0,0 +1,556 @@
import { spawn } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { ProviderQuotaResult, QuotaWindow } from "@paperclipai/adapter-utils";
const CODEX_USAGE_SOURCE_RPC = "codex-rpc";
const CODEX_USAGE_SOURCE_WHAM = "codex-wham";
export function codexHomeDir(): string {
const fromEnv = process.env.CODEX_HOME;
if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim();
return path.join(os.homedir(), ".codex");
}
interface CodexLegacyAuthFile {
accessToken?: string | null;
accountId?: string | null;
}
interface CodexTokenBlock {
id_token?: string | null;
access_token?: string | null;
refresh_token?: string | null;
account_id?: string | null;
}
interface CodexModernAuthFile {
OPENAI_API_KEY?: string | null;
tokens?: CodexTokenBlock | null;
last_refresh?: string | null;
}
export interface CodexAuthInfo {
accessToken: string;
accountId: string | null;
refreshToken: string | null;
idToken: string | null;
email: string | null;
planType: string | null;
lastRefresh: string | null;
}
function base64UrlDecode(input: string): string | null {
try {
let normalized = input.replace(/-/g, "+").replace(/_/g, "/");
const remainder = normalized.length % 4;
if (remainder > 0) normalized += "=".repeat(4 - remainder);
return Buffer.from(normalized, "base64").toString("utf8");
} catch {
return null;
}
}
function decodeJwtPayload(token: string | null | undefined): Record<string, unknown> | null {
if (typeof token !== "string" || token.trim().length === 0) return null;
const parts = token.split(".");
if (parts.length < 2) return null;
const decoded = base64UrlDecode(parts[1] ?? "");
if (!decoded) return null;
try {
const parsed = JSON.parse(decoded) as unknown;
return typeof parsed === "object" && parsed !== null ? parsed as Record<string, unknown> : null;
} catch {
return null;
}
}
function readNestedString(record: Record<string, unknown>, pathSegments: string[]): string | null {
let current: unknown = record;
for (const segment of pathSegments) {
if (typeof current !== "object" || current === null || Array.isArray(current)) return null;
current = (current as Record<string, unknown>)[segment];
}
return typeof current === "string" && current.trim().length > 0 ? current.trim() : null;
}
function parsePlanAndEmailFromToken(idToken: string | null, accessToken: string | null): {
email: string | null;
planType: string | null;
} {
const payloads = [decodeJwtPayload(idToken), decodeJwtPayload(accessToken)].filter(
(value): value is Record<string, unknown> => value != null,
);
for (const payload of payloads) {
const directEmail = typeof payload.email === "string" ? payload.email : null;
const authBlock =
typeof payload["https://api.openai.com/auth"] === "object" &&
payload["https://api.openai.com/auth"] !== null &&
!Array.isArray(payload["https://api.openai.com/auth"])
? payload["https://api.openai.com/auth"] as Record<string, unknown>
: null;
const profileBlock =
typeof payload["https://api.openai.com/profile"] === "object" &&
payload["https://api.openai.com/profile"] !== null &&
!Array.isArray(payload["https://api.openai.com/profile"])
? payload["https://api.openai.com/profile"] as Record<string, unknown>
: null;
const email =
directEmail
?? (typeof profileBlock?.email === "string" ? profileBlock.email : null)
?? (typeof authBlock?.chatgpt_user_email === "string" ? authBlock.chatgpt_user_email : null);
const planType =
typeof authBlock?.chatgpt_plan_type === "string" ? authBlock.chatgpt_plan_type : null;
if (email || planType) return { email: email ?? null, planType };
}
return { email: null, planType: null };
}
export async function readCodexAuthInfo(): Promise<CodexAuthInfo | null> {
const authPath = path.join(codexHomeDir(), "auth.json");
let raw: string;
try {
raw = await fs.readFile(authPath, "utf8");
} catch {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const obj = parsed as Record<string, unknown>;
const modern = obj as CodexModernAuthFile;
const legacy = obj as CodexLegacyAuthFile;
const accessToken =
legacy.accessToken
?? modern.tokens?.access_token
?? readNestedString(obj, ["tokens", "access_token"]);
if (typeof accessToken !== "string" || accessToken.length === 0) return null;
const accountId =
legacy.accountId
?? modern.tokens?.account_id
?? readNestedString(obj, ["tokens", "account_id"]);
const refreshToken =
modern.tokens?.refresh_token
?? readNestedString(obj, ["tokens", "refresh_token"]);
const idToken =
modern.tokens?.id_token
?? readNestedString(obj, ["tokens", "id_token"]);
const { email, planType } = parsePlanAndEmailFromToken(idToken, accessToken);
return {
accessToken,
accountId:
typeof accountId === "string" && accountId.trim().length > 0 ? accountId.trim() : null,
refreshToken:
typeof refreshToken === "string" && refreshToken.trim().length > 0 ? refreshToken.trim() : null,
idToken:
typeof idToken === "string" && idToken.trim().length > 0 ? idToken.trim() : null,
email,
planType,
lastRefresh:
typeof modern.last_refresh === "string" && modern.last_refresh.trim().length > 0
? modern.last_refresh.trim()
: null,
};
}
export async function readCodexToken(): Promise<{ token: string; accountId: string | null } | null> {
const auth = await readCodexAuthInfo();
if (!auth) return null;
return { token: auth.accessToken, accountId: auth.accountId };
}
interface WhamWindow {
used_percent?: number | null;
limit_window_seconds?: number | null;
reset_at?: string | number | null;
}
interface WhamCredits {
balance?: number | null;
unlimited?: boolean | null;
}
interface WhamUsageResponse {
plan_type?: string | null;
rate_limit?: {
primary_window?: WhamWindow | null;
secondary_window?: WhamWindow | null;
} | null;
credits?: WhamCredits | null;
}
/**
* Map a window duration in seconds to a human-readable label.
* Falls back to the provided fallback string when seconds is null/undefined.
*/
export function secondsToWindowLabel(
seconds: number | null | undefined,
fallback: string,
): string {
if (seconds == null) return fallback;
const hours = seconds / 3600;
if (hours < 6) return "5h";
if (hours <= 24) return "24h";
if (hours <= 168) return "7d";
return `${Math.round(hours / 24)}d`;
}
/** fetch with an abort-based timeout so a hanging provider api doesn't block the response indefinitely */
export async function fetchWithTimeout(
url: string,
init: RequestInit,
ms = 8000,
): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fetch(url, { ...init, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
function normalizeCodexUsedPercent(rawPct: number | null | undefined): number | null {
if (rawPct == null) return null;
return Math.min(100, Math.round(rawPct < 1 ? rawPct * 100 : rawPct));
}
export async function fetchCodexQuota(
token: string,
accountId: string | null,
): Promise<QuotaWindow[]> {
const headers: Record<string, string> = {
Authorization: `Bearer ${token}`,
};
if (accountId) headers["ChatGPT-Account-Id"] = accountId;
const resp = await fetchWithTimeout("https://chatgpt.com/backend-api/wham/usage", { headers });
if (!resp.ok) throw new Error(`chatgpt wham api returned ${resp.status}`);
const body = (await resp.json()) as WhamUsageResponse;
const windows: QuotaWindow[] = [];
const rateLimit = body.rate_limit;
if (rateLimit?.primary_window != null) {
const w = rateLimit.primary_window;
windows.push({
label: "5h limit",
usedPercent: normalizeCodexUsedPercent(w.used_percent),
resetsAt:
typeof w.reset_at === "number"
? unixSecondsToIso(w.reset_at)
: (w.reset_at ?? null),
valueLabel: null,
detail: null,
});
}
if (rateLimit?.secondary_window != null) {
const w = rateLimit.secondary_window;
windows.push({
label: "Weekly limit",
usedPercent: normalizeCodexUsedPercent(w.used_percent),
resetsAt:
typeof w.reset_at === "number"
? unixSecondsToIso(w.reset_at)
: (w.reset_at ?? null),
valueLabel: null,
detail: null,
});
}
if (body.credits != null && body.credits.unlimited !== true) {
const balance = body.credits.balance;
const valueLabel = balance != null ? `$${(balance / 100).toFixed(2)} remaining` : "N/A";
windows.push({
label: "Credits",
usedPercent: null,
resetsAt: null,
valueLabel,
detail: null,
});
}
return windows;
}
interface CodexRpcWindow {
usedPercent?: number | null;
windowDurationMins?: number | null;
resetsAt?: number | null;
}
interface CodexRpcCredits {
hasCredits?: boolean | null;
unlimited?: boolean | null;
balance?: string | number | null;
}
interface CodexRpcLimit {
limitId?: string | null;
limitName?: string | null;
primary?: CodexRpcWindow | null;
secondary?: CodexRpcWindow | null;
credits?: CodexRpcCredits | null;
planType?: string | null;
}
interface CodexRpcRateLimitsResult {
rateLimits?: CodexRpcLimit | null;
rateLimitsByLimitId?: Record<string, CodexRpcLimit> | null;
}
interface CodexRpcAccountResult {
account?: {
type?: string | null;
email?: string | null;
planType?: string | null;
} | null;
requiresOpenaiAuth?: boolean | null;
}
export interface CodexRpcQuotaSnapshot {
windows: QuotaWindow[];
email: string | null;
planType: string | null;
}
function unixSecondsToIso(value: number | null | undefined): string | null {
if (typeof value !== "number" || !Number.isFinite(value)) return null;
return new Date(value * 1000).toISOString();
}
function buildCodexRpcWindow(label: string, window: CodexRpcWindow | null | undefined): QuotaWindow | null {
if (!window) return null;
return {
label,
usedPercent: normalizeCodexUsedPercent(window.usedPercent),
resetsAt: unixSecondsToIso(window.resetsAt),
valueLabel: null,
detail: null,
};
}
function parseCreditBalance(value: string | number | null | undefined): string | null {
if (typeof value === "number" && Number.isFinite(value)) {
return `$${value.toFixed(2)} remaining`;
}
if (typeof value === "string" && value.trim().length > 0) {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return `$${parsed.toFixed(2)} remaining`;
}
return value.trim();
}
return null;
}
export function mapCodexRpcQuota(result: CodexRpcRateLimitsResult, account?: CodexRpcAccountResult | null): CodexRpcQuotaSnapshot {
const windows: QuotaWindow[] = [];
const limitOrder = ["codex"];
const limitsById = result.rateLimitsByLimitId ?? {};
for (const key of Object.keys(limitsById)) {
if (!limitOrder.includes(key)) limitOrder.push(key);
}
const rootLimit = result.rateLimits ?? null;
const allLimits = new Map<string, CodexRpcLimit>();
if (rootLimit?.limitId) allLimits.set(rootLimit.limitId, rootLimit);
for (const [key, value] of Object.entries(limitsById)) {
allLimits.set(key, value);
}
if (!allLimits.has("codex") && rootLimit) allLimits.set("codex", rootLimit);
for (const limitId of limitOrder) {
const limit = allLimits.get(limitId);
if (!limit) continue;
const prefix =
limitId === "codex"
? ""
: `${limit.limitName ?? limitId} · `;
const primary = buildCodexRpcWindow(`${prefix}5h limit`, limit.primary);
if (primary) windows.push(primary);
const secondary = buildCodexRpcWindow(`${prefix}Weekly limit`, limit.secondary);
if (secondary) windows.push(secondary);
if (limitId === "codex" && limit.credits && limit.credits.unlimited !== true) {
windows.push({
label: "Credits",
usedPercent: null,
resetsAt: null,
valueLabel: parseCreditBalance(limit.credits.balance) ?? "N/A",
detail: null,
});
}
}
return {
windows,
email:
typeof account?.account?.email === "string" && account.account.email.trim().length > 0
? account.account.email.trim()
: null,
planType:
typeof account?.account?.planType === "string" && account.account.planType.trim().length > 0
? account.account.planType.trim()
: (typeof rootLimit?.planType === "string" && rootLimit.planType.trim().length > 0 ? rootLimit.planType.trim() : null),
};
}
type PendingRequest = {
resolve: (value: Record<string, unknown>) => void;
reject: (error: Error) => void;
timer: NodeJS.Timeout;
};
class CodexRpcClient {
private proc = spawn(
"codex",
["-s", "read-only", "-a", "untrusted", "app-server"],
{ stdio: ["pipe", "pipe", "pipe"], env: process.env },
);
private nextId = 1;
private buffer = "";
private pending = new Map<number, PendingRequest>();
private stderr = "";
constructor() {
this.proc.stdout.setEncoding("utf8");
this.proc.stderr.setEncoding("utf8");
this.proc.stdout.on("data", (chunk: string) => this.onStdout(chunk));
this.proc.stderr.on("data", (chunk: string) => {
this.stderr += chunk;
});
this.proc.on("exit", () => {
for (const request of this.pending.values()) {
clearTimeout(request.timer);
request.reject(new Error(this.stderr.trim() || "codex app-server closed unexpectedly"));
}
this.pending.clear();
});
}
private onStdout(chunk: string) {
this.buffer += chunk;
while (true) {
const newlineIndex = this.buffer.indexOf("\n");
if (newlineIndex < 0) break;
const line = this.buffer.slice(0, newlineIndex).trim();
this.buffer = this.buffer.slice(newlineIndex + 1);
if (!line) continue;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(line) as Record<string, unknown>;
} catch {
continue;
}
const id = typeof parsed.id === "number" ? parsed.id : null;
if (id == null) continue;
const pending = this.pending.get(id);
if (!pending) continue;
this.pending.delete(id);
clearTimeout(pending.timer);
pending.resolve(parsed);
}
}
private request(method: string, params: Record<string, unknown> = {}, timeoutMs = 6_000): Promise<Record<string, unknown>> {
const id = this.nextId++;
const payload = JSON.stringify({ id, method, params }) + "\n";
return new Promise<Record<string, unknown>>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`codex app-server timed out on ${method}`));
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer });
this.proc.stdin.write(payload);
});
}
private notify(method: string, params: Record<string, unknown> = {}) {
this.proc.stdin.write(JSON.stringify({ method, params }) + "\n");
}
async initialize() {
await this.request("initialize", {
clientInfo: {
name: "paperclip",
version: "0.0.0",
},
});
this.notify("initialized", {});
}
async fetchRateLimits(): Promise<CodexRpcRateLimitsResult> {
const message = await this.request("account/rateLimits/read");
return (message.result as CodexRpcRateLimitsResult | undefined) ?? {};
}
async fetchAccount(): Promise<CodexRpcAccountResult | null> {
try {
const message = await this.request("account/read");
return (message.result as CodexRpcAccountResult | undefined) ?? null;
} catch {
return null;
}
}
async shutdown() {
this.proc.kill("SIGTERM");
}
}
export async function fetchCodexRpcQuota(): Promise<CodexRpcQuotaSnapshot> {
const client = new CodexRpcClient();
try {
await client.initialize();
const [limits, account] = await Promise.all([
client.fetchRateLimits(),
client.fetchAccount(),
]);
return mapCodexRpcQuota(limits, account);
} finally {
await client.shutdown();
}
}
function formatProviderError(source: string, error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return `${source}: ${message}`;
}
export async function getQuotaWindows(): Promise<ProviderQuotaResult> {
const errors: string[] = [];
try {
const rpc = await fetchCodexRpcQuota();
if (rpc.windows.length > 0) {
return { provider: "openai", source: CODEX_USAGE_SOURCE_RPC, ok: true, windows: rpc.windows };
}
} catch (error) {
errors.push(formatProviderError("Codex app-server", error));
}
const auth = await readCodexToken();
if (auth) {
try {
const windows = await fetchCodexQuota(auth.token, auth.accountId);
return { provider: "openai", source: CODEX_USAGE_SOURCE_WHAM, ok: true, windows };
} catch (error) {
errors.push(formatProviderError("ChatGPT WHAM usage", error));
}
} else {
errors.push("no local codex auth token");
}
return {
provider: "openai",
ok: false,
error: errors.join("; "),
windows: [],
};
}

View File

@@ -0,0 +1,87 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import type {
AdapterSkillContext,
AdapterSkillEntry,
AdapterSkillSnapshot,
} from "@paperclipai/adapter-utils";
import {
readPaperclipRuntimeSkillEntries,
resolvePaperclipDesiredSkillNames,
} from "@paperclipai/adapter-utils/server-utils";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
async function buildCodexSkillSnapshot(
config: Record<string, unknown>,
): Promise<AdapterSkillSnapshot> {
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry]));
const desiredSkills = resolvePaperclipDesiredSkillNames(config, availableEntries);
const desiredSet = new Set(desiredSkills);
const entries: AdapterSkillEntry[] = availableEntries.map((entry) => ({
key: entry.key,
runtimeName: entry.runtimeName,
desired: desiredSet.has(entry.key),
managed: true,
state: desiredSet.has(entry.key) ? "configured" : "available",
origin: entry.required ? "paperclip_required" : "company_managed",
originLabel: entry.required ? "Required by Paperclip" : "Managed by Paperclip",
readOnly: false,
sourcePath: entry.source,
targetPath: null,
detail: desiredSet.has(entry.key)
? "Will be linked into the workspace .agents/skills directory on the next run."
: null,
required: Boolean(entry.required),
requiredReason: entry.requiredReason ?? null,
}));
const warnings: string[] = [];
for (const desiredSkill of desiredSkills) {
if (availableByKey.has(desiredSkill)) continue;
warnings.push(`Desired skill "${desiredSkill}" is not available from the Paperclip skills directory.`);
entries.push({
key: desiredSkill,
runtimeName: null,
desired: true,
managed: true,
state: "missing",
origin: "external_unknown",
originLabel: "External or unavailable",
readOnly: false,
sourcePath: null,
targetPath: null,
detail: "Paperclip cannot find this skill in the local runtime skills directory.",
});
}
entries.sort((left, right) => left.key.localeCompare(right.key));
return {
adapterType: "codex_local",
supported: true,
mode: "ephemeral",
desiredSkills,
entries,
warnings,
};
}
export async function listCodexSkills(ctx: AdapterSkillContext): Promise<AdapterSkillSnapshot> {
return buildCodexSkillSnapshot(ctx.config);
}
export async function syncCodexSkills(
ctx: AdapterSkillContext,
_desiredSkills: string[],
): Promise<AdapterSkillSnapshot> {
return buildCodexSkillSnapshot(ctx.config);
}
export function resolveCodexDesiredSkillNames(
config: Record<string, unknown>,
availableEntries: Array<{ key: string; required?: boolean }>,
) {
return resolvePaperclipDesiredSkillNames(config, availableEntries);
}

View File

@@ -1,8 +1,4 @@
import {
redactHomePathUserSegments,
redactHomePathUserSegmentsInValue,
type TranscriptEntry,
} from "@paperclipai/adapter-utils";
import { type TranscriptEntry } from "@paperclipai/adapter-utils";
function safeJsonParse(text: string): unknown {
try {
@@ -43,12 +39,12 @@ function errorText(value: unknown): string {
}
function stringifyUnknown(value: unknown): string {
if (typeof value === "string") return redactHomePathUserSegments(value);
if (typeof value === "string") return value;
if (value === null || value === undefined) return "";
try {
return JSON.stringify(redactHomePathUserSegmentsInValue(value), null, 2);
return JSON.stringify(value, null, 2);
} catch {
return redactHomePathUserSegments(String(value));
return String(value);
}
}
@@ -61,8 +57,8 @@ function parseCommandExecutionItem(
const command = asString(item.command);
const status = asString(item.status);
const exitCode = typeof item.exit_code === "number" && Number.isFinite(item.exit_code) ? item.exit_code : null;
const safeCommand = redactHomePathUserSegments(command);
const output = redactHomePathUserSegments(asString(item.aggregated_output)).replace(/\s+$/, "");
const safeCommand = command;
const output = asString(item.aggregated_output).replace(/\s+$/, "");
if (phase === "started") {
return [{
@@ -109,7 +105,7 @@ function parseFileChangeItem(item: Record<string, unknown>, ts: string): Transcr
.filter((change): change is Record<string, unknown> => Boolean(change))
.map((change) => {
const kind = asString(change.kind, "update");
const path = redactHomePathUserSegments(asString(change.path, "unknown"));
const path = asString(change.path, "unknown");
return `${kind} ${path}`;
});
@@ -131,13 +127,13 @@ function parseCodexItem(
if (itemType === "agent_message") {
const text = asString(item.text);
if (text) return [{ kind: "assistant", ts, text: redactHomePathUserSegments(text) }];
if (text) return [{ kind: "assistant", ts, text }];
return [];
}
if (itemType === "reasoning") {
const text = asString(item.text);
if (text) return [{ kind: "thinking", ts, text: redactHomePathUserSegments(text) }];
if (text) return [{ kind: "thinking", ts, text }];
return [{ kind: "system", ts, text: phase === "started" ? "reasoning started" : "reasoning completed" }];
}
@@ -153,9 +149,9 @@ function parseCodexItem(
return [{
kind: "tool_call",
ts,
name: redactHomePathUserSegments(asString(item.name, "unknown")),
name: asString(item.name, "unknown"),
toolUseId: asString(item.id),
input: redactHomePathUserSegmentsInValue(item.input ?? {}),
input: item.input ?? {},
}];
}
@@ -167,12 +163,12 @@ function parseCodexItem(
asString(item.result) ||
stringifyUnknown(item.content ?? item.output ?? item.result);
const isError = item.is_error === true || asString(item.status) === "error";
return [{ kind: "tool_result", ts, toolUseId, content: redactHomePathUserSegments(content), isError }];
return [{ kind: "tool_result", ts, toolUseId, content, isError }];
}
if (itemType === "error" && phase === "completed") {
const text = errorText(item.message ?? item.error ?? item);
return [{ kind: "stderr", ts, text: redactHomePathUserSegments(text || "error") }];
return [{ kind: "stderr", ts, text: text || "error" }];
}
const id = asString(item.id);
@@ -181,14 +177,14 @@ function parseCodexItem(
return [{
kind: "system",
ts,
text: redactHomePathUserSegments(`item ${phase}: ${itemType || "unknown"}${meta ? ` (${meta})` : ""}`),
text: `item ${phase}: ${itemType || "unknown"}${meta ? ` (${meta})` : ""}`,
}];
}
export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[] {
const parsed = asRecord(safeJsonParse(line));
if (!parsed) {
return [{ kind: "stdout", ts, text: redactHomePathUserSegments(line) }];
return [{ kind: "stdout", ts, text: line }];
}
const type = asString(parsed.type);
@@ -198,8 +194,8 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
return [{
kind: "init",
ts,
model: redactHomePathUserSegments(asString(parsed.model, "codex")),
sessionId: redactHomePathUserSegments(threadId),
model: asString(parsed.model, "codex"),
sessionId: threadId,
}];
}
@@ -221,15 +217,15 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
return [{
kind: "result",
ts,
text: redactHomePathUserSegments(asString(parsed.result)),
text: asString(parsed.result),
inputTokens,
outputTokens,
cachedTokens,
costUsd: asNumber(parsed.total_cost_usd),
subtype: redactHomePathUserSegments(asString(parsed.subtype)),
subtype: asString(parsed.subtype),
isError: parsed.is_error === true,
errors: Array.isArray(parsed.errors)
? parsed.errors.map(errorText).map(redactHomePathUserSegments).filter(Boolean)
? parsed.errors.map(errorText).filter(Boolean)
: [],
}];
}
@@ -243,21 +239,21 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
return [{
kind: "result",
ts,
text: redactHomePathUserSegments(asString(parsed.result)),
text: asString(parsed.result),
inputTokens,
outputTokens,
cachedTokens,
costUsd: asNumber(parsed.total_cost_usd),
subtype: redactHomePathUserSegments(asString(parsed.subtype, "turn.failed")),
subtype: asString(parsed.subtype, "turn.failed"),
isError: true,
errors: message ? [redactHomePathUserSegments(message)] : [],
errors: message ? [message] : [],
}];
}
if (type === "error") {
const message = errorText(parsed.message ?? parsed.error ?? parsed);
return [{ kind: "stderr", ts, text: redactHomePathUserSegments(message || line) }];
return [{ kind: "stderr", ts, text: message || line }];
}
return [{ kind: "stdout", ts, text: redactHomePathUserSegments(line) }];
return [{ kind: "stdout", ts, text: line }];
}

View File

@@ -1,5 +1,13 @@
# @paperclipai/adapter-cursor-local
## 0.3.1
### Patch Changes
- Stable release preparation for 0.3.1
- Updated dependencies
- @paperclipai/adapter-utils@0.3.1
## 0.3.0
### Minor Changes

View File

@@ -1,6 +1,16 @@
{
"name": "@paperclipai/adapter-cursor-local",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapters/cursor-local"
},
"type": "module",
"exports": {
".": "./src/index.ts",

View File

@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
import { inferOpenAiCompatibleBiller, type AdapterExecutionContext, type AdapterExecutionResult } from "@paperclipai/adapter-utils";
import {
asString,
asNumber,
@@ -14,7 +14,8 @@ import {
ensureCommandResolvable,
ensurePaperclipSkillSymlink,
ensurePathInEnv,
listPaperclipSkillEntries,
readPaperclipRuntimeSkillEntries,
resolvePaperclipDesiredSkillNames,
removeMaintainerOnlySkillSymlinks,
renderTemplate,
joinPromptSections,
@@ -47,6 +48,17 @@ function resolveCursorBillingType(env: Record<string, string>): "api" | "subscri
: "subscription";
}
function resolveCursorBiller(
env: Record<string, string>,
billingType: "api" | "subscription",
provider: string | null,
): string {
const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env, null);
if (openAiCompatibleBiller === "openrouter") return "openrouter";
if (billingType === "subscription") return "cursor";
return provider ?? "cursor";
}
function resolveProviderFromModel(model: string): string | null {
const trimmed = model.trim().toLowerCase();
if (!trimmed) return null;
@@ -83,7 +95,7 @@ function cursorSkillsHome(): string {
type EnsureCursorSkillsInjectedOptions = {
skillsDir?: string | null;
skillsEntries?: Array<{ name: string; source: string }>;
skillsEntries?: Array<{ key: string; runtimeName: string; source: string }>;
skillsHome?: string;
linkSkill?: (source: string, target: string) => Promise<void>;
};
@@ -96,8 +108,12 @@ export async function ensureCursorSkillsInjected(
?? (options.skillsDir
? (await fs.readdir(options.skillsDir, { withFileTypes: true }))
.filter((entry) => entry.isDirectory())
.map((entry) => ({ name: entry.name, source: path.join(options.skillsDir!, entry.name) }))
: await listPaperclipSkillEntries(__moduleDir));
.map((entry) => ({
key: entry.name,
runtimeName: entry.name,
source: path.join(options.skillsDir!, entry.name),
}))
: await readPaperclipRuntimeSkillEntries({}, __moduleDir));
if (skillsEntries.length === 0) return;
const skillsHome = options.skillsHome ?? cursorSkillsHome();
@@ -112,7 +128,7 @@ export async function ensureCursorSkillsInjected(
}
const removedSkills = await removeMaintainerOnlySkillSymlinks(
skillsHome,
skillsEntries.map((entry) => entry.name),
skillsEntries.map((entry) => entry.runtimeName),
);
for (const skillName of removedSkills) {
await onLog(
@@ -122,26 +138,26 @@ export async function ensureCursorSkillsInjected(
}
const linkSkill = options.linkSkill ?? ((source: string, target: string) => fs.symlink(source, target));
for (const entry of skillsEntries) {
const target = path.join(skillsHome, entry.name);
const target = path.join(skillsHome, entry.runtimeName);
try {
const result = await ensurePaperclipSkillSymlink(entry.source, target, linkSkill);
if (result === "skipped") continue;
await onLog(
"stderr",
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Cursor skill "${entry.name}" into ${skillsHome}\n`,
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Cursor skill "${entry.key}" into ${skillsHome}\n`,
);
} catch (err) {
await onLog(
"stderr",
`[paperclip] Failed to inject Cursor skill "${entry.name}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
`[paperclip] Failed to inject Cursor skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
);
}
}
}
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
const { runId, agent, runtime, config, context, onLog, onMeta, authToken } = ctx;
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
const promptTemplate = asString(
config.promptTemplate,
@@ -157,6 +173,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const workspaceId = asString(workspaceContext.workspaceId, "");
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
const agentHome = asString(workspaceContext.agentHome, "");
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
? context.paperclipWorkspaces.filter(
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
@@ -167,7 +184,11 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
await ensureCursorSkillsInjected(onLog);
const cursorSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const desiredCursorSkillNames = resolvePaperclipDesiredSkillNames(config, cursorSkillEntries);
await ensureCursorSkillsInjected(onLog, {
skillsEntries: cursorSkillEntries.filter((entry) => desiredCursorSkillNames.includes(entry.key)),
});
const envConfig = parseObject(config.env);
const hasExplicitApiKey =
@@ -230,6 +251,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (workspaceRepoRef) {
env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
}
if (agentHome) {
env.AGENT_HOME = agentHome;
}
if (workspaceHints.length > 0) {
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
}
@@ -239,8 +263,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (!hasExplicitApiKey && authToken) {
env.PAPERCLIP_API_KEY = authToken;
}
const billingType = resolveCursorBillingType(env);
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
const effectiveEnv = Object.fromEntries(
Object.entries({ ...process.env, ...env }).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
const billingType = resolveCursorBillingType(effectiveEnv);
const runtimeEnv = ensurePathInEnv(effectiveEnv);
await ensureCommandResolvable(command, cwd, runtimeEnv);
const timeoutSec = asNumber(config.timeoutSec, 0);
@@ -261,7 +290,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const sessionId = canResumeSession ? runtimeSessionId : null;
if (runtimeSessionId && !canResumeSession) {
await onLog(
"stderr",
"stdout",
`[paperclip] Cursor session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
);
}
@@ -279,13 +308,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
`Resolve any relative file references from ${instructionsDir}.\n\n`;
instructionsChars = instructionsPrefix.length;
await onLog(
"stderr",
"stdout",
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
await onLog(
"stderr",
"stdout",
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
);
}
@@ -399,6 +428,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
timeoutSec,
graceSec,
stdin: prompt,
onSpawn,
onLog: async (stream, chunk) => {
if (stream !== "stdout") {
await onLog(stream, chunk);
@@ -470,6 +500,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
sessionParams: resolvedSessionParams,
sessionDisplayId: resolvedSessionId,
provider: providerFromModel,
biller: resolveCursorBiller(effectiveEnv, billingType, providerFromModel),
model,
billingType,
costUsd: attempt.parsed.costUsd,
@@ -490,7 +521,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
isCursorUnknownSessionError(initial.proc.stdout, initial.proc.stderr)
) {
await onLog(
"stderr",
"stdout",
`[paperclip] Cursor resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
);
const retry = await runAttempt(null);

View File

@@ -1,4 +1,5 @@
export { execute, ensureCursorSkillsInjected } from "./execute.js";
export { listCursorSkills, syncCursorSkills } from "./skills.js";
export { testEnvironment } from "./test.js";
export { parseCursorJsonl, isCursorUnknownSessionError } from "./parse.js";
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";

View File

@@ -0,0 +1,91 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type {
AdapterSkillContext,
AdapterSkillSnapshot,
} from "@paperclipai/adapter-utils";
import {
buildPersistentSkillSnapshot,
ensurePaperclipSkillSymlink,
readPaperclipRuntimeSkillEntries,
readInstalledSkillTargets,
resolvePaperclipDesiredSkillNames,
} from "@paperclipai/adapter-utils/server-utils";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
function asString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function resolveCursorSkillsHome(config: Record<string, unknown>) {
const env =
typeof config.env === "object" && config.env !== null && !Array.isArray(config.env)
? (config.env as Record<string, unknown>)
: {};
const configuredHome = asString(env.HOME);
const home = configuredHome ? path.resolve(configuredHome) : os.homedir();
return path.join(home, ".cursor", "skills");
}
async function buildCursorSkillSnapshot(config: Record<string, unknown>): Promise<AdapterSkillSnapshot> {
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const desiredSkills = resolvePaperclipDesiredSkillNames(config, availableEntries);
const skillsHome = resolveCursorSkillsHome(config);
const installed = await readInstalledSkillTargets(skillsHome);
return buildPersistentSkillSnapshot({
adapterType: "cursor",
availableEntries,
desiredSkills,
installed,
skillsHome,
locationLabel: "~/.cursor/skills",
missingDetail: "Configured but not currently linked into the Cursor skills home.",
externalConflictDetail: "Skill name is occupied by an external installation.",
externalDetail: "Installed outside Paperclip management.",
});
}
export async function listCursorSkills(ctx: AdapterSkillContext): Promise<AdapterSkillSnapshot> {
return buildCursorSkillSnapshot(ctx.config);
}
export async function syncCursorSkills(
ctx: AdapterSkillContext,
desiredSkills: string[],
): Promise<AdapterSkillSnapshot> {
const availableEntries = await readPaperclipRuntimeSkillEntries(ctx.config, __moduleDir);
const desiredSet = new Set([
...desiredSkills,
...availableEntries.filter((entry) => entry.required).map((entry) => entry.key),
]);
const skillsHome = resolveCursorSkillsHome(ctx.config);
await fs.mkdir(skillsHome, { recursive: true });
const installed = await readInstalledSkillTargets(skillsHome);
const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry]));
for (const available of availableEntries) {
if (!desiredSet.has(available.key)) continue;
const target = path.join(skillsHome, available.runtimeName);
await ensurePaperclipSkillSymlink(available.source, target);
}
for (const [name, installedEntry] of installed.entries()) {
const available = availableByRuntimeName.get(name);
if (!available) continue;
if (desiredSet.has(available.key)) continue;
if (installedEntry.targetPath !== available.source) continue;
await fs.unlink(path.join(skillsHome, name)).catch(() => {});
}
return buildCursorSkillSnapshot(ctx.config);
}
export function resolveCursorDesiredSkillNames(
config: Record<string, unknown>,
availableEntries: Array<{ key: string; required?: boolean }>,
) {
return resolvePaperclipDesiredSkillNames(config, availableEntries);
}

View File

@@ -1,6 +1,16 @@
{
"name": "@paperclipai/adapter-gemini-local",
"version": "0.2.7",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapters/gemini-local"
},
"type": "module",
"exports": {
".": "./src/index.ts",

View File

@@ -15,7 +15,8 @@ import {
ensurePaperclipSkillSymlink,
joinPromptSections,
ensurePathInEnv,
listPaperclipSkillEntries,
readPaperclipRuntimeSkillEntries,
resolvePaperclipDesiredSkillNames,
removeMaintainerOnlySkillSymlinks,
parseObject,
redactEnvForLogs,
@@ -84,9 +85,12 @@ function geminiSkillsHome(): string {
*/
async function ensureGeminiSkillsInjected(
onLog: AdapterExecutionContext["onLog"],
skillsEntries: Array<{ key: string; runtimeName: string; source: string }>,
desiredSkillNames?: string[],
): Promise<void> {
const skillsEntries = await listPaperclipSkillEntries(__moduleDir);
if (skillsEntries.length === 0) return;
const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key));
const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key));
if (selectedEntries.length === 0) return;
const skillsHome = geminiSkillsHome();
try {
@@ -100,7 +104,7 @@ async function ensureGeminiSkillsInjected(
}
const removedSkills = await removeMaintainerOnlySkillSymlinks(
skillsHome,
skillsEntries.map((entry) => entry.name),
selectedEntries.map((entry) => entry.runtimeName),
);
for (const skillName of removedSkills) {
await onLog(
@@ -109,27 +113,27 @@ async function ensureGeminiSkillsInjected(
);
}
for (const entry of skillsEntries) {
const target = path.join(skillsHome, entry.name);
for (const entry of selectedEntries) {
const target = path.join(skillsHome, entry.runtimeName);
try {
const result = await ensurePaperclipSkillSymlink(entry.source, target);
if (result === "skipped") continue;
await onLog(
"stderr",
`[paperclip] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.name}\n`,
`[paperclip] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.key}\n`,
);
} catch (err) {
await onLog(
"stderr",
`[paperclip] Failed to link Gemini skill "${entry.name}": ${err instanceof Error ? err.message : String(err)}\n`,
`[paperclip] Failed to link Gemini skill "${entry.key}": ${err instanceof Error ? err.message : String(err)}\n`,
);
}
}
}
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
const { runId, agent, runtime, config, context, onLog, onMeta, authToken } = ctx;
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
const promptTemplate = asString(
config.promptTemplate,
@@ -145,6 +149,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const workspaceId = asString(workspaceContext.workspaceId, "");
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
const agentHome = asString(workspaceContext.agentHome, "");
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
? context.paperclipWorkspaces.filter(
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
@@ -155,7 +160,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
await ensureGeminiSkillsInjected(onLog);
const geminiSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const desiredGeminiSkillNames = resolvePaperclipDesiredSkillNames(config, geminiSkillEntries);
await ensureGeminiSkillsInjected(onLog, geminiSkillEntries, desiredGeminiSkillNames);
const envConfig = parseObject(config.env);
const hasExplicitApiKey =
@@ -196,6 +203,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (workspaceId) env.PAPERCLIP_WORKSPACE_ID = workspaceId;
if (workspaceRepoUrl) env.PAPERCLIP_WORKSPACE_REPO_URL = workspaceRepoUrl;
if (workspaceRepoRef) env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
if (agentHome) env.AGENT_HOME = agentHome;
if (workspaceHints.length > 0) env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
for (const [key, value] of Object.entries(envConfig)) {
@@ -204,8 +212,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (!hasExplicitApiKey && authToken) {
env.PAPERCLIP_API_KEY = authToken;
}
const billingType = resolveGeminiBillingType(env);
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
const effectiveEnv = Object.fromEntries(
Object.entries({ ...process.env, ...env }).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
const billingType = resolveGeminiBillingType(effectiveEnv);
const runtimeEnv = ensurePathInEnv(effectiveEnv);
await ensureCommandResolvable(command, cwd, runtimeEnv);
const timeoutSec = asNumber(config.timeoutSec, 0);
@@ -225,7 +238,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const sessionId = canResumeSession ? runtimeSessionId : null;
if (runtimeSessionId && !canResumeSession) {
await onLog(
"stderr",
"stdout",
`[paperclip] Gemini session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
);
}
@@ -241,19 +254,19 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
`Resolve any relative file references from ${instructionsDir}.\n\n`;
await onLog(
"stderr",
"stdout",
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
await onLog(
"stderr",
"stdout",
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
);
}
}
const commandNotes = (() => {
const notes: string[] = ["Prompt is passed to Gemini as the final positional argument."];
const notes: string[] = ["Prompt is passed to Gemini via --prompt for non-interactive execution."];
notes.push("Added --approval-mode yolo for unattended execution.");
if (!instructionsFilePath) return notes;
if (instructionsPrefix.length > 0) {
@@ -315,7 +328,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
args.push("--sandbox=none");
}
if (extraArgs.length > 0) args.push(...extraArgs);
args.push(prompt);
args.push("--prompt", prompt);
return args;
};
@@ -342,6 +355,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
env,
timeoutSec,
graceSec,
onSpawn,
onLog,
});
return {
@@ -418,6 +432,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
sessionParams: resolvedSessionParams,
sessionDisplayId: resolvedSessionId,
provider: "google",
biller: "google",
model,
billingType,
costUsd: attempt.parsed.costUsd,
@@ -439,7 +454,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
isGeminiUnknownSessionError(initial.proc.stdout, initial.proc.stderr)
) {
await onLog(
"stderr",
"stdout",
`[paperclip] Gemini resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
);
const retry = await runAttempt(null);

Some files were not shown because too many files have changed in this diff Show More