@hasna/loops 0.4.12 → 0.4.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +106 -3
  2. package/README.md +70 -17
  3. package/dist/api/index.d.ts +35 -0
  4. package/dist/api/index.js +750 -10
  5. package/dist/cli/index.js +1744 -361
  6. package/dist/cli/ui.d.ts +44 -0
  7. package/dist/daemon/index.js +948 -212
  8. package/dist/generated/storage-kit/health.d.ts +19 -0
  9. package/dist/generated/storage-kit/index.d.ts +7 -0
  10. package/dist/generated/storage-kit/migrations.d.ts +47 -0
  11. package/dist/generated/storage-kit/mode.d.ts +47 -0
  12. package/dist/generated/storage-kit/pool.d.ts +33 -0
  13. package/dist/generated/storage-kit/query.d.ts +35 -0
  14. package/dist/generated/storage-kit/tls.d.ts +25 -0
  15. package/dist/index.d.ts +3 -3
  16. package/dist/index.js +6513 -4840
  17. package/dist/lib/health.d.ts +83 -3
  18. package/dist/lib/mode.d.ts +27 -0
  19. package/dist/lib/mode.js +69 -2
  20. package/dist/lib/scheduler.d.ts +5 -2
  21. package/dist/lib/storage/index.d.ts +1 -0
  22. package/dist/lib/storage/index.js +1329 -211
  23. package/dist/lib/storage/pg-executor.d.ts +27 -0
  24. package/dist/lib/storage/pg-runner-claim.d.ts +40 -0
  25. package/dist/lib/storage/postgres-loop-storage.d.ts +114 -0
  26. package/dist/lib/storage/sqlite.js +336 -8
  27. package/dist/lib/store.d.ts +234 -0
  28. package/dist/lib/store.js +350 -8
  29. package/dist/mcp/index.js +1447 -479
  30. package/dist/runner/index.js +179 -25
  31. package/dist/sdk/http.d.ts +115 -0
  32. package/dist/sdk/http.js +145 -0
  33. package/dist/sdk/index.d.ts +5 -1
  34. package/dist/sdk/index.js +1106 -296
  35. package/dist/serve/index.d.ts +4 -0
  36. package/dist/serve/index.js +7619 -0
  37. package/dist/types.d.ts +3 -0
  38. package/docs/CUTOVER-RUNBOOK.md +61 -0
  39. package/docs/DEPLOYMENT_MODES.md +23 -1
  40. package/docs/USAGE.md +66 -16
  41. package/package.json +14 -2
