Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/stores/bare-git/bare-git-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,16 +255,23 @@ export const createBareGitStore = (repoDir: string, opts: BareGitStoreOptions =
if (!s) return { results: [] };
// -o = one line per occurrence -> occurrence count; -F -i mirror the contract.
const grep = await git.tryRun(
['grep', '-o', '-I', '-i', '-F', '--no-color', '--threads=2', '-e', q, s.version],
['grep', '-z', '-o', '-I', '-i', '-F', '--no-color', '--threads=2', '-e', q, s.version],
{ timeoutMs: SEARCH_TIMEOUT_MS }
);
if (!grep) return { results: [] }; // exit 1 = no match; an infra failure already threw
const counts = new Map<string, number>();
for (const line of grep.split('\n')) {
if (!line) continue;
const rest = line.slice(line.indexOf(':') + 1);
const path = rest.slice(0, rest.indexOf(':'));
// With -z, a record is "revision:path\0matched-text\n", so file names
// containing Unicode, quotes, or newlines are never C-quoted or split.
for (let cursor = 0; cursor < grep.length;) {
const sep = grep.indexOf('\0', cursor);
if (sep < 0) break;
const end = grep.indexOf('\n', sep + 1);
if (end < 0) break;
const label = grep.slice(cursor, sep);
const colon = label.indexOf(':');
const path = colon < 0 ? '' : label.slice(colon + 1);
if (path) counts.set(path, (counts.get(path) ?? 0) + 1);
cursor = end + 1;
}
// grep already yields every ranking input (path, occurrences, mtime), so the
// page is decided before any blob is read - one page of docs, not one per match.
Expand Down
36 changes: 21 additions & 15 deletions src/stores/bare-git/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,23 @@ const ISO_LINE = /^\d{4}-\d\d-\d\dT/;
// newest-first, so the first mention of a path wins.
const datesFrom = async (git: GitRunner, range: string): Promise<Map<string, string>> => {
const mtimes = new Map<string, string>();
const log = await git.tryRun(['log', '--format=%cI', '--name-only', range]);
// -z preserves UTF-8 path bytes and newlines inside filenames. Git emits a
// separator newline before each path record; strip only that separator.
const log = await git.tryRun(['log', '-z', '--format=%cI', '--name-only', range]);
if (!log) return mtimes;
let date = '';
for (const line of log.split('\n')) {
if (line === '') continue;
for (const record of log.split('\0')) {
const line = record.startsWith('\n') ? record.slice(1) : record;
if (!line) continue;
if (ISO_LINE.test(line)) date = line.trim();
else if (!mtimes.has(line)) mtimes.set(line, date);
}
return mtimes;
};

export const buildSnapshot = async (git: GitRunner, version: string): Promise<Snapshot> => {
const tree = await git.tryRun(['ls-tree', '-r', '--name-only', version]);
const paths = new Set((tree ?? '').split('\n').filter(Boolean));
const tree = await git.tryRun(['ls-tree', '-r', '--name-only', '-z', version]);
const paths = new Set((tree ?? '').split('\0').filter(Boolean));
return { version, paths, mtimes: await datesFrom(git, version) };
};

Expand All @@ -52,20 +55,23 @@ export const driftChanges = async (
next: string
): Promise<DriftChange[]> => {
if (!old) {
const tree = await git.tryRun(['ls-tree', '-r', '--name-only', next]);
const tree = await git.tryRun(['ls-tree', '-r', '--name-only', '-z', next]);
return (tree ?? '')
.split('\n')
.split('\0')
.filter(Boolean)
.map((path) => ({ path, deleted: false }));
}
const out = await git.tryRun(['diff', '--name-status', '--no-renames', old, next]);
return (out ?? '')
.split('\n')
.filter(Boolean)
.map((line) => {
const tab = line.indexOf('\t');
return { path: line.slice(tab + 1), deleted: line.slice(0, tab) === 'D' };
});
// -z emits status and raw path as consecutive NUL-terminated records.
const out = await git.tryRun(['diff', '--name-status', '--no-renames', '-z', old, next]);
const fields = (out ?? '').split('\0').filter(Boolean);
const changes: DriftChange[] = [];
for (let i = 0; i + 1 < fields.length; i += 2) {
const status = fields[i];
const path = fields[i + 1];
if (status === undefined || path === undefined) continue;
changes.push({ path, deleted: status === 'D' });
}
return changes;
};

// Move a snapshot to `version` using the diff the drift check already paid for:
Expand Down
4 changes: 2 additions & 2 deletions src/stores/bare-git/stats-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ export const computeVaultStats = async (
version: string | null
): Promise<VaultStats> => {
if (!version) return EMPTY;
const stdout = await runnerOf(target).tryRun(['ls-tree', '-r', '-t', '-l', version]);
const stdout = await runnerOf(target).tryRun(['ls-tree', '-r', '-t', '-l', '-z', version]);
if (stdout === null) return EMPTY;
let files = 0;
let folders = 0;
let sizeBytes = 0;
for (const line of stdout.split('\n')) {
for (const line of stdout.split('\0')) {
if (!line) continue;
const [, type, , size] = line.slice(0, line.indexOf('\t')).trim().split(/\s+/);
if (type === 'blob') {
Expand Down
4 changes: 2 additions & 2 deletions src/stores/bare-git/validate-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export const validateBareRepoTree = async (
): Promise<TreeViolation[]> => {
const ref = opts.ref ?? 'refs/heads/main';
const maxBytes = opts.maxBytes ?? MAX_DOC_BYTES;
const stdout = await createGitRunner(repoDir).run(['ls-tree', '-r', '-l', ref]);
const stdout = await createGitRunner(repoDir).run(['ls-tree', '-r', '-l', '-z', ref]);
const violations: TreeViolation[] = [];
for (const line of stdout.split('\n')) {
for (const line of stdout.split('\0')) {
if (!line) continue;
const tab = line.indexOf('\t');
const [mode, type, , size] = line.slice(0, tab).trim().split(/\s+/);
Expand Down
48 changes: 48 additions & 0 deletions test/stores/unicode-paths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { createBareGitStore, validateBareRepoTree } from '../../src/index.js';
import { externalCommit } from './external-git.js';

const ACCENTED_DIR = 'Área de exemplos sintéticos';
const ACCENTED_PATH = ACCENTED_DIR + '/Índice de ações.md';

const repoFor = async () => join(await mkdtemp(join(tmpdir(), 'agentage-unicode-')), 'vault.git');

describe('Git-backed memory: Unicode path regression', () => {
it('lists a committed accented filename with canonical Unicode and searches its content', async () => {
const repo = await repoFor();
const writer = createBareGitStore(repo);
await writer.write({ path: ACCENTED_PATH, body: 'CHAVEUNICODE7X9 resposta de teste' });
const fresh = createBareGitStore(repo);
const scoped = await fresh.list({ folder: ACCENTED_DIR, depth: 2 });
expect(scoped.files).toBe(1);
expect(scoped.entries.map((e) => e.path)).toContain(ACCENTED_PATH);
const found = await fresh.search({ query: 'CHAVEUNICODE7X9', limit: 5 });
expect(found.results.map((e) => e.path)).toContain(ACCENTED_PATH);
expect((await fresh.read(ACCENTED_PATH))?.body).toContain('CHAVEUNICODE7X9');
});

it('reconciles a Unicode path added and removed by an external push (drift)', async () => {
const repo = await repoFor();
const store = createBareGitStore(repo);
await store.write({ path: 'seed.md', body: 'ok' });
await store.list({});
await externalCommit(repo, [{ path: ACCENTED_PATH, content: 'drift Unicode' }]);
await store.refresh();
expect((await store.list({ folder: ACCENTED_DIR })).entries.map((e) => e.path)).toContain(
ACCENTED_PATH
);
await externalCommit(repo, [{ path: ACCENTED_PATH, remove: true }]);
await store.refresh();
expect((await store.list({ folder: ACCENTED_DIR })).entries).toEqual([]);
});

it('does not flag an otherwise safe UTF-8 filename in pre-receive tree validation', async () => {
const repo = await repoFor();
const store = createBareGitStore(repo);
await store.write({ path: ACCENTED_PATH, body: 'valid' });
expect(await validateBareRepoTree(repo)).toEqual([]);
});
});
Loading