Skip to content
Merged
4 changes: 4 additions & 0 deletions behavior-changes.d/secret_store_spooled_info_gst2988.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
kind: fix
---
The secret_store_spooled notice a publish prints when it redacts is now an info notice that says what happened: every publish seals the originals in this machine's encrypted spool first, and the next owner push or maintenance pass moves them into the store (gbrain git commit-push does not). It used to be a degraded notice that said the store could not be written, which was not true. The secrets and secret-spans audit logs under ~/.gbrain/audit are now written at mode 0600, and an older file with looser permissions is tightened on its next write.
4 changes: 4 additions & 0 deletions changelog.d/capy-gst-3106-refresh-retry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**`gbrain sources refresh` no longer stops and asks for the user when a local commit lands while it publishes the checkout's earlier local commits.**

### Fixed
- On a managed brain whose refresh publishes local commits by itself (Git durability on, or `sources.refresh_publish_diverged` true), a commit made on the checkout after that publish and before the fast-forward ended the run with `refresh_diverged` and a fix that said to ask the user, although nothing was lost and the next refresh succeeded. The refresh now retries once from a fresh check in the same run, which publishes the new commit too. If that retry is refused as well, the refusal still says the first commits were already published.
7 changes: 7 additions & 0 deletions changelog.d/secret-notice-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**A publish that redacts secrets no longer reports a failure that did not happen, and the secret audit logs are private to their owner.**

### Fixed
- The `secret_store_spooled` notice is now an info notice. It says the originals were sealed in this machine's encrypted spool, which every redacting publish does, and that the next owner push or maintenance pass moves them into the secret store. It also says that `gbrain git commit-push` does not move them itself. It used to be a degraded notice saying the store could not be written, which was not true. `gbrain doctor`'s `secret_store` check still reports originals left in the spool.
- The `secrets` and `secret-spans` audit logs (`~/.gbrain/audit/`) are now created at mode 0600, and an existing file with looser permissions is tightened on its next write. Before, a publish created them with the process umask (usually 0644). They hold page slugs, field names, store entry ids and span offsets, never a value.

<!-- behavior-change: secret_store_spooled_info_gst2988 -->
11 changes: 7 additions & 4 deletions docs/guides/secret-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ A remote caller needs both:

Otherwise the call fails with `secret_reveal_forbidden`. Every reveal, CLI or MCP, is appended to the `secrets` audit
log (`~/.gbrain/audit/secrets-<year>-W<week>.jsonl`) with the entry, the caller and the pages, never the value.
That file and the `secret-spans` audit log are mode 0600, and a looser existing file is tightened on its next write.

## A false positive

Expand Down Expand Up @@ -99,10 +100,12 @@ publish. The details, and what is held back instead, are in
- `gbrain git redact-unpushed --source <id>` shows what a publish would redact, writing nothing; `--apply --expect
<hash>` does it without pushing.

<a id="secret_store_spooled"></a>A publish runs without the database, so it first writes each original to an encrypted
spool on this machine, `~/.gbrain/secret-store/spool/` (directory 0700, one 0600 file per entry, the same key). The
owner moves spooled entries into the store right after its push, and maintenance (the `bookkeeping_gc` phase) moves
any that are left. `gbrain secrets reveal <id>` reads a spooled entry meanwhile, and `gbrain secrets list` (field `spooled` with
<a id="secret_store_spooled"></a>A publish runs without the database, so it always first writes each original to an encrypted
spool on this machine, `~/.gbrain/secret-store/spool/` (directory 0700, one 0600 file per entry, the same key), and
says so with the info notice `secret_store_spooled`. The first publish that redacts creates the key. The
owner moves spooled entries into the store right after its push (a page write's Git effect), and maintenance (the
`bookkeeping_gc` phase) moves any that are left. `gbrain git commit-push` does not move them, so on a host where no
owner push and no maintenance run they stay in the spool; doctor's `secret_store` check counts them. `gbrain secrets reveal <id>` reads a spooled entry meanwhile, and `gbrain secrets list` (field `spooled` with
`--json`) shows how many wait. `gbrain secrets list` also counts entries and occurrences by rule (`by_rule`), and what
the publish redactions on this machine replaced by rule (`publish_redactions`): spans, values, and how many sat in a
presigned link's `X-Amz-Credential=` parameter as opposed to bare. An entry leaves the spool only once its store row reads back to the same original, so a
Expand Down
15 changes: 14 additions & 1 deletion src/core/audit/audit-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ export interface AuditWriterOpts {
* (no trailer).
*/
errorTrailer?: string;
/**
* Permission bits for the audit file, for trails about secrets (0o600). A new file is created with them, and an
* existing file with looser bits is tightened on the next write. Unset keeps the process umask.
*/
fileMode?: number;
}

