mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-02 02:07:25 +08:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents ask for decisions and optional details through cards in chat. > - A clear approval in a message can leave the matching card pending. > - An unanswered question can also block an unrelated later reply. > - Decisions need a saved source message, while optional questions need to remain answerable in history. > - This pull request records conversational decisions and lets users move on from questions and answer them later. ## Linked Issues or Issue Description **What happened?** Native Claude and Codex could act on approval in chat while the original approval card stayed pending. Pending question forms stayed above the composer, were absent from history, and could suppress later chat replies. A late native question answer could wait for a finished run to reconnect. **Expected behavior** The active agent records a clear approval or refusal against the exact card and user message. Ambiguous replies do not grant consent. Users can send another message without answering a question. The question remains pending in history and can be reopened and answered later. The saved answer reaches the agent. **Steps to reproduce** 1. Ask an agent to propose work with a confirmation card, then approve it in chat. 2. Check that the original card records that approval before work starts. 3. Ask an interactive question, send an unrelated message, and reload. 4. Open the unanswered question from history and submit an answer. Related work: #14408 added completion delivery. #14607 tests completion reporting turns. Neither records conversational answers on approval cards. ## What Changed - Add a confirmation endpoint backed by a user comment, with schema validation, OpenAPI discovery, and native Plan-mode access. Ask mode remains read-only. - Check company, active run, actor, current session, message provenance, revision, and resolver policy. Save the decision and audit in one transaction. Retries do not repeat effects. Emit resolution telemetry after commit. - Give fresh and resumed chat turns the actual pending confirmation identities. Teach agents to save clear conversational decisions before acting and to clarify ambiguity. - Keep unanswered Agent Chat questions as compact history entries. A newer user message closes the old form. Question cards never contribute to composer pending counts or navigation, including after dismissing a fresh form. The history card is the sole reminder; clicking it restores that exact form and draft. - Preserve Agent Chat questions when later messages or questions arrive. Historical ordinary inputs no longer gate later chat replies. Current-run requests, task execution, and governed approvals keep their gates. Remove the special acknowledgement-publication proof helpers that this rule replaces. - Route answers to finished native runs through durable fresh-wake delivery, with existing idempotency and source-question context. Settle late replies against contiguous completed conversation turns and freeze their history replay; failed, unhandled, and newly arriving messages remain actionable. - Add real-component Storybook scenarios, database and UI regressions, and a three-turn native Claude/Codex E2E case. Capture distinct, UI-ready screenshots and report the individual assertions. ## Verification - Focused decision/publication/UI regressions after merging master: 288 passed; subsequent UI draft, failed-send, and conversation checks: 199 passed. - Native question and durable delivery regressions: 106 passed, including all four terminal run states and exactly-once late delivery. Seven targeted regressions fail against the original implementation and pass with the fix. - Latest conversation/decision/native-delivery regressions after the master merge: 121 passed. Covers completed progress, missing or failed intervening turns, new messages during a late reply, stale sessions, and frozen retry/replay boundaries. Four new assertions fail before the ordering fix. - E2E support suite after the master merge: 792 passed. Negative controls reject expired cards, wrong questions/answers, stale or missing replies, unrelated clarification forms, and unexpected tasks. - The embedded-browser walkthrough caught one additional defect: dismissing a fresh question still showed a composer badge. Both Cancel and close-button regressions failed before the fix. The fix at `65f2ade12` passes 170 chat-thread tests and 792 E2E support tests. After merging master, 232 chat-thread/confirmation tests, server/UI typechecks, and token gates pass. The preview and two-provider live E2E pass at `e5512a206`; Greptile is 5/5 with zero unresolved threads at that commit. All 55 checks are now successful at `e5512a206` (four conditional checks skipped), including the aggregate verification gate and clean-install canary test. The first attempt was interrupted by simultaneous CI worker shutdowns; one failed-job rerun passed without code changes. - [Published Storybook](https://d1p6rlowie26tp.cloudfront.net/storybook/branches/codex~2Fchat-approval-resolution/?path=/story/chat-comments-agent-chat-unanswered-questions--moved-on): nine real-component scenarios. Manually exercised move on, reopen, preserve draft, answer later, answer one of multiple questions, and a custom mobile answer in the embedded browser. Retested fresh Cancel and close-button dismissal in the updated build, then reopened and submitted the preserved Green selection and inspected its answered receipt. Static preview has no live model/backend; its callbacks are fixture responses. - [First live campaign](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36714504406-1/) reproduced the late-answer completion-state defect on both providers despite correct saved answers and acknowledgements. It also exposed a valid imperative clarification rejected by the old oracle. Both issues are fixed with regression controls; this failing run is retained as evidence. - [Four-cell qualification](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36717804064-1/) passed 4/4 at `2bf8a1009`: unanswered-question return and ambiguous confirmation, each on native Claude and Codex. Inspected saved state, source-message decisions, visible cards, and agent replies. Both late-answer chats settled to waiting; no unrequested tasks were created. [Final branch rerun](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36719666238-1/) passed 2/2 at `142630720`: the same unanswered-question journey after merging master, plus an additional screenshot and browser assertion for the actual late-answer acknowledgement. - [Composer-reminder E2E](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36727006818-1/) passed 2/2 at `5b62c52d9`: native Claude and Codex, three turns each, with explicit no-badge assertions before and after reload. Inspected saved pending/answered state, both screenshots with a clear composer, and actual Blue acknowledgements; all five behavioral matchers passed per provider and neither created tasks. Cost coverage is partial; this is bounded workflow qualification. - [Fresh-dismissal E2E](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36742773318-1/) passed 2/2 at `e5512a206`: native Claude and Codex, including fresh Cancel, clear composer, reopen, unrelated message, reload, late Blue answer, and actual agent acknowledgement. All five behavioral matchers pass per provider. Inspected the fresh-dismissal screenshots and saved pending/answered identity; neither created tasks. Cost coverage is partial (4/6 runs). - Prior evidence remains available in [the earlier campaign](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-36642252725-1/). Its early loading screenshot and overwritten final capture prompted the UI-ready, distinct screenshot fixes. ## Risks - The model interprets intent. The server verifies permission and provenance; it does not infer consent from text. Ambiguous and unrelated replies are not approvals. - Historical questions can accumulate. They remain visible, pending, and answerable; no automatic answer or expiry is invented. - The change to completion gates is scoped to Agent Chat and ordinary historical inputs. Current-turn and governed approvals retain their existing controls. - Live qualification is limited to the selected stories. Broader native onboarding finalization remains separate work. - No database migration. Telemetry adds no fields or values; the contract and README document the commit boundary. Privacy review was requested on the PR. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and browser-test orchestration. The exact model ID and context-window size are not exposed to this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
217 lines
10 KiB
JavaScript
217 lines
10 KiB
JavaScript
import { readFile, writeFile } from "node:fs/promises";
|
|
import { existsSync } from "node:fs";
|
|
import { createHash } from "node:crypto";
|
|
import { dirname, relative, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
const repositoryRoot = resolve(packageRoot, "../..");
|
|
const contractPath = resolve(packageRoot, "spec/capability/source-contract.json");
|
|
const outputDirectory = resolve(packageRoot, "generated/capability");
|
|
const outputPaths = {
|
|
capabilities: resolve(outputDirectory, "capabilities.yaml"),
|
|
tools: resolve(outputDirectory, "mcp-tool-map.yaml"),
|
|
evals: resolve(outputDirectory, "eval-traceability.yaml"),
|
|
overview: resolve(outputDirectory, "capability-contract.md"),
|
|
handoff: resolve(outputDirectory, "downstream-handoff.md"),
|
|
};
|
|
|
|
const checkOnly = process.argv.includes("--check");
|
|
const dispositions = new Set(["control_plane_owned", "always_agent_tool", "optional_agent_tool"]);
|
|
|
|
function sourceAnchor(path, line, heading) {
|
|
return `${path}#L${line}:${heading.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "")}`;
|
|
}
|
|
|
|
function classifyHeading(path, heading) {
|
|
const normalized = heading.toLowerCase();
|
|
if (normalized === "conversational confirmation answers") return "always_agent_tool";
|
|
if (/(authentication|identity|checkout|budget|error|wake|heartbeat|approval follow-up|activity|audit|release|terminology)/.test(normalized)) {
|
|
return "control_plane_owned";
|
|
}
|
|
if (/(artifact|comment|document|plan|interaction|final disposition|work product|report|question)/.test(normalized)) {
|
|
return "always_agent_tool";
|
|
}
|
|
if (/(company|agent|project|goal|routine|workspace|approval|case|secret|import|export|skill)/.test(normalized) || path.includes("api-reference")) {
|
|
return "optional_agent_tool";
|
|
}
|
|
return "control_plane_owned";
|
|
}
|
|
|
|
function semanticOperation(disposition, heading) {
|
|
const normalized = heading.toLowerCase();
|
|
if (normalized === "conversational confirmation answers") return "call_api";
|
|
if (disposition === "control_plane_owned") return "runtime_reconciliation";
|
|
if (normalized.includes("document") || normalized.includes("plan")) return "write_document";
|
|
if (normalized.includes("comment") || normalized.includes("report")) return "report_progress";
|
|
if (normalized.includes("artifact") || normalized.includes("work product")) return "register_deliverable";
|
|
if (normalized.includes("interaction") || normalized.includes("question")) return "request_human_input";
|
|
return disposition === "always_agent_tool" ? "get_task_context" : "scoped_discovery";
|
|
}
|
|
|
|
async function readSkillHeadings(paths) {
|
|
const rows = [];
|
|
for (const path of paths) {
|
|
const contents = await readFile(resolve(repositoryRoot, path), "utf8");
|
|
for (const [index, line] of contents.split(/\r?\n/).entries()) {
|
|
const match = /^(#{1,6})\s+(.+?)\s*#*$/.exec(line);
|
|
if (!match) continue;
|
|
const heading = match[2].trim();
|
|
const disposition = classifyHeading(path, heading);
|
|
rows.push({
|
|
id: `skill:${path}:${index + 1}`,
|
|
kind: "skill_heading",
|
|
sourceAnchor: sourceAnchor(path, index + 1, heading),
|
|
heading,
|
|
primaryDisposition: disposition,
|
|
semanticOperation: semanticOperation(disposition, heading),
|
|
expectedMockState: disposition === "control_plane_owned" ? "runtime_decision_record" : "operation_result",
|
|
});
|
|
}
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
async function readLegacyTools() {
|
|
const path = "packages/mcp-server/src/tools.ts";
|
|
const contents = await readFile(resolve(repositoryRoot, path), "utf8");
|
|
return [...contents.matchAll(/makeTool\(\s*\n?\s*"(paperclip[A-Za-z0-9]+)"/g)].map((match) => ({
|
|
name: match[1],
|
|
sourceAnchor: sourceAnchor(path, contents.slice(0, match.index).split("\n").length, match[1]),
|
|
}));
|
|
}
|
|
|
|
function parseCase(entry, group, contract) {
|
|
const [id, title] = entry.split("|", 2);
|
|
const [primaryDisposition, validationKind, operation, expectedMockState] = contract.evalGroups[group];
|
|
return {
|
|
id,
|
|
title,
|
|
group,
|
|
sourceAnchor: `paperclip-evals/paperclip-skill-optimization/${group}.yaml#${id}`,
|
|
primaryDisposition,
|
|
fixtureProfile: `${group}-baseline`,
|
|
dominantValidationKind: validationKind,
|
|
requiredCapabilityGrants: primaryDisposition === "optional_agent_tool" ? [`${group}:read_or_write`] : [],
|
|
semanticOperation: operation,
|
|
expectedSemanticOperations: operation === "none" ? [] : [operation],
|
|
forbiddenOperations: primaryDisposition === "control_plane_owned" ? ["legacy_mcp_transport"] : [],
|
|
expectedMockState,
|
|
browserEvidenceRecipe: `${group}/${id}`,
|
|
};
|
|
}
|
|
|
|
export function validateRows(rows, label) {
|
|
const ids = new Set();
|
|
const anchors = new Set();
|
|
for (const row of rows) {
|
|
if (!row.id || ids.has(row.id)) throw new Error(`${label} has a missing or duplicate id: ${row.id ?? "<missing>"}`);
|
|
ids.add(row.id);
|
|
if (!dispositions.has(row.primaryDisposition)) throw new Error(`${label} row ${row.id} has no valid primary disposition`);
|
|
if (!row.sourceAnchor) throw new Error(`${label} row ${row.id} has no source anchor`);
|
|
if (anchors.has(row.sourceAnchor)) throw new Error(`${label} has a duplicate source anchor: ${row.sourceAnchor}`);
|
|
anchors.add(row.sourceAnchor);
|
|
}
|
|
}
|
|
|
|
function stableJson(value) {
|
|
return `${JSON.stringify(value, null, 2)}\n`;
|
|
}
|
|
|
|
function renderOverview(capabilities, tools, evals) {
|
|
const digest = createHash("sha256").update(stableJson({ capabilities, tools, evals })).digest("hex");
|
|
return [
|
|
"# Capability Capability Contract",
|
|
"",
|
|
"Generated by `scripts/generate-capability-contract.mjs`; do not edit generated files.",
|
|
"",
|
|
`- Skill/reference headings: ${capabilities.length}`,
|
|
`- Legacy MCP tools: ${tools.length}`,
|
|
`- Eval cases: ${evals.length} across ${new Set(evals.map((row) => row.group)).size} groups`,
|
|
`- Deterministic content SHA-256: \`${digest}\``,
|
|
"",
|
|
"Every row has exactly one primary disposition, a source anchor, a semantic operation, and a mock-state expectation.",
|
|
].join("\n") + "\n";
|
|
}
|
|
|
|
function renderHandoff() {
|
|
return [
|
|
"# Capability Downstream Handoff",
|
|
"",
|
|
"Generated by `scripts/generate-capability-contract.mjs`; do not edit generated files.",
|
|
"",
|
|
"## Stable Inputs",
|
|
"",
|
|
"- `capabilities.yaml`: every current Paperclip skill and reference heading, including its source anchor, disposition, semantic operation, and mock-state expectation.",
|
|
"- `mcp-tool-map.yaml`: the complete 42-tool legacy MCP replacement map.",
|
|
"- `eval-traceability.yaml`: all 106 corpus cases in 16 groups, including fixtures, grants, operations, state projections, forbids, and browser evidence IDs.",
|
|
"- `contract-schema.json`: required row fields and the closed disposition enum.",
|
|
"",
|
|
"## Consumer Tracks",
|
|
"",
|
|
"- **7B UX interaction map:** use eval `browserEvidenceRecipe`, semantic operation, and expected state to define transcript, authorization, and parity views.",
|
|
"- **7C mock control plane:** implement only the state projections and control-plane-owned operations represented by the generated rows.",
|
|
"- **7D semantic catalog:** use the operation/disposition fields to create always and optional descriptors; control-plane-owned rows stay absent from model tools.",
|
|
"- **7E eval conformance:** import each case by stable ID and assert the declared operation, forbidden operation set, and final mock projection.",
|
|
"- **7F scenario explorer:** index scenarios by the generated evidence recipe and render the linked source anchor, disposition, operation, and mock-state projection.",
|
|
"",
|
|
"`pnpm --dir packages/paperclip-runner check:capability-contract` is the drift gate before consuming these artifacts.",
|
|
].join("\n") + "\n";
|
|
}
|
|
|
|
async function buildContract() {
|
|
const contract = JSON.parse(await readFile(contractPath, "utf8"));
|
|
const capabilities = await readSkillHeadings(contract.skillSources);
|
|
const discoveredTools = await readLegacyTools();
|
|
const tools = discoveredTools.map((tool) => {
|
|
const mapping = contract.toolMappings[tool.name];
|
|
if (!mapping) throw new Error(`Legacy MCP tool ${tool.name} is unclassified`);
|
|
return {
|
|
id: `mcp:${tool.name}`,
|
|
kind: "legacy_mcp_tool",
|
|
name: tool.name,
|
|
sourceAnchor: tool.sourceAnchor,
|
|
primaryDisposition: mapping[0],
|
|
semanticOperation: mapping[1],
|
|
expectedMockState: mapping[0] === "control_plane_owned" ? "runtime_decision_record" : "operation_result",
|
|
};
|
|
});
|
|
const evals = Object.entries(contract.evalCases).flatMap(([group, entries]) => entries.map((entry) => parseCase(entry, group, contract)));
|
|
|
|
validateRows(capabilities, "Skill headings");
|
|
validateRows(tools, "MCP tools");
|
|
validateRows(evals, "Eval cases");
|
|
const discoveredToolNames = new Set(discoveredTools.map((tool) => tool.name));
|
|
for (const mappedToolName of Object.keys(contract.toolMappings)) {
|
|
if (!discoveredToolNames.has(mappedToolName)) throw new Error(`MCP mapping has no registered source tool: ${mappedToolName}`);
|
|
}
|
|
if (tools.length !== 42 || Object.keys(contract.toolMappings).length !== 42) throw new Error(`Expected 42 legacy MCP tools, found ${tools.length}`);
|
|
if (evals.length !== 106 || new Set(evals.map((row) => row.group)).size !== 16) throw new Error(`Expected 106 eval cases in 16 groups, found ${evals.length}`);
|
|
|
|
return {
|
|
[outputPaths.capabilities]: stableJson({ schemaVersion: 1, rows: capabilities }),
|
|
[outputPaths.tools]: stableJson({ schemaVersion: 1, rows: tools }),
|
|
[outputPaths.evals]: stableJson({ schemaVersion: 1, rows: evals }),
|
|
[outputPaths.overview]: renderOverview(capabilities, tools, evals),
|
|
[outputPaths.handoff]: renderHandoff(),
|
|
};
|
|
}
|
|
|
|
export async function main() {
|
|
const output = await buildContract();
|
|
for (const [path, contents] of Object.entries(output)) {
|
|
if (checkOnly) {
|
|
if (!existsSync(path) || await readFile(path, "utf8") !== contents) throw new Error(`Generated contract drift: ${relative(packageRoot, path)}`);
|
|
} else {
|
|
await writeFile(path, contents);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
main().catch((error) => {
|
|
console.error(error.message);
|
|
process.exitCode = 1;
|
|
});
|
|
}
|