@hasna/todos 0.11.74 → 0.11.81
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.
- package/README.md +8 -0
- package/dist/cli/cloud-router.d.ts +71 -0
- package/dist/cli/cloud-router.d.ts.map +1 -0
- package/dist/cli/commands/project-commands.d.ts.map +1 -1
- package/dist/cli/commands/query-commands.d.ts.map +1 -1
- package/dist/cli/commands/storage-commands.d.ts.map +1 -1
- package/dist/cli/commands/task-commands.d.ts.map +1 -1
- package/dist/cli/helpers.d.ts +22 -0
- package/dist/cli/helpers.d.ts.map +1 -1
- package/dist/cli/index.js +72388 -61727
- package/dist/contracts.js +314 -14
- package/dist/db/database.d.ts.map +1 -1
- package/dist/index.js +1158 -236
- package/dist/lib/routing-doctor.d.ts +144 -0
- package/dist/lib/routing-doctor.d.ts.map +1 -0
- package/dist/lib/shadow-status.d.ts +38 -0
- package/dist/lib/shadow-status.d.ts.map +1 -0
- package/dist/mcp/index.js +10249 -340
- package/dist/mcp/tools/task-adv-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-crud.d.ts.map +1 -1
- package/dist/mcp/tools/task-project-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-workflow-tools.d.ts.map +1 -1
- package/dist/registry.js +314 -14
- package/dist/release-provenance.json +3 -3
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.d.ts.map +1 -1
- package/dist/sdk/index.js +135 -0
- package/dist/sdk/v1.generated.d.ts +124 -0
- package/dist/sdk/v1.generated.d.ts.map +1 -0
- package/dist/server/cloud.d.ts +50 -0
- package/dist/server/cloud.d.ts.map +1 -0
- package/dist/server/index.js +11944 -2012
- package/dist/server/openapi.d.ts +628 -0
- package/dist/server/openapi.d.ts.map +1 -0
- package/dist/server/serve.d.ts.map +1 -1
- package/dist/server/v1.d.ts +19 -0
- package/dist/server/v1.d.ts.map +1 -0
- package/dist/storage/cloud-client.d.ts +30 -0
- package/dist/storage/cloud-client.d.ts.map +1 -0
- package/dist/storage/config.d.ts +12 -0
- package/dist/storage/config.d.ts.map +1 -1
- package/dist/storage/factory.d.ts +2 -0
- package/dist/storage/factory.d.ts.map +1 -1
- package/dist/storage/index.d.ts +8 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/postgres-adapter.d.ts.map +1 -1
- package/dist/storage/postgres-sync.d.ts.map +1 -1
- package/dist/storage/shadow-outbox-schema.d.ts +21 -0
- package/dist/storage/shadow-outbox-schema.d.ts.map +1 -0
- package/dist/storage/shadow-outbox.d.ts +125 -0
- package/dist/storage/shadow-outbox.d.ts.map +1 -0
- package/dist/storage/shadow-runtime.d.ts +29 -0
- package/dist/storage/shadow-runtime.d.ts.map +1 -0
- package/dist/storage/shadow.d.ts +118 -0
- package/dist/storage/shadow.d.ts.map +1 -0
- package/dist/storage.d.ts +2 -1
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +1157 -220
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +6 -2
- package/vendor/hasna-contracts-0.5.1.tgz +0 -0
package/dist/index.js
CHANGED
|
@@ -2643,6 +2643,294 @@ var init_machines = __esm(() => {
|
|
|
2643
2643
|
];
|
|
2644
2644
|
});
|
|
2645
2645
|
|
|
2646
|
+
// src/storage/config.ts
|
|
2647
|
+
var exports_config = {};
|
|
2648
|
+
__export(exports_config, {
|
|
2649
|
+
parseStorageMode: () => parseStorageMode,
|
|
2650
|
+
loadTodosStorageConfig: () => loadTodosStorageConfig,
|
|
2651
|
+
loadStorageConfig: () => loadStorageConfig,
|
|
2652
|
+
isTodosShadowEnabled: () => isTodosShadowEnabled,
|
|
2653
|
+
isTodosRemoteStorageEnabled: () => isTodosRemoteStorageEnabled,
|
|
2654
|
+
getTodosStorageShadowEnvName: () => getTodosStorageShadowEnvName,
|
|
2655
|
+
getTodosStorageMode: () => getTodosStorageMode,
|
|
2656
|
+
getTodosStorageEnvName: () => getTodosStorageEnvName,
|
|
2657
|
+
getTodosStorageDatabaseUrl: () => getTodosStorageDatabaseUrl,
|
|
2658
|
+
getTodosStorageDatabaseEnv: () => getTodosStorageDatabaseEnv,
|
|
2659
|
+
getStorageMode: () => getStorageMode,
|
|
2660
|
+
getStorageDatabaseUrl: () => getStorageDatabaseUrl,
|
|
2661
|
+
getStorageDatabaseEnv: () => getStorageDatabaseEnv,
|
|
2662
|
+
getCanonicalTodosRdsConfig: () => getCanonicalTodosRdsConfig,
|
|
2663
|
+
assertTodosShadowConfig: () => assertTodosShadowConfig,
|
|
2664
|
+
assertTodosRemoteStorageConfig: () => assertTodosRemoteStorageConfig,
|
|
2665
|
+
TODOS_STORAGE_TABLES: () => TODOS_STORAGE_TABLES,
|
|
2666
|
+
TODOS_STORAGE_FALLBACK_ENV: () => TODOS_STORAGE_FALLBACK_ENV,
|
|
2667
|
+
TODOS_STORAGE_ENV: () => TODOS_STORAGE_ENV,
|
|
2668
|
+
STORAGE_TABLES: () => STORAGE_TABLES,
|
|
2669
|
+
CANONICAL_TODOS_RDS_RUNTIME_PATH: () => CANONICAL_TODOS_RDS_RUNTIME_PATH,
|
|
2670
|
+
CANONICAL_TODOS_RDS_DATABASE: () => CANONICAL_TODOS_RDS_DATABASE,
|
|
2671
|
+
CANONICAL_TODOS_RDS_CLUSTER: () => CANONICAL_TODOS_RDS_CLUSTER
|
|
2672
|
+
});
|
|
2673
|
+
function getCanonicalTodosRdsConfig() {
|
|
2674
|
+
return {
|
|
2675
|
+
cluster: CANONICAL_TODOS_RDS_CLUSTER,
|
|
2676
|
+
database: CANONICAL_TODOS_RDS_DATABASE,
|
|
2677
|
+
runtimeSecretPath: CANONICAL_TODOS_RDS_RUNTIME_PATH,
|
|
2678
|
+
primaryEnv: TODOS_STORAGE_ENV.databaseUrl,
|
|
2679
|
+
fallbackEnv: TODOS_STORAGE_FALLBACK_ENV.databaseUrl
|
|
2680
|
+
};
|
|
2681
|
+
}
|
|
2682
|
+
function loadTodosStorageConfig(env = process.env) {
|
|
2683
|
+
const mode = getTodosStorageMode(env);
|
|
2684
|
+
const databaseUrl = getTodosStorageDatabaseUrl(env);
|
|
2685
|
+
const bucket = readStorageEnv(env, "s3Bucket").value;
|
|
2686
|
+
const prefix = readStorageEnv(env, "s3Prefix").value ?? "todos/";
|
|
2687
|
+
const region = readStorageEnv(env, "awsRegion").value;
|
|
2688
|
+
const endpoint = readStorageEnv(env, "s3Endpoint").value;
|
|
2689
|
+
const schema = readStorageEnv(env, "databaseSchema").value;
|
|
2690
|
+
return {
|
|
2691
|
+
service: "todos",
|
|
2692
|
+
mode,
|
|
2693
|
+
...databaseUrl ? {
|
|
2694
|
+
database: {
|
|
2695
|
+
provider: "postgres",
|
|
2696
|
+
url: databaseUrl,
|
|
2697
|
+
ssl: parseBoolean(readStorageEnv(env, "databaseSsl").value, true),
|
|
2698
|
+
...schema ? { schema } : {}
|
|
2699
|
+
}
|
|
2700
|
+
} : {},
|
|
2701
|
+
...bucket ? {
|
|
2702
|
+
objectStorage: {
|
|
2703
|
+
provider: "s3",
|
|
2704
|
+
bucket,
|
|
2705
|
+
prefix,
|
|
2706
|
+
...region ? { region } : {},
|
|
2707
|
+
...endpoint ? { endpoint } : {},
|
|
2708
|
+
forcePathStyle: parseBoolean(readStorageEnv(env, "s3ForcePathStyle").value, false)
|
|
2709
|
+
}
|
|
2710
|
+
} : {},
|
|
2711
|
+
sync: {
|
|
2712
|
+
batchSize: parsePositiveInteger(readStorageEnv(env, "syncBatchSize").value, 500),
|
|
2713
|
+
dryRun: parseBoolean(readStorageEnv(env, "syncDryRun").value, false)
|
|
2714
|
+
}
|
|
2715
|
+
};
|
|
2716
|
+
}
|
|
2717
|
+
function loadStorageConfig(env = process.env) {
|
|
2718
|
+
return loadTodosStorageConfig(env);
|
|
2719
|
+
}
|
|
2720
|
+
function isTodosRemoteStorageEnabled(config) {
|
|
2721
|
+
return config.mode === "remote" || config.mode === "hybrid";
|
|
2722
|
+
}
|
|
2723
|
+
function assertTodosRemoteStorageConfig(config) {
|
|
2724
|
+
if (!isTodosRemoteStorageEnabled(config))
|
|
2725
|
+
return;
|
|
2726
|
+
if (!config.database?.url) {
|
|
2727
|
+
throw new Error(`${TODOS_STORAGE_ENV.databaseUrl} is required when ${TODOS_STORAGE_ENV.mode}=${config.mode}`);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
function parseStorageMode(value) {
|
|
2731
|
+
const normalized = clean(value)?.toLowerCase();
|
|
2732
|
+
if (!normalized)
|
|
2733
|
+
return "local";
|
|
2734
|
+
if (normalized === "local" || normalized === "remote" || normalized === "hybrid")
|
|
2735
|
+
return normalized;
|
|
2736
|
+
throw new Error(`${TODOS_STORAGE_ENV.mode} must be local, remote, or hybrid`);
|
|
2737
|
+
}
|
|
2738
|
+
function getTodosStorageMode(env = process.env) {
|
|
2739
|
+
return parseStorageMode(readStorageEnv(env, "mode").value);
|
|
2740
|
+
}
|
|
2741
|
+
function getStorageMode(env = process.env) {
|
|
2742
|
+
return getTodosStorageMode(env);
|
|
2743
|
+
}
|
|
2744
|
+
function isTodosShadowEnabled(env = process.env) {
|
|
2745
|
+
return parseBoolean(readStorageEnv(env, "shadow").value, false);
|
|
2746
|
+
}
|
|
2747
|
+
function getTodosStorageShadowEnvName(env = process.env) {
|
|
2748
|
+
return readStorageEnv(env, "shadow").name;
|
|
2749
|
+
}
|
|
2750
|
+
function assertTodosShadowConfig(config, env = process.env) {
|
|
2751
|
+
if (!isTodosShadowEnabled(env))
|
|
2752
|
+
return;
|
|
2753
|
+
if (config.mode !== "local") {
|
|
2754
|
+
throw new Error(`${readStorageEnv(env, "shadow").name} shadow mirror requires ${TODOS_STORAGE_ENV.mode}=local (got ${config.mode})`);
|
|
2755
|
+
}
|
|
2756
|
+
if (!config.database?.url) {
|
|
2757
|
+
throw new Error(`${TODOS_STORAGE_ENV.databaseUrl} is required when ${readStorageEnv(env, "shadow").name} is enabled`);
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
function getTodosStorageDatabaseEnv(env = process.env) {
|
|
2761
|
+
return readStorageEnv(env, "databaseUrl").name;
|
|
2762
|
+
}
|
|
2763
|
+
function getStorageDatabaseEnv(env = process.env) {
|
|
2764
|
+
return getTodosStorageDatabaseEnv(env);
|
|
2765
|
+
}
|
|
2766
|
+
function getTodosStorageDatabaseUrl(env = process.env) {
|
|
2767
|
+
return readStorageEnv(env, "databaseUrl").value;
|
|
2768
|
+
}
|
|
2769
|
+
function getStorageDatabaseUrl(env = process.env) {
|
|
2770
|
+
return getTodosStorageDatabaseUrl(env);
|
|
2771
|
+
}
|
|
2772
|
+
function getTodosStorageEnvName(env, key) {
|
|
2773
|
+
return readStorageEnv(env, key).name;
|
|
2774
|
+
}
|
|
2775
|
+
function readStorageEnv(env, key) {
|
|
2776
|
+
const primaryName = TODOS_STORAGE_ENV[key];
|
|
2777
|
+
const primaryValue = clean(env[primaryName]);
|
|
2778
|
+
if (primaryValue !== undefined)
|
|
2779
|
+
return { name: primaryName, value: primaryValue };
|
|
2780
|
+
const fallbackName = TODOS_STORAGE_FALLBACK_ENV[key];
|
|
2781
|
+
const fallbackValue = clean(env[fallbackName]);
|
|
2782
|
+
if (fallbackValue !== undefined)
|
|
2783
|
+
return { name: fallbackName, value: fallbackValue };
|
|
2784
|
+
return { name: primaryName };
|
|
2785
|
+
}
|
|
2786
|
+
function clean(value) {
|
|
2787
|
+
const trimmed = value?.trim();
|
|
2788
|
+
return trimmed ? trimmed : undefined;
|
|
2789
|
+
}
|
|
2790
|
+
function parseBoolean(value, fallback) {
|
|
2791
|
+
const normalized = clean(value)?.toLowerCase();
|
|
2792
|
+
if (!normalized)
|
|
2793
|
+
return fallback;
|
|
2794
|
+
if (["1", "true", "yes", "on"].includes(normalized))
|
|
2795
|
+
return true;
|
|
2796
|
+
if (["0", "false", "no", "off"].includes(normalized))
|
|
2797
|
+
return false;
|
|
2798
|
+
throw new Error(`Expected boolean env value, got ${value}`);
|
|
2799
|
+
}
|
|
2800
|
+
function parsePositiveInteger(value, fallback) {
|
|
2801
|
+
const normalized = clean(value);
|
|
2802
|
+
if (!normalized)
|
|
2803
|
+
return fallback;
|
|
2804
|
+
const parsed = Number.parseInt(normalized, 10);
|
|
2805
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
2806
|
+
throw new Error(`${TODOS_STORAGE_ENV.syncBatchSize} must be a positive integer`);
|
|
2807
|
+
}
|
|
2808
|
+
return parsed;
|
|
2809
|
+
}
|
|
2810
|
+
var TODOS_STORAGE_TABLES, STORAGE_TABLES, TODOS_STORAGE_ENV, TODOS_STORAGE_FALLBACK_ENV, CANONICAL_TODOS_RDS_CLUSTER = "hasna-xyz-infra-apps-prod-postgres", CANONICAL_TODOS_RDS_DATABASE = "todos", CANONICAL_TODOS_RDS_RUNTIME_PATH = "hasna/xyz/opensource/todos/prod/rds";
|
|
2811
|
+
var init_config = __esm(() => {
|
|
2812
|
+
TODOS_STORAGE_TABLES = [
|
|
2813
|
+
"todos_sync_records",
|
|
2814
|
+
"todos_sync_cursors"
|
|
2815
|
+
];
|
|
2816
|
+
STORAGE_TABLES = TODOS_STORAGE_TABLES;
|
|
2817
|
+
TODOS_STORAGE_ENV = {
|
|
2818
|
+
mode: "HASNA_TODOS_STORAGE_MODE",
|
|
2819
|
+
shadow: "HASNA_TODOS_SHADOW",
|
|
2820
|
+
databaseUrl: "HASNA_TODOS_DATABASE_URL",
|
|
2821
|
+
databaseSsl: "HASNA_TODOS_DATABASE_SSL",
|
|
2822
|
+
databaseSchema: "HASNA_TODOS_DATABASE_SCHEMA",
|
|
2823
|
+
s3Bucket: "HASNA_TODOS_S3_BUCKET",
|
|
2824
|
+
s3Prefix: "HASNA_TODOS_S3_PREFIX",
|
|
2825
|
+
awsRegion: "HASNA_TODOS_AWS_REGION",
|
|
2826
|
+
s3Endpoint: "HASNA_TODOS_S3_ENDPOINT",
|
|
2827
|
+
s3ForcePathStyle: "HASNA_TODOS_S3_FORCE_PATH_STYLE",
|
|
2828
|
+
s3AccessKeyId: "HASNA_TODOS_S3_ACCESS_KEY_ID",
|
|
2829
|
+
s3SecretAccessKey: "HASNA_TODOS_S3_SECRET_ACCESS_KEY",
|
|
2830
|
+
s3SessionToken: "HASNA_TODOS_S3_SESSION_TOKEN",
|
|
2831
|
+
syncBatchSize: "HASNA_TODOS_SYNC_BATCH_SIZE",
|
|
2832
|
+
syncDryRun: "HASNA_TODOS_SYNC_DRY_RUN"
|
|
2833
|
+
};
|
|
2834
|
+
TODOS_STORAGE_FALLBACK_ENV = {
|
|
2835
|
+
mode: "TODOS_STORAGE_MODE",
|
|
2836
|
+
shadow: "TODOS_SHADOW",
|
|
2837
|
+
databaseUrl: "TODOS_DATABASE_URL",
|
|
2838
|
+
databaseSsl: "TODOS_DATABASE_SSL",
|
|
2839
|
+
databaseSchema: "TODOS_DATABASE_SCHEMA",
|
|
2840
|
+
s3Bucket: "TODOS_S3_BUCKET",
|
|
2841
|
+
s3Prefix: "TODOS_S3_PREFIX",
|
|
2842
|
+
awsRegion: "TODOS_AWS_REGION",
|
|
2843
|
+
s3Endpoint: "TODOS_S3_ENDPOINT",
|
|
2844
|
+
s3ForcePathStyle: "TODOS_S3_FORCE_PATH_STYLE",
|
|
2845
|
+
s3AccessKeyId: "TODOS_S3_ACCESS_KEY_ID",
|
|
2846
|
+
s3SecretAccessKey: "TODOS_S3_SECRET_ACCESS_KEY",
|
|
2847
|
+
s3SessionToken: "TODOS_S3_SESSION_TOKEN",
|
|
2848
|
+
syncBatchSize: "TODOS_SYNC_BATCH_SIZE",
|
|
2849
|
+
syncDryRun: "TODOS_SYNC_DRY_RUN"
|
|
2850
|
+
};
|
|
2851
|
+
});
|
|
2852
|
+
|
|
2853
|
+
// src/storage/shadow-outbox-schema.ts
|
|
2854
|
+
var exports_shadow_outbox_schema = {};
|
|
2855
|
+
__export(exports_shadow_outbox_schema, {
|
|
2856
|
+
installShadowOutboxSchema: () => installShadowOutboxSchema,
|
|
2857
|
+
SHADOW_TRIGGER_TABLES: () => SHADOW_TRIGGER_TABLES
|
|
2858
|
+
});
|
|
2859
|
+
function installShadowOutboxSchema(db) {
|
|
2860
|
+
db.run(`CREATE TABLE IF NOT EXISTS shadow_outbox (
|
|
2861
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2862
|
+
object_type TEXT NOT NULL,
|
|
2863
|
+
object_id TEXT NOT NULL,
|
|
2864
|
+
op TEXT NOT NULL,
|
|
2865
|
+
enqueued_at INTEGER NOT NULL,
|
|
2866
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
2867
|
+
next_attempt_at INTEGER NOT NULL DEFAULT 0,
|
|
2868
|
+
last_error TEXT,
|
|
2869
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
2870
|
+
revision INTEGER NOT NULL DEFAULT 0
|
|
2871
|
+
)`);
|
|
2872
|
+
ensureColumn(db, "shadow_outbox", "revision", "INTEGER NOT NULL DEFAULT 0");
|
|
2873
|
+
db.run(`CREATE UNIQUE INDEX IF NOT EXISTS shadow_outbox_pending_uq
|
|
2874
|
+
ON shadow_outbox(object_type, object_id) WHERE status='pending'`);
|
|
2875
|
+
db.run(`CREATE INDEX IF NOT EXISTS shadow_outbox_ready_idx
|
|
2876
|
+
ON shadow_outbox(status, next_attempt_at)`);
|
|
2877
|
+
for (const { table, objectType, deletes } of SHADOW_TRIGGER_TABLES) {
|
|
2878
|
+
const exists = db.query(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`).get(table);
|
|
2879
|
+
if (!exists)
|
|
2880
|
+
continue;
|
|
2881
|
+
const insertTrigger = `shadow_ob_${table}_ai`;
|
|
2882
|
+
const updateTrigger = `shadow_ob_${table}_au`;
|
|
2883
|
+
db.run(`DROP TRIGGER IF EXISTS ${insertTrigger}`);
|
|
2884
|
+
db.run(`DROP TRIGGER IF EXISTS ${updateTrigger}`);
|
|
2885
|
+
db.run(upsertTriggerSql(insertTrigger, table, objectType, "INSERT", "NEW"));
|
|
2886
|
+
db.run(upsertTriggerSql(updateTrigger, table, objectType, "UPDATE", "NEW"));
|
|
2887
|
+
if (deletes) {
|
|
2888
|
+
const deleteTrigger = `shadow_ob_${table}_ad`;
|
|
2889
|
+
db.run(`DROP TRIGGER IF EXISTS ${deleteTrigger}`);
|
|
2890
|
+
db.run(deleteTriggerSql(deleteTrigger, table, objectType));
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
function ensureColumn(db, table, column, definition) {
|
|
2895
|
+
const rows = db.query(`PRAGMA table_info(${table})`).all();
|
|
2896
|
+
if (rows.some((row) => row.name === column))
|
|
2897
|
+
return;
|
|
2898
|
+
db.run(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
|
2899
|
+
}
|
|
2900
|
+
function upsertTriggerSql(name, table, objectType, event, row) {
|
|
2901
|
+
return `CREATE TRIGGER IF NOT EXISTS ${name}
|
|
2902
|
+
AFTER ${event} ON ${table}
|
|
2903
|
+
BEGIN
|
|
2904
|
+
INSERT INTO shadow_outbox(object_type, object_id, op, enqueued_at, attempts, next_attempt_at, last_error, status, revision)
|
|
2905
|
+
VALUES('${objectType}', ${row}.id, 'upsert', CAST(strftime('%s','now') AS INTEGER) * 1000, 0, 0, NULL, 'pending', 0)
|
|
2906
|
+
ON CONFLICT(object_type, object_id) WHERE status='pending'
|
|
2907
|
+
DO UPDATE SET op='upsert', enqueued_at=excluded.enqueued_at, attempts=0, next_attempt_at=0, last_error=NULL, revision=shadow_outbox.revision + 1;
|
|
2908
|
+
END`;
|
|
2909
|
+
}
|
|
2910
|
+
function deleteTriggerSql(name, table, objectType) {
|
|
2911
|
+
return `CREATE TRIGGER IF NOT EXISTS ${name}
|
|
2912
|
+
AFTER DELETE ON ${table}
|
|
2913
|
+
BEGIN
|
|
2914
|
+
INSERT INTO shadow_outbox(object_type, object_id, op, enqueued_at, attempts, next_attempt_at, last_error, status, revision)
|
|
2915
|
+
VALUES('${objectType}', OLD.id, 'delete', CAST(strftime('%s','now') AS INTEGER) * 1000, 0, 0, NULL, 'pending', 0)
|
|
2916
|
+
ON CONFLICT(object_type, object_id) WHERE status='pending'
|
|
2917
|
+
DO UPDATE SET op='delete', enqueued_at=excluded.enqueued_at, attempts=0, next_attempt_at=0, last_error=NULL, revision=shadow_outbox.revision + 1;
|
|
2918
|
+
END`;
|
|
2919
|
+
}
|
|
2920
|
+
var SHADOW_TRIGGER_TABLES;
|
|
2921
|
+
var init_shadow_outbox_schema = __esm(() => {
|
|
2922
|
+
SHADOW_TRIGGER_TABLES = [
|
|
2923
|
+
{ table: "tasks", objectType: "tasks", deletes: true },
|
|
2924
|
+
{ table: "projects", objectType: "projects", deletes: true },
|
|
2925
|
+
{ table: "project_machine_paths", objectType: "project_machine_paths", deletes: true },
|
|
2926
|
+
{ table: "plans", objectType: "plans", deletes: true },
|
|
2927
|
+
{ table: "agents", objectType: "agents", deletes: false },
|
|
2928
|
+
{ table: "task_lists", objectType: "task_lists", deletes: true },
|
|
2929
|
+
{ table: "task_templates", objectType: "templates", deletes: true },
|
|
2930
|
+
{ table: "task_history", objectType: "audit_history", deletes: false }
|
|
2931
|
+
];
|
|
2932
|
+
});
|
|
2933
|
+
|
|
2646
2934
|
// src/db/database.ts
|
|
2647
2935
|
var exports_database = {};
|
|
2648
2936
|
__export(exports_database, {
|
|
@@ -2733,8 +3021,20 @@ function openDatabase(path) {
|
|
|
2733
3021
|
runMigrations(db);
|
|
2734
3022
|
backfillTaskTags(db);
|
|
2735
3023
|
backfillMachineId(db);
|
|
3024
|
+
maybeInstallShadowCapture(db);
|
|
2736
3025
|
return db;
|
|
2737
3026
|
}
|
|
3027
|
+
function maybeInstallShadowCapture(db) {
|
|
3028
|
+
try {
|
|
3029
|
+
const { isTodosShadowEnabled: isTodosShadowEnabled2 } = (init_config(), __toCommonJS(exports_config));
|
|
3030
|
+
if (!isTodosShadowEnabled2())
|
|
3031
|
+
return;
|
|
3032
|
+
const { installShadowOutboxSchema: installShadowOutboxSchema2 } = (init_shadow_outbox_schema(), __toCommonJS(exports_shadow_outbox_schema));
|
|
3033
|
+
installShadowOutboxSchema2(db);
|
|
3034
|
+
} catch (error) {
|
|
3035
|
+
console.error(`[todos] shadow capture install failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
2738
3038
|
function getDatabase(dbPath) {
|
|
2739
3039
|
const path = dbPath || getDbPath();
|
|
2740
3040
|
if (_db && _dbPath === path)
|
|
@@ -3111,7 +3411,7 @@ function getCompletionGuardConfig(projectPath) {
|
|
|
3111
3411
|
return global;
|
|
3112
3412
|
}
|
|
3113
3413
|
var cached = null, GUARD_DEFAULTS;
|
|
3114
|
-
var
|
|
3414
|
+
var init_config2 = __esm(() => {
|
|
3115
3415
|
init_sync_utils();
|
|
3116
3416
|
GUARD_DEFAULTS = {
|
|
3117
3417
|
enabled: false,
|
|
@@ -3482,7 +3782,7 @@ function checkCompletionGuard(task, agentId, db, configOverride) {
|
|
|
3482
3782
|
}
|
|
3483
3783
|
var init_completion_guard = __esm(() => {
|
|
3484
3784
|
init_types();
|
|
3485
|
-
|
|
3785
|
+
init_config2();
|
|
3486
3786
|
init_projects();
|
|
3487
3787
|
});
|
|
3488
3788
|
|
|
@@ -3490,8 +3790,8 @@ var init_completion_guard = __esm(() => {
|
|
|
3490
3790
|
import { tmpdir } from "os";
|
|
3491
3791
|
import { resolve as resolve3, sep } from "path";
|
|
3492
3792
|
function envFlag(name) {
|
|
3493
|
-
const value = process.env[name];
|
|
3494
|
-
return value === "1" || value === "true" || value === "yes";
|
|
3793
|
+
const value = process.env[name]?.trim().toLowerCase();
|
|
3794
|
+
return value === "1" || value === "true" || value === "yes" || value === "on";
|
|
3495
3795
|
}
|
|
3496
3796
|
function isUnder(parent, child) {
|
|
3497
3797
|
const normalizedParent = resolve3(parent);
|
|
@@ -3517,7 +3817,7 @@ function usesIsolatedTodosHome() {
|
|
|
3517
3817
|
function shouldEmitSharedTaskEvents(dbPath) {
|
|
3518
3818
|
if (envFlag("TODOS_DISABLE_SHARED_EVENTS"))
|
|
3519
3819
|
return false;
|
|
3520
|
-
if (envFlag("TODOS_ALLOW_EPHEMERAL_SHARED_EVENTS"))
|
|
3820
|
+
if (envFlag("TODOS_ALLOW_EPHEMERAL_SHARED_EVENTS") || envFlag("HASNA_TODOS_ALLOW_GLOBAL_EVENTS_FROM_TEMP_DB"))
|
|
3521
3821
|
return true;
|
|
3522
3822
|
if (!isEphemeralTodosDatabase(dbPath))
|
|
3523
3823
|
return true;
|
|
@@ -3619,7 +3919,7 @@ function upsertSecretSafetyConfig(input) {
|
|
|
3619
3919
|
}
|
|
3620
3920
|
var DEFAULT_SECRET_PATTERNS, DEFAULT_SECRET_KEY_PATTERN, NON_SECRET_USAGE_KEYS;
|
|
3621
3921
|
var init_redaction = __esm(() => {
|
|
3622
|
-
|
|
3922
|
+
init_config2();
|
|
3623
3923
|
DEFAULT_SECRET_PATTERNS = [
|
|
3624
3924
|
{ name: "aws-access-key", regex: /\b(AKIA|ASIA)[0-9A-Z]{16}\b/g, replacement: "[REDACTED_AWS_KEY]" },
|
|
3625
3925
|
{ name: "private-key", regex: /-----BEGIN (?:RSA |EC |OPENSSH |)PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |)PRIVATE KEY-----/g, replacement: "[REDACTED_PRIVATE_KEY]" },
|
|
@@ -3776,7 +4076,7 @@ function checkWorkspacePermission(input = {}) {
|
|
|
3776
4076
|
}
|
|
3777
4077
|
var DEFAULT_DENYLIST, DEFAULT_ENV_REDACTIONS, PRESET_DEFAULTS;
|
|
3778
4078
|
var init_workspace_trust = __esm(() => {
|
|
3779
|
-
|
|
4079
|
+
init_config2();
|
|
3780
4080
|
DEFAULT_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
|
|
3781
4081
|
DEFAULT_ENV_REDACTIONS = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
|
|
3782
4082
|
PRESET_DEFAULTS = {
|
|
@@ -4010,7 +4310,7 @@ function explainRunnerSandbox(input = {}) {
|
|
|
4010
4310
|
}
|
|
4011
4311
|
var DEFAULT_COMMAND_DENYLIST, DEFAULT_ENV_REDACTIONS2;
|
|
4012
4312
|
var init_runner_sandbox = __esm(() => {
|
|
4013
|
-
|
|
4313
|
+
init_config2();
|
|
4014
4314
|
init_workspace_trust();
|
|
4015
4315
|
DEFAULT_COMMAND_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
|
|
4016
4316
|
DEFAULT_ENV_REDACTIONS2 = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
|
|
@@ -4246,7 +4546,7 @@ var LOCAL_EVENT_TYPES, VALID_TARGETS;
|
|
|
4246
4546
|
var init_event_hooks = __esm(() => {
|
|
4247
4547
|
init_redaction();
|
|
4248
4548
|
init_runner_sandbox();
|
|
4249
|
-
|
|
4549
|
+
init_config2();
|
|
4250
4550
|
init_event_emission_safety();
|
|
4251
4551
|
LOCAL_EVENT_TYPES = [
|
|
4252
4552
|
"task.created",
|
|
@@ -16636,7 +16936,7 @@ function writeSdkIntegrationFixtures(directory, options = {}) {
|
|
|
16636
16936
|
init_audit();
|
|
16637
16937
|
init_database();
|
|
16638
16938
|
init_tasks();
|
|
16639
|
-
|
|
16939
|
+
init_config2();
|
|
16640
16940
|
init_event_emission_safety();
|
|
16641
16941
|
init_event_hooks();
|
|
16642
16942
|
|
|
@@ -17260,7 +17560,7 @@ init_task_lifecycle();
|
|
|
17260
17560
|
init_tasks();
|
|
17261
17561
|
init_plans();
|
|
17262
17562
|
init_task_runs();
|
|
17263
|
-
|
|
17563
|
+
init_config2();
|
|
17264
17564
|
var LOCAL_ROADMAP_SCHEMA_VERSION = 1;
|
|
17265
17565
|
function timestamp() {
|
|
17266
17566
|
return new Date().toISOString();
|
|
@@ -17626,7 +17926,7 @@ function renderRoadmapMarkdown(idOrName, db) {
|
|
|
17626
17926
|
// src/lib/audit-ledger.ts
|
|
17627
17927
|
init_database();
|
|
17628
17928
|
init_task_runs();
|
|
17629
|
-
|
|
17929
|
+
init_config2();
|
|
17630
17930
|
init_redaction();
|
|
17631
17931
|
import { createHash as createHash5 } from "crypto";
|
|
17632
17932
|
var LOCAL_AUDIT_LEDGER_SCHEMA_VERSION = 1;
|
|
@@ -19843,7 +20143,7 @@ init_task_runs();
|
|
|
19843
20143
|
init_event_hooks();
|
|
19844
20144
|
|
|
19845
20145
|
// src/lib/terminal-notifications.ts
|
|
19846
|
-
|
|
20146
|
+
init_config2();
|
|
19847
20147
|
init_event_hooks();
|
|
19848
20148
|
init_redaction();
|
|
19849
20149
|
var SEVERITY_ORDER = {
|
|
@@ -21013,7 +21313,7 @@ function renderLocalReportMarkdown(report) {
|
|
|
21013
21313
|
`;
|
|
21014
21314
|
}
|
|
21015
21315
|
// src/lib/local-encryption.ts
|
|
21016
|
-
|
|
21316
|
+
init_config2();
|
|
21017
21317
|
init_redaction();
|
|
21018
21318
|
import { createCipheriv, createDecipheriv, createHash as createHash8, randomBytes, scryptSync, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
21019
21319
|
var TODOS_ENCRYPTED_VALUE_KIND = "hasna.todos.encrypted-value";
|
|
@@ -21842,168 +22142,9 @@ var TODOS_REGISTRY = createTodosRegistry({
|
|
|
21842
22142
|
generatedAt: "1970-01-01T00:00:00.000Z"
|
|
21843
22143
|
});
|
|
21844
22144
|
|
|
21845
|
-
// src/storage/
|
|
21846
|
-
|
|
21847
|
-
|
|
21848
|
-
"todos_sync_cursors"
|
|
21849
|
-
];
|
|
21850
|
-
var STORAGE_TABLES = TODOS_STORAGE_TABLES;
|
|
21851
|
-
var TODOS_STORAGE_ENV = {
|
|
21852
|
-
mode: "HASNA_TODOS_STORAGE_MODE",
|
|
21853
|
-
databaseUrl: "HASNA_TODOS_DATABASE_URL",
|
|
21854
|
-
databaseSsl: "HASNA_TODOS_DATABASE_SSL",
|
|
21855
|
-
databaseSchema: "HASNA_TODOS_DATABASE_SCHEMA",
|
|
21856
|
-
s3Bucket: "HASNA_TODOS_S3_BUCKET",
|
|
21857
|
-
s3Prefix: "HASNA_TODOS_S3_PREFIX",
|
|
21858
|
-
awsRegion: "HASNA_TODOS_AWS_REGION",
|
|
21859
|
-
s3Endpoint: "HASNA_TODOS_S3_ENDPOINT",
|
|
21860
|
-
s3ForcePathStyle: "HASNA_TODOS_S3_FORCE_PATH_STYLE",
|
|
21861
|
-
s3AccessKeyId: "HASNA_TODOS_S3_ACCESS_KEY_ID",
|
|
21862
|
-
s3SecretAccessKey: "HASNA_TODOS_S3_SECRET_ACCESS_KEY",
|
|
21863
|
-
s3SessionToken: "HASNA_TODOS_S3_SESSION_TOKEN",
|
|
21864
|
-
syncBatchSize: "HASNA_TODOS_SYNC_BATCH_SIZE",
|
|
21865
|
-
syncDryRun: "HASNA_TODOS_SYNC_DRY_RUN"
|
|
21866
|
-
};
|
|
21867
|
-
var TODOS_STORAGE_FALLBACK_ENV = {
|
|
21868
|
-
mode: "TODOS_STORAGE_MODE",
|
|
21869
|
-
databaseUrl: "TODOS_DATABASE_URL",
|
|
21870
|
-
databaseSsl: "TODOS_DATABASE_SSL",
|
|
21871
|
-
databaseSchema: "TODOS_DATABASE_SCHEMA",
|
|
21872
|
-
s3Bucket: "TODOS_S3_BUCKET",
|
|
21873
|
-
s3Prefix: "TODOS_S3_PREFIX",
|
|
21874
|
-
awsRegion: "TODOS_AWS_REGION",
|
|
21875
|
-
s3Endpoint: "TODOS_S3_ENDPOINT",
|
|
21876
|
-
s3ForcePathStyle: "TODOS_S3_FORCE_PATH_STYLE",
|
|
21877
|
-
s3AccessKeyId: "TODOS_S3_ACCESS_KEY_ID",
|
|
21878
|
-
s3SecretAccessKey: "TODOS_S3_SECRET_ACCESS_KEY",
|
|
21879
|
-
s3SessionToken: "TODOS_S3_SESSION_TOKEN",
|
|
21880
|
-
syncBatchSize: "TODOS_SYNC_BATCH_SIZE",
|
|
21881
|
-
syncDryRun: "TODOS_SYNC_DRY_RUN"
|
|
21882
|
-
};
|
|
21883
|
-
var CANONICAL_TODOS_RDS_CLUSTER = "hasna-xyz-infra-apps-prod-postgres";
|
|
21884
|
-
var CANONICAL_TODOS_RDS_DATABASE = "todos";
|
|
21885
|
-
var CANONICAL_TODOS_RDS_RUNTIME_PATH = "hasna/xyz/opensource/todos/prod/rds";
|
|
21886
|
-
function getCanonicalTodosRdsConfig() {
|
|
21887
|
-
return {
|
|
21888
|
-
cluster: CANONICAL_TODOS_RDS_CLUSTER,
|
|
21889
|
-
database: CANONICAL_TODOS_RDS_DATABASE,
|
|
21890
|
-
runtimeSecretPath: CANONICAL_TODOS_RDS_RUNTIME_PATH,
|
|
21891
|
-
primaryEnv: TODOS_STORAGE_ENV.databaseUrl,
|
|
21892
|
-
fallbackEnv: TODOS_STORAGE_FALLBACK_ENV.databaseUrl
|
|
21893
|
-
};
|
|
21894
|
-
}
|
|
21895
|
-
function loadTodosStorageConfig(env = process.env) {
|
|
21896
|
-
const mode = getTodosStorageMode(env);
|
|
21897
|
-
const databaseUrl = getTodosStorageDatabaseUrl(env);
|
|
21898
|
-
const bucket = readStorageEnv(env, "s3Bucket").value;
|
|
21899
|
-
const prefix = readStorageEnv(env, "s3Prefix").value ?? "todos/";
|
|
21900
|
-
const region = readStorageEnv(env, "awsRegion").value;
|
|
21901
|
-
const endpoint = readStorageEnv(env, "s3Endpoint").value;
|
|
21902
|
-
const schema = readStorageEnv(env, "databaseSchema").value;
|
|
21903
|
-
return {
|
|
21904
|
-
service: "todos",
|
|
21905
|
-
mode,
|
|
21906
|
-
...databaseUrl ? {
|
|
21907
|
-
database: {
|
|
21908
|
-
provider: "postgres",
|
|
21909
|
-
url: databaseUrl,
|
|
21910
|
-
ssl: parseBoolean(readStorageEnv(env, "databaseSsl").value, true),
|
|
21911
|
-
...schema ? { schema } : {}
|
|
21912
|
-
}
|
|
21913
|
-
} : {},
|
|
21914
|
-
...bucket ? {
|
|
21915
|
-
objectStorage: {
|
|
21916
|
-
provider: "s3",
|
|
21917
|
-
bucket,
|
|
21918
|
-
prefix,
|
|
21919
|
-
...region ? { region } : {},
|
|
21920
|
-
...endpoint ? { endpoint } : {},
|
|
21921
|
-
forcePathStyle: parseBoolean(readStorageEnv(env, "s3ForcePathStyle").value, false)
|
|
21922
|
-
}
|
|
21923
|
-
} : {},
|
|
21924
|
-
sync: {
|
|
21925
|
-
batchSize: parsePositiveInteger(readStorageEnv(env, "syncBatchSize").value, 500),
|
|
21926
|
-
dryRun: parseBoolean(readStorageEnv(env, "syncDryRun").value, false)
|
|
21927
|
-
}
|
|
21928
|
-
};
|
|
21929
|
-
}
|
|
21930
|
-
function loadStorageConfig(env = process.env) {
|
|
21931
|
-
return loadTodosStorageConfig(env);
|
|
21932
|
-
}
|
|
21933
|
-
function isTodosRemoteStorageEnabled(config) {
|
|
21934
|
-
return config.mode === "remote" || config.mode === "hybrid";
|
|
21935
|
-
}
|
|
21936
|
-
function assertTodosRemoteStorageConfig(config) {
|
|
21937
|
-
if (!isTodosRemoteStorageEnabled(config))
|
|
21938
|
-
return;
|
|
21939
|
-
if (!config.database?.url) {
|
|
21940
|
-
throw new Error(`${TODOS_STORAGE_ENV.databaseUrl} is required when ${TODOS_STORAGE_ENV.mode}=${config.mode}`);
|
|
21941
|
-
}
|
|
21942
|
-
}
|
|
21943
|
-
function parseStorageMode(value) {
|
|
21944
|
-
const normalized = clean(value)?.toLowerCase();
|
|
21945
|
-
if (!normalized)
|
|
21946
|
-
return "local";
|
|
21947
|
-
if (normalized === "local" || normalized === "remote" || normalized === "hybrid")
|
|
21948
|
-
return normalized;
|
|
21949
|
-
throw new Error(`${TODOS_STORAGE_ENV.mode} must be local, remote, or hybrid`);
|
|
21950
|
-
}
|
|
21951
|
-
function getTodosStorageMode(env = process.env) {
|
|
21952
|
-
return parseStorageMode(readStorageEnv(env, "mode").value);
|
|
21953
|
-
}
|
|
21954
|
-
function getStorageMode(env = process.env) {
|
|
21955
|
-
return getTodosStorageMode(env);
|
|
21956
|
-
}
|
|
21957
|
-
function getTodosStorageDatabaseEnv(env = process.env) {
|
|
21958
|
-
return readStorageEnv(env, "databaseUrl").name;
|
|
21959
|
-
}
|
|
21960
|
-
function getStorageDatabaseEnv(env = process.env) {
|
|
21961
|
-
return getTodosStorageDatabaseEnv(env);
|
|
21962
|
-
}
|
|
21963
|
-
function getTodosStorageDatabaseUrl(env = process.env) {
|
|
21964
|
-
return readStorageEnv(env, "databaseUrl").value;
|
|
21965
|
-
}
|
|
21966
|
-
function getStorageDatabaseUrl(env = process.env) {
|
|
21967
|
-
return getTodosStorageDatabaseUrl(env);
|
|
21968
|
-
}
|
|
21969
|
-
function getTodosStorageEnvName(env, key) {
|
|
21970
|
-
return readStorageEnv(env, key).name;
|
|
21971
|
-
}
|
|
21972
|
-
function readStorageEnv(env, key) {
|
|
21973
|
-
const primaryName = TODOS_STORAGE_ENV[key];
|
|
21974
|
-
const primaryValue = clean(env[primaryName]);
|
|
21975
|
-
if (primaryValue !== undefined)
|
|
21976
|
-
return { name: primaryName, value: primaryValue };
|
|
21977
|
-
const fallbackName = TODOS_STORAGE_FALLBACK_ENV[key];
|
|
21978
|
-
const fallbackValue = clean(env[fallbackName]);
|
|
21979
|
-
if (fallbackValue !== undefined)
|
|
21980
|
-
return { name: fallbackName, value: fallbackValue };
|
|
21981
|
-
return { name: primaryName };
|
|
21982
|
-
}
|
|
21983
|
-
function clean(value) {
|
|
21984
|
-
const trimmed = value?.trim();
|
|
21985
|
-
return trimmed ? trimmed : undefined;
|
|
21986
|
-
}
|
|
21987
|
-
function parseBoolean(value, fallback) {
|
|
21988
|
-
const normalized = clean(value)?.toLowerCase();
|
|
21989
|
-
if (!normalized)
|
|
21990
|
-
return fallback;
|
|
21991
|
-
if (["1", "true", "yes", "on"].includes(normalized))
|
|
21992
|
-
return true;
|
|
21993
|
-
if (["0", "false", "no", "off"].includes(normalized))
|
|
21994
|
-
return false;
|
|
21995
|
-
throw new Error(`Expected boolean env value, got ${value}`);
|
|
21996
|
-
}
|
|
21997
|
-
function parsePositiveInteger(value, fallback) {
|
|
21998
|
-
const normalized = clean(value);
|
|
21999
|
-
if (!normalized)
|
|
22000
|
-
return fallback;
|
|
22001
|
-
const parsed = Number.parseInt(normalized, 10);
|
|
22002
|
-
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
22003
|
-
throw new Error(`${TODOS_STORAGE_ENV.syncBatchSize} must be a positive integer`);
|
|
22004
|
-
}
|
|
22005
|
-
return parsed;
|
|
22006
|
-
}
|
|
22145
|
+
// src/storage/index.ts
|
|
22146
|
+
init_config();
|
|
22147
|
+
|
|
22007
22148
|
// src/storage/local-sqlite.ts
|
|
22008
22149
|
init_tasks();
|
|
22009
22150
|
init_projects();
|
|
@@ -23114,6 +23255,9 @@ function postgresTodosSyncSchemaSql(tableName = DEFAULT_TODOS_POSTGRES_SYNC_TABL
|
|
|
23114
23255
|
PRIMARY KEY (service, object_type, object_id)
|
|
23115
23256
|
)`,
|
|
23116
23257
|
`CREATE INDEX IF NOT EXISTS ${tableName}_updated_idx ON ${tableName} (service, updated_at)`,
|
|
23258
|
+
`CREATE INDEX IF NOT EXISTS ${tableName}_task_status_idx ON ${tableName} ((payload->>'status')) WHERE object_type = 'tasks' AND deleted_at IS NULL`,
|
|
23259
|
+
`CREATE INDEX IF NOT EXISTS ${tableName}_task_project_idx ON ${tableName} ((payload->>'project_id')) WHERE object_type = 'tasks' AND deleted_at IS NULL`,
|
|
23260
|
+
`CREATE INDEX IF NOT EXISTS ${tableName}_payload_gin ON ${tableName} USING gin (payload jsonb_path_ops)`,
|
|
23117
23261
|
`CREATE TABLE IF NOT EXISTS ${cursorTableName} (
|
|
23118
23262
|
service text NOT NULL,
|
|
23119
23263
|
cursor_name text NOT NULL,
|
|
@@ -23164,7 +23308,7 @@ class PostgresTodosSyncStore {
|
|
|
23164
23308
|
this.service,
|
|
23165
23309
|
entry.type,
|
|
23166
23310
|
entry.id,
|
|
23167
|
-
|
|
23311
|
+
entry.payload,
|
|
23168
23312
|
entry.updatedAt,
|
|
23169
23313
|
entry.deletedAt,
|
|
23170
23314
|
sourceMachineId,
|
|
@@ -23370,8 +23514,8 @@ function createPostgresTodosStorageAdapter(options) {
|
|
|
23370
23514
|
tasks: {
|
|
23371
23515
|
create: (input, context) => createTask2(input, store, context),
|
|
23372
23516
|
get: (id) => store.get("tasks", id),
|
|
23373
|
-
list: (filter = {}) =>
|
|
23374
|
-
count:
|
|
23517
|
+
list: (filter = {}) => store.listTasks(filter),
|
|
23518
|
+
count: (filter = {}) => store.countTasks(filter),
|
|
23375
23519
|
update: (id, input) => updateTask2(id, input, store),
|
|
23376
23520
|
delete: (id, context) => store.delete("tasks", id, context),
|
|
23377
23521
|
start: (id, agentId) => startTask2(id, agentId, store),
|
|
@@ -23487,6 +23631,72 @@ class PostgresJsonRecordStore {
|
|
|
23487
23631
|
updatedAt: stringValue2(row.updated_at) ?? new Date().toISOString()
|
|
23488
23632
|
}));
|
|
23489
23633
|
}
|
|
23634
|
+
buildTaskFilterSql(filter) {
|
|
23635
|
+
const params = [this.service, "tasks"];
|
|
23636
|
+
const conds = ["service = $1", "object_type = $2", "deleted_at IS NULL"];
|
|
23637
|
+
const p = (value) => {
|
|
23638
|
+
params.push(value);
|
|
23639
|
+
return `$${params.length}`;
|
|
23640
|
+
};
|
|
23641
|
+
const inClause = (column, values) => {
|
|
23642
|
+
if (values.length === 0)
|
|
23643
|
+
return "1=0";
|
|
23644
|
+
return `${column} IN (${values.map((v) => p(v)).join(", ")})`;
|
|
23645
|
+
};
|
|
23646
|
+
if (filter.ids)
|
|
23647
|
+
conds.push(inClause("payload->>'id'", filter.ids));
|
|
23648
|
+
if (filter.project_id !== undefined)
|
|
23649
|
+
conds.push(`payload->>'project_id' = ${p(filter.project_id)}`);
|
|
23650
|
+
if (filter.parent_id !== undefined)
|
|
23651
|
+
conds.push(`payload->>'parent_id' IS NOT DISTINCT FROM ${p(filter.parent_id)}`);
|
|
23652
|
+
if (filter.plan_id !== undefined)
|
|
23653
|
+
conds.push(`payload->>'plan_id' = ${p(filter.plan_id)}`);
|
|
23654
|
+
if (filter.task_list_id !== undefined)
|
|
23655
|
+
conds.push(`payload->>'task_list_id' = ${p(filter.task_list_id)}`);
|
|
23656
|
+
if (filter.status !== undefined)
|
|
23657
|
+
conds.push(inClause("payload->>'status'", toFilterArray(filter.status)));
|
|
23658
|
+
if (filter.priority !== undefined)
|
|
23659
|
+
conds.push(inClause("payload->>'priority'", toFilterArray(filter.priority)));
|
|
23660
|
+
if (filter.assigned_to !== undefined)
|
|
23661
|
+
conds.push(`payload->>'assigned_to' = ${p(filter.assigned_to)}`);
|
|
23662
|
+
if (filter.agent_id !== undefined)
|
|
23663
|
+
conds.push(`payload->>'agent_id' = ${p(filter.agent_id)}`);
|
|
23664
|
+
if (filter.session_id !== undefined)
|
|
23665
|
+
conds.push(`payload->>'session_id' = ${p(filter.session_id)}`);
|
|
23666
|
+
if (filter.tags?.length)
|
|
23667
|
+
conds.push(`payload->'tags' @> ${p(filter.tags)}::jsonb`);
|
|
23668
|
+
if (filter.has_recurrence !== undefined) {
|
|
23669
|
+
conds.push(`(COALESCE(payload->>'recurrence_rule', '') <> '') = ${p(filter.has_recurrence)}`);
|
|
23670
|
+
}
|
|
23671
|
+
if (filter.task_type !== undefined) {
|
|
23672
|
+
conds.push(inClause("COALESCE(payload->>'task_type', '')", toFilterArray(filter.task_type)));
|
|
23673
|
+
}
|
|
23674
|
+
if (filter.include_subtasks !== true)
|
|
23675
|
+
conds.push(`(payload->>'parent_id' IS NULL OR payload->>'parent_id' = '')`);
|
|
23676
|
+
return { where: conds.join(" AND "), params };
|
|
23677
|
+
}
|
|
23678
|
+
async listTasks(filter) {
|
|
23679
|
+
await this.ensureSchema();
|
|
23680
|
+
const { where, params } = this.buildTaskFilterSql(filter);
|
|
23681
|
+
let sql = `/* todos:list-tasks */ SELECT payload FROM ${this.tableName} WHERE ${where} ${TASK_ORDER_BY}`;
|
|
23682
|
+
if (filter.limit !== undefined) {
|
|
23683
|
+
params.push(filter.limit);
|
|
23684
|
+
sql += ` LIMIT $${params.length}`;
|
|
23685
|
+
}
|
|
23686
|
+
if (filter.offset) {
|
|
23687
|
+
params.push(filter.offset);
|
|
23688
|
+
sql += ` OFFSET $${params.length}`;
|
|
23689
|
+
}
|
|
23690
|
+
const result = await this.options.client.query(sql, params);
|
|
23691
|
+
return result.rows.map((row) => payloadRecord2(row.payload));
|
|
23692
|
+
}
|
|
23693
|
+
async countTasks(filter) {
|
|
23694
|
+
await this.ensureSchema();
|
|
23695
|
+
const { where, params } = this.buildTaskFilterSql(filter);
|
|
23696
|
+
const sql = `/* todos:count-tasks */ SELECT COUNT(*)::int AS count FROM ${this.tableName} WHERE ${where}`;
|
|
23697
|
+
const result = await this.options.client.query(sql, params);
|
|
23698
|
+
return Number(result.rows[0]?.count ?? 0);
|
|
23699
|
+
}
|
|
23490
23700
|
async listTombstones() {
|
|
23491
23701
|
await this.ensureSchema();
|
|
23492
23702
|
const result = await this.options.client.query(`SELECT object_type, object_id, payload, updated_at, deleted_at, source_machine_id, version
|
|
@@ -23527,7 +23737,7 @@ class PostgresJsonRecordStore {
|
|
|
23527
23737
|
this.service,
|
|
23528
23738
|
type,
|
|
23529
23739
|
value.id,
|
|
23530
|
-
|
|
23740
|
+
jsonbParam(value),
|
|
23531
23741
|
updatedAt,
|
|
23532
23742
|
context.requestId ?? this.sourceMachineId ?? null,
|
|
23533
23743
|
numberValue3(value.version)
|
|
@@ -23589,7 +23799,7 @@ class PostgresJsonRecordStore {
|
|
|
23589
23799
|
this.service,
|
|
23590
23800
|
tombstone.object_type,
|
|
23591
23801
|
tombstone.object_id,
|
|
23592
|
-
|
|
23802
|
+
jsonbParam(tombstone.payload ?? { id: tombstone.object_id, deleted_at: deletedAt }),
|
|
23593
23803
|
updatedAt,
|
|
23594
23804
|
deletedAt,
|
|
23595
23805
|
tombstone.source_machine_id ?? context.requestId ?? this.sourceMachineId ?? null,
|
|
@@ -23768,13 +23978,15 @@ async function patchTask(task2, patch, store) {
|
|
|
23768
23978
|
await store.upsert("tasks", updated);
|
|
23769
23979
|
return updated;
|
|
23770
23980
|
}
|
|
23981
|
+
var TASK_ORDER_BY = "ORDER BY CASE payload->>'priority' WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END ASC, payload->>'created_at' ASC, payload->>'id' ASC";
|
|
23982
|
+
function toFilterArray(value) {
|
|
23983
|
+
return Array.isArray(value) ? value : [value];
|
|
23984
|
+
}
|
|
23985
|
+
function jsonbParam(value) {
|
|
23986
|
+
return value;
|
|
23987
|
+
}
|
|
23771
23988
|
async function listTasks2(filter, store) {
|
|
23772
|
-
|
|
23773
|
-
tasks = tasks.filter((task2) => taskMatchesFilter(task2, filter));
|
|
23774
|
-
tasks.sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority) || a.created_at.localeCompare(b.created_at));
|
|
23775
|
-
const offset = filter.offset ?? 0;
|
|
23776
|
-
const limit = filter.limit ?? tasks.length;
|
|
23777
|
-
return tasks.slice(offset, offset + limit);
|
|
23989
|
+
return store.listTasks(filter);
|
|
23778
23990
|
}
|
|
23779
23991
|
async function getNextTask2(filters, store) {
|
|
23780
23992
|
return (await listTasks2({ ...filters, status: "pending", limit: 1 }, store))[0] ?? null;
|
|
@@ -24082,43 +24294,6 @@ async function generateProjectPrefix(name, store) {
|
|
|
24082
24294
|
}
|
|
24083
24295
|
return candidate;
|
|
24084
24296
|
}
|
|
24085
|
-
function taskMatchesFilter(task2, filter) {
|
|
24086
|
-
if (filter.ids && !filter.ids.includes(task2.id))
|
|
24087
|
-
return false;
|
|
24088
|
-
if (filter.project_id !== undefined && task2.project_id !== filter.project_id)
|
|
24089
|
-
return false;
|
|
24090
|
-
if (filter.parent_id !== undefined && task2.parent_id !== filter.parent_id)
|
|
24091
|
-
return false;
|
|
24092
|
-
if (filter.plan_id !== undefined && task2.plan_id !== filter.plan_id)
|
|
24093
|
-
return false;
|
|
24094
|
-
if (filter.task_list_id !== undefined && task2.task_list_id !== filter.task_list_id)
|
|
24095
|
-
return false;
|
|
24096
|
-
if (filter.status !== undefined && !matchesOne(task2.status, filter.status))
|
|
24097
|
-
return false;
|
|
24098
|
-
if (filter.priority !== undefined && !matchesOne(task2.priority, filter.priority))
|
|
24099
|
-
return false;
|
|
24100
|
-
if (filter.assigned_to !== undefined && task2.assigned_to !== filter.assigned_to)
|
|
24101
|
-
return false;
|
|
24102
|
-
if (filter.agent_id !== undefined && task2.agent_id !== filter.agent_id)
|
|
24103
|
-
return false;
|
|
24104
|
-
if (filter.session_id !== undefined && task2.session_id !== filter.session_id)
|
|
24105
|
-
return false;
|
|
24106
|
-
if (filter.tags?.length && !filter.tags.every((tag) => task2.tags.includes(tag)))
|
|
24107
|
-
return false;
|
|
24108
|
-
if (filter.has_recurrence !== undefined && Boolean(task2.recurrence_rule) !== filter.has_recurrence)
|
|
24109
|
-
return false;
|
|
24110
|
-
if (filter.include_subtasks !== true && task2.parent_id)
|
|
24111
|
-
return false;
|
|
24112
|
-
if (filter.task_type !== undefined && !matchesOne(task2.task_type ?? "", filter.task_type))
|
|
24113
|
-
return false;
|
|
24114
|
-
return true;
|
|
24115
|
-
}
|
|
24116
|
-
function matchesOne(value, expected) {
|
|
24117
|
-
return Array.isArray(expected) ? expected.includes(value) : value === expected;
|
|
24118
|
-
}
|
|
24119
|
-
function priorityRank(priority) {
|
|
24120
|
-
return { critical: 0, high: 1, medium: 2, low: 3 }[priority];
|
|
24121
|
-
}
|
|
24122
24297
|
function slugifyRaw(value) {
|
|
24123
24298
|
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
24124
24299
|
}
|
|
@@ -24178,11 +24353,424 @@ function numberValue3(value) {
|
|
|
24178
24353
|
return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
|
|
24179
24354
|
}
|
|
24180
24355
|
|
|
24356
|
+
// src/storage/shadow.ts
|
|
24357
|
+
var SNAPSHOT_TO_OBJECT_TYPE = {
|
|
24358
|
+
tasks: "tasks",
|
|
24359
|
+
projects: "projects",
|
|
24360
|
+
plans: "plans",
|
|
24361
|
+
agents: "agents",
|
|
24362
|
+
taskLists: "task_lists",
|
|
24363
|
+
templates: "templates",
|
|
24364
|
+
auditHistory: "audit_history"
|
|
24365
|
+
};
|
|
24366
|
+
|
|
24367
|
+
class TodosShadowMirror {
|
|
24368
|
+
queue = [];
|
|
24369
|
+
syncStore;
|
|
24370
|
+
maxRetries;
|
|
24371
|
+
retryBaseMs;
|
|
24372
|
+
onEvent;
|
|
24373
|
+
schemaReady;
|
|
24374
|
+
pumping = false;
|
|
24375
|
+
scheduledRetries = 0;
|
|
24376
|
+
idleResolvers = [];
|
|
24377
|
+
metrics = {
|
|
24378
|
+
enqueued: 0,
|
|
24379
|
+
mirrored: 0,
|
|
24380
|
+
retries: 0,
|
|
24381
|
+
failed: 0,
|
|
24382
|
+
lastMirrorAt: null,
|
|
24383
|
+
lastLagMs: null,
|
|
24384
|
+
lastError: null
|
|
24385
|
+
};
|
|
24386
|
+
constructor(options) {
|
|
24387
|
+
const syncStore = options.syncStore ?? (options.postgresClient ? createPostgresTodosSyncStore(options.postgresClient, {
|
|
24388
|
+
...options.sourceMachineId ? { sourceMachineId: options.sourceMachineId } : {}
|
|
24389
|
+
}) : null);
|
|
24390
|
+
if (!syncStore) {
|
|
24391
|
+
throw new Error("shadow mirror requires a Postgres sync store or query client");
|
|
24392
|
+
}
|
|
24393
|
+
this.syncStore = syncStore;
|
|
24394
|
+
this.maxRetries = Math.max(0, options.maxRetries ?? 5);
|
|
24395
|
+
this.retryBaseMs = Math.max(1, options.retryBaseMs ?? 250);
|
|
24396
|
+
if (options.onEvent)
|
|
24397
|
+
this.onEvent = options.onEvent;
|
|
24398
|
+
this.schemaReady = options.ensureSchema === false ? Promise.resolve() : null;
|
|
24399
|
+
}
|
|
24400
|
+
getMetrics() {
|
|
24401
|
+
return {
|
|
24402
|
+
enabled: true,
|
|
24403
|
+
enqueued: this.metrics.enqueued,
|
|
24404
|
+
mirrored: this.metrics.mirrored,
|
|
24405
|
+
retries: this.metrics.retries,
|
|
24406
|
+
failed: this.metrics.failed,
|
|
24407
|
+
divergence: this.metrics.failed + this.queue.length + this.scheduledRetries,
|
|
24408
|
+
pending: this.queue.length + this.scheduledRetries,
|
|
24409
|
+
inFlight: this.pumping || this.scheduledRetries > 0,
|
|
24410
|
+
lastMirrorAt: this.metrics.lastMirrorAt,
|
|
24411
|
+
lastLagMs: this.metrics.lastLagMs,
|
|
24412
|
+
lastError: this.metrics.lastError
|
|
24413
|
+
};
|
|
24414
|
+
}
|
|
24415
|
+
enqueueUpsert(key, record, context) {
|
|
24416
|
+
if (!record || typeof record !== "object")
|
|
24417
|
+
return;
|
|
24418
|
+
const payload = record;
|
|
24419
|
+
if (typeof payload["id"] !== "string" || !payload["id"])
|
|
24420
|
+
return;
|
|
24421
|
+
this.metrics.enqueued += 1;
|
|
24422
|
+
this.queue.push({
|
|
24423
|
+
kind: "upsert",
|
|
24424
|
+
key,
|
|
24425
|
+
record: payload,
|
|
24426
|
+
...context ? { context } : {},
|
|
24427
|
+
enqueuedAt: Date.now(),
|
|
24428
|
+
attempts: 0
|
|
24429
|
+
});
|
|
24430
|
+
this.pump();
|
|
24431
|
+
}
|
|
24432
|
+
enqueueDelete(objectType, id, context) {
|
|
24433
|
+
if (!id)
|
|
24434
|
+
return;
|
|
24435
|
+
this.metrics.enqueued += 1;
|
|
24436
|
+
this.queue.push({
|
|
24437
|
+
kind: "delete",
|
|
24438
|
+
objectType,
|
|
24439
|
+
id,
|
|
24440
|
+
...context ? { context } : {},
|
|
24441
|
+
enqueuedAt: Date.now(),
|
|
24442
|
+
attempts: 0
|
|
24443
|
+
});
|
|
24444
|
+
this.pump();
|
|
24445
|
+
}
|
|
24446
|
+
async flush() {
|
|
24447
|
+
if (this.idle())
|
|
24448
|
+
return;
|
|
24449
|
+
await new Promise((resolve10) => {
|
|
24450
|
+
this.idleResolvers.push(resolve10);
|
|
24451
|
+
this.pump();
|
|
24452
|
+
});
|
|
24453
|
+
}
|
|
24454
|
+
idle() {
|
|
24455
|
+
return this.queue.length === 0 && !this.pumping && this.scheduledRetries === 0;
|
|
24456
|
+
}
|
|
24457
|
+
notifyIdle() {
|
|
24458
|
+
if (!this.idle())
|
|
24459
|
+
return;
|
|
24460
|
+
const resolvers = this.idleResolvers;
|
|
24461
|
+
this.idleResolvers = [];
|
|
24462
|
+
for (const resolve10 of resolvers)
|
|
24463
|
+
resolve10();
|
|
24464
|
+
}
|
|
24465
|
+
pump() {
|
|
24466
|
+
if (this.pumping)
|
|
24467
|
+
return;
|
|
24468
|
+
this.pumping = true;
|
|
24469
|
+
this.drain();
|
|
24470
|
+
}
|
|
24471
|
+
async drain() {
|
|
24472
|
+
try {
|
|
24473
|
+
while (this.queue.length > 0) {
|
|
24474
|
+
const op = this.queue.shift();
|
|
24475
|
+
await this.process(op);
|
|
24476
|
+
}
|
|
24477
|
+
} finally {
|
|
24478
|
+
this.pumping = false;
|
|
24479
|
+
this.notifyIdle();
|
|
24480
|
+
}
|
|
24481
|
+
}
|
|
24482
|
+
async process(op) {
|
|
24483
|
+
try {
|
|
24484
|
+
await this.ensureSchema();
|
|
24485
|
+
await this.push(op);
|
|
24486
|
+
const objectType = op.kind === "upsert" ? SNAPSHOT_TO_OBJECT_TYPE[op.key] : op.objectType;
|
|
24487
|
+
const id = op.kind === "upsert" ? String(op.record["id"]) : op.id;
|
|
24488
|
+
const lagMs = Date.now() - op.enqueuedAt;
|
|
24489
|
+
this.metrics.mirrored += 1;
|
|
24490
|
+
this.metrics.lastMirrorAt = new Date().toISOString();
|
|
24491
|
+
this.metrics.lastLagMs = lagMs;
|
|
24492
|
+
this.onEvent?.({ type: "mirrored", objectType, id, lagMs });
|
|
24493
|
+
} catch (error) {
|
|
24494
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
24495
|
+
const objectType = op.kind === "upsert" ? SNAPSHOT_TO_OBJECT_TYPE[op.key] : op.objectType;
|
|
24496
|
+
const id = op.kind === "upsert" ? String(op.record["id"]) : op.id;
|
|
24497
|
+
this.metrics.retries += 1;
|
|
24498
|
+
this.metrics.lastError = message;
|
|
24499
|
+
op.attempts += 1;
|
|
24500
|
+
if (op.attempts <= this.maxRetries) {
|
|
24501
|
+
this.onEvent?.({ type: "retry", objectType, id, attempt: op.attempts, error: message });
|
|
24502
|
+
const delay = this.retryBaseMs * 2 ** (op.attempts - 1);
|
|
24503
|
+
this.scheduledRetries += 1;
|
|
24504
|
+
setTimeout(() => {
|
|
24505
|
+
this.scheduledRetries -= 1;
|
|
24506
|
+
this.queue.push(op);
|
|
24507
|
+
this.pump();
|
|
24508
|
+
}, delay);
|
|
24509
|
+
return;
|
|
24510
|
+
}
|
|
24511
|
+
this.metrics.failed += 1;
|
|
24512
|
+
this.onEvent?.({ type: "dropped", objectType, id, error: message });
|
|
24513
|
+
}
|
|
24514
|
+
}
|
|
24515
|
+
ensureSchema() {
|
|
24516
|
+
if (!this.schemaReady) {
|
|
24517
|
+
this.schemaReady = this.syncStore.ensureSchema().catch((error) => {
|
|
24518
|
+
this.schemaReady = null;
|
|
24519
|
+
throw error;
|
|
24520
|
+
});
|
|
24521
|
+
}
|
|
24522
|
+
return this.schemaReady;
|
|
24523
|
+
}
|
|
24524
|
+
async push(op) {
|
|
24525
|
+
const snapshot = emptySnapshot();
|
|
24526
|
+
const context = op.context ?? {};
|
|
24527
|
+
if (op.kind === "upsert") {
|
|
24528
|
+
snapshot[op.key].push(op.record);
|
|
24529
|
+
} else {
|
|
24530
|
+
const now4 = new Date().toISOString();
|
|
24531
|
+
const tombstone = {
|
|
24532
|
+
object_type: op.objectType,
|
|
24533
|
+
object_id: op.id,
|
|
24534
|
+
deleted_at: now4,
|
|
24535
|
+
updated_at: now4,
|
|
24536
|
+
payload: { id: op.id, deleted_at: now4 },
|
|
24537
|
+
version: null
|
|
24538
|
+
};
|
|
24539
|
+
snapshot.tombstones = [tombstone];
|
|
24540
|
+
}
|
|
24541
|
+
await this.syncStore.pushSnapshot(snapshot, context);
|
|
24542
|
+
}
|
|
24543
|
+
}
|
|
24544
|
+
function emptySnapshot() {
|
|
24545
|
+
return {
|
|
24546
|
+
exportedAt: new Date().toISOString(),
|
|
24547
|
+
source: "sqlite",
|
|
24548
|
+
tasks: [],
|
|
24549
|
+
projects: [],
|
|
24550
|
+
projectMachinePaths: [],
|
|
24551
|
+
plans: [],
|
|
24552
|
+
agents: [],
|
|
24553
|
+
taskLists: [],
|
|
24554
|
+
templates: [],
|
|
24555
|
+
auditHistory: [],
|
|
24556
|
+
tombstones: []
|
|
24557
|
+
};
|
|
24558
|
+
}
|
|
24559
|
+
function createShadowTodosStorageAdapter(options) {
|
|
24560
|
+
const local = options.localAdapter ?? createLocalSqliteTodosStorageAdapter(options.local);
|
|
24561
|
+
const mirror = new TodosShadowMirror(options);
|
|
24562
|
+
const adapter = {
|
|
24563
|
+
...local,
|
|
24564
|
+
kind: "sqlite",
|
|
24565
|
+
capabilities: { ...local.capabilities, remotePersistence: false, sync: true },
|
|
24566
|
+
tasks: {
|
|
24567
|
+
...local.tasks,
|
|
24568
|
+
async create(input, context) {
|
|
24569
|
+
const task2 = await local.tasks.create(input, context);
|
|
24570
|
+
mirror.enqueueUpsert("tasks", task2, context);
|
|
24571
|
+
return task2;
|
|
24572
|
+
},
|
|
24573
|
+
async update(id, input, context) {
|
|
24574
|
+
const task2 = await local.tasks.update(id, input, context);
|
|
24575
|
+
mirror.enqueueUpsert("tasks", task2, context);
|
|
24576
|
+
return task2;
|
|
24577
|
+
},
|
|
24578
|
+
async start(id, agentId, context) {
|
|
24579
|
+
const task2 = await local.tasks.start(id, agentId, context);
|
|
24580
|
+
mirror.enqueueUpsert("tasks", task2, context);
|
|
24581
|
+
return task2;
|
|
24582
|
+
},
|
|
24583
|
+
async complete(id, agentId, opts, context) {
|
|
24584
|
+
const task2 = await local.tasks.complete(id, agentId, opts, context);
|
|
24585
|
+
mirror.enqueueUpsert("tasks", task2, context);
|
|
24586
|
+
return task2;
|
|
24587
|
+
},
|
|
24588
|
+
async fail(id, agentId, reason, opts, context) {
|
|
24589
|
+
const result = await local.tasks.fail(id, agentId, reason, opts, context);
|
|
24590
|
+
mirror.enqueueUpsert("tasks", result.task, context);
|
|
24591
|
+
if (result.retryTask)
|
|
24592
|
+
mirror.enqueueUpsert("tasks", result.retryTask, context);
|
|
24593
|
+
return result;
|
|
24594
|
+
},
|
|
24595
|
+
async claimNext(agentId, filters, context) {
|
|
24596
|
+
const task2 = await local.tasks.claimNext(agentId, filters, context);
|
|
24597
|
+
if (task2)
|
|
24598
|
+
mirror.enqueueUpsert("tasks", task2, context);
|
|
24599
|
+
return task2;
|
|
24600
|
+
},
|
|
24601
|
+
async delete(id, context) {
|
|
24602
|
+
const deleted = await local.tasks.delete(id, context);
|
|
24603
|
+
if (deleted)
|
|
24604
|
+
mirror.enqueueDelete("tasks", id, context);
|
|
24605
|
+
return deleted;
|
|
24606
|
+
}
|
|
24607
|
+
},
|
|
24608
|
+
projects: {
|
|
24609
|
+
...local.projects,
|
|
24610
|
+
async create(input, context) {
|
|
24611
|
+
const project = await local.projects.create(input, context);
|
|
24612
|
+
mirror.enqueueUpsert("projects", project, context);
|
|
24613
|
+
return project;
|
|
24614
|
+
},
|
|
24615
|
+
async update(id, input, context) {
|
|
24616
|
+
const project = await local.projects.update(id, input, context);
|
|
24617
|
+
mirror.enqueueUpsert("projects", project, context);
|
|
24618
|
+
return project;
|
|
24619
|
+
},
|
|
24620
|
+
async delete(id, context) {
|
|
24621
|
+
const deleted = await local.projects.delete(id, context);
|
|
24622
|
+
if (deleted)
|
|
24623
|
+
mirror.enqueueDelete("projects", id, context);
|
|
24624
|
+
return deleted;
|
|
24625
|
+
}
|
|
24626
|
+
},
|
|
24627
|
+
plans: {
|
|
24628
|
+
...local.plans,
|
|
24629
|
+
async create(input, context) {
|
|
24630
|
+
const plan = await local.plans.create(input, context);
|
|
24631
|
+
mirror.enqueueUpsert("plans", plan, context);
|
|
24632
|
+
return plan;
|
|
24633
|
+
},
|
|
24634
|
+
async update(id, input, context) {
|
|
24635
|
+
const plan = await local.plans.update(id, input, context);
|
|
24636
|
+
mirror.enqueueUpsert("plans", plan, context);
|
|
24637
|
+
return plan;
|
|
24638
|
+
},
|
|
24639
|
+
async delete(id, context) {
|
|
24640
|
+
const deleted = await local.plans.delete(id, context);
|
|
24641
|
+
if (deleted)
|
|
24642
|
+
mirror.enqueueDelete("plans", id, context);
|
|
24643
|
+
return deleted;
|
|
24644
|
+
}
|
|
24645
|
+
},
|
|
24646
|
+
agents: {
|
|
24647
|
+
...local.agents,
|
|
24648
|
+
async register(input, context) {
|
|
24649
|
+
const result = await local.agents.register(input, context);
|
|
24650
|
+
if (isAgent(result))
|
|
24651
|
+
mirror.enqueueUpsert("agents", result, context);
|
|
24652
|
+
return result;
|
|
24653
|
+
},
|
|
24654
|
+
async update(id, input, context) {
|
|
24655
|
+
const agent = await local.agents.update(id, input, context);
|
|
24656
|
+
if (agent)
|
|
24657
|
+
mirror.enqueueUpsert("agents", agent, context);
|
|
24658
|
+
return agent;
|
|
24659
|
+
}
|
|
24660
|
+
},
|
|
24661
|
+
taskLists: {
|
|
24662
|
+
...local.taskLists,
|
|
24663
|
+
async create(input, context) {
|
|
24664
|
+
const list = await local.taskLists.create(input, context);
|
|
24665
|
+
mirror.enqueueUpsert("taskLists", list, context);
|
|
24666
|
+
return list;
|
|
24667
|
+
},
|
|
24668
|
+
async update(id, input, context) {
|
|
24669
|
+
const list = await local.taskLists.update(id, input, context);
|
|
24670
|
+
mirror.enqueueUpsert("taskLists", list, context);
|
|
24671
|
+
return list;
|
|
24672
|
+
},
|
|
24673
|
+
async delete(id, context) {
|
|
24674
|
+
const deleted = await local.taskLists.delete(id, context);
|
|
24675
|
+
if (deleted)
|
|
24676
|
+
mirror.enqueueDelete("task_lists", id, context);
|
|
24677
|
+
return deleted;
|
|
24678
|
+
}
|
|
24679
|
+
},
|
|
24680
|
+
templates: {
|
|
24681
|
+
...local.templates,
|
|
24682
|
+
async create(input, context) {
|
|
24683
|
+
const template = await local.templates.create(input, context);
|
|
24684
|
+
mirror.enqueueUpsert("templates", template, context);
|
|
24685
|
+
return template;
|
|
24686
|
+
},
|
|
24687
|
+
async update(id, input, context) {
|
|
24688
|
+
const template = await local.templates.update(id, input, context);
|
|
24689
|
+
if (template)
|
|
24690
|
+
mirror.enqueueUpsert("templates", template, context);
|
|
24691
|
+
return template;
|
|
24692
|
+
},
|
|
24693
|
+
async delete(id, context) {
|
|
24694
|
+
const deleted = await local.templates.delete(id, context);
|
|
24695
|
+
if (deleted)
|
|
24696
|
+
mirror.enqueueDelete("templates", id, context);
|
|
24697
|
+
return deleted;
|
|
24698
|
+
}
|
|
24699
|
+
},
|
|
24700
|
+
audit: {
|
|
24701
|
+
...local.audit,
|
|
24702
|
+
async logTaskChange(taskId, action, field2, oldValue, newValue, agentId, context) {
|
|
24703
|
+
const history = await local.audit.logTaskChange(taskId, action, field2, oldValue, newValue, agentId, context);
|
|
24704
|
+
mirror.enqueueUpsert("auditHistory", history, context);
|
|
24705
|
+
return history;
|
|
24706
|
+
}
|
|
24707
|
+
},
|
|
24708
|
+
shadow: mirror
|
|
24709
|
+
};
|
|
24710
|
+
if (adapter.transaction) {
|
|
24711
|
+
const localTransaction = local.transaction;
|
|
24712
|
+
adapter.transaction = (fn, context) => localTransaction(() => fn(adapter), context);
|
|
24713
|
+
}
|
|
24714
|
+
return adapter;
|
|
24715
|
+
}
|
|
24716
|
+
function isAgent(value) {
|
|
24717
|
+
return !value.conflict;
|
|
24718
|
+
}
|
|
24719
|
+
|
|
24720
|
+
// src/storage/cloud-client.ts
|
|
24721
|
+
init_config();
|
|
24722
|
+
function resolveBunSql() {
|
|
24723
|
+
const runtime = globalThis.Bun;
|
|
24724
|
+
const ctor = runtime?.SQL;
|
|
24725
|
+
if (typeof ctor !== "function") {
|
|
24726
|
+
throw new Error("Live Postgres access requires the Bun runtime (Bun.SQL). Run todos under bun, or inject a TodosPostgresQueryClient.");
|
|
24727
|
+
}
|
|
24728
|
+
return ctor;
|
|
24729
|
+
}
|
|
24730
|
+
function toRows(result) {
|
|
24731
|
+
if (Array.isArray(result))
|
|
24732
|
+
return result;
|
|
24733
|
+
if (result && typeof result === "object" && Array.isArray(result.rows)) {
|
|
24734
|
+
return result.rows;
|
|
24735
|
+
}
|
|
24736
|
+
return [];
|
|
24737
|
+
}
|
|
24738
|
+
function createTodosCloudQueryClient(url, options = {}) {
|
|
24739
|
+
const SQL = resolveBunSql();
|
|
24740
|
+
const sql = new SQL(url, {
|
|
24741
|
+
max: options.max ?? 2,
|
|
24742
|
+
idleTimeout: options.idleTimeout ?? 20,
|
|
24743
|
+
connectionTimeout: options.connectionTimeout ?? 15
|
|
24744
|
+
});
|
|
24745
|
+
return {
|
|
24746
|
+
async query(text, values = []) {
|
|
24747
|
+
const result = await sql.unsafe(text, values.length ? [...values] : []);
|
|
24748
|
+
return { rows: toRows(result) };
|
|
24749
|
+
},
|
|
24750
|
+
async close() {
|
|
24751
|
+
if (typeof sql.end === "function")
|
|
24752
|
+
await sql.end();
|
|
24753
|
+
else if (typeof sql.close === "function")
|
|
24754
|
+
await sql.close();
|
|
24755
|
+
}
|
|
24756
|
+
};
|
|
24757
|
+
}
|
|
24758
|
+
function createTodosCloudQueryClientFromEnv(env = process.env, options = {}) {
|
|
24759
|
+
const url = getTodosStorageDatabaseUrl(env);
|
|
24760
|
+
if (!url)
|
|
24761
|
+
return null;
|
|
24762
|
+
return createTodosCloudQueryClient(url, options);
|
|
24763
|
+
}
|
|
24764
|
+
|
|
24181
24765
|
// src/storage/factory.ts
|
|
24766
|
+
init_config();
|
|
24182
24767
|
function createTodosStorageAdapter(options = {}) {
|
|
24183
24768
|
const config = options.config ?? loadTodosStorageConfig(options.env);
|
|
24184
|
-
if (config.mode === "local")
|
|
24769
|
+
if (config.mode === "local") {
|
|
24770
|
+
if (isTodosShadowEnabled(options.env))
|
|
24771
|
+
return createShadowAdapter(options, config);
|
|
24185
24772
|
return createLocalSqliteTodosStorageAdapter(options.local);
|
|
24773
|
+
}
|
|
24186
24774
|
assertTodosRemoteStorageConfig(config);
|
|
24187
24775
|
const adapter = config.mode === "hybrid" ? options.hybridAdapter ?? createImplicitHybridAdapter(options) ?? options.remoteAdapter : options.remoteAdapter ?? createImplicitPostgresAdapter(options);
|
|
24188
24776
|
if (!adapter) {
|
|
@@ -24191,6 +24779,20 @@ function createTodosStorageAdapter(options = {}) {
|
|
|
24191
24779
|
assertRemoteAdapterCapabilities(adapter, config.mode);
|
|
24192
24780
|
return adapter;
|
|
24193
24781
|
}
|
|
24782
|
+
function createShadowAdapter(options, config) {
|
|
24783
|
+
assertTodosShadowConfig(config, options.env);
|
|
24784
|
+
const postgresClient = options.postgresClient ?? createTodosCloudQueryClientFromEnv(options.env);
|
|
24785
|
+
if (!options.postgresSyncStore && !postgresClient) {
|
|
24786
|
+
throw new Error("shadow mirror requires a remote database URL or an injected Postgres client");
|
|
24787
|
+
}
|
|
24788
|
+
return createShadowTodosStorageAdapter({
|
|
24789
|
+
...options.shadow ?? {},
|
|
24790
|
+
...options.local ? { local: options.local } : {},
|
|
24791
|
+
...options.postgresSyncStore ? { syncStore: options.postgresSyncStore } : {},
|
|
24792
|
+
...postgresClient ? { postgresClient } : {},
|
|
24793
|
+
...options.hybrid?.sourceMachineId ? { sourceMachineId: options.hybrid.sourceMachineId } : {}
|
|
24794
|
+
});
|
|
24795
|
+
}
|
|
24194
24796
|
function createImplicitPostgresAdapter(options) {
|
|
24195
24797
|
if (!options.postgresClient)
|
|
24196
24798
|
return null;
|
|
@@ -24217,6 +24819,326 @@ function assertRemoteAdapterCapabilities(adapter, mode) {
|
|
|
24217
24819
|
throw new Error("hybrid storage adapter must also set capabilities.localPersistence=true");
|
|
24218
24820
|
}
|
|
24219
24821
|
}
|
|
24822
|
+
// src/storage/shadow-outbox.ts
|
|
24823
|
+
init_shadow_outbox_schema();
|
|
24824
|
+
init_shadow_outbox_schema();
|
|
24825
|
+
var MAX_BACKOFF_MS = 5 * 60000;
|
|
24826
|
+
|
|
24827
|
+
class TodosShadowOutbox {
|
|
24828
|
+
db;
|
|
24829
|
+
syncStore;
|
|
24830
|
+
local;
|
|
24831
|
+
maxRetries;
|
|
24832
|
+
retryBaseMs;
|
|
24833
|
+
batchSize;
|
|
24834
|
+
onEvent;
|
|
24835
|
+
schemaReady;
|
|
24836
|
+
loopTimer = null;
|
|
24837
|
+
draining = false;
|
|
24838
|
+
metrics = {
|
|
24839
|
+
mirrored: 0,
|
|
24840
|
+
retries: 0,
|
|
24841
|
+
lastMirrorAt: null,
|
|
24842
|
+
lastLagMs: null,
|
|
24843
|
+
lastError: null
|
|
24844
|
+
};
|
|
24845
|
+
constructor(options) {
|
|
24846
|
+
this.db = options.db;
|
|
24847
|
+
const syncStore = options.syncStore ?? (options.postgresClient ? createPostgresTodosSyncStore(options.postgresClient, {
|
|
24848
|
+
...options.sourceMachineId ? { sourceMachineId: options.sourceMachineId } : {}
|
|
24849
|
+
}) : null);
|
|
24850
|
+
if (!syncStore) {
|
|
24851
|
+
throw new Error("shadow outbox requires a Postgres sync store or query client");
|
|
24852
|
+
}
|
|
24853
|
+
this.syncStore = syncStore;
|
|
24854
|
+
this.local = options.localAdapter ?? createLocalSqliteTodosStorageAdapter({ db: options.db });
|
|
24855
|
+
this.maxRetries = Math.max(0, options.maxRetries ?? 8);
|
|
24856
|
+
this.retryBaseMs = Math.max(1, options.retryBaseMs ?? 500);
|
|
24857
|
+
this.batchSize = Math.max(1, options.batchSize ?? 50);
|
|
24858
|
+
if (options.onEvent)
|
|
24859
|
+
this.onEvent = options.onEvent;
|
|
24860
|
+
this.schemaReady = options.ensureSchema === false ? Promise.resolve() : null;
|
|
24861
|
+
}
|
|
24862
|
+
install() {
|
|
24863
|
+
installShadowOutboxSchema(this.db);
|
|
24864
|
+
}
|
|
24865
|
+
getStats() {
|
|
24866
|
+
const pending = this.countByStatus("pending");
|
|
24867
|
+
const failed = this.countByStatus("failed");
|
|
24868
|
+
return {
|
|
24869
|
+
enabled: true,
|
|
24870
|
+
durable: true,
|
|
24871
|
+
pending,
|
|
24872
|
+
failed,
|
|
24873
|
+
depth: pending + failed,
|
|
24874
|
+
mirrored: this.metrics.mirrored,
|
|
24875
|
+
retries: this.metrics.retries,
|
|
24876
|
+
lastMirrorAt: this.metrics.lastMirrorAt,
|
|
24877
|
+
lastLagMs: this.metrics.lastLagMs,
|
|
24878
|
+
lastError: this.metrics.lastError,
|
|
24879
|
+
draining: this.loopTimer !== null
|
|
24880
|
+
};
|
|
24881
|
+
}
|
|
24882
|
+
countByStatus(status) {
|
|
24883
|
+
const row = this.db.query(`SELECT count(*) AS n FROM shadow_outbox WHERE status=?`).get(status);
|
|
24884
|
+
return row?.n ?? 0;
|
|
24885
|
+
}
|
|
24886
|
+
startLoop(intervalMs = 2000) {
|
|
24887
|
+
if (this.loopTimer)
|
|
24888
|
+
return;
|
|
24889
|
+
this.loopTimer = setInterval(() => {
|
|
24890
|
+
this.drainOnce().catch(() => {});
|
|
24891
|
+
}, Math.max(250, intervalMs));
|
|
24892
|
+
if (typeof this.loopTimer.unref === "function")
|
|
24893
|
+
this.loopTimer.unref();
|
|
24894
|
+
}
|
|
24895
|
+
stopLoop() {
|
|
24896
|
+
if (this.loopTimer) {
|
|
24897
|
+
clearInterval(this.loopTimer);
|
|
24898
|
+
this.loopTimer = null;
|
|
24899
|
+
}
|
|
24900
|
+
}
|
|
24901
|
+
async flush(timeoutMs = 15000) {
|
|
24902
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
24903
|
+
while (Date.now() < deadline) {
|
|
24904
|
+
const processed = await this.drainOnce();
|
|
24905
|
+
if (this.countByStatus("pending") === 0)
|
|
24906
|
+
break;
|
|
24907
|
+
if (processed === 0) {
|
|
24908
|
+
const remaining = deadline - Date.now();
|
|
24909
|
+
if (remaining <= 0)
|
|
24910
|
+
break;
|
|
24911
|
+
await new Promise((resolve10) => setTimeout(resolve10, Math.min(200, remaining)));
|
|
24912
|
+
}
|
|
24913
|
+
}
|
|
24914
|
+
return this.getStats();
|
|
24915
|
+
}
|
|
24916
|
+
async drainOnce() {
|
|
24917
|
+
if (this.draining)
|
|
24918
|
+
return 0;
|
|
24919
|
+
this.draining = true;
|
|
24920
|
+
try {
|
|
24921
|
+
await this.ensureSchema();
|
|
24922
|
+
const now4 = Date.now();
|
|
24923
|
+
const rows = this.db.query(`SELECT seq, object_type, object_id, op, enqueued_at, attempts, revision
|
|
24924
|
+
FROM shadow_outbox
|
|
24925
|
+
WHERE status='pending' AND next_attempt_at <= ?
|
|
24926
|
+
ORDER BY seq ASC
|
|
24927
|
+
LIMIT ?`).all(now4, this.batchSize);
|
|
24928
|
+
if (rows.length === 0)
|
|
24929
|
+
return 0;
|
|
24930
|
+
for (const row of rows) {
|
|
24931
|
+
await this.processRow(row);
|
|
24932
|
+
}
|
|
24933
|
+
return rows.length;
|
|
24934
|
+
} catch {
|
|
24935
|
+
return 0;
|
|
24936
|
+
} finally {
|
|
24937
|
+
this.draining = false;
|
|
24938
|
+
}
|
|
24939
|
+
}
|
|
24940
|
+
async processRow(row) {
|
|
24941
|
+
try {
|
|
24942
|
+
const snapshot = await this.buildSnapshot(row);
|
|
24943
|
+
await this.syncStore.pushSnapshot(snapshot, {});
|
|
24944
|
+
const lagMs = Date.now() - row.enqueued_at;
|
|
24945
|
+
this.db.run(`DELETE FROM shadow_outbox WHERE seq=? AND revision=?`, [row.seq, row.revision]);
|
|
24946
|
+
this.metrics.mirrored += 1;
|
|
24947
|
+
this.metrics.lastMirrorAt = new Date().toISOString();
|
|
24948
|
+
this.metrics.lastLagMs = lagMs;
|
|
24949
|
+
this.onEvent?.({ type: "mirrored", objectType: row.object_type, id: row.object_id, lagMs });
|
|
24950
|
+
} catch (error) {
|
|
24951
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
24952
|
+
this.metrics.retries += 1;
|
|
24953
|
+
this.metrics.lastError = message;
|
|
24954
|
+
const attempts = row.attempts + 1;
|
|
24955
|
+
if (attempts > this.maxRetries) {
|
|
24956
|
+
this.db.run(`UPDATE shadow_outbox SET attempts=?, last_error=?, status='failed' WHERE seq=? AND revision=?`, [attempts, message, row.seq, row.revision]);
|
|
24957
|
+
this.onEvent?.({ type: "parked", objectType: row.object_type, id: row.object_id, error: message });
|
|
24958
|
+
return;
|
|
24959
|
+
}
|
|
24960
|
+
const delay = Math.min(MAX_BACKOFF_MS, this.retryBaseMs * 2 ** (attempts - 1));
|
|
24961
|
+
this.db.run(`UPDATE shadow_outbox SET attempts=?, next_attempt_at=?, last_error=? WHERE seq=? AND revision=?`, [attempts, Date.now() + delay, message, row.seq, row.revision]);
|
|
24962
|
+
this.onEvent?.({ type: "retry", objectType: row.object_type, id: row.object_id, attempt: attempts, error: message });
|
|
24963
|
+
}
|
|
24964
|
+
}
|
|
24965
|
+
async buildSnapshot(row) {
|
|
24966
|
+
const snapshot = emptySnapshot2();
|
|
24967
|
+
if (row.op === "delete") {
|
|
24968
|
+
snapshot.tombstones = [this.tombstone(row.object_type, row.object_id)];
|
|
24969
|
+
return snapshot;
|
|
24970
|
+
}
|
|
24971
|
+
const record = await this.readCurrent(row.object_type, row.object_id);
|
|
24972
|
+
if (!record) {
|
|
24973
|
+
snapshot.tombstones = [this.tombstone(row.object_type, row.object_id)];
|
|
24974
|
+
return snapshot;
|
|
24975
|
+
}
|
|
24976
|
+
switch (row.object_type) {
|
|
24977
|
+
case "tasks":
|
|
24978
|
+
snapshot.tasks.push(record);
|
|
24979
|
+
break;
|
|
24980
|
+
case "projects":
|
|
24981
|
+
snapshot.projects.push(record);
|
|
24982
|
+
break;
|
|
24983
|
+
case "project_machine_paths":
|
|
24984
|
+
snapshot.projectMachinePaths?.push(record);
|
|
24985
|
+
break;
|
|
24986
|
+
case "plans":
|
|
24987
|
+
snapshot.plans.push(record);
|
|
24988
|
+
break;
|
|
24989
|
+
case "agents":
|
|
24990
|
+
snapshot.agents.push(record);
|
|
24991
|
+
break;
|
|
24992
|
+
case "task_lists":
|
|
24993
|
+
snapshot.taskLists.push(record);
|
|
24994
|
+
break;
|
|
24995
|
+
case "templates":
|
|
24996
|
+
snapshot.templates.push(record);
|
|
24997
|
+
break;
|
|
24998
|
+
case "audit_history":
|
|
24999
|
+
snapshot.auditHistory.push(record);
|
|
25000
|
+
break;
|
|
25001
|
+
default:
|
|
25002
|
+
break;
|
|
25003
|
+
}
|
|
25004
|
+
return snapshot;
|
|
25005
|
+
}
|
|
25006
|
+
async readCurrent(objectType, id) {
|
|
25007
|
+
switch (objectType) {
|
|
25008
|
+
case "tasks":
|
|
25009
|
+
return await this.local.tasks.get(id);
|
|
25010
|
+
case "projects":
|
|
25011
|
+
return await this.local.projects.get(id);
|
|
25012
|
+
case "project_machine_paths": {
|
|
25013
|
+
const raw = this.db.query(`SELECT * FROM project_machine_paths WHERE id=?`).get(id);
|
|
25014
|
+
return raw ?? null;
|
|
25015
|
+
}
|
|
25016
|
+
case "plans":
|
|
25017
|
+
return await this.local.plans.get(id);
|
|
25018
|
+
case "agents":
|
|
25019
|
+
return await this.local.agents.get(id);
|
|
25020
|
+
case "task_lists":
|
|
25021
|
+
return await this.local.taskLists.get(id);
|
|
25022
|
+
case "templates":
|
|
25023
|
+
return await this.local.templates.get(id);
|
|
25024
|
+
case "audit_history": {
|
|
25025
|
+
const raw = this.db.query(`SELECT * FROM task_history WHERE id=?`).get(id);
|
|
25026
|
+
return raw ?? null;
|
|
25027
|
+
}
|
|
25028
|
+
default:
|
|
25029
|
+
return null;
|
|
25030
|
+
}
|
|
25031
|
+
}
|
|
25032
|
+
tombstone(objectType, id) {
|
|
25033
|
+
const now4 = new Date().toISOString();
|
|
25034
|
+
return {
|
|
25035
|
+
object_type: objectType,
|
|
25036
|
+
object_id: id,
|
|
25037
|
+
deleted_at: now4,
|
|
25038
|
+
updated_at: now4,
|
|
25039
|
+
payload: { id, deleted_at: now4 },
|
|
25040
|
+
version: null
|
|
25041
|
+
};
|
|
25042
|
+
}
|
|
25043
|
+
ensureSchema() {
|
|
25044
|
+
if (!this.schemaReady) {
|
|
25045
|
+
this.schemaReady = this.syncStore.ensureSchema().catch((error) => {
|
|
25046
|
+
this.schemaReady = null;
|
|
25047
|
+
throw error;
|
|
25048
|
+
});
|
|
25049
|
+
}
|
|
25050
|
+
return this.schemaReady;
|
|
25051
|
+
}
|
|
25052
|
+
}
|
|
25053
|
+
function emptySnapshot2() {
|
|
25054
|
+
return {
|
|
25055
|
+
exportedAt: new Date().toISOString(),
|
|
25056
|
+
source: "sqlite",
|
|
25057
|
+
tasks: [],
|
|
25058
|
+
projects: [],
|
|
25059
|
+
projectMachinePaths: [],
|
|
25060
|
+
plans: [],
|
|
25061
|
+
agents: [],
|
|
25062
|
+
taskLists: [],
|
|
25063
|
+
templates: [],
|
|
25064
|
+
auditHistory: [],
|
|
25065
|
+
tombstones: []
|
|
25066
|
+
};
|
|
25067
|
+
}
|
|
25068
|
+
function createTodosShadowOutbox(options) {
|
|
25069
|
+
const outbox = new TodosShadowOutbox(options);
|
|
25070
|
+
outbox.install();
|
|
25071
|
+
return outbox;
|
|
25072
|
+
}
|
|
25073
|
+
// src/storage/shadow-runtime.ts
|
|
25074
|
+
init_config();
|
|
25075
|
+
var _capturedDb = null;
|
|
25076
|
+
var _outbox = null;
|
|
25077
|
+
var _cloud = null;
|
|
25078
|
+
var _exitRegistered = false;
|
|
25079
|
+
function maybeInstallShadowCapture2(db, env = process.env) {
|
|
25080
|
+
if (!isTodosShadowEnabled(env))
|
|
25081
|
+
return false;
|
|
25082
|
+
if (_capturedDb === db)
|
|
25083
|
+
return true;
|
|
25084
|
+
installShadowOutboxSchema(db);
|
|
25085
|
+
_capturedDb = db;
|
|
25086
|
+
return true;
|
|
25087
|
+
}
|
|
25088
|
+
function getRuntimeShadowOutbox(db, env = process.env) {
|
|
25089
|
+
if (!isTodosShadowEnabled(env)) {
|
|
25090
|
+
throw new Error(`dual-write shadow is disabled: set ${getTodosStorageShadowEnvName(env)}=1 to enable it`);
|
|
25091
|
+
}
|
|
25092
|
+
if (_outbox && _capturedDb === db)
|
|
25093
|
+
return _outbox;
|
|
25094
|
+
const cloud = createTodosCloudQueryClientFromEnv(env);
|
|
25095
|
+
if (!cloud) {
|
|
25096
|
+
throw new Error(`dual-write shadow drain requires a remote Postgres DSN in ${getTodosStorageDatabaseEnv(env)}`);
|
|
25097
|
+
}
|
|
25098
|
+
_cloud = cloud;
|
|
25099
|
+
installShadowOutboxSchema(db);
|
|
25100
|
+
_capturedDb = db;
|
|
25101
|
+
_outbox = new TodosShadowOutbox({ db, postgresClient: cloud });
|
|
25102
|
+
return _outbox;
|
|
25103
|
+
}
|
|
25104
|
+
function startRuntimeShadowDrain(db, env = process.env) {
|
|
25105
|
+
if (!isTodosShadowEnabled(env))
|
|
25106
|
+
return;
|
|
25107
|
+
maybeInstallShadowCapture2(db, env);
|
|
25108
|
+
try {
|
|
25109
|
+
const outbox = getRuntimeShadowOutbox(db, env);
|
|
25110
|
+
outbox.startLoop();
|
|
25111
|
+
registerShadowExitFlush(db, env);
|
|
25112
|
+
} catch (error) {
|
|
25113
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
25114
|
+
console.error(`[todos] shadow drain not started: ${message}`);
|
|
25115
|
+
}
|
|
25116
|
+
}
|
|
25117
|
+
function registerShadowExitFlush(db, env = process.env) {
|
|
25118
|
+
if (_exitRegistered)
|
|
25119
|
+
return;
|
|
25120
|
+
if (!isTodosShadowEnabled(env))
|
|
25121
|
+
return;
|
|
25122
|
+
_exitRegistered = true;
|
|
25123
|
+
const flush = async () => {
|
|
25124
|
+
try {
|
|
25125
|
+
const outbox = getRuntimeShadowOutbox(db, env);
|
|
25126
|
+
await outbox.flush(5000);
|
|
25127
|
+
} catch {} finally {
|
|
25128
|
+
await closeRuntimeShadowCloud();
|
|
25129
|
+
}
|
|
25130
|
+
};
|
|
25131
|
+
process.once("beforeExit", () => {
|
|
25132
|
+
flush();
|
|
25133
|
+
});
|
|
25134
|
+
}
|
|
25135
|
+
async function closeRuntimeShadowCloud() {
|
|
25136
|
+
if (_cloud) {
|
|
25137
|
+
const cloud = _cloud;
|
|
25138
|
+
_cloud = null;
|
|
25139
|
+
await cloud.close().catch(() => {});
|
|
25140
|
+
}
|
|
25141
|
+
}
|
|
24220
25142
|
// src/storage/s3-artifacts.ts
|
|
24221
25143
|
import { createHash as createHash9, createHmac as createHmac2 } from "crypto";
|
|
24222
25144
|
function createTodosS3ArtifactStore(options) {
|
|
@@ -24697,7 +25619,7 @@ class TodosTimeoutError extends Error {
|
|
|
24697
25619
|
}
|
|
24698
25620
|
|
|
24699
25621
|
// src/sdk/client.ts
|
|
24700
|
-
|
|
25622
|
+
init_config2();
|
|
24701
25623
|
function buildQuery(params) {
|
|
24702
25624
|
const search = new URLSearchParams;
|
|
24703
25625
|
for (const [k, v] of Object.entries(params)) {
|
|
@@ -28558,7 +29480,7 @@ CLI equivalent: \`${r.equivalent_cli}\`
|
|
|
28558
29480
|
init_task_commits();
|
|
28559
29481
|
init_database();
|
|
28560
29482
|
init_tasks();
|
|
28561
|
-
|
|
29483
|
+
init_config2();
|
|
28562
29484
|
init_redaction();
|
|
28563
29485
|
import { existsSync as existsSync14, readFileSync as readFileSync10 } from "fs";
|
|
28564
29486
|
var DEFAULT_RETRY = {
|
|
@@ -29028,7 +29950,7 @@ init_task_commits();
|
|
|
29028
29950
|
init_database();
|
|
29029
29951
|
init_tasks();
|
|
29030
29952
|
init_task_runs();
|
|
29031
|
-
|
|
29953
|
+
init_config2();
|
|
29032
29954
|
import { relative as relative3, resolve as resolve13 } from "path";
|
|
29033
29955
|
function normalizePath4(path) {
|
|
29034
29956
|
return resolve13(path);
|
|
@@ -29496,7 +30418,7 @@ init_task_runs();
|
|
|
29496
30418
|
init_database();
|
|
29497
30419
|
init_redaction();
|
|
29498
30420
|
init_runner_sandbox();
|
|
29499
|
-
|
|
30421
|
+
init_config2();
|
|
29500
30422
|
function dispatcherFromRun(run) {
|
|
29501
30423
|
const value = run.metadata["agent_run_dispatcher"];
|
|
29502
30424
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
@@ -41875,7 +42797,7 @@ function runSearchView(idOrName, db) {
|
|
|
41875
42797
|
}
|
|
41876
42798
|
// src/lib/claude-tasks.ts
|
|
41877
42799
|
init_tasks();
|
|
41878
|
-
|
|
42800
|
+
init_config2();
|
|
41879
42801
|
init_sync_utils();
|
|
41880
42802
|
import { existsSync as existsSync26, readFileSync as readFileSync23, readdirSync as readdirSync5, writeFileSync as writeFileSync20 } from "fs";
|
|
41881
42803
|
import { join as join24 } from "path";
|
|
@@ -42118,7 +43040,7 @@ function syncClaudeTaskList(taskListId, projectId, options = {}) {
|
|
|
42118
43040
|
// src/lib/agent-tasks.ts
|
|
42119
43041
|
init_tasks();
|
|
42120
43042
|
init_sync_utils();
|
|
42121
|
-
|
|
43043
|
+
init_config2();
|
|
42122
43044
|
import { existsSync as existsSync27 } from "fs";
|
|
42123
43045
|
import { join as join25 } from "path";
|
|
42124
43046
|
function agentBaseDir(agent) {
|
|
@@ -42330,7 +43252,7 @@ function syncAgentTaskList(agent, taskListId, projectId, options = {}) {
|
|
|
42330
43252
|
}
|
|
42331
43253
|
|
|
42332
43254
|
// src/lib/sync.ts
|
|
42333
|
-
|
|
43255
|
+
init_config2();
|
|
42334
43256
|
function normalizeAgent2(agent) {
|
|
42335
43257
|
return agent.trim().toLowerCase();
|
|
42336
43258
|
}
|
|
@@ -42950,7 +43872,7 @@ function checkBudget(agentId, db) {
|
|
|
42950
43872
|
}
|
|
42951
43873
|
|
|
42952
43874
|
// src/index.ts
|
|
42953
|
-
|
|
43875
|
+
init_config2();
|
|
42954
43876
|
init_runner_sandbox();
|
|
42955
43877
|
init_event_hooks();
|
|
42956
43878
|
|
|
@@ -43160,7 +44082,7 @@ ${line}`,
|
|
|
43160
44082
|
init_tasks();
|
|
43161
44083
|
init_types();
|
|
43162
44084
|
init_database();
|
|
43163
|
-
|
|
44085
|
+
init_config2();
|
|
43164
44086
|
var LOCAL_FIELDS_KEY2 = "local_fields";
|
|
43165
44087
|
var WORKFLOW_STATE_KEY = "workflow_state";
|
|
43166
44088
|
var DEFAULT_WORKFLOW_STATES = [
|
|
@@ -43621,7 +44543,7 @@ function renderAgentReplaySimulationMarkdown(simulation) {
|
|
|
43621
44543
|
`);
|
|
43622
44544
|
}
|
|
43623
44545
|
// src/lib/local-extensions.ts
|
|
43624
|
-
|
|
44546
|
+
init_config2();
|
|
43625
44547
|
import { createHash as createHash17, createVerify } from "crypto";
|
|
43626
44548
|
import { existsSync as existsSync29, readdirSync as readdirSync6, readFileSync as readFileSync26, statSync as statSync11 } from "fs";
|
|
43627
44549
|
import { basename as basename6, join as join27, resolve as resolve19 } from "path";
|
|
@@ -45729,7 +46651,7 @@ function runTodosDoctor(options = {}) {
|
|
|
45729
46651
|
// src/lib/capacity-forecasts.ts
|
|
45730
46652
|
init_tasks();
|
|
45731
46653
|
init_task_relations();
|
|
45732
|
-
|
|
46654
|
+
init_config2();
|
|
45733
46655
|
var LOCAL_CAPACITY_SCHEMA_VERSION = 1;
|
|
45734
46656
|
function timestamp2() {
|
|
45735
46657
|
return new Date().toISOString();
|