export interface AuditWriter<T extends { ts: string }> {
Expand Down Expand Up @@ -203,10 +208,18 @@ export function createAuditWriter<T extends { ts: string }>(
const file = path.join(dir, computeFilename(fileDate));
try {
fs.mkdirSync(dir, { recursive: true });
fs.appendFileSync(file, JSON.stringify(row) + '\n', { encoding: 'utf8' });
fs.appendFileSync(file, JSON.stringify(row) + '\n', { encoding: 'utf8', ...(opts.fileMode === undefined ? {} : { mode: opts.fileMode }) });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[${errorLabel}] ${errorMessagePrefix}write failed (${msg})${errorTrailer}\n`);
return;
}
if (opts.fileMode === undefined || process.platform === 'win32') return;
try {
if ((fs.statSync(file).mode & 0o777 & ~opts.fileMode) !== 0) fs.chmodSync(file, opts.fileMode);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[${errorLabel}] ${errorMessagePrefix}could not tighten ${file} to ${opts.fileMode.toString(8)} (${msg})${errorTrailer}\n`);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/core/error-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,6 @@ export const NOTICE_CODES = {
publish_secret_held_back: { kind: 'degraded', summary: 'A publish held back files the secret scan cannot vouch for (over the scan cap, not valid UTF-8, or a .gbrain-scan-allow or .gitattributes change): the pushed commits keep the remote\'s version, and one local held commit keeps this machine\'s. docs/guides/shared-checkout-git.md#publish_secret_held_back' },
publish_secret_side_refs: { kind: 'safety', summary: 'After a publish redaction, other local branches, tags or worktrees still hold the old commits with the original values; gbrain never moves them, and pushing one by hand would publish the values. docs/guides/shared-checkout-git.md#publish_secret_side_refs' },
publish_secret_unsigned: { kind: 'info', summary: 'A publish redaction rebuilt signed commits, which cannot keep their signatures. docs/guides/shared-checkout-git.md#publish_secret_unsigned' },
secret_store_spooled: { kind: 'degraded', summary: 'The secret store could not be written, so originals went to this machine\'s encrypted spool (~/.gbrain/secret-store/spool); maintenance moves them into the store and gbrain secrets reveal reads them meanwhile. docs/guides/secret-store.md#secret_store_spooled' },
secret_store_spooled: { kind: 'info', summary: 'A publish sealed the originals it redacted in this machine\'s encrypted spool (~/.gbrain/secret-store/spool), as every redacting publish does: it runs without the database. The next owner push or maintenance pass moves them into the store (gbrain git commit-push does not), and gbrain secrets reveal reads them meanwhile; doctor\'s secret_store check reports any left behind. docs/guides/secret-store.md#secret_store_spooled' },
maintenance_owned_by_serve: { kind: 'info', summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing.' },
} as const satisfies Record<string, NoticeEntry>;
4 changes: 2 additions & 2 deletions src/core/git/redact-unpushed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ function redactionNotices(o: RedactOutcome): Notice[] {
fix: { ask_user: true, argv: ['git', '-C', o.root, 'for-each-ref', '--contains', o.old_head], consent: [], actor: 'user', requires_exclusive: false, why: 'Read-only: lists the refs that still reach the old commits.', docs: `${DOCS}#publish_secret_side_refs` } });
if (o.unsigned.length) notices.push({ code: 'publish_secret_unsigned', kind: 'info', why: `${o.unsigned.length} signed commit(s) were rebuilt without their signature (a rebuilt commit cannot keep one): ${o.unsigned.map(sha => sha.slice(0, 12)).join(', ')}.`,
fix: readOnly(['git', '-C', o.root, 'log', '--show-signature', '-n', String(Math.min(o.commits, 20))], 'Read-only: shows which published commits are signed.', `${DOCS}#publish_secret_unsigned`) });
if (o.spooled) notices.push({ code: 'secret_store_spooled', kind: 'degraded', why: `${o.spooled} original(s) went to this machine's encrypted spool because the secret store could not be written; maintenance moves them into the store, and gbrain secrets reveal reads them meanwhile.`,
fix: readOnly(['gbrain', 'secrets', 'list', '--json'], 'Read-only: the store entries; spooled ones appear once maintenance moves them in.', 'docs/guides/secret-store.md#secret_store_spooled') });
if (o.spooled) notices.push({ code: 'secret_store_spooled', kind: 'info', why: `${o.spooled} original(s) were sealed in this machine's encrypted spool (a publish runs without the database, so it always seals there first). They move into the secret store at the next push a brain owner makes (a page write's Git effect) or at the next maintenance pass (bookkeeping_gc); gbrain git redact-unpushed --apply moves them right away. gbrain git commit-push does not move them itself, so on a host where no owner push and no maintenance run, they stay in the spool; gbrain secrets reveal reads them there meanwhile.`,
fix: readOnly(['gbrain', 'secrets', 'list', '--json'], 'Read-only: the store entries and how many originals still wait in the spool (spooled).', 'docs/guides/secret-store.md#secret_store_spooled') });
return notices;
}
2 changes: 1 addition & 1 deletion src/core/persistence/worktree-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTi
const pushed = await publishInChild(root, sourceId, targetHead);
const published = { sha: pushed.sha ?? targetHead, local_commits: localCommits, integrated: pushed.integrated,
...(pushed.quarantined ? { quarantined: pushed.quarantined } : {}), ...(pushed.superseded_remote_paths ? { superseded_remote_paths: pushed.superseded_remote_paths } : {}) };
const plan = await precheck(engine, git, sourceId, fetchTimeoutMs).catch(error => { throw notePublished(error, published); });
const plan = await precheck(engine, git, sourceId, fetchTimeoutMs).catch(async error => { notePublished(error, published); throw error instanceof OperationError && error.code === 'refresh_diverged' && await revParse(git, root, 'HEAD') !== oldHead ? retryInTick(error) : error; });
return { ...plan, published: { ...published, sha: pushed.sha ?? plan.targetHead } };
}
const dirt = await dirtyOverlap(git, root, oldHead, targetHead);
Expand Down
2 changes: 1 addition & 1 deletion src/core/repair/secret-spans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ function valuesOf(planned: Planned): string[] {
async function* once(text: string): AsyncIterable<Uint8Array> { if (text) yield Buffer.from(text, 'utf8'); }

const receiptKey = (hash: string, pageId: number) => `${hash}:${pageId}`;
const audit = createAuditWriter<{ ts: string } & Json>({ featureName: 'secret-spans', errorLabel: 'secret-spans-audit', errorTrailer: '; repair continues' });
const audit = createAuditWriter<{ ts: string } & Json>({ featureName: 'secret-spans', errorLabel: 'secret-spans-audit', errorTrailer: '; repair continues', fileMode: 0o600 });

/** Rewrites one page's changed fields in the caller's transaction; `unsealed`: a segmented body whose projection is built after commit. */
async function writePage(tx: BrainEngine, planned: Planned): Promise<{ unsealed: boolean }> {
Expand Down
2 changes: 1 addition & 1 deletion src/core/secret-store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const aad = (id: string, sourceId: string, rule: string) => Buffer.from(`gbrain-
const macOf = (key: Buffer, value: string) => createHmac('sha256', macKeyOf(key)).update(value, 'utf8').digest('hex');

export const secretsAudit = createAuditWriter<{ ts: string } & Record<string, unknown>>({
featureName: 'secrets', errorLabel: 'secrets-audit', errorTrailer: '; the read or write itself went ahead',
featureName: 'secrets', errorLabel: 'secrets-audit', errorTrailer: '; the read or write itself went ahead', fileMode: 0o600,
});

function keyMissing(keyId: string) {
Expand Down
21 changes: 21 additions & 0 deletions test/audit/audit-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,27 @@ describe('createAuditWriter — log()', () => {
});
});

it('fileMode: a new file is created with it, a looser existing file is tightened, and no mode keeps the umask', async () => {
const dir = makeDir();
await withEnv({ GBRAIN_AUDIT_DIR: dir }, async () => {
const prev = process.umask(0o022);
try {
const tight = createAuditWriter<TestEvent>({ featureName: 'mode-new', fileMode: 0o600 });
tight.log({ message: 'first' });
expect(fs.statSync(path.join(dir, tight.computeFilename())).mode & 0o777).toBe(0o600);
const loose = path.join(dir, computeIsoWeekFilename('mode-old'));
fs.writeFileSync(loose, '');
fs.chmodSync(loose, 0o644);
createAuditWriter<TestEvent>({ featureName: 'mode-old', fileMode: 0o600 }).log({ message: 'second' });
expect(fs.statSync(loose).mode & 0o777).toBe(0o600);
expect(fs.readFileSync(loose, 'utf8')).toContain('"message":"second"');
const plain = createAuditWriter<TestEvent>({ featureName: 'mode-unset' });
plain.log({ message: 'third' });
expect(fs.statSync(path.join(dir, plain.computeFilename())).mode & 0o777).toBe(0o644);
} finally { process.umask(prev); }
});
});

it('best-effort: write failure stderr-warns but does not throw', async () => {
// Force a non-creatable path: use a file-as-dir trick. Create a regular
// file at `${root}/blocker`, then point GBRAIN_AUDIT_DIR at
Expand Down
10 changes: 10 additions & 0 deletions test/dream-patterns-leftover-cap-9708.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import type { OperationContext } from '../src/core/ops/contract.ts';
import { runPhasePatterns } from '../src/core/cycle/patterns.ts';
import * as journal from '../src/core/persistence/journal.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { outstandingAdmissionWindow } from '../src/core/persistence/limits.ts';
import { repairAdmissionWindow } from '../src/core/repair/settle.ts';
import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';
import { durableGitRepo } from './helpers/git-publication.ts';
import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
Expand Down Expand Up @@ -129,5 +131,13 @@ for (const backend of testBackends()) {
expect(watch.admitted().sort()).toEqual(LEFTOVER.filter(slug => !afterFirst.includes(slug)));
expect(Math.max(...watch.sizes())).toBeLessThanOrEqual(CAP);
}, { databaseUrl, setup }), 180_000);

test('repairs and maintenance batches share one window: half the cap, at least 1 and at most 64', () => managedBrain(async ({ engine }) => {
for (const [cap, window] of [[8, 4], [1, 1], [200, 64]]) {
await engine.setConfig('persistence.limits.principal_outstanding', String(cap));
expect(await outstandingAdmissionWindow(engine)).toBe(window);
expect(await repairAdmissionWindow(engine)).toBe(window);
}
}, { databaseUrl, setup }), 180_000);
});
}
13 changes: 13 additions & 0 deletions test/publish-redact-unpushed-gst2988.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { finishRedactions, secretPublishMaintenance, settlePublishRedactions } from '../src/core/git/redact-finish.ts';
import { reveal, seal } from '../src/core/secret-store/store.ts';
import { computeIsoWeekFilename } from '../src/core/audit/audit-writer.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { withEnv } from './helpers/with-env.ts';

Expand Down Expand Up @@ -87,6 +88,11 @@ describe('GST-2988 a publish redacts unpushed secrets', () => {
expect(result.outcome).toBe('pushed');
expect(result.redaction).toMatchObject({ values: 1, rebuilt: 2, old_head: old, held: [], spooled: 1 });
expect(result.notices?.map(n => n.code)).toEqual(['publish_secret_redacted', 'secret_store_spooled']);
const spooledNotice = result.notices!.find(n => n.code === 'secret_store_spooled')!;
expect(spooledNotice.kind).toBe('info');
expect(spooledNotice.why).toStartWith('1 original(s) were sealed in this machine\'s encrypted spool');
expect(spooledNotice.why).toContain('gbrain git commit-push does not move them itself');
expect(spooledNotice.why).not.toContain('could not be written');
expect(remoteTip(r)).toBe(git(r.root, 'rev-parse', 'HEAD'));
expectRemoteClean(r);
const file = readFileSync(join(r.root, 'notes.md'), 'utf8');
Expand Down Expand Up @@ -431,10 +437,17 @@ for (const [arm, databaseUrl] of [['pglite', undefined], ...(PG_URL ? [['postgre
test("a page write's Git effect publishes redacted: the store holds the original, the database page holds the same marker", async () => {
const c = managedCheckout();
await managedWrite(c, databaseUrl, async w => {
const auditFile = join(c.home, 'audit', computeIsoWeekFilename('secret-spans'));
mkdirSync(join(c.home, 'audit'), { recursive: true });
writeFileSync(auditFile, '', { mode: 0o644 });
chmodSync(auditFile, 0o644);
await w.runEffects();
expect(await w.effect()).toMatchObject({ state: 'committed', error_code: null });
expect(git(c.remote, 'rev-parse', 'refs/heads/main')).toBe(git(c.root, 'rev-parse', 'HEAD'));
managedRemoteClean(c);
expect(readFileSync(auditFile, 'utf8')).toContain('"kind":"publish-redact"');
expect(readFileSync(auditFile, 'utf8')).not.toContain(token);
expect(statSync(auditFile).mode & 0o777).toBe(0o600);
const marker = MARKER.exec(readFileSync(join(c.root, 'notes/beta-example.md'), 'utf8'))!;
const page = (await w.engine.getPage('notes/beta-example', { sourceId: w.sourceId }))!;
expect(page.compiled_truth).not.toContain(token);
Expand Down
16 changes: 16 additions & 0 deletions test/refresh-publish-diverged-7686.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,22 @@ test('setting on: a refusal after the publish says the local commits were alread
expect(error.message).toContain(`already published the checkout's 1 local commit(s) merged with the upstream as ${remoteHead(f)}`);
}), 120_000);

