Skip to content

fix(chat): keep sessions in ~/.gaia/sessions and refuse corrupt files - #4371

Merged
kovtcharov-amd merged 4 commits into
mainfrom
replicate/chat-sessions-storage-4311
Sep 25, 2026
Merged

kovtcharov-amd merged 4 commits into
mainfrom
replicate/chat-sessions-storage-4311

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

gaia chat saved full transcripts and indexed-file paths to ./.gaia/sessions in whatever directory it started from, often a git repo where they could be committed by accident. A truncated session file was treated as "not found", so the next save quietly replaced the user's history with an empty session. Sessions now live in ~/.gaia/sessions (the location the docs already promised), saves are atomic, and a corrupt file raises an error and is left untouched instead of being overwritten.

Session ids are now restricted to 1–128 characters from A-Z a-z 0-9 . _ -, which blocks ../ escapes. The flagship server checks this up front, so a caller sending any other id (such as a:b or ../x) to /v1/gaia/query or /v1/gaia/sessions/{session_id}/bypass gets a 400 naming the allowed characters, not a 500. UUIDs and ids like s1 are unaffected. The gaia SPEC, SKILL, README, and CHANGELOG document this.

Sessions saved by earlier versions stay where they were. The chat CHANGELOG tells users to move them into ~/.gaia/sessions.

Replicates #4311 onto a branch this session can push to — that PR lives on the kovtcharov/gaia fork, whose push access was revoked mid-review, so it could no longer be refreshed against main and went CONFLICTING. No content changes beyond conflict resolution against current main.

🔍 Conflict resolution

Two conflicts, both doc-only and both purely additive — no Python file conflicted:

  • hub/agents/chat/python/CHANGELOG.md — main added a /clear-cache bullet under the same ## Unreleased heading this PR adds its sessions bullet to. Kept both.
  • hub/agents/gaia/npm/SPEC.md §5.2 — main appended the one-shot/idle-deletion paragraphs to the same sentence this PR extends with the session-id rule. Kept both, session-id rule first so it sits next to the sentence it qualifies.

The review ask on #4311 (invalid session_id returning 500) was addressed by its second commit at 07:02Z, after the 06:55Z review.

Test plan

  • hub/agents/chat/python/tests/test_session_storage.py: 14 pass, 1 fails Windows-only (see below)
  • hub/agents/gaia/python/tests/test_server_query.py: 49 pass, including ../x, a:b, a/b, ... and a 129-character id getting a 400 on /query and bypass while a UUID and s1 still work
  • hub/agents/gaia/python/tests/ hub/agents/chat/python/tests/: 528 pass, 3 skipped, 1 Windows-only failure
  • black and isort clean
  • Reviewer note: test_truncated_session_is_loud_and_not_overwritten passes on the ubuntu-latest runner this suite uses but fails on a Windows dev box — pytest.raises(match=str(path)) treats the Windows path's backslashes as regex escapes (\U). Pre-existing in fix(chat): keep sessions in ~/.gaia/sessions and refuse corrupt files #4311, not introduced here, and invisible to CI; re.escape(...) fixes it if you want it in scope.

Kalin Ovtcharov and others added 3 commits September 24, 2026 23:48
gaia chat saved full transcripts to ./.gaia/sessions in whatever directory it
started from, often a git repo, and a truncated session file was treated as
"not found", so the next save silently replaced the user's history with an
empty session.

- Sessions default to <GAIA_CONFIG_DIR>/sessions, matching the documented
  ~/.gaia/sessions location, so they resume from any directory.
- Saves write to a temp file and os.replace it, so a crash mid-save keeps
  the previous file intact.
- A present-but-unparseable file raises SessionCorruptError (and leaves the
  file untouched) instead of returning None.
- session_id must match [A-Za-z0-9._-]{1,128}, must not be all dots, and
  must resolve inside the session dir.

Fixes #4219
A session_id that can't be a session file name (../x, a:b) reached the agent
build, raised ValueError from the session store, and came back from /query as
a generic 500. It is the caller's mistake, so it is now a 400 whose message
names the allowed characters.

