Deploy Engine
Skill for deploying web artifacts to hq-deploy infrastructure. Invoked directly via /deploy, or auto-triggered by auto-deploy-on-create (silent post-build) and hq-deploy-reinforcement (intent-to-share, deliverable PRDs) policies. The two paths share this same engine.
Guiding principle: quick casual handoff — preview, upload, link. Sensitive artifacts get the lowest-friction appropriate gate: password, Cognito company access, or an email allowlist when the user names recipients.
Fast path: single static page, company-gated. For one static index.html (no build step) that should be visible only to the active company's members, skip the rest of this file and run:
bash .claude/skills/project-summary/scripts/deploy-summary.sh <build-dir> <app-name> [company-slug]
It applies and proves the gate before uploading, reuses <app-name> so the URL stays stable, falls back to a password gate when no company resolves, and prints LIVE=, MODE=, GATE= (and PASSWORD= in password mode). Use the full flow below for anything else: builds, public deploys, email allowlists, or route mode.
Reuse before creating. When a static artifact belongs on a site that is already live, add it as a route on that app instead of creating a new one. When it is unclear whether it belongs there, ask the user. See "Reuse an existing deploy (route mode)" in C.2.
Access modes (reference)
Every deployed app has exactly one edge access mode. New policy-aware deploys prefer the first-class access-policy endpoint for Cognito gates; the legacy access-mode endpoint remains the right path for password and email/domain allowlists.
| Mode | When to pick it | What it does |
|---|---|---|
| public | Default. Casual handoff, anyone with the link. | No gate. App serves immediately. |
| password | Sensitive content, casual share over Slack/email, recipients unknown ahead of time. | App owner sets a password (Argon2id-hashed). Visitors land on hq.{your-domain}.com/__access, enter the password, get a 24h hq-access JWT cookie scoped to .{your-domain}.com. |
| company | Internal/company-only share; user says "restricted to org", "internal-only", "company-only"; or config prefers org-restricted deploys. | Visitors sign in with HQ Cognito on hq.{your-domain}.com/__access; the HQ access service checks active membership in the app's company before minting a policy-versioned hq-access cookie. |
| selected | Specific HQ people/groups when the caller has resolvable HQ directory IDs. | Same Cognito flow as company, but only selected user/group IDs in the policy are accepted. Use only when IDs are known from the HQ directory, not from free-form names. |
| private | Legacy sensitive sharing for known recipients by email/domain when Cognito company membership is not the desired gate. | Visitors must be signed in to hq-auth (auth.{your-domain}.com) AND their email must be on the app's allowlist. Lands on hq.{your-domain}.com/__private, which checks the session + allowlist and mints the same hq-access JWT. |
Embedding a deployed app in another site
Public apps can be embedded in an iframe on another site, such as Notion. Apps with password, company, selected, or private access cannot be embedded. The browser does not send the hq-access cookie inside a third-party frame because it uses SameSite=Lax, so the frame shows the access page or fails. To share a gated app, send the link instead.
Pick company when the user asks for org/company/internal restriction. Pick private over password when the user gives concrete email/domain recipients ("share with [EMAIL] and the @example.com team") and did not ask for company-wide Cognito access. Pick password when sensitivity is detected but recipients are unspecified and config does not prefer org restriction.
Canonical mutation endpoint for switching between modes:
POST /api/apps/:id/access-mode {mode, password?}— atomic; clears the fields that don't belong to the chosen mode; wipes EmailGrant rows when leavingprivateso orphans can't silently re-activate on a future flip back.PUT /api/apps/:id/access-policy {mode, companyUid, users?, groups?, password?}— first-class policy endpoint forcompany,selected, and policy-versionedpassword. Use this for Cognito org gates.
Legacy path gotcha: PATCH /api/apps/:id {passwordProtected, password} is rejected with 409 ACCESS_MODE_CONFLICT when the app is currently in private mode. Always use /access-mode to change modes; reserve PATCH for in-mode password rotation.
Email allowlist CRUD (only relevant in private mode):
GET /api/apps/:id/allowed-emailsPOST /api/apps/:id/allowed-emails {email}— accepts an exact address ([EMAIL]) or a@domain.tldpattern; idempotent; lowercased server-side.DELETE /api/apps/:id/allowed-emails/{patternKey}—patternKeyURL-encoded.
Comments (opt-in) — --comments on|off: orthogonal to access mode. Turn it on when the user wants identity-verified commenting on the deploy: viewers drop a point pin, drag a box/region, or highlight a passage of text and comment on it, each tagged to who they are; the owner reads/resolves/deletes from a side pane, and a "Sign in to comment" Cognito prompt turns viewers into HQ users. It sets the per-app commentsEnabled flag, which the deploy pipeline reads to inject the comment widget at deploy time. Access controls still hold: on a gated deploy the thread is only readable/writable by viewers who pass the gate (the recorded owner can also read the in-page list with their own verified HQ sign-in), and access revocation applies to the comment surface too. After turning comments on, the skill offers to watch for new comments at an interval the user picks and tell them when one arrives (C.2.6). Turning comments on again while a watcher for that site is still running does not start a second one.
- Detect intent from the invocation:
--comments/--comments on(or "with comments", "turn comments on") → on;--comments off(or "turn comments off") → off; otherwise leave unset. - Wire it in Phase C once
appIdis known and beforePOST /api/deploys/:id/complete(see C.2.6):PATCH /api/apps/:id {commentsEnabled: true|false}. The widget is injected during…/complete, which reads the flag at that moment. - Off by default. Without the flag
commentsEnabledstays unset and the injector is a strict no-op — the served HTML is byte-identical to a pre-feature deploy (no widget markup, no script, no network calls). The flag takes effect on the next deploy's…/complete. - Static deploys only. Injection runs in the static
…/completepath.app(api/*) deploys and Next.js/Hono live deploys do not get the widget. The widget resolves the app from the page's origin on the platform domain, so comments work on the platform URL, not on a custom domain. Turning comments on pins the URL the API returns for the app to that platform host, so share the returned URL: it is{sub}.indigo-hq.comuntil the platform default moves tohq.work. - Turning comments off (
commentsEnabled: false) keeps every stored comment. The viewer-facing routes answer403 COMMENTS_DISABLED; a widget still present in already-served HTML removes itself on load, and a viewer's post is refused with "Comments are turned off for this page". The owner routes below keep working. Turning comments back on shows the same thread again.
Reading and answering comments as the owner (no browser needed). When the user asks to see, answer, or resolve comments on a deploy, use the owner routes. They take Authorization: Bearer $JWT plus X-Org-Slug (or X-HQ-Deploy-Scope: personal). Call them through the hq CLI: hq deploy comments list <app> (--company <slug>|--personal) --json reads them, hq deploy comments reply <app> (--company <slug>|--personal) --text-file <file> [--reply-to <commentId>|--anchor-json <json>] [--deploy-id <id>] adds one as the caller (unanchored by default; --reply-to copies that comment's anchor), and hq deploy comments resolve <app> <commentId> (--company <slug>|--personal) [--reopen] resolves or reopens one. They work on gated deploys, and work whether commentsEnabled is on or off. Only the app owner or an org admin can call them (others get 403 FORBIDDEN).
GET /api/apps/:id/manage/comments— every comment on the app. Returns{commentsEnabled, comments: [{id, body, author{email,name}, anchor, status, deployId, createdAt}]}.POST /api/apps/:id/manage/comments {body, anchor, deployId?}— add a comment as the caller. The author is always the verified caller; the body cannot set it.PATCH /api/apps/:id/manage/comments/:commentId {status: "resolved"|"open"}— resolve or reopen. Any otherstatus→400 COMMENT_STATUS_INVALID; unknown id →404 COMMENT_NOT_FOUND.- There is no owner-route delete. GET takes no filters; filter
status == "open"client-side. Rate limits are per IP: 60 reads/min, 10 writes/min (429 RATE_LIMITEDwithRetry-After).
POST body rules. body must be a non-empty string (else 400 COMMENT_BODY_REQUIRED). anchor is required and must be an object with a valid mode (else 400 COMMENT_ANCHOR_INVALID). Anchor shapes:
| mode | Fields | Use |
|---|---|---|
| unanchored | none | General reply or note not tied to a spot. Default for agent replies. |
| anchored | cssPath, xRatio, yRatio (0..1), optional viewportWidth, scrollY | Point pin. |
| region | as anchored, plus wRatio, hRatio | Dragged box. |
| text | quote (required, non-empty, ≤3000 UTF-16 units), prefix/suffix (optional, ≤64 each), optional cssPath of the starting block | Highlighted passage. Over-length or blank quote → COMMENT_ANCHOR_INVALID. |
To place a reply next to the comment it answers, copy that comment's anchor object verbatim.
Replies are flat. A comment has no parent/thread id; the API ignores any parentId. Quote or name what you are answering in body (for example Re: "tighten the headline" — done in the latest deploy.).
Author naming. The server sets the author; the body cannot. Name resolution for owner-route posts: the name this user already has on the app's comments (from a browser sign-in), else their email, else App owner / Org admin. Viewer comments carry the verified Cognito name and email; there are no anonymous comments.
Stale text highlights. On load the widget re-finds each text quote using its stored prefix/suffix. If the words were edited out, or the only matches have no agreeing context, the comment is not moved to another passage; it is listed in the side pane with a "Text changed" tag ("Hidden on page" when found but not visible). Point and box comments whose element is gone show a "context changed" state. Treat these as likely addressed, but confirm before resolving.
Review loop (on redeploy, or "what did reviewers say").
- Run
hq deploy comments list <app> (--company <slug>|--personal) --status open --json(<app>is the app id or exact name;hq deploy comments read <app> <commentId> --company <slug>prints one comment). - Group by anchor:
textbyquote, pins/boxes bycssPath,unanchoredseparately. NotedeployIdso you know which version each comment was left on. - Summarize for the user and make the fixes in the source.
- Redeploy through this skill.
- For each addressed comment, optionally add a short reply that quotes it with
hq deploy comments reply <app> ... --reply-to <commentId> --text-file <file>(or leave it unanchored), thenhq deploy comments resolve <app> <commentId> .... Write the reply text to a file so it never sits on a shell command line. Leave anything not addressed open and say which ones.
Do not use /api/apps/:id/comments for this. That route serves the in-page widget only: it needs the deploy's browser Origin plus the hq-access cookie from signing in on the page, and returns 403 COMMENT_ORIGIN_REQUIRED / COMMENT_ACCESS_REQUIRED to a CLI or agent. A 403 from it does not mean the owner can't read comments. hq deploy comments list calls the owner route for company apps and, with --personal, for personal apps. If the local repos/private/hq-deploy checkout lacks src/api/routes/comments-manage.ts, it is stale; read origin/main before concluding a capability doesn't exist.
Site events (opt-in) — --events on|off: lets a deployed page tell its owner that a visitor did something (pressed a button, made a wish, cast a vote) and show the owner's answer back on the page. The owner, or the owner's agent, reads the events, acts on them (often by changing the site and redeploying), and replies. This is how to build interactive, agent-run sites. The full recipe is under "Interactive sites (site events loop)" below.
- Detect intent:
--events/--events on, or a request for a site that "notifies me", "the agent answers", "visitors can ask/wish/vote and you respond" → on;--events off→ off; otherwise leave unset. - Wire it once
appIdis known (C.2.7):hq deploy events enable "$APP_ID" --company "$ORG_SLUG"(or--personal). Unlike comments, nothing is injected at deploy time; the page calls the API itself, so the flag takes effect at once. - Off by default. With
eventsEnabledunset or false,POST /site-eventsanswers403 EVENTS_DISABLEDand nothing is stored. Turning events off keeps stored events; the owner routes keep working. - Platform URL only. The API finds the app from the browser's
Originon the platform domain (https://{sub}.indigo-hq.comuntil the platform default moves tohq.work). Turning events on pins the app's public URL, as the API returns it, to the platform host, and the page must call the API from there. A custom domain will not work. - Access gates still apply. On a password, company, selected, or private deploy, every visitor route needs the visitor's
hq-accesscookie for that app (403 EVENT_ACCESS_REQUIREDotherwise), and the event records the verified viewer asactor. Public deploys record no actor.
Visitor routes (called by the page with fetch(..., {credentials: 'include'}); no app id, the Origin decides). $API is the deploy API base resolved in 1e; write that value into the page rather than assuming production:
POST $API/site-events {name, data?}→201 {id, name, status:"new", reply:null, createdAt}.name: 1–64 ofA-Za-z0-9_.:-, starting with a letter or digit.data: a JSON object, at most 2048 bytes. Writes are limited per IP (20 burst, then 20/min;429 RATE_LIMITEDwithRetry-After).GET /site-events/:eventId→ that event's{id, name, status, reply, repliedAt, createdAt}. Poll it every few seconds after a POST to show the reply.GET /site-events/replies→{events:[...]}, the 50 newest answered events, newest first. Public reads never returndataoractor.
Owner routes (same Authorization + X-Org-Slug headers as every Phase C call; owner or org admin only, else 403 FORBIDDEN). Use hq deploy events list|reply|watch, which wrap them:
GET /api/apps/:id/manage/events?after=&status=new|handled&limit=1..200→{eventsEnabled, events:[{id, name, data, actor, status, reply, repliedAt, handledBy, createdAt}], nextAfter}, oldest first. PassnextAfterback asafterto continue. Events younger than 10 seconds are held back so a cursor never skips a late write.PATCH /api/apps/:id/manage/events/:eventId {reply?, status?}→ a reply (1–4000 characters) marks the eventhandledand publishes the reply to the page.- Events and replies expire after 30 days.
Plan limits, domains, visit stats, receipts (reference).
- Deploy counts never block and have no plan caps. Deployment counts are unlimited on every plan, and deploy responses do not carry a deployment-count limit nag. Other resource limits may still appear in
planLimits. The presigned/api/deployspath used in C.2 does not attach plan limits. Current plan data comes from hq-pro; seecore/knowledge/public/hq-core/plans-and-pricing.md. - Custom domains. Any company on any plan can buy either domain add-on once it has a card on file. Prices are in the Domains row of
core/knowledge/public/hq-core/plans-and-pricing.md; do not quote prices from memory. People add and remove domains in the HQ desktop app; point users there rather than to the console. Agents can use the API below. Only a company owner or admin can add a paid domain (403 BILLING_ADMIN_REQUIREDotherwise). With no card on file the add answers402 PAYMENT_METHOD_REQUIREDwith abillingUrl: give the user that link, and retry the add after they confirm the card is added.503 BILLING_UNAVAILABLEis retryable. Comments and site events do not work on a custom domain (see above). - Per-app domain (standard).
GET|POST /api/apps/:id/domains {domain, environment?},PATCH|DELETE /api/apps/:id/domains/:domain,POST /api/apps/:id/domains/:domain/refresh; thehq-deployCLI wraps these ashq-deploy domains list|add|edit|refresh|remove(run in a directory linked withhq-deploy link). Only theproductionenvironment can have a custom domain (409 ENVIRONMENT_NOT_SERVEDotherwise). The add response lists the DNS records to create: a certificate validation CNAME and a CNAME for the domain. Runrefreshafter the records are in place, until the domain serves. A bare domain such asacme.comcannot take a CNAME at most DNS providers. The response then setsapex: trueand gives guidance: create an ALIAS or ANAME record (or use CNAME flattening) pointing at the given target, or usewww.acme.cominstead. Removing a domain stops its charge. If billing cannot be reached at that moment, the response saysbillingRemovalPending: trueand HQ keeps retrying; deleting the app also removes its domains and their charges. The standard tier keeps the "Built in HQ" badge. - Company base domain (premium).
GET|POST|DELETE /api/orgs/:orgSlug/base-domainandPOST /api/orgs/:orgSlug/base-domain/refresh. All of the company's deploys serve under{subdomain}.{base domain}. While the base domain is live, deploys carry no "Built in HQ" badge and keep their own favicon. Comment-widget branding is unchanged. - Visit stats.
GET /api/appsitems carrylastVisitAt(ISO ornull) andviews30d(null= analytics unavailable, not zero).GET /api/apps/:id/analyticsreturns a trailing 30-day dailyseriesandtotals. Counts come from a nightly CloudFront log rollup, so today's views appear the next day;lastVisitAtis written at the edge at most every 5 minutes per app and ignores bots. The console's Deployments page shows the same numbers. - Completion receipts. When a deploy goes live, hq-deploy sends a
deployment_completedreceipt and adeploy-succeededoutcome event to hq-pro on the deployer's behalf (best effort; a failure never fails the deploy). No action is needed from this skill.
Architecture: Three Phases, Inline Parallel Scripts
The engine is three phases, structured by data-dependency. Independent work runs in parallel via bash background jobs; I/O-heavy decisions live in inline scripts (no Task sub-agents — they cost 3–5s of spawn overhead each and the JWT/verdicts have to flow back to main anyway).
| Phase | What runs | Parallelism |
|-------|-----------|-------------|
| Step 1 | Preferences + exclusions (gate) | inline, sequential |
| Phase A | Framework detect + design pass (A.1.5, generated static only) → Build (inline) ‖ Identity (script) ‖ Sensitivity (script) | detect + design sync, then 3-way parallel via & + wait |
| Phase B | Localhost preview (inline-bg) ‖ Guardrails (script) | 2-way parallel via & + wait |
| Phase C | Password gen → reuse check (route mode) → upload → wire password → announce → present link | sequential, hard-gated |
Hard ordering constraints (preserved from core/policies/hq-deploy-reinforcement.md):
- Identity (Phase A) MUST complete before Upload (Phase C)
- Guardrails (Phase B) MUST gate Upload (Phase C)
- Upload (Phase C) returns
appIdwhich MUST exist before password persist + announce - The route-mode reuse check (C.2) MUST decide the target app before any app is created, and a merged route-mode tree MUST pass guardrails again before upload
- Localhost preview (Phase B) is NEVER gated by identity — always runs
- Design pass (A.1.5) MUST complete before Build/Guardrails package the artifact — it restyles the generated static source in place, so it runs synchronously right after framework detection and before the Phase A fan-out
Inline helper scripts (each is self-contained, returns one JSON line on stdout):
| Script | Purpose | Returns |
|--------|---------|---------|
| .claude/skills/deploy/scripts/identity-resolve.sh | Resolves Cognito JWT (cache → refresh → login); --force-refresh bypasses a rejected cache token; jq preferred, node via hook-lib.sh | {"status":"ok"\|"login_required"\|"missing_dependency",...} |
| .claude/skills/deploy/scripts/sensitivity-check.sh <path> [user_msg] | Classifies artifact sensitivity (filename-list grep, no content surfaces) | {"sensitive":bool,"trigger":string\|null} |
| .claude/skills/deploy/scripts/guardrails-check.sh <output_dir> | Caps + builds tarball | {"pass":bool,"reason":string\|null,"tarball_path":string,...} |
| .claude/skills/deploy/scripts/og-inject.sh <output_dir> [base_url] [app_name] [api_base] | Injects OG/Twitter preview tags; base_url is the app URL the API returned. With no page image, points og:image at hq-deploy's generated card (<api_base>/api/public/apps/<slug>/card.jpg, or https://api.<rest of the base_url host> when api_base is not given), using a blank _hq-og.png placeholder only when base_url is empty; also adds og:video pointing at a build og*.mp4 or hq-deploy's <api_base>/api/public/apps/<slug>/preview.mp4 (a recording of the page once a public app has one, else 404 so iMessage shows og:image; other apps always show og:image; gated apps never get a video); on pages that already have tags, rewrites a legacy card.png image URL to card.jpg in place and adds only the og:video block when the page has none | {"injected":int,"rewritten":int,"videoAdded":int,"image":string,"video":"api\|existing\|none","changed":bool} |
| .claude/skills/deploy/scripts/password-helper.sh | gen / announce / persist / lookup | password text, or persisted entry |
| .claude/skills/deploy/scripts/route-host.sh | hosts / merge / record: local snapshots of live static sites, so a new artifact can be added as a route on an existing app | one JSON line |
All scripts are deterministic, run in 0.3–0.5s, and never echo JWTs / artifact contents / matched PII.
Step 1 — Preferences and Exclusions
Auto-deploy is opt-out. Honor user preference and rule out projects that shouldn't deploy.
1a. Read user preference
$PREF_FILE is ~/.hq/deploy-prefs.json — a file owned exclusively by /deploy. The legacy ~/.hq/config.json is read-only here (backwards compat) and never written by this skill: that path is owned by the HQ Desktop App's strict HqConfig serde struct, and overlapping writers caused the HQ Desktop App to bail on every sync (see feedback_3ab4f113-2e7c-4e4e-a171-771b47a2b5fd).
PREF_FILE="$HOME/.hq/deploy-prefs.json"
LEGACY_PREF_FILE="$HOME/.hq/config.json"
# One-time migration: lift deploy-owned fields out of the legacy file so
# hq-sync can resume parsing ~/.hq/config.json as HqConfig. Read-only on the
# legacy path — never write back to it.
if [ ! -f "$PREF_FILE" ] && [ -f "$LEGACY_PREF_FILE" ]; then
LEGACY_DEFAULT=$(jq -r '.defaultOrg // empty' "$LEGACY_PREF_FILE" 2>/dev/null)
LEGACY_PREF=$(jq -r '.deploy.preference // empty' "$LEGACY_PREF_FILE" 2>/dev/null)
if [ -n "$LEGACY_DEFAULT" ] || [ -n "$LEGACY_PREF" ]; then
mkdir -p "$HOME/.hq"
jq -n --arg slug "$LEGACY_DEFAULT" --arg pref "$LEGACY_PREF" \
'{} | (if $slug != "" then .defaultOrg = $slug else . end)
| (if $pref != "" then .deploy.preference = $pref else . end)' \
> "$PREF_FILE"
fi
fi
if [ -f "$PREF_FILE" ]; then
DEPLOY_PREF=$(jq -r '.deploy.preference // "hq-deploy"' "$PREF_FILE" 2>/dev/null)
DEPLOY_ACCESS_SENSITIVE_DEFAULT=$(jq -r '.deploy.access.sensitiveDefault // "password"' "$PREF_FILE" 2>/dev/null)
DEPLOY_ACCESS_INTERNAL_DEFAULT=$(jq -r '.deploy.access.internalDefault // "company"' "$PREF_FILE" 2>/dev/null)
DEPLOY_ORG_RESTRICTED_BY_DEFAULT=$(jq -r '.deploy.access.orgRestrictedByDefault // false' "$PREF_FILE" 2>/dev/null)
else
DEPLOY_PREF="hq-deploy"
DEPLOY_ACCESS_SENSITIVE_DEFAULT="password"
DEPLOY_ACCESS_INTERNAL_DEFAULT="company"
DEPLOY_ORG_RESTRICTED_BY_DEFAULT="false"
fi
Valid values: hq-deploy (default), vercel, netlify, custom, none.
Access preference values:
.deploy.access.sensitiveDefault:password(default) orcompany.deploy.access.internalDefault:company(default).deploy.access.orgRestrictedByDefault:truemakes sensitive deploys company-restricted unless the user asks for public/password/email-recipient sharing
1b. Per-project override
if [ -f "prd.json" ]; then
PRD_DEPLOY=$(jq -r '.metadata.deploy // "unset"' prd.json 2>/dev/null)
if [ "$PRD_DEPLOY" = "false" ]; then DEPLOY_PREF="none"; fi
fi
1c. Honor the preference
hq-deploy→ continuevercel,netlify,custom→ silently stop (user has their own pipeline)none→ silently stop, skip even localhost preview
1d. Exclusions
- Vercel-managed:
manifest.yamlvercel_projects[]lists this project → skip - Backend service: Dockerfile / serverless.yml / sst.config.* at root → skip (Phase B guardrails will also catch these)
- Build is dirty: a recent test/typecheck failed → skip
1e. Resolve Context
| Thing | How |
|-------|-----|
| Deploy context | Company context via $ORG_SLUG, or explicit personal context when the signed-in user has no companies |
| API endpoint | $HQ_DEPLOY_API → manifest services.hq-deploy.endpoint → https://api.hq.work (always-on public default) — via resolve-deploy-api.sh |
| App name | package.json name → current directory name, slug-cased |
Resolve the deploy API base concretely, up front — this must produce a non-empty
$API or Phase C stalls on an empty upload host. The resolver applies the chain above
and always falls back to the public default, so a fresh install (no manifest, no
$HQ_DEPLOY_API) still deploys:
API="$(.claude/skills/deploy/scripts/resolve-deploy-api.sh)"
# $API is now guaranteed non-empty (public default https://api.hq.work when
# nothing else is configured). Every Phase C hq-deploy call uses "$API/api/...".
https://api.indigo-hq.com is the same API and keeps serving, so a manifest or
$HQ_DEPLOY_API that still names it, and older installs whose default it is,
keep working. Apps on the shared platform distribution serve on both
https://{sub}.hq.work and https://{sub}.indigo-hq.com, and old
indigo-hq.com links keep working. The link the skill prints is always the URL
the API returns, which stays on indigo-hq.com until the platform switch.
Org resolution chain
The org the deploy targets MUST be resolved — never fall back to a hardcoded slug. Walk these priorities in order until one produces $ORG_SLUG. Priorities 1–4 don't need a JWT and run here; Priority 5 needs $JWT and runs in A.5 after the Phase A barrier. When the signed-in user has no company at all, A.5 sets PERSONAL_SCOPE=true and the deploy ships to their personal scope (Priority 5b). Priority 6 is the state-aware CTA path, reached only when the org is genuinely ambiguous (multi-org) or vault is unreachable.
| Priority | Source | Notes |
|---|---|---|
| 1 | --org=<slug> arg or HQ_ORG env | Explicit one-off override |
| 2 | Agent-supplied via session context | Agent sets HQ_ORG before invoking when conversation clearly implies a company |
| 3 | cwd → companies/{slug}/… segment | Running inside HQ tree |
| 4 | ~/.hq/deploy-prefs.json defaultOrg field | Persisted choice (legacy ~/.hq/config.json read as fallback for backwards-compat) |
| 5 | Single active vault membership | Auto-resolved + auto-written to defaultOrg (runs in A.5) |
| 5b | No active membership → personal scope | Signed in but no company: deploy to the auto-provisioned personal-<sub> scope (PERSONAL_SCOPE=true, runs in A.5). Upload proceeds with X-HQ-Deploy-Scope: personal |
| 6 | State-aware CTA (multi-org / unreachable — see C.5) | Only when the org is genuinely ambiguous or vault is down; preview already shown; skip upload |
Pre-JWT block (Priorities 1–4):
ORG_SLUG="${HQ_ORG:-}"
# Priority 3: cwd → companies/{slug}/...
if [ -z "$ORG_SLUG" ]; then
PWD_REAL="$(pwd -P)"
HQ_ROOT=""
D="$PWD_REAL"
while [ "$D" != "/" ] && [ -n "$D" ]; do
if [ -f "$D/companies/manifest.yaml" ]; then HQ_ROOT="$D"; break; fi
D="$(dirname "$D")"
done
if [ -n "$HQ_ROOT" ]; then
REL="${PWD_REAL#$HQ_ROOT/companies/}"
if [ "$REL" != "$PWD_REAL" ]; then
CAND="${REL%%/*}"
# Reject non-company paths like _template or stray files
if [ -d "$HQ_ROOT/companies/$CAND" ] && [[ "$CAND" != _* ]]; then
ORG_SLUG="$CAND"
fi
fi
fi
fi
# Priority 4: ~/.hq/deploy-prefs.json defaultOrg (legacy ~/.hq/config.json read-only fallback)
if [ -z "$ORG_SLUG" ] && [ -f "$HOME/.hq/deploy-prefs.json" ]; then
ORG_SLUG=$(jq -r '.defaultOrg // empty' "$HOME/.hq/deploy-prefs.json" 2>/dev/null)
fi
if [ -z "$ORG_SLUG" ] && [ -f "$HOME/.hq/config.json" ]; then
ORG_SLUG=$(jq -r '.defaultOrg // empty' "$HOME/.hq/config.json" 2>/dev/null)
fi
Priorities 5 and 6 run in A.5 once $JWT is in scope.
1f. Writing a preference on request
When the user says "I use Vercel", "don't deploy my stuff":
mkdir -p "$HOME/.hq"
if [ -f "$PREF_FILE" ]; then
jq '.deploy.preference = "vercel"' "$PREF_FILE" > "$PREF_FILE.tmp" && mv "$PREF_FILE.tmp" "$PREF_FILE"
else
echo '{"deploy":{"preference":"vercel"}}' > "$PREF_FILE"
fi
Then say once:
Got it — I won't offer auto-deploy. You can change this in
~/.hq/deploy-prefs.json.
Phase A — Fan-out (3-way parallel)
After Step 1 resolves preferences, kick three workstreams off in the same shell command: Build inline, Identity script, Sensitivity script. Phase A completes when all three have returned.
A.1 — Framework detection (sync, fast)
# Skip rebuild if dist/index.html newer than newest source file
if [ -f "dist/index.html" ] || [ -f "out/index.html" ] || [ -f "build/client/index.html" ]; then
SKIP_BUILD=1
fi
# Detect framework + output dir + deploy type
if [ -f "next.config.js" ] || [ -f "next.config.mjs" ] || [ -f "next.config.ts" ]; then
FRAMEWORK="nextjs"; OUTPUT_DIR="out"; DEPLOY_TYPE="static"
elif [ -f "remix.config.js" ] || [ -f "remix.config.ts" ]; then
FRAMEWORK="remix"; OUTPUT_DIR="build/client"; DEPLOY_TYPE="ssr"
elif [ -f "astro.config.js" ] || [ -f "astro.config.mjs" ] || [ -f "astro.config.ts" ]; then
FRAMEWORK="astro"; OUTPUT_DIR="dist"; DEPLOY_TYPE="static"
elif [ -f "vite.config.js" ] || [ -f "vite.config.ts" ] || [ -f "vite.config.mjs" ]; then
FRAMEWORK="vite"; OUTPUT_DIR="dist"; DEPLOY_TYPE="static"
else
FRAMEWORK="static"; DEPLOY_TYPE="static"
for d in dist build out public .; do [ -f "$d/index.html" ] && OUTPUT_DIR="$d" && break; done
fi
# Backend API routes → upgrade to the `app` deploy type (per-app-function path).
# Orthogonal to the framework above: a root `api/` dir with >=1 handler file
# (api/**/*.{ts,js}) means the app ships backend routes, so it deploys as a
# static frontend PLUS an `api/*` per-app Lambda with keyless secret bindings —
# NOT Docker/ECR/ECS. Framework NAME is preserved (a Vite app with api/ stays
# framework=vite, type=app). No api/ dir (or empty) stays `static`. See the
# "App deploy type" section below and hq-deploy `src/deploy/function/`.
if [ "$DEPLOY_TYPE" != "ssr" ] && [ -n "$(find api -type f \( -name '*.ts' -o -name '*.js' \) 2>/dev/null | head -n1)" ]; then
DEPLOY_TYPE="app"
fi
# Next.js here means a static export (`output: 'export'` → out/). A Next.js 15
# app that needs a server (SSR, route handlers, middleware), or a Hono 4 app,
# is not a tarball deploy: hq-deploy runs those live through its own CLI
# (`hq-deploy link --org <slug>` once, then `hq-deploy deploy`; Next via the
# pinned OpenNext builder, Hono via the Fetch/Lambda adapter, production
# environment only). If the Next build produces no out/index.html, or the
# project depends on `hono`, hand off to that CLI instead of this tarball flow.
# Package manager
if [ -f "bun.lockb" ] || [ -f "bun.lock" ]; then PM="bun"
elif [ -f "pnpm-lock.yaml" ]; then PM="pnpm"
elif [ -f "yarn.lock" ]; then PM="yarn"
else PM="npm"; fi
A.1.5 — Design pass (generated single-page artifacts only)
Default ON — this is the deploy-quality default. A plain, HQ-generated report/deck/summary should never ship looking like an unstyled document. Before the artifact is packaged, lift a self-authored single-page HTML to on-brand quality using the hq-design house system. This runs synchronously here (right after framework detection, before the Phase A fan-out) so the restyled file is what Phase B guardrails tars and Phase C uploads.
Gate — decide whether to run it:
DESIGN_PASS=1
[ "$FRAMEWORK" != "static" ] && DESIGN_PASS=0 # framework builds (Next/Vite/Astro/Remix) own their design — never touch them
[ -f "$OUTPUT_DIR/DESIGN.md" ] && DESIGN_PASS=0 # artifact already declares its own design system
[ "$(jq -r '.deploy.designPass // "true"' "$HOME/.hq/deploy-prefs.json" 2>/dev/null)" = "false" ] && DESIGN_PASS=0 # user disabled globally
case "$LATEST_USER_MSG" in # explicit opt-out in the latest message
*as-is*|*"as is"*|*"no design"*|*"skip design"*|*"no restyle"*|*"don't restyle"*|*"dont restyle"*|*"leave the styling"*|*"keep the design"*|*"keep the styling"*) DESIGN_PASS=0 ;;
esac
Scope is deliberately narrow: only FRAMEWORK=static single-page artifacts (reports, decks, summaries, briefs that HQ generated). Framework builds and already-designed artifacts pass through untouched.
When DESIGN_PASS=1, apply the pass — this is design work you do inline, not a script: