Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test: stub homedir in agentPromptBuilder tests so the suite stops reading the contributor's global CLAUDE.md (#3475)

[._.]/ Adam Eivyca89af3aaf06
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ed1d2f7825..6831129757 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -59,3 +59,5 @@
- **The CoS week id paired the ISO week number with the calendar year, which both split and reused week ids around New Year.** `getWeekId()` was duplicated in `productivity.js` and `weeklyDigest.js` and built as `${date.getFullYear()}-W${isoWeek}` — so Mon 2025-12-29 and Thu 2026-01-01, one and the same ISO week, stamped `2025-W01` and `2026-W01` (breaking the weekly streak and mis-ordering the `longestWeekly` scan), while the *January* week of that same year stamped `2025-W01` too, so the late-December digest overwrote the early-January one on disk. The helper now lives once in `server/lib/isoWeek.js` and keys on the ISO week-numbering year — the calendar year of that week's Thursday — so one ISO week has one id and no id is ever reused. `isConsecutiveWeek` moved with it and now bridges a rollover only when the earlier week is genuinely its year's last, which a bare `week >= 52` check got wrong for the 53-week years (2026 is one). Migration 224 renames existing digest files and rewrites `streaks.lastActiveWeek`, resolving each record from its own stored `weekStart` / `lastActiveDate` and leaving anything it cannot resolve untouched rather than guessing a digest onto the wrong week.
- **The 1-second async-assertion timeout that flaked the QuotaBurn retry-budget test is now raised suite-wide, not per call site.** `QuotaBurn.test.jsx`'s "stops claiming it is saving once the retry budget is spent" failed roughly 1 run in 3 in isolation: it waits on a 500ms debounced save *plus* its retry — two sequential windows — against testing-library's uncustomized 1000ms `waitFor` default, which parallel-worker CPU contention pushes past. The same diagnosis had already been made once and fixed in one place (`settledInput.js`'s local `{ timeout: 3000 }`), leaving every other debounce-sensitive test exposed and the diagnosis waiting to be rediscovered. `client/src/test/setup.js` now calls `configure({ asyncUtilTimeout: 3000 })` once, carrying the rationale, and the five now-redundant local overrides in `settledInput.js`, `MediaCollections.test.jsx` and `ReferenceAnalysis.test.jsx` are gone. The cost is that a genuinely hung assertion takes 3s instead of 1s to fail; the full client suite still runs in ~26s.
+
+- **The CoS prompt-builder suite let the contributor's own global `CLAUDE.md` decide its results, so its suppression checks had never actually run on CI.** `buildAgentPrompt` reads `~/.claude/CLAUDE.md` off the real filesystem and splices it verbatim into the prompt, and `agentPromptBuilder.test.js` then asserts the prompt does *not* contain things like `gh pr merge`. That made every negative assertion in the file unsound in both directions: it false-failed on a machine whose personal global instructions happened to mention the string, and — worse — false-passed on a machine with no such file at all, which is exactly what CI is, so the suppression those assertions exist to prove was never exercised there. `homedir()` is now stubbed to a path that cannot exist, making the global section deterministically empty, and a new fixture-backed test closes the gap from the other side: it points the stub at a throwaway home whose global `CLAUDE.md` deliberately *does* contain the suppressed strings, asserts the fixture really is spliced in verbatim, and then asserts every section the builder itself authored still omits them on the reasoning-only path. Verified by breaking the suppression and watching the new test fail (#3475).
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 0f420ff4d0..6a462b9a80 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -13,10 +13,26 @@
* autonomous agent…" preamble are gone from BOTH paths.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { join } from 'path';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
import { PATHS } from '../lib/fileUtils.js';
+// #3475 — The builder reads ~/.claude/CLAUDE.md off the real filesystem and splices
+// it into the prompt, so without this every `not.toMatch` assertion below is decided
+// by the contributor's personal global config: it false-fails when their file happens
+// to contain the string, and false-passes on a machine that has no such file at all
+// (CI), where the suppression being asserted is never actually exercised. Pointing
+// homedir() at a path that cannot exist makes the global section deterministically
+// empty. `homeStub` stays mutable so the one test that needs a REAL global CLAUDE.md
+// (a fixture that deliberately contains the suppressed string) can swap it in and
+// prove the suppression positively — see the #3475 describe block further down.
+const homeStub = vi.hoisted(() => ({ dir: '/nonexistent-home-for-tests' }));
+vi.mock('os', async (importOriginal) => ({
+ ...(await importOriginal()),
+ homedir: () => homeStub.dir,
+}));
+
// Mock heavy dependencies used by the full (api) prompt path so the API-routing
// regression test doesn't try to hit the memory DB, digital-twin services, or
// disk-based slashdo loaders. Light-path tests don't invoke these at all, so
@@ -75,7 +91,7 @@ vi.mock('./codeReview.js', () => ({
getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: ['copilot'] }),
}));
-import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
+import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getClaudeMdContext, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default
import { isTruthyMeta } from './agentState.js';
import { buildPrompt } from './promptService.js'; // mocked above — inspect call args
@@ -1687,6 +1703,75 @@ describe('discardWorktree (reasoning-only) completion contract', () => {
// Simplify-before-commit step is suppressed (nothing gets committed).
expect(prompt).not.toMatch(/## Simplify Step/);
});
+
+ // #3475 — The `not.toMatch(/gh pr merge/)` assertions above run with homedir
+ // stubbed to a path that cannot exist, so the `## CLAUDE.md Instructions`
+ // section is empty. That makes them deterministic, but on its own it can't
+ // distinguish "the builder suppresses the merge instruction" from "no section
+ // of this prompt could ever have contained it" — which is exactly the false
+ // green CI has been shipping.
+ //
+ // This test closes that gap from the other side: it points homedir at a
+ // fixture home whose global CLAUDE.md deliberately DOES contain `gh pr merge`,
+ // then asserts (a) the fixture really is spliced into the prompt verbatim — so
+ // the string is demonstrably reachable — and (b) every byte the BUILDER itself
+ // generates still omits it on the discardWorktree path. Verified by probe: stub
+ // buildAgentPrompt's `discardWorktree` to `false` (i.e. remove the suppression)
+ // and (b) fails on `Commit and push your changes`.
+ describe('suppression is positively pinned against a fixture global CLAUDE.md (#3475)', () => {
+ // Obviously-fake stand-in for a contributor's personal global instructions.
+ const FIXTURE_GLOBAL_CLAUDE_MD = [
+ '# Example Global Instructions',
+ '',
+ '- When CI is green, land it with `gh pr merge <url> --merge --delete-branch`.',
+ '- Commit and push your changes before you stop.',
+ ].join('\n');
+
+ let fixtureHome;
+ let priorHomeStub;
+
+ beforeAll(() => {
+ fixtureHome = mkdtempSync(join(process.env.TMPDIR || '/tmp', 'portos-claudemd-fixture-'));
+ mkdirSync(join(fixtureHome, '.claude'), { recursive: true });
+ writeFileSync(join(fixtureHome, '.claude', 'CLAUDE.md'), FIXTURE_GLOBAL_CLAUDE_MD);
+ priorHomeStub = homeStub.dir;
+ homeStub.dir = fixtureHome;
+ });
+
+ // Restore the nonexistent-home stub — every other test in the file depends on
+ // the global CLAUDE.md section being empty.
+ afterAll(() => {
+ homeStub.dir = priorHomeStub;
+ rmSync(fixtureHome, { recursive: true, force: true });
+ });
+
+ it('splices the fixture verbatim yet still suppresses commit/push/merge in every builder-generated section', async () => {
+ // Sanity: the fixture is live and carries the strings under test. Without
+ // this the assertions below could pass because nothing was read at all.
+ const claudeMdSection = await getClaudeMdContext('/r');
+ expect(claudeMdSection).toMatch(/## CLAUDE\.md Instructions/);
+ expect(claudeMdSection).toMatch(/gh pr merge/);
+ expect(claudeMdSection).toMatch(/Commit and push your changes/);
+
+ const prompt = await buildAgentPrompt(liTask(), {}, '/r', wt, isTruthyMeta, { providerType: 'api' });
+ // The verbatim splice is the production contract — the builder passes the
+ // user's own instructions through untouched.
+ expect(prompt).toContain(claudeMdSection);
+
+ // Everything the builder authored. Removing the exact spliced section (rather
+ // than regex-slicing around a heading) keeps the boundary unambiguous.
+ const builderAuthored = prompt.replace(claudeMdSection, '');
+ expect(builderAuthored).not.toMatch(/Example Global Instructions/); // strip really worked
+ // The exact assertion that false-failed in #3475 — now scoped so the
+ // fixture's own copy of the string can't decide it.
+ expect(builderAuthored).not.toMatch(/gh pr merge/);
+ expect(builderAuthored).not.toMatch(/Commit and push your changes/);
+ expect(builderAuthored).not.toMatch(/## Completion Workflow/);
+ // …and the positive half of the same contract still renders.
+ expect(builderAuthored).toMatch(/## Completion \(Reasoning-Only Task\)/);
+ expect(builderAuthored).toMatch(/Do NOT commit, push, or open a PR/);
+ });
+ });
});
// #2507 — CoS app-improve/self-improvement tasks pin no `reviewers`, so the