- validate_session_id() in the chat session store is the one definition of a
  valid id; the server checks it before building an agent on /query and before
  the lookup on /sessions/{session_id}/bypass.
- SPEC, SKILL, README and CHANGELOG say 400 on both routes.
# Conflicts:
#	hub/agents/chat/python/CHANGELOG.md
#	hub/agents/gaia/npm/SPEC.md
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
hub/agents/gaia/npm ✅ ALLOW experimental experimental 1 high body.injection.credential_request

✅ All audited skills cleared the tier they claim.

Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

# Conflicts:
#	hub/agents/gaia/npm/CHANGELOG.md
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into main with commit d417ae0 Sep 25, 2026
28 of 29 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the replicate/chat-sessions-storage-4311 branch September 25, 2026 20:16
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions 🟢

This is a clean, well-motivated fix: sessions land in ~/.gaia/sessions as documented, saves are atomic, corrupt files now fail loudly instead of silently discarding history, and path traversal is blocked at both the regex and filesystem layer. The four doc surfaces (README, SPEC, SKILL, CHANGELOG) are all updated consistently. Tests cover the new paths well.

Two small things worth tidying before or just after merge:

🟢 The Windows-only test uses a raw path as a regex match string. pytest.raises(match=str(path)) treats Windows backslashes as regex escapes (\U, \s, etc.), causing a false failure. The fix is one word: re.escape(str(path)). The PR author already flagged this; calling it out so it doesn't get lost.

🟢 load_session catches (OSError, ValueError, TypeError, AttributeError) but not KeyError. ChatSession.from_dict currently raises only TypeError for structural mismatches (via cls(**data) and PathPermission(**perm_dict)), so there's no live KeyError path today. But if anyone extends from_dict to use direct key access (e.g., data["new_field"]), that KeyError would escape the SessionCorruptError wrapper and surface as an unhandled exception. Adding it to the tuple costs nothing:

except (OSError, ValueError, TypeError, AttributeError, KeyError) as e:
🔍 Technical details

Windows regex test — hub/agents/chat/python/tests/test_session_storage.py:105:

# current
with pytest.raises(SessionCorruptError, match=str(path)):
# fix
with pytest.raises(SessionCorruptError, match=re.escape(str(path))):

KeyError gap — hub/agents/chat/python/gaia_agent_chat/session.py:398–405:

The existing exception tuple is (OSError, ValueError, TypeError, AttributeError). Adding KeyError closes the gap defensively without changing any current behaviour since from_dict only raises TypeError today.

Both are 🟢 nits — neither blocks merge.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Chat transcripts now live in ~/.gaia/sessions instead of whatever directory gaia chat was launched from, saves are atomic, and a corrupt session file fails loudly instead of being silently replaced by an empty one. The core change is sound and well tested; what's missing is the care around everyone who already has sessions on disk.

Three things worth addressing:

  • Old sessions are stranded. Transcripts saved by earlier versions stay in the project directory, and resuming one by id now just says "not found". The changelog tells people to move them, but nothing in the product does — a one-time hint when the old folder is present would cost little and save a support thread.
  • Folder-access approvals quietly change scope. The cached "always allow this folder" answers live inside the sessions folder, so they move with it: previously-granted approvals are forgotten (users get re-prompted), and new ones now apply everywhere instead of per project. That's a trust-scope change and it isn't mentioned anywhere in the release notes.
  • Some ids that worked are now rejected without a way to detect it. On Linux an id containing a colon was a perfectly usable session before this change; it's now a 400. The contract version the server advertises is unchanged, so an integrator can't probe for the new rule — bump the minor or mark the rule with the version it arrived in.

Real-world evidence

The automated evidence stage failed to run — evidence-bundle.md reports the harness errored before producing anything (auth / install / rate-limit), so no surface was exercised in CI and this verdict rests on static review alone. I also could not run the suite here (no pytest in this environment), so the test results are the author's reported numbers, not something I reproduced.

