From 19cfaf5c32dd75ba14e7d7425952f8d38360f10e Mon Sep 17 00:00:00 2001
From: JonatasFreireDev
Date: Thu, 16 Jul 2026 13:28:10 -0300
Subject: [PATCH 1/3] feat: add local project status server
---
FRAMEWORK.md | 19 ++
PRODUCT.md | 62 ++++++
docs/execution-runtime.md | 20 ++
internal/cli/app_test.go | 2 +-
internal/cli/cobra.go | 1 +
internal/cli/server.go | 97 +++++++++
internal/projectserver/api.go | 138 +++++++++++++
internal/projectserver/dashboard.html | 95 +++++++++
internal/projectserver/server.go | 280 ++++++++++++++++++++++++++
internal/projectserver/server_test.go | 117 +++++++++++
internal/workflow/rejection_test.go | 84 ++++++++
internal/workflow/workflow.go | 38 ++--
12 files changed, 938 insertions(+), 15 deletions(-)
create mode 100644 PRODUCT.md
create mode 100644 internal/cli/server.go
create mode 100644 internal/projectserver/api.go
create mode 100644 internal/projectserver/dashboard.html
create mode 100644 internal/projectserver/server.go
create mode 100644 internal/projectserver/server_test.go
create mode 100644 internal/workflow/rejection_test.go
diff --git a/FRAMEWORK.md b/FRAMEWORK.md
index e5b930a..0e5c3af 100644
--- a/FRAMEWORK.md
+++ b/FRAMEWORK.md
@@ -589,6 +589,7 @@ draft
proposed
materialized (Execution Graph only)
approved
+rejected
in_progress
implemented
validated
@@ -602,6 +603,10 @@ Rules:
- `draft`: artifact created, still incomplete.
- `proposed`: ready for human or audit review.
- `approved`: can feed the next stage.
+- `rejected`: a human reviewed the current content and declined approval with a
+ required rationale. It cannot feed downstream work. A human may reject an
+ approved artifact to reopen it. After revision, it may return to `draft`,
+ `proposed`, or directly to `approved` through a new, recorded human review.
- `in_progress`: being implemented.
- `implemented`: code or artifact was produced.
- `validated`: passed QA, review, Security Review when applicable, and has sufficient evidence.
@@ -615,6 +620,9 @@ Mandatory transitions:
- `validate --write-registry` preserves `parents`, `children`, `depends_on`, decisions, and delivery dependencies from structured companion `context.md` YAML. Starting-point-specific parents are additive and must not erase the existing product graph.
- `proposed`: does not require an approval record, but must not advance from an incomplete parent gate.
- `approved` and later states: require a corresponding approval record in `.product/history/`, with `artifact_id`, `path`, `content_hash`, `status_granted`, `approved_by`, `approved_at`, and `notes`. Validator and operational navigation both require that record to match the current artifact content; editing status prose alone never advances work.
+- Rejection uses the same immutable history record with `status_granted:
+ rejected`; `approved_by` identifies the rejecting human for compatibility
+ with the audit schema, and `notes` must state what requires revision.
- Human approval may be applied to one artifact with `approve` or to an explicit batch with `approve-batch`. Batch approval must preview the exact paths, IDs, hashes, ignored artifacts, blockers, and next gate first; it requires explicit scope, human identity, and `--yes`, and never includes stale or ineligible artifacts.
- `approved -> in_progress`: requires an approved task or an explicit prototype/draft exception.
- `in_progress -> implemented`: requires structured working-tree evidence in the task file: branch, base commit, changed paths, diff hash, tests, and gate results. It does not require a commit.
@@ -748,6 +756,17 @@ Installation, CLI update, product upgrade, and removal are separate. Install scr
The CLI's generated help is authoritative for command syntax. Git history records how framework boundaries evolved; skills define specialist procedure; templates define artifact structure; `BOOTSTRAP.md` defines the initial route; `context.md` defines local state and handoff.
+### Local project-status server
+
+The optional `server` command provides a local-only, browser-based status
+surface for project users. It is not the technical workspace `dashboard`, does
+not expose a remote API, and does not create approvals itself. The interface
+may present eligible approval actions only through the existing approval engine,
+which remains responsible for previews, explicit confirmation, evidence, and
+authorization boundaries. The local process binds to loopback, supports graceful
+shutdown through `Ctrl+C` or `server stop`, and stores only ephemeral connection
+metadata under `.product/`.
+
## 16. Final Rule
The framework must help agents think before they build.
diff --git a/PRODUCT.md b/PRODUCT.md
new file mode 100644
index 0000000..86347c4
--- /dev/null
+++ b/PRODUCT.md
@@ -0,0 +1,62 @@
+# Product
+
+## Register
+
+product
+
+## Platform
+
+web
+
+## Users
+
+The primary users are people authorized to approve project documentation and
+project collaborators who need to understand its current state. Approvers need
+to identify the items that block progress, inspect their context and content,
+and take a governed approval or rejection action. Collaborators need the same
+clear navigation and status visibility without gaining approval authority.
+
+## Product Purpose
+
+The project dashboard makes documentation and its delivery status understandable
+at a glance. Its primary outcome is that a user can immediately see what is
+blocking the project, navigate the relevant documentation, understand why it
+matters, and take the next permitted action.
+
+## Positioning
+
+Turn a project's documentation tree into a clear, actionable view of what is
+blocking progress and what can safely move forward.
+
+## Brand Personality
+
+Usable, clean, and pleasant. The interface should feel calm and dependable when
+someone is deciding whether to approve a project artifact.
+
+## Anti-references
+
+Avoid extravagant or decorative color. Status color must communicate a concrete
+state and always be accompanied by text or another non-color cue. Avoid dense,
+technical-first screens that expose implementation detail before the user asks
+for it.
+
+## Design Principles
+
+1. Show blockers before activity: the first screen answers what is preventing
+ progress.
+2. Reveal detail through navigation: start with a readable documentation tree
+ and disclose file content, metadata, and dependencies only for the selected
+ item.
+3. Make authority explicit: approval, rejection, and batch approval actions are
+ visible only for eligible artifacts and authorized people.
+4. Preserve decision context: every approval action makes the artifact content,
+ current status, and reason for its gate available before confirmation.
+5. Keep the visual system quiet: use restrained, purposeful color and clear
+ hierarchy rather than decorative metrics or technical noise.
+
+## Accessibility & Inclusion
+
+All primary navigation and approval workflows must be usable with a keyboard
+and understandable with screen readers. Status must never rely on color alone.
+Interactive controls need accessible names, visible focus, and predictable
+keyboard order.
diff --git a/docs/execution-runtime.md b/docs/execution-runtime.md
index e45b8ac..c469477 100644
--- a/docs/execution-runtime.md
+++ b/docs/execution-runtime.md
@@ -53,6 +53,26 @@ ACP dispatch is experimental and disabled by default. A run requires explicit en
Extensions are versioned manifests discovered without execution. A capability is usable only when that manifest declares it and the product has a matching versioned record under `.product/extensions/`; discovery itself grants no trust or authority.
+## Local project-status server
+
+`spec-framework server` is a local-only, user-facing status surface. It binds
+only to `127.0.0.1`, opens the browser by default, and does not expose a remote
+API. It is deliberately separate from `dashboard`, which is the technical
+workspace view.
+
+Run `spec-framework server start` to start it, `spec-framework server status`
+to print its local URL, and `spec-framework server stop` from another terminal
+to request graceful shutdown. The foreground process also stops on `Ctrl+C`.
+The server stores a short-lived local descriptor under `.product/server.json`;
+it is removed after normal shutdown and never contains approval data.
+
+When the status surface enables review actions, it delegates approval and
+rejection to the same lifecycle engine as the CLI. A rejection requires a
+human identity and revision rationale, writes immutable history, and moves an
+eligible artifact to `rejected`, including an approved artifact that must be
+reopened. A revised rejected artifact may then be directly approved through a
+new recorded human review; the runtime never silently edits product scope.
+
## Owning skills
- `execution-graph`: defines and validates the DAG and graph lifecycle.
diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go
index d4df0cc..7b9147a 100644
--- a/internal/cli/app_test.go
+++ b/internal/cli/app_test.go
@@ -45,7 +45,7 @@ func TestUnknownCommandIsUsageError(t *testing.T) {
func TestCobraCommandTreeKeepsStableTopLevelCommands(t *testing.T) {
root := cli.New("test").NewCommand(&bytes.Buffer{}, &bytes.Buffer{})
- for _, name := range []string{"init", "validate", "graph", "runtime", "update", "uninstall", "upgrade", "version"} {
+ for _, name := range []string{"init", "validate", "graph", "runtime", "server", "update", "uninstall", "upgrade", "version"} {
command, _, err := root.Find([]string{name})
if err != nil || command == root || command.Name() != name {
t.Errorf("Cobra command %q was not registered: command=%v err=%v", name, command, err)
diff --git a/internal/cli/cobra.go b/internal/cli/cobra.go
index acbec11..d56ecd1 100644
--- a/internal/cli/cobra.go
+++ b/internal/cli/cobra.go
@@ -66,6 +66,7 @@ func (app App) NewCommand(stdout, stderr io.Writer) *cobra.Command {
app.legacyCommand("approve-stage", "Approve eligible artifacts in a stage atomically.", func(args []string, out, errout io.Writer) int { return runStage("approve-stage", args, out, errout) }, stdout, stderr),
app.legacyCommand("impact", "Inspect a decision's validity and propagation.", func(args []string, out, errout io.Writer) int { return runImpact(args, out, errout) }, stdout, stderr),
app.legacyCommand("dashboard", "Show a consolidated workflow dashboard.", func(args []string, out, errout io.Writer) int { return runDashboard(args, out, errout) }, stdout, stderr),
+ app.legacyCommand("server", "Run the local project-status server.", func(args []string, out, errout io.Writer) int { return runServer(args, out, errout) }, stdout, stderr),
app.legacyCommand("decisions", "Check or migrate product decisions.", func(args []string, out, errout io.Writer) int { return runDecisions(args, out, errout) }, stdout, stderr),
app.legacyCommand("dispatch", "Plan and supervise governed subagent assignments.", func(args []string, out, errout io.Writer) int { return runDispatch(args, out, errout) }, stdout, stderr),
)
diff --git a/internal/cli/server.go b/internal/cli/server.go
new file mode 100644
index 0000000..283b327
--- /dev/null
+++ b/internal/cli/server.go
@@ -0,0 +1,97 @@
+package cli
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/projectserver"
+)
+
+func runServer(args []string, stdout, stderr io.Writer) int {
+ action := "start"
+ if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
+ action, args = args[0], args[1:]
+ }
+ flags := flag.NewFlagSet("server "+action, flag.ContinueOnError)
+ flags.SetOutput(stderr)
+ root := flags.String("product-root", "product", "product root")
+ port := flags.Int("port", 0, "local port; 0 selects a free port")
+ noOpen := flags.Bool("no-open", false, "do not open the browser")
+ if err := flags.Parse(args); err != nil {
+ return 2
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ productRoot := *root
+ if !filepath.IsAbs(productRoot) {
+ productRoot = filepath.Join(cwd, productRoot)
+ }
+ switch action {
+ case "start":
+ return startServer(productRoot, *port, *noOpen, stdout, stderr)
+ case "stop":
+ if err := projectserver.Stop(productRoot); err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintln(stdout, "Local project server stopped.")
+ return 0
+ case "status":
+ descriptor, err := projectserver.Healthy(productRoot)
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Local project server: running\n- URL: %s\n", descriptor.URL)
+ return 0
+ default:
+ fmt.Fprintln(stderr, "server requires start, stop, or status")
+ return 2
+ }
+}
+
+func startServer(root string, port int, noOpen bool, stdout, stderr io.Writer) int {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ running, err := projectserver.Start(ctx, projectserver.Config{ProductRoot: root, Port: port})
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Local project server running\n- URL: %s\n- Stop: Ctrl+C or spec-framework server stop --product-root %s\n", running.URL, filepath.Clean(root))
+ if !noOpen {
+ if err := openBrowser(running.URL); err != nil {
+ fmt.Fprintln(stderr, "Could not open browser:", err)
+ }
+ }
+ if err := <-running.Done; err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ return 0
+}
+
+func openBrowser(url string) error {
+ var command *exec.Cmd
+ switch runtime.GOOS {
+ case "windows":
+ command = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
+ case "darwin":
+ command = exec.Command("open", url)
+ default:
+ command = exec.Command("xdg-open", url)
+ }
+ return command.Start()
+}
diff --git a/internal/projectserver/api.go b/internal/projectserver/api.go
new file mode 100644
index 0000000..84848b0
--- /dev/null
+++ b/internal/projectserver/api.go
@@ -0,0 +1,138 @@
+package projectserver
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+type projectStatus struct {
+ Documents []document `json:"documents"`
+ Metrics metrics `json:"metrics"`
+}
+
+type metrics struct {
+ Total int `json:"total"`
+ Approved int `json:"approved"`
+ Pending int `json:"pending"`
+ Rejected int `json:"rejected"`
+}
+
+type document struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Path string `json:"path"`
+ Folder string `json:"folder"`
+ Status string `json:"status"`
+ Updated string `json:"updated"`
+ Content string `json:"content"`
+}
+
+type transitionRequest struct {
+ ArtifactID string `json:"artifactId"`
+ Status string `json:"status"`
+ ApprovedBy string `json:"approvedBy"`
+ Notes string `json:"notes"`
+ Confirmed bool `json:"confirmed"`
+}
+
+type batchApprovalRequest struct {
+ ArtifactIDs []string `json:"artifactIds"`
+ ApprovedBy string `json:"approvedBy"`
+ Notes string `json:"notes"`
+ Confirmed bool `json:"confirmed"`
+}
+
+func readStatus(root string) (projectStatus, error) {
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ return projectStatus{}, fmt.Errorf("read artifact registry: %w", err)
+ }
+ result := projectStatus{Documents: make([]document, 0, len(registry.Artifacts))}
+ for _, artifact := range registry.Artifacts {
+ path := filepath.Join(root, filepath.FromSlash(artifact.Path))
+ content, err := os.ReadFile(path)
+ if err != nil {
+ return projectStatus{}, fmt.Errorf("read %s: %w", artifact.Path, err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ return projectStatus{}, err
+ }
+ result.Documents = append(result.Documents, document{ID: artifact.ID, Title: titleFor(artifact, content), Path: filepath.ToSlash(artifact.Path), Folder: folderFor(artifact.Path), Status: artifact.Status, Updated: info.ModTime().UTC().Format(time.RFC3339), Content: string(content)})
+ result.Metrics.Total++
+ switch artifact.Status {
+ case "approved":
+ result.Metrics.Approved++
+ case "rejected":
+ result.Metrics.Rejected++
+ default:
+ result.Metrics.Pending++
+ }
+ }
+ sort.Slice(result.Documents, func(i, j int) bool { return result.Documents[i].Path < result.Documents[j].Path })
+ return result, nil
+}
+
+func findArtifact(root, id string) (workflow.Artifact, error) {
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ return workflow.Artifact{}, err
+ }
+ for _, artifact := range registry.Artifacts {
+ if artifact.ID == id {
+ return artifact, nil
+ }
+ }
+ return workflow.Artifact{}, errors.New("artifact not found")
+}
+
+func titleFor(artifact workflow.Artifact, content []byte) string {
+ for _, line := range strings.Split(string(content), "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "# ") {
+ return strings.TrimSpace(strings.TrimPrefix(line, "# "))
+ }
+ }
+ return artifact.ID
+}
+
+func folderFor(path string) string {
+ folder := filepath.ToSlash(filepath.Dir(path))
+ if folder == "." {
+ return "Raiz"
+ }
+ return folder
+}
+
+func decodeJSON(request *http.Request, target any) error {
+ defer request.Body.Close()
+ decoder := json.NewDecoder(io.LimitReader(request.Body, 1<<20))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ return errors.New("invalid request body")
+ }
+ return nil
+}
+
+func writeJSON(w http.ResponseWriter, status int, value any) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(value)
+}
+
+func writeAPIError(w http.ResponseWriter, status int, err error) {
+ writeJSON(w, status, map[string]string{"error": err.Error()})
+}
+func methodNotAllowed(w http.ResponseWriter) {
+ writeAPIError(w, http.StatusMethodNotAllowed, errors.New("method not allowed"))
+}
diff --git a/internal/projectserver/dashboard.html b/internal/projectserver/dashboard.html
new file mode 100644
index 0000000..3034f23
--- /dev/null
+++ b/internal/projectserver/dashboard.html
@@ -0,0 +1,95 @@
+
+
+
+
+
+ Status do projeto
+
+
+
+ Pular para o conteúdo
+
+
+ !
1 pendência bloqueadora impede o progresso do projeto
Revise a pendência abaixo para destravar o andamento.
Especificação de check-in
Fluxo de exceção não documentado para cancelamento de reserva.
+
Especificação de check-in
04 Solução › 04.2 Arquitetura · Atualizado hoje às 09:41
Bloqueador
+
+
+
+
+
+
+
diff --git a/internal/projectserver/server.go b/internal/projectserver/server.go
new file mode 100644
index 0000000..472db29
--- /dev/null
+++ b/internal/projectserver/server.go
@@ -0,0 +1,280 @@
+package projectserver
+
+import (
+ "context"
+ "crypto/rand"
+ _ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+const descriptorName = "server.json"
+
+// Config constrains the dashboard runtime to a local product directory.
+type Config struct {
+ ProductRoot string
+ Port int
+}
+
+// Descriptor is the minimal local control record used by server status and stop.
+// The token makes the stop endpoint unavailable to unrelated local processes.
+type Descriptor struct {
+ URL string `json:"url"`
+ Token string `json:"token"`
+}
+
+type Running struct {
+ URL string
+ Done <-chan error
+}
+
+func Start(ctx context.Context, config Config) (Running, error) {
+ root, err := filepath.Abs(config.ProductRoot)
+ if err != nil {
+ return Running{}, err
+ }
+ info, err := os.Stat(root)
+ if err != nil || !info.IsDir() {
+ return Running{}, fmt.Errorf("product root is not a directory: %s", root)
+ }
+ listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", fmt.Sprint(config.Port)))
+ if err != nil {
+ return Running{}, err
+ }
+ token, err := newToken()
+ if err != nil {
+ _ = listener.Close()
+ return Running{}, err
+ }
+ url := "http://" + listener.Addr().String()
+ if err := writeDescriptor(root, Descriptor{URL: url, Token: token}); err != nil {
+ _ = listener.Close()
+ return Running{}, err
+ }
+
+ shutdown := make(chan struct{})
+ var shutdownOnce sync.Once
+ requestShutdown := func() { shutdownOnce.Do(func() { close(shutdown) }) }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = io.WriteString(w, dashboardHTML)
+ })
+ mux.HandleFunc("/__spec-framework/health", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"status":"ok"}`)
+ })
+ mux.HandleFunc("/__spec-framework/stop", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.Header.Get("X-Spec-Server-Token") != token {
+ http.NotFound(w, r)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ requestShutdown()
+ })
+ mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ methodNotAllowed(w)
+ return
+ }
+ status, err := readStatus(root)
+ if err != nil {
+ writeAPIError(w, http.StatusInternalServerError, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, status)
+ })
+ mux.HandleFunc("/api/transition", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w)
+ return
+ }
+ var request transitionRequest
+ if err := decodeJSON(r, &request); err != nil {
+ writeAPIError(w, http.StatusBadRequest, err)
+ return
+ }
+ if !request.Confirmed {
+ writeAPIError(w, http.StatusBadRequest, errors.New("confirmation is required"))
+ return
+ }
+ if strings.TrimSpace(request.ApprovedBy) == "" {
+ writeAPIError(w, http.StatusBadRequest, errors.New("approver identity is required"))
+ return
+ }
+ artifact, err := findArtifact(root, request.ArtifactID)
+ if err != nil {
+ writeAPIError(w, http.StatusNotFound, err)
+ return
+ }
+ record, err := workflow.Approve(root, filepath.Join(root, filepath.FromSlash(artifact.Path)), request.Status, request.ApprovedBy, request.Notes)
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, record)
+ })
+ mux.HandleFunc("/api/batch-approve", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w)
+ return
+ }
+ var request batchApprovalRequest
+ if err := decodeJSON(r, &request); err != nil {
+ writeAPIError(w, http.StatusBadRequest, err)
+ return
+ }
+ if !request.Confirmed {
+ writeAPIError(w, http.StatusBadRequest, errors.New("confirmation is required"))
+ return
+ }
+ if strings.TrimSpace(request.ApprovedBy) == "" {
+ writeAPIError(w, http.StatusBadRequest, errors.New("approver identity is required"))
+ return
+ }
+ plan, err := workflow.BuildBatchApprovalPlan(root, workflow.BatchScope{IDs: request.ArtifactIDs}, "approved")
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ records, err := workflow.ApproveBatch(root, plan, request.ApprovedBy, request.Notes)
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, records)
+ })
+
+ httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
+ done := make(chan error, 1)
+ go func() {
+ err := httpServer.Serve(listener)
+ if !errors.Is(err, http.ErrServerClosed) {
+ done <- err
+ return
+ }
+ done <- nil
+ }()
+ go func() {
+ select {
+ case <-ctx.Done():
+ case <-shutdown:
+ }
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = httpServer.Shutdown(shutdownCtx)
+ _ = os.Remove(descriptorPath(root))
+ }()
+ return Running{URL: url, Done: done}, nil
+}
+
+func Stop(productRoot string) error {
+ descriptor, err := ReadDescriptor(productRoot)
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequest(http.MethodPost, descriptor.URL+"/__spec-framework/stop", nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("X-Spec-Server-Token", descriptor.Token)
+ client := &http.Client{Timeout: 3 * time.Second}
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("local server is not reachable: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ return fmt.Errorf("local server refused stop request: %s", resp.Status)
+ }
+ return nil
+}
+
+func Healthy(productRoot string) (Descriptor, error) {
+ descriptor, err := ReadDescriptor(productRoot)
+ if err != nil {
+ return Descriptor{}, err
+ }
+ client := &http.Client{Timeout: 3 * time.Second}
+ response, err := client.Get(descriptor.URL + "/__spec-framework/health")
+ if err != nil {
+ return Descriptor{}, fmt.Errorf("local server is not reachable: %w", err)
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ return Descriptor{}, fmt.Errorf("local server health check failed: %s", response.Status)
+ }
+ return descriptor, nil
+}
+
+func ReadDescriptor(productRoot string) (Descriptor, error) {
+ data, err := os.ReadFile(descriptorPath(productRoot))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return Descriptor{}, errors.New("no local project server is recorded for this product")
+ }
+ return Descriptor{}, err
+ }
+ var descriptor Descriptor
+ if err := json.Unmarshal(data, &descriptor); err != nil {
+ return Descriptor{}, fmt.Errorf("read local server descriptor: %w", err)
+ }
+ if !strings.HasPrefix(descriptor.URL, "http://127.0.0.1:") || descriptor.Token == "" {
+ return Descriptor{}, errors.New("local server descriptor is invalid")
+ }
+ return descriptor, nil
+}
+
+func descriptorPath(root string) string { return filepath.Join(root, ".product", descriptorName) }
+
+func writeDescriptor(root string, descriptor Descriptor) error {
+ dir := filepath.Dir(descriptorPath(root))
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ data, err := json.Marshal(descriptor)
+ if err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(dir, ".server-*.tmp")
+ if err != nil {
+ return err
+ }
+ name := tmp.Name()
+ defer os.Remove(name)
+ if _, err := tmp.Write(data); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(name, descriptorPath(root))
+}
+
+func newToken() (string, error) {
+ bytes := make([]byte, 24)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(bytes), nil
+}
+
+//go:embed dashboard.html
+var dashboardHTML string
diff --git a/internal/projectserver/server_test.go b/internal/projectserver/server_test.go
new file mode 100644
index 0000000..86dcb8d
--- /dev/null
+++ b/internal/projectserver/server_test.go
@@ -0,0 +1,117 @@
+package projectserver
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+func TestStartServesLocalPageAndStopRemovesDescriptor(t *testing.T) {
+ root := t.TempDir()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ running, err := Start(ctx, Config{ProductRoot: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ response, err := http.Get(running.URL + "/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("status=%s", response.Status)
+ }
+ if _, err := ReadDescriptor(root); err != nil {
+ t.Fatalf("descriptor: %v", err)
+ }
+ if _, err := Healthy(root); err != nil {
+ t.Fatalf("health: %v", err)
+ }
+ if err := Stop(root); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-running.Done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("server did not stop")
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ _, err := os.Stat(filepath.Join(root, ".product", descriptorName))
+ if os.IsNotExist(err) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("descriptor still exists: %v", err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func TestStatusAndRejectionEndpointsUseProductData(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := workflow.Artifact{ID: "TASK-1", Type: "task", Status: "draft", Path: "tasks/one.md"}
+ data, err := json.Marshal(workflow.Registry{Artifacts: []workflow.Artifact{artifact}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, ".product", "artifacts.json"), data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, "tasks", "one.md")
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("status: draft\n# Tarefa de exemplo\n\nConteúdo."), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ running, err := Start(ctx, Config{ProductRoot: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = Stop(root); <-running.Done }()
+ response, err := http.Get(running.URL + "/api/status")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var status projectStatus
+ if err := json.NewDecoder(response.Body).Decode(&status); err != nil {
+ t.Fatal(err)
+ }
+ if len(status.Documents) != 1 || status.Documents[0].Title != "Tarefa de exemplo" || status.Metrics.Pending != 1 {
+ t.Fatalf("status=%+v", status)
+ }
+ body := bytes.NewBufferString(`{"artifactId":"TASK-1","status":"rejected","approvedBy":"Product Owner","notes":"Falta definir os critérios.","confirmed":true}`)
+ response, err = http.Post(running.URL+"/api/transition", "application/json", body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("rejection status=%s", response.Status)
+ }
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("artifact status=%s", registry.Artifacts[0].Status)
+ }
+}
diff --git a/internal/workflow/rejection_test.go b/internal/workflow/rejection_test.go
new file mode 100644
index 0000000..f2589a5
--- /dev/null
+++ b/internal/workflow/rejection_test.go
@@ -0,0 +1,84 @@
+package workflow
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestRejectRequiresRationaleAndReturnsToDraft(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "draft", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: draft\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "rejected", "Product Owner", ""); err == nil || !strings.Contains(err.Error(), "requires notes") {
+ t.Fatalf("empty rejection err=%v", err)
+ }
+ record, err := Approve(root, path, "rejected", "Product Owner", "Clarify the failure path before approval.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if record.StatusGranted != "rejected" || record.Notes == "" {
+ t.Fatalf("record=%+v", record)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+ if _, err := Approve(root, path, "draft", "Product Owner", "Revisions started."); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestRejectCanReopenApprovedArtifact(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "approved", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: approved\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "rejected", "Product Owner", "The approved version needs a correction."); err != nil {
+ t.Fatal(err)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+}
+
+func TestRejectedArtifactCanBeApprovedAgain(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "rejected", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: rejected\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "approved", "Product Owner", "Revised after the rejection."); err != nil {
+ t.Fatal(err)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "approved" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+}
diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go
index e6bdef6..a26c395 100644
--- a/internal/workflow/workflow.go
+++ b/internal/workflow/workflow.go
@@ -373,10 +373,12 @@ func PreviewApproval(root, artifactPath, grant string) (ApprovalPreview, error)
return ApprovalPreview{}, fmt.Errorf("invalid status transition %s -> %s", a.Status, grant)
}
var blockers []string
- for _, pid := range a.ParentIDs {
- for _, p := range r.Artifacts {
- if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
- blockers = append(blockers, fmt.Sprintf("parent %s lacks current approval evidence", pid))
+ if grant != "rejected" && grant != "draft" && grant != "proposed" {
+ for _, pid := range a.ParentIDs {
+ for _, p := range r.Artifacts {
+ if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
+ blockers = append(blockers, fmt.Sprintf("parent %s lacks current approval evidence", pid))
+ }
}
}
}
@@ -388,14 +390,16 @@ func PreviewApproval(root, artifactPath, grant string) (ApprovalPreview, error)
if err != nil {
return ApprovalPreview{}, err
}
- validation, err := validator.ValidateCandidate(context.Background(), root, root, artifactPath, updated, grant)
- if err != nil {
- return ApprovalPreview{}, err
- }
validationBlockers := make([]string, 0)
- for _, diagnostic := range validation.Diagnostics {
- if filepath.ToSlash(diagnostic.File) == rel && (diagnostic.Check == "template-conformance" || diagnostic.Check == "import-provenance" || diagnostic.Check == "status-coherence" || diagnostic.Check == "qa-evidence" || diagnostic.Check == "delivery") && diagnostic.Severity == validator.Error {
- validationBlockers = append(validationBlockers, fmt.Sprintf("%s: %s", diagnostic.Check, diagnostic.Message))
+ if grant != "rejected" && grant != "draft" && grant != "proposed" {
+ validation, err := validator.ValidateCandidate(context.Background(), root, root, artifactPath, updated, grant)
+ if err != nil {
+ return ApprovalPreview{}, err
+ }
+ for _, diagnostic := range validation.Diagnostics {
+ if filepath.ToSlash(diagnostic.File) == rel && (diagnostic.Check == "template-conformance" || diagnostic.Check == "import-provenance" || diagnostic.Check == "status-coherence" || diagnostic.Check == "qa-evidence" || diagnostic.Check == "delivery") && diagnostic.Severity == validator.Error {
+ validationBlockers = append(validationBlockers, fmt.Sprintf("%s: %s", diagnostic.Check, diagnostic.Message))
+ }
}
}
updates, err := approvalUpdatesForArtifact(root, a, artifactPath, updated, grant)
@@ -736,14 +740,17 @@ func requiredContracts(contextPath string) []string {
func Approve(root, artifactPath, grant, approvedBy, notes string) (Approval, error) {
grant = strings.TrimSpace(grant)
- if !map[string]bool{"approved": true, "in_progress": true, "implemented": true, "validated": true, "released": true}[grant] {
+ if !map[string]bool{"draft": true, "proposed": true, "approved": true, "rejected": true, "in_progress": true, "implemented": true, "validated": true, "released": true}[grant] {
return Approval{}, fmt.Errorf("unsupported grant %q", grant)
}
+ if grant == "rejected" && strings.TrimSpace(notes) == "" {
+ return Approval{}, errors.New("rejection requires notes explaining what must be revised")
+ }
preview, err := PreviewApproval(root, artifactPath, grant)
if err != nil {
return Approval{}, err
}
- if len(preview.ParentBlockers) > 0 || len(preview.ValidationBlockers) > 0 {
+ if grant != "rejected" && grant != "draft" && grant != "proposed" && (len(preview.ParentBlockers) > 0 || len(preview.ValidationBlockers) > 0) {
return Approval{}, errors.New(strings.Join(append(preview.ParentBlockers, preview.ValidationBlockers...), "; "))
}
r, err := LoadRegistry(root)
@@ -766,6 +773,9 @@ func Approve(root, artifactPath, grant, approvedBy, notes string) (Approval, err
return Approval{}, fmt.Errorf("artifact is not registered: %s", rel)
}
for _, pid := range r.Artifacts[idx].ParentIDs {
+ if grant == "rejected" || grant == "draft" || grant == "proposed" {
+ break
+ }
for _, p := range r.Artifacts {
if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
return Approval{}, fmt.Errorf("parent %s lacks current approval evidence", pid)
@@ -1282,7 +1292,7 @@ func validTransition(from, to string) bool {
if from == to {
return true
}
- allowed := map[string][]string{"draft": {"proposed", "approved"}, "proposed": {"approved"}, "materialized": {"approved"}, "approved": {"in_progress"}, "in_progress": {"implemented"}, "implemented": {"validated"}, "validated": {"released"}}
+ allowed := map[string][]string{"draft": {"proposed", "approved", "rejected"}, "proposed": {"approved", "rejected"}, "materialized": {"approved", "rejected"}, "approved": {"in_progress", "rejected"}, "in_progress": {"implemented"}, "implemented": {"validated"}, "validated": {"released"}, "rejected": {"draft", "proposed", "approved"}}
return contains(allowed[from], to)
}
func readJSON(path string, value any) error {
From d5acf06dd223f3d98b03aced490e33e4f97195f2 Mon Sep 17 00:00:00 2001
From: JonatasFreireDev
Date: Thu, 16 Jul 2026 14:34:10 -0300
Subject: [PATCH 2/3] chore: capture pending project updates
---
.github/hooks/impeccable.json | 13 +
.github/skills/impeccable/SKILL.md | 167 +
.github/skills/impeccable/reference/adapt.md | 312 +
.../impeccable/reference/adapt.native.md | 58 +
.../skills/impeccable/reference/android.md | 40 +
.../skills/impeccable/reference/animate.md | 203 +
.github/skills/impeccable/reference/audit.md | 135 +
.../impeccable/reference/audit.native.md | 139 +
.github/skills/impeccable/reference/bolder.md | 120 +
.github/skills/impeccable/reference/brand.md | 108 +
.../skills/impeccable/reference/clarify.md | 288 +
.github/skills/impeccable/reference/codex.md | 105 +
.../skills/impeccable/reference/colorize.md | 257 +
.github/skills/impeccable/reference/craft.md | 123 +
.../skills/impeccable/reference/critique.md | 780 ++
.../skills/impeccable/reference/delight.md | 302 +
.../skills/impeccable/reference/distill.md | 111 +
.../skills/impeccable/reference/document.md | 429 +
.../skills/impeccable/reference/extract.md | 69 +
.github/skills/impeccable/reference/harden.md | 347 +
.github/skills/impeccable/reference/hooks.md | 92 +
.github/skills/impeccable/reference/init.md | 221 +
.../reference/interaction-design.md | 189 +
.github/skills/impeccable/reference/ios.md | 45 +
.github/skills/impeccable/reference/layout.md | 185 +
.github/skills/impeccable/reference/live.md | 718 +
.../skills/impeccable/reference/onboard.md | 234 +
.../skills/impeccable/reference/optimize.md | 258 +
.../skills/impeccable/reference/overdrive.md | 130 +
.github/skills/impeccable/reference/polish.md | 241 +
.../skills/impeccable/reference/product.md | 60 +
.../skills/impeccable/reference/quieter.md | 99 +
.github/skills/impeccable/reference/shape.md | 165 +
.../skills/impeccable/reference/typeset.md | 301 +
.../impeccable/scripts/command-metadata.json | 94 +
.../impeccable/scripts/context-signals.mjs | 226 +
.github/skills/impeccable/scripts/context.mjs | 1023 ++
.../impeccable/scripts/critique-storage.mjs | 242 +
.../skills/impeccable/scripts/detect-csp.mjs | 198 +
.github/skills/impeccable/scripts/detect.mjs | 21 +
.../detector/browser/injected/index.mjs | 1937 +++
.../impeccable/scripts/detector/cli/main.mjs | 321 +
.../scripts/detector/design-system.mjs | 814 ++
.../detector/detect-antipatterns-browser.js | 5245 +++++++
.../scripts/detector/detect-antipatterns.mjs | 50 +
.../detector/engines/browser/detect-url.mjs | 277 +
.../detector/engines/regex/detect-text.mjs | 573 +
.../engines/static-html/css-cascade.mjs | 1015 ++
.../engines/static-html/detect-html.mjs | 234 +
.../engines/visual/screenshot-contrast.mjs | 189 +
.../impeccable/scripts/detector/findings.mjs | 12 +
.../scripts/detector/node/file-system.mjs | 198 +
.../scripts/detector/profile/profiler.mjs | 166 +
.../detector/registry/antipatterns.mjs | 514 +
.../scripts/detector/rules/checks.mjs | 2703 ++++
.../scripts/detector/shared/color.mjs | 124 +
.../scripts/detector/shared/constants.mjs | 101 +
.../scripts/detector/shared/fonts.mjs | 30 +
.../detector/shared/inline-ignores.mjs | 148 +
.../scripts/detector/shared/page.mjs | 7 +
.../skills/impeccable/scripts/hook-admin.mjs | 661 +
.../impeccable/scripts/hook-before-edit.mjs | 516 +
.../skills/impeccable/scripts/hook-lib.mjs | 1765 +++
.github/skills/impeccable/scripts/hook.mjs | 61 +
.../impeccable/scripts/lib/design-parser.mjs | 842 ++
.../scripts/lib/impeccable-config.mjs | 640 +
.../scripts/lib/impeccable-paths.mjs | 129 +
.../impeccable/scripts/lib/is-generated.mjs | 69 +
.../impeccable/scripts/lib/provider.mjs | 4 +
.../impeccable/scripts/lib/target-args.mjs | 42 +
.../skills/impeccable/scripts/live-accept.mjs | 812 ++
.../impeccable/scripts/live-browser-dom.js | 146 +
.../scripts/live-browser-session.js | 123 +
.../skills/impeccable/scripts/live-browser.js | 11240 ++++++++++++++++
.../scripts/live-commit-manual-edits.mjs | 1241 ++
.../impeccable/scripts/live-complete.mjs | 75 +
.../scripts/live-copy-edit-agent.mjs | 683 +
.../scripts/live-discard-manual-edits.mjs | 51 +
.../skills/impeccable/scripts/live-inject.mjs | 583 +
.../skills/impeccable/scripts/live-insert.mjs | 272 +
.../scripts/live-manual-edit-evidence.mjs | 363 +
.../skills/impeccable/scripts/live-poll.mjs | 384 +
.../skills/impeccable/scripts/live-resume.mjs | 94 +
.../skills/impeccable/scripts/live-server.mjs | 1137 ++
.../skills/impeccable/scripts/live-status.mjs | 61 +
.../skills/impeccable/scripts/live-target.mjs | 30 +
.../skills/impeccable/scripts/live-wrap.mjs | 894 ++
.github/skills/impeccable/scripts/live.mjs | 297 +
.../scripts/live/browser-script-parts.mjs | 50 +
.../impeccable/scripts/live/completion.mjs | 19 +
.../scripts/live/event-validation.mjs | 137 +
.../impeccable/scripts/live/insert-ui.mjs | 458 +
.../impeccable/scripts/live/manual-apply.mjs | 939 ++
.../scripts/live/manual-edit-routes.mjs | 357 +
.../scripts/live/manual-edits-buffer.mjs | 152 +
.../impeccable/scripts/live/session-store.mjs | 289 +
.../scripts/live/svelte-component.mjs | 826 ++
.../scripts/live/sveltekit-adapter.mjs | 274 +
.../impeccable/scripts/live/ui-core.mjs | 180 +
.../impeccable/scripts/live/vocabulary.mjs | 36 +
.../scripts/modern-screenshot.umd.js | 14 +
.github/skills/impeccable/scripts/palette.mjs | 633 +
.github/skills/impeccable/scripts/pin.mjs | 221 +
docs/todo/compozy-inspired-improvements.md | 168 +
examples/events/.product/artifacts.json | 1535 +--
...ents-001-approved-1784222157279091500.json | 9 +
...ster-001-approved-1784216433078634000.json | 9 +
...ster-001-approved-1784218628166918900.json | 9 +
...ster-001-rejected-1784217749635638900.json | 9 +
...ster-001-rejected-1784218645272006100.json | 9 +
examples/events/.product/server.json | 1 +
.../events/audits/security/threat-register.md | 2 +-
examples/events/engineering/context.md | 2 +-
.../events/engineering/engineering-system.md | 2 +-
.../engineering/engineering-system.yaml | 30 +-
.../engineering/quality/quality-system.md | 2 +-
.../engineering/quality/quality-system.yaml | 64 +-
internal/projectserver/dashboard.html | 1 +
internal/projectserver/server.go | 17 +
internal/projectserver/server_test.go | 16 +
120 files changed, 51811 insertions(+), 1380 deletions(-)
create mode 100644 .github/hooks/impeccable.json
create mode 100644 .github/skills/impeccable/SKILL.md
create mode 100644 .github/skills/impeccable/reference/adapt.md
create mode 100644 .github/skills/impeccable/reference/adapt.native.md
create mode 100644 .github/skills/impeccable/reference/android.md
create mode 100644 .github/skills/impeccable/reference/animate.md
create mode 100644 .github/skills/impeccable/reference/audit.md
create mode 100644 .github/skills/impeccable/reference/audit.native.md
create mode 100644 .github/skills/impeccable/reference/bolder.md
create mode 100644 .github/skills/impeccable/reference/brand.md
create mode 100644 .github/skills/impeccable/reference/clarify.md
create mode 100644 .github/skills/impeccable/reference/codex.md
create mode 100644 .github/skills/impeccable/reference/colorize.md
create mode 100644 .github/skills/impeccable/reference/craft.md
create mode 100644 .github/skills/impeccable/reference/critique.md
create mode 100644 .github/skills/impeccable/reference/delight.md
create mode 100644 .github/skills/impeccable/reference/distill.md
create mode 100644 .github/skills/impeccable/reference/document.md
create mode 100644 .github/skills/impeccable/reference/extract.md
create mode 100644 .github/skills/impeccable/reference/harden.md
create mode 100644 .github/skills/impeccable/reference/hooks.md
create mode 100644 .github/skills/impeccable/reference/init.md
create mode 100644 .github/skills/impeccable/reference/interaction-design.md
create mode 100644 .github/skills/impeccable/reference/ios.md
create mode 100644 .github/skills/impeccable/reference/layout.md
create mode 100644 .github/skills/impeccable/reference/live.md
create mode 100644 .github/skills/impeccable/reference/onboard.md
create mode 100644 .github/skills/impeccable/reference/optimize.md
create mode 100644 .github/skills/impeccable/reference/overdrive.md
create mode 100644 .github/skills/impeccable/reference/polish.md
create mode 100644 .github/skills/impeccable/reference/product.md
create mode 100644 .github/skills/impeccable/reference/quieter.md
create mode 100644 .github/skills/impeccable/reference/shape.md
create mode 100644 .github/skills/impeccable/reference/typeset.md
create mode 100644 .github/skills/impeccable/scripts/command-metadata.json
create mode 100644 .github/skills/impeccable/scripts/context-signals.mjs
create mode 100644 .github/skills/impeccable/scripts/context.mjs
create mode 100644 .github/skills/impeccable/scripts/critique-storage.mjs
create mode 100644 .github/skills/impeccable/scripts/detect-csp.mjs
create mode 100644 .github/skills/impeccable/scripts/detect.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/browser/injected/index.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/cli/main.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/design-system.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
create mode 100644 .github/skills/impeccable/scripts/detector/detect-antipatterns.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/findings.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/node/file-system.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/profile/profiler.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/registry/antipatterns.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/rules/checks.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/shared/color.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/shared/constants.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/shared/fonts.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/shared/inline-ignores.mjs
create mode 100644 .github/skills/impeccable/scripts/detector/shared/page.mjs
create mode 100644 .github/skills/impeccable/scripts/hook-admin.mjs
create mode 100644 .github/skills/impeccable/scripts/hook-before-edit.mjs
create mode 100644 .github/skills/impeccable/scripts/hook-lib.mjs
create mode 100644 .github/skills/impeccable/scripts/hook.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/design-parser.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/impeccable-config.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/impeccable-paths.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/is-generated.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/provider.mjs
create mode 100644 .github/skills/impeccable/scripts/lib/target-args.mjs
create mode 100644 .github/skills/impeccable/scripts/live-accept.mjs
create mode 100644 .github/skills/impeccable/scripts/live-browser-dom.js
create mode 100644 .github/skills/impeccable/scripts/live-browser-session.js
create mode 100644 .github/skills/impeccable/scripts/live-browser.js
create mode 100644 .github/skills/impeccable/scripts/live-commit-manual-edits.mjs
create mode 100644 .github/skills/impeccable/scripts/live-complete.mjs
create mode 100644 .github/skills/impeccable/scripts/live-copy-edit-agent.mjs
create mode 100644 .github/skills/impeccable/scripts/live-discard-manual-edits.mjs
create mode 100644 .github/skills/impeccable/scripts/live-inject.mjs
create mode 100644 .github/skills/impeccable/scripts/live-insert.mjs
create mode 100644 .github/skills/impeccable/scripts/live-manual-edit-evidence.mjs
create mode 100644 .github/skills/impeccable/scripts/live-poll.mjs
create mode 100644 .github/skills/impeccable/scripts/live-resume.mjs
create mode 100644 .github/skills/impeccable/scripts/live-server.mjs
create mode 100644 .github/skills/impeccable/scripts/live-status.mjs
create mode 100644 .github/skills/impeccable/scripts/live-target.mjs
create mode 100644 .github/skills/impeccable/scripts/live-wrap.mjs
create mode 100644 .github/skills/impeccable/scripts/live.mjs
create mode 100644 .github/skills/impeccable/scripts/live/browser-script-parts.mjs
create mode 100644 .github/skills/impeccable/scripts/live/completion.mjs
create mode 100644 .github/skills/impeccable/scripts/live/event-validation.mjs
create mode 100644 .github/skills/impeccable/scripts/live/insert-ui.mjs
create mode 100644 .github/skills/impeccable/scripts/live/manual-apply.mjs
create mode 100644 .github/skills/impeccable/scripts/live/manual-edit-routes.mjs
create mode 100644 .github/skills/impeccable/scripts/live/manual-edits-buffer.mjs
create mode 100644 .github/skills/impeccable/scripts/live/session-store.mjs
create mode 100644 .github/skills/impeccable/scripts/live/svelte-component.mjs
create mode 100644 .github/skills/impeccable/scripts/live/sveltekit-adapter.mjs
create mode 100644 .github/skills/impeccable/scripts/live/ui-core.mjs
create mode 100644 .github/skills/impeccable/scripts/live/vocabulary.mjs
create mode 100644 .github/skills/impeccable/scripts/modern-screenshot.umd.js
create mode 100644 .github/skills/impeccable/scripts/palette.mjs
create mode 100644 .github/skills/impeccable/scripts/pin.mjs
create mode 100644 docs/todo/compozy-inspired-improvements.md
create mode 100644 examples/events/.product/history/approval-engsys-events-001-approved-1784222157279091500.json
create mode 100644 examples/events/.product/history/approval-threat-register-001-approved-1784216433078634000.json
create mode 100644 examples/events/.product/history/approval-threat-register-001-approved-1784218628166918900.json
create mode 100644 examples/events/.product/history/approval-threat-register-001-rejected-1784217749635638900.json
create mode 100644 examples/events/.product/history/approval-threat-register-001-rejected-1784218645272006100.json
create mode 100644 examples/events/.product/server.json
diff --git a/.github/hooks/impeccable.json b/.github/hooks/impeccable.json
new file mode 100644
index 0000000..0e93780
--- /dev/null
+++ b/.github/hooks/impeccable.json
@@ -0,0 +1,13 @@
+{
+ "version": 1,
+ "hooks": {
+ "postToolUse": [
+ {
+ "type": "command",
+ "matcher": "edit|create|apply_patch",
+ "bash": "node \"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs\"",
+ "timeoutSec": 5
+ }
+ ]
+ }
+}
diff --git a/.github/skills/impeccable/SKILL.md b/.github/skills/impeccable/SKILL.md
new file mode 100644
index 0000000..34c7658
--- /dev/null
+++ b/.github/skills/impeccable/SKILL.md
@@ -0,0 +1,167 @@
+---
+name: impeccable
+description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
+version: 3.9.1
+user-invocable: true
+argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
+license: Apache 2.0
+---
+
+Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
+
+## Setup
+
+You MUST do these steps before proceeding:
+
+1. Run `node .github/skills/impeccable/scripts/context.mjs` once per session; if the runtime shows this skill's loaded base directory, run `node /scripts/context.mjs` instead. Keep cwd/workdir at the user's project, not the skill directory. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and append `--target ` to the same command. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`:** divert into `reference/init.md` first when the user invoked `init`, `teach`, `craft`, or `shape`, or when their wording clearly maps to one of those from-scratch build flows (for example: "build/create/make a landing page", "design a new app", or "shape a feature"). Captured product context is the point of those flows. For any other command, a scoped evaluate / refine / enhance / fix / iterate request against existing code, do **not** divert into init. The existing code is the context: proceed with the requested command, infer the register from the surface in focus (step 4), and offer `/impeccable init` once as a suggestion the user can take later. A missing PRODUCT.md must never block a scoped request. If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task.
+2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read the command's reference next: **`reference/.md`, or the native variant from the Commands table** (e.g. `reference/audit.native.md`) **when the project platform is native** (`ios` / `android` / `adaptive`, per the `context.mjs` directive). One file, not both. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects.
+3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins.
+4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md.
+5. **If PRODUCT.md's `## Platform` is `ios` or `android`**, also read `reference/.md` (HIG / Material 3 conventions). `adaptive` (cross-platform, ships both) reads both files. `web`, absent, or unrecognized: nothing extra to read. `context.mjs` prints the directive when one applies.
+6. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .github/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.**
+
+## Design guidance
+
+Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). the model is capable of extraordinary work. Don't hold back.
+
+### General rules
+
+#### Color
+
+- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read.
+- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color.
+
+#### Typography
+
+- Cap body line length at 65–75ch.
+- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights.
+- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing.
+- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed".
+- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans.
+
+#### Layout
+
+- Vary spacing for rhythm.
+- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
+- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler.
+- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`.
+- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999.
+
+#### Motion
+- Motion should be intentional, and not be an afterthought. consider it as part of the build.
+- Don't animate CSS layout properties unless truly needed.
+- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
+- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc)
+- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition.
+- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all.
+- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank.
+- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth.
+
+#### Interaction
+
+- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `
` open near the top of the document.
+ const idx = content.indexOf(config.insertAfter);
+ if (idx === -1) return content;
+ const after = idx + config.insertAfter.length;
+ // Preserve an existing trailing newline if the anchor already has one.
+ // Slice the remainder from the original anchor offset, not prefix.length:
+ // in the no-newline case prefix is one char longer than the anchor (the
+ // appended '\n'), so slicing by prefix.length would drop the first real
+ // character after the anchor (#227).
+ const existingNewline = readLineEndingAt(content, after);
+ const prefix = content.slice(0, after) + (existingNewline || lineEnding);
+ const rest = content.slice(after + existingNewline.length);
+ return prefix + block + rest;
+}
+
+/**
+ * Remove the live script block. Matches either HTML or JSX comment markers
+ * regardless of config (so stale tags from a wrong config can still be cleaned).
+ *
+ * Indent-preserving: captures any whitespace immediately preceding the opener
+ * marker and re-emits it in place of the removed block. `insertTag` inserted
+ * the block *after* the original line's indent and *before* the anchor (e.g.
+ * `
` naturally
+ // belong at the end, and the same literal can appear earlier in code blocks
+ // within rendered documentation pages.
+ if (config.insertBefore) {
+ const idx = content.lastIndexOf(config.insertBefore);
+ if (idx === -1) return content;
+ return content.slice(0, idx) + block + content.slice(idx);
+ }
+ // insertAfter: match the FIRST occurrence — typical anchors like `
` or
+ // `
`), which moved the indent onto the opener line and left the anchor
+ * unindented. Replacing the whole block (plus its trailing newline) with just
+ * the captured indent hands the indent back to the anchor that follows.
+ */
+function removeTag(content, _syntax) {
+ const patterns = [
+ /([ \t]*)[\s\S]*?([ \t]*(?:\r\n|\n|\r|$)?)/,
+ /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}([ \t]*(?:\r\n|\n|\r|$)?)/,
+ ];
+ for (const pat of patterns) {
+ let changed = false;
+ let next = content;
+ do {
+ content = next;
+ next = content.replace(pat, (_match, leadingIndent, trailing = '') => {
+ if (/[\r\n]/.test(trailing)) return leadingIndent;
+ return leadingIndent || trailing || '';
+ });
+ if (next !== content) changed = true;
+ } while (next !== content);
+ if (changed) return next;
+ }
+ return content;
+}
+
+// ---------------------------------------------------------------------------
+// Content-Security-Policy meta-tag patcher
+//
+// When the user's HTML carries ``,
+// the cross-origin load of /live.js (and the SSE/POST connection back to
+// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
+//
+// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
+// and stash the original `content` value in a `data-impeccable-csp-original`
+// attribute (base64) so revert is exact.
+//
+// On remove: detect the marker attribute, decode it, restore the original
+// content value verbatim, drop the marker.
+//
+// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
+// shared helpers) is NOT patched here — those need framework-specific config
+// edits and are handled via the existing detect-csp.mjs reference output.
+// Only the in-source meta-tag form gets the auto-patch.
+// ---------------------------------------------------------------------------
+
+const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
+
+function findCspMetaTags(content) {
+ const out = [];
+ const tagRe = /]*?)\/?>/gis;
+ let m;
+ while ((m = tagRe.exec(content)) !== null) {
+ const attrs = m[1];
+ if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
+ out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
+ }
+ return out;
+}
+
+function getAttr(attrs, name) {
+ const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
+ const m = attrs.match(re);
+ return m ? { quote: m[1], value: m[2], full: m[0] } : null;
+}
+
+function appendOriginToDirective(csp, directive, origin) {
+ const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
+ const m = csp.match(re);
+ if (m) {
+ const tokens = m[4].trim().split(/\s+/);
+ if (tokens.includes(origin)) return csp;
+ return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
+ }
+ // Directive missing — add it. Use 'self' + origin so we don't inadvertently
+ // narrow the policy compared to the default-src fallback (most users with
+ // an explicit CSP have 'self' there).
+ return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
+}
+
+export function patchCspMeta(content, port) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+ const origin = `http://localhost:${port}`;
+
+ // Walk last-to-first so prior splices don't invalidate later indices.
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const attrs = tag.attrs;
+ if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
+ const contentAttr = getAttr(attrs, 'content');
+ if (!contentAttr) continue;
+
+ const original = contentAttr.value;
+ let patched = original;
+ patched = appendOriginToDirective(patched, 'script-src', origin);
+ patched = appendOriginToDirective(patched, 'connect-src', origin);
+ // The shader overlay during 'generating' creates a screenshot via
+ // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
+ // those. Add `blob:` so the overlay doesn't throw a CSP violation.
+ patched = appendOriginToDirective(patched, 'img-src', 'blob:');
+ if (patched === original) continue;
+
+ const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
+ const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
+ // The tagRe captures any whitespace between the last attribute and the
+ // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
+ // a replace would land it BEFORE that trailing space, leaving a double
+ // space inside attrs and clobbering the space before `/>`. Split off
+ // the trailing whitespace, splice the marker into the attribute body,
+ // and re-append the original trailing whitespace so a self-closing
+ // `` round-trips byte-for-byte.
+ const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
+ const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
+ const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
+ const newTag = tag.full.replace(attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+export function revertCspMeta(content) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
+ if (!origAttr) continue;
+ const contentAttr = getAttr(tag.attrs, 'content');
+ if (!contentAttr) continue;
+
+ let originalValue;
+ try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
+ catch { continue; }
+
+ const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
+ let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
+ // Drop the marker attribute and any single space immediately preceding it.
+ newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
+ const newTag = tag.full.replace(tag.attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Auto-execute
+// ---------------------------------------------------------------------------
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
+ injectCli();
+}
+
+export { insertTag, removeTag, validateConfig, buildTagBlock };
+// patchCspMeta + revertCspMeta are exported above where they're defined.
diff --git a/.github/skills/impeccable/scripts/live-insert.mjs b/.github/skills/impeccable/scripts/live-insert.mjs
new file mode 100644
index 0000000..0ed3caf
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-insert.mjs
@@ -0,0 +1,272 @@
+/**
+ * CLI helper: find an anchor element in source and splice an insert-variant
+ * wrapper before or after it (no original variant — net-new content).
+ *
+ * Usage:
+ * node live-insert.mjs --id SESSION_ID --count N --position after \
+ * --classes "hero" --tag section [--file path]
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import {
+ buildSearchQueries,
+ findElement,
+ findAllElements,
+ filterByText,
+ findFileWithQuery,
+ detectCommentSyntax,
+ detectStyleMode,
+ buildCssAuthoring,
+ buildCssSelectorPrefixExamples,
+} from './live-wrap.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentInsertSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+const INSERT_POSITIONS = new Set(['before', 'after']);
+
+export function isInsertPosition(value) {
+ return INSERT_POSITIONS.has(value);
+}
+
+export function computeInsertLine(startLine, endLine, position) {
+ return position === 'before' ? startLine : endLine + 1;
+}
+
+export function buildInsertWrapperLines({ id, count, indent, commentSyntax, isJsx }) {
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+ const attrs =
+ 'data-impeccable-variants="' + id + '" ' +
+ 'data-impeccable-mode="insert" ' +
+ 'data-impeccable-variant-count="' + count + '" ' +
+ styleContents;
+
+ if (isJsx) {
+ return [
+ indent + '
',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+}
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+function resolveElementMatch({ lines, queries, tag, text }) {
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) candidates.push(c);
+ }
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) return { error: 'element_not_found' };
+ if (candidates.length === 1) return { match: candidates[0] };
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) return { match: filtered[0] };
+ if (filtered.length === 0) return { match: candidates[0] };
+ return { error: 'element_ambiguous', candidates: filtered };
+ }
+
+ for (const q of queries) {
+ const match = findElement(lines, q, tag);
+ if (match) return { match };
+ }
+ return { error: 'element_not_found' };
+}
+
+export async function insertCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-insert.mjs [options]
+
+Find an anchor element in source and splice an insert-variant wrapper.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+ --position POS before | after (relative to the anchor element)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the anchor element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --text TEXT Anchor textContent for disambiguation (~80 chars)
+
+Output (JSON):
+ { mode: "insert", file, position, insertLine, commentSyntax, styleMode, styleTag, cssAuthoring }`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3', 10);
+ const position = argVal(args, '--position');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+ const text = argVal(args, '--text');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!position) { console.error('Missing --position (before | after)'); process.exit(1); }
+ if (!isInsertPosition(position)) { console.error('Invalid --position: ' + position); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+ const genOpts = { cwd: process.cwd() };
+
+ let targetFile = filePath;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) break;
+ }
+ if (!targetFile) {
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ console.error(JSON.stringify({
+ error: generatedHit ? 'element_not_in_source' : 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ } else if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ }));
+ process.exit(1);
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+ const resolved = resolveElementMatch({ lines, queries, tag, text });
+
+ if (resolved.error === 'element_ambiguous') {
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: resolved.candidates.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ }));
+ process.exit(1);
+ }
+ if (!resolved.match) {
+ console.error(JSON.stringify({ error: 'element_not_found', fallback: 'agent-driven' }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = resolved.match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const spliceIndex = computeInsertLine(startLine, endLine, position);
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+
+ if (shouldUseSvelteComponentInjection(targetFile)) {
+ const session = scaffoldSvelteComponentInsertSession({
+ id,
+ count,
+ sourceFile: relTargetFile,
+ insertLine: spliceIndex + 1,
+ position,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ anchorLines: lines.slice(startLine, endLine + 1),
+ cwd: process.cwd(),
+ });
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: session.manifestFile,
+ sourceFile: relTargetFile,
+ previewMode: 'svelte-component',
+ componentDir: session.componentDir,
+ propContract: session.propContract,
+ insertLine: 1,
+ sourceInsertLine: spliceIndex + 1,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ commentSyntax,
+ styleMode: 'svelte-component',
+ styleTag: null,
+ cssSelectorPrefixExamples: [],
+ cssAuthoring: buildSvelteComponentCssAuthoring(count),
+ }));
+ return;
+ }
+
+ const indent = lines[spliceIndex]?.match(/^(\s*)/)?.[1]
+ ?? lines[startLine]?.match(/^(\s*)/)?.[1]
+ ?? '';
+
+ const wrapperLines = buildInsertWrapperLines({
+ id,
+ count,
+ indent,
+ commentSyntax,
+ isJsx,
+ });
+
+ const newLines = [
+ ...lines.slice(0, spliceIndex),
+ ...wrapperLines,
+ ...lines.slice(spliceIndex),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ const insertLine = spliceIndex + 3;
+
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: relTargetFile,
+ insertLine: insertLine + 1,
+ commentSyntax,
+ styleMode: styleMode.mode,
+ styleTag: styleMode.styleTag,
+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
+ cssAuthoring: buildCssAuthoring(styleMode, count),
+ }));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-insert.mjs') || _running?.endsWith('live-insert.mjs/')) {
+ insertCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs b/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs
new file mode 100644
index 0000000..dd10e96
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs
@@ -0,0 +1,363 @@
+#!/usr/bin/env node
+/**
+ * Collect evidence for pending live copy edits.
+ *
+ * This module intentionally does not edit source files and does not choose a
+ * winner. It gathers staged browser edits, rendered context, framework source
+ * hints, and likely source candidates so the AI copy-edit batch runner can make
+ * source changes with full repo context.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer, getBufferPath } from './live/manual-edits-buffer.mjs';
+
+const EVIDENCE_VERSION = 1;
+const TEXT_EXTENSIONS = new Set(['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro', '.js', '.mjs', '.ts']);
+const SEARCH_DIRS = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', 'site', 'lib', 'data'];
+const STRONG_LITERAL_MATCH_LIMIT = 8;
+const WEAK_LITERAL_MATCH_LIMIT = 4;
+const OBJECT_KEY_MATCH_LIMIT = 8;
+const LOCATOR_MATCH_LIMIT = 4;
+const CONTEXT_MATCH_LIMIT = 8;
+const CONTEXT_MATCH_PER_HINT = 2;
+const SKIP_DIRS = new Set([
+ 'node_modules',
+ '.git',
+ '.impeccable',
+ '.astro',
+ '.next',
+ '.nuxt',
+ '.svelte-kit',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+]);
+
+export function buildManualEditEvidence({ cwd = process.cwd(), pageUrl = null } = {}) {
+ const buffer = readBuffer(cwd);
+ const entries = pageUrl
+ ? buffer.entries.filter((entry) => entry.pageUrl === pageUrl)
+ : buffer.entries;
+ const opCount = countOps(entries);
+
+ if (opCount === 0) {
+ return {
+ pageUrl,
+ count: 0,
+ entries: [],
+ ops: [],
+ candidates: [],
+ };
+ }
+
+ const searchFiles = collectSearchFiles(cwd);
+ const ops = flattenOps(entries);
+ const candidates = ops.map((op) => buildCandidatesForOp(op, cwd, searchFiles));
+ return {
+ version: EVIDENCE_VERSION,
+ pageUrl: pageUrl || null,
+ count: opCount,
+ entries,
+ ops,
+ context: {
+ cwd,
+ bufferPath: path.relative(cwd, getBufferPath(cwd)),
+ totalEntries: entries.length,
+ totalOps: opCount,
+ },
+ candidates,
+ };
+}
+
+function countOps(entries) {
+ let count = 0;
+ for (const entry of entries) count += Array.isArray(entry.ops) ? entry.ops.length : 0;
+ return count;
+}
+
+function flattenOps(entries) {
+ const out = [];
+ for (const entry of entries) {
+ const contextHintsByRef = buildContextHintsByRef(entry);
+ for (const op of entry.ops || []) {
+ out.push({
+ entryId: entry.id,
+ pageUrl: entry.pageUrl,
+ ref: op.ref,
+ contextRef: op.contextRef || null,
+ tag: op.tag,
+ elementId: op.elementId || null,
+ classes: Array.isArray(op.classes) ? op.classes : [],
+ originalText: op.originalText,
+ newText: op.newText,
+ deleted: op.deleted === true,
+ sourceHint: op.sourceHint || null,
+ leaf: op.leaf || null,
+ nearbyEditableTexts: Array.isArray(op.nearbyEditableTexts) ? op.nearbyEditableTexts : [],
+ container: op.container || null,
+ contextHints: contextHintsByRef.get(op.ref) || [],
+ });
+ }
+ }
+ return out;
+}
+
+function buildContextHintsByRef(entry) {
+ const map = new Map();
+ for (const op of entry.ops || []) {
+ const hints = new Set();
+ const add = (value) => {
+ const text = normalizeText(decodeBasicHtml(String(value || '')));
+ if (text.length < 3 || text.length > 160) return;
+ if (text === normalizeText(op.originalText) || text === normalizeText(op.newText)) return;
+ hints.add(text);
+ };
+
+ for (const item of op.nearbyEditableTexts || []) {
+ add(typeof item === 'string' ? item : item?.text);
+ }
+ const outer = typeof entry.element?.outerHTML === 'string' ? entry.element.outerHTML : '';
+ for (const match of outer.matchAll(/data-impeccable-original-text="([^"]*)"/g)) add(match[1]);
+ if (typeof entry.element?.textContent === 'string') {
+ for (const chunk of entry.element.textContent.split(/\s{2,}|\n|\t/)) add(chunk);
+ }
+ map.set(op.ref, [...hints].slice(0, 16));
+ }
+ return map;
+}
+
+function buildCandidatesForOp(op, cwd, searchFiles) {
+ const originalText = String(op.originalText || '');
+ const contextNeedles = op.contextHints || [];
+ return {
+ entryId: op.entryId,
+ ref: op.ref,
+ originalText,
+ sourceHint: analyzeSourceHint(op, cwd),
+ textMatches: originalText ? findLiteralMatches(searchFiles, originalText, { max: literalMatchLimit(originalText) }) : [],
+ objectKeyMatches: originalText ? findObjectKeyMatches(searchFiles, originalText, { max: OBJECT_KEY_MATCH_LIMIT }) : [],
+ locatorMatches: findLocatorMatches(searchFiles, op, { max: LOCATOR_MATCH_LIMIT }),
+ contextTextMatches: findContextMatches(searchFiles, contextNeedles, { maxPerHint: CONTEXT_MATCH_PER_HINT, max: CONTEXT_MATCH_LIMIT }),
+ };
+}
+
+function literalMatchLimit(text) {
+ return isWeakSourceNeedle(text) ? WEAK_LITERAL_MATCH_LIMIT : STRONG_LITERAL_MATCH_LIMIT;
+}
+
+function isWeakSourceNeedle(text) {
+ const normalized = normalizeText(text);
+ return normalized.length < 4 || /^[\d.,+\-%\s]+$/.test(normalized);
+}
+
+function analyzeSourceHint(op, cwd) {
+ const hint = normalizeSourceHint(op.sourceHint);
+ if (!hint.file) return null;
+ const file = path.resolve(cwd, hint.file);
+ const relativeFile = path.relative(cwd, file);
+ if (!isPathInsideOrEqual(cwd, file)) {
+ return { ...hint, status: 'outside_cwd', relativeFile: hint.file };
+ }
+ if (!fs.existsSync(file)) {
+ return { ...hint, status: 'file_missing', relativeFile };
+ }
+ if (isGeneratedFile(file, { cwd })) {
+ return { ...hint, status: 'generated', relativeFile };
+ }
+
+ const content = fs.readFileSync(file, 'utf-8');
+ const lines = content.split('\n');
+ const line = hint.line || 1;
+ const start = Math.max(0, line - 4);
+ const end = Math.min(lines.length, line + 3);
+ const windowText = lines.slice(start, end).join('\n');
+ const containsOriginalText = typeof op.originalText === 'string' && windowText.includes(op.originalText);
+ return {
+ ...hint,
+ status: containsOriginalText ? 'ok' : 'text_not_found_near_hint',
+ relativeFile,
+ excerpt: lines.slice(start, end).map((text, index) => ({
+ line: start + index + 1,
+ text: text.slice(0, 240),
+ })),
+ };
+}
+
+function normalizeSourceHint(hint) {
+ if (!hint || typeof hint !== 'object') return {};
+ let line = Number.isFinite(Number(hint.line)) ? Number(hint.line) : null;
+ let column = Number.isFinite(Number(hint.column)) ? Number(hint.column) : null;
+ if ((!line || !column) && typeof hint.loc === 'string') {
+ const match = hint.loc.match(/^(\d+)(?::(\d+))?/);
+ if (match) {
+ line = Number(match[1]);
+ if (match[2]) column = Number(match[2]);
+ }
+ }
+ return {
+ file: typeof hint.file === 'string' ? hint.file : '',
+ loc: typeof hint.loc === 'string' ? hint.loc : '',
+ line,
+ column,
+ };
+}
+
+function collectSearchFiles(cwd) {
+ const out = [];
+ const seenDirs = new Set();
+ const seenFiles = new Set();
+ for (const dir of SEARCH_DIRS) {
+ scanDir(path.join(cwd, dir), cwd, seenDirs, seenFiles, out, 0);
+ }
+ scanRootFiles(cwd, seenFiles, out);
+ return out;
+}
+
+function scanDir(dir, cwd, seenDirs, seenFiles, out, depth) {
+ if (depth > 7 || !fs.existsSync(dir)) return;
+ let realDir;
+ try { realDir = fs.realpathSync(dir); } catch { return; }
+ if (seenDirs.has(realDir)) return;
+ seenDirs.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ scanDir(fullPath, cwd, seenDirs, seenFiles, out, depth + 1);
+ continue;
+ }
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(fullPath, cwd, seenFiles, out);
+ }
+}
+
+function scanRootFiles(cwd, seenFiles, out) {
+ let entries;
+ try { entries = fs.readdirSync(cwd, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(path.join(cwd, entry.name), cwd, seenFiles, out);
+ }
+}
+
+function maybeAddSearchFile(file, cwd, seenFiles, out) {
+ let realFile;
+ try { realFile = fs.realpathSync(file); } catch { return; }
+ if (seenFiles.has(realFile)) return;
+ seenFiles.add(realFile);
+ if (isGeneratedFile(file, { cwd })) return;
+ let content;
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { return; }
+ out.push({ file, relativeFile: path.relative(cwd, file), content, lines: content.split('\n') });
+}
+
+function findLiteralMatches(searchFiles, needle, { max }) {
+ return findMatches(searchFiles, needle, { kind: 'text', max });
+}
+
+function findObjectKeyMatches(searchFiles, text, { max }) {
+ const re = new RegExp('(["\\\'`])' + escapeRegExp(text) + '\\1(?=\\s*:)', 'g');
+ const out = [];
+ for (const file of searchFiles) {
+ for (const match of file.content.matchAll(re)) {
+ out.push(matchForIndex(file, match.index, 'object_key', text));
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findLocatorMatches(searchFiles, op, { max }) {
+ const needles = [];
+ if (op.elementId) needles.push({ kind: 'id', needle: op.elementId });
+ for (const cls of op.classes || []) {
+ if (cls) needles.push({ kind: 'class', needle: cls });
+ }
+ if (op.tag) needles.push({ kind: 'tag', needle: '<' + op.tag });
+
+ const out = [];
+ const seen = new Set();
+ for (const { kind, needle } of needles) {
+ for (const match of findMatches(searchFiles, needle, { kind, max })) {
+ const key = match.file + ':' + match.line + ':' + kind + ':' + needle;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findContextMatches(searchFiles, hints, { maxPerHint, max }) {
+ const out = [];
+ const seen = new Set();
+ for (const hint of hints || []) {
+ for (const match of findMatches(searchFiles, hint, { kind: 'context', max: maxPerHint })) {
+ const key = match.file + ':' + match.line + ':' + hint;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle: hint });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findMatches(searchFiles, needle, { kind, max }) {
+ const text = String(needle || '');
+ if (!text) return [];
+ const out = [];
+ for (const file of searchFiles) {
+ let index = 0;
+ while (out.length < max) {
+ index = file.content.indexOf(text, index);
+ if (index === -1) break;
+ out.push(matchForIndex(file, index, kind, text));
+ index += Math.max(1, text.length);
+ }
+ if (out.length >= max) break;
+ }
+ return out;
+}
+
+function matchForIndex(file, index, kind, needle) {
+ const line = file.content.slice(0, index).split('\n').length;
+ const lineText = file.lines[line - 1] || '';
+ return {
+ kind,
+ file: file.relativeFile,
+ line,
+ needle,
+ excerpt: lineText.trim().slice(0, 240),
+ };
+}
+
+function isPathInsideOrEqual(cwd, file) {
+ const rel = path.relative(path.resolve(cwd), path.resolve(file));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+function normalizeText(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim();
+}
+
+function decodeBasicHtml(value) {
+ return value
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/'/g, "'")
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>');
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/.github/skills/impeccable/scripts/live-poll.mjs b/.github/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 0000000..740161e
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,384 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * node /live-poll.mjs # Block until browser event, print JSON
+ * node /live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
+ * node /live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
+ * node /live-poll.mjs --reply done # Reply "done" to event
+ * node /live-poll.mjs --reply error "msg" # Reply with error
+ */
+
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live/completion.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+
+// Absolute path to a sibling script in this skill's scripts dir, so runtime
+// error hints print a directly-runnable command instead of a placeholder.
+const SELF_DIR = path.dirname(fileURLToPath(import.meta.url));
+const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;
+
+// Node's built-in fetch (undici under the hood) enforces a 300s headers
+// timeout that can't be lowered per-request. We cap each request below
+// that ceiling and loop in `pollOnce` to synthesize a long poll without
+// depending on the standalone undici package.
+export const PER_REQUEST_TIMEOUT_MS = 270_000;
+export const DEFAULT_EVENT_LEASE_MS = 600_000;
+
+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);
+
+function readServerInfo() {
+ const record = readLiveServerInfo(process.cwd());
+ if (!record) {
+ console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ return record.info;
+}
+
+export function buildPollReplyPayload(token, { id, type, message, file, data }) {
+ return { token, id, type, message, file, data };
+}
+
+export function manualApplyPollBanner(event = {}) {
+ const id = event.id || 'EVENT_ID';
+ return [
+ `Manual Apply action required: edit source, then reply with \`live-poll.mjs --reply ${id} done --data ''\`.`,
+ 'The JSON data must include status, appliedEntryIds, failed, files, and notes; summary counters are only a recovery fallback.',
+ 'Do not run live-commit-manual-edits.mjs for this leased event.',
+ 'Do not poll again before replying.',
+ ].join('\n') + '\n';
+}
+
+/**
+ * Parse `--reply [--file path] [--data ''] [message]` argv
+ * into a reply object. Returns null when `--reply` is absent. Throws (code
+ * INVALID_REPLY_ARGS) when the reply shape is missing its event id/status and
+ * INVALID_DATA_JSON when `--data` is present but not valid JSON.
+ */
+export function parseReplyArgs(args) {
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx === -1) return null;
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2];
+ validateReplyArgs({ id, status });
+ const fileIdx = args.indexOf('--file');
+ const file = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ const dataIdx = args.indexOf('--data');
+ let data;
+ if (dataIdx !== -1 && dataIdx + 1 < args.length) {
+ try {
+ data = JSON.parse(args[dataIdx + 1]);
+ } catch (err) {
+ const wrapped = new Error('--data must be valid JSON: ' + err.message);
+ wrapped.code = 'INVALID_DATA_JSON';
+ throw wrapped;
+ }
+ }
+ const message = args.find((a, i) =>
+ i > replyIdx + 2
+ && !a.startsWith('--')
+ && i !== fileIdx + 1
+ && i !== dataIdx + 1
+ ) || undefined;
+ return { id, type: status, message, file, data };
+}
+
+function validateReplyArgs({ id, status }) {
+ const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply [--file path] [--data ''] [message]`;
+ if (!id || id.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing event id after --reply.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (['done', 'error', 'complete', 'discard', 'discarded'].includes(id)) {
+ const err = new Error(`${usage}\nThe value after --reply must be the event id, not the status ${JSON.stringify(id)}. Use --reply EVENT_ID ${id}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (!status || status.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing reply status after event id ${JSON.stringify(id)}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+}
+
+export function requiresAgentReply(event) {
+ return EVENT_TYPES_NEEDING_AGENT_REPLY.has(event?.type);
+}
+
+export async function postReply(base, token, reply) {
+ const res = await fetch(`${base}/poll`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(buildPollReplyPayload(token, reply)),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ const parts = [body.error || res.statusText, body.reason, body.hint].filter(Boolean);
+ throw new Error(parts.join(': '));
+ }
+}
+
+export async function fetchServerStatus(base, token) {
+ const res = await fetch(`${base}/status?token=${token}`);
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+ if (!res.ok) {
+ throw new Error(`Status failed: ${res.status} ${res.statusText}`);
+ }
+ return res.json();
+}
+
+export function isEventPending(status, eventId) {
+ return (status.pendingEvents || []).some((entry) => entry.id === eventId);
+}
+
+export async function waitForEventAck(base, token, eventId, {
+ pollIntervalMs = 400,
+ maxWaitMs = 600_000,
+} = {}) {
+ const deadline = Date.now() + maxWaitMs;
+ while (Date.now() < deadline) {
+ const status = await fetchServerStatus(base, token);
+ if (!isEventPending(status, eventId)) return true;
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
+ }
+ return false;
+}
+
+export async function fetchNextEvent(base, token, { totalDeadline } = {}) {
+ while (true) {
+ if (totalDeadline && Date.now() >= totalDeadline) {
+ return { type: 'timeout' };
+ }
+
+ const remaining = totalDeadline
+ ? totalDeadline - Date.now()
+ : PER_REQUEST_TIMEOUT_MS;
+ const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);
+ const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);
+
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+
+ if (!res.ok) {
+ throw new Error(`Poll failed: ${res.status} ${res.statusText}`);
+ }
+
+ const next = await res.json();
+ if (next?.type === 'timeout') {
+ if (totalDeadline && Date.now() < totalDeadline) continue;
+ if (!totalDeadline) continue;
+ return next;
+ }
+ return next;
+ }
+}
+
+export async function augmentEventWithAcceptHandling(event, base, token) {
+ if (event.type !== 'accept' && event.type !== 'discard') return event;
+
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
+ const acceptScript = path.join(__dirname, 'live-accept.mjs');
+ const scriptArgs = buildAcceptScriptArgs(event);
+
+ try {
+ const out = execFileSync(
+ 'node',
+ [acceptScript, ...scriptArgs],
+ { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 },
+ );
+ event._acceptResult = JSON.parse(out.trim());
+ } catch (err) {
+ event._acceptResult = { handled: false, mode: 'error', error: err.message };
+ }
+
+ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
+ try {
+ await postReply(base, token, {
+ id: event.id,
+ type: completionType,
+ message: event._acceptResult?.error,
+ file: event._acceptResult?.file,
+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
+ });
+ } catch (err) {
+ event._completionAck = { ok: false, error: err.message };
+ }
+ if (!event._completionAck) {
+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
+ }
+
+ return event;
+}
+
+export function buildAcceptScriptArgs(event) {
+ const scriptArgs = event.type === 'discard'
+ ? ['--id', String(event.id), '--discard']
+ : ['--id', String(event.id), '--variant', String(event.variantId)];
+ if (event.pageUrl) scriptArgs.push('--page-url', String(event.pageUrl));
+ if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
+ scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
+ }
+ return scriptArgs;
+}
+
+export function writeCarbonizeBanner(event) {
+ if (event.type === 'manual_edit_apply') {
+ process.stderr.write('\n' + manualApplyPollBanner(event) + '\n');
+ }
+ if (event._acceptResult?.carbonize === true) {
+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
+ }
+}
+
+export function printPollEvent(event) {
+ console.log(JSON.stringify(event));
+}
+
+export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {
+ const deadline = Date.now() + totalTimeout;
+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline });
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+ return event;
+}
+
+export async function runPollStream(base, token, {
+ ackTimeoutMs = 600_000,
+ ackPollIntervalMs = 400,
+ shouldContinue = () => true,
+} = {}) {
+ process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');
+
+ while (shouldContinue()) {
+ const event = await fetchNextEvent(base, token);
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+
+ if (event.type === 'exit') return event;
+
+ if (requiresAgentReply(event)) {
+ const acked = await waitForEventAck(base, token, event.id, {
+ pollIntervalMs: ackPollIntervalMs,
+ maxWaitMs: ackTimeoutMs,
+ });
+ if (!acked) {
+ const err = new Error(`Timed out waiting for --reply on event ${event.id}`);
+ err.code = 'ACK_TIMEOUT';
+ throw err;
+ }
+ }
+ }
+
+ return null;
+}
+
+function handlePollError(err) {
+ if (err.code === 'AUTH_FAILED') {
+ console.error(err.message);
+ console.error(`Try restarting: ${scriptCmd('live-server.mjs')} stop && ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.code === 'ACK_TIMEOUT') {
+ console.error(err.message);
+ process.exit(1);
+ }
+ console.error('Poll failed:', err.message);
+ process.exit(1);
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON, exit
+ poll --stream Keep polling; print one JSON line per event (see live.md)
+ poll --reply done Reply "done" to event (replace or insert generate)
+ poll --reply steer_done Reply after handling a steer event (unlocks Steer bar)
+ poll --reply error "msg" Reply with an error message
+ poll --reply done --data ''
+ Reply with a structured JSON result (manual_edit_apply)
+
+Options:
+ --timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode
+ --ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)
+ --file PATH Attach a source file path to the reply (generate/steer flow)
+ --data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON
+ --help Show this help message
+
+Harness note:
+ Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.
+ --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: node /live-poll.mjs --reply [--file path] [--data ''] [message]
+ if (args.includes('--reply')) {
+ let reply;
+ try {
+ reply = parseReplyArgs(args);
+ } catch (err) {
+ console.error(err.message);
+ process.exit(1);
+ }
+
+ try {
+ await postReply(base, info.token, reply);
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ const streamMode = args.includes('--stream');
+ const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));
+ const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;
+
+ try {
+ if (streamMode) {
+ await runPollStream(base, info.token, { ackTimeoutMs });
+ return;
+ }
+
+ const timeoutArg = args.find((a) => a.startsWith('--timeout='));
+ const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;
+ await runPollOnce(base, info.token, { totalTimeout });
+ } catch (err) {
+ handlePollError(err);
+ }
+}
+
+// Auto-execute when run directly
+const _running = process.argv[1];
+if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
+ pollCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-resume.mjs b/.github/skills/impeccable/scripts/live-resume.mjs
new file mode 100644
index 0000000..74284d4
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-resume.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+/**
+ * Recover the next agent action from the durable live-session journal.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+
+function manualApplyReplyCommand(eventOrId = 'EVENT_ID') {
+ const id = typeof eventOrId === 'string' ? eventOrId : eventOrId?.id || 'EVENT_ID';
+ return `live-poll.mjs --reply ${id} done --data ''`;
+}
+
+export function manualApplyResumeHint(event = {}) {
+ const summary = event.manualApplySummary || summarizeManualApplyEvent(event);
+ const parts = [];
+ if (summary.pageUrl) parts.push(`page ${summary.pageUrl}`);
+ if (summary.chunk) parts.push(`chunk ${summary.chunk.index}/${summary.chunk.total}`);
+ if (Number.isFinite(summary.opCount)) parts.push(`${summary.opCount} op(s)`);
+ if (Number.isFinite(summary.entryCount)) parts.push(`${summary.entryCount} entr${summary.entryCount === 1 ? 'y' : 'ies'}`);
+ if (summary.files?.length) parts.push(`likely files: ${summary.files.join(', ')}`);
+ const scope = parts.length ? ` (${parts.join(', ')})` : '';
+ return `Manual Apply pending${scope}. If you have not already leased it, run live-poll.mjs. Apply the source edits from the manual_edit_apply batch, then reply with ${manualApplyReplyCommand(event.id)}. Polling only leases this work item; it does not commit source edits. Do not run live-commit-manual-edits.mjs for this leased event. Do not poll again before replying.`;
+}
+
+function summarizeManualApplyEvent(event = {}) {
+ const entries = Array.isArray(event.batch?.entries) ? event.batch.entries : [];
+ const opCount = entries.reduce((sum, entry) => sum + (Array.isArray(entry.ops) ? entry.ops.length : 0), 0);
+ return {
+ pageUrl: event.pageUrl || null,
+ chunk: event.chunk || null,
+ entryCount: entries.length,
+ opCount,
+ files: collectManualApplyFiles(event.batch),
+ };
+}
+
+function collectManualApplyFiles(batch) {
+ const files = [];
+ for (const entry of batch?.entries || []) {
+ for (const op of entry.ops || []) files.push(op.sourceHint?.file);
+ }
+ for (const candidate of batch?.candidates || []) {
+ files.push(candidate.sourceHint?.relativeFile, candidate.sourceHint?.file);
+ for (const item of candidate.textMatches || []) files.push(item.file);
+ for (const item of candidate.objectKeyMatches || []) files.push(item.file);
+ for (const item of candidate.locatorMatches || []) files.push(item.file);
+ for (const item of candidate.contextTextMatches || []) files.push(item.file);
+ }
+ return [...new Set(files.filter((file) => typeof file === 'string' && file.length > 0))].sort();
+}
+
+function parseArgs(argv) {
+ const out = { id: null };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--id') out.id = argv[++i];
+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
+ else if (arg === '--help' || arg === '-h') out.help = true;
+ }
+ return out;
+}
+
+export async function resumeCli() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
+ return;
+ }
+
+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
+ if (!snapshot) {
+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
+ return;
+ }
+
+ const pending = snapshot.pendingEvent || null;
+ const nextAction = pending
+ ? pending.type === 'manual_edit_apply'
+ ? manualApplyResumeHint(pending)
+ : `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
+ : snapshot.phase === 'carbonize_required'
+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
+ : snapshot.phase === 'accept_requested'
+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
+
+ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
+ resumeCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-server.mjs b/.github/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 0000000..5735f2a
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,1137 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node /live-server.mjs # start
+ * node /live-server.mjs stop # stop + remove injected live.js tag
+ * node /live-server.mjs stop --keep-inject # stop only
+ * node /live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import { spawn, execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+import { parseDesignMd } from './lib/design-parser.mjs';
+import { loadContext } from './context.mjs';
+import {
+ assembleLiveBrowserScript,
+ assertLiveBrowserScriptParts,
+ readLiveBrowserScriptParts,
+ resolveLiveBrowserScriptParts,
+} from './live/browser-script-parts.mjs';
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { validateEvent } from './live/event-validation.mjs';
+import { createManualEditRoutes } from './live/manual-edit-routes.mjs';
+import { LIVE_COMMANDS } from './live/vocabulary.mjs';
+import {
+ getDesignSidecarPath,
+ getLiveDir,
+ getLiveAnnotationsDir,
+ IMPECCABLE_COMMAND_PREFIX,
+ readLiveServerInfo,
+ removeLiveServerInfo,
+ resolveDesignSidecarPath,
+ writeLiveServerInfo,
+} from './lib/impeccable-paths.mjs';
+import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
+import {
+ createManualApplyController,
+ summarizeManualApplyFailures,
+} from './live/manual-apply.mjs';
+import {
+ applyDeferredSvelteComponentAccepts,
+ removeAllSvelteComponentSessions,
+} from './live/svelte-component.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+// PRODUCT.md / DESIGN.md live wherever context.mjs resolves. The generated
+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
+// DESIGN.json fallback for existing projects.
+const PROJECT_CONTEXT = loadContext(process.cwd());
+const CONTEXT_DIR = PROJECT_CONTEXT.contextDir;
+const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath
+ ? path.resolve(process.cwd(), PROJECT_CONTEXT.designPath)
+ : null;
+const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
+const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ nextEventSeq: 1,
+ lastAgentPollingBroadcast: null,
+ exitTimer: null,
+ sessionDir: null, // per-session tmp dir for annotation screenshots
+ sessionStore: null,
+ leaseTimer: null,
+ manualEditActivity: null,
+ nextManualEditSeq: 1,
+ // Deferreds for in-flight chat-routed Apply events. Keyed by event id; each
+ // entry is resolved when the chat agent POSTs an ack carrying the batch
+ // result, or rejected when the hard timeout fires.
+ pendingApplyDeferreds: new Map(),
+ // Updated whenever a /poll long-poll request arrives or is resolved with an
+ // event. Used to detect "a chat agent is likely attached" without requiring
+ // a poll to be parked at the exact moment we dispatch.
+ lastPollAt: 0,
+ timedOutApplyIds: new Map(),
+};
+
+const CHAT_POLL_FRESHNESS_MS = 60_000;
+const POLL_LEASE_EXPIRY_TIMER_GRACE_MS = 2;
+const DEBUG_MANUAL_EDIT_EVENTS = /^(1|true|yes)$/i.test(process.env.IMPECCABLE_LIVE_DEBUG_EVENTS || '');
+
+const manualApply = createManualApplyController({
+ pendingEvents: state.pendingEvents,
+ pendingApplyDeferreds: state.pendingApplyDeferreds,
+ timedOutApplyIds: state.timedOutApplyIds,
+ enqueueEvent,
+ acknowledgePendingEvent,
+ flushPendingPolls,
+ recordManualEditActivity,
+ cwd: () => process.cwd(),
+});
+
+const manualEditRoutes = createManualEditRoutes({
+ getToken: () => state.token,
+ manualApply,
+ recordManualEditActivity,
+ getManualEditStatus,
+ chatAgentLikelyActive,
+ cwd: () => process.cwd(),
+ env: () => process.env,
+});
+
+function chatAgentLikelyActive() {
+ if (state.pendingPolls.length > 0) return true;
+ if (!state.lastPollAt) return false;
+ return Date.now() - state.lastPollAt < CHAT_POLL_FRESHNESS_MS;
+}
+
+// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
+// cap at 10 MB to guard against runaway writes from a misbehaving client.
+const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
+
+function enqueueEvent(event) {
+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
+ state.pendingEvents.push({ event, leaseUntil: 0, seq: state.nextEventSeq++ });
+ flushPendingPolls();
+}
+
+function restorePendingEventsFromStore() {
+ if (!state.sessionStore) return;
+ for (const snapshot of state.sessionStore.listActiveSessions()) {
+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
+ }
+}
+
+function findAvailablePendingEvent(now = Date.now()) {
+ for (const entry of state.pendingEvents) {
+ if (entry.leaseUntil && entry.leaseUntil > now) continue;
+ return entry;
+ }
+ return null;
+}
+
+function leaseEvent(entry, leaseMs) {
+ if (!entry.event?.id) {
+ const idx = state.pendingEvents.indexOf(entry);
+ if (idx !== -1) state.pendingEvents.splice(idx, 1);
+ return entry.event;
+ }
+ entry.leaseUntil = Date.now() + leaseMs;
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return entry.event;
+}
+
+function acknowledgePendingEvent(id) {
+ if (!id) return false;
+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
+ if (idx === -1) return false;
+ const acknowledged = state.pendingEvents[idx].event;
+ state.pendingEvents.splice(idx, 1);
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return acknowledged;
+}
+
+function findPendingEventById(id) {
+ if (!id) return null;
+ const entry = state.pendingEvents.find((item) => item.event?.id === id);
+ return entry?.event || null;
+}
+
+function summarizePendingEventForStatus(entry) {
+ const event = entry.event || {};
+ const summary = {
+ id: event.id,
+ type: event.type,
+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
+ leaseUntil: entry.leaseUntil || null,
+ };
+ if (event.type === 'manual_edit_apply') {
+ summary.pageUrl = event.pageUrl || null;
+ summary.chunk = event.chunk || null;
+ summary.repair = event.repair || null;
+ summary.evidencePath = event.evidencePath || null;
+ summary.agentAction = event.agentAction || manualApply.buildAgentAction(event);
+ summary.manualApplySummary = manualApply.summarizeEvent(event, manualApply.getDeferred(event.id)?.batch || event.batch);
+ }
+ return summary;
+}
+
+function summarizeActiveSessionForClient(snapshot = {}) {
+ return {
+ id: snapshot.id,
+ phase: snapshot.phase,
+ pageUrl: snapshot.pageUrl ?? null,
+ sourceFile: snapshot.sourceFile ?? null,
+ previewFile: snapshot.previewFile ?? null,
+ previewMode: snapshot.previewMode ?? null,
+ expectedVariants: snapshot.expectedVariants ?? 0,
+ arrivedVariants: snapshot.arrivedVariants ?? 0,
+ visibleVariant: snapshot.visibleVariant ?? null,
+ checkpointRevision: snapshot.checkpointRevision ?? 0,
+ paramValues: snapshot.paramValues || {},
+ };
+}
+
+function activeSessionSummaries() {
+ if (!state.sessionStore) return [];
+ return state.sessionStore.listActiveSessions().map((snapshot) => summarizeActiveSessionForClient(snapshot));
+}
+
+function cancelQueuedAnonymousExitEvents() {
+ let removed = 0;
+ for (let i = state.pendingEvents.length - 1; i >= 0; i -= 1) {
+ const event = state.pendingEvents[i]?.event;
+ if (event?.type !== 'exit' || event.id) continue;
+ state.pendingEvents.splice(i, 1);
+ removed += 1;
+ }
+ if (removed > 0) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ }
+ return removed;
+}
+
+function scheduleLeaseFlush() {
+ if (state.leaseTimer) {
+ clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ }
+ const now = Date.now();
+ const nextLeaseUntil = state.pendingEvents
+ .map((entry) => entry.leaseUntil || 0)
+ .filter((leaseUntil) => leaseUntil > now)
+ .sort((a, b) => a - b)[0];
+ if (!nextLeaseUntil) return;
+ state.leaseTimer = setTimeout(() => {
+ state.leaseTimer = null;
+ flushPendingPolls();
+ broadcastAgentPollingIfChanged();
+ }, Math.max(0, nextLeaseUntil - now + POLL_LEASE_EXPIRY_TIMER_GRACE_MS));
+}
+
+function flushPendingPolls() {
+ let changed = false;
+ while (state.pendingPolls.length > 0) {
+ const entry = findAvailablePendingEvent();
+ if (!entry) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return;
+ }
+ const poll = state.pendingPolls.shift();
+ poll.resolve(leaseEvent(entry, poll.leaseMs));
+ changed = true;
+ }
+ scheduleLeaseFlush();
+ if (changed) broadcastAgentPollingIfChanged();
+}
+
+function agentPollingConnected() {
+ const now = Date.now();
+ return state.pendingPolls.length > 0
+ || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);
+}
+
+function broadcastAgentPollingIfChanged() {
+ const connected = agentPollingConnected();
+ if (state.lastAgentPollingBroadcast === connected) return;
+ state.lastAgentPollingBroadcast = connected;
+ broadcast({ type: 'agent_polling', connected });
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+function recordManualEditActivity(type, details = {}) {
+ const entry = {
+ seq: state.nextManualEditSeq++,
+ type,
+ ts: new Date().toISOString(),
+ ...details,
+ };
+ state.manualEditActivity = entry;
+ if (DEBUG_MANUAL_EDIT_EVENTS) {
+ try {
+ const filePath = path.join(getLiveDir(process.cwd()), 'manual-edit-events.jsonl');
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.appendFileSync(filePath, JSON.stringify(entry) + '\n');
+ } catch {
+ /* diagnostics are best-effort; never block live mode on observability */
+ }
+ }
+ broadcast(entry);
+ return entry;
+}
+
+function getManualEditStatus() {
+ try {
+ const { totalCount, perPage } = countPendingByPage(process.cwd());
+ return { totalCount, perPage, lastActivity: state.manualEditActivity };
+ } catch (err) {
+ return {
+ totalCount: null,
+ perPage: {},
+ lastActivity: state.manualEditActivity,
+ error: err.message,
+ };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: prefer the skill-bundled detector, then fall back to
+ // source/npm package locations for local development and older installs.
+ // This one IS cached — detect.js rarely changes during a session.
+ const detectPaths = [
+ path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ // Browser script parts: DO NOT cache. Return paths so the /live.js handler
+ // can re-read every part on each request. Editing browser code during
+ // iteration should land on the next tab reload, not require a server restart.
+ const liveScriptParts = resolveLiveBrowserScriptParts(__dirname);
+ try {
+ assertLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ process.stderr.write('Error: ' + err.message + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScriptParts };
+}
+
+function hasProjectContext() {
+ // PRODUCT.md carries brand voice / anti-references — that's what determines
+ // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
+ // concern, surfaced by the design panel's own empty state.
+ return !!PROJECT_CONTEXT.hasProduct;
+}
+
+function statOrNull(filePath) {
+ try { return fs.statSync(filePath); } catch { return null; }
+}
+
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptParts }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ // Re-read from disk each request so edits to live-browser.js land on
+ // the next tab reload. No-store headers prevent browser caching across
+ // sessions — during iteration, a cached old script silently breaks
+ // every subsequent session.
+ let parts;
+ try {
+ parts = readLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
+ res.end('Error reading live browser scripts: ' + err.message);
+ return;
+ }
+ const body = assembleLiveBrowserScript({
+ token: state.token,
+ port: state.port,
+ vocabulary: LIVE_COMMANDS,
+ commandPrefix: IMPECCABLE_COMMAND_PREFIX,
+ parts,
+ });
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
+ 'Pragma': 'no-cache',
+ });
+ res.end(body);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Vendored modern-screenshot (UMD build) ---
+ // Lazy-loaded by live.js when the user clicks Go; exposes
+ // window.modernScreenshot.domToBlob(...) for capture.
+ if (p === '/modern-screenshot.js') {
+ const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
+ try {
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'public, max-age=31536000, immutable',
+ });
+ res.end(fs.readFileSync(vendorPath));
+ } catch {
+ res.writeHead(404); res.end('Vendor script not found');
+ }
+ return;
+ }
+
+ // --- Annotation upload (browser → server, raw PNG body) ---
+ // Client generates the eventId, POSTs the PNG, then POSTs the generate
+ // event with screenshotPath already set. Keeps bytes out of the SSE/poll
+ // bridge and preserves the "one shot from the user's POV" UX.
+ if (p === '/annotation' && req.method === 'POST') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const eventId = url.searchParams.get('eventId');
+ if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid eventId' }));
+ return;
+ }
+ if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
+ res.writeHead(415, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
+ return;
+ }
+ if (!state.sessionDir) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Session dir unavailable' }));
+ return;
+ }
+ const chunks = [];
+ let total = 0;
+ let aborted = false;
+ req.on('data', (c) => {
+ if (aborted) return;
+ total += c.length;
+ if (total > MAX_ANNOTATION_BYTES) {
+ aborted = true;
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Payload too large' }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => {
+ if (aborted) return;
+ const absPath = path.join(state.sessionDir, eventId + '.png');
+ try {
+ fs.writeFileSync(absPath, Buffer.concat(chunks));
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
+ return;
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, path: absPath }));
+ });
+ req.on('error', () => {
+ if (!aborted) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Upload failed' }));
+ }
+ });
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/status') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
+ const sessions = activeSessionSummaries();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok',
+ port: state.port,
+ connectedClients: state.sseClients.size,
+ pendingEvents: state.pendingEvents.map((entry) => summarizePendingEventForStatus(entry)),
+ agentPolling: agentPollingConnected(),
+ activeSessions: sessions,
+ manualEdits: getManualEditStatus(),
+ }));
+ return;
+ }
+
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Design system (unified v2 response) + raw ---
+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
+ // sidecar when present. Panel merges them:
+ // { present, parsed, sidecar, hasMd, hasSidecar,
+ // mdNewerThanJson, parseError?, sidecarError? }
+ // - parsed: output of parseDesignMd (frontmatter
+ // + six canonical sections) when DESIGN.md exists.
+ // - sidecar: .impeccable/design.json contents when present.
+ // Expected shape: schemaVersion 2, carrying
+ // extensions + components + narrative.
+ // /design-system/raw returns DESIGN.md markdown verbatim
+ if (p === '/design-system.json' || p === '/design-system/raw') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+
+ const mdPath = DESIGN_MD_PATH;
+ const jsonPath = resolveDesignSidecarPath(process.cwd(), PROJECT_CONTEXT.designContextDir || CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
+ const mdStat = statOrNull(mdPath);
+ const jsonStat = statOrNull(jsonPath);
+
+ if (p === '/design-system/raw') {
+ if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
+ res.end(fs.readFileSync(mdPath, 'utf-8'));
+ return;
+ }
+
+ if (!mdStat && !jsonStat) {
+ res.writeHead(404, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ present: false }));
+ return;
+ }
+
+ const response = {
+ present: true,
+ hasMd: !!mdStat,
+ hasSidecar: !!jsonStat,
+ mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
+ };
+
+ if (mdStat) {
+ try {
+ response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
+ } catch (err) {
+ response.parseError = err.message;
+ }
+ }
+
+ if (jsonStat) {
+ try {
+ response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
+ } catch (err) {
+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
+ }
+ }
+
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(response));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ let content;
+ try { content = fs.readFileSync(absPath, 'utf-8'); }
+ catch { res.writeHead(404); res.end('File not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(content);
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ clearTimeout(state.exitTimer);
+ state.exitTimer = null;
+ cancelQueuedAnonymousExitEvents();
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ agentPolling: agentPollingConnected(),
+ activeSessions: activeSessionSummaries(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+
+ // Keepalive: SSE comment every 30s prevents silent connection drops.
+ const heartbeat = setInterval(() => {
+ try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
+ }, SSE_HEARTBEAT_INTERVAL);
+
+ req.on('close', () => {
+ clearInterval(heartbeat);
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ if (manualEditRoutes(req, res, url)) return;
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Defense in depth: manual copy edits must use the staged stash/apply
+ // endpoints. The direct Save event path is disabled in the browser.
+ if (msg.type === 'manual_edits') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edits must POST to /manual-edit-stash, not /events' }));
+ return;
+ }
+ if (msg.type === 'manual_edit_apply') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edit_apply is disabled; use /manual-edit-stash then /manual-edit-commit' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ if (state.sessionStore && msg.id) {
+ try {
+ state.sessionStore.appendEvent(msg);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
+ return;
+ }
+ }
+ if (msg.type === 'exit') {
+ cleanupSvelteComponentSessionsBeforeExit();
+ }
+ if (msg.type !== 'checkpoint') {
+ enqueueEvent(msg);
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ state.lastPollAt = Date.now();
+ const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
+ const available = findAvailablePendingEvent();
+ if (available) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));
+ return;
+ }
+ const poll = { resolve, leaseMs };
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ state.lastPollAt = Date.now();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(poll);
+ broadcastAgentPollingIfChanged();
+ scheduleLeaseFlush();
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ });
+}
+
+function sessionFileMetadataFromPollReply(file) {
+ if (!file || typeof file !== 'string') return { file };
+ const normalized = file.split(path.sep).join('/');
+ const base = { file: normalized };
+ if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;
+ if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;
+
+ let full;
+ try {
+ full = path.resolve(process.cwd(), normalized);
+ const rel = path.relative(process.cwd(), full);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;
+ } catch {
+ return base;
+ }
+
+ try {
+ const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));
+ if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;
+ return {
+ file: String(manifest.sourceFile).split(path.sep).join('/'),
+ sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),
+ previewFile: normalized,
+ previewMode: 'svelte-component',
+ };
+ } catch {
+ return base;
+ }
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const pendingApplyDeferred = manualApply.getDeferred(msg.id);
+ if (pendingApplyDeferred) {
+ const validation = manualApply.validateResultMessage(msg, pendingApplyDeferred);
+ if (!validation.ok) {
+ recordManualEditActivity('manual_edit_apply_reply_invalid', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ reason: validation.body?.reason || validation.body?.error || 'invalid_manual_apply_result',
+ status: msg.data?.status || null,
+ });
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(validation.body));
+ return;
+ }
+ recordManualEditActivity('manual_edit_apply_reply_received', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ status: validation.result.status,
+ appliedCount: validation.result.appliedEntryIds.length,
+ failed: summarizeManualApplyFailures(validation.result.failed),
+ fileCount: validation.result.files.length,
+ noteCount: validation.result.notes.length,
+ });
+ manualApply.resolveDeferred(msg.id, validation.result);
+ acknowledgePendingEvent(msg.id);
+ flushPendingPolls();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ return;
+ }
+ if (manualApply.hasTimedOutId(msg.id)) {
+ const rollback = manualApply.rollbackTimedOutReply(msg);
+ recordManualEditActivity('manual_edit_apply_stale_reply_rejected', {
+ id: msg.id,
+ rolledBackFileCount: rollback.rolledBackFiles?.length || 0,
+ rollbackFailureCount: rollback.rollbackFailures?.length || 0,
+ });
+ res.writeHead(409, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));
+ return;
+ }
+ const pendingEventBeforeAck = findPendingEventById(msg.id);
+ if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'
+ && !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: 'steer_done_requires_file_or_message',
+ hint: 'Reply with --file after writing source, or include a message explaining an intentional no-op.',
+ }));
+ return;
+ }
+ const acknowledgedEvent = acknowledgePendingEvent(msg.id);
+ let skipJournalReply = false;
+ let existingSession = null;
+ if (!acknowledgedEvent && state.sessionStore && msg.id) {
+ try {
+ existingSession = state.sessionStore.getSnapshot(msg.id, { includeCompleted: true });
+ if (!existingSession?.updatedAt) existingSession = null;
+ skipJournalReply = existingSession?.phase === 'completed' || existingSession?.phase === 'discarded';
+ } catch { /* fall through and record the reply normally */ }
+ }
+ if (!acknowledgedEvent && !existingSession) {
+ recordManualEditActivity('manual_edit_poll_reply_unknown', {
+ id: msg.id || null,
+ type: msg.type || null,
+ });
+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: msg.id ? 'unknown_poll_reply_id' : 'missing_poll_reply_id',
+ id: msg.id,
+ }));
+ return;
+ }
+ const replyFileMeta = sessionFileMetadataFromPollReply(msg.file);
+ if (state.sessionStore && msg.id && !skipJournalReply) {
+ try {
+ const eventType = msg.type === 'steer_done'
+ ? 'steer_done'
+ : msg.type === 'discard' || msg.type === 'discarded'
+ ? 'discarded'
+ : msg.type === 'complete'
+ ? 'complete'
+ : msg.type === 'error'
+ ? 'agent_error'
+ : 'agent_done';
+ state.sessionStore.appendEvent({
+ type: eventType,
+ id: msg.id,
+ file: replyFileMeta.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ message: msg.message,
+ sourceEventType: acknowledgedEvent?.type,
+ carbonize: msg.data?.carbonize === true,
+ });
+ } catch { /* keep reply path best-effort; browser still needs SSE */ }
+ }
+ flushPendingPolls();
+ // Forward the reply to the browser via SSE
+ broadcast({
+ type: msg.type || 'done',
+ id: msg.id,
+ message: msg.message,
+ file: msg.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ data: msg.data,
+ });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ cleanupSvelteComponentSessionsBeforeExit();
+ removeLiveServerInfo(process.cwd());
+ if (state.leaseTimer) clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ if (state.sessionDir) {
+ try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
+ }
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+function cleanupSvelteComponentSessionsBeforeExit() {
+ try {
+ removeAllSvelteComponentSessions(process.cwd());
+ } catch (err) {
+ console.warn('[impeccable] Svelte component session cleanup failed:', err.message);
+ }
+}
+
+function applyLegacyDeferredAcceptsOnStartup() {
+ try {
+ const result = applyDeferredSvelteComponentAccepts(process.cwd());
+ if (result.applied > 0 || result.failed > 0) {
+ console.log('[impeccable] applied legacy deferred Svelte component accepts:', JSON.stringify(result));
+ }
+ } catch (err) {
+ console.warn('[impeccable] legacy deferred Svelte component accept apply failed:', err.message);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server (foreground)
+ stop Stop the server and remove the injected live.js script tag
+ stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
+
+Options:
+ --background Start detached, print connection JSON to stdout, then exit
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --keep-inject Only with stop: skip live-inject.mjs --remove
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
+ /annotation POST raw image/png to stage a variant screenshot
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /manual-edit-stash Stage browser copy edits
+ /manual-edit-commit Apply staged browser copy edits
+ /manual-edit-discard Discard staged browser copy edits
+ /source Raw source file reader (no-HMR fallback)
+ /status Durable recovery status (token-protected)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ const keepInject = args.includes('--keep-inject');
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
+ if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
+ } catch {
+ console.log('No running live server found.');
+ }
+ if (!keepInject) {
+ const injectPath = path.join(__dirname, 'live-inject.mjs');
+ try {
+ const out = execFileSync(process.execPath, [injectPath, '--remove'], {
+ encoding: 'utf-8',
+ cwd: process.cwd(),
+ });
+ const line = out.trim().split('\n').filter(Boolean).pop();
+ if (line) {
+ try {
+ const j = JSON.parse(line);
+ if (j.removed === true) {
+ console.log(`Removed live script tag from ${j.file}.`);
+ }
+ } catch {
+ /* ignore non-JSON lines */
+ }
+ }
+ } catch (err) {
+ const detail = err.stderr?.toString?.().trim?.()
+ || err.stdout?.toString?.().trim?.()
+ || err.message
+ || String(err);
+ console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
+ }
+ }
+ process.exit(0);
+}
+
+// --background: spawn a detached child server, wait for it to be ready,
+// print the connection JSON, then exit. This keeps the startup command
+// simple (no shell backgrounding or chained commands).
+if (args.includes('--background')) {
+ const childArgs = args.filter(a => a !== '--background');
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
+ detached: true,
+ stdio: 'ignore',
+ cwd: process.cwd(),
+ });
+ child.unref();
+
+ // Poll for the PID file (the child writes it once the HTTP server is listening).
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ if (info.pid !== process.pid) {
+ // Output JSON so the agent can read port + token from stdout.
+ console.log(JSON.stringify(info));
+ process.exit(0);
+ }
+ } catch { /* not ready yet */ }
+ await new Promise(r => setTimeout(r, 200));
+ }
+ console.error('Timed out waiting for live server to start.');
+ process.exit(1);
+}
+
+// Check for existing session
+const existingRecord = readLiveServerInfo(process.cwd());
+if (existingRecord?.info) {
+ const existing = existingRecord.info;
+ try {
+ process.kill(existing.pid, 0);
+ console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
+ console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
+ process.exit(1);
+ } catch {
+ try { fs.unlinkSync(existingRecord.path); } catch {}
+ }
+}
+
+state.token = randomUUID();
+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
+manualApply.rollbackTransaction({
+ reason: 'manual_edit_server_start_recovered_abandoned_transaction',
+});
+applyLegacyDeferredAcceptsOnStartup();
+restorePendingEventsFromStore();
+manualApply.pruneStaleEvidence();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+// Annotation screenshots live in the project root so the agent's Read tool
+// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
+// projects (or quick restarts) don't collide.
+const annotRoot = getLiveAnnotationsDir(process.cwd());
+fs.mkdirSync(annotRoot, { recursive: true });
+state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
+
+const { detectScript, liveScriptParts } = loadBrowserScripts();
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptParts }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
+ const url = `http://localhost:${state.port}`;
+ console.log(`\nImpeccable live server running on ${url}`);
+ console.log(`Token: ${state.token}\n`);
+ console.log(`Script: ${url}/live.js`);
+ console.log('Inject: managed by live-inject.mjs; Astro source tags use is:inline automatically.');
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.github/skills/impeccable/scripts/live-status.mjs b/.github/skills/impeccable/scripts/live-status.mjs
new file mode 100644
index 0000000..f7e4649
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-status.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Print durable recovery status for Impeccable live sessions.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+import { manualApplyResumeHint } from './live-resume.mjs';
+
+function readServerInfo() {
+ return readLiveServerInfo(process.cwd())?.info || null;
+}
+
+async function fetchServerStatus(info) {
+ if (!info) return null;
+ try {
+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+export async function statusCli() {
+ const info = readServerInfo();
+ const server = await fetchServerStatus(info);
+ const store = createLiveSessionStore({ cwd: process.cwd() });
+ const activeSessions = store.listActiveSessions();
+ const manualApply = findPendingManualApply(server, activeSessions);
+ const payload = {
+ liveServer: server ? {
+ status: server.status,
+ port: server.port,
+ connectedClients: server.connectedClients,
+ agentPolling: server.agentPolling,
+ pendingEvents: server.pendingEvents,
+ } : null,
+ activeSessions: server?.activeSessions || activeSessions,
+ recoveryHint: manualApply
+ ? manualApplyResumeHint(manualApply)
+ : server
+ ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id after manual cleanup.'
+ : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
+ };
+ console.log(JSON.stringify(payload, null, 2));
+}
+
+function findPendingManualApply(server, activeSessions) {
+ const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');
+ if (fromServer) return fromServer;
+ const fromSession = activeSessions
+ ?.map((session) => session.pendingEvent)
+ .find((event) => event?.type === 'manual_edit_apply');
+ return fromSession || null;
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
+ statusCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-target.mjs b/.github/skills/impeccable/scripts/live-target.mjs
new file mode 100644
index 0000000..498bc55
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-target.mjs
@@ -0,0 +1,30 @@
+import path from 'node:path';
+import { resolveProjectRoot } from './context.mjs';
+import { parseTargetPath } from './lib/target-args.mjs';
+
+export function resolveLiveTarget(cwd = process.cwd(), args = []) {
+ const originalCwd = path.resolve(cwd);
+ let targetPath = null;
+ try {
+ targetPath = parseTargetPath(args, { strict: true });
+ } catch (err) {
+ if (err?.name === 'TargetArgError') {
+ process.stderr.write(`${err.message}\n`);
+ process.exit(1);
+ }
+ throw err;
+ }
+ const absoluteTargetPath = targetPath
+ ? path.isAbsolute(targetPath) ? targetPath : path.resolve(originalCwd, targetPath)
+ : null;
+ const projectRoot = targetPath
+ ? resolveProjectRoot(originalCwd, { targetPath: absoluteTargetPath })
+ : originalCwd;
+ return {
+ originalCwd,
+ projectRoot,
+ targetPath,
+ absoluteTargetPath,
+ targetOptions: absoluteTargetPath ? { targetPath: absoluteTargetPath } : {},
+ };
+}
diff --git a/.github/skills/impeccable/scripts/live-wrap.mjs b/.github/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 0000000..438c01b
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,894 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * node /live-wrap.mjs --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer as readManualEditsBuffer } from './live/manual-edits-buffer.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma- or space-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --text TEXT Picked element's textContent. Used to disambiguate when
+ classes/tag match multiple sibling elements (e.g. a list
+ of s with the same className). Pass the first ~80
+ chars of event.element.textContent.
+ --page-url URL Current page URL. Required when pending manual edits may
+ affect the picked source block. Pending edits are filtered
+ to this page so an edit on /a doesn't bleed into /b.
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+ const text = argVal(args, '--text');
+ const pageUrl = argVal(args, '--page-url');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ const genOpts = { cwd: process.cwd() };
+
+ // Find the source file. Generated files are excluded from auto-search so we
+ // don't silently write variants into a file the next build will wipe.
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ // Nothing in source. Did the element show up in a generated file? That
+ // tells the agent "fall back to the agent-driven flow" vs "element just
+ // doesn't exist in this project."
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ if (generatedHit) {
+ console.error(JSON.stringify({
+ error: 'element_not_in_source',
+ fallback: 'agent-driven',
+ generatedMatch: path.relative(process.cwd(), generatedHit),
+ hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
+ }));
+ } else {
+ console.error(JSON.stringify({
+ error: 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
+ }));
+ }
+ process.exit(1);
+ }
+ } else {
+ if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order. When `--text` is
+ // supplied, collect every candidate the queries surface and disambiguate
+ // by the picked element's textContent. Without `--text`, fall back to the
+ // legacy first-match behavior so unmodified callers keep working.
+ let match = null;
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) {
+ candidates.push(c);
+ }
+ }
+ // Once a more-specific query (ID, full className combo) yielded a unique
+ // result, stop — falling through to the loose tag+single-class query
+ // would readmit the siblings we just disambiguated past.
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ if (candidates.length === 1) {
+ match = candidates[0];
+ } else {
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) {
+ match = filtered[0];
+ } else if (filtered.length === 0) {
+ // Source uses dynamic content (`
{title}
` etc.) so the
+ // browser-side textContent doesn't appear literally in source. Fall
+ // back to first-match rather than refusing — this is the same
+ // behavior unmodified callers see, just preserved.
+ match = candidates[0];
+ } else {
+ // Multiple candidates ALSO match the text. Truly ambiguous — refuse
+ // rather than pick wrong, and hand the agent the candidate locations
+ // so it can disambiguate by reading the file.
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: filtered.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ }
+ } else {
+ for (const q of queries) {
+ match = findElement(lines, q, tag);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element. Reindent under the wrapper while preserving
+ // the relative depth between lines — `l.trimStart()` would strip ALL leading
+ // whitespace and collapse e.g. `` (6/8/6 spaces)
+ // to a single uniform indent, so on accept/discard the round-trip restores
+ // the inner element at its parent's depth instead of nested inside it.
+ // Strip only the COMMON minimum leading whitespace across the picked lines;
+ // `deindentContent` on the accept side already mirrors this convention.
+ let originalLines = lines.slice(startLine, endLine + 1);
+
+ // Buffer-aware "original" content: if the user has pending manual edits for
+ // this page whose originalText appears in the picked source range, apply
+ // them so the wrap block's "original" variant reflects what the user was
+ // looking at (their edited DOM), not the raw source. Source itself stays
+ // untouched here — only the wrap block's embedded "original" copy is
+ // adjusted. The pending edits remain in the buffer until committed.
+ //
+ // Apply buffered edits only when the browser provided the current page URL.
+ // Without it, fail if pending edits plausibly touch this exact source range;
+ // otherwise skip buffer awareness so unrelated staged edits on another page
+ // do not block normal wrap work.
+ let pendingBuffer = { entries: [] };
+ try { pendingBuffer = readManualEditsBuffer(process.cwd()); } catch {}
+ const pendingEntriesForTarget = pageUrl
+ ? []
+ : pendingEntriesThatMayAffectWrap(pendingBuffer.entries, targetFile, originalLines, startLine, process.cwd());
+ if (pendingEntriesForTarget.length > 0) {
+ console.error(JSON.stringify({
+ error: 'missing_page_url_with_pending_edits',
+ pendingEntries: pendingEntriesForTarget.length,
+ hint: 'Pending manual edits may affect the selected source block. Pass --page-url=$event.pageUrl so the wrap block reflects the user\'s staged DOM.',
+ }));
+ process.exit(1);
+ }
+ if (pageUrl) {
+ const failedBufferedOps = [];
+ for (const entry of pendingBuffer.entries || []) {
+ if (entry.pageUrl !== pageUrl) continue;
+ for (const op of entry.ops || []) {
+ const mayAffectWrap = manualEditMayAffectWrap(op, targetFile, originalLines, startLine, process.cwd());
+ const result = applyBufferedManualEditToLines(originalLines, startLine, op);
+ if (result.changed) {
+ originalLines = result.lines;
+ continue;
+ }
+ if (!mayAffectWrap) continue;
+ failedBufferedOps.push({
+ entryId: entry.id,
+ ref: op?.ref || null,
+ originalText: op?.originalText || null,
+ reason: 'ambiguous_or_unmatched_pending_edit',
+ });
+ }
+ }
+ if (failedBufferedOps.length > 0) {
+ console.error(JSON.stringify({
+ error: 'manual_edit_buffer_apply_failed',
+ pendingOps: failedBufferedOps,
+ hint: 'A staged copy edit appears to affect the selected source block, but could not be applied unambiguously to the wrap original. Apply or discard copy edits first, or write the wrapper manually.',
+ }));
+ process.exit(1);
+ }
+ }
+
+ const originalBaseIndent = minLeadingSpaces(originalLines);
+ const reindentOriginal = (extra) => originalLines
+ .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
+ .join('\n');
+ const originalIndented = reindentOriginal(' ');
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+ const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);
+
+ // Wrapper attributes differ by syntax. HTML allows plain string attrs;
+ // JSX requires object-literal style and parses string attrs as HTML (which
+ // either type-errors or renders a literal CSS string).
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+
+ // JSX/TSX guard: the picked element occupies a single JSX child slot
+ // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
+ // any other expression position). Replacing it with `comment +
+
+ // comment` yields three adjacent siblings — invalid JSX. We can't use a
+ // Fragment `<>>` either: parents that clone children (Radix `asChild`,
+ // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
+ // they try to pass an `id` through.
+ //
+ // Solution: keep the wrapper `
` as the single JSX-slot child and
+ // tuck both marker comments INSIDE it. accept/discard then expands its
+ // replacement range to include the wrapper's `
` open / close lines
+ // so the entire scaffold gets removed cleanly.
+ const wrapperLines = isJsx ? [
+ indent + '