@popmelt.com/core 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.11.4",
3
+ "version": "0.12.0",
4
4
  "description": "Ambient project memory and shared understanding for Codex",
5
5
  "author": {
6
6
  "name": "Popmelt",
@@ -158,7 +158,7 @@ Search raw \`.popmelt\` records only when the supplied Imprint context is insuff
158
158
 
159
159
  Use Popmelt history to explain why a decision was made or how shared understanding developed. Use git history only when the question depends on chronology or source provenance. Clearly distinguish recorded human or collaboration evidence from your own inference.
160
160
 
161
- Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Tn(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let r of o.annotations){let i=r.elements.map(l=>{let b=[l.selector];return l.reactComponent&&b.push(`(${l.reactComponent})`),b.join(" ")}).join(", "),s=r.instruction||"No text";n.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`);let c=t?.[r.id];if(c?.length)for(let l of c)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of o.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes)n.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of o.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),c=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";n.push(`- ${r.selector} ${i}${c}: ${s} \u2192 ${a}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of o.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;n.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of o.spacingTokenChanges){n.push(`
161
+ Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Tn(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let r of o.annotations){let i=r.elements.map(l=>{let b=[l.selector];return l.reactComponent&&b.push(`(${l.reactComponent})`),b.join(" ")}).join(", "),s=r.instruction||"No text";n.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`);let c=t?.[r.id];if(c?.length)for(let l of c)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of o.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes){let a=s.token?` [${s.token}]`:"";n.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of o.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),c=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";n.push(`- ${r.selector} ${i}${c}: ${s} \u2192 ${a}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of o.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;n.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of o.spacingTokenChanges){n.push(`
162
162
  ### ${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`);for(let i of r.affectedElements){let s=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?n.push(`- ${i.selector}${s}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):n.push(`- ${i.selector}${s}: ${i.property} ${r.originalPx}px \u2192 ${r.newPx}px`),n.push(` class="${i.className}"`)}}}if(o.inspectedElement){let r=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let i=[r.selector];r.reactComponent&&i.push(`(${r.reactComponent})`),r.context&&i.push(`in ${r.context}`),r.textContent&&i.push(`"${r.textContent.slice(0,80)}"`),n.push(`- ${i.join(" ")}`)}return n.join(`
163
163
  `)}function is(o,e,t){let n=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${a.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),a.feedbackSummary&&n.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&n.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${a.question}"`);else{if(n.push(`### Round ${s} (assistant)`),a.responseText&&n.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let c of a.resolutions){let l=c.finalScope??c.inferredScope,b=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${c.annotationId}: ${c.status}${b} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&n.push(` Files: ${c.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&n.push(`Tools used: ${a.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let b=new Map;for(let S of s)if(typeof S=="object"&&S!==null&&"text"in S){let w=S,P=w.scope||"general";b.has(P)||b.set(P,[]),b.get(P).push(w.text)}for(let[S,w]of b){n.push(`**${S.charAt(0).toUpperCase()+S.slice(1)}**`);for(let P of w)n.push(`- ${P}`)}}else for(let b of s)typeof b=="string"&&n.push(`- ${b}`);let a=t.designModel.tokens;a&&typeof a=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(a,null,2)),n.push("```"));let c=t.designModel.components;c&&typeof c=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(c,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=t?.screenshotPaths??{},a=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of a){n.push(""),n.push(`## Page: ${c}`);let b=s[c];b&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let S={...e,annotations:l,styleModifications:e.styleModifications},w=Tn(S,t?.imagePaths,t?.attachmentFiles);w&&(n.push(""),n.push(w))}}else{let s=Tn(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
164
164
  `)}function ss(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function as(o,e,t,n){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),t!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let a of e)a.role==="human"?(s++,a.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${a.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),a.feedbackSummary&&r.push(`Annotations: ${a.feedbackSummary}`))):a.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${a.question}"`)):(r.push(`### Round ${s} (assistant)`),a.responseText&&r.push(`Response: ${a.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of n)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),r.push("<resolution>"),r.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),r.push("</resolution>"),r.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
@@ -170,10 +170,10 @@ Apply an evidence-sufficiency stopping rule: stop researching as soon as the rel
170
170
  `);let n=new Map;for(let r of e){let i=r.pathname||"(unknown)",s=n.get(i)??[];s.push(r.instruction),n.set(i,s)}return[...n.entries()].map(([r,i])=>`\`${r}\`
171
171
  ${i.map(s=>`- ${s}`).join(`
172
172
  `)}`).join(`
173
- `)}var _s={name:"@popmelt.com/core",version:"0.11.4",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{source:"./src/plugins/next.ts",types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var En=_s.version;var Ql=1111,Xl=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Yl=1800*1e3,Zl=3600*1e3,$s=45e3,ep=5e3,tp=1e4,np=2*1024*1024;function Os(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
173
+ `)}var _s={name:"@popmelt.com/core",version:"0.12.0",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{source:"./src/plugins/next.ts",types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var En=_s.version;var Ql=1111,Xl=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Yl=1800*1e3,Zl=3600*1e3,$s=45e3,ep=5e3,tp=1e4,np=2*1024*1024;function Os(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
174
174
  `)}function _n(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Ds(o){let e=o.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let t=o[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=o.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function op(o,e){if(e.size===1)return[...o].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function qs(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function rp(o,e,t){let n=[...t];for(let r of o)if(r.type==="tool_use"){let i=r.tool||"",s=r.file??void 0,a=r.content??void 0,c=s?s.split("/").pop()??s:void 0,l;switch(i){case"Read":l=c?`Reading ${c}`:"Reading file";break;case"Edit":l=c?`Editing ${c}`:"Editing file";break;case"Write":l=c?`Writing ${c}`:"Writing file";break;case"Bash":l=a?a.split(`
175
175
  `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let b=s??a??void 0,S=s?Js(s)?s:Hl(e,s):void 0,w=n[n.length-1];w&&w.kind==="tool_group"&&w.tool===i?w.items.push({label:l,detail:b,...S?{filePath:S}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:l,detail:b,...S?{filePath:S}:{}}]})}return n}function ip(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
176
- `)}function sp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Ns(o){let e=o.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(c=>`${a}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),t=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let c=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${c}`}),i=[...e,...n,...t,...r].map(s=>sp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function ap(o,e){let t=o.headers.origin;qs(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function $(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}var dp=16384,cp=131072;async function Oe(o,e=dp){let t=[],n=0;for await(let i of o){let s=typeof i=="string"?Buffer.from(i):i;if(n+=s.length,n>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let r=JSON.parse(Buffer.concat(t).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function lp(o,e){let t=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function pp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function up(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,r,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Mo(o,e){try{o.res.write(`event: ${e.type}
176
+ `)}function sp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Ns(o){let e=o.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(c=>`${a}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}${c.token?` [${c.token}]`:""}`)}),t=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let c=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${c}`}),i=[...e,...n,...t,...r].map(s=>sp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function ap(o,e){let t=o.headers.origin;qs(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function $(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}var dp=16384,cp=131072;async function Oe(o,e=dp){let t=[],n=0;for await(let i of o){let s=typeof i=="string"?Buffer.from(i):i;if(n+=s.length,n>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let r=JSON.parse(Buffer.concat(t).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function lp(o,e){let t=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function pp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function up(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,r,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Mo(o,e){try{o.res.write(`event: ${e.type}
177
177
  data: ${JSON.stringify(e)}
178
178
 
179
179
  `)}catch{}}function Zt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function mp(o){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}function fp(o,e){return new Promise((t,n)=>{let r=s=>{o.removeListener("listening",i),n(s)},i=()=>{o.removeListener("error",r),t()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}async function Ls(o={}){let e=new Date().toISOString(),t=o.port??Ql,n=o.projectRoot??process.cwd(),r=await Ul(n).catch(()=>n),i=Kn(r),s=await Ii(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Xe(Kl(),"popmelt-bridge"),l=o.maxTurns??40,b=o.maxBudgetUsd??1,S=[...o.allowedTools??Xl],w=o.claudePath??"claude",P=o.copilotPath??"copilot",T=o.provider??"codex",h=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=o.restartMode??"embedded",y=t,p={},A={claude:w,codex:"codex",copilot:P};for(let[d,v]of Object.entries(A))try{let _=v.includes("/")?v:Jl("which",[v],{encoding:"utf-8"}).trim();p[d]={available:!0,path:_}}catch{p[d]={available:!1,path:null}}function f(d,v){return new Promise(_=>{let I=Cs(v,["--version"],{stdio:["ignore","ignore","ignore"]}),M=!1,R=J=>{M||(M=!0,_(J))},N=setTimeout(()=>{I.kill("SIGTERM"),R(!0)},5e3);I.on("error",()=>{clearTimeout(N),R(!1)}),I.on("close",J=>{clearTimeout(N),R(J===0)})})}await Promise.all([(async()=>{p.claude&&(p.claude.models=p.claude.available&&p.claude.path?await ms(p.claude.path).catch(()=>go):go)})(),(async()=>{p.codex&&(p.codex.models=p.codex.available&&p.codex.path?await us(p.codex.path).catch(()=>Rn):Rn)})(),(async()=>{p.copilot&&(p.copilot.models=p.copilot.available&&p.copilot.path?await ps(p.copilot.path).catch(()=>[Pn]):[Pn])})()]);let[m,j,D]=await Promise.all([hr(r),gr(r),yr(r,p.copilot?.path??P)]);p.claude&&(p.claude.mcp=m),p.codex&&(p.codex.mcp=j),p.copilot&&(p.copilot.mcp=D),m.found&&m.name&&S.push(`mcp__${m.name}__*`),await ql(c,{recursive:!0}),Bs(c).catch(()=>{});let k=new Io(1),O=new lo,K=new uo($s),H=null,E=0,W=!1,G=()=>{E+=1,W=!1,H&&clearTimeout(H),H=null},fe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(g!=="detached"||K.size>0||W)return;W=!0;let d=++E,v=Date.now()+tp,_=()=>{if(d!==E)return;if(K.size>0){G();return}if(!(k.isRunning||k.depth>0||O.isRunning||O.depth>0)||Date.now()>=v){W=!1,H=setTimeout(fe,50),H.unref?.();return}H=setTimeout(_,250),H.unref?.()};_()},oe=new Set,x=new Ro(r),C=await x.recoverInterruptedTurns();C>0&&console.warn(`[Popmelt] Recovered ${C} interrupted thread turn(s) from durable history.`);let q=new io(r);q.sweep();let B=new zt(r),Q=new St(r,i);try{let d=await Q.store.migrateTopology();d.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${d.relationMutations} relation mutation(s)).`)}catch(d){console.warn(`[Popmelt] Imprint topology migration deferred: ${d instanceof Error?d.message:String(d)}`)}let he=new Po(r),_e=new to(r),se=new co(r,{claudePath:w,provider:T,timeoutMs:h,loadProjectableDecisions:d=>B.getProjectableDecisions(d),onEvent:d=>{for(let v of oe)Mo(v,d)}}),De=new Wn({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:x,memoryService:B,imprintService:Q,loadConcreteModel:()=>se.loadModel()});B.beginAutomaticInitialization({writerVersion:En}).then(async d=>{d.state==="ready"?(await B.migrateImprintSnapshot(),await B.syncImprintGraph(),await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),T!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await $e({provider:T,reason:"Project accepted decisions that were waiting when the bridge restarted"})):d.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${d.error}`)});let gt=20,en=300*1e3,Ae=[];function nt(){let d=Date.now()-en;for(;Ae.length>0&&(Ae[0].completedAt<d||Ae.length>gt);)Ae.shift()}let yt=new Map;k.addListener((d,v,_)=>{for(let I of oe)(!_||!I.sourceId||I.sourceId===_)&&Mo(I,d)}),O.addListener((d,v,_)=>{for(let I of oe)(!_||!I.sourceId||I.sourceId===_)&&Mo(I,d)}),O.setProcessor(async d=>{let v=d.provider??T;try{let _=await se.run({provider:v,model:d.model,threadId:d.threadId,presentationJobId:d.id,agentSettings:d.agentSettings});if(d.status==="cancelled")return;let I=await se.loadRuns(),M=_.runId?I.runs.find(N=>N.id===_.runId):void 0;if(_.success&&_.proposalId){let N=await se.findModelProposal(_.proposalId),J=await se.loadModel(),U=N?Ji(N,J):null;if(N&&U){let F=N.decisionIds.map(L=>({decisionId:L,status:"projected"}));await B.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(L=>({path:L.path,value:L.value,decisionIds:L.decisionIds})),coverage:F}),await se.applySelectedModelProposal(N.id,U.map(L=>({path:L.path,value:L.value})),U.map(L=>({group:L.path[0]==="rules"||L.path[0]==="components"||L.path[0]==="tokens"?L.path[0]:"model",label:L.label??L.id,detail:L.rationale,path:L.path,value:L.value})),"automatic")}}let R=ip(_,M);if(d.threadId&&(await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:R,model:d.model,provider:v})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:R,model:d.model,provider:v})),_.success)d.status="done",d.result=R,O.broadcast({type:"done",jobId:d.id,success:!0,responseText:R,threadId:d.threadId},d.id,d.sourceId),Ae.push({id:d.id,status:"done",completedAt:Date.now(),threadId:d.threadId,annotationIds:d.annotationIds,color:"#000000",kind:"project_model"}),nt();else{if(d.status="error",d.error=_.error??"Projection failed",d.threadId){let N=`Model projection failed.
@@ -1 +1 @@
1
- import{a as p}from"./chunk-NOHXTT24.mjs";import{request as c}from"http";function u(){let e=process.env.POPMELT_BRIDGE_URL;if(!e)return null;try{let t=new URL(e);return{port:t.port?Number.parseInt(t.port,10):null,projectId:process.env.POPMELT_PROJECT_ID||null,leaseEligible:!1}}catch{return null}}async function h(e,t,i){let r=u();if(e?.bridge===!1||r)return r??{port:null,projectId:null,leaseEligible:!1};try{let{startPopmelt:o}=await import("./server-UXP4AHUF.mjs"),n=t.config?.server?.host,l=n===!0?"0.0.0.0":n||"localhost",s=t.config?.server?.port??i,d=`http://${l==="0.0.0.0"?"localhost":l}:${s}`,a=await o({port:e?.port,projectRoot:e?.projectRoot,devOrigin:d,force:!0,detached:!0,manageLease:!1});return console.log(`[popmelt] bridge ready at http://localhost:${a.port}`),{port:a.port,projectId:a.projectId,leaseEligible:!0}}catch(o){let n=o instanceof Error?o.message:String(o);return console.warn("[popmelt] bridge failed to start:",n),{port:null,projectId:null,leaseEligible:!1}}}async function v(e,t,i=fetch){if(!e.leaseEligible||e.port===null)return null;let r=await p({port:e.port,projectId:e.projectId},i);if(!r)return null;let o=()=>{n()},n=async()=>{process.removeListener("beforeExit",o),await r.release()};return process.once("beforeExit",o),t.httpServer?.once("close",()=>{n()}),{id:r.id,release:n}}function g(e,t,i){if(i.port===null)return null;let r=new URL(t,"http://popmelt.local");if(r.pathname!==`${e}/status`)return null;let o=new URL("/status",`http://localhost:${i.port}`);return r.searchParams.forEach((n,l)=>o.searchParams.append(l,n)),i.projectId&&o.searchParams.set("projectId",i.projectId),o}function b(e,t){return(i,r,o)=>{let n=g(e,i.url||"",t());if(!n)return o();let l=c(n,{method:i.method,headers:{...i.headers,host:n.host}},s=>{r.writeHead(s.statusCode||502,s.headers),s.pipe(r)});l.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Popmelt bridge not running on port ${t().port}`)}),i.pipe(l)}}function P(e){let t=e.port===null?null:`http://localhost:${e.port}`;return`window.__POPMELT_BRIDGE_URL__=${JSON.stringify(t)};window.__POPMELT_PROJECT_ID__=${JSON.stringify(e.projectId)};`}export{h as a,v as b,b as c,P as d};
1
+ import{a as p}from"./chunk-NOHXTT24.mjs";import{request as c}from"http";function u(){let e=process.env.POPMELT_BRIDGE_URL;if(!e)return null;try{let t=new URL(e);return{port:t.port?Number.parseInt(t.port,10):null,projectId:process.env.POPMELT_PROJECT_ID||null,leaseEligible:!1}}catch{return null}}async function h(e,t,i){let r=u();if(e?.bridge===!1||r)return r??{port:null,projectId:null,leaseEligible:!1};try{let{startPopmelt:o}=await import("./server-34WZBGOE.mjs"),n=t.config?.server?.host,l=n===!0?"0.0.0.0":n||"localhost",s=t.config?.server?.port??i,d=`http://${l==="0.0.0.0"?"localhost":l}:${s}`,a=await o({port:e?.port,projectRoot:e?.projectRoot,devOrigin:d,force:!0,detached:!0,manageLease:!1});return console.log(`[popmelt] bridge ready at http://localhost:${a.port}`),{port:a.port,projectId:a.projectId,leaseEligible:!0}}catch(o){let n=o instanceof Error?o.message:String(o);return console.warn("[popmelt] bridge failed to start:",n),{port:null,projectId:null,leaseEligible:!1}}}async function v(e,t,i=fetch){if(!e.leaseEligible||e.port===null)return null;let r=await p({port:e.port,projectId:e.projectId},i);if(!r)return null;let o=()=>{n()},n=async()=>{process.removeListener("beforeExit",o),await r.release()};return process.once("beforeExit",o),t.httpServer?.once("close",()=>{n()}),{id:r.id,release:n}}function g(e,t,i){if(i.port===null)return null;let r=new URL(t,"http://popmelt.local");if(r.pathname!==`${e}/status`)return null;let o=new URL("/status",`http://localhost:${i.port}`);return r.searchParams.forEach((n,l)=>o.searchParams.append(l,n)),i.projectId&&o.searchParams.set("projectId",i.projectId),o}function b(e,t){return(i,r,o)=>{let n=g(e,i.url||"",t());if(!n)return o();let l=c(n,{method:i.method,headers:{...i.headers,host:n.host}},s=>{r.writeHead(s.statusCode||502,s.headers),s.pipe(r)});l.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Popmelt bridge not running on port ${t().port}`)}),i.pipe(l)}}function P(e){let t=e.port===null?null:`http://localhost:${e.port}`;return`window.__POPMELT_BRIDGE_URL__=${JSON.stringify(t)};window.__POPMELT_PROJECT_ID__=${JSON.stringify(e.projectId)};`}export{h as a,v as b,b as c,P as d};
package/dist/cli.mjs CHANGED
@@ -159,7 +159,7 @@ Search raw \`.popmelt\` records only when the supplied Imprint context is insuff
159
159
 
160
160
  Use Popmelt history to explain why a decision was made or how shared understanding developed. Use git history only when the question depends on chronology or source provenance. Clearly distinguish recorded human or collaboration evidence from your own inference.
161
161
 
162
- Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Ln(t,e,n){let o=[];if(t.annotations.length>0){o.push("## Annotations");for(let r of t.annotations){let i=r.elements.map(l=>{let y=[l.selector];return l.reactComponent&&y.push(`(${l.reactComponent})`),y.join(" ")}).join(", "),s=r.instruction||"No text";o.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)o.push(` Attached image: use the Read tool to view ${l}`);let d=n?.[r.id];if(d?.length)for(let l of d)o.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(t.styleModifications.length>0){o.push(""),o.push("## Style Changes (make permanent in source)"),o.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of t.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes)o.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(t.textModifications?.length){o.push(""),o.push("## Text Changes (make permanent in source)"),o.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of t.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),d=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";o.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(t.domModifications?.length){o.push(""),o.push("## DOM Structure Changes (make permanent in source)"),o.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of t.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;o.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(t.spacingTokenChanges?.length){o.push(""),o.push("## Spacing Token Changes"),o.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of t.spacingTokenChanges){o.push(`
162
+ Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Ln(t,e,n){let o=[];if(t.annotations.length>0){o.push("## Annotations");for(let r of t.annotations){let i=r.elements.map(l=>{let y=[l.selector];return l.reactComponent&&y.push(`(${l.reactComponent})`),y.join(" ")}).join(", "),s=r.instruction||"No text";o.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)o.push(` Attached image: use the Read tool to view ${l}`);let d=n?.[r.id];if(d?.length)for(let l of d)o.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(t.styleModifications.length>0){o.push(""),o.push("## Style Changes (make permanent in source)"),o.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of t.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes){let a=s.token?` [${s.token}]`:"";o.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(t.textModifications?.length){o.push(""),o.push("## Text Changes (make permanent in source)"),o.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of t.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),d=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";o.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(t.domModifications?.length){o.push(""),o.push("## DOM Structure Changes (make permanent in source)"),o.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of t.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;o.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(t.spacingTokenChanges?.length){o.push(""),o.push("## Spacing Token Changes"),o.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of t.spacingTokenChanges){o.push(`
163
163
  ### ${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`);for(let i of r.affectedElements){let s=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?o.push(`- ${i.selector}${s}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):o.push(`- ${i.selector}${s}: ${i.property} ${r.originalPx}px \u2192 ${r.newPx}px`),o.push(` class="${i.className}"`)}}}if(t.inspectedElement){let r=t.inspectedElement;o.push(""),o.push("## Inspected Element"),o.push("The developer has this element selected in the inspector:");let i=[r.selector];r.reactComponent&&i.push(`(${r.reactComponent})`),r.context&&i.push(`in ${r.context}`),r.textContent&&i.push(`"${r.textContent.slice(0,80)}"`),o.push(`- ${i.join(" ")}`)}return o.join(`
164
164
  `)}function zs(t,e,n){let o=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(o.push("You are reviewing a UI screenshot with developer annotations."),o.push(""),!i&&n?.provider!=="codex"&&(o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${t}`),o.push("")),o.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){o.push(""),o.push("## Previous Conversation");let s=0;for(let a of n.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&o.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${a.question}"`);else{if(o.push(`### Round ${s} (assistant)`),a.responseText&&o.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let l=d.finalScope??d.inferredScope,y=l?` [${l.breadth} ${l.target}]`:"";o.push(`- ${d.annotationId}: ${d.status}${y} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&o.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&o.push(`Tools used: ${a.toolsUsed.join(", ")}`)}o.push(""),o.push("The current round is shown in full below.")}if(n?.designModel){o.push(""),o.push("## Established Design Policies"),o.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(o.push(""),o.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let y=new Map;for(let b of s)if(typeof b=="object"&&b!==null&&"text"in b){let h=b,k=h.scope||"general";y.has(k)||y.set(k,[]),y.get(k).push(h.text)}for(let[b,h]of y){o.push(`**${b.charAt(0).toUpperCase()+b.slice(1)}**`);for(let k of h)o.push(`- ${k}`)}}else for(let y of s)typeof y=="string"&&o.push(`- ${y}`);let a=n.designModel.tokens;a&&typeof a=="object"&&(o.push(""),o.push("Design tokens:"),o.push("```json"),o.push(JSON.stringify(a,null,2)),o.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(o.push(""),o.push("Component patterns:"),o.push("```json"),o.push(JSON.stringify(d,null,2)),o.push("```")),o.push(""),o.push("### Applied Model-Gap Details"),o.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),o.push("<novel>"),o.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),o.push("</novel>"),o.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),o.push("- `element`: What you are styling or creating"),o.push("- `decision`: What you actually implemented (specific values)"),o.push("- `reason`: Why this is novel (what is missing from the model)"),o.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),o.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(n?.designModel||(o.push(""),o.push("## Design Context"),o.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=n?.screenshotPaths??{},a=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(d)}o.push(""),o.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of a){o.push(""),o.push(`## Page: ${d}`);let y=s[d];y&&n?.provider!=="codex"?o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${y}`):!y&&n?.provider!=="codex"&&(Object.keys(s).length===0?(o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${t}`),o.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):o.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let b={...e,annotations:l,styleModifications:e.styleModifications},h=Ln(b,n?.imagePaths,n?.attachmentFiles);h&&(o.push(""),o.push(h))}}else{let s=Ln(e,n?.imagePaths,n?.attachmentFiles);s&&(o.push(""),o.push(s))}return o.push(""),o.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),o.push(""),o.push("## Resolution"),o.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),o.push("<resolution>"),o.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),o.push("</resolution>"),o.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push(""),o.push("## Questions"),o.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),o.push('<question>What do you mean by "..."?</question>'),o.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),o.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),o.join(`
165
165
  `)}function Ws(t){return t.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Vs(t,e,n,o){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${t}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let a of e)a.role==="human"?(s++,a.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${a.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),a.feedbackSummary&&r.push(`Annotations: ${a.feedbackSummary}`))):a.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${a.question}"`)):(r.push(`### Round ${s} (assistant)`),a.responseText&&r.push(`Response: ${a.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),o&&o.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of o)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),r.push("<resolution>"),r.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),r.push("</resolution>"),r.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
@@ -171,10 +171,10 @@ Apply an evidence-sufficiency stopping rule: stop researching as soon as the rel
171
171
  `);let o=new Map;for(let r of e){let i=r.pathname||"(unknown)",s=o.get(i)??[];s.push(r.instruction),o.set(i,s)}return[...o.entries()].map(([r,i])=>`\`${r}\`
172
172
  ${i.map(s=>`- ${s}`).join(`
173
173
  `)}`).join(`
174
- `)}var ga={name:"@popmelt.com/core",version:"0.11.4",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{source:"./src/plugins/next.ts",types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var Ye=ga.version;var lu=1111,pu=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],uu=1800*1e3,mu=3600*1e3,Ia=45e3,fu=5e3,hu=1e4,gu=2*1024*1024;function wa(t){return t.length<=1?t[0]??"":["The developer sent these queued steering messages while you were working:","",...t.map((e,n)=>`${n+1}. ${e}`)].join(`
174
+ `)}var ga={name:"@popmelt.com/core",version:"0.12.0",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{source:"./src/plugins/next.ts",types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var Ye=ga.version;var lu=1111,pu=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],uu=1800*1e3,mu=3600*1e3,Ia=45e3,fu=5e3,hu=1e4,gu=2*1024*1024;function wa(t){return t.length<=1?t[0]??"":["The developer sent these queued steering messages while you were working:","",...t.map((e,n)=>`${n+1}. ${e}`)].join(`
175
175
  `)}function Kn(t){return[...new Set(t.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function va(t){let e=t.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let n=t[e];if(!n?.question||!n.jobId.startsWith("imprint-"))return[];let o=t.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return o?.imprintSummary?.grounding?[o.imprintSummary.grounding.explanationId]:[]}function yu(t,e){if(e.size===1)return[...t].reverse().find(n=>{let o=n.imprintSummary;return n.role==="assistant"&&!!o?.grounding&&!o?.resolvedAction&&e.has(o.grounding.explanationId)})}function Pa(t){if(!t)return!1;try{let e=new URL(t);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Iu(t,e,n){let o=[...n];for(let r of t)if(r.type==="tool_use"){let i=r.tool||"",s=r.file??void 0,a=r.content??void 0,d=s?s.split("/").pop()??s:void 0,l;switch(i){case"Read":l=d?`Reading ${d}`:"Reading file";break;case"Edit":l=d?`Editing ${d}`:"Editing file";break;case"Write":l=d?`Writing ${d}`:"Writing file";break;case"Bash":l=a?a.split(`
176
176
  `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let y=s??a??void 0,b=s?Sa(s)?s:cu(e,s):void 0,h=o[o.length-1];h&&h.kind==="tool_group"&&h.tool===i?h.items.push({label:l,detail:y,...b?{filePath:b}:{}}):o.push({kind:"tool_group",tool:i,items:[{label:l,detail:y,...b?{filePath:b}:{}}]})}return o}function wu(t,e){if(t.processedIds.length===0&&t.success)return"No accepted decisions were ready for model projection.";if(t.success&&t.proposalId)return"";let n=[];return t.success?n.push("Model suggestion ready."):n.push("Model projection failed."),t.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),t.error&&(n.push(""),n.push(`Error: ${t.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
177
- `)}function vu(t,e=96){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function xa(t){let e=t.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${a}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(t.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),o=(t.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=t.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...o,...n,...r].map(s=>vu(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function xu(t,e){let n=t.headers.origin;Pa(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}var bu=16384,Su=131072;async function De(t,e=bu){let n=[],o=0;for await(let i of t){let s=typeof i=="string"?Buffer.from(i):i;if(o+=s.length,o>e)throw new Error("Request body too large");n.push(s)}if(n.length===0)return{};let r=JSON.parse(Buffer.concat(n).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function Pu(t,e){let n=[],o=0;for await(let r of t){let i=typeof r=="string"?Buffer.from(r):r;if(o+=i.length,o>e)throw new Error("Request body too large");n.push(i)}return Buffer.concat(n)}function Tu(t,e){let n=t.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function ku(t,e){if(!t)return e;let n=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,o,r,i]=n;return`\x1B[38;2;${parseInt(o,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Yo(t,e){try{t.res.write(`event: ${e.type}
177
+ `)}function vu(t,e=96){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function xa(t){let e=t.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${a}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}${d.token?` [${d.token}]`:""}`)}),n=(t.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),o=(t.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=t.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...o,...n,...r].map(s=>vu(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function xu(t,e){let n=t.headers.origin;Pa(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}var bu=16384,Su=131072;async function De(t,e=bu){let n=[],o=0;for await(let i of t){let s=typeof i=="string"?Buffer.from(i):i;if(o+=s.length,o>e)throw new Error("Request body too large");n.push(s)}if(n.length===0)return{};let r=JSON.parse(Buffer.concat(n).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function Pu(t,e){let n=[],o=0;for await(let r of t){let i=typeof r=="string"?Buffer.from(r):r;if(o+=i.length,o>e)throw new Error("Request body too large");n.push(i)}return Buffer.concat(n)}function Tu(t,e){let n=t.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function ku(t,e){if(!t)return e;let n=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,o,r,i]=n;return`\x1B[38;2;${parseInt(o,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Yo(t,e){try{t.res.write(`event: ${e.type}
178
178
  data: ${JSON.stringify(e)}
179
179
 
180
180
  `)}catch{}}function pn(t){return t==="claude"||t==="codex"||t==="copilot"?t:void 0}async function Zo(t){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),o=await fetch(`http://127.0.0.1:${t}/status`,{signal:e.signal});return clearTimeout(n),o.ok?await o.json():null}catch{return null}}function Ru(t,e){return new Promise((n,o)=>{let r=s=>{t.removeListener("listening",i),o(s)},i=()=>{t.removeListener("error",r),n()};t.once("error",r),t.once("listening",i),t.listen(e,"127.0.0.1")})}async function Qn(t={}){let e=new Date().toISOString(),n=t.port??lu,o=t.projectRoot??process.cwd(),r=await ou(o).catch(()=>o),i=vt(r),s=await tn(r),a=t.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=t.tempDir??Ze(au(),"popmelt-bridge"),l=t.maxTurns??40,y=t.maxBudgetUsd??1,b=[...t.allowedTools??pu],h=t.claudePath??"claude",k=t.copilotPath??"copilot",P=t.provider??"codex",g=t.timeoutMs,u=t.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,I=t.restartMode??"embedded",w=n,p={},j={claude:h,codex:"codex",copilot:k};for(let[c,x]of Object.entries(j))try{let _=x.includes("/")?x:Zp("which",[x],{encoding:"utf-8"}).trim();p[c]={available:!0,path:_}}catch{p[c]={available:!1,path:null}}function f(c,x){return new Promise(_=>{let v=ya(x,["--version"],{stdio:["ignore","ignore","ignore"]}),M=!1,R=J=>{M||(M=!0,_(J))},N=setTimeout(()=>{v.kill("SIGTERM"),R(!0)},5e3);v.on("error",()=>{clearTimeout(N),R(!1)}),v.on("close",J=>{clearTimeout(N),R(J===0)})})}await Promise.all([(async()=>{p.claude&&(p.claude.models=p.claude.available&&p.claude.path?await Ys(p.claude.path).catch(()=>Bo):Bo)})(),(async()=>{p.codex&&(p.codex.models=p.codex.available&&p.codex.path?await Xs(p.codex.path).catch(()=>Un):Un)})(),(async()=>{p.copilot&&(p.copilot.models=p.copilot.available&&p.copilot.path?await Qs(p.copilot.path).catch(()=>[zn]):[zn])})()]);let[m,A,D]=await Promise.all([Jr(r),qr(r),Lr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=m),p.codex&&(p.codex.mcp=A),p.copilot&&(p.copilot.mcp=D),m.found&&m.name&&b.push(`mcp__${m.name}__*`),await eu(d,{recursive:!0}),ba(d).catch(()=>{});let T=new qo(1),O=new _o,H=new $o(Ia),K=null,E=0,V=!1,G=()=>{E+=1,V=!1,K&&clearTimeout(K),K=null},fe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(I!=="detached"||H.size>0||V)return;V=!0;let c=++E,x=Date.now()+hu,_=()=>{if(c!==E)return;if(H.size>0){G();return}if(!(T.isRunning||T.depth>0||O.isRunning||O.depth>0)||Date.now()>=x){V=!1,K=setTimeout(fe,50),K.unref?.();return}K=setTimeout(_,250),K.unref?.()};_()},oe=new Set,S=new Go(r),C=await S.recoverInterruptedTurns();C>0&&console.warn(`[Popmelt] Recovered ${C} interrupted thread turn(s) from durable history.`);let q=new jo(r);q.sweep();let B=new en(r),Q=new Et(r,i);try{let c=await Q.store.migrateTopology();c.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${c.relationMutations} relation mutation(s)).`)}catch(c){console.warn(`[Popmelt] Imprint topology migration deferred: ${c instanceof Error?c.message:String(c)}`)}let he=new Ko(r),Ce=new Po(r),se=new Eo(r,{claudePath:h,provider:P,timeoutMs:g,loadProjectableDecisions:c=>B.getProjectableDecisions(c),onEvent:c=>{for(let x of oe)Yo(x,c)}}),Ne=new go({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:S,memoryService:B,imprintService:Q,loadConcreteModel:()=>se.loadModel()});B.beginAutomaticInitialization({writerVersion:Ye}).then(async c=>{c.state==="ready"?(await B.migrateImprintSnapshot(),await B.syncImprintGraph(),await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),P!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Oe({provider:P,reason:"Project accepted decisions that were waiting when the bridge restarted"})):c.state==="degraded"&&console.warn(`[\u22B9 ${w}] Product memory is degraded; legacy preview remains available: ${c.error}`)});let Pt=20,yn=300*1e3,Ae=[];function it(){let c=Date.now()-yn;for(;Ae.length>0&&(Ae[0].completedAt<c||Ae.length>Pt);)Ae.shift()}let Tt=new Map;T.addListener((c,x,_)=>{for(let v of oe)(!_||!v.sourceId||v.sourceId===_)&&Yo(v,c)}),O.addListener((c,x,_)=>{for(let v of oe)(!_||!v.sourceId||v.sourceId===_)&&Yo(v,c)}),O.setProcessor(async c=>{let x=c.provider??P;try{let _=await se.run({provider:x,model:c.model,threadId:c.threadId,presentationJobId:c.id,agentSettings:c.agentSettings});if(c.status==="cancelled")return;let v=await se.loadRuns(),M=_.runId?v.runs.find(N=>N.id===_.runId):void 0;if(_.success&&_.proposalId){let N=await se.findModelProposal(_.proposalId),J=await se.loadModel(),U=N?Ps(N,J):null;if(N&&U){let F=N.decisionIds.map(L=>({decisionId:L,status:"projected"}));await B.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(L=>({path:L.path,value:L.value,decisionIds:L.decisionIds})),coverage:F}),await se.applySelectedModelProposal(N.id,U.map(L=>({path:L.path,value:L.value})),U.map(L=>({group:L.path[0]==="rules"||L.path[0]==="components"||L.path[0]==="tokens"?L.path[0]:"model",label:L.label??L.id,detail:L.rationale,path:L.path,value:L.value})),"automatic")}}let R=wu(_,M);if(c.threadId&&(await S.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:R,model:c.model,provider:x})||await S.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:R,model:c.model,provider:x})),_.success)c.status="done",c.result=R,O.broadcast({type:"done",jobId:c.id,success:!0,responseText:R,threadId:c.threadId},c.id,c.sourceId),Ae.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),it();else{if(c.status="error",c.error=_.error??"Projection failed",c.threadId){let N=`Model projection failed.
package/dist/index.d.mts CHANGED
@@ -23,6 +23,30 @@ type PopmeltProviderProps = PropsWithChildren<{
23
23
  declare function PopmeltProvider({ children, enabled, bridgeUrl, projectId: projectIdProp, navigate: navigateProp, }: PopmeltProviderProps): react.JSX.Element;
24
24
  declare function usePopmelt(): PopmeltContextValue;
25
25
 
26
+ declare const STICKER_COLOR_NAMES: readonly ["slate", "gray", "zinc", "neutral", "stone", "red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "sky", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose"];
27
+ type StickerColorName = (typeof STICKER_COLOR_NAMES)[number];
28
+ declare const STICKER_COLOR_STEPS: readonly [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
29
+ type StickerColorStep = (typeof STICKER_COLOR_STEPS)[number];
30
+
31
+ declare const STICKER_FAMILIES: readonly ["padding", "margin", "border", "radius", "stack", "grid", "text", "color", "transform", "opacity"];
32
+ type StickerFamily = (typeof STICKER_FAMILIES)[number];
33
+ declare const SPACING_STEPS: readonly [0, 1, 2, 3, 4, 6, 8, 10, 12, 16];
34
+ declare const BORDER_STEPS: readonly [0, 1, 2, 4, 8];
35
+ declare const ALIGN_STEPS: readonly ["stretch", "start", "center", "end", "baseline"];
36
+ declare const JUSTIFY_STEPS: readonly ["start", "center", "end", "between", "around", "evenly"];
37
+ declare const GRID_COUNT_STEPS: readonly [1, 2, 3, 4, 5, 6];
38
+ declare const FONT_SIZE_STEPS: readonly ["xs", "sm", "base", "lg", "xl", "2xl", "3xl", "4xl"];
39
+ declare const FONT_WEIGHT_STEPS: readonly [300, 400, 500, 600, 700, 800];
40
+ declare const LINE_HEIGHT_STEPS: readonly ["none", "tight", "snug", "normal", "relaxed", "loose"];
41
+ declare const LETTER_SPACING_STEPS: readonly ["tighter", "tight", "normal", "wide", "wider", "widest"];
42
+ declare const TEXT_ALIGN_STEPS: readonly ["left", "center", "right", "justify"];
43
+ declare const SCALE_STEPS: readonly [0, 50, 75, 90, 95, 100, 105, 110, 125, 150];
44
+ declare const ROTATE_STEPS: readonly [0, 1, 2, 3, 6, 12, 45, 90, 180];
45
+ declare const OPACITY_STEPS: readonly [0, 5, 10, 20, 25, 30, 40, 50, 60, 70, 75, 80, 90, 95, 100];
46
+ declare const MIX_BLEND_STEPS: readonly ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"];
47
+ type StickerStep = (typeof SPACING_STEPS)[number] | (typeof BORDER_STEPS)[number] | (typeof ALIGN_STEPS)[number] | (typeof JUSTIFY_STEPS)[number] | (typeof GRID_COUNT_STEPS)[number] | (typeof FONT_SIZE_STEPS)[number] | (typeof FONT_WEIGHT_STEPS)[number] | (typeof LINE_HEIGHT_STEPS)[number] | (typeof LETTER_SPACING_STEPS)[number] | (typeof TEXT_ALIGN_STEPS)[number] | (typeof SCALE_STEPS)[number] | (typeof ROTATE_STEPS)[number] | (typeof OPACITY_STEPS)[number] | (typeof MIX_BLEND_STEPS)[number] | StickerColorStep;
48
+ type StickerSubproperty = 'all' | 'x' | 'y' | 'top' | 'right' | 'bottom' | 'left' | 'top-left' | 'top-right' | 'bottom-right' | 'bottom-left' | 'vertical' | 'horizontal' | 'gap' | 'align' | 'justify' | 'rows' | 'columns' | 'size' | 'weight' | 'line-height' | 'letter-spacing' | 'text-align' | 'color' | 'translate' | 'scale' | 'rotate' | 'opacity' | 'mix-blend' | StickerColorName;
49
+
26
50
  type AnnotationLifecycleStatus = 'pending' | 'sending' | 'in_flight' | 'resolved' | 'needs_review' | 'dismissed' | 'waiting_input' | 'failed';
27
51
  type ScopeBreadth = 'instance' | 'pattern';
28
52
  type ScopeTarget = 'element' | 'component' | 'token';
@@ -30,7 +54,7 @@ type Scope = {
30
54
  breadth: ScopeBreadth;
31
55
  target: ScopeTarget;
32
56
  };
33
- declare const TOOL_TYPES: readonly ["freehand", "line", "rectangle", "circle", "inspector", "hand", "model"];
57
+ declare const TOOL_TYPES: readonly ["freehand", "line", "rectangle", "circle", "inspector", "sticker", "hand", "model"];
34
58
  type ToolType = (typeof TOOL_TYPES)[number];
35
59
  type AnnotationType = ToolType | 'text';
36
60
  type Point = {
@@ -61,6 +85,12 @@ type StyleChange = {
61
85
  property: string;
62
86
  original: string;
63
87
  modified: string;
88
+ token?: string;
89
+ sticker?: {
90
+ family: StickerFamily;
91
+ subproperty: StickerSubproperty;
92
+ step: StickerStep;
93
+ };
64
94
  };
65
95
  type StyleModification = {
66
96
  selector: string;