Skip to content
Draft
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
5 changes: 5 additions & 0 deletions specification/tracker-native-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ operator verifies the stopped database and chooses a rollback.
GitHub sources. It uses the existing source owner, cursor, and
`adapter-runner.lock` beside the journal. The GitHub CLI binding uses an
explicit, private account directory and the existing `tracked` label.
Each normal poll also lists all open issues with that label, independent
of the intake watermark. Chief of Staff receives one alert per issue
without a durable link to an existing, nondeleted Tracker item. Completed
items still count. A successful sweep clears the alert when the link
becomes valid or the issue leaves the open, tracked set.
- **Dispatch watchdog.** A dispatch tick has two minutes to finish.
On timeout the scheduler cancels that tick and resumes polling. The
next tick reconciles reservations for which a host start may have
Expand Down
12 changes: 12 additions & 0 deletions src/repositories/projects-sessions/TrackerAdapterRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ export class TrackerAdapterRepository {
.get(sourceId, externalId) as TrackerAdapterLink | undefined;
}

hasLiveIssueLink(sourceId: string, externalId: string): boolean {
return Boolean(
this.database
.prepare(
`SELECT 1 FROM adapter_links AS link JOIN items AS item ON item.id = link.item_id
WHERE link.source_id = ? AND link.external_id = ?
AND item.deleted = 0 AND item.title IS NOT NULL`
)
.get(sourceId, externalId)
);
}

