diff --git a/app.js b/app.js
index 20d3ee5..30f5716 100644
--- a/app.js
+++ b/app.js
@@ -1,3 +1,6 @@
+import { createGenerationSessionClient } from './src/generationSession.js';
+import { createGenerationHistoryClient, recoverGenerationHistory } from './src/generationHistory.js';
+import { resolveGenerationHistoryEndpoint } from './src/generationHistoryConfig.js';
import posthog from "posthog-js";
import {
closeModal,
@@ -171,13 +174,13 @@ let subscriptionState = createSubscriptionState({ isResolved: true })
let sessionReadiness = Promise.resolve()
// --- PIPELINE ---
-const PIPELINE_ENDPOINT = `${BUILDSHIP_BASE_URL}/service/runpipeline`
+const PIPELINE_ENDPOINT = `${BUILDSHIP_BASE_URL}${import.meta.env.VITE_HISTORY_TARGET === 'staging' ? '/staging' : ''}/service/runpipeline`
// --- IDENTITY RESOLUTION ---
const IDENTITY_COOKIE_KEY = 'bs_identity'
const IDENTITY_SESSION_KEY = 'bs_user_id'
const IDENTITY_TOKEN_KEY = 'bs_identity_token'
-const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}/authUserCheck`
+const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}${import.meta.env.VITE_HISTORY_TARGET === 'staging' ? '/staging' : ''}/authUserCheck`
let identityState = {
userId: null,
@@ -186,6 +189,44 @@ let identityState = {
resolved: false,
}
+let identityEpoch = 0;
+// Obtain a fresh anonymous proof; persisted tokens may have expired or been claimed.
+let legacyIdentityToken = null;
+const generationSessionClient = createGenerationSessionClient({
+ endpoint: IDENTITY_ENDPOINT,
+ getSession: () => ({ token: authState.sessionToken, key: authState.isVerified ? authState.email : null }),
+ getLegacyToken: async () => {
+ if (!legacyIdentityToken) {
+ let timer;
+ try { await Promise.race([resolveIdentity(), new Promise(resolve => { timer = setTimeout(resolve, 5000); })]); }
+ finally { clearTimeout(timer); }
+ }
+ return legacyIdentityToken;
+ },
+});
+function resetGenerationIdentity() {
+ identityEpoch++;
+ legacyIdentityToken = null;
+ generationSessionClient.invalidate();
+ identityResolvePromise = null;
+ identityState = { userId: null, token: null, status: null, resolved: false };
+}
+async function ensureAccountGenerationIdentity({ reconcileUsage = true } = {}) {
+ const epoch = identityEpoch;
+ const token = authState.sessionToken;
+ const result = await generationSessionClient.ensure();
+ if (epoch !== identityEpoch || token !== authState.sessionToken || !authState.isVerified) {
+ throw new DOMException('Account session changed', 'AbortError');
+ }
+ identityState = { userId: result.userId, token: result.token, status: 'account', resolved: true };
+ if (reconcileUsage && result.usageCount !== undefined) {
+ const month = getCurrentYearMonth();
+ const count = !result.usageMonth || result.usageMonth === month ? result.usageCount : 0;
+ localStorage.setItem(USAGE_STORAGE_KEY, JSON.stringify({ count, month }));
+ updateUsageDisplay();
+ }
+}
+
// --- TIER LIMITS ---
// Single source of truth in src/plansSurface.js so the plans page, the
// paywall and generation gating agree (STU-382 criterion 1).
@@ -2199,6 +2240,7 @@ let pipelineState = {
};
function resetPipelineResults() {
+ document.getElementById("history-review-notice")?.remove();
pipelineState.step1Result = null;
pipelineState.step2Result = null;
pipelineState.step3Result = null;
@@ -4906,6 +4948,7 @@ async function runPromptArchitect(userInput, images = []) {
}
async function runCodeGenerator(masterPrompt, selectedModel, images = [], runId) {
+ const generationRunId = runId ?? pipelineState.runId;
const prompt = buildGeneratorPrompt(masterPrompt)
const context = createBuildShipContext("generator", pipelineState.bundleSpec)
try {
@@ -4920,6 +4963,10 @@ async function runCodeGenerator(masterPrompt, selectedModel, images = [], runId)
// A cancelled request is a stale run, not a model problem: it must not
// trigger a second request on the fallback model.
if (primaryError.isPipelineCancel) throw primaryError
+ if (!isCurrentPipelineRun(generationRunId)) {
+ primaryError.isPipelineCancel = true;
+ throw primaryError;
+ }
if (selectedModel !== FALLBACK_MODEL) {
console.warn(`Code Generator failed with ${selectedModel}, retrying with fallback model:`, primaryError.message)
// The fallback is a real service event, so the run says so while it
@@ -6083,6 +6130,14 @@ async function refreshSession(sessionToken) {
}
function saveSession(email, sessionToken) {
+ resetHistory();
+ if (authState.isVerified && authState.email !== email) {
+ invalidatePipelineRun();
+ abortPipelineRequests();
+ pipelineState.isRunning = false;
+ setRunPipelineButtonBusy(false);
+ }
+ resetGenerationIdentity();
const storedSession = getStoredSession()
const sessionChanged = (authState.email || storedSession.email) !== email
authState.email = email
@@ -6091,9 +6146,16 @@ function saveSession(email, sessionToken) {
subscriptionState = createSubscriptionState({ isLoading: true })
localStorage.setItem(AUTH_SESSION_STORAGE_KEY, JSON.stringify({ email, sessionToken }))
if (sessionChanged) clearSubscriptionCache()
+ void ensureAccountGenerationIdentity().catch(() => {});
}
function clearSession() {
+ resetHistory();
+ resetGenerationIdentity();
+ invalidatePipelineRun();
+ abortPipelineRequests();
+ pipelineState.isRunning = false;
+ setRunPipelineButtonBusy(false);
authState.email = null
authState.sessionToken = null
authState.isVerified = false
@@ -6258,6 +6320,12 @@ async function handleMagicLinkRequest() {
}
function handleSignOut() {
+ resetHistory();
+ resetGenerationIdentity();
+ invalidatePipelineRun();
+ abortPipelineRequests();
+ pipelineState.isRunning = false;
+ setRunPipelineButtonBusy(false);
// Reset in-memory auth/subscription state first so the immediate re-render
// below reflects a signed-out identity/plan.
authState.email = null
@@ -6368,6 +6436,7 @@ function getOrCreateCookieId() {
}
async function resolveIdentity() {
+ const epoch = identityEpoch;
try {
if (typeof FingerprintJS === 'undefined') {
console.warn('resolveIdentity: FingerprintJS not loaded, skipping')
@@ -6389,6 +6458,9 @@ async function resolveIdentity() {
}
const data = await response.json()
+ if (epoch !== identityEpoch) return;
+ legacyIdentityToken = data.identity_token || null;
+ if (authState.isVerified) return;
identityState.userId = data.user_id
identityState.token = data.identity_token || null
identityState.status = data.status
@@ -6415,6 +6487,7 @@ async function resolveIdentity() {
let identityResolvePromise = null
function ensureIdentityReady(maxWaitMs = 5000) {
+ if (authState.isVerified) return ensureAccountGenerationIdentity();
if (identityState.resolved) return Promise.resolve()
if (!identityResolvePromise) {
identityResolvePromise = resolveIdentity().catch((err) => {
@@ -7067,6 +7140,8 @@ function abortPipelineRequests() {
}
async function callBuildShip(step, model, prompt, context = {}, images = []) {
+ const requestRunId = pipelineState.runId;
+ const requestIdentityEpoch = identityEpoch;
const BUILDSHIP_TIMEOUT_MS = 120000
const controller = new AbortController()
activeBuildShipControllers.add(controller)
@@ -7077,15 +7152,21 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) {
}, BUILDSHIP_TIMEOUT_MS)
try {
+ // Stage token renewal must not overwrite the newer generator metering result.
+ if (authState.isVerified) await ensureAccountGenerationIdentity({ reconcileUsage: false });
+ if (!isCurrentPipelineRun(requestRunId) || requestIdentityEpoch !== identityEpoch || controller.signal.aborted) {
+ throw new DOMException("Pipeline session changed", "AbortError");
+ }
const res = await fetch(PIPELINE_ENDPOINT, {
method: 'POST',
+ credentials: 'omit',
headers: {
'Content-Type': 'application/json',
- ...(identityState.token ? { Authorization: `Bearer ${identityState.token}` } : {}),
},
signal: controller.signal,
body: JSON.stringify({
user_id: identityState.userId,
+ sessionToken: identityState.token,
request_id: pipelineState.requestId,
step,
model,
@@ -7099,6 +7180,10 @@ async function callBuildShip(step, model, prompt, context = {}, images = []) {
// instead of a JSON body. Parse defensively so we surface the raw body in
// the error rather than crashing on JSON.parse.
const rawText = await res.text()
+ // Abort may lose a race with response delivery; stale accounts cannot meter usage.
+ if (!isCurrentPipelineRun(requestRunId) || requestIdentityEpoch !== identityEpoch || controller.signal.aborted) {
+ throw new DOMException("Pipeline session changed", "AbortError");
+ }
let data = {}
try {
data = rawText ? JSON.parse(rawText) : {}
@@ -9489,6 +9574,10 @@ function showResultsView(codeContent, auditContent) {
const panel = document.getElementById("main-stage-container");
const from = currentSurfaceRect(panel);
const wasResults = document.body.classList.contains("results-fullscreen");
+ panel?.classList.add("visible");
+ document.getElementById("ready-state")?.classList.add("hidden");
+ const promptEl = document.getElementById("pipeline-submitted-prompt");
+ if (promptEl) promptEl.textContent = pipelineState.submittedPrompt || "";
cancelPipelineHideTimer();
document.getElementById("pipeline-progress")?.classList.remove("visible");
setGenerationStageVisible(true);
@@ -10106,3 +10195,144 @@ window.editPipelinePrompt = editPipelinePrompt;
window.retryPipelineRun = retryPipelineRun;
window.openCreditsModal = openCreditsModal;
window.closeCreditsModal = closeCreditsModal;
+
+// History requests use the application session, never a caller-supplied owner.
+const historyClient = createGenerationHistoryClient({
+ endpoint: resolveGenerationHistoryEndpoint({
+ target: import.meta.env.VITE_HISTORY_TARGET || 'production',
+ productionEndpoint: `${BUILDSHIP_BASE_URL}/service/generation-history`,
+ stagingEndpoint: `${BUILDSHIP_BASE_URL}/staging/service/generation-history`,
+ }),
+ getSession: () => ({ token: authState.sessionToken, key: authState.isVerified ? authState.email : null }),
+});
+let historyCursor = null;
+let historyEpoch = 0;
+let historyRecovery = null;
+let historyResultsBundle = null;
+const historyEl = id => document.getElementById(`history-${id}`);
+function resetHistory() {
+ if (historyResultsBundle && pipelineState.artifactBundle === historyResultsBundle) {
+ resetPipelineResults();
+ pipelineState.submittedPrompt = "";
+ document.getElementById("results-view")?.classList.remove("visible");
+ document.body.classList.remove("results-fullscreen", "results-with-sidebar");
+ document.getElementById("main-stage-container")?.classList.remove("visible");
+ const promptEl = document.getElementById("pipeline-submitted-prompt");
+ if (promptEl) promptEl.textContent = "";
+ setGenerationStageVisible(false);
+ }
+ historyResultsBundle = null;
+ historyEpoch++;
+ historyClient.invalidate();
+ historyCursor = null;
+ historyRecovery = null;
+ if (historyEl('panel')) historyEl('panel').setAttribute('aria-busy', 'false');
+ historyEl('list')?.replaceChildren();
+ historyEl('detail')?.replaceChildren();
+ if (historyEl('status')) historyEl('status').textContent = 'Refresh to load your saved generations.';
+ if (historyEl('next')) historyEl('next').disabled = true;
+}
+function historyButton(label, action) {
+ const button = document.createElement('button');
+ button.type = 'button'; button.className = 'btn-action ghost sm';
+ button.textContent = label; button.addEventListener('click', action);
+ return button;
+}
+async function historyTask(action) {
+ const epoch = ++historyEpoch;
+ historyClient.invalidate();
+ historyEl('status').textContent = 'Loading history…';
+ historyEl('panel').setAttribute('aria-busy', 'true');
+ try {
+ await ensureAccountGenerationIdentity();
+ if (epoch !== historyEpoch) return;
+ await action(() => epoch === historyEpoch);
+ }
+ catch (error) {
+ if (epoch === historyEpoch && error.name !== 'AbortError') historyEl('status').textContent =
+ error.status === 401 ? 'Session expired. Sign in again, then refresh.' :
+ error.status === 404 ? 'This entry is no longer available. Refresh the list.' : 'History could not be loaded or changed. Try again.';
+ } finally { if (epoch === historyEpoch) historyEl('panel').setAttribute('aria-busy', 'false'); }
+}
+function loadHistory(next = false) {
+ historyRecovery = null;
+ const cursor = next ? historyCursor : null;
+ return historyTask(async current => {
+ const page = await historyClient.list(cursor ? { cursor } : {});
+ if (!current()) return;
+ historyCursor = page.nextCursor;
+ historyEl('list').replaceChildren(); historyEl('detail').replaceChildren();
+ historyEl('next').disabled = !historyCursor;
+ historyEl('status').textContent = page.items.length ? 'Saved generations' :
+ historyCursor ? 'No entries on this page. Continue to the next page.' : 'No saved generations on this page.';
+ for (const item of page.items) {
+ if (!item || typeof item.id !== 'string' || !item.id || item.id.includes('/')) continue;
+ const row = document.createElement('li');
+ row.append(historyButton(item.id, () => openHistory(item.id)));
+ const status = document.createElement('span');
+ status.textContent = ` — ${typeof item.status === 'string' ? item.status : 'Status unknown'}`;
+ row.append(status); historyEl('list').append(row);
+ }
+ });
+}
+function openHistory(id) {
+ if (pipelineState.isRunning) { historyEl('status').textContent = 'Wait for generation to finish before opening history.'; return; }
+ historyRecovery = null;
+ historyEl('detail').replaceChildren();
+ return historyTask(async current => {
+ const detail = await historyClient.detail(id);
+ if (!current()) return;
+ if (detail.generation.id !== id) throw new Error('Mismatched history detail');
+ const recovered = recoverGenerationHistory(detail);
+ historyRecovery = recovered;
+ const panel = historyEl('detail'); panel.replaceChildren();
+ const message = document.createElement('p');
+ message.textContent = recovered.artifactBundle ?
+ recovered.reviewAvailable ? 'Stored artifacts and review available.' : 'Review unavailable. Recovered code has not acquired review approval.' :
+ 'Replay unavailable: this record is incomplete or cannot be validated. Available text is shown below.';
+ panel.append(message);
+ for (const [name, stage] of Object.entries(recovered.stages)) {
+ for (const field of ['input_text', 'output_text']) {
+ if (typeof stage?.[field] !== 'string') continue;
+ const section = document.createElement('details'); const title = document.createElement('summary');
+ title.textContent = `${name} ${field}`; const pre = document.createElement('pre');
+ pre.style.whiteSpace = 'pre-wrap'; pre.textContent = stage[field]; section.append(title, pre); panel.append(section);
+ }
+ }
+ if (recovered.artifactBundle) panel.append(historyButton('Open in Results', () => {
+ if (pipelineState.isRunning) { historyEl('status').textContent = 'Wait for generation to finish before opening history.'; return; }
+ if (historyRecovery !== recovered || !authState.isVerified) return;
+ resetPipelineResults();
+ Object.assign(pipelineState, { artifactBundle: recovered.artifactBundle, bundleSpec: recovered.bundleSpec,
+ step1Result: recovered.bundleSpec ? JSON.stringify(recovered.bundleSpec) : null,
+ step2Result: JSON.stringify(recovered.artifactBundle), step3Result: recovered.review ? JSON.stringify(recovered.review) : null,
+ bundleReview: recovered.bundleReview, submittedPrompt: recovered.originalPrompt || '', submittedImages: [],
+ selectedArtifactId: recovered.artifactBundle.artifacts[0].id, requestId: id });
+ historyResultsBundle = recovered.artifactBundle;
+ // The adapter merges stored review by validated artifact ID and preserves original code.
+ switchView('home');
+ showResultsView(getSelectedArtifactCode(), recovered.reviewAvailable ? renderMarkdownAudit(pipelineState.step3Result) : '
Review unavailable for this saved generation.
');
+ if (!recovered.reviewAvailable) {
+ const notice = document.createElement('p'); notice.id = 'history-review-notice'; notice.setAttribute('role', 'status');
+ notice.textContent = 'Review unavailable for this saved generation. Existing deployment checks still apply.';
+ document.getElementById('results-view')?.prepend(notice);
+ }
+ }));
+ panel.append(historyButton('Delete this generation', () => {
+ const confirm = document.createElement('div'); confirm.setAttribute('role', 'group'); confirm.setAttribute('aria-label', 'Confirm deletion');
+ const warning = document.createElement('p'); warning.textContent = 'Delete this generation permanently? Generation content will be removed; an internal marker prevents late writes from restoring it.';
+ confirm.append(warning, historyButton('Cancel', () => confirm.remove()), historyButton('Confirm delete', () => historyTask(async current => {
+ await historyClient.delete(id); if (!current()) return;
+ historyRecovery = null; panel.replaceChildren(); historyEl('status').textContent = 'Generation deleted. Refresh to update the list.';
+ })));
+ panel.append(confirm);
+ }));
+ historyEl('status').textContent = 'Generation details loaded.';
+ });
+}
+historyEl('refresh').addEventListener('click', () => loadHistory());
+historyEl('next').addEventListener('click', () => loadHistory(true));
+
+if (import.meta.env.DEV) {
+ window.__CCC_HISTORY_TEST__ = { session: saveSession, pending: value => { pipelineState.isRunning = value; }, state: () => pipelineState };
+}
diff --git a/docs/design/BEHAVIOR-OVERRIDES.md b/docs/design/BEHAVIOR-OVERRIDES.md
index c14ce7e..866c0d7 100644
--- a/docs/design/BEHAVIOR-OVERRIDES.md
+++ b/docs/design/BEHAVIOR-OVERRIDES.md
@@ -47,7 +47,7 @@ The handoff shows several demo-only concepts. Production must not fabricate them
| Purchases inside the hero modal | Pricing modal links to Stripe checkout / portal via existing `startCheckout` / `openCustomerPortal`. |
| Connection success animations | Show real connection status; use loading, error, and retry states. |
| Usage breakdown by day/category | Show only the data the backend returns (`used / limit` and current period). |
-| Generation history table | Do not add a history table unless the backend endpoint exists and is enabled. |
+| Generation history table | Owner-scoped history is implemented under STU-930–933; runtime availability requires the configured authenticated endpoint. See [acceptance boundaries](../generation-history-acceptance.md). |
| Account deletion flow | Do not add account deletion; if unavailable, omit the control or show a disabled / support message. |
## 5. Other production rules
@@ -55,3 +55,9 @@ The handoff shows several demo-only concepts. Production must not fabricate them
- Keep the brand logomark inline (SVG), not as an external image request.
- Preserve the real copy and labels from the export, but replace any static placeholders with live data equivalents listed above.
- Do not add OpenDesign chrome, preview labels, or design-process annotations to the production UI.
+
+## Generation history (STU-933)
+
+List existing records, including incomplete ones, without new retention or tier restrictions. Empty pages may have continuation cursors. Open restores available artifacts into Results without generation, billing or deployment; Deploy remains a separate explicit action with existing safety gates. Prefer complete generator output, otherwise validated nontruncated review-input generatedBundle. Missing review remains unavailable; generator code never implies reviewer approval. Stored fixedCode merges by artifact identity. Preserve safe raw text for partial records.
+
+Logout/account changes invalidate pending requests and clear history; opening history prevents late generation responses replacing the selection. Delete removes generation content, retaining only an internal owner-bound anti-resurrection marker. Foreign, absent and deleted records share 404. Source acceptance does not establish live endpoint availability.
diff --git a/docs/design/TRACEABILITY.md b/docs/design/TRACEABILITY.md
index 255f733..f563247 100644
--- a/docs/design/TRACEABILITY.md
+++ b/docs/design/TRACEABILITY.md
@@ -21,7 +21,9 @@
| No fabricated purchases | Hero plan/billing dialogs | Stripe checkout/portal only | Use existing `startCheckout` / `openCustomerPortal`. |
| No fabricated connection success | Journey / account connection card | Real connection states only | |
| No usage breakdown | Account usage card | Show `used / limit` only | |
-| No generation history | Account history table | Omit unless backend endpoint exists | |
+| Owner-scoped generation history (STU-930–933) | Approved generation-history plan | Account list/detail/delete and Results hydration | [Source and delivery boundaries](../generation-history-acceptance.md). |
| No account deletion | Account security section | Omit or show support message | |
| Nine handoff viewports with reflow expectations | `DESIGN-HANDOFF.md` + manifest | Responsive tests | See [RESPONSIVE.md](./RESPONSIVE.md). |
| Fixed 1920×1080 fit scaling is presentation-only | `custom-code-connect-hero.html` `.stage` | Real fluid layout | See [RESPONSIVE.md](./RESPONSIVE.md). |
+| Staging FTP isolation (STU-933) | Approved exact ownership amendment | scripts/deploy_ftp.py --target staging | Local mocked guard proof only. |
+| Actual staging acceptance (STU-934) | Post-PR delivery gate | Provider routes, auth/CORS, indexes, two-account isolation, FlutterFlow redeploy | Outstanding; requires actual isolated infrastructure. |
diff --git a/docs/generation-history-acceptance.md b/docs/generation-history-acceptance.md
new file mode 100644
index 0000000..a08a580
--- /dev/null
+++ b/docs/generation-history-acceptance.md
@@ -0,0 +1,29 @@
+# Generation history source acceptance — STU-933
+
+Candidate starts at frontend c6a7ef1ee5c4219a1fdef9928812f36a2b031a49, in `/Users/home/.t3/worktrees/dreamflowCommandForFlutterFlow/t3-3d283578-bd96247123bf8c0a`. Common Git directory verified as `/Users/home/Projects/dreamflowCommandForFlutterFlow/.git`. The commit containing this document identifies the complete handoff candidate; controller acceptance remains separate.
+
+Backend source evidence is historical and separate from live readiness. [PR 194](https://github.com/sgardoll/buildship/pull/194) merged externally at `00d89badea64a62f8365d9728776d896e0e7bd04`; PR 195 was subsequently reported merged. Source schema repair `4989e9c2ac48030c4ad726047e756f17b293c652` in PR 196 had passing checks, but PR 196 closed unmerged. A later live export renamed the production workflow to `service-generation-history-6f54`, upgraded REST to 2.0.2, and dropped allowedOrigins and response-body mappings. The proposed reconciliation in PR 197 is superseded by Stuart's report that he completed the repair manually and is closing that PR. Neither PR 196 nor PR 197 merge is a prerequisite now. Preserve owner changes and refresh live state before any further backend edit.
+
+The independent frontend review checked the API source at `4989e9c2` against `00d89bad` and found compatible request/response envelopes. This does not verify the manually edited hosted workflow. Hosted editor, HTTP/CORS and two-account staging acceptance remain unproven under STU-934. Expected response mappings are handler.body and HTTP status handler.status; the canonical frontend origin is https://customcode.connectio.com.au.
+
+## Account authentication correction
+
+The earlier compatibility review missed that real sign-in sessions contain email rather than user_id. Its authentication conclusion is withdrawn. See [account identity repair](generation-history-account-auth.md) for the coordinated `/authUserCheck` bootstrap and session lifecycle. Backend repair and current-head acceptance are required before readiness; historical tests below do not prove live account ownership.
+
+## Contract checked against accepted source
+
+Read-only source: `/Users/home/Projects/buildship/workflows/service-generation-history-Hst1/nodes/history-api/main.ts`, plus workflow `triggers.json`. The worker compared these API files at the earlier accepted source. Subsequent backend fallback/schema changes require final controller pairing verification; the endpoint envelope is reported unchanged. Compared with `src/generationHistory.js`, its synthetic unit fixtures, and `e2e/generation-history.spec.js`.
+
+POST `/service/generation-history` (staging `/staging/service/generation-history`) uses bearer application session authentication. Bodies contain action plus optional cursor or id, never owner. List returns `{items,nextCursor}`, at most 20 items scanned within 100 documents; empty continuation pages are valid. Detail returns `{generation,identityMismatch}` with whitelisted stage text, character counts, truncation and finish reason. Delete returns `{deleted:true,id}`; repeat deletion returns 404. Errors use `{error:{code,message}}`; absent, foreign and tombstoned records share NOT_FOUND. Timestamps are seconds/nanoseconds objects or null. Backend rejects extra fields, invalid IDs and invalid signed cursors. Frontend validation is deliberately less restrictive (8192 cursor characters versus backend 6000, character versus byte ID limit); backend validation remains authoritative and normal returned cursors/IDs are compatible. Mock fixtures are synthetic partial response subsets, not captures of live service traffic.
+
+## Staging FTP guard
+
+Use the existing script with `--target staging`. Export all five `STAGING_FTP_HOSTNAME`, `STAGING_FTP_PORT`, `STAGING_FTP_USERNAME`, `STAGING_FTP_PASSWORD`, `STAGING_FTP_HOME_PATH` settings through a secure shell environment. The script does not read .env automatically. No production password/Keychain fallback is allowed. A separate account and explicit absolute non-root path are mandatory; bare web roots, traversal and control characters are rejected. Every managed remote directory must already exist and report its expected absolute PWD before upload/prune. Provider aliases and directory provisioning must be resolved during STU-934. Local symlinks, remote symlinks in managed directories, failed directory listings and unsafe remote file names are rejected. Dry-run does not mkdir, upload or delete, but does connect/read remote metadata when actually invoked. No FTP invocation was made for this task.
+
+Default production target retains existing host/account/password resolution and reproducibility/build guards. Remote listing safety applies to both targets. FTP server PWD behavior and real account confinement still require provider verification; local guards cannot prove server-side isolation or distinguish undisclosed production aliases.
+
+## Evidence and remaining delivery gate
+
+Local evidence directory: `/tmp/stu933-evidence/` (ephemeral machine-local logs). `backend-source.txt` and `backend-contract.txt` retain the source examined; `node.txt`, `ci.log`, command logs and `results.txt` record local verification. No secrets or customer exports were used.
+
+`staging-acceptance` means **local configuration/isolation guard proof only**. STU-934 remains outstanding: actual staging host/certificate/root isolation, deployed routes and result bindings, CORS and session-verifier compatibility, staging collection/index queries, synthetic two-account list/detail/delete, and real explicit FlutterFlow redeploy. No production data was copied/deleted and no provider deployment occurred in frontend source verification. Frontend PR 131 was subsequently created after independent acceptance at d9a4045; later review repairs require their own current-head checks. Recovered worker logs show 428 unit tests, 283 browser tests, build, seven accessibility shells, nine deployment checks, thirty proxy cases, bundle scan and fourteen staging checks passed on Node 22.15.1. Controller added malformed-listing rejection and post-preflight pruning failure propagation; all sixteen staging tests pass.
diff --git a/docs/generation-history-account-auth.md b/docs/generation-history-account-auth.md
new file mode 100644
index 0000000..0f63678
--- /dev/null
+++ b/docs/generation-history-account-auth.md
@@ -0,0 +1,13 @@
+# Account identity repair
+
+The original history implementation confused an email app-session JWT with a pipeline identity JWT. A live email session was rejected by the history verifier. Earlier synthetic-token source acceptance does not prove this integration.
+
+The frontend now calls the existing POST `/authUserCheck` (staging `/staging/authUserCheck`) with JSON `{sessionToken, identityToken?}`. The session token is the verified sign-in session; the optional identity token is fresh legacy proof obtained from the anonymous resolver, never a submitted owner ID. No Authorization header is required by this resolver contract. The backend owns signature verification and immutable account-to-identity association. It reuses an established account marker; first linkage may adopt only a proven unclaimed/same-account legacy identity, and foreign proof produces a distinct account identity without exposing foreign history.
+
+The resolver returns `{user_id, identity_token, ...}`. The frontend retains the account credentials only in memory and refreshes them before signed-in pipeline calls, including retries/refinements. The backend caps their expiry at the app session expiry. History list/detail/delete send the email app session as JSON `sessionToken` and are sent only after account bootstrap succeeds. Pipeline requests send the scoped account (or signed-out anonymous) identity token as JSON `sessionToken`. Neither request sends Authorization; both use `credentials: omit`. Account bootstrap is unchanged. History never authenticates using the device token. Staging resolver, history and pipeline routes all use `/staging/` and require the backend's isolated collection bindings.
+
+Sign-in/session rotation and sign-out invalidate pending account resolutions. Account changes also cancel an active generation. Late anonymous or account responses cannot replace the current account's identity. Bridge failure blocks signed-in generation/history rather than falling back to anonymous access. Anonymous generation keeps its existing resolver path; the backend must refuse anonymous capabilities for an identity already claimed by an account.
+
+Evidence is synthetic and local: unit tests exercise real email-session-shaped request semantics, owner-field omission, delayed response rejection, logout, malformed responses and retry. Browser tests check email-vs-generation token separation, account A→B switching during a delayed bridge, and fail-closed behavior. Full-suite and independent-review results are recorded with the PR head. Backend source/emulator acceptance, deployment, CORS, real authenticated reads, two-account isolation and editor retest remain separate; no live writes or deployment are authorized by these tests. Preserve Stuart's manual backend workflow changes.
+
+Body-token transition (owner authorized): backend may accept legacy headers but must reject conflicting body/header credentials. JSON Content-Type still triggers a preflight; removing Authorization reduces the requested headers to content-type with credentials omitted. A local cross-origin browser probe observed OPTIONS requesting only content-type and a successful POST with no Authorization/cookies. Production/staging invalid-token list probes returned readable401; these are not valid-session acceptance. The preview browser also allowed the Authorization negative control, so this harness does not establish strict browser CORS enforcement; deployed ordinary-browser acceptance remains required. No valid bootstrap, generation or deletion was performed.
diff --git a/e2e/fixtures/apiFixtures.js b/e2e/fixtures/apiFixtures.js
index 0047d92..5c21b5f 100644
--- a/e2e/fixtures/apiFixtures.js
+++ b/e2e/fixtures/apiFixtures.js
@@ -496,7 +496,9 @@ const VENDORED_SRI_ASSETS = [
*/
export async function applyDefaultRoutes(page, overrides = {}) {
const routes = {
- [ENDPOINTS.identity]: guestIdentity(),
+ [ENDPOINTS.identity]: request => request.postDataJSON()?.sessionToken
+ ? ok({user_id:"account-test-0001",identity_token:"synthetic-account-generation-token",status:"recognized"})
+ : guestIdentity(),
[ENDPOINTS.authSendMagicLink]: magicLinkSent(),
[ENDPOINTS.authVerifyMagicLink]: signedInSession(),
[ENDPOINTS.authRefreshSession]: signedInSession(),
diff --git a/e2e/generation-history.spec.js b/e2e/generation-history.spec.js
new file mode 100644
index 0000000..f842570
--- /dev/null
+++ b/e2e/generation-history.spec.js
@@ -0,0 +1,200 @@
+import { test, expect } from '@playwright/test';
+import { applyDefaultRoutes, ENDPOINTS } from './fixtures/apiFixtures.js';
+test('history bounded pagination, safe detail and selected deletion', async ({ page }) => {
+ await page.addInitScript(() => {
+ localStorage.setItem('hasSeenWalkthrough', 'true');
+ localStorage.setItem('ccc_auth_session', JSON.stringify({email:'test@example.com',sessionToken:'synthetic'}));
+ });
+ await applyDefaultRoutes(page, { [ENDPOINTS.authRefreshSession]: {status:200,contentType:'application/json',body:JSON.stringify({email:'test@example.com',sessionToken:'synthetic'})} });
+ const calls=[]; let deleteFailed = false;
+ await page.route('**/service/generation-history', route => {
+ const body=route.request().postDataJSON(); calls.push(body);
+ expect(route.request().headers().authorization).toBeUndefined();expect(route.request().postDataJSON().sessionToken).toBe('synthetic');
+ expect(body.user_id).toBeUndefined();
+ if (body.action === 'delete' && !deleteFailed) { deleteFailed = true; return route.fulfill({status:500,json:{error:{code:'INTERNAL_ERROR'}}}); }
+ const data=body.action==='list' ? body.cursor ? {items:[{id:'entry',status:'
Generation history
- not saved
+ Saved generations
-
-
Saved history isn't available yet.
-
Per-run records aren't persisted, so there is no past list to show. Your current result stays open in the generation workspace.
+
+
Refresh to load your saved generations.
+
+
+
+
diff --git a/scripts/deploy_ftp.py b/scripts/deploy_ftp.py
index ed659fe..dd08cbb 100755
--- a/scripts/deploy_ftp.py
+++ b/scripts/deploy_ftp.py
@@ -66,6 +66,52 @@ def resolve_password():
)
+def staging_config():
+ """Resolve staging only from explicit environment; never consult Keychain."""
+ keys = ('HOSTNAME', 'PORT', 'USERNAME', 'PASSWORD', 'HOME_PATH')
+ values = {key: os.environ.get('STAGING_FTP_' + key, '') for key in keys}
+ if any(not value.strip() for value in values.values()):
+ sys.exit('Staging requires all STAGING_FTP_* settings, including HOME_PATH.')
+ root = values['HOME_PATH']
+ parts = root.split('/')[1:]
+ if (not root.startswith('/') or not parts or
+ any(not part or part in ('.', '..') for part in parts) or
+ any(c in root for c in ('\\', '\r', '\n', '\x00')) or
+ root.lower() in ('/public_html', '/www', '/htdocs')):
+ sys.exit('Staging requires an explicit non-root isolated absolute HOME_PATH.')
+ if values['USERNAME'].casefold() == USER.casefold():
+ sys.exit('Staging must use a separate FTP account.')
+ if any(c in values['HOSTNAME'] + values['USERNAME'] for c in ('\r', '\n', '\x00')):
+ sys.exit('Invalid staging connection settings.')
+ try:
+ port = int(values['PORT'])
+ if not 1 <= port <= 65535:
+ raise ValueError()
+ except ValueError:
+ sys.exit('Invalid STAGING_FTP_PORT.')
+ return values['HOSTNAME'], port, values['USERNAME'], values['PASSWORD'], root
+
+
+def enter_staging_root(ftp, root, local_dirs):
+ """Fail closed on aliases/symlinked managed directories before any writes."""
+ ftp.cwd(root)
+ if ftp.pwd() != root:
+ sys.exit('Staging root does not resolve to the configured absolute path.')
+ for rel in sorted(local_dirs - {''}):
+ path = root + '/' + rel
+ try:
+ ftp.cwd(path)
+ except ftplib.error_perm as error:
+ if not str(error).startswith('550'):
+ raise
+ sys.exit('Staging managed directories must exist and be verifiable before deployment.')
+ if ftp.pwd() != path:
+ sys.exit('Staging managed directory resolves outside its expected path.')
+ ftp.cwd(root)
+ for rel in sorted(local_dirs):
+ list_remote_dir(ftp, rel, strict=True)
+
+
def local_files_and_dirs(root):
"""Returns (relative file paths, relative dir paths including "") under root."""
files = set()
@@ -101,7 +147,8 @@ def upload_all(ftp, local_files, dry_run):
failed = []
for rel in sorted(local_files):
- ensure_remote_dir(ftp, os.path.dirname(rel), made_dirs)
+ if not dry_run:
+ ensure_remote_dir(ftp, os.path.dirname(rel), made_dirs)
local_path = DIST / rel
size = local_path.stat().st_size
@@ -121,28 +168,39 @@ def upload_all(ftp, local_files, dry_run):
return uploaded, failed
-def list_remote_dir(ftp, rel_dir):
+def list_remote_dir(ftp, rel_dir, strict=False):
"""Returns [(name, is_dir), ...] for one directory, or [] if it doesn't exist."""
entries = []
lines = []
try:
ftp.retrlines(f"LIST {rel_dir}" if rel_dir else "LIST", lines.append)
except ftplib.all_errors:
+ if strict:
+ sys.exit("Cannot inspect staging directory; refusing deployment.")
return entries
for line in lines:
parts = line.split(None, 8)
if len(parts) < 9:
+ if strict:
+ sys.exit("Unrecognized staging directory listing; refusing deployment.")
continue
name = parts[8]
if name in (".", ".."):
continue
+ if '/' in name or "\\" in name or any(ord(c) < 32 for c in name):
+ sys.exit('Unsafe remote listing entry; refusing to prune.')
+ # Never follow or delete symlinks advertised by LIST.
+ if parts[0].startswith('l'):
+ if strict:
+ sys.exit('Staging managed directory contains a symlink.')
+ continue
entries.append((name, parts[0].startswith("d")))
return entries
-def prune_stale_files(ftp, local_files, local_dirs, dry_run):
+def prune_stale_files(ftp, local_files, local_dirs, dry_run, strict=False):
"""Deletes remote files not present locally, scoped to directories dist
manages. A remote directory with no local counterpart is never listed, so
it is never touched."""
@@ -150,7 +208,7 @@ def prune_stale_files(ftp, local_files, local_dirs, dry_run):
failed = []
for rel_dir in sorted(local_dirs):
- for name, is_dir in list_remote_dir(ftp, rel_dir):
+ for name, is_dir in list_remote_dir(ftp, rel_dir, strict=strict):
if is_dir:
continue # only prune files; subdirectories are handled by their own entry in local_dirs
rel = f"{rel_dir}/{name}" if rel_dir else name
@@ -298,7 +356,9 @@ def main():
"--allow-dirty", action="store_true",
help="Allow deploying an uncommitted dist/ (not recommended)",
)
+ parser.add_argument("--target", choices=("production", "staging"), default="production")
args = parser.parse_args()
+ staging = staging_config() if args.target == "staging" else None
if not DIST.is_dir():
sys.exit(f"{DIST} does not exist. Run `npm run build` first.")
@@ -310,18 +370,27 @@ def main():
if not local_files:
sys.exit(f"{DIST} has no files to deploy.")
- password = resolve_password()
+ if staging:
+ host, port, user, password, root = staging
+ if any('\\' in rel or any(ord(c) < 32 for c in rel) for rel in local_files | local_dirs):
+ sys.exit('Unsafe staging artifact path.')
+ if any(path.is_symlink() for path in DIST.rglob('*')):
+ sys.exit('Staging dist must not contain symlinks.')
+ else:
+ host, port, user, password = HOST, PORT, USER, resolve_password()
ftp = ftplib.FTP()
- ftp.connect(HOST, PORT, timeout=120)
- ftp.login(USER, password)
- print(f"connected to {HOST} as {USER}" + (" (dry run)" if args.dry_run else ""))
+ ftp.connect(host, port, timeout=120)
+ ftp.login(user, password)
+ if staging:
+ enter_staging_root(ftp, root, local_dirs)
+ print(f"connected to {args.target}" + (" (dry run)" if args.dry_run else ""))
print("\n-- upload --")
uploaded, upload_failed = upload_all(ftp, local_files, args.dry_run)
print("\n-- prune stale files --")
- removed, prune_failed = prune_stale_files(ftp, local_files, local_dirs, args.dry_run)
+ removed, prune_failed = prune_stale_files(ftp, local_files, local_dirs, args.dry_run, strict=bool(staging))
ftp.quit()
diff --git a/scripts/test-deploy-guard.py b/scripts/test-deploy-guard.py
index 6fb0cf8..c7c0f33 100644
--- a/scripts/test-deploy-guard.py
+++ b/scripts/test-deploy-guard.py
@@ -50,6 +50,11 @@ def expected_absent_bundles(deploy, html):
def main():
deploy = load_deploy_module()
+ # Production password precedence remains unchanged; no Keychain access.
+ from unittest.mock import patch
+ with patch.dict(deploy.os.environ, {'FTP_PASSWORD': 'synthetic-production'}), patch.object(deploy.subprocess, 'run', side_effect=AssertionError('unexpected Keychain')):
+ assert deploy.resolve_password() == 'synthetic-production'
+
built_html = (deploy.DIST / "index.html").read_text(encoding="utf-8")
absent_html = built_html.replace("assets/index-", "assets/index-absent-")
diff --git a/scripts/test-staging-deploy.py b/scripts/test-staging-deploy.py
new file mode 100644
index 0000000..9e90c1a
--- /dev/null
+++ b/scripts/test-staging-deploy.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Local mocked staging isolation proof; never connects to FTP."""
+import importlib.util
+import os
+import unittest
+from unittest.mock import Mock, patch
+from pathlib import Path
+spec = importlib.util.spec_from_file_location('deploy', Path(__file__).with_name('deploy_ftp.py'))
+d = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(d)
+ENV = dict(zip(('STAGING_FTP_' + k for k in ('HOSTNAME','PORT','USERNAME','PASSWORD','HOME_PATH')), ('staging.example.test','21','stage-user','synthetic-password','/staging')))
+
+class StagingTests(unittest.TestCase):
+ def test_explicit_settings(self):
+ with patch.dict(os.environ, ENV, clear=True), patch.object(d, 'resolve_password', side_effect=AssertionError):
+ self.assertEqual(d.staging_config(), ('staging.example.test',21,'stage-user','synthetic-password','/staging'))
+ def test_each_missing_setting_fails_without_fallback(self):
+ for key in ENV:
+ env = {**ENV, 'FTP_PASSWORD':'production-placeholder'}
+ del env[key]
+ with self.subTest(key=key), patch.dict(os.environ, env, clear=True), self.assertRaises(SystemExit):
+ d.staging_config()
+ def test_unsafe_roots(self):
+ for root in ('/', '', '/public_html', '/www', '/htdocs', 'staging', '/a/../b', '/a//b', '/a/', '/a\nb', '/a\\b'):
+ with self.subTest(root=root), patch.dict(os.environ, {**ENV,'STAGING_FTP_HOME_PATH':root}, clear=True), self.assertRaises(SystemExit):
+ d.staging_config()
+ def test_production_account_and_invalid_port(self):
+ for key,value in [('USERNAME',d.USER),('PORT','0'),('PORT','65536'),('PORT','x')]:
+ with patch.dict(os.environ,{**ENV,'STAGING_FTP_'+key:value},clear=True), self.assertRaises(SystemExit):
+ d.staging_config()
+ def test_root_alias_fails_before_write(self):
+ ftp=Mock(); ftp.pwd.return_value='/'
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''})
+ ftp.storbinary.assert_not_called(); ftp.delete.assert_not_called()
+ def test_subdirectory_alias_fails(self):
+ ftp=Mock(); ftp.pwd.side_effect=['/staging','/production/assets']
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{'','assets'})
+ def test_verified_root_restored(self):
+ ftp=Mock(); ftp.pwd.side_effect=['/staging','/staging/assets']
+ d.enter_staging_root(ftp,'/staging',{'','assets'})
+ self.assertEqual(ftp.cwd.call_args.args,('/staging',))
+ def test_dry_run_has_no_mkdir_upload_delete(self):
+ ftp=Mock()
+ with patch.object(d,'DIST',Path(__file__).parent.parent):
+ d.upload_all(ftp,{'scripts/deploy_ftp.py'},True)
+ ftp.mkd.assert_not_called(); ftp.storbinary.assert_not_called()
+ def test_missing_directory_fails_closed(self):
+ ftp=Mock(); ftp.pwd.return_value='/staging'
+ ftp.cwd.side_effect=[None,d.ftplib.error_perm('550 unavailable')]
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{'','assets'})
+ ftp.mkd.assert_not_called()
+ def test_missing_config_prevents_connection_even_allow_dirty(self):
+ with patch.dict(os.environ,{},clear=True), patch('sys.argv',['deploy','--target','staging','--allow-dirty']), patch.object(d.ftplib,'FTP') as factory:
+ with self.assertRaises(SystemExit): d.main()
+ factory.assert_not_called()
+ def test_staging_main_uses_only_staging_connection(self):
+ ftp=Mock()
+ with patch.dict(os.environ,ENV,clear=True), patch('sys.argv',['deploy','--target','staging']), patch.object(d,'ensure_dist_self_consistent'), patch.object(d,'ensure_dist_committed'), patch.object(d,'local_files_and_dirs',return_value=({'index.html'},{''})), patch.object(d,'resolve_password',side_effect=AssertionError), patch.object(d.ftplib,'FTP',return_value=ftp), patch.object(d,'enter_staging_root') as enter, patch.object(d,'upload_all',return_value=([],[])), patch.object(d,'prune_stale_files',return_value=([],[])):
+ d.main()
+ ftp.connect.assert_called_once_with('staging.example.test',21,timeout=120)
+ ftp.login.assert_called_once_with('stage-user','synthetic-password')
+ enter.assert_called_once_with(ftp,'/staging',{''})
+ def test_remote_symlink_blocks_staging(self):
+ ftp=Mock(); ftp.pwd.return_value='/staging'
+ ftp.retrlines.side_effect=lambda cmd,cb: cb('lrwxrwxrwx 1 u g 1 Jan 1 00:00 index.html -> target')
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''})
+ ftp.storbinary.assert_not_called()
+ def test_listing_failure_blocks_staging(self):
+ ftp=Mock(); ftp.pwd.return_value='/staging'
+ ftp.retrlines.side_effect=d.ftplib.error_perm('550 denied')
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,'/staging',{''})
+ def test_malformed_listing_blocks_staging(self):
+ ftp=Mock(); ftp.pwd.return_value="/staging"
+ ftp.retrlines.side_effect=lambda cmd,cb: cb("unrecognized listing")
+ with self.assertRaises(SystemExit): d.enter_staging_root(ftp,"/staging",{""})
+ ftp.storbinary.assert_not_called()
+ def test_listing_failure_after_preflight_fails_main(self):
+ ftp=Mock(); ftp.pwd.return_value='/staging'
+ ftp.retrlines.side_effect=[None,d.ftplib.error_perm('550 listing denied')]
+ with patch.dict(os.environ,ENV,clear=True), patch('sys.argv',['deploy','--target','staging']), patch.object(d,'ensure_dist_self_consistent'), patch.object(d,'ensure_dist_committed'), patch.object(d,'local_files_and_dirs',return_value=({'index.html'},{''})), patch.object(d.ftplib,'FTP',return_value=ftp), patch.object(d,'upload_all',return_value=([],[])):
+ with self.assertRaisesRegex(SystemExit,'Cannot inspect staging directory'):
+ d.main()
+ self.assertEqual(ftp.retrlines.call_count,2)
+ ftp.delete.assert_not_called()
+ def test_hostile_listing_cannot_escape(self):
+ ftp=Mock(); ftp.retrlines.side_effect=lambda cmd,cb: cb('-rw-r--r-- 1 u g 1 Jan 1 00:00 ../outside')
+ with self.assertRaises(SystemExit): d.prune_stale_files(ftp,set(),{''},False)
+ ftp.delete.assert_not_called()
+
+if __name__ == '__main__': unittest.main()
diff --git a/src/generationHistory.js b/src/generationHistory.js
new file mode 100644
index 0000000..7e83a72
--- /dev/null
+++ b/src/generationHistory.js
@@ -0,0 +1,124 @@
+import { normalizeArtifactBundle, parseJsonLike } from './artifactBundle.js';
+import { buildBundleDeployPlan } from './bundleDeployPlanner.js';
+
+const object = v => v && typeof v === 'object' && !Array.isArray(v);
+const text = v => typeof v === 'string' && v.trim().length > 0;
+const abortError = () => new DOMException('History request invalidated', 'AbortError');
+
+/** getSession returns {token, key}; key must change on logout/account switch.
+ * Call invalidate immediately on session changes or selection changes. Each call
+ * performs one bounded server page, including empty continuation pages. */
+export function createGenerationHistoryClient({ endpoint, getSession, fetchImpl = globalThis.fetch }) {
+ const url = new URL(endpoint);
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !['/service/generation-history', '/staging/service/generation-history'].includes(url.pathname)) throw new Error('Invalid history endpoint');
+ let epoch = 0;
+ const pending = new Set();
+ function invalidate() { epoch++; for (const c of pending) c.abort(); pending.clear(); }
+ async function request(body, { signal } = {}) {
+ const session = getSession();
+ if (!text(session?.token) || !text(session?.key)) throw new Error('Authenticated session required');
+ const { token, key } = session;
+ const started = epoch;
+ const controller = new AbortController();
+ const cancel = () => controller.abort();
+ signal?.addEventListener('abort', cancel, { once: true });
+ if (signal?.aborted) cancel();
+ pending.add(controller);
+ const check = () => {
+ const now = getSession();
+ if (controller.signal.aborted || epoch !== started || now?.key !== key || now?.token !== token) throw abortError();
+ };
+ try {
+ check();
+ const response = await fetchImpl(url.href, { method: 'POST', credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...body, sessionToken: token }), signal: controller.signal });
+ const data = await response.json();
+ check();
+ if (!response.ok) {
+ const error = new Error('History request failed');
+ error.status = response.status;
+ error.code = data?.error?.code || 'INVALID_RESPONSE';
+ throw error;
+ }
+ return data;
+ } finally { pending.delete(controller); signal?.removeEventListener('abort', cancel); }
+ }
+ const validId = id => { if (!text(id) || id.length > 1500 || id.includes('/')) throw new Error('Invalid history id'); };
+ return {
+ invalidate,
+ async list({ cursor, signal } = {}) {
+ if (cursor !== undefined && (!text(cursor) || cursor.length > 8192)) throw new Error('Invalid cursor');
+ const data = await request({ action: 'list', ...(cursor === undefined ? {} : { cursor }) }, { signal });
+ if (!Array.isArray(data?.items) || data.items.length > 20 || !(data.nextCursor === null || (text(data.nextCursor) && data.nextCursor.length <= 8192)) || (cursor && cursor === data.nextCursor)) throw new Error('Invalid history page');
+ return data;
+ },
+ async detail(id, options) { validId(id); const data = await request({ action: 'detail', id }, options); if (!object(data?.generation)) throw new Error('Invalid history detail'); return data; },
+ async delete(id, options) { validId(id); const data = await request({ action: 'delete', id }, options); if (data?.deleted !== true || data.id !== id) throw new Error('Invalid deletion response'); return data; },
+ };
+}
+
+function completeStage(stage, field) {
+ const value = stage?.[`${field}_text`];
+ return text(value) && stage[`${field}_truncated`] === false && stage.status === 'success'
+ && (field === 'input' || ['stop', 'end_turn'].includes(stage.finish_reason))
+ && Number.isInteger(stage[`${field}_chars`]) && stage[`${field}_chars`] === value.length;
+}
+function validatedBundle(raw) {
+ if (!object(raw) || !['artifact-bundle/v1'].includes(raw.schemaVersion) || !Array.isArray(raw.artifacts) || !raw.artifacts.length) return null;
+ const types = ['CustomAction', 'CustomWidget', 'CustomFunction', 'CustomClass', 'CodeFile'];
+ if (raw.artifacts.some(a => !object(a) || !text(a.id) || !types.includes(a.artifactType) || !text(a.artifactName) || (typeof a.fileName !== 'string' || !/^[\w-]+\.dart$/.test(a.fileName)) || !text(a.code) || (a.deployPath !== undefined && (typeof a.deployPath !== 'string' || !/^lib\/(?:[\w-]+\/)*[\w-]+\.dart$/.test(a.deployPath))))) return null;
+ if (Object.hasOwn(raw, 'deployOrder') && (!Array.isArray(raw.deployOrder)
+ || raw.deployOrder.length !== raw.artifacts.length
+ || new Set(raw.deployOrder).size !== raw.artifacts.length
+ || raw.deployOrder.some(id => typeof id !== 'string' || !raw.artifacts.some(a => a.id === id)))) return null;
+ const bundle = normalizeArtifactBundle(raw);
+ if (new Set(bundle.artifacts.map(a => a.id)).size !== bundle.artifacts.length) return null;
+ if (bundle.deployOrder.length !== bundle.artifacts.length || new Set(bundle.deployOrder).size !== bundle.artifacts.length || bundle.deployOrder.some(id => !bundle.artifacts.some(a => a.id === id))) return null;
+ const plan = buildBundleDeployPlan(bundle);
+ if (plan.errors.length) return null;
+ const files = plan.fileEntries;
+ // Validate actual deploy targets as well as supplied paths.
+ if (files && new Set(files.map(f => f.path)).size !== files.length) return null;
+
+ return bundle;
+}
+
+/** Pure recovery, never generation, deployment, or approval. Raw stage text is
+ * returned for text-only display. UI must retain existing deployment gates. */
+export function recoverGenerationHistory(detail) {
+ const g = detail?.generation || {};
+ const stages = object(g.stages) ? g.stages : {};
+ const result = { availability: 'unavailable', source: null, artifactBundle: null, bundleReview: null, review: null, reviewAvailable: false, originalPrompt: null, bundleSpec: null, stages, metadata: Object.fromEntries(['id', 'request_id', 'created_at', 'updated_at', 'stage', 'status', 'is_test', 'models', 'totals'].map(k => [k, g[k] ?? null])) };
+ if (detail?.identityMismatch || !text(g.id) || g.id !== g.request_id) return result;
+ const architect = stages.architect, generator = stages.generator, review = stages.review;
+ if (completeStage(architect, 'input')) result.originalPrompt = parseJsonLike(architect.input_text)?.userRequest ?? null;
+ if (typeof result.originalPrompt !== 'string') result.originalPrompt = null;
+ result.bundleSpec = completeStage(architect, 'output') ? parseJsonLike(architect.output_text) : null;
+ if (!result.bundleSpec && completeStage(generator, 'input')) result.bundleSpec = parseJsonLike(generator.input_text)?.bundleSpec ?? null;
+ let bundle = completeStage(generator, 'output') ? validatedBundle(parseJsonLike(generator.output_text)) : null;
+ if (bundle) result.source = 'generator-output';
+ if (!bundle && completeStage(review, 'input')) {
+ bundle = validatedBundle(parseJsonLike(review.input_text)?.generatedBundle);
+ if (bundle) result.source = 'review-input';
+ }
+ if (!bundle) return result;
+ result.artifactBundle = bundle;
+ result.availability = 'pre-review';
+ const rawReview = completeStage(review, 'output') ? parseJsonLike(review.output_text) : null;
+ if (!object(rawReview) || (rawReview.schemaVersion !== undefined && rawReview.schemaVersion !== 'artifact-bundle/v1') || !Array.isArray(rawReview.artifacts)) return result;
+ const summary = rawReview.bundleReview;
+ if (!object(summary) || !['pass', 'warn', 'fail'].includes(summary.status) || !Number.isInteger(summary.score) || summary.score < 0 || summary.score > 100 || !text(summary.summary)) return result;
+ if (rawReview.artifacts.some(a => !object(a) || !text(a.id) || !['pass', 'warn', 'fail'].includes(a.review?.status))) return result;
+ const normalized = normalizeArtifactBundle({ ...bundle, artifacts: rawReview.artifacts.map(a => ({
+ ...bundle.artifacts.find(original => original.id === a.id), id: a.id, review: a.review,
+ })) });
+ const reviews = new Map(normalized.artifacts.map(a => [a.id, a.review]));
+ if (reviews.size !== bundle.artifacts.length || normalized.artifacts.length !== reviews.size || bundle.artifacts.some(a => !object(reviews.get(a.id)))) return result;
+ result.review = rawReview;
+ result.reviewAvailable = true;
+ result.availability = 'reviewed';
+ result.bundleReview = { ...bundle, artifacts: bundle.artifacts.map(a => {
+ const stored = reviews.get(a.id);
+ return { ...a, review: stored, ...(text(stored.fixedSource) ? { fixedCode: stored.fixedSource.trim() } : {}) };
+ }) };
+ return result;
+}
diff --git a/src/generationHistory.test.js b/src/generationHistory.test.js
new file mode 100644
index 0000000..163340e
--- /dev/null
+++ b/src/generationHistory.test.js
@@ -0,0 +1,92 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { recoverGenerationHistory as recover, createGenerationHistoryClient as client } from './generationHistory.js';
+const bundle = () => ({schemaVersion:'artifact-bundle/v1',artifacts:[{id:'one',artifactType:'CodeFile',artifactName:'One',fileName:'one.dart',code:'class One {}'}]});
+const detail = stages => ({generation:{id:'synthetic',request_id:'synthetic',stages}});
+const stage = (value, field) => ({status:'success',finish_reason:'stop',[`${field}_text`]:JSON.stringify(value),[`${field}_chars`]:JSON.stringify(value).length,[`${field}_truncated`]:false});
+const output = value => stage(value, 'output');
+test('complete output and actual review preserve original and fixed source', () => {
+ const value = recover(detail({generator:output(bundle()),review:output({schemaVersion:'artifact-bundle/v1',bundleReview:{status:'pass',score:95,summary:'Synthetic review'},artifacts:[{id:'one',review:{status:'pass',fixedSource:'class One { }'}}]})}));
+ assert.equal(value.availability,'reviewed'); assert.equal(value.artifactBundle.artifacts[0].code,'class One {}'); assert.equal(value.bundleReview.artifacts[0].fixedCode,'class One { }');
+});
+test('review input recovery is explicitly pre-review and prompt is recovered', () => {
+ const value = recover(detail({architect:stage({userRequest:'Synthetic prompt'}, 'input'),review:stage({generatedBundle:bundle()}, 'input')}));
+ assert.equal(value.source,'review-input'); assert.equal(value.reviewAvailable,false); assert.equal(value.originalPrompt,'Synthetic prompt'); assert.equal(value.metadata.status,null);
+});
+test('missing, unsupported, truncated, duplicate and mismatched data cannot replay', () => {
+ for (const generator of [{}, {...output(bundle()),output_truncated:true}, {...output(bundle()),finish_reason:'length'}, {...output(bundle()),output_chars:99999}, output({...bundle(),schemaVersion:'future'}), output({...bundle(),artifacts:[...bundle().artifacts,...bundle().artifacts]})]) assert.equal(recover(detail({generator})).availability,'unavailable');
+ assert.equal(recover({...detail({generator:output(bundle())}),identityMismatch:true}).availability,'unavailable');
+});
+test('bounded page allows empty continuation and sends no owner fields', async () => {
+ let body;
+ const c = client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'synthetic',key:'a'}),fetchImpl:async (_,opts)=>{assert.equal(opts.credentials,'omit'); assert.deepEqual(opts.headers,{'Content-Type':'application/json'}); body=JSON.parse(opts.body);return {ok:true,json:async()=>({items:[],nextCursor:'next'})};}});
+ assert.equal((await c.list({user_id:'forged'})).nextCursor,'next'); assert.deepEqual(body,{action:'list',sessionToken:'synthetic'});
+ await assert.rejects(c.list({cursor:'next'}),/Invalid history page/);
+});
+test('session changes and invalidation suppress late responses even if fetch ignores abort', async () => {
+ for (const mode of ['session','invalidate','signal']) {
+ let session={token:'token',key:'a'}, release;
+ const signal=new AbortController();
+ const c=client({endpoint:'https://example.test/service/generation-history',getSession:()=>session,fetchImpl:()=>new Promise(resolve=>{release=()=>resolve({ok:true,json:async()=>({items:[],nextCursor:null})});})});
+ const pending=c.list({signal:signal.signal});
+ if(mode==='session')session={token:'token2',key:'b'}; else if(mode==='invalidate')c.invalidate(); else signal.abort();
+ release(); await assert.rejects(pending,{name:'AbortError'});
+ }
+});
+test('detail/delete and structured HTTP errors',async()=>{
+ let response={generation:{id:'a'}};
+ const c=client({endpoint:'https://example.test/service/generation-history',getSession:()=>({token:'t',key:'a'}),fetchImpl:async()=>({ok:true,json:async()=>response})});
+ assert.equal((await c.detail('a')).generation.id,'a'); response={deleted:true,id:'a'}; assert.equal((await c.delete('a')).deleted,true);
+ await assert.rejects(c.detail('../bad'));
+});
+
+const reviewer = () => ({bundleReview:{status:'pass',score:95,summary:'Reviewed'},artifacts:[{id:'one',review:{status:'pass',findings:[]}}]});
+test('missing completeness metadata never grants replay or review', () => {
+ for (const field of ['status','output_truncated','output_chars','finish_reason']) {
+ const generator = output(bundle()); delete generator[field];
+ assert.equal(recover(detail({generator})).availability,'unavailable', field);
+ const review = output(reviewer()); delete review[field];
+ assert.equal(recover(detail({generator:output(bundle()),review})).availability,'pre-review', field);
+ }
+ for (const field of ['status','input_truncated','input_chars']) {
+ const review = stage({generatedBundle:bundle()},'input'); delete review[field];
+ assert.equal(recover(detail({review})).availability,'unavailable',field);
+ }
+});
+test('actual reviewer envelope works with optional fixedSource and no schemaVersion', () => {
+ for (const fixedSource of [undefined,'class One { int x = 1; }']) {
+ const review = reviewer(); review.artifacts[0].review.fixedSource = fixedSource;
+ const result = recover(detail({generator:output(bundle()),review:output(review)}));
+ assert.equal(result.availability,'reviewed');
+ assert.equal(result.bundleReview.artifacts[0].fixedCode,fixedSource);
+ assert.equal(result.artifactBundle.artifacts[0].code,'class One {}');
+ }
+});
+test('planner-supported shared functions replay but unrelated collisions do not', () => {
+ const artifacts = ['one','two'].map(id => ({id,artifactType:'CustomFunction',artifactName:id,fileName:'custom_functions.dart',deployPath:'lib/flutter_flow/custom_functions.dart',code:`int ${id}() => 1;`}));
+ assert.equal(recover(detail({generator:output({...bundle(),artifacts})})).availability,'pre-review');
+ artifacts[1].artifactType='CodeFile';
+ assert.equal(recover(detail({generator:output({...bundle(),artifacts})})).availability,'unavailable');
+});
+test('supplied malformed deployOrder is rejected before normalization', () => {
+ for (const deployOrder of ['one',null,{},[],['one','one'],['missing'],[42]]) {
+ assert.equal(recover(detail({generator:output({...bundle(),deployOrder})})).availability,'unavailable');
+ }
+ assert.equal(recover(detail({generator:output({...bundle(),deployOrder:['one']})})).availability,'pre-review');
+});
+test('nonstring and malformed stored paths are unavailable without throwing', () => {
+ for (const deployPath of [42,null,{},[],false,'','lib/../one.dart','lib//one.dart','lib/./one.dart','lib/one.dart?x','lib/one\\bad.dart','lib/one\u0000.dart']) {
+ const raw = bundle(); raw.artifacts[0].deployPath=deployPath;
+ assert.equal(recover(detail({generator:output(raw)})).availability,'unavailable',JSON.stringify(deployPath));
+ }
+});
+
+test('reviewer artifact metadata cannot override validated generator metadata or crash recovery', () => {
+ for (const extra of [{fileName:42},{artifactName:{}},{deployPath:42},{code:{}},{artifactType:[]}]) {
+ const review = reviewer(); Object.assign(review.artifacts[0], extra);
+ const value = recover(detail({generator:output(bundle()),review:output(review)}));
+ assert.equal(value.availability,'reviewed');
+ assert.equal(value.bundleReview.artifacts[0].fileName,'one.dart');
+ assert.equal(value.bundleReview.artifacts[0].code,'class One {}');
+ }
+});
diff --git a/src/generationHistoryConfig.js b/src/generationHistoryConfig.js
new file mode 100644
index 0000000..0edbdce
--- /dev/null
+++ b/src/generationHistoryConfig.js
@@ -0,0 +1,11 @@
+/** Public URLs only. No implicit production fallback, including in staging. */
+export function resolveGenerationHistoryEndpoint({ target, stagingEndpoint, productionEndpoint } = {}) {
+ if (!['staging', 'production'].includes(target)) throw new Error('Explicit history target required');
+ const value = target === 'staging' ? stagingEndpoint : productionEndpoint;
+ const url = new URL(value);
+ const path = target === 'staging' ? '/staging/service/generation-history' : '/service/generation-history';
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== path) {
+ throw new Error('Invalid public history endpoint for target');
+ }
+ return url.href;
+}
diff --git a/src/generationHistoryConfig.test.js b/src/generationHistoryConfig.test.js
new file mode 100644
index 0000000..e3620a0
--- /dev/null
+++ b/src/generationHistoryConfig.test.js
@@ -0,0 +1,7 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { resolveGenerationHistoryEndpoint as resolve } from './generationHistoryConfig.js';
+test('explicit isolated public endpoints', () => {
+ assert.equal(resolve({target:'staging',stagingEndpoint:'https://example.test/staging/service/generation-history'}),'https://example.test/staging/service/generation-history');
+ for (const config of [{}, {target:'staging',productionEndpoint:'https://example.test/service/generation-history'}, {target:'staging',stagingEndpoint:'https://example.test/service/generation-history'}, {target:'production',productionEndpoint:'https://secret@example.test/service/generation-history'}]) assert.throws(() => resolve(config));
+});
diff --git a/src/generationSession.js b/src/generationSession.js
new file mode 100644
index 0000000..5af9fe0
--- /dev/null
+++ b/src/generationSession.js
@@ -0,0 +1,54 @@
+// Account generation credentials are never persisted or used to authenticate history.
+export function createGenerationSessionClient({ endpoint, getSession, getLegacyToken, fetchImpl = fetch }) {
+ let epoch = 0;
+ let pending = null;
+ const stale = () => new DOMException('Account session changed', 'AbortError');
+ function invalidate() {
+ epoch++;
+ pending?.controller.abort();
+ pending = null;
+ }
+ async function ensure() {
+ const session = getSession();
+ if (!session?.token || !session?.key) throw new Error('Sign in to prepare generation.');
+ if (pending?.token === session.token && pending.key === session.key) return pending.promise;
+ invalidate();
+ const currentEpoch = epoch;
+ const controller = new AbortController();
+ const current = () => {
+ const now = getSession();
+ return epoch === currentEpoch && now?.token === session.token && now?.key === session.key;
+ };
+ const task = { token: session.token, key: session.key, controller };
+ task.promise = (async () => {
+ const timer = setTimeout(() => controller.abort(), 15000);
+ try {
+ const identityToken = await getLegacyToken();
+ if (!current()) throw stale();
+ const response = await fetchImpl(endpoint, {
+ method: 'POST', signal: controller.signal,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ sessionToken: session.token, ...(identityToken ? { identityToken } : {}) }),
+ });
+ if (!current()) throw stale();
+ if (!response.ok) throw new Error('Account generation access could not be prepared. Please retry.');
+ const data = await response.json();
+ if (!current()) throw stale();
+ if (typeof data?.user_id !== 'string' || !data.user_id || typeof data.identity_token !== 'string' || !data.identity_token) {
+ throw new Error('Invalid account generation session.');
+ }
+ return {
+ userId: data.user_id, token: data.identity_token,
+ ...(Number.isInteger(data.usage_count) && data.usage_count >= 0 ? { usageCount: data.usage_count } : {}),
+ ...(typeof data.usage_month === 'string' && /^\d{4}-\d{2}$/.test(data.usage_month) ? { usageMonth: data.usage_month } : {}),
+ };
+ } finally {
+ clearTimeout(timer);
+ if (pending === task) pending = null;
+ }
+ })();
+ pending = task;
+ return task.promise;
+ }
+ return { ensure, invalidate };
+}
diff --git a/src/generationSession.test.js b/src/generationSession.test.js
new file mode 100644
index 0000000..9dae175
--- /dev/null
+++ b/src/generationSession.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createGenerationSessionClient } from './generationSession.js';
+const session = { key: 'a@example.com', token: 'email-session-jwt' };
+const response = (user_id = 'account-a') => ({ ok: true, json: async () => ({ user_id, identity_token: `signed-${user_id}` }) });
+test('bridge authenticates email session; legacy token is proof only, no caller owner fields', async () => {
+ const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => 'legacy-signed', fetchImpl: async (url, init) => {
+ assert.equal(url, '/authUserCheck');
+ assert.equal(init.headers.Authorization, undefined);
+ assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt', identityToken: 'legacy-signed' });
+ return response();
+ } });
+ assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed-account-a' });
+});
+test('missing legacy identity sends only session token; server identity is authoritative', async () => {
+ const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async (_, init) => { assert.deepEqual(JSON.parse(init.body), { sessionToken: 'email-session-jwt' }); return response('new-owner'); } });
+ assert.equal((await client.ensure()).userId, 'new-owner');
+});
+test('account switch rejects old delayed response, even if transport ignores abort', async () => {
+ let current = session, release, entered;
+ const started = new Promise(r => entered = r);
+ const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => current, getLegacyToken: async () => null, fetchImpl: async (_, init) => {
+ if (JSON.parse(init.body).sessionToken === 'email-session-jwt') { entered(); await new Promise(r => release = r); return response(); }
+ return response('account-b');
+ } });
+ const old = client.ensure(); await started;
+ current = { key: 'b@example.com', token: 'email-b' }; client.invalidate();
+ assert.equal((await client.ensure()).userId, 'account-b');
+ release(); await assert.rejects(old, { name: 'AbortError' });
+});
+test('logout while obtaining proof prevents bridge request', async () => {
+ let current = session, release;
+ const proof = new Promise(r => release = r);
+ const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => current, getLegacyToken: () => proof, fetchImpl: () => { throw new Error('Must not request'); } });
+ const pending = client.ensure(); current = null; client.invalidate(); release('legacy');
+ await assert.rejects(pending, { name: 'AbortError' });
+});
+test('bridge errors and malformed credentials fail closed and allow retry', async () => {
+ let count = 0;
+ const client = createGenerationSessionClient({ endpoint: '/bridge', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async () => ++count === 1 ? { ok: false } : count === 2 ? { ok: true, json: async () => ({ user_id: 'a' }) } : response() });
+ await assert.rejects(client.ensure(), /could not be prepared/);
+ await assert.rejects(client.ensure(), /Invalid/);
+ assert.equal((await client.ensure()).userId, 'account-a');
+});
+test('returns validated account usage without accepting malformed counters', async () => {
+ let data = { user_id: 'account-a', identity_token: 'signed', usage_count: 31, usage_month: '2026-11' };
+ const client = createGenerationSessionClient({ endpoint: '/authUserCheck', getSession: () => session, getLegacyToken: async () => null, fetchImpl: async () => ({ ok: true, json: async () => data }) });
+ assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed', usageCount: 31, usageMonth: '2026-11' });
+ data = { ...data, usage_count: -1, usage_month: {} };
+ assert.deepEqual(await client.ensure(), { userId: 'account-a', token: 'signed' });
+});
diff --git a/src/pipelineAccountIsolation.test.js b/src/pipelineAccountIsolation.test.js
new file mode 100644
index 0000000..c96bd6f
--- /dev/null
+++ b/src/pipelineAccountIsolation.test.js
@@ -0,0 +1,50 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+const app = readFileSync(new URL('../app.js', import.meta.url), 'utf8');
+const start = app.indexOf('async function callBuildShip(');
+const actualFunction = app.slice(start, app.indexOf('\n// Set when', start));
+function harness(status = 200) {
+ let release, started;
+ const bodyStarted = new Promise(resolve => { started = resolve; });
+ const body = new Promise(resolve => { release = resolve; });
+ const writes = [];
+ const env = {
+ pipelineState: { runId: 1, requestId: 'request-a' }, identityEpoch: 1,
+ authState: { isVerified: true }, identityState: { userId: 'a', token: 'scoped-a' },
+ ensureAccountGenerationIdentity: async () => {},
+ isCurrentPipelineRun: id => id === env.pipelineState.runId,
+ activeBuildShipControllers: new Set(), AbortController, DOMException, setTimeout, clearTimeout,
+ PIPELINE_ENDPOINT: 'https://example.test/pipeline', USAGE_STORAGE_KEY: 'usage',
+ fetch: async (_, init) => { assert.equal(init.credentials, 'omit'); assert.deepEqual(init.headers, { 'Content-Type': 'application/json' }); assert.equal(JSON.parse(init.body).sessionToken, env.identityState.token); return ({ status, ok: status === 200, text: async () => { started(); return body; } }); },
+ localStorage: { setItem: (...args) => writes.push(args) },
+ updateUsageDisplay: () => {}, getCurrentYearMonth: () => '2026-11', incrementUsage: () => writes.push('increment'),
+ createModelArmorError: () => null, console: { log() {} },
+ };
+ // Execute the production function with an abort-insensitive transport, not a duplicate implementation.
+ const call = new Function('env', `with (env) { return (${actualFunction}); }`)(env);
+ return { env, writes, release, bodyStarted, call };
+}
+for (const status of [200, 429]) test(`late ${status} response cannot meter a different account`, async () => {
+ const h = harness(status);
+ const pending = h.call('generator', 'model', 'account A prompt');
+ await h.bodyStarted;
+ h.env.identityEpoch++; h.env.pipelineState.runId++;
+ h.env.identityState = { userId: 'b', token: 'scoped-b' };
+ h.env.activeBuildShipControllers.forEach(c => c.abort());
+ h.release(JSON.stringify({ output: 'code', usage_status: 'success', usage_count: 31, usage_month: '2026-11', serverCount: 31 }));
+ await assert.rejects(pending, error => error.isPipelineCancel === true);
+ assert.deepEqual(h.writes, []);
+});
+test('current account generator response still reconciles usage', async () => {
+ const h = harness(); const pending = h.call('generator', 'model', 'prompt');
+ await h.bodyStarted;
+ h.release(JSON.stringify({ output: 'code', usage_status: 'success', usage_count: 31, usage_month: '2026-11' }));
+ assert.equal(await pending, 'code');
+ assert.deepEqual(h.writes, [['usage', JSON.stringify({ count: 31, month: '2026-11' })]]);
+});
+
+test("anonymous pipeline retains its identity token in the body", async () => {
+ const h = harness(); h.env.authState.isVerified = false; h.env.identityState.token = "anonymous-proof";
+ const pending = h.call("architect", "model", "prompt"); await h.bodyStarted; h.release(JSON.stringify({ output: "plan" })); assert.equal(await pending, "plan");
+});