Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

fix(onboarding): close the remaining review findings on the wizard fix

Claude29c03a8226d2
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index e332447b..77eb29ed 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -63,15 +63,20 @@ class ChatResponse(BaseModel):
session_id: str
+# Wizard answers are a sentence or two, or a short one-per-line list. The
+# free-text parsers in onboarding/wizard.py run regexes over this, so it is
+# a safety bound on event-loop time, not only a UX choice — do not raise it
+# without re-checking the parser benchmarks in test_onboarding_wizard_arr_parse.
ONBOARD_ANSWER_MAX_CHARS = 10_000
class OnboardAnswerRequest(BaseModel):
session_id: str
- # Wizard answers are a sentence or two, or a short one-per-line list.
- # The free-text parsers in onboarding/wizard.py run regexes over this,
- # so bound it rather than let one request pin the event loop.
- answer: str = Field(max_length=ONBOARD_ANSWER_MAX_CHARS)
+ # Bounded to ONBOARD_ANSWER_MAX_CHARS in the route rather than with
+ # Field(max_length=...): FastAPI's default validation error echoes the
+ # rejected input back in the response body, and wizard answers include
+ # financials the UI promises are stored locally only.
+ answer: str
class OnboardStatusResponse(BaseModel):
diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.py
index f3be72ce..8abcca10 100644
--- a/packages/core/openexecutive/api/routes/onboarding.py
+++ b/packages/core/openexecutive/api/routes/onboarding.py
@@ -7,7 +7,11 @@ import uuid
from fastapi import APIRouter, HTTPException
-from openexecutive.api.models import OnboardAnswerRequest, OnboardStatusResponse
+from openexecutive.api.models import (
+ ONBOARD_ANSWER_MAX_CHARS,
+ OnboardAnswerRequest,
+ OnboardStatusResponse,
+)
from openexecutive.onboarding.wizard import (
TOTAL_STEPS,
WizardState,
@@ -62,6 +66,11 @@ async def submit_answer(body: OnboardAnswerRequest) -> OnboardStatusResponse:
raise HTTPException(status_code=404, detail="Onboarding session not found")
if state.completed:
raise HTTPException(status_code=400, detail="Onboarding already completed")
+ if len(body.answer) > ONBOARD_ANSWER_MAX_CHARS:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Answer is too long (limit {ONBOARD_ANSWER_MAX_CHARS:,} characters).",
+ )
# process_answer mutates the stored state in place. Keep a snapshot so
# a failed profile build on the final answer can be rolled back —
diff --git a/packages/core/openexecutive/memory/company_profile.py b/packages/core/openexecutive/memory/company_profile.py
index ab87a239..ee3c1850 100644
--- a/packages/core/openexecutive/memory/company_profile.py
+++ b/packages/core/openexecutive/memory/company_profile.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import contextlib
import os
+import secrets
+import stat
from pathlib import Path
from typing import Any
@@ -84,13 +86,44 @@ class CompanyProfile(BaseModel):
# value) can never leave a truncated profile behind: every other
# subsystem loads this file, and callers such as the onboarding
# route roll back on failure assuming the old profile survived.
- # Plain open() (not mkstemp) so the temp file gets the normal umask
- # permissions the final file would have had.
- tmp_path = path.with_name(f".tmp-{os.getpid()}-{path.name}")
+ #
+ # - O_EXCL via `opener`: the temp name is created fresh and never
+ # follows a pre-planted symlink. Going through open() (not
+ # os.fdopen) keeps the explicit-encoding contract visible.
+ # - A random component plus O_EXCL: two processes on one volume
+ # (both PID 1 in their containers) cannot collide.
+ # - The destination's mode is carried over: rename creates a new
+ # inode, so a file an operator chmod'd 0600 would otherwise
+ # silently revert to the umask default.
+ # - fsync file and directory: a hard crash between write and
+ # rename must not leave a zero-length profile.
+ # Stale temps from an earlier crash are swept first so a
+ # 0644 copy of the financials never lingers in company/.
+ for stale in path.parent.glob(f".tmp-*-{path.name}"):
+ with contextlib.suppress(OSError):
+ stale.unlink()
+ tmp_path = path.with_name(f".tmp-{os.getpid()}-{secrets.token_hex(4)}-{path.name}")
+ existing_mode: int | None = None
+ with contextlib.suppress(OSError):
+ existing_mode = stat.S_IMODE(path.stat().st_mode)
+
+ def _exclusive(p: str, flags: int) -> int:
+ return os.open(p, flags | os.O_EXCL, 0o600 if existing_mode is None else existing_mode)
+
try:
- with open(tmp_path, "w", encoding="utf-8") as f:
+ with open(tmp_path, "w", encoding="utf-8", opener=_exclusive) as f:
+ if existing_mode is not None:
+ os.fchmod(f.fileno(), existing_mode)
yaml.dump(data, f, default_flow_style=False, sort_keys=True)
+ f.flush()
+ os.fsync(f.fileno())
os.replace(tmp_path, path)
+ with contextlib.suppress(OSError):
+ dir_fd = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_path)
diff --git a/packages/core/openexecutive/onboarding/profile_builder.py b/packages/core/openexecutive/onboarding/profile_builder.py
index 605c5a25..ab680205 100644
--- a/packages/core/openexecutive/onboarding/profile_builder.py
+++ b/packages/core/openexecutive/onboarding/profile_builder.py
@@ -61,8 +61,12 @@ def _save_wizard_people(answers: dict) -> None: # type: ignore[type-arg]
scopes.append(AuthorityScope(tok))
if scopes:
set_authority_scope(pid, scopes)
- except Exception:
- logger.warning("_save_wizard_people failed — skipping people creation", exc_info=True)
+ except Exception as exc:
+ # Type name only: the traceback would carry the wizard's org-chart
+ # answers (names, emails, handles) into the log stream.
+ logger.warning(
+ "_save_wizard_people failed (%s) — skipping people creation", type(exc).__name__
+ )
def load_or_create_profile(path: Path | str | None = None) -> CompanyProfile:
diff --git a/packages/core/openexecutive/onboarding/wizard.py b/packages/core/openexecutive/onboarding/wizard.py
index 635b7e51..6c3f7ee5 100644
--- a/packages/core/openexecutive/onboarding/wizard.py
+++ b/packages/core/openexecutive/onboarding/wizard.py
@@ -272,8 +272,11 @@ def build_profile_from_answers(answers: dict[str, Any]) -> dict[str, Any]:
# Same digit-first rule as the ARR parse above: `[\d,]+` matched a
# bare comma, so "runway is fine, monthly costs are low" captured
# "," and crashed on float("").
+ # `(?:[Kk]\s*)?` rather than `[Kk]?\s*` after the first `\s*`: two
+ # adjacent `\s*` with an optional token between them let a long
+ # whitespace run be split quadratically many ways.
burn_match = re.search(
- r"\$?(?<![\d,])(\d[\d,]*)\s*[Kk]?\s*(?:monthly|/month|per month|burn)", text
+ r"\$?(?<![\d,])(\d[\d,]*)\s*(?:[Kk]\s*)?(?:monthly|/month|per month|burn)", text
)
runway_match = re.search(r"(\d+)\s*month", text)
diff --git a/packages/core/tests/unit/test_company_profile.py b/packages/core/tests/unit/test_company_profile.py
index 33d995ff..87630737 100644
--- a/packages/core/tests/unit/test_company_profile.py
+++ b/packages/core/tests/unit/test_company_profile.py
@@ -135,3 +135,21 @@ def test_save_to_yaml_is_atomic(tmp_path: Path, monkeypatch):
assert CompanyProfile.load_from_yaml(path).name == "Before"
assert [p.name for p in tmp_path.iterdir()] == ["profile.yaml"], "temp file left behind"
+
+
+def test_save_to_yaml_preserves_mode_and_sweeps_stale_temps(tmp_path: Path):
+ """Rename creates a new inode; an operator's chmod must survive it."""
+ import os
+ import stat
+
+ path = tmp_path / "profile.yaml"
+ CompanyProfile(name="Before").save_to_yaml(path)
+ os.chmod(path, 0o600)
+ stale = tmp_path / ".tmp-1-deadbeef-profile.yaml"
+ stale.write_text("leftover from a crash", encoding="utf-8")
+
+ CompanyProfile(name="After").save_to_yaml(path)
+
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
+ assert CompanyProfile.load_from_yaml(path).name == "After"
+ assert [p.name for p in tmp_path.iterdir()] == ["profile.yaml"]
diff --git a/packages/core/tests/unit/test_onboarding_wizard_arr_parse.py b/packages/core/tests/unit/test_onboarding_wizard_arr_parse.py
index 2d1f6d7b..11fe5020 100644
--- a/packages/core/tests/unit/test_onboarding_wizard_arr_parse.py
+++ b/packages/core/tests/unit/test_onboarding_wizard_arr_parse.py
@@ -106,3 +106,17 @@ def test_long_digit_run_is_linear_time() -> None:
assert "annual_revenue_arr" not in profile
assert "burn_rate_monthly" not in profile["financials"]
+
+
+def test_long_whitespace_run_is_linear_time() -> None:
+ """A digit followed by a long space run must not go quadratic either.
+
+ The burn-rate pattern once had `\\s*[Kk]?\\s*`; with the K absent the two
+ `\\s*` could split the run every possible way (400ms at 10k chars, 6s at
+ 40k). Sized past the API's answer bound so it does not depend on it.
+ """
+ text = "1" + " " * 200_000
+ profile = build_profile_from_answers({"business_model": text, "financials": text})
+
+ assert "annual_revenue_arr" not in profile
+ assert "burn_rate_monthly" not in profile["financials"]
diff --git a/packages/core/tests/unit/test_onboarding_wizard_route.py b/packages/core/tests/unit/test_onboarding_wizard_route.py
index 973da01e..56182927 100644
--- a/packages/core/tests/unit/test_onboarding_wizard_route.py
+++ b/packages/core/tests/unit/test_onboarding_wizard_route.py
@@ -114,10 +114,14 @@ def test_oversized_answer_is_rejected_before_parsing(
monkeypatch.setattr(profile_builder, "build_and_save_profile", _never)
session_id = client.get("/onboard/start").json()["session_id"]
- too_long = "x" * (ONBOARD_ANSWER_MAX_CHARS + 1)
+ too_long = "SECRET-BURN-" + "x" * ONBOARD_ANSWER_MAX_CHARS
resp = client.post("/onboard/answer", json={"session_id": session_id, "answer": too_long})
assert resp.status_code == 422
assert route._wizard_sessions[session_id].current_step == 0
+ # The rejection must not echo the answer back (FastAPI's default
+ # validation error would include the full `input`).
+ assert "SECRET-BURN" not in resp.text
+ assert len(resp.content) < 500
just_fits = "x" * ONBOARD_ANSWER_MAX_CHARS
resp = client.post("/onboard/answer", json={"session_id": session_id, "answer": just_fits})