The change touches two surfaces the project expects evidence for — the gaia chat CLI (where sessions are written and resumed) and the HTTP API (the new 400 on /query and /sessions/{id}/bypass) — and the description shows unit-test counts only. Green unit tests gate the logic, not the surface. A short real gaia chat save-then-resume transcript and one real request/response showing the 400 would close this; it's a nudge for an artifact, not a merge blocker.

🔍 Technical details

🟡 Important

1. No migration or hint for sessions left behind in the old location (hub/agents/chat/python/gaia_agent_chat/session.py:102)

The default moves from a cwd-relative .gaia/sessions to <GAIA_CONFIG_DIR>/sessions, and existing files are neither moved nor pointed at. A user who runs /load <id> from the repo they've always used gets Session not found with nothing linking that to the move. The CHANGELOG note is the only signal, and changelogs aren't read at the moment of failure. Cheapest fix that stays honest: in SessionManager.__init__, if Path(".gaia/sessions") exists and holds *.json, log once naming both paths and the move command. A real migration (copy on first run) is also defensible, but the one-line hint is the low-risk version.

2. The path-permission cache rides along with the sessions directory (session.py:108)

permissions_file = self.session_dir / "path_permissions.json" is unchanged, so moving session_dir silently relocates the cached folder-access grants too. Two consequences, neither documented: every approval a user previously granted is dropped (they get re-prompted), and from now on an "always allow" granted while working in project A applies when chat is started from project B. That second half is a widening of a security-relevant cache — validate_path / validate_directory consult it before indexing or watching a path. It may well be the behaviour you want (the cache is keyed by absolute path, not by project), but it should be a deliberate, stated decision: either pin permissions_file to its own location independent of session_dir, or add a CHANGELOG line saying folder approvals are now machine-wide.

3. Input narrowing shipped under an unchanged contract version (hub/agents/gaia/python/gaia_agent/server.py:65, hub/agents/gaia/npm/SPEC.md:291)

API_VERSION stays "2.15" while /query and /sessions/{id}/bypass start rejecting ids they used to accept. On Linux, a:b.json is a legal filename — an id like an ISO timestamp or user:123 produced a working session file before this change and is now a 400. Every other contract change in this file is marked (contract ≥ 2.13, ≥ 2.14, ≥ 2.15) precisely so a client can probe /version and adapt; this one isn't, so an integrator has no way to tell which build enforces it. Suggest bumping to 2.16 and annotating the SPEC §5.2 sentence with the version, the same way the other rules are.

4. No surface evidence for a CLI + HTTP change — see the visible section above; flagged once, not per file.

🟢 Minor

Windows-only regex escape in the new test (hub/agents/chat/python/tests/test_session_storage.py:77) — already called out in the test plan; it's a one-liner, worth taking now.

    with pytest.raises(SessionCorruptError, match=re.escape(str(path))):

(add import re at the top.)

save_session still swallows write failures (session.py:370) — the PR makes load loud but leaves save returning False on a disk-full OSError, with only a log line. Given the fail-loudly rule and that this PR is explicitly about not losing transcripts silently, worth revisiting in a follow-up.

UI sessions are invisible to listing and cleanup (session.py:419, session.py:488) — both glob session_*.json, so UUID-named sessions from the Agent UI never appear in list_sessions() and are never trimmed by cleanup_old_sessions. Pre-existing, but consolidating every project's sessions into one shared directory turns it into unbounded growth in the user's home.

Validation-by-side-effect (session.py:315) — create_session calls self._session_path(session_id) and discards the result. validate_session_id(session_id) says the same thing without looking like a dropped value.

Strengths

  • The atomic-save implementation is properly done: mkstemp in the target directory, flush + fsync before os.replace, and a BaseException handler that removes the temp file — no half-written file and no leftovers, and the test asserts both.
  • load_session catches a specific exception tuple and re-raises with context via raise ... from e, with an error message that names the file and what to do about it. That is exactly the shape the project's fail-loudly rule asks for.
  • The tests pin behaviours rather than implementation — that the working directory stays empty, that a truncated file is left byte-identical after the failure, that no temp files survive a double save.
  • Docs were updated together (CHANGELOG, README, SPEC, SKILL, playbook) instead of one surface, per the bundled-docs rule.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant