mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-12 06:10:44 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Background services own future checks, retries, and recovery work. > - An idle tenant can stop only when a durable wake covers its remaining duties. > - The current alarm catalog covers several domains but leaves these owners blocked. > - A saved future timestamp alone cannot prove that reconstruction or admitted work has settled. > - This pull request binds durable domain snapshots to the actual registered worker revisions. > - The tenant can hand off supported future duties and retain all checks for uncertain or active work. ## Linked Issues or Issue Description No matching public issue was found. Related work: [domain deadline handoff #18656](https://github.com/paperclipai/paperclip/pull/18656), [owned blocker diagnostics #18632](https://github.com/paperclipai/paperclip/pull/18632), and [completed history proof #18646](https://github.com/paperclipai/paperclip/pull/18646). The separate [native idle-session change #18988](https://github.com/paperclipai/paperclip/pull/18988) covers runtime retirement. [Far-future retry re-probes #13534](https://github.com/paperclipai/paperclip/pull/13534) changes recovery responsiveness after an upstream success; this change preserves existing retry decisions. **What happened?** Future status-card, external-object, skill-sync, watchdog, retry, and quota duties lacked complete owner-bound coverage in the idle deadline proof. A completed quota task could also retain its monitor policy and timestamp and remain blocked after the scheduler had disarmed it. **Expected behavior** A settled registered owner can hand off its exact supported future deadline. Active work, dirty reconstruction, transaction uncertainty, changed revisions, claims, unknown state, and unsupported duties keep the tenant awake. Completed history retains its data and stops recurring work when the owner has no remaining duty. **Steps to reproduce** 1. Produce a supported future duty through its normal service. 2. Let the registered worker finish reconstruction and admitted work. 3. Request an owned idle report with the negotiated domain deadline catalog. 4. Check the saved earliest deadline and generation before durable alarm registration. 5. Stop and reconstruct the worker. Check that ordinary admission and claims resume useful work once due. 6. Complete a quota task. Keep its saved policy and timestamp. Check that linked unfinished work still blocks sleep and that settled history does not. **Paperclip version or commit** The owned patch was qualified at `699c8569fa34338dd75cdc5731381ec1e2efdb45`. Publication head `491fac368ee72eaac8ae105d53e6bf6b305d8a6a` normally merges actual master `039e0dad2c51c80251e1302a19c5566e039c357a`. All 43 owned files are byte-identical. All 29 new upstream paths are preserved. The later normal current-master integration is `8c912e1ba4fc66397a7341ade59373af8075068f`, described separately below. **Deployment mode** Source checkout with real PostgreSQL 17 and a controlled local Node process. No deployed alarm, tenant suspension, database suspension, or fleet result is claimed. ## What Changed - Add registered-worker reconciliation revisions and invalidate them on stop. - Keep status-card, external-object, and skill deadline interpretation with their owners. - Reuse the watchdog classifier against the supplied database snapshot. - Validate the exact saved retry run and paired queued wake. - Validate legacy quota source bindings and the current assignee or reviewer policy. - Preserve common issue scope, dependency, sibling, and state checks for covered waits. - Compose normalized owner snapshots within the existing bounded deadline proof and recheck revisions after inspection. - Bind actual service and worker instances from server startup. Missing bindings preserve existing blockers. - Retain completed quota policy and timestamps while independently rejecting linked unfinished runs or wakes. - Block unconsumed budget evaluation inputs through the owning queue predicate. Accounting policy and settlement stay unchanged. - Bind completed quota history through fixed-size UUID-array parameters, preserve exact company/task/source associations, and guard external references before the run-ID join. - Batch watchdog subtrees and shared classifier facts without changing the 64-query or two-second proof budget; preserve exact company pairing for first-run evidence. - Extend production-path regression controls and document supported coverage and limits. ## Verification Current integration head: `688abc6cac6016b9fb50e5832f81e2975ed5d49f`. Fresh exact-head checks completed with **58 successes, three intentional skips and one neutral review**, including aggregate `ci / verify`. The complete current Greptile review is **5/5**. The complete current Ponytail verdict is **Ship (4/5)**, with only optional cleanup of an unused MCP proof input; both prior correctness findings are resolved. All review threads and nested pages were inspected. The normal master merges preserve the registered retry deadline owner and current startup completion log after the same readiness await. The earlier focused evidence below remains tied to its tested source revisions. Current-master integration `8c912e1ba4fc66397a7341ade59373af8075068f`: - Normally merge actual master `46fb933b0155d183ce64a8bdc4950d1b58c926f6`. Every nonoverlapping tree blob retains its owning parent across 14,044 paths. All 42 owner-only files and 15 critical binding/proof/readiness files remain byte-identical. Three automatic overlaps preserve the existing watchdog binding, conservative unavailable-reader fallback and optional actual owner arguments. The two scoped-deadline conflicts retain the entire upstream resource-reservation/mid-pass admission/abort algorithm inside the existing reconciliation revision/running/failure fence, with both parent test sets. - Actual TypeScript 7.0.2 server noEmit passed in 9.434 seconds, normal source declaration layers in 12.102 seconds, and four selected test/helper/config layers extending the actual CI configuration in 3.167 seconds. No compiler option weakening, heap override, donor declarations or SDK replacement stub. - Focused PG0 controls passed: 102 scheduler/proof/owner controls in 16.451 seconds, including all 21 scoped-deadline cases; 121 startup controls; and all 107 unchanged instance-settings route cases in 6.456 seconds. The latter first hit a local prewire-guard listener-registration race. Only the ignored guard was corrected to register the same actual OS-bound server port immediately after native listen returns. Closed, unknown, foreign, offhost and PG destinations remain blocked. Original failure evidence is retained; product code and assertions were unchanged. - The exact current UI policy command now reports zero findings (0.362 seconds); its seven scanner controls pass. The earlier dependent PR used an old scanner/source baseline under a newly enforcing trusted workflow and reported 397 findings. Carrying the genuine current master resolves that mismatch without editing unrelated UI sites or relaxing the gate. - Every meaningful worker checked its executing PID/thread/preload hash and matching receipt. PG0 controls opened no PostgreSQL sockets; all owned processes exited. Original dependency-cache/DNS, ignored-harness syntax/type and guard failures remain separate from product results. - This is fresh semantic and focused runtime qualification, not a local whole-repository or current-head PostgreSQL acceptance rerun. The upstream workspace-busy parked-retry/terminal-holder notification path remains unchanged by this merge and needs its separate current-graph producer check. Historical six-case/scale results below stay tied to their measured sources. A matching controlled default-cadence follow-up is in #19191; no fresh current-head two-cycle or deployed suspension claim follows from this merge. - All 59 exact-head check contexts now pass (55 success, one neutral, three intentional skips), plus the legacy security status. The complete edited Greptile review is 5/5 for this exact commit, with all root/nested pages inspected and no unresolved threads. Ponytail stopped without completing its new turn; it supplied no new verdict or finding. Prior actual findings remain addressed. Earlier scores/checks below belong to their explicit earlier commits. On frozen clean merged source `699c8569fa`: - Real PostgreSQL acceptance: **6/6 passed**,83.483 seconds wall. Actual retry producer creates the exact saved run/wake; stopped and reconstructed owner resumes through current admission, one durable start, real local process output and normal task completion. Includes cancellation, drain arrival, retained quota history with queued-run/wake negatives, watchdog review settlement and budget-input empty/pending/consumed control using the actual owner. - Affected coordinator, deadline, scoped-deadline, recovery and composed-proof controls: **78/78 in five files passed**,32.114 seconds wall, worker 1/no file parallelism. - `pnpm exec tsc --noEmit -p server/tsconfig.json`: **passed**,17.467 seconds. Native TypeScript 7.0.2 and Node 24.22.2. - PostgreSQL tests use one dedicated test database, matching fixture/admin URLs, pool limit four, one worker, and no embedded fallback. Every run recorded unchanged source hashes and a clean checkout. - The eight-second real-clock retry is a domain execution check. It is below the Cloud minimum wake lead and is not a positive accepted hosted sleep cycle. - The completed quota-history product failure and original fixture/protocol failures were preserved; the owning-reader fix passed a real PostgreSQL red/green regression before the fresh merged six-case pass. - After runtime completion, the dedicated database had zero other clients and no owned runtime processes. All three qualification process PIDs exited. The coordinator independently audits and drops the database. - Comment-only cleanup has equal strict TypeScript parser ASTs across 15 files. The final lexical audit finds no added comments relative to actual master. `git diff --check` passed. - Earlier retry fixtures omitted responsible-user membership, advanced JavaScript time past the real PostgreSQL lease clock, or produced stdout without normal task completion. Corrected fixtures use real membership, an eight-second real deadline, and ordinary task comment/completion. The last case exposed legitimate disposition repair rather than duplicate retry promotion. - The quota and watchdog controls first ran before admitted work or the existing 30-second reconstruction duty settled. The stronger tests require an interim blocked report and then exact settled-owner proof. Production deadlines were not changed. The separate completed-quota-history defect was fixed in its reader and verified with linked unfinished-run and wake controls. - The status/object and skill owners reviewed the actual final startup, route and post-backup bindings. Their domain source evidence carries where token-equivalent. The master coordinator coalescing change was reviewed separately. Historical domain PostgreSQL results are not presented as fresh full-suite results on this head. The later master merge adds retry predecessor cleanup checks under the existing issue claim lock. The source audit confirms unchanged saved deadlines and run/wake identities. The three actual retry lifecycle/cancellation/drain cases passed on the batched candidate with this parent (31.817 seconds). Those local dependency controls preceded the current exact-head remote run. Native backup preservation and TestOps changes from master are retained. No pass is inferred for changed dependency behavior solely from unchanged owned files. Review repair published as `643f1e7400`: - The original reader returned `unknown` after seven actual watchdog reviews settled across seven companies. The unchanged composed-report regression passed after batching; the final reader passed in 61.841 seconds, including active queued-work and stopped-owner rejection. - A separate two-company red/green control rejects terminal-run context from another company as first-run grace evidence. Shared facts are serialized once, with per-root IDs and review summaries. - The affected recovery, proof and diagnostic unit controls passed 47/47 (14.575 seconds). Startup owner-contract fixtures passed 121/121 (10.589 seconds). - Diagnostic PostgreSQL controls passed7/7 (12.406 seconds), including the normal budget-input producer and its exact blocker reason. Initial empty-state setup uses the same cleanup as per-case teardown when a dedicated test database is reused. - Actual repository `pnpm exec tsc --noEmit -p server/tsconfig.json` passed 12.710 seconds with no heap override. Final source has no added code comments; whitespace checks pass. - The original query-budget failure, two-company discriminator, initial cross-suite fixture failure and an interrupted incorrect local-driver selector are retained separately. The interrupted run is not a pass. Independent cleanup found zero owned clients or runtime processes. Quota-scale repair published as `6696a37f8a`: - The exact 10,000-row completed-history case reproduced `MAX_PARAMETERS_EXCEEDED`:90,002 bound parameters exceeded the driver's 65,534 limit, and the composed report returned `unknown` despite settled owners. Original failure and actual driver diagnostics are retained. - Fixed pending-work queries use three typed UUID-array parameters plus the result limit, keeping exact company/issue/source tuple bindings. The primary run-ID column stays uncast; a guarded CASE validates the raw external reference before conversion. The 10,000-row cap and 64-query/two-second proof budget are unchanged. - The same 10,000-row composed-report case passed 18.860 seconds, with unfinished run/wake rejection, malformed-reference safety and conservative 10,001-row overflow. Its fixture derives retained history from the actual quota producer and normal task completion, expands valid persisted issue/source pairs, then starts the actual registered owners. - The existing actual quota producer case passed 14.187 seconds, including exact future deadline, retained completion history, unfinished work, real foreign-company source references and noncanonical/malformed references. - Affected owner/proof controls passed 22/22 (26.444 seconds). Production server noEmit passed 16.039 seconds. - CI on 643 identified TS7034/TS7005 in the settled-watchdog fixture's initially untyped collection. It is now explicitly typed. A separate affected-entry semantic check extending the repository's actual `server/src/__tests__/tsconfig.json` passed 15.093 seconds: six affected tests, two owner files, ambient declarations and current imported source, with unchanged strict/module/lib/path settings. The production server config excludes that test directory and is not presented as test-layer proof. No custom suppression or replacement SDK stub was added. - All runs were sequential with pool max 4, worker 1, source/config/command hashes and cleared inherited provider/LIVE/other-database variables. Cleanup found zero owned database clients or local runtime processes. At prior head `6696a37f8a5718cd0f79054969a0084462d41d47`, all required CI gates pass. The exact-head inventory has 55 successes, one neutral review and three intentional skips. Greptile is 5/5. The complete latest Ponytail verdict confirms the quota finding is fixed; its only remaining note is optional unused MCP proof state, not a behavior defect. All three review threads are resolved. The earlier 643 result remains historical. The repository-wide typecheck, tests, build and browser gates passed in the prior `6696a37f8a5718cd0f79054969a0084462d41d47` CI run. The new `8c912e1ba4fc66397a7341ade59373af8075068f` full CI also passes. They were not run as a full local workspace command in the focused PostgreSQL lease. Local evidence above uses bounded external databases and does not claim embedded-cluster, live-provider or deployed-alarm qualification. ## Risks - An unsupported or uncertain owner state must remain blocked. An optimistic exemption could lose work while compute is stopped. - Changes during reconstruction or inspection must invalidate the proof. A memory-only timer is not durable alarm coverage. - Current authorization, budgets, cancellation, accounting, and resource ownership still apply on dispatch. The proof does not grant execution authority. - The supported writer model uses in-process transaction signals and startup/resume reconstruction. Independent SQL writers and other replicas need an explicit wake contract. - Native, review, coalesced, and taskless retry variants remain conservative until their owner cases qualify. Reviewer quota and hosted alarm qualification remain open. - The shared catalog remains opt-in. Legacy callers and missing owner bindings retain their old blockers. ## Model Used OpenAI `gpt-6.1-sol` was the configured model for the delegated service implementations and reviews. OpenAI Codex, based on GPT-6, performed managing review and integration. Both used repository tools and code execution. The exact served backend snapshots and context-window limits were not exposed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run tests locally and they pass on the final merged head - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green — exact current-head run passes - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups — complete current-head review and all paginated threads inspected - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
382 lines
28 KiB
TypeScript
382 lines
28 KiB
TypeScript
import { DELIVERY_QUEUES, notifyDeliveryWork } from './delivery-work-notifications.js';
|
|
import type { createDeliveryWorkCoordinator } from './delivery-work-coordinator.js';
|
|
import type { DeadlineReconciliationSnapshot } from './deadline-reconciliation.js';
|
|
import { lockProjectRootMutation } from './projects.js';
|
|
import { reserveInitialSkillWork, settleInitialSkillWork } from './skill-source-import-budget.js';
|
|
import { admitDeferredSkillImports, lockSkillImportQueue, SKILL_IMPORT_CAPACITY_WAIT } from './skill-source-import-queue.js';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { skillSourceRetryAt } from './skill-source-retry.js';
|
|
import { and, asc, eq, inArray, isNotNull, isNull, lte, or, sql } from 'drizzle-orm';
|
|
import { activityLog, agents, authUsers, heartbeatRuns, companies, companyMemberships, companySkillSources, companySkillSourceEntries,
|
|
projectSkillSources, projectWorkspaces, projects, type Db } from '@paperclipai/db';
|
|
import type { ProjectSkillRepository } from '@paperclipai/shared';
|
|
import { authorizationService, type AuthorizationActor } from './authorization.js';
|
|
import { skillSourceGitHubReader } from './skill-source-github-access.js';
|
|
import { skillSourceService, type SkillSourceContext } from './skill-sources.js';
|
|
import { scanGitHubSkillsWithPackageFallback } from './github-skill-source.js';
|
|
import { companySkillPolicyService } from './company-skill-policy.js';
|
|
import { persistActivity, publishActivity } from './activity-log.js';
|
|
import type { ActivityPublication } from './activity-log.js';
|
|
import { currentSkillActor, skillAccessService } from './skill-access.js';
|
|
import { enqueueProjectSkillSource, projectSkillRepository, projectSkillSetupIdentity } from './project-skill-source-bindings.js';
|
|
import { conflict, forbidden, notFound } from '../errors.js';
|
|
import { loadConfig } from '../config.js';
|
|
|
|
export const SKILL_SOURCE_REFRESH_MS = 5 * 60_000;
|
|
type Setup = { companyId: string; refreshUserId: string | null; refreshAgentId: string | null;
|
|
refreshLocalTrusted: boolean; refreshGrantId: string | null; connectionId: string | null };
|
|
|
|
export async function projectSkillRepositories(db: Db, companyId: string, actor: AuthorizationActor): Promise<ProjectSkillRepository[]> {
|
|
const rows = await db.select({ workspace: projectWorkspaces, project: projects }).from(projectWorkspaces)
|
|
.innerJoin(projects, and(eq(projects.id, projectWorkspaces.projectId), eq(projects.companyId, companyId)))
|
|
.where(eq(projectWorkspaces.companyId, companyId)).orderBy(asc(projects.name), asc(projectWorkspaces.name));
|
|
const bindings = await db.select().from(projectSkillSources).where(eq(projectSkillSources.companyId, companyId));
|
|
const removed = new Set((await db.select({ id: companySkillSources.id }).from(companySkillSources)
|
|
.where(and(eq(companySkillSources.companyId, companyId), sql`${companySkillSources.removedAt} is not null`))).map(source => source.id));
|
|
const allowed = new Map<string, boolean>();
|
|
const access = authorizationService(db);
|
|
const result: ProjectSkillRepository[] = [];
|
|
for (const { workspace, project } of rows) {
|
|
const repo = projectSkillRepository(workspace);
|
|
if (!repo) continue;
|
|
if (!allowed.has(project.id)) allowed.set(project.id, (await access.decide({ actor, action: 'project:read',
|
|
resource: { type: 'project', companyId, projectId: project.id } })).allowed);
|
|
if (!allowed.get(project.id)) continue;
|
|
const binding = bindings.find(item => (item.active || (!item.sourceId && item.lastError !== null)) && item.workspaceId === workspace.id && item.repositoryUrl === repo.repositoryUrl && item.trackingRef === repo.trackingRef);
|
|
result.push({ projectId: project.id, projectName: project.name, projectVisibility: project.visibility as 'open' | 'private',
|
|
workspaceId: workspace.id, ...repo, bindingId: binding?.id ?? null, sourceId: binding?.sourceId && !removed.has(binding.sourceId) ? binding.sourceId : null,
|
|
status: binding?.sourceId && removed.has(binding.sourceId) ? 'available' : binding?.status ?? 'available', lastError: binding?.lastError ?? null,
|
|
...(binding?.status === 'pending' ? { importState: binding.leaseToken && binding.leaseExpiresAt && binding.leaseExpiresAt > new Date() ? 'importing' as const : 'queued' as const } : {}) });
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export async function adoptProjectSkillRepository(db: Db, companyId: string, workspaceId: string, authorize: SkillSourceContext['authorize']) {
|
|
const actor = currentSkillActor();
|
|
if (!actor) throw forbidden('Authentication required');
|
|
const [workspace] = await db.select().from(projectWorkspaces).where(and(eq(projectWorkspaces.companyId, companyId), eq(projectWorkspaces.id, workspaceId)));
|
|
if (!workspace || !(await authorizationService(db).decide({ actor, action: 'project:read', resource: { type: 'project', companyId, projectId: workspace.projectId } })).allowed) throw notFound('Project repository not found');
|
|
const repository = projectSkillRepository(workspace);
|
|
if (!repository) throw notFound('Project repository not found');
|
|
await authorize('skills.import', { sourceType: 'git', sourceLocator: repository.repositoryUrl });
|
|
return db.transaction(async tx => {
|
|
const database = tx as unknown as Db;
|
|
// Follow the editor: root provenance, project, workspace, then queue/binding.
|
|
const project = await lockProjectRootMutation(tx, workspace.projectId);
|
|
if (!project || project.companyId !== companyId) throw notFound('Project repository not found');
|
|
const [currentWorkspace] = await tx.select().from(projectWorkspaces).where(and(
|
|
eq(projectWorkspaces.companyId, companyId), eq(projectWorkspaces.projectId, project.id), eq(projectWorkspaces.id, workspaceId))).for('update');
|
|
if (!currentWorkspace) throw notFound('Project repository not found');
|
|
const currentRepository = projectSkillRepository(currentWorkspace);
|
|
if (!currentRepository || currentRepository.repositoryUrl !== repository.repositoryUrl || currentRepository.trackingRef !== repository.trackingRef) {
|
|
throw conflict('Project repository changed. Reload Sources and try again.');
|
|
}
|
|
if (!(await authorizationService(database).decide({ actor, action: 'project:read', resource: { type: 'project', companyId, projectId: project.id } })).allowed) throw notFound('Project repository not found');
|
|
// Capture the setup before the company queue, consistently with attachment.
|
|
const setup = await projectSkillSetupIdentity(database, companyId);
|
|
await lockSkillImportQueue(database, companyId);
|
|
const [previous] = await tx.select({ bindingId: projectSkillSources.id, removedAt: companySkillSources.removedAt })
|
|
.from(projectSkillSources).innerJoin(companySkillSources, eq(companySkillSources.id, projectSkillSources.sourceId))
|
|
.where(and(eq(projectSkillSources.companyId, companyId), eq(projectSkillSources.workspaceId, workspace.id),
|
|
eq(projectSkillSources.repositoryUrl, repository.repositoryUrl), eq(projectSkillSources.trackingRef, repository.trackingRef)))
|
|
.for('update');
|
|
if (previous?.removedAt) {
|
|
// Retain the original project's access provenance, but free this workspace
|
|
// for a new tracking identity. Never attach new readers to retained copies.
|
|
await tx.update(projectSkillSources).set({ workspaceId: null, active: false })
|
|
.where(eq(projectSkillSources.id, previous.bindingId));
|
|
}
|
|
const binding = await enqueueProjectSkillSource(database, currentWorkspace, setup);
|
|
if (!binding) throw notFound('Project repository not found');
|
|
if (!binding.sourceId) await tx.update(projectSkillSources).set({ status: 'pending', nextSyncAt: new Date(), failureCount: 0, lastError: binding.lastError === SKILL_IMPORT_CAPACITY_WAIT ? SKILL_IMPORT_CAPACITY_WAIT : null,
|
|
...setup,
|
|
}).where(eq(projectSkillSources.id, binding.id));
|
|
const { publication } = await persistActivity(database, { companyId, actorType: actor.type === 'agent' ? 'agent' : 'user',
|
|
actorId: actor.agentId ?? actor.userId ?? 'board', agentId: actor.agentId, runId: actor.runId,
|
|
action: 'project.skills_import_requested', entityType: 'project', entityId: workspace.projectId, details: { workspaceId, bindingId: binding.id } });
|
|
// Publish only after the transaction completes (caller's route refreshes query state).
|
|
return { bindingId: binding.id, publication };
|
|
});
|
|
}
|
|
|
|
function setupActor(setup: Setup): AuthorizationActor {
|
|
return setup.refreshAgentId ? { type: 'agent', agentId: setup.refreshAgentId, companyId: setup.companyId,
|
|
onBehalfOfUserId: setup.refreshUserId === 'local-board' ? null : setup.refreshUserId, source: 'agent_key' }
|
|
: { type: 'board', userId: setup.refreshUserId, source: setup.refreshLocalTrusted ? 'local_implicit' : 'session', companyIds: [setup.companyId] };
|
|
}
|
|
export async function skillSourceSetupContext(db: Db, setup: Setup): Promise<SkillSourceContext> {
|
|
if (!setup.refreshUserId && !setup.refreshLocalTrusted) throw forbidden('Choose a GitHub connection to enable automatic updates.');
|
|
if (!setup.refreshLocalTrusted) {
|
|
const [member] = await db.select({ id: companyMemberships.id }).from(companyMemberships)
|
|
.innerJoin(authUsers, eq(authUsers.id, companyMemberships.principalId)).where(and(
|
|
eq(companyMemberships.companyId, setup.companyId), eq(companyMemberships.principalType, 'user'),
|
|
eq(companyMemberships.principalId, setup.refreshUserId!), eq(companyMemberships.status, 'active')));
|
|
if (!member) throw forbidden('The person who connected this source no longer has company access. Choose another GitHub connection.');
|
|
}
|
|
if (setup.refreshAgentId) {
|
|
const [agent] = await db.select({ status: agents.status }).from(agents).where(and(eq(agents.companyId, setup.companyId), eq(agents.id, setup.refreshAgentId)));
|
|
if (!agent || agent.status === 'terminated') throw forbidden('The agent who connected this source is unavailable. Choose a GitHub connection.');
|
|
}
|
|
if (setup.refreshAgentId && (!setup.connectionId || !setup.refreshGrantId)) throw forbidden('Choose a GitHub connection to authorize this agent-created repository.');
|
|
const readerActor: AuthorizationActor = { type: 'board', userId: setup.refreshUserId,
|
|
source: setup.refreshLocalTrusted ? 'local_implicit' : 'session', companyIds: [setup.companyId] };
|
|
const actor = setupActor(setup);
|
|
const access = authorizationService(db), policies = companySkillPolicyService(db);
|
|
const principal = setup.refreshAgentId ? await policies.resolveAgentPrincipal(setup.companyId, setup.refreshAgentId)
|
|
: { type: 'board' as const, id: setup.refreshUserId ?? 'board', role: 'board' };
|
|
const readers = new Map<string, ReturnType<typeof skillSourceGitHubReader>>();
|
|
const publications: ActivityPublication[] = [];
|
|
return {
|
|
actor: { type: 'system', userId: setup.refreshUserId, agentId: setup.refreshAgentId },
|
|
setup: { userId: setup.refreshUserId, agentId: setup.refreshAgentId, localTrusted: setup.refreshLocalTrusted, grantId: setup.refreshGrantId },
|
|
read: connectionId => {
|
|
const key = connectionId ?? '';
|
|
for (const reader of readers.values()) if (reader.connectionId && reader.connectionId === connectionId) return reader;
|
|
if (!readers.has(key)) readers.set(key, skillSourceGitHubReader(db, setup.companyId, readerActor as Parameters<typeof skillSourceGitHubReader>[2], connectionId, { grantId: setup.refreshGrantId }));
|
|
return readers.get(key)!;
|
|
},
|
|
authorize: async (action, resource) => {
|
|
const platform = await access.decide({ actor, action: 'skill_config:update', resource: { type: 'company', companyId: setup.companyId } });
|
|
if (!platform.allowed && !['deny_no_grant', 'deny_missing_consent', 'deny_missing_grant'].includes(platform.reason)) throw forbidden('Automatic skill updates are unavailable for the setup identity.');
|
|
if (resource.skillId) await skillAccessService(db, actor).assertSkill(setup.companyId, resource.skillId);
|
|
const decision = await policies.evaluate({ companyId: setup.companyId, principal, action, resource });
|
|
if (!decision.allowed) throw forbidden('Automatic skill updates are denied by company policy.');
|
|
},
|
|
audit: async (tx, sourceId, action, details) => {
|
|
const { publication } = await persistActivity(tx as unknown as Db, { companyId: setup.companyId, actorType: 'system', actorId: 'skill-source-sync',
|
|
agentId: setup.refreshAgentId, action, entityType: 'company_skill_source', entityId: sourceId,
|
|
details: { ...details, refreshUserId: setup.refreshUserId } });
|
|
publications.push(publication);
|
|
},
|
|
publishCommittedActivity: () => { for (const publication of publications.splice(0)) publishActivity(publication); },
|
|
};
|
|
}
|
|
|
|
export function skillSourceSyncService(db: Db, options: { context?: (setup: Setup) => Promise<SkillSourceContext> } = {}) {
|
|
const contextFor = options.context ?? (setup => skillSourceSetupContext(db, setup));
|
|
const sources = skillSourceService(db);
|
|
let running: Promise<{ imported: number; checked: number }> | null = null;
|
|
const shutdown = new AbortController();
|
|
const reconciliationId = randomUUID();
|
|
let revision = 0, requested = 0, completed = -1, manual = 0;
|
|
let started = false, reconciling = false;
|
|
let requestReconciliation: (() => void) | undefined;
|
|
const reconciliationSnapshot = (): DeadlineReconciliationSnapshot => ({ revision: `${reconciliationId}:${revision}`,
|
|
reconciled: started && !shutdown.signal.aborted && !reconciling && !running && manual === 0 && requested === completed });
|
|
|
|
async function recoverSetup(source: typeof companySkillSources.$inferSelect) {
|
|
if (source.refreshUserId || source.refreshLocalTrusted || source.refreshAgentId) return source;
|
|
const installed = await db.select({ id: companySkillSourceEntries.skillId }).from(companySkillSourceEntries)
|
|
.where(and(eq(companySkillSourceEntries.companyId, source.companyId), eq(companySkillSourceEntries.sourceId, source.id)));
|
|
const skillIds = installed.map(entry => entry.id).filter((id): id is string => Boolean(id));
|
|
const [event] = await db.select().from(activityLog).where(and(eq(activityLog.companyId, source.companyId),
|
|
or(eq(activityLog.actorType, 'user'), and(eq(activityLog.actorType, 'agent'), isNotNull(activityLog.runId))),
|
|
inArray(activityLog.action, ['company.skill_source_refreshed', 'company.skill_imported', 'company.skills_imported']),
|
|
or(eq(activityLog.entityId, source.id), ...(skillIds.length ? [inArray(activityLog.entityId, skillIds)] : []))))
|
|
.orderBy(asc(activityLog.createdAt)).limit(1);
|
|
if (!event || !event.actorId || event.actorId === 'board') return source;
|
|
let userId = event.actorId;
|
|
if (event.actorType === 'agent') {
|
|
const [run] = await db.select({ userId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, source.companyId), eq(heartbeatRuns.id, event.runId!),
|
|
eq(heartbeatRuns.agentId, event.agentId ?? event.actorId)));
|
|
if (!run?.userId) return source;
|
|
userId = run.userId;
|
|
}
|
|
if (!userId) return source;
|
|
const localTrusted = userId === 'local-board' && loadConfig().deploymentMode === 'local_trusted';
|
|
const [updated] = await db.update(companySkillSources).set({ refreshUserId: userId,
|
|
refreshAgentId: event.actorType === 'agent' ? event.agentId ?? event.actorId : null,
|
|
refreshLocalTrusted: localTrusted,
|
|
}).where(and(eq(companySkillSources.id, source.id), isNull(companySkillSources.refreshUserId))).returning();
|
|
return updated ?? (await db.select().from(companySkillSources).where(eq(companySkillSources.id, source.id)))[0]!;
|
|
}
|
|
|
|
async function importBinding(binding: typeof projectSkillSources.$inferSelect, now: Date) {
|
|
const token = randomUUID();
|
|
const [claimed] = await db.update(projectSkillSources).set({ leaseToken: token, leaseExpiresAt: new Date(now.getTime() + 10 * 60_000) })
|
|
.where(and(eq(projectSkillSources.id, binding.id), eq(projectSkillSources.active, true), isNull(projectSkillSources.sourceId),
|
|
or(isNull(projectSkillSources.leaseToken), lte(projectSkillSources.leaseExpiresAt, now)))).returning();
|
|
if (!claimed) return false;
|
|
try {
|
|
if (!options.context) {
|
|
const actor = setupActor(binding);
|
|
if (!(await authorizationService(db).decide({ actor, action: 'project:read', resource: { type: 'project', companyId: binding.companyId, projectId: binding.projectId } })).allowed) throw forbidden('Project access changed. Choose an authorized GitHub connection to retry.');
|
|
}
|
|
const context = await contextFor(binding);
|
|
await context.authorize('skills.import', { sourceType: 'git', sourceLocator: binding.repositoryUrl });
|
|
await reserveInitialSkillWork(db, binding, token, now);
|
|
const reader = context.read(binding.connectionId);
|
|
const scan = await scanGitHubSkillsWithPackageFallback({ repositoryUrl: binding.repositoryUrl, trackingRef: binding.trackingRef, packageMode: 'repository' }, reader, { signal: shutdown.signal });
|
|
const [existing] = await db.select().from(companySkillSources).where(and(eq(companySkillSources.companyId, binding.companyId),
|
|
eq(companySkillSources.repositoryUrl, scan.repositoryUrl), eq(companySkillSources.trackingRef, binding.trackingRef), isNull(companySkillSources.removedAt)));
|
|
let sourceId: string;
|
|
if (existing) {
|
|
await context.authorize('skills.import', { sourceType: 'git', sourceLocator: existing.repositoryUrl });
|
|
sourceId = existing.id;
|
|
} else {
|
|
try {
|
|
const result = await sources.create(binding.companyId, { repositoryUrl: scan.repositoryUrl, trackingRef: binding.trackingRef,
|
|
commitSha: scan.commitSha, packageMode: scan.packageMode, selectedPaths: scan.candidates.map(candidate => candidate.path),
|
|
connectionId: scan.connectionId ?? binding.connectionId }, { ...context, signal: shutdown.signal, projectBindingId: binding.id, projectBindingLeaseToken: token }, scan);
|
|
sourceId = result.source.id;
|
|
} catch (error) {
|
|
if (!(error instanceof Error && 'status' in error && error.status === 409)) throw error;
|
|
const [concurrent] = await db.select().from(companySkillSources).where(and(eq(companySkillSources.companyId, binding.companyId), eq(companySkillSources.repositoryUrl, scan.repositoryUrl), eq(companySkillSources.trackingRef, binding.trackingRef), isNull(companySkillSources.removedAt)));
|
|
if (!concurrent) throw error;
|
|
sourceId = concurrent.id;
|
|
}
|
|
}
|
|
return await db.transaction(async tx => {
|
|
// Removal locks the source before its bindings. Follow the same order
|
|
// and recheck provenance while that lock prevents concurrent removal.
|
|
const [source] = await tx.select().from(companySkillSources).where(and(
|
|
eq(companySkillSources.companyId, binding.companyId), eq(companySkillSources.id, sourceId))).for('update');
|
|
if (!source || source.removedAt) throw conflict('Source was removed during import. Retry to start independent tracking.');
|
|
if (source.trackingRef !== binding.trackingRef || source.repositoryUrl.toLowerCase() !== scan.repositoryUrl.toLowerCase()
|
|
|| (source.repositoryId && source.repositoryId !== scan.repositoryId)) {
|
|
throw conflict('Source repository or branch changed during import. Retry from Skills.');
|
|
}
|
|
const linked = await tx.update(projectSkillSources).set({ sourceId, status: 'ready', lastError: null, failureCount: 0, leaseToken: null, leaseExpiresAt: null })
|
|
.where(and(eq(projectSkillSources.id, binding.id), eq(projectSkillSources.companyId, binding.companyId),
|
|
eq(projectSkillSources.active, true), eq(projectSkillSources.leaseToken, token))).returning({ id: projectSkillSources.id });
|
|
if (linked.length) await settleInitialSkillWork(tx as unknown as Db, binding.companyId, scan.packageMode === 'skills' || scan.repositorySubset ? {} : scan);
|
|
return linked.length > 0;
|
|
});
|
|
} catch (error) {
|
|
const message = shutdown.signal.aborted ? binding.lastError : error instanceof Error && 'status' in error ? error.message : 'Skill import failed. Retry from Skills.';
|
|
await db.update(projectSkillSources).set({ status: shutdown.signal.aborted ? 'pending' : 'error', lastError: message, leaseToken: null, leaseExpiresAt: null,
|
|
...(error instanceof Error && 'status' in error && error.status === 403 ? { active: false } : {}),
|
|
failureCount: shutdown.signal.aborted ? binding.failureCount : binding.failureCount + 1, nextSyncAt: shutdown.signal.aborted ? now : skillSourceRetryAt(error, binding.failureCount, now) })
|
|
.where(and(eq(projectSkillSources.id, binding.id), eq(projectSkillSources.leaseToken, token)));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function sweep(now: Date) {
|
|
const activeCompanies = await db.select({ id: companies.id }).from(companies).where(eq(companies.status, 'active'));
|
|
const ids = activeCompanies.map(company => company.id);
|
|
if (!ids.length) return { imported: 0, checked: 0 };
|
|
for (const id of ids) await admitDeferredSkillImports(db, id, now);
|
|
const pending = await db.select().from(projectSkillSources).where(and(inArray(projectSkillSources.companyId, ids),
|
|
eq(projectSkillSources.active, true), isNull(projectSkillSources.sourceId), lte(projectSkillSources.nextSyncAt, now),
|
|
or(isNull(projectSkillSources.leaseToken), lte(projectSkillSources.leaseExpiresAt, now))))
|
|
.orderBy(asc(projectSkillSources.nextSyncAt)).limit(10);
|
|
let imported = 0, checked = 0;
|
|
for (const binding of pending) { if (shutdown.signal.aborted) break; if (await importBinding(binding, now)) imported++; }
|
|
const due = await db.select().from(companySkillSources).where(and(inArray(companySkillSources.companyId, ids),
|
|
eq(companySkillSources.enabled, true), eq(companySkillSources.automaticUpdates, true), lte(companySkillSources.nextSyncAt, now),
|
|
or(isNull(companySkillSources.leaseToken), lte(companySkillSources.leaseExpiresAt, now)),
|
|
or(eq(companySkillSources.accessScope, 'company'), sql`exists (select 1 from ${projectSkillSources} b where b.source_id = ${companySkillSources.id} and b.company_id = ${companySkillSources.companyId} and b.active)`)))
|
|
.orderBy(asc(companySkillSources.nextSyncAt)).limit(10);
|
|
for (const entry of due) {
|
|
if (shutdown.signal.aborted) break;
|
|
const source = await recoverSetup(entry);
|
|
try {
|
|
const context = await contextFor(source);
|
|
if (!options.context) {
|
|
try { await skillAccessService(db, setupActor(source)).assertSource(source.companyId, source.id); }
|
|
catch (error) {
|
|
if (!(error instanceof Error && 'status' in error && error.status === 404)) throw error;
|
|
throw forbidden('The person who connected this source no longer has project access. Choose another GitHub connection.');
|
|
}
|
|
}
|
|
await sources.refresh(source.companyId, source.id, context, undefined, undefined, { checkCommit: true, automatic: true, now, signal: shutdown.signal });
|
|
checked++;
|
|
} catch (error) {
|
|
if (error instanceof Error && 'status' in error && error.status === 409) continue;
|
|
// Failures in context or policy authorization precede the refresh lease.
|
|
// Compare the attempt and revision so another worker's result wins.
|
|
if (!shutdown.signal.aborted) {
|
|
await db.update(companySkillSources).set({ lastError: error instanceof Error && 'status' in error ? error.message : 'Automatic update failed. The installed skills were kept.',
|
|
failureCount: source.failureCount + 1, nextSyncAt: skillSourceRetryAt(error, source.failureCount, now), lastAttemptAt: now })
|
|
.where(and(eq(companySkillSources.id, source.id), eq(companySkillSources.revision, source.revision),
|
|
eq(companySkillSources.failureCount, source.failureCount),
|
|
source.lastAttemptAt ? eq(companySkillSources.lastAttemptAt, source.lastAttemptAt) : isNull(companySkillSources.lastAttemptAt),
|
|
or(isNull(companySkillSources.leaseToken), lte(companySkillSources.leaseExpiresAt, now))));
|
|
}
|
|
}
|
|
}
|
|
for (const id of ids) await admitDeferredSkillImports(db, id, new Date());
|
|
return { imported, checked };
|
|
}
|
|
async function performRefreshSource(companyId: string, sourceId: string, initiator: SkillSourceContext) {
|
|
const [source] = await db.select().from(companySkillSources).where(and(eq(companySkillSources.companyId, companyId), eq(companySkillSources.id, sourceId)));
|
|
if (!source) throw notFound('Skill source not found');
|
|
await initiator.authorize('skills.update', { sourceType: 'git', sourceLocator: source.repositoryUrl });
|
|
if (!source.refreshUserId && !source.refreshLocalTrusted) return sources.refresh(companyId, sourceId, initiator);
|
|
const setup = await contextFor(source);
|
|
if (!options.context) {
|
|
try { await skillAccessService(db, setupActor(source)).assertSource(companyId, sourceId); }
|
|
catch (error) {
|
|
if (!(error instanceof Error && 'status' in error && error.status === 404)) throw error;
|
|
throw forbidden('The person who connected this source no longer has project access. Choose another GitHub connection.');
|
|
}
|
|
}
|
|
return sources.refresh(companyId, sourceId, { ...setup, actor: initiator.actor,
|
|
publishCommittedActivity: initiator.publishCommittedActivity,
|
|
authorize: async (action, resource) => { await initiator.authorize(action, resource); await setup.authorize(action, resource); },
|
|
audit: async (tx, id, action, details) => initiator.audit(tx, id, action, { ...details, refreshUserId: source.refreshUserId }),
|
|
});
|
|
}
|
|
function tick(now = new Date()) {
|
|
if (shutdown.signal.aborted) return Promise.resolve({ imported: 0, checked: 0 });
|
|
if (running) return running;
|
|
revision++;
|
|
requested++;
|
|
running = sweep(now).finally(() => {
|
|
running = null; revision++;
|
|
if (!reconciling) requestReconciliation?.();
|
|
});
|
|
return running;
|
|
}
|
|
function start(coordinator: Pick<ReturnType<typeof createDeliveryWorkCoordinator>, 'register'>) {
|
|
started = true; revision++;
|
|
let nextDeadline: number | null = null;
|
|
const registration = coordinator.register(DELIVERY_QUEUES.skillSourceSync, {
|
|
retryMs: 5_000,
|
|
pausePassiveMaintenance: true,
|
|
onSettled: () => { requested++; revision++; },
|
|
onStop: () => { started = false; revision++; requestReconciliation = undefined; },
|
|
async run() {
|
|
reconciling = true; revision++;
|
|
try {
|
|
const pending = tick();
|
|
const generation = requested;
|
|
await pending;
|
|
const [row] = await db.execute<{ next_at: string | Date | null }>(sql`
|
|
SELECT min(at) AS next_at FROM (
|
|
SELECT greatest(b.next_sync_at, CASE WHEN b.lease_token IS NOT NULL THEN b.lease_expires_at END) AS at
|
|
FROM project_skill_sources b JOIN companies c ON c.id = b.company_id
|
|
WHERE c.status = 'active' AND b.active AND b.source_id IS NULL
|
|
UNION ALL
|
|
SELECT greatest(s.next_sync_at, CASE WHEN s.lease_token IS NOT NULL THEN s.lease_expires_at END) AS at
|
|
FROM company_skill_sources s JOIN companies c ON c.id = s.company_id
|
|
WHERE c.status = 'active' AND s.enabled AND s.automatic_updates
|
|
AND (s.access_scope = 'company' OR EXISTS (
|
|
SELECT 1 FROM project_skill_sources b WHERE b.source_id = s.id AND b.company_id = s.company_id AND b.active))
|
|
) deadlines`);
|
|
if (!row || row.next_at === undefined) throw new Error('Skill sync deadline query returned no result');
|
|
nextDeadline = row.next_at === null ? null : new Date(row.next_at).getTime();
|
|
if (nextDeadline !== null) {
|
|
if (!Number.isFinite(nextDeadline)) throw new Error('Invalid skill sync deadline');
|
|
if (nextDeadline <= Date.now()) nextDeadline = Date.now() + 5_000;
|
|
}
|
|
completed = generation;
|
|
} finally { reconciling = false; revision++; }
|
|
},
|
|
hasPending: async () => false,
|
|
nextRunAt: () => completed !== requested ? Date.now() + 5_000 : nextDeadline,
|
|
});
|
|
requestReconciliation = registration.wake;
|
|
return registration;
|
|
}
|
|
async function refreshSource(companyId: string, sourceId: string, initiator: SkillSourceContext) {
|
|
manual++; requested++; revision++;
|
|
try { return await performRefreshSource(companyId, sourceId, initiator); }
|
|
finally { manual--; revision++; requestReconciliation?.(); }
|
|
}
|
|
return { tick, start, refreshSource, reconciliationSnapshot,
|
|
stop: async () => { revision++; shutdown.abort(); await running; } };
|
|
}
|