Skip to content
Merged
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: 17 additions & 0 deletions src/domain/interfaces/ITrailerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,21 @@ export interface ITrailerService {
* @returns Array of commits with matching trailers.
*/
queryTrailers(key: string, options?: ITrailerQueryOptions): ICommitTrailers[];

/**
* Amend HEAD commit to append AI-* trailers to the commit message.
* Preserves existing trailers and skips duplicates.
* @param trailers - Trailers to add.
* @param cwd - Working directory.
*/
addTrailers(trailers: readonly ITrailer[], cwd?: string): void;

/**
* Build a commit message with trailers appended.
* Pure string operation — no git commands.
* @param message - Original commit message.
* @param trailers - Trailers to append.
* @returns Complete commit message with trailer block.
*/
buildCommitMessage(message: string, trailers: readonly ITrailer[]): string;
}
2 changes: 2 additions & 0 deletions src/infrastructure/di/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { IGitClient } from '../../domain/interfaces/IGitClient';
import { NotesService } from '../services/NotesService';
import { GitClient } from '../git/GitClient';
import { MemoryRepository } from '../repositories/MemoryRepository';
import { TrailerService } from '../services/TrailerService';
import { EventBus } from '../events/EventBus';
import { createLogger } from '../logging/factory';
import { createLLMClient } from '../llm/LLMClientFactory';
Expand Down Expand Up @@ -55,6 +56,7 @@ export function createContainer(options?: IContainerOptions): AwilixContainer<IC
notesService: asClass(NotesService).singleton(),
gitClient: asClass(GitClient).singleton(),
memoryRepository: asClass(MemoryRepository).singleton(),
trailerService: asClass(TrailerService).singleton(),