@@ -0,0 +1,19 @@
1
+ import type { TypedQueryClient } from "./query.js";
2
+ import { type Migration, type MigrationRunnerOptions } from "./migrations.js";
3
+ export interface HealthResult {
4
+ ok: boolean;
5
+ /** Round-trip latency of the probe query, in milliseconds. */
6
+ latencyMs: number;
7
+ error?: string;
8
+ }
9
+ /** Cheap reachability probe: `SELECT 1`. Never throws — reports `ok: false`. */
10
+ export declare function checkHealth(client: TypedQueryClient): Promise<HealthResult>;
11
+ export interface ReadyResult extends HealthResult {
12
+ /** Migration ids that are defined but not yet applied. */
13
+ pendingMigrations: string[];
14
+ }
15
+ /**
16
+ * Readiness probe: reachable AND fully migrated. Reports `ok: false` with the
17
+ * list of pending migration ids when the schema is behind.
18
+ */
19
+ export declare function checkReady(client: TypedQueryClient, migrations: readonly Migration[], options?: MigrationRunnerOptions): Promise<ReadyResult>;
@@ -0,0 +1,7 @@
1
+ export declare const KIT_VERSION = "0.4.0";
2
+ export * from "./mode.js";
3
+ export * from "./tls.js";
4
+ export * from "./query.js";
5
+ export * from "./pool.js";
6
+ export * from "./migrations.js";
7
+ export * from "./health.js";
@@ -0,0 +1,47 @@
1
+ import type { TypedQueryClient } from "./query.js";
2
+ /** Default ledger table name. Override per app if a legacy name exists. */
3
+ export declare const DEFAULT_MIGRATION_LEDGER_TABLE = "schema_migrations";
4
+ export interface Migration {
5
+ readonly id: string;
6
+ readonly sql: string;
7
+ readonly checksum: string;
8
+ }
9
+ export type MigrationState = "already_applied" | "pending";
10
+ export interface MigrationPlanItem {
11
+ readonly migration: Migration;
12
+ readonly state: MigrationState;
13
+ }
14
+ export interface AppliedMigration {
15
+ readonly id: string;
16
+ readonly checksum: string;
17
+ readonly appliedAt: string;
18
+ }
19
+ export interface MigrationResult {
20
+ readonly dryRun: boolean;
21
+ readonly applied: AppliedMigration[];
22
+ readonly plan: MigrationPlanItem[];
23
+ }
24
+ /** Stable sha256 checksum for a migration's SQL text. */
25
+ export declare function checksumSql(sql: string): string;
26
+ /** Freeze a migration definition, computing its checksum from the SQL. */
27
+ export declare function defineMigration(id: string, sql: string): Migration;
28
+ export interface MigrationRunnerOptions {
29
+ ledgerTable?: string;
30
+ }
31
+ export declare class MigrationLedger {
32
+ private readonly client;
33
+ private readonly migrations;
34
+ private readonly ledgerTable;
35
+ constructor(client: TypedQueryClient, migrations: readonly Migration[], options?: MigrationRunnerOptions);
36
+ ensureLedger(): Promise<void>;
37
+ listApplied(): Promise<AppliedMigration[]>;
38
+ private readApplied;
39
+ /** Compute the migration plan and guard against drift/downgrade. */
40
+ private buildPlan;
41
+ /** Apply all pending migrations. With `dryRun`, report the plan only. */
42
+ migrate(opts?: {
43
+ dryRun?: boolean;
44
+ }): Promise<MigrationResult>;
45
+ }
46
+ /** Convenience: build a ledger and run all pending migrations. */
47
+ export declare function createMigrationLedger(client: TypedQueryClient, migrations: readonly Migration[], options?: MigrationRunnerOptions): MigrationLedger;
@@ -0,0 +1,47 @@
1
+ export declare const STORAGE_MODES: readonly ["local", "cloud"];
2
+ export type StorageMode = (typeof STORAGE_MODES)[number];
3
+ export declare const DEPRECATED_STORAGE_MODE_ALIASES: readonly ["remote", "hybrid", "self_hosted"];
4
+ export type Env = Record<string, string | undefined>;
5
+ export interface StorageModeNormalization {
6
+ mode: StorageMode;
7
+ /** The deprecated alias that was normalized to `cloud`, if any. */
8
+ deprecatedAlias: string | null;
9
+ }
10
+ /**
11
+ * Normalize a raw storage-mode string to the `local | cloud` runtime enum.
12
+ * Accepts deprecated aliases (`remote`, `hybrid`, `self_hosted`) and maps them
13
+ * to `cloud`. Throws on any other value.
14
+ */
15
+ export declare function normalizeStorageMode(value: string): StorageModeNormalization;
16
+ /** Upper-snake env token for an app name, e.g. `todos` -> `TODOS`. */
17
+ export declare function envToken(name: string): string;
18
+ export interface StorageEnvKeys {
19
+ /** `HASNA_<NAME>_STORAGE_MODE` then the optional `<NAME>_STORAGE_MODE` alias. */
20
+ modeKeys: string[];
21
+ /** `HASNA_<NAME>_DATABASE_URL` then the optional `<NAME>_DATABASE_URL` alias. */
22
+ databaseUrlKeys: string[];
23
+ }
24
+ /** Resolve the canonical env-key spec for an app's storage config. */
25
+ export declare function storageEnvKeys(name: string): StorageEnvKeys;
26
+ export interface StorageModeResolution {
27
+ mode: StorageMode;
28
+ /** Env key the mode came from, or `"default"`. */
29
+ source: string;
30
+ deprecatedAlias: string | null;
31
+ databaseUrlPresent: boolean;
32
+ /** Env key the database URL came from, or `null`. */
33
+ databaseUrlSource: string | null;
34
+ warning: string | null;
35
+ }
36
+ /**
37
+ * Resolve an app's storage mode from the environment per the contract env spec.
38
+ * Precedence: `HASNA_<NAME>_STORAGE_MODE`, then `<NAME>_STORAGE_MODE`, else
39
+ * `local`. Never reads secret values — only detects DATABASE_URL presence.
40
+ */
41
+ export declare function resolveStorageMode(name: string, env?: Env): StorageModeResolution;
42
+ /**
43
+ * Resolve the database URL value for an app, honoring the canonical then alias
44
+ * env keys. Returns `null` when unset. The caller is responsible for never
45
+ * logging the returned value.
46
+ */
47
+ export declare function resolveDatabaseUrl(name: string, env?: Env): string | null;
@@ -0,0 +1,33 @@
1
+ import type { Pool } from "pg";
2
+ import { type TlsResolveOptions } from "./tls.js";
3
+ import { type PoolQueryClient } from "./query.js";
4
+ export interface CreatePgPoolOptions extends TlsResolveOptions {
5
+ connectionString: string;
6
+ /** Max clients in the pool. Defaults to pg's default (10). */
7
+ max?: number;
8
+ /** Idle client timeout (ms). */
9
+ idleTimeoutMillis?: number;
10
+ /** Connection acquisition timeout (ms). */
11
+ connectionTimeoutMillis?: number;
12
+ /** Application name reported to Postgres (shows in pg_stat_activity). */
13
+ applicationName?: string;
14
+ }
15
+ /** Build a `pg.Pool` with fleet-standard TLS handling. */
16
+ export declare function createPgPool(options: CreatePgPoolOptions): Pool;
17
+ export interface CreateCloudPoolFromEnvOptions extends TlsResolveOptions {
18
+ max?: number;
19
+ idleTimeoutMillis?: number;
20
+ connectionTimeoutMillis?: number;
21
+ applicationName?: string;
22
+ }
23
+ export interface CloudPoolFromEnv {
24
+ client: PoolQueryClient;
25
+ connectionSource: string;
26
+ }
27
+ /**
28
+ * Resolve mode + database URL from the environment and build a cloud pool.
29
+ *
30
+ * Throws when the resolved mode is not `cloud` (PURE REMOTE has no Postgres in
31
+ * `local` mode) or when the database URL is missing. Never logs the URL.
32
+ */
33
+ export declare function createCloudPoolFromEnv(appName: string, options?: CreateCloudPoolFromEnvOptions): CloudPoolFromEnv;
@@ -0,0 +1,35 @@
1
+ import type { Pool, QueryResultRow } from "pg";
2
+ export interface QueryResult<T extends QueryResultRow> {
3
+ rows: T[];
4
+ rowCount: number;
5
+ }
6
+ /**
7
+ * Minimal executor contract. `pg.Pool` and `pg.PoolClient` both satisfy the
8
+ * `query` method; the wrapper builds the rest on top so tests can substitute a
9
+ * lightweight shim without pulling in a live Postgres.
10
+ */
11
+ export interface PgExecutor {
12
+ query<T extends QueryResultRow>(sql: string, params?: readonly unknown[]): Promise<{
13
+ rows: T[];
14
+ rowCount: number | null;
15
+ }>;
16
+ }
17
+ export interface TypedQueryClient {
18
+ query<T extends QueryResultRow>(sql: string, params?: readonly unknown[]): Promise<QueryResult<T>>;
19
+ many<T extends QueryResultRow>(sql: string, params?: readonly unknown[]): Promise<T[]>;
20
+ /** First row or `null`. Restored here after open-knowledge dropped it. */
21
+ get<T extends QueryResultRow>(sql: string, params?: readonly unknown[]): Promise<T | null>;
22
+ /** Exactly one row; throws if zero or more than one row is returned. */
23
+ one<T extends QueryResultRow>(sql: string, params?: readonly unknown[]): Promise<T>;
24
+ execute(sql: string, params?: readonly unknown[]): Promise<void>;
25
+ }
26
+ /** Wrap any `PgExecutor` (a Pool, a PoolClient, or a test shim) with the typed vocabulary. */
27
+ export declare function wrapExecutor(executor: PgExecutor): TypedQueryClient;
28
+ export interface PoolQueryClient extends TypedQueryClient {
29
+ readonly pool: Pool;
30
+ /** Run a callback inside a `BEGIN`/`COMMIT` transaction on a dedicated client. */
31
+ transaction<T>(fn: (client: TypedQueryClient) => Promise<T>): Promise<T>;
32
+ close(): Promise<void>;
33
+ }
34
+ /** Build a `PoolQueryClient` around a live `pg.Pool`. */
35
+ export declare function createQueryClient(pool: Pool): PoolQueryClient;
@@ -0,0 +1,25 @@
1
+ /** The `ssl` field shape accepted by `pg.Pool` / `pg.Client`. */
2
+ export type PgSslConfig = boolean | {
3
+ rejectUnauthorized: boolean;
4
+ ca?: string;
5
+ };
6
+ export interface TlsResolveOptions {
7
+ /** Inline CA bundle (PEM). Wins over every other CA source. */
8
+ ca?: string;
9
+ /** Path to a CA bundle PEM file, e.g. the Amazon RDS global bundle. */
10
+ caCertPath?: string;
11
+ /** Environment used to discover PGSSLROOTCERT / NODE_EXTRA_CA_CERTS. */
12
+ env?: Record<string, string | undefined>;
13
+ }
14
+ export type SslMode = "disable" | "prefer" | "require" | "verify-ca" | "verify-full";
15
+ /**
16
+ * Extract the effective `sslmode` from a Postgres connection string. Honors the
17
+ * `sslmode` query param and the legacy `ssl=true` boolean. Returns `disable`
18
+ * when TLS is not requested.
19
+ */
20
+ export declare function sslModeFromConnectionString(connectionString: string): SslMode;
21
+ /**
22
+ * Resolve the `pg` ssl config for a connection string. See the module header
23
+ * for the full mode table. Returns `undefined` when TLS should be off.
24
+ */
25
+ export declare function resolveTlsConfig(connectionString: string, options?: TlsResolveOptions): PgSslConfig | undefined;
package/dist/index.d.ts CHANGED
@@ -14,8 +14,8 @@ export { AmbiguousNameError, CodedError, LoopArchivedError, LoopNotFoundError, V
14
14
  export type { CatchUpPolicy, CreateLoopInput, ExecutorResult, IntervalAnchor, Loop, LoopRun, LoopStatus, OverlapPolicy, RunStatus, TimeoutMs, CronSchedule, DynamicSchedule, IntervalSchedule, OnceSchedule, ScheduleSpec, AccountRef, AgentAllowlistSpec, AgentConfigIsolation, AgentPermissionMode, AgentPromptSource, AgentProvider, AgentRoutingSpec, AgentSandbox, AgentTarget, AgentTargetBase, AgentWorktreeMode, AgentWorktreeSpec, CommandTarget, ExecutableTarget, ExecutableTargetInput, LoopTarget, LoopTargetInput, PromptFileAgentTarget, RuntimePreflightPolicy, WorkflowTarget, CreateWorkflowInput, WorkflowEvent, WorkflowRun, WorkflowRunStatus, WorkflowSpec, WorkflowStatus, WorkflowStep, WorkflowStepInput, WorkflowStepRun, WorkflowStepRunStatus, } from "./types.js";
15
15
  export { runDoctor } from "./lib/doctor.js";
16
16
  export type { DoctorCheck, DoctorReport, DoctorSeverity } from "./lib/doctor.js";
17
- export { buildHealthReport, classifyRunFailure, expectationForLoop } from "./lib/health.js";
18
- export type { LoopExpectationResult, LoopsHealthReport, RunFailureClassification, RunFailureSignal, } from "./lib/health.js";
17
+ export { buildHealthReport, buildHealthScan, classifyRunFailure, expectationForLoop, writeHealthScanReports } from "./lib/health.js";
18
+ export type { BuildHealthScanOptions, HealthScanFinding, HealthScanFindingKind, HealthScanFindingSeverity, HealthScanSelfHealAction, HealthScanStatus, LoopExpectationResult, LoopsHealthReport, LoopsHealthScan, RunFailureClassification, RunFailureSignal, WriteHealthScanReportsOptions, } from "./lib/health.js";
19
19
  export { computeNextAfter, initialNextRun, nextCronRun, parseCron, parseDuration } from "./lib/recurrence.js";
20
20
  export { runLoopNow, tick } from "./lib/scheduler.js";
21
21
  export type { ManualRunSource, RunLoopNowDeps, RunLoopNowExecuted, RunLoopNowMode, RunLoopNowResult, RunLoopNowScheduled, } from "./lib/scheduler.js";
@@ -23,7 +23,7 @@ export { Store } from "./lib/store.js";
23
23
  export { POSTGRES_MIGRATION_LEDGER_TABLE, POSTGRES_STORAGE_MIGRATIONS, PostgresStorage, SqliteLoopStorage, checksumStorageSql, createPostgresStorage, createSqliteLoopStorage, } from "./lib/storage/index.js";
24
24
  export type { AppliedStorageMigration, AuditEventRecord, LoopStorageBackend, LoopStorageContract, LoopStorageMethodName, PostgresQueryExecutor, RunnerLeaseRecord, RunnerLeaseStatus, RunnerMachineRecord, RunnerMachineStatus, SchemaMigrationStorage, StorageMigration, StorageMigrationPlanItem, StorageMigrationResult, } from "./lib/storage/index.js";
25
25
  export { LOOP_DEPLOYMENT_MODES, buildDeploymentStatus, deploymentStatusLine, loopControlPlaneConfig, normalizeLoopDeploymentMode, resolveLoopDeploymentMode, } from "./lib/mode.js";
26
- export type { LoopControlPlaneConfig, LoopDeploymentMode, LoopDeploymentStatus, LoopModeResolution, LoopSourceOfTruth } from "./lib/mode.js";
26
+ export type { LoopControlPlaneConfig, LoopDeploymentMode, LoopDeploymentStatus, LoopModeResolution, LoopRemoteArtifactStore, LoopRemoteSchedulerBackend, LoopRouteAdmissionGate, LoopRouteAdmissionStateStore, LoopSchedulerStateStatus, LoopSourceOfTruth, } from "./lib/mode.js";
27
27
  export { executeLoop, executeTarget, preflightTarget } from "./lib/executor.js";
28
28
  export { executeLoopTarget, executeWorkflow, preflightWorkflow } from "./lib/workflow-runner.js";
29
29
  export { workflowBodyFromJson, workflowExecutionOrder } from "./lib/workflow-spec.js";