test('setting on: a local commit that lands after the refresh published the first one is published on a retry, never refused as needing the user', () => each(async f => {
const first = diverge(f);
await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');
const committing = join(bin, `gbrain-commit-after-${f.engine.kind}`);
const marker = join(bin, `committed-after-${f.engine.kind}`);
writeFileSync(committing, `#!/bin/sh\n'${childCli}' "$@"; rc=$?\nif [ ! -e '${marker}' ]; then : > '${marker}'; printf '%s' '${page('Second', 'A second local commit made while the refresh ran.')}' > '${join(f.root, 'beta/second.md')}' && git -C '${f.root}' add beta/second.md && git -C '${f.root}' commit -qm 'second local commit' || exit 98; fi\nexit $rc\n`);
chmodSync(committing, 0o755);
const done = await withEnv({ GBRAIN_JOB_CHILD_CLI: committing }, () => refreshWorktree(f.engine, f.alpha));
expect(done).toMatchObject({ status: 'completed', published: { local_commits: 1 } });
expect(done.published!.sha).toBe(remoteHead(f));
expect(f.head()).toBe(remoteHead(f));
git(f.root, 'merge-base', '--is-ancestor', first, 'HEAD');
expect(readFileSync(join(f.root, 'beta/second.md'), 'utf8')).toContain('A second local commit made while the refresh ran.');
expect(git(f.root, 'ls-tree', '-r', '--name-only', remoteHead(f))).toContain('beta/second.md');
}), 120_000);

test('setting on: the publish runs in a child gbrain, never in this process, so an unusable child refuses and nothing is pushed or fenced', () => each(async f => {
const local = diverge(f);
const remote = remoteHead(f);
Expand Down
Loading