eventBus: asFunction(() => {
const bus = new EventBus(container.cradle.logger);
Expand Down
2 changes: 2 additions & 0 deletions src/infrastructure/di/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ import type { ILiberateService } from '../../application/interfaces/ILiberateSer
import type { IMemoryContextLoader } from '../../domain/interfaces/IMemoryContextLoader';
import type { IContextFormatter } from '../../domain/interfaces/IContextFormatter';
import type { ISessionCaptureService } from '../../domain/interfaces/ISessionCaptureService';
import type { ITrailerService } from '../../domain/interfaces/ITrailerService';

export interface ICradle {
// Infrastructure
logger: ILogger;
notesService: INotesService;
gitClient: IGitClient;
memoryRepository: IMemoryRepository;
trailerService: ITrailerService;
triageService: IGitTriageService;
llmClient: ILLMClient | null;
eventBus: IEventBus;
Expand Down
55 changes: 55 additions & 0 deletions src/infrastructure/services/TrailerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,61 @@ export class TrailerService implements ITrailerService {
}
}

addTrailers(trailers: readonly ITrailer[], cwd?: string): void {
// Only operate on AI-* trailers to match readTrailers/parseTrailerBlock behavior.
const aiTrailers = trailers.filter(t => t.key.startsWith(AI_TRAILER_PREFIX));
if (aiTrailers.length === 0) return;

// Read existing trailers to avoid duplicates
const existing = this.readTrailers('HEAD', cwd);
const existingKeys = new Set(existing.map(t => `${t.key}:${t.value}`));
const newTrailers = aiTrailers.filter(t => !existingKeys.has(`${t.key}:${t.value}`));
if (newTrailers.length === 0) return;

// Get current commit message
const currentMessage = execFileSync(
'git',
['log', '-1', '--format=%B', 'HEAD'],
{ encoding: 'utf8', cwd, stdio: ['pipe', 'pipe', 'pipe'] }
).trimEnd();

// Build amended message with new trailers
const amended = this.buildCommitMessage(currentMessage, newTrailers);

// Amend HEAD with the new message
execFileSync(
'git',
['commit', '--amend', '--no-edit', '-m', amended],
{ encoding: 'utf8', cwd, stdio: ['pipe', 'pipe', 'pipe'] }
);
}

buildCommitMessage(message: string, trailers: readonly ITrailer[]): string {
if (trailers.length === 0) return message;

const trailerBlock = this.formatTrailers(trailers);
const trimmed = message.trimEnd();

// Detect existing trailer block: lines after the last blank line
// must all match "Key: Value" format (git trailer convention).
if (this.hasTrailerBlock(trimmed)) {
return `${trimmed}\n${trailerBlock}\n`;
}

return `${trimmed}\n\n${trailerBlock}\n`;
}

private hasTrailerBlock(message: string): boolean {
const lastBlankIdx = message.lastIndexOf('\n\n');
if (lastBlankIdx === -1) return false;

const afterBlank = message.slice(lastBlankIdx + 2).trim();
if (!afterBlank) return false;

const lines = afterBlank.split('\n').filter(l => l.trim().length > 0);
return lines.length > 0 && lines.every(l => /^[\w-]+:\s/.test(l));
}

private parseTrailerBlock(block: string): ITrailer[] {
const trailers: ITrailer[] = [];
const lines = block.split('\n');
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/infrastructure/di/container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('createContainer', () => {
assert.ok(cradle.notesService);
assert.ok(cradle.gitClient);
assert.ok(cradle.memoryRepository);
assert.ok(cradle.trailerService);
assert.ok(cradle.eventBus);
assert.ok(cradle.triageService);
assert.ok(cradle.memoryService);
Expand Down Expand Up @@ -162,6 +163,24 @@ describe('createContainer', () => {
});
});

describe('trailerService', () => {
it('should resolve with expected interface', () => {
const container = createContainer();
const { trailerService } = container.cradle;

assert.equal(typeof trailerService.readTrailers, 'function');
assert.equal(typeof trailerService.formatTrailers, 'function');
assert.equal(typeof trailerService.queryTrailers, 'function');
Copy link

Copilot AI Feb 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test block claims to check the resolved TrailerService interface, but it only asserts the pre-existing methods. Since ITrailerService now includes addTrailers and buildCommitMessage, either add assertions for those methods too or rename the test to avoid going stale/misleading.

Suggested change
assert.equal(typeof trailerService.queryTrailers, 'function');
assert.equal(typeof trailerService.queryTrailers, 'function');
assert.equal(typeof trailerService.addTrailers, 'function');
assert.equal(typeof trailerService.buildCommitMessage, 'function');

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — added assertions for addTrailers and buildCommitMessage to the container interface test. See 8fcd93f.

assert.equal(typeof trailerService.addTrailers, 'function');
assert.equal(typeof trailerService.buildCommitMessage, 'function');
});

it('should return singleton within container scope', () => {
const container = createContainer();
assert.equal(container.cradle.trailerService, container.cradle.trailerService);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
});

describe('hook services', () => {
it('should resolve hook services with expected interfaces', () => {
const container = createContainer();
Expand Down
146 changes: 146 additions & 0 deletions tests/unit/infrastructure/services/TrailerService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,150 @@ describe('TrailerService', () => {
assert.equal(results.length, 0);
});
});

describe('buildCommitMessage', () => {
it('should append trailers with blank line separator', () => {
const result = service.buildCommitMessage('feat: add auth', [
{ key: 'AI-Decision', value: 'Use JWT' },
]);
assert.equal(result, 'feat: add auth\n\nAI-Decision: Use JWT\n');
});

it('should append multiple trailers', () => {
const result = service.buildCommitMessage('feat: add auth', [
{ key: 'AI-Decision', value: 'Use JWT' },
{ key: 'AI-Confidence', value: 'high' },
]);
assert.equal(result, 'feat: add auth\n\nAI-Decision: Use JWT\nAI-Confidence: high\n');
});

it('should append after existing trailers without extra blank line', () => {
const msg = 'feat: add auth\n\nCo-Authored-By: Someone <s@e.com>';
const result = service.buildCommitMessage(msg, [
{ key: 'AI-Decision', value: 'Use JWT' },
]);
assert.equal(
result,
'feat: add auth\n\nCo-Authored-By: Someone <s@e.com>\nAI-Decision: Use JWT\n'
);
});

it('should handle message with body and no existing trailers', () => {
const msg = 'feat: add auth\n\nAdded JWT-based auth flow.';
const result = service.buildCommitMessage(msg, [
{ key: 'AI-Decision', value: 'Use JWT' },
]);
assert.equal(
result,
'feat: add auth\n\nAdded JWT-based auth flow.\n\nAI-Decision: Use JWT\n'
);
});

it('should return original message when trailers array is empty', () => {
assert.equal(service.buildCommitMessage('feat: add auth', []), 'feat: add auth');
});

it('should handle trailing whitespace in message', () => {
const result = service.buildCommitMessage('feat: add auth \n\n', [
{ key: 'AI-Fact', value: 'test' },
]);
assert.equal(result, 'feat: add auth\n\nAI-Fact: test\n');
});
});

describe('addTrailers', () => {
let writeRepoDir: string;

before(() => {
writeRepoDir = mkdtempSync(join(tmpdir(), 'git-mem-trailer-write-'));
git(['init'], writeRepoDir);
git(['config', 'user.email', 'test@test.com'], writeRepoDir);
git(['config', 'user.name', 'Test User'], writeRepoDir);
});

after(() => {
rmSync(writeRepoDir, { recursive: true, force: true });
});

it('should amend HEAD with new trailers', () => {
writeFileSync(join(writeRepoDir, 'a.txt'), 'content');
git(['add', '.'], writeRepoDir);
git(['commit', '-m', 'feat: initial'], writeRepoDir);

service.addTrailers(
[{ key: 'AI-Decision', value: 'Use Redis' }],
writeRepoDir
);

const trailers = service.readTrailers('HEAD', writeRepoDir);
const decision = trailers.find(t => t.key === 'AI-Decision');
assert.ok(decision);
assert.equal(decision.value, 'Use Redis');
});

it('should preserve existing trailers', () => {
writeFileSync(join(writeRepoDir, 'b.txt'), 'content');
git(['add', '.'], writeRepoDir);
const msg = 'feat: with trailer\n\nAI-Gotcha: Watch out for nulls';
git(['commit', '-m', msg], writeRepoDir);

service.addTrailers(
[{ key: 'AI-Confidence', value: 'high' }],
writeRepoDir
);

const trailers = service.readTrailers('HEAD', writeRepoDir);
assert.ok(trailers.find(t => t.key === 'AI-Gotcha'));
assert.ok(trailers.find(t => t.key === 'AI-Confidence'));
});

it('should not duplicate existing trailers', () => {
writeFileSync(join(writeRepoDir, 'c.txt'), 'content');
git(['add', '.'], writeRepoDir);
const msg = 'feat: dup test\n\nAI-Decision: Use Redis';
git(['commit', '-m', msg], writeRepoDir);

service.addTrailers(
[{ key: 'AI-Decision', value: 'Use Redis' }],
writeRepoDir
);

const trailers = service.readTrailers('HEAD', writeRepoDir);
const decisions = trailers.filter(t => t.key === 'AI-Decision');
assert.equal(decisions.length, 1);
});

it('should be a no-op when trailers array is empty', () => {
writeFileSync(join(writeRepoDir, 'd.txt'), 'content');
git(['add', '.'], writeRepoDir);
git(['commit', '-m', 'feat: empty test'], writeRepoDir);
const shaBefore = git(['rev-parse', 'HEAD'], writeRepoDir);

service.addTrailers([], writeRepoDir);

const shaAfter = git(['rev-parse', 'HEAD'], writeRepoDir);
assert.equal(shaBefore, shaAfter);
});

it('should add multiple trailers at once', () => {
writeFileSync(join(writeRepoDir, 'e.txt'), 'content');
git(['add', '.'], writeRepoDir);
git(['commit', '-m', 'feat: multi trailer'], writeRepoDir);

service.addTrailers(
[
{ key: 'AI-Decision', value: 'Use PostgreSQL' },
{ key: 'AI-Confidence', value: 'high' },
{ key: 'AI-Tags', value: 'db, infrastructure' },
],
writeRepoDir
);

const trailers = service.readTrailers('HEAD', writeRepoDir);
assert.equal(trailers.length, 3);
assert.ok(trailers.find(t => t.key === 'AI-Decision'));
assert.ok(trailers.find(t => t.key === 'AI-Confidence'));
assert.ok(trailers.find(t => t.key === 'AI-Tags'));
});
});
});