linkByKey(sourceId: string, key: string): TrackerAdapterLink | undefined {
return this.database
.prepare(
Expand Down
45 changes: 8 additions & 37 deletions src/services/projects-sessions/TrackerAdapterPollService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import type {
TrackerAdapterPollDependencies,
TrackerAdapterPollOptions,
TrackerAdapterPollResult,
TrackerAdapterReadQuery,
TrackerAdapterWriteError
TrackerAdapterReadQuery
} from './TrackerAdapterPollService.types';
import type { TrackerPersistenceService } from './TrackerPersistenceService';
import type { TrackerAdapterOwner } from './tracker-adapter-poll-service/manageTrackerAdapterSource.types';
Expand All @@ -18,9 +17,10 @@ import {
readTrackerIssues
} from './tracker-adapter-poll-service/readTrackerIntake';
import { unlinkedRepository } from './tracker-adapter-poll-service/manageTrackerAdapterSource';
import { completeTrackerGithubPoll } from './tracker-adapter-poll-service/reconcileTrackedGithubIssues';
import {
assertTrackerPollActive,
TrackerAdapterPollError
trackerAdapterPollFailure
} from './tracker-adapter-poll-service/trackerAdapterPollError';

export type {
Expand All @@ -38,8 +38,6 @@ export type {

const overlapMs = 5_000;
const commentBackfillMs = 7 * 86_400_000;
const intakeError = 'Tracker adapter intake failed';
const writeBackError = 'Tracker adapter write-back failed';

/** Poll one persisted source while holding the injected owner's exclusive lease. */
export class TrackerAdapterPollService {
Expand Down Expand Up @@ -142,14 +140,14 @@ export class TrackerAdapterPollService {
const result = await pollIntake(context, source, query, { dryRun, commentsOnly });
if (dryRun || commentsOnly) return { ...result, synced_back: 0, sync_errors: [] };
this.sources.advance(source.id, startedAt);
const sync = await syncBack(context, source, signal);
assertTrackerPollActive(signal);
const sync = await completeTrackerGithubPoll(context, source, signal);
this.sources.recordRun(source.id, this.now(), sync.sync_errors[0]?.error ?? null);
return { ...result, ...sync };
} catch {
} catch (error) {
assertTrackerPollActive(signal);
if (!dryRun && !commentsOnly) this.sources.recordRun(source.id, this.now(), intakeError);
throw new TrackerAdapterPollError(intakeError);
const failure = trackerAdapterPollFailure(error instanceof Error ? error : undefined);
if (!dryRun && !commentsOnly) this.sources.recordRun(source.id, this.now(), failure.message);
throw failure;
}
}

Expand Down Expand Up @@ -184,30 +182,3 @@ async function pollIntake(
events: issues.events + comments.events
};
}

async function syncBack(
{ dependencies, repository }: TrackerAdapterIntakeContext,
source: TrackerAdapterSource,
signal: AbortSignal
) {
const { provider, hasStarted } = dependencies;
const sync_errors: TrackerAdapterWriteError[] = [];
let synced_back = 0;
if (!provider.markTracked || !hasStarted) return { synced_back, sync_errors };
for (const link of repository.pending(source.id)) {
assertTrackerPollActive(signal);
const item = repository.item(link.item_id);
if (!item || item.deleted) continue;
try {
if (!hasStarted(item.id)) continue;
await provider.markTracked(source, link.external_key, signal);
assertTrackerPollActive(signal);
repository.acknowledgeWrite(link);
synced_back++;
} catch {
assertTrackerPollActive(signal);
sync_errors.push({ external_id: link.external_id, error: writeBackError });
}
}
return { synced_back, sync_errors };
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ export interface TrackerGithubAdapterProvider {
source: Readonly<TrackerAdapterSource>,
query: TrackerAdapterReadQuery
): AsyncIterable<TrackerGithubIssue>;
/** Read every open issue labeled tracked independently of the intake watermark. */
readTrackedIssues?(
source: Readonly<TrackerAdapterSource>,
signal: AbortSignal
): Promise<readonly TrackerGithubIssue[]>;
readIssue?(
source: Readonly<TrackerAdapterSource>,
issue: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// @harness-uid u_wlip653voz
import type { TrackerAdapterSource } from '../../../repositories/projects-sessions/TrackerAdapterRepository.types';
import type {
TrackerAdapterIntakeContext,
TrackerAdapterWriteError,
TrackerGithubAdapterProvider,
TrackerGithubIssue
} from '../TrackerAdapterPollService.types';
import { missingTrackedGithubItemKind } from '../tracker-native-runtime-service/trackerCosInbox';
import { recordWatchdogAlert } from '../tracker-native-runtime-service/trackerHostWatchdogAlerts';
import { readWatchdogAlerts } from '../tracker-native-runtime-service/trackerHostWatchdogState';
import {
assertTrackerPollActive,
githubReconciliationError,
TrackerAdapterPollError
} from './trackerAdapterPollError';

const writeBackError = 'Tracker adapter write-back failed';

export async function completeTrackerGithubPoll(
context: TrackerAdapterIntakeContext,
source: TrackerAdapterSource,
signal: AbortSignal
) {
const synced = await syncBack(context, source, signal);
await reconcileTrackedGithubIssues(context, source, signal);
assertTrackerPollActive(signal);
return synced;
}

async function reconcileTrackedGithubIssues(
{ dependencies, repository, store }: TrackerAdapterIntakeContext,
source: TrackerAdapterSource,
signal: AbortSignal
): Promise<void> {
const issues = await readTrackedIssues(dependencies.provider, source, signal);
if (!issues) return;
assertTrackerPollActive(signal);
const prefix = `${missingTrackedGithubItemKind}:${source.id}:`;
const active = new Set<string>();
const now = (dependencies.now ?? Date.now)();
for (const issue of issues) {
if (!isOpenTrackedIssue(issue) || repository.hasLiveIssueLink(source.id, String(issue.id)))
continue;
const key = `${prefix}${issue.id}`;
if (active.has(key)) continue;
active.add(key);
const url = `https://github.com/${source.target}/issues/${issue.number}`;
recordWatchdogAlert(
store,
{
itemId: 'unknown',
kind: missingTrackedGithubItemKind,
key,
identity: key,
reason: `GitHub issue has a tracked label but no live Tracker item: ${url}`,
localOnly: true
},
now
);
}
const alerts = Object.entries(readWatchdogAlerts(store));
const remaining = alerts.filter(([key]) => !key.startsWith(prefix) || active.has(key));
if (remaining.length !== alerts.length)
store.writeMeta({ watchdog_alerts: JSON.stringify(Object.fromEntries(remaining)) });
}

async function readTrackedIssues(
provider: TrackerGithubAdapterProvider,
source: TrackerAdapterSource,
signal: AbortSignal
) {
try {
return await provider.readTrackedIssues?.(source, signal);
} catch {
throw new TrackerAdapterPollError(githubReconciliationError);
}
}

function isOpenTrackedIssue(issue: TrackerGithubIssue): boolean {
return (
issue.state === 'open' &&
!issue.pull_request &&
issue.labels.some(({ name }) => name.toLowerCase() === 'tracked')
);
}

async function syncBack(
{ dependencies, repository }: TrackerAdapterIntakeContext,
source: TrackerAdapterSource,
signal: AbortSignal
) {
const { provider, hasStarted } = dependencies;
const sync_errors: TrackerAdapterWriteError[] = [];
let synced_back = 0;
if (!provider.markTracked || !hasStarted) return { synced_back, sync_errors };
for (const link of repository.pending(source.id)) {
assertTrackerPollActive(signal);
const item = repository.item(link.item_id);
if (!item || item.deleted) continue;
try {
if (!hasStarted(item.id)) continue;
await provider.markTracked(source, link.external_key, signal);
assertTrackerPollActive(signal);
repository.acknowledgeWrite(link);
synced_back++;
} catch {
assertTrackerPollActive(signal);
sync_errors.push({ external_id: link.external_id, error: writeBackError });
}
}
return { synced_back, sync_errors };
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// @harness-uid u_wlip653voz
export const githubReconciliationError = 'Tracker GitHub reconciliation failed';

export class TrackerAdapterPollError extends Error {
constructor(message: string) {
super(message);
Expand All @@ -9,3 +11,11 @@ export class TrackerAdapterPollError extends Error {
export function assertTrackerPollActive(signal: AbortSignal): void {
if (signal.aborted) throw new TrackerAdapterPollError('Tracker adapter poll cancelled');
}

export function trackerAdapterPollFailure(error?: Error): TrackerAdapterPollError {
const message =
error instanceof TrackerAdapterPollError && error.message === githubReconciliationError
? githubReconciliationError
: 'Tracker adapter intake failed';
return new TrackerAdapterPollError(message);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
// @harness-uid u_bl6xl2h4a3
export const missingTrackedGithubItemKind = 'missing-tracked-github-item';

/** What a script or session sent to Chief of Staff itself, as opposed to a session-health check. */
export const trackerCosInboxKinds: ReadonlySet<string> = new Set([
'alert',
'flag-refused',
'cos-message'
'cos-message',
missingTrackedGithubItemKind
]);

/** How long a message stays in the inbox when its item is finished or unknown. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export function trackerGithubCli(binding: {
: [];
yield* new Map([...older, ...recent].map((issue) => [issue.id, issue])).values();
},
async readTrackedIssues({ target }, signal) {
const query = `repos/${target}/issues?state=open&labels=${tracked}&per_page=100`;
return (await read(query, signal)).map((issue) => adapterIssue.parse(issue));
},
readIssue: ({ target }, issue, signal) => readTrackerIssue(request, { target, issue }, signal),
async readTimeline({ target }, issue, signal) {
return adapterTimeline.parse(
Expand Down
3 changes: 3 additions & 0 deletions test/services/projects-sessions/tracker-adapter-poll.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test, vi } from 'vitest';
import { proveTrackedGithubReconciliation } from '../../support/trackerReconciliationFixture';
import {
adapterFixture,
adapterFollowUpFixture,
Expand All @@ -7,6 +8,8 @@ import {
readFollowUpFixtureItems
} from '../../support/trackerAdapterFixture';

test('poll routes missing items to CoS', proveTrackedGithubReconciliation);

test('poll dry-run deduplicates explicit backfill without moving the source cursor', async () => {
const { database, feed, readIssues, readTimeline, service, store } = adapterFixture({
redactText: (text) => text.replace('fixture-private', '[redacted]')
Expand Down
10 changes: 5 additions & 5 deletions test/support/trackerAdapterFixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,26 @@ export function adapterFixture(options: TrackerAdapterFixtureOptions = {}) {
});
const ids = () =>
['fixture-001', 'fixture-002', 'fixture-003'][runtime.store.maxSeq()] ?? 'fixture-004';
const provider = { readIssues, readIssue, readTimeline, readComments, markTracked };
const runtime: TrackerNativeRuntimeService = new TrackerNativeRuntimeService(database, {
node,
role: 'spoke',
now: () => feed.now,
adapter: {
lease: options.lease ?? { owner: node, tryAcquire: () => () => {} },
provider: { readIssues, readIssue, readTimeline, readComments, markTracked },
provider: { ...options.provider, ...provider },
redactText: options.redactText ?? ((text) => text),
intakePolicy: options.intakePolicy,
now: () => feed.now,
itemId: ids,
hasStarted: () => feed.started
}
});
const { adapter: service, store, items } = runtime;
seedLegacySource(database);
return {
service: service!,
store,
items,
service: runtime.adapter!,
store: runtime.store,
items: runtime.items,
database,
feed,
readIssues,
Expand Down
2 changes: 2 additions & 0 deletions test/support/trackerAdapterFixture.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { DatabaseSync } from 'node:sqlite';
import type {
TrackerAdapterLease,
TrackerAdapterPollDependencies,
TrackerGithubAdapterProvider,
TrackerGithubComment,
TrackerGithubIssue,
TrackerGithubTimelineEvent
Expand All @@ -11,6 +12,7 @@ export interface TrackerAdapterFixtureOptions {
node?: string;
lease?: TrackerAdapterLease;
database?: DatabaseSync;
provider?: Partial<TrackerGithubAdapterProvider>;
redactText?: TrackerAdapterPollDependencies['redactText'];
intakePolicy?: TrackerAdapterPollDependencies['intakePolicy'];
}
Expand Down
Loading
Loading