UNPKG

@hasna/projects

Version:

High-level project management CLI, MCP server, SDK, and AI SDK agent loop for coding agents

293 lines • 18.1 kB
import type { ApiKeyPrincipal } from "@hasna/contracts/auth"; import type { ProjectionPolicy } from "./projection-policy.js"; import type { TypedQueryClient } from "../generated/storage-kit/query.js"; import { type AppendReceiptInput, type ProjectRegistrationManifestCreateInput, type ProjectRegistrationManifestCreateResult, type ProjectRegistrationManifestRecord, type ProjectRegistrationReceipt, type ProjectRegistrationReceiptLookupInput, type ProjectRegistrationReceiptLookupResult, type ProjectRegistrationReceiptQuery } from "../lib/project-registration.js"; import { type AsyncProjectResourceLinkProducerEvidenceVerifier } from "../lib/project-resource-link-migrations.js"; import type { Agent, CreateAgentInput, CreateRecipeInput, CreateRootInput, CreateWorkspaceInput, EventSource, GuardedProjectMutationReceiptLookupInput, GuardedProjectMutationReceiptLookupResult, GuardedProjectReadRequest, GuardedProjectReadResult, GuardedProjectMutationRequest, GuardedProjectMutationResult, GuardedProjectMutationRollbackRequest, JsonObject, ProjectResourceLink, ProjectResourceLinkMutationRequest, ProjectResourceLinkMutationResult, ProjectResourceLinkMigrationAdvanceRequest, ProjectResourceLinkMigrationPlanRequest, ProjectResourceLinkMigrationReadRequest, ProjectResourceLinkMigrationResult, ProjectResourceLinkMigrationRollbackRequest, ProjectResourceLinkReadRequest, ProjectResourceLinkReadResult, ProjectResourceLinkRollbackRequest, ProjectRelationMutationRequest, ProjectRelationMutationResult, ProjectRelationReadRequest, ProjectRelationReadResult, ProjectQuarantineReadRequest, ProjectQuarantineReadResult, ProjectQuarantineRequest, ProjectQuarantineResult, ProjectQuarantineRollbackRequest, Recipe, RecordWorkspaceEventInput, Root, UpdateRootInput, UpdateWorkspaceInput, Workspace, WorkspaceAgentAssignment, WorkspaceEvent, WorkspaceLocation, WorkspaceLock, WorkspaceKind, WorkspaceStatus, Machine } from "../types/workspace.js"; import type { ProjectQueryScope } from "../lib/project-list-output.js"; export declare function generateWorkspaceId(): string; export declare function generateRootId(): string; export declare function generateRecipeId(): string; export declare function generateAgentId(): string; export declare function generateEventId(): string; export declare function slugify(name: string): string; /** Not-found error carrying an HTTP status hint for the router. */ export declare class NotFoundError extends Error { readonly status = 404; constructor(message: string); } /** Client/validation error (bad input) carrying a 400 hint. */ export declare class ValidationError extends Error { readonly status = 400; constructor(message: string); } /** * A full-registration ledger refusal that carries the domain reason code on the * response body. The CLI store maps these codes back onto the same errors the * on-box implementation throws (a manifest conflict is a * `ProjectRegistrationStepError`, exactly as it is locally), so the hosted flow * classifies a refusal identically to the local one instead of degrading it to * a bare transport error. */ export declare class ProjectRegistrationLedgerError extends Error { readonly reason: string; readonly status: number; constructor(reason: string, message: string, status?: number); } /** * Server-side bounds on a single `/v1/projects` page. These protect the * database from an unbounded scan; they are NOT a statement that the caller may * only ever see this many projects. The response reports `total` and `has_more` * so a client can page the rest — the `@hasna/projects` store does so * automatically. */ export declare const WORKSPACE_LIST_DEFAULT_LIMIT = 100; export declare const WORKSPACE_LIST_MAX_LIMIT = 1000; export interface WorkspaceFilter { status?: WorkspaceStatus; kind?: WorkspaceKind; root_id?: string; query?: string; query_scope?: ProjectQueryScope; tags?: string[]; exclude_eval_artifacts?: boolean; /** Exclude rows tagged `registry-fixture` (the normalization program's generated test rows). Default reads exclude them. */ exclude_registry_fixtures?: boolean; limit?: number; offset?: number; } export declare class ProjectsPgStore { private readonly db; private readonly producerEvidenceVerifier?; constructor(db: TypedQueryClient, producerEvidenceVerifier?: AsyncProjectResourceLinkProducerEvidenceVerifier | undefined); private inTransaction; private ensureUniqueSlug; listRoots(): Promise<Root[]>; getRoot(idOrSlug: string): Promise<Root | null>; createRoot(input: CreateRootInput): Promise<Root>; updateRoot(idOrSlug: string, input: UpdateRootInput): Promise<Root>; deleteRoot(idOrSlug: string, detachWorkspaces?: boolean): Promise<{ root: Root; detached_workspaces: number; }>; listAgents(): Promise<Agent[]>; getAgent(idOrSlug: string): Promise<Agent | null>; createAgent(input: CreateAgentInput): Promise<Agent>; listRecipes(): Promise<Recipe[]>; getRecipe(idOrSlug: string): Promise<Recipe | null>; createRecipe(input: CreateRecipeInput): Promise<Recipe>; /** * Shared predicate for listing and counting workspaces. Kept in one place so * a reported total can never describe a different set than the rows beside * it. */ private workspaceFilterSql; listWorkspaces(filter?: WorkspaceFilter): Promise<Workspace[]>; /** Rows matching `filter`, ignoring its limit/offset. */ countWorkspaces(filter?: WorkspaceFilter): Promise<number>; getWorkspace(idOrSlug: string): Promise<Workspace | null>; issueProductProjection(policy: ProjectionPolicy | undefined, principal: ApiKeyPrincipal, projectId: string, input: unknown): Promise<Record<string, unknown>>; readProductProjection(policy: ProjectionPolicy | undefined, principal: ApiKeyPrincipal, projectId: string, receiptId: string, input: unknown): Promise<Record<string, unknown>>; guardedReadWorkspace(input: GuardedProjectReadRequest, startedAtMs?: number): Promise<GuardedProjectReadResult>; listProjectResourceLinks(projectId: string, maxItems?: number): Promise<ProjectResourceLink[]>; listWorkspaceLocations(projectId: string): Promise<WorkspaceLocation[]>; listMachines(): Promise<Machine[]>; private registrationManifestRow; private requireRegistrationReceiptRow; createProjectRegistrationManifest(input: ProjectRegistrationManifestCreateInput): Promise<ProjectRegistrationManifestCreateResult>; readProjectRegistrationManifest(operationId: string): Promise<ProjectRegistrationManifestRecord | null>; appendProjectRegistrationReceipt(input: AppendReceiptInput): Promise<ProjectRegistrationReceipt>; lookupProjectRegistrationReceipt(input: ProjectRegistrationReceiptLookupInput): Promise<ProjectRegistrationReceiptLookupResult>; listProjectRegistrationReceipts(operationId: string): Promise<ProjectRegistrationReceipt[]>; findProjectRegistrationReceipts(input: ProjectRegistrationReceiptQuery): Promise<ProjectRegistrationReceipt[]>; addWorkspaceLocation(input: { workspace_id: string; path: string; machine_id?: string; label?: string; kind?: string; is_primary?: boolean; metadata?: JsonObject; agent_id?: string; source?: EventSource; command?: string; created_at?: string; }): Promise<WorkspaceLocation>; listWorkspaceAgents(workspaceId: string): Promise<WorkspaceAgentAssignment[]>; private toWorkspaceAgentAssignment; assignAgentToWorkspace(input: { workspace_id: string; agent_id: string; role?: string; assigned_by?: string; metadata?: JsonObject; created_at?: string; }): Promise<WorkspaceAgentAssignment>; listLocks(): Promise<WorkspaceLock[]>; acquireLock(input: { lock_key: string; workspace_id?: string; agent_id?: string; reason?: string; ttl_seconds?: number; created_at?: string; }): Promise<WorkspaceLock>; releaseLock(lockKey: string, lockId: string): Promise<boolean>; forceReleaseLock(lockKey: string): Promise<boolean>; private pruneExpiredLocks; private listWorkspaceLocationsBounded; private replaceWorkspaceLocations; private replaceProjectResourceLinksExact; readProjectResourceLinks(input: ProjectResourceLinkReadRequest, startedAtMs?: number): Promise<ProjectResourceLinkReadResult>; /** * The relation graph keyed by the projects it touches. * * A relation write does not advance the project row (linking must not write * any `workspaces` column — see `mutateProjectRelation`), so the revision CAS * alone cannot serialize two concurrent writers that would each close the * same hierarchy loop. Taking a transaction-scoped advisory lock on BOTH * endpoints, in sorted order, restores that serialization: a new loop always * shares an endpoint with an existing edge of the loop, so two writers that * could jointly close one cannot run their walks concurrently, and the sorted * order removes the deadlock a two-key lock would otherwise invite. * * The key is derived here, not by Postgres' `hashtext`, so it is identical * across processes and stable across releases. */ private lockProjectRelationEndpoints; /** * The single lock every hierarchical write takes. * * The endpoint lock above is NOT sufficient on its own, and that was measured * on PostgreSQL 16.15 rather than reasoned about (review NO_GO, Files * f_CvF7ODh_8L). Two writers with DISJOINT endpoints share no endpoint key, so * their cycle walks run concurrently against the same pre-state: with existing * edges Y->P and Q->X, a writer adding X->Y locks {X,Y} and a writer adding * P->Q locks {P,Q}, neither walk sees the other's pending edge, and together * they commit the loop X->Y->P->Q->X. A cycle can always be closed by two * edges whose endpoints are disjoint — so no per-endpoint lock can be enough. * * The walk reads the WHOLE hierarchy graph, so the lock that makes it sound is * one on the whole graph. Hierarchy writes are rare and short, and `related_to` * writes (which can never be an edge of the hierarchy) do not take it, so this * serializes exactly the writes that can form a loop and nothing else. * * Lock order is always endpoint keys (sorted) then this key, so the two lock * families cannot deadlock against each other. */ private lockProjectRelationHierarchy; private listProjectRelationHeads; private projectRelationViewsFor; readProjectRelations(input: ProjectRelationReadRequest, startedAtMs?: number): Promise<ProjectRelationReadResult>; mutateProjectRelation(input: ProjectRelationMutationRequest): Promise<ProjectRelationMutationResult>; private mutateProjectRelationInCurrentTransaction; /** Every live hierarchical edge — the graph the cycle walk runs over. */ private listProjectRelationAcyclicEdges; readDuplicateProjectQuarantinePreimage(input: ProjectQuarantineReadRequest, startedAtMs?: number): Promise<ProjectQuarantineReadResult>; requireWorkspace(idOrSlug: string): Promise<Workspace>; createWorkspace(input: CreateWorkspaceInput): Promise<Workspace>; /** * Refuse a hosted write that would pin `integrations.conversations_channel` * at a name the conversations app has no channel for (BUG-0063 / BUG-0076). * * Applied at the stores' own write points — update, guarded patch and create * — because a direct HTTP/SDK caller never passes a client-level guard. The * rule itself is imported from the db-free `project-channel-guard` module: * this store never touches `bun:sqlite`. Only a positive `missing` verdict * refuses; an unavailable probe or an `unknown` verdict passes (`probe` * undefined in tests and on any box without the conversations CLI), so this * never invents a failure from an answer it could not obtain. */ private assertChannelIntegrationWritable; updateWorkspace(idOrSlug: string, input: UpdateWorkspaceInput): Promise<Workspace>; /** * The `target_id` foreign key, applied on the path where Postgres does not * apply it. * * A real insert checks the FK. An `ON CONFLICT (receipt_id) DO NOTHING` * insert that meets an existing row never inserts anything, so the * AFTER-INSERT foreign-key check never runs and a candidate naming a * nonexistent target would otherwise be accepted silently. MEASURED on * Postgres 16.15 (A3-00870 review): with a receipt already recorded, that * statement refuses a bad CHECK but NOT a bad `target_id`. * * So the writer makes the same check the FK makes, on the conflict path only, * and refuses with a named error. The inserting path is left to the database. */ private assertGuardedReceiptTargetExists; /** * Idempotent receipt writer — the guarded-mutation receipt contract, hosted * parity with the local `insertGuardedProjectMutationReceipt`. * * `receipt_id` is derived deterministically from the operation identity * (`buildReceiptId`), so retrying an operation-id after a FAILED attempt * derives the SAME primary key. The first attempt already recorded that * outcome; the retry must read that immutable row back instead of racing the * primary key into the reported 500 * (`duplicate key value violates unique constraint * "guarded_project_mutation_receipts_pkey"`, A3-00870). * * `ON CONFLICT (receipt_id) DO NOTHING` + read-back (not a bare pre-read) is * what makes the write idempotent: Postgres settles the conflict itself, so * two writers of the same derived id cannot both insert, the conflicting * insert does not abort the surrounding transaction, and the read-back returns * the FIRST recorded row for that id: a receipt is immutable evidence, so its * `before_json`/`created_at` stay those of the attempt that actually produced * the outcome. * * The conflict path is not a free pass for the row constraints. The database * still refuses a bad NOT NULL or CHECK there, but NOT the `target_id` foreign * key (see {@link assertGuardedReceiptTargetExists}), so the writer runs that * check itself whenever the insert inserted nothing — `RETURNING` is what * distinguishes the two paths, because a row comes back only when one was * actually inserted. A candidate naming a missing target is refused on both * paths, never accepted because a receipt with the same id already existed. * * Idempotent write, NOT a promoted response: the caller keeps computing its * own fail-closed outcome, so a retried `terminal_nonacceptance` still returns * `terminal_nonacceptance` carrying the originally recorded receipt, and a * retry can never claim success for an attempt that failed. A retry whose * derived id differs — a different request digest, precondition/revision or * outcome — is a different logical attempt and records its own row. */ private insertGuardedReceipt; private guardedAcceptedReceipt; private guardedAcceptedByStep; private requireForwardProjectResourceLinkReceipt; private guardedTerminalNonacceptance; private duplicateGuardedReceipt; private guardedConditionalUpdate; mutateProjectResourceLinks(input: ProjectResourceLinkMutationRequest): Promise<ProjectResourceLinkMutationResult>; private mutateProjectResourceLinksInCurrentTransaction; rollbackProjectResourceLinks(input: ProjectResourceLinkRollbackRequest): Promise<ProjectResourceLinkMutationResult>; quarantineDuplicateProject(input: ProjectQuarantineRequest): Promise<ProjectQuarantineResult>; private quarantineDuplicateProjectInCurrentTransaction; rollbackDuplicateProjectQuarantine(input: ProjectQuarantineRollbackRequest): Promise<ProjectQuarantineResult>; private rollbackDuplicateProjectQuarantineInCurrentTransaction; private resourceLinkMigrationManifest; private resourceLinkMigrationEvents; private boundedResourceLinkMigrationEvents; private insertResourceLinkMigrationEvent; private persistResourceLinkMigrationTransition; planProjectResourceLinkMigration(input: ProjectResourceLinkMigrationPlanRequest): Promise<ProjectResourceLinkMigrationResult>; readProjectResourceLinkMigration(input: ProjectResourceLinkMigrationReadRequest): Promise<ProjectResourceLinkMigrationResult>; advanceProjectResourceLinkMigration(input: ProjectResourceLinkMigrationAdvanceRequest): Promise<ProjectResourceLinkMigrationResult>; rollbackProjectResourceLinkMigration(input: ProjectResourceLinkMigrationRollbackRequest): Promise<ProjectResourceLinkMigrationResult>; guardedUpdateWorkspace(input: GuardedProjectMutationRequest): Promise<GuardedProjectMutationResult>; private guardedUpdateWorkspaceInCurrentTransaction; lookupGuardedWorkspaceMutationReceipt(input: GuardedProjectMutationReceiptLookupInput): Promise<GuardedProjectMutationReceiptLookupResult>; rollbackGuardedWorkspaceMutation(input: GuardedProjectMutationRollbackRequest): Promise<GuardedProjectMutationResult>; private rollbackGuardedWorkspaceMutationInCurrentTransaction; archiveWorkspace(idOrSlug: string, input?: Omit<UpdateWorkspaceInput, "status">): Promise<Workspace>; unarchiveWorkspace(idOrSlug: string, input?: Omit<UpdateWorkspaceInput, "status">): Promise<Workspace>; deleteWorkspace(idOrSlug: string, input?: Omit<UpdateWorkspaceInput, "status"> & { hard?: boolean; }): Promise<{ workspace: Workspace; hard: boolean; }>; listWorkspaceEvents(workspaceId: string, limit?: number): Promise<WorkspaceEvent[]>; recordEvent(input: RecordWorkspaceEventInput): Promise<WorkspaceEvent>; ping(): Promise<boolean>; } //# sourceMappingURL=pg-store.d.ts.map