@inflexa-ai/harness 0.44.0 → 0.45.0

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 (99) hide show
  1. package/dist/app/approve-plan.d.ts +48 -0
  2. package/dist/app/approve-plan.js +84 -0
  3. package/dist/app/data-profile-view.d.ts +1 -1
  4. package/dist/app/run-activity.js +4 -6
  5. package/dist/contracts/chat-events.d.ts +2 -0
  6. package/dist/contracts/chat-frame.d.ts +7 -0
  7. package/dist/contracts/chat-frame.js +18 -4
  8. package/dist/contracts/chat-parts.d.ts +73 -2
  9. package/dist/contracts/chat-parts.js +3 -1
  10. package/dist/contracts/index.d.ts +3 -1
  11. package/dist/contracts/index.js +1 -0
  12. package/dist/contracts/part-registry.js +3 -0
  13. package/dist/contracts/schemas/chat-events.d.ts +13 -0
  14. package/dist/contracts/schemas/chat-events.js +1 -0
  15. package/dist/contracts/schemas/chat-parts.d.ts +200 -15
  16. package/dist/contracts/schemas/chat-parts.js +63 -12
  17. package/dist/contracts/schemas/index.d.ts +1 -1
  18. package/dist/contracts/schemas/index.js +1 -1
  19. package/dist/contracts/subagent-activity.d.ts +12 -0
  20. package/dist/contracts/subagent-activity.js +76 -0
  21. package/dist/execution/artifact-metadata.js +1 -3
  22. package/dist/execution/run-canceler.js +1 -1
  23. package/dist/execution/run-event-parts.d.ts +6 -5
  24. package/dist/execution/run-event-parts.js +6 -5
  25. package/dist/execution/run-event-stream.d.ts +18 -6
  26. package/dist/execution/run-event-stream.js +67 -17
  27. package/dist/execution/run-synthesis.d.ts +21 -0
  28. package/dist/execution/run-synthesis.js +77 -3
  29. package/dist/index.d.ts +22 -8
  30. package/dist/index.js +16 -2
  31. package/dist/lib/hooks.d.ts +1 -1
  32. package/dist/lib/metrics.d.ts +2 -2
  33. package/dist/loop/run-agent.js +1 -0
  34. package/dist/loop/types.d.ts +2 -0
  35. package/dist/memory/card-builders.d.ts +11 -0
  36. package/dist/memory/card-builders.js +35 -21
  37. package/dist/memory/conversation-display-recorder.d.ts +2 -0
  38. package/dist/memory/conversation-display-recorder.js +10 -1
  39. package/dist/memory/conversation-display-storage.d.ts +9 -2
  40. package/dist/memory/conversation-display-storage.js +18 -3
  41. package/dist/memory/thread-history.d.ts +8 -1
  42. package/dist/memory/thread-history.js +13 -3
  43. package/dist/memory/thread-store.d.ts +13 -0
  44. package/dist/memory/thread-store.js +15 -1
  45. package/dist/prompts/conversation.d.ts +1 -1
  46. package/dist/prompts/conversation.js +3 -1
  47. package/dist/provenance/seam.d.ts +16 -5
  48. package/dist/providers/ai-sdk.js +6 -4
  49. package/dist/report-model/pin-snapshot.d.ts +1 -1
  50. package/dist/report-model/pin-snapshot.js +2 -50
  51. package/dist/runtime/assemble.d.ts +8 -1
  52. package/dist/runtime/assemble.js +11 -0
  53. package/dist/runtime/boot.d.ts +3 -0
  54. package/dist/runtime/boot.js +10 -1
  55. package/dist/sandbox/sandbox-step-translate.d.ts +23 -0
  56. package/dist/sandbox/sandbox-step-translate.js +24 -0
  57. package/dist/schemas/artifact-manifest.d.ts +1 -1
  58. package/dist/schemas/artifact-manifest.js +11 -9
  59. package/dist/schemas/plan-schemas.d.ts +18 -18
  60. package/dist/schemas/run-synthesis.d.ts +2 -2
  61. package/dist/state/analyses-metrics.d.ts +79 -7
  62. package/dist/state/analyses-metrics.js +141 -6
  63. package/dist/state/artifacts.d.ts +50 -3
  64. package/dist/state/artifacts.js +67 -7
  65. package/dist/state/data-profile.d.ts +4 -2
  66. package/dist/state/data-profile.js +7 -5
  67. package/dist/state/index.d.ts +9 -8
  68. package/dist/state/index.js +5 -5
  69. package/dist/state/migrations/20261012120000_index_the_runs_by_start.d.ts +8 -0
  70. package/dist/state/migrations/20261012120000_index_the_runs_by_start.js +12 -0
  71. package/dist/state/migrations/20261013120000_index_the_ended_runs_and_the_recent_threads.d.ts +8 -0
  72. package/dist/state/migrations/20261013120000_index_the_ended_runs_and_the_recent_threads.js +13 -0
  73. package/dist/state/migrations/20261013180000_narrow_the_active_run_index.d.ts +8 -0
  74. package/dist/state/migrations/20261013180000_narrow_the_active_run_index.js +13 -0
  75. package/dist/state/migrations/20261014120000_index_the_plans_by_parent_and_the_runs_by_plan.d.ts +8 -0
  76. package/dist/state/migrations/20261014120000_index_the_plans_by_parent_and_the_runs_by_plan.js +13 -0
  77. package/dist/state/migrations/index.js +8 -0
  78. package/dist/state/plans.d.ts +21 -0
  79. package/dist/state/plans.js +25 -0
  80. package/dist/state/runs.d.ts +36 -5
  81. package/dist/state/runs.js +65 -19
  82. package/dist/state/schema.d.ts +2 -0
  83. package/dist/tasks/data-profile-activity.d.ts +7 -1
  84. package/dist/tasks/data-profile-activity.js +18 -9
  85. package/dist/tasks/data-profile.d.ts +15 -1
  86. package/dist/tasks/data-profile.js +16 -11
  87. package/dist/tools/approval/gateway.js +28 -5
  88. package/dist/tools/display/show-user.d.ts +1 -1
  89. package/dist/tools/execute-analysis.d.ts +51 -0
  90. package/dist/tools/execute-analysis.js +241 -109
  91. package/dist/tools/research/inspect-data-profile.d.ts +1 -1
  92. package/dist/tools/research/inspect-run.d.ts +1 -1
  93. package/dist/tools/research/inspect-run.js +7 -7
  94. package/dist/workflows/execute-analysis.d.ts +4 -3
  95. package/dist/workflows/execute-analysis.js +35 -22
  96. package/dist/workflows/plan/graph.d.ts +16 -0
  97. package/dist/workflows/plan/graph.js +36 -0
  98. package/dist/workflows/sandbox-step.js +14 -12
  99. package/package.json +1 -1
@@ -19,6 +19,30 @@
19
19
  export function stepPartId(kind, runId, stepId) {
20
20
  return `${kind}-${runId}-${stepId}`;
21
21
  }
22
+ /**
23
+ * The two parts of one activity emission: the reconciling `data-step-activity` that holds the current activity,
24
+ * and the `data-activity-entry` that keeps the emission in the run stream. Both carry the same phase, activity,
25
+ * and time. `seq` is the position of the emission in the body of its workflow, so each entry has its own id, and a
26
+ * recovered body counts the same emissions again and gives the same ids. Every producer mints the two parts here.
27
+ */
28
+ export function activityEmission(frame, seq, phase, activity, at) {
29
+ const { runId, stepId } = frame;
30
+ return {
31
+ activity: { type: "data-step-activity", id: stepPartId("step-activity", runId, stepId), runId, stepId, phase, activity, at },
32
+ entry: { type: "data-activity-entry", id: `${stepPartId("activity-entry", runId, stepId)}-${seq}`, runId, stepId, phase, activity, at },
33
+ };
34
+ }
35
+ /**
36
+ * The two parts of one synthesis progress report: the reconciling `data-synthesis-progress` that holds the current
37
+ * phase, and the `data-activity-entry` that keeps the report in the run stream under the synthesis step. `seq` is the
38
+ * position of the report in the synthesis, so each entry has its own id. The `extra` fields stay on the progress part.
39
+ */
40
+ export function synthesisEmission(runId, stepId, seq, phase, activity, at, extra) {
41
+ return {
42
+ progress: { type: "data-synthesis-progress", id: `synthesis-progress-${runId}`, runId, phase, activity, at, ...extra },
43
+ entry: { type: "data-activity-entry", id: `${stepPartId("activity-entry", runId, stepId)}-${seq}`, runId, stepId, phase, activity, at },
44
+ };
45
+ }
22
46
  /**
23
47
  * The live-activity phrase for one tool call: the tool's name, then its own
24
48
  * description of this call when it has one.
@@ -30,5 +30,5 @@ export declare const ArtifactManifestEntrySchema: z.ZodObject<{
30
30
  hash: z.ZodOptional<z.ZodString>;
31
31
  }, z.core.$strip>;
32
32
  export type ArtifactManifestEntry = z.infer<typeof ArtifactManifestEntrySchema>;
33
- /** Infer artifact type from a file path based on its parent subdirectory. */
33
+ /** Infer artifact type from a file path. A folder segment at the start of the path or after a `/` gives its type. */
34
34
  export declare function inferArtifactType(filePath: string): ArtifactType;
@@ -22,15 +22,17 @@ export const ArtifactManifestEntrySchema = z.object({
22
22
  /** SHA-256 content hash for integrity verification (e.g., sha256:abcdef...). */
23
23
  hash: z.string().optional(),
24
24
  });
25
- /** Infer artifact type from a file path based on its parent subdirectory. */
25
+ const FOLDER_TYPES = [
26
+ ["figures", "figure"],
27
+ ["scripts", "script"],
28
+ ["logs", "log"],
29
+ ["notebooks", "notebook"],
30
+ ];
31
+ /** Infer artifact type from a file path. A folder segment at the start of the path or after a `/` gives its type. */
26
32
  export function inferArtifactType(filePath) {
27
- if (filePath.includes("/figures/"))
28
- return "figure";
29
- if (filePath.includes("/scripts/"))
30
- return "script";
31
- if (filePath.includes("/logs/"))
32
- return "log";
33
- if (filePath.includes("/notebooks/"))
34
- return "notebook";
33
+ for (const [folder, type] of FOLDER_TYPES) {
34
+ if (filePath.startsWith(`${folder}/`) || filePath.includes(`/${folder}/`))
35
+ return type;
36
+ }
35
37
  return "output";
36
38
  }
@@ -11,13 +11,8 @@ export declare const PlanStepSchema: z.ZodObject<{
11
11
  context: z.ZodOptional<z.ZodString>;
12
12
  description: z.ZodOptional<z.ZodString>;
13
13
  id: z.ZodString;
14
- constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
15
- track: z.ZodString;
16
- step_type: z.ZodString;
17
- question: z.ZodString;
18
- acceptance_criteria: z.ZodArray<z.ZodString>;
19
14
  caveats: z.ZodOptional<z.ZodArray<z.ZodString>>;
20
- packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
15
+ question: z.ZodString;
21
16
  depends_on: z.ZodArray<z.ZodString>;
22
17
  resources: z.ZodNonOptional<z.ZodOptional<z.ZodObject<{
23
18
  cpu: z.ZodNumber;
@@ -26,6 +21,11 @@ export declare const PlanStepSchema: z.ZodObject<{
26
21
  count: z.ZodNumber;
27
22
  }, z.core.$strip>>;
28
23
  }, z.core.$strip>>>;
24
+ track: z.ZodString;
25
+ step_type: z.ZodString;
26
+ acceptance_criteria: z.ZodArray<z.ZodString>;
27
+ constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
28
+ packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
29
29
  agent: z.ZodEnum<{
30
30
  [x: string]: string;
31
31
  }>;
@@ -44,13 +44,8 @@ export declare const PlannerPlanSchema: z.ZodObject<{
44
44
  context: z.ZodOptional<z.ZodString>;
45
45
  description: z.ZodOptional<z.ZodString>;
46
46
  id: z.ZodString;
47
- constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
48
- track: z.ZodString;
49
- step_type: z.ZodString;
50
- question: z.ZodString;
51
- acceptance_criteria: z.ZodArray<z.ZodString>;
52
47
  caveats: z.ZodOptional<z.ZodArray<z.ZodString>>;
53
- packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
48
+ question: z.ZodString;
54
49
  depends_on: z.ZodArray<z.ZodString>;
55
50
  resources: z.ZodNonOptional<z.ZodOptional<z.ZodObject<{
56
51
  cpu: z.ZodNumber;
@@ -59,6 +54,11 @@ export declare const PlannerPlanSchema: z.ZodObject<{
59
54
  count: z.ZodNumber;
60
55
  }, z.core.$strip>>;
61
56
  }, z.core.$strip>>>;
57
+ track: z.ZodString;
58
+ step_type: z.ZodString;
59
+ acceptance_criteria: z.ZodArray<z.ZodString>;
60
+ constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
61
+ packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
62
62
  agent: z.ZodEnum<{
63
63
  [x: string]: string;
64
64
  }>;
@@ -86,13 +86,8 @@ export declare const PlanningAgentOutputSchema: z.ZodObject<{
86
86
  context: z.ZodOptional<z.ZodString>;
87
87
  description: z.ZodOptional<z.ZodString>;
88
88
  id: z.ZodString;
89
- constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
90
- track: z.ZodString;
91
- step_type: z.ZodString;
92
- question: z.ZodString;
93
- acceptance_criteria: z.ZodArray<z.ZodString>;
94
89
  caveats: z.ZodOptional<z.ZodArray<z.ZodString>>;
95
- packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
90
+ question: z.ZodString;
96
91
  depends_on: z.ZodArray<z.ZodString>;
97
92
  resources: z.ZodNonOptional<z.ZodOptional<z.ZodObject<{
98
93
  cpu: z.ZodNumber;
@@ -101,6 +96,11 @@ export declare const PlanningAgentOutputSchema: z.ZodObject<{
101
96
  count: z.ZodNumber;
102
97
  }, z.core.$strip>>;
103
98
  }, z.core.$strip>>>;
99
+ track: z.ZodString;
100
+ step_type: z.ZodString;
101
+ acceptance_criteria: z.ZodArray<z.ZodString>;
102
+ constraints: z.ZodOptional<z.ZodArray<z.ZodString>>;
103
+ packages: z.ZodNonOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
104
104
  agent: z.ZodEnum<{
105
105
  [x: string]: string;
106
106
  }>;
@@ -31,11 +31,11 @@ export declare const SynthesizedFindingSchema: z.ZodObject<{
31
31
  high: "high";
32
32
  }>;
33
33
  noveltyStatus: z.ZodEnum<{
34
- expected: "expected";
35
34
  novel: "novel";
36
35
  confirmed: "confirmed";
37
36
  partially_confirmed: "partially_confirmed";
38
37
  contradicted: "contradicted";
38
+ expected: "expected";
39
39
  }>;
40
40
  literatureInterpretation: z.ZodString;
41
41
  references: z.ZodArray<z.ZodObject<{
@@ -97,11 +97,11 @@ export declare const RunSynthesisSchema: z.ZodObject<{
97
97
  high: "high";
98
98
  }>;
99
99
  noveltyStatus: z.ZodEnum<{
100
- expected: "expected";
101
100
  novel: "novel";
102
101
  confirmed: "confirmed";
103
102
  partially_confirmed: "partially_confirmed";
104
103
  contradicted: "contradicted";
104
+ expected: "expected";
105
105
  }>;
106
106
  literatureInterpretation: z.ZodString;
107
107
  references: z.ZodArray<z.ZodObject<{
@@ -1,11 +1,44 @@
1
1
  /**
2
- * Cross-entity aggregate reads used by `routes/analyses-metrics.ts` to build
3
- * the per-analysis metrics view. Each query touches one table; the view is
4
- * the batch shape callers want.
2
+ * Cross-entity aggregate reads for a list of analyses. Each read takes the ids
3
+ * of a page and sends one statement, whatever the length of the list: an
4
+ * embedder builds the per-analysis summary of a list from these reads, never
5
+ * from one read for each analysis.
5
6
  */
6
7
  import { type ResultAsync } from "neverthrow";
8
+ import type { DataProfileLifecycleStatus } from "../contracts/data-profile.js";
7
9
  import { type DbError } from "../lib/db-result.js";
8
10
  import type { Querier } from "./db.js";
11
+ import type { RunStatus, TerminalRunStatus } from "./schema.js";
12
+ /** The newest run of one analysis, with the title of its plan and the counts of its step rows. */
13
+ export interface LatestRunSummary {
14
+ readonly analysisId: string;
15
+ readonly runId: string;
16
+ readonly status: RunStatus;
17
+ readonly planTitle: string | null;
18
+ readonly doneSteps: number;
19
+ readonly totalSteps: number;
20
+ readonly startedAt: string;
21
+ readonly completedAt: string | null;
22
+ }
23
+ /** A run of a list of run ids, with the fields of the newest-run read and the thread of the run. */
24
+ export interface RunProgressSummary extends LatestRunSummary {
25
+ /** The thread of the run as the ledger stores it, or `null`. */
26
+ readonly threadId: string | null;
27
+ }
28
+ /** A terminal run that ended at or after a time. */
29
+ export interface EndedRunSummary {
30
+ readonly analysisId: string;
31
+ readonly runId: string;
32
+ readonly status: TerminalRunStatus;
33
+ readonly completedAt: string;
34
+ }
35
+ /** The data profile state of one analysis that has a profile status. */
36
+ export interface DataProfileSummary {
37
+ readonly analysisId: string;
38
+ readonly status: DataProfileLifecycleStatus;
39
+ readonly completedAt: string | null;
40
+ readonly profiledFiles: number | null;
41
+ }
9
42
  export declare function queryRunCountsByAnalyses(pool: Querier, analysisIds: string[]): ResultAsync<Array<{
10
43
  analysisId: string;
11
44
  status: string;
@@ -15,7 +48,46 @@ export declare function queryThreadCountsByAnalyses(pool: Querier, analysisIds:
15
48
  analysisId: string;
16
49
  count: number;
17
50
  }>, DbError>;
18
- export declare function queryDataProfileStatusByAnalyses(pool: Querier, analysisIds: string[]): ResultAsync<Array<{
19
- analysisId: string;
20
- status: string | null;
21
- }>, DbError>;
51
+ /**
52
+ * The newest run of each analysis of a list, in one statement. An analysis with
53
+ * no run has no entry. The newest run has the latest `started_at`, and `run_id`
54
+ * breaks a tie in descending order. The `LATERAL` subquery reads
55
+ * `idx_cortex_runs_analysis_started`, thus one index entry for each analysis
56
+ * and not a sort of the run history.
57
+ *
58
+ * The plan joins on `plan_id` and `analysis_id`: a plan of a different analysis
59
+ * gives no title, the scope rule of `loadPlan`. The statement gives the title
60
+ * only when it is a string, and the row mapping trims it with `trim()`, the
61
+ * rule of the cli `planTitleOf`. A blank title or a title that is not a string
62
+ * reads as `null`. The step counts
63
+ * cover the ledger rows of the selected run only, the reserved synthesis row
64
+ * included.
65
+ */
66
+ export declare function queryLatestRunsByAnalyses(pool: Querier, analysisIds: string[]): ResultAsync<LatestRunSummary[], DbError>;
67
+ /**
68
+ * The progress of each run of a list of run ids, in one statement. An id with
69
+ * no run row has no entry. The entries come newest first by `started_at`, and
70
+ * `run_id` breaks a tie in descending order. The plan title and the step counts
71
+ * follow the rules of `queryLatestRunsByAnalyses`, and each entry adds the
72
+ * thread of the run.
73
+ */
74
+ export declare function queryRunProgressByRuns(pool: Querier, runIds: string[]): ResultAsync<RunProgressSummary[], DbError>;
75
+ /**
76
+ * The newest `limit` terminal runs of every analysis that ended at or after
77
+ * `since`, newest completion first, with `run_id` breaking a tie in descending
78
+ * order. `since` is in the form of `toISOString()`, the form of each
79
+ * `completed_at` stamp, thus the text comparison is the time comparison. The
80
+ * statement walks `idx_cortex_runs_completed`.
81
+ */
82
+ export declare function queryRunsEndedSince(pool: Querier, input: {
83
+ since: string;
84
+ limit: number;
85
+ }): ResultAsync<EndedRunSummary[], DbError>;
86
+ /**
87
+ * The profile state of each analysis of a list, in one statement. An analysis
88
+ * with no ledger row, or with a cleared row whose status is null, has no entry:
89
+ * the same collapsed absence as `loadDataProfileStatus`. The statement selects
90
+ * only the three parts of the stored result that the file count reads, and the
91
+ * count itself is `profileDatasetFileCount`.
92
+ */
93
+ export declare function queryDataProfileStatusByAnalyses(pool: Querier, analysisIds: string[]): ResultAsync<DataProfileSummary[], DbError>;
@@ -1,9 +1,11 @@
1
1
  /**
2
- * Cross-entity aggregate reads used by `routes/analyses-metrics.ts` to build
3
- * the per-analysis metrics view. Each query touches one table; the view is
4
- * the batch shape callers want.
2
+ * Cross-entity aggregate reads for a list of analyses. Each read takes the ids
3
+ * of a page and sends one statement, whatever the length of the list: an
4
+ * embedder builds the per-analysis summary of a list from these reads, never
5
+ * from one read for each analysis.
5
6
  */
6
7
  import { okAsync } from "neverthrow";
8
+ import { profileDatasetFileCount } from "../app/data-profile-view.js";
7
9
  import { tryQuery } from "../lib/db-result.js";
8
10
  export function queryRunCountsByAnalyses(pool, analysisIds) {
9
11
  if (analysisIds.length === 0)
@@ -41,19 +43,152 @@ export function queryThreadCountsByAnalyses(pool, analysisIds) {
41
43
  }));
42
44
  });
43
45
  }
46
+ /** A plan title as text: trimmed with `trim()`, and `null` when it is blank. The SQL gives the title only when it is a string. */
47
+ function titleOf(title) {
48
+ const trimmed = title?.trim() ?? "";
49
+ return trimmed === "" ? null : trimmed;
50
+ }
51
+ /**
52
+ * The columns of a run summary over a run alias `r`, and the plan alias `p` and
53
+ * the step count alias `s` of `RUN_PROGRESS_JOINS`. The two reads of a run
54
+ * summary put these after their own selection of `r`, thus the title rule and
55
+ * the step count rule have one text.
56
+ */
57
+ const RUN_PROGRESS_COLUMNS = `r.analysis_id, r.run_id, r.status, r.started_at, r.completed_at,
58
+ CASE WHEN jsonb_typeof(p.plan->'title') = 'string' THEN p.plan->>'title' END AS plan_title,
59
+ s.done_steps, s.total_steps`;
60
+ /** The plan join and the step count subquery for a run alias `r` that selects `analysis_id`, `run_id`, and `plan_id`. */
61
+ const RUN_PROGRESS_JOINS = `LEFT JOIN cortex_plans p ON p.plan_id = r.plan_id AND p.analysis_id = r.analysis_id
62
+ CROSS JOIN LATERAL (
63
+ SELECT COUNT(*)::int AS total_steps,
64
+ (COUNT(*) FILTER (WHERE status = 'completed'))::int AS done_steps
65
+ FROM cortex_step_executions
66
+ WHERE run_id = r.run_id
67
+ ) s`;
68
+ function toRunSummary(row) {
69
+ return {
70
+ analysisId: row.analysis_id,
71
+ runId: row.run_id,
72
+ status: row.status,
73
+ planTitle: titleOf(row.plan_title),
74
+ doneSteps: row.done_steps,
75
+ totalSteps: row.total_steps,
76
+ startedAt: row.started_at,
77
+ completedAt: row.completed_at,
78
+ };
79
+ }
80
+ /**
81
+ * The newest run of each analysis of a list, in one statement. An analysis with
82
+ * no run has no entry. The newest run has the latest `started_at`, and `run_id`
83
+ * breaks a tie in descending order. The `LATERAL` subquery reads
84
+ * `idx_cortex_runs_analysis_started`, thus one index entry for each analysis
85
+ * and not a sort of the run history.
86
+ *
87
+ * The plan joins on `plan_id` and `analysis_id`: a plan of a different analysis
88
+ * gives no title, the scope rule of `loadPlan`. The statement gives the title
89
+ * only when it is a string, and the row mapping trims it with `trim()`, the
90
+ * rule of the cli `planTitleOf`. A blank title or a title that is not a string
91
+ * reads as `null`. The step counts
92
+ * cover the ledger rows of the selected run only, the reserved synthesis row
93
+ * included.
94
+ */
95
+ export function queryLatestRunsByAnalyses(pool, analysisIds) {
96
+ if (analysisIds.length === 0)
97
+ return okAsync([]);
98
+ return tryQuery("analysesMetrics.queryLatestRunsByAnalyses", async () => {
99
+ const result = await pool.query({
100
+ text: `SELECT ${RUN_PROGRESS_COLUMNS}
101
+ FROM unnest($1::text[]) AS a(id)
102
+ CROSS JOIN LATERAL (
103
+ SELECT analysis_id, run_id, status, started_at, completed_at, plan_id
104
+ FROM cortex_runs
105
+ WHERE analysis_id = a.id
106
+ ORDER BY started_at DESC, run_id DESC
107
+ LIMIT 1
108
+ ) r
109
+ ${RUN_PROGRESS_JOINS}`,
110
+ values: [analysisIds],
111
+ });
112
+ return result.rows.map(toRunSummary);
113
+ });
114
+ }
115
+ /**
116
+ * The progress of each run of a list of run ids, in one statement. An id with
117
+ * no run row has no entry. The entries come newest first by `started_at`, and
118
+ * `run_id` breaks a tie in descending order. The plan title and the step counts
119
+ * follow the rules of `queryLatestRunsByAnalyses`, and each entry adds the
120
+ * thread of the run.
121
+ */
122
+ export function queryRunProgressByRuns(pool, runIds) {
123
+ if (runIds.length === 0)
124
+ return okAsync([]);
125
+ return tryQuery("analysesMetrics.queryRunProgressByRuns", async () => {
126
+ const result = await pool.query({
127
+ text: `SELECT ${RUN_PROGRESS_COLUMNS}, r.thread_id
128
+ FROM cortex_runs r
129
+ ${RUN_PROGRESS_JOINS}
130
+ WHERE r.run_id = ANY($1::text[])
131
+ ORDER BY r.started_at DESC, r.run_id DESC`,
132
+ values: [runIds],
133
+ });
134
+ return result.rows.map((row) => ({ ...toRunSummary(row), threadId: row.thread_id }));
135
+ });
136
+ }
137
+ /**
138
+ * The newest `limit` terminal runs of every analysis that ended at or after
139
+ * `since`, newest completion first, with `run_id` breaking a tie in descending
140
+ * order. `since` is in the form of `toISOString()`, the form of each
141
+ * `completed_at` stamp, thus the text comparison is the time comparison. The
142
+ * statement walks `idx_cortex_runs_completed`.
143
+ */
144
+ export function queryRunsEndedSince(pool, input) {
145
+ return tryQuery("analysesMetrics.queryRunsEndedSince", async () => {
146
+ const result = await pool.query({
147
+ text: `SELECT analysis_id, run_id, status, completed_at
148
+ FROM cortex_runs
149
+ WHERE status IN ('completed', 'partial', 'failed', 'canceled', 'suspended_insufficient_funds')
150
+ AND completed_at >= $1
151
+ ORDER BY completed_at DESC, run_id DESC
152
+ LIMIT $2`,
153
+ values: [input.since, input.limit],
154
+ });
155
+ return result.rows.map((row) => ({
156
+ analysisId: row.analysis_id,
157
+ runId: row.run_id,
158
+ status: row.status,
159
+ completedAt: row.completed_at,
160
+ }));
161
+ });
162
+ }
163
+ /**
164
+ * The profile state of each analysis of a list, in one statement. An analysis
165
+ * with no ledger row, or with a cleared row whose status is null, has no entry:
166
+ * the same collapsed absence as `loadDataProfileStatus`. The statement selects
167
+ * only the three parts of the stored result that the file count reads, and the
168
+ * count itself is `profileDatasetFileCount`.
169
+ */
44
170
  export function queryDataProfileStatusByAnalyses(pool, analysisIds) {
45
171
  if (analysisIds.length === 0)
46
172
  return okAsync([]);
47
173
  return tryQuery("analysesMetrics.queryDataProfileStatusByAnalyses", async () => {
48
174
  const result = await pool.query({
49
- text: `SELECT analysis_id, data_profile_status
175
+ text: `SELECT analysis_id, data_profile_status, data_profile_completed_at,
176
+ data_profile_result->'partition' AS partition,
177
+ data_profile_result->'coverage' AS coverage,
178
+ data_profile_result->'kinds' AS kinds
50
179
  FROM cortex_analysis_state
51
- WHERE analysis_id = ANY($1::text[])`,
180
+ WHERE analysis_id = ANY($1::text[]) AND data_profile_status IS NOT NULL`,
52
181
  values: [analysisIds],
53
182
  });
54
183
  return result.rows.map((r) => ({
55
184
  analysisId: r.analysis_id,
56
- status: r.data_profile_status ?? null,
185
+ status: r.data_profile_status,
186
+ completedAt: r.data_profile_completed_at ?? null,
187
+ profiledFiles: profileDatasetFileCount({
188
+ ...(r.partition === null ? {} : { partition: r.partition }),
189
+ ...(r.coverage === null ? {} : { coverage: r.coverage }),
190
+ ...(r.kinds === null ? {} : { kinds: r.kinds }),
191
+ }),
57
192
  }));
58
193
  });
59
194
  }
@@ -5,7 +5,7 @@
5
5
  import type { ResultAsync } from "neverthrow";
6
6
  import { type DbError } from "../lib/db-result.js";
7
7
  import type { Querier } from "./db.js";
8
- import type { ArtifactRow } from "./schema.js";
8
+ import type { ArtifactRole, ArtifactRow } from "./schema.js";
9
9
  export interface RegisterArtifactInput {
10
10
  resourceId: string;
11
11
  path: string;
@@ -75,8 +75,55 @@ export interface AnalysisArtifactRef {
75
75
  * false.
76
76
  */
77
77
  export declare function queryAnalysisArtifacts(pool: Querier, analysisId: string): ResultAsync<AnalysisArtifactRef[], DbError>;
78
- /** Count step-output artifacts produced by a run — for the run-completed card. */
79
- export declare function countArtifactsForRun(pool: Querier, analysisId: string, runId: string): ResultAsync<number, DbError>;
78
+ /** The sort of {@link queryArtifactPage}: `path` is path order, `recent` is newest registration first. */
79
+ export type ArtifactPageSort = "path" | "recent";
80
+ /** The filters, the sort, and the window of {@link queryArtifactPage}. A filter that is absent selects each row. */
81
+ export interface ArtifactPageQuery {
82
+ runId?: string;
83
+ stepId?: string;
84
+ fileType?: string;
85
+ /** A part of the path, with no regard to case. Each character matches only itself. */
86
+ q?: string;
87
+ sort: ArtifactPageSort;
88
+ limit: number;
89
+ offset: number;
90
+ }
91
+ /** One ledger row of {@link queryArtifactPage}. */
92
+ export interface ArtifactPageEntry {
93
+ /** Workspace-root-relative path (`runs/{runId}/{stepId}/output/de.csv`). */
94
+ path: string;
95
+ /** Bytes. */
96
+ size: number;
97
+ fileType: string | null;
98
+ role: ArtifactRole;
99
+ runId: string | null;
100
+ stepId: string | null;
101
+ createdAt: string;
102
+ }
103
+ /** One page of the ledger, and the count of the rows that the filters select. */
104
+ export interface ArtifactPage {
105
+ entries: ArtifactPageEntry[];
106
+ total: number;
107
+ }
108
+ /**
109
+ * One page of the artifact ledger of an analysis, in two statements: the count of the rows that the filters
110
+ * select, and the page. The count is a separate statement because a page past the end has no row to carry it.
111
+ *
112
+ * Every row of the analysis is a member, an `input` row and a row with `unrecoverable_at` included. The cost
113
+ * grows with the ledger of the one analysis, because the count reads each filtered row.
114
+ */
115
+ export declare function queryArtifactPage(pool: Querier, analysisId: string, query: ArtifactPageQuery): ResultAsync<ArtifactPage, DbError>;
116
+ /** The step-output count of one run, from {@link countArtifactsByRuns}. */
117
+ export interface RunArtifactCount {
118
+ runId: string;
119
+ count: number;
120
+ }
121
+ /**
122
+ * The step-output count of each run of a list, in one statement. A run with no step output has no entry,
123
+ * and a caller reads it as 0. An `input` row never counts. The run-completed card and a list of runs use
124
+ * this one rule.
125
+ */
126
+ export declare function countArtifactsByRuns(pool: Querier, analysisId: string, runIds: readonly string[]): ResultAsync<RunArtifactCount[], DbError>;
80
127
  export declare function updateArtifactId(pool: Querier, resourceId: string, path: string, artifactId: string, fileType?: string | null): ResultAsync<void, DbError>;
81
128
  export declare function updateFileIds(pool: Querier, pairs: Array<{
82
129
  artifactId: string;
@@ -179,16 +179,76 @@ export function queryAnalysisArtifacts(pool, analysisId) {
179
179
  return result.rows.map((r) => ({ path: r.path, hash: r.hash, fileType: r.file_type ?? null }));
180
180
  });
181
181
  }
182
- /** Count step-output artifacts produced by a run — for the run-completed card. */
183
- export function countArtifactsForRun(pool, analysisId, runId) {
184
- return tryQuery("artifacts.countArtifactsForRun", async () => {
182
+ /**
183
+ * One page of the artifact ledger of an analysis, in two statements: the count of the rows that the filters
184
+ * select, and the page. The count is a separate statement because a page past the end has no row to carry it.
185
+ *
186
+ * Every row of the analysis is a member, an `input` row and a row with `unrecoverable_at` included. The cost
187
+ * grows with the ledger of the one analysis, because the count reads each filtered row.
188
+ */
189
+ export function queryArtifactPage(pool, analysisId, query) {
190
+ return tryQuery("artifacts.queryArtifactPage", async () => {
191
+ const values = [analysisId];
192
+ const conditions = ["analysis_id = $1"];
193
+ const bind = (value) => {
194
+ values.push(value);
195
+ return `$${values.length}`;
196
+ };
197
+ if (query.runId !== undefined)
198
+ conditions.push(`source_run = ${bind(query.runId)}`);
199
+ if (query.stepId !== undefined)
200
+ conditions.push(`source_step = ${bind(query.stepId)}`);
201
+ if (query.fileType !== undefined)
202
+ conditions.push(`file_type = ${bind(query.fileType)}`);
203
+ // `LIKE` would turn `%` and `_` of the input into wildcards.
204
+ if (query.q !== undefined)
205
+ conditions.push(`strpos(lower(path), lower(${bind(query.q)}::text)) > 0`);
206
+ const where = conditions.join(" AND ");
207
+ const countResult = await pool.query({
208
+ text: `SELECT COUNT(*)::int AS total FROM cortex_artifacts WHERE ${where}`,
209
+ values,
210
+ });
211
+ // `path` is unique in one analysis, thus it breaks each tie and two pages never overlap.
212
+ const order = query.sort === "recent" ? "created_at DESC, path ASC" : "path ASC";
213
+ const rowsResult = await pool.query({
214
+ text: `SELECT path, size, file_type, role, source_run, source_step, created_at
215
+ FROM cortex_artifacts
216
+ WHERE ${where}
217
+ ORDER BY ${order}
218
+ LIMIT ${bind(query.limit)} OFFSET ${bind(query.offset)}`,
219
+ values,
220
+ });
221
+ return {
222
+ entries: rowsResult.rows.map((r) => ({
223
+ path: r.path,
224
+ size: Number(r.size),
225
+ fileType: r.file_type ?? null,
226
+ role: r.role,
227
+ runId: r.source_run ?? null,
228
+ stepId: r.source_step ?? null,
229
+ createdAt: r.created_at,
230
+ })),
231
+ total: Number(countResult.rows[0]?.total ?? 0),
232
+ };
233
+ });
234
+ }
235
+ /**
236
+ * The step-output count of each run of a list, in one statement. A run with no step output has no entry,
237
+ * and a caller reads it as 0. An `input` row never counts. The run-completed card and a list of runs use
238
+ * this one rule.
239
+ */
240
+ export function countArtifactsByRuns(pool, analysisId, runIds) {
241
+ return tryQuery("artifacts.countArtifactsByRuns", async () => {
242
+ if (runIds.length === 0)
243
+ return [];
185
244
  const result = await pool.query({
186
- text: `SELECT COUNT(*)::text AS n
245
+ text: `SELECT source_run, COUNT(*)::int AS n
187
246
  FROM cortex_artifacts
188
- WHERE analysis_id = $1 AND source_run = $2 AND role = 'step_output'`,
189
- values: [analysisId, runId],
247
+ WHERE analysis_id = $1 AND source_run = ANY($2::text[]) AND role = 'step_output'
248
+ GROUP BY source_run`,
249
+ values: [analysisId, [...runIds]],
190
250
  });
191
- return Number(result.rows[0]?.n ?? 0);
251
+ return result.rows.map((r) => ({ runId: r.source_run, count: Number(r.n) }));
192
252
  });
193
253
  }
194
254
  export function updateArtifactId(pool, resourceId, path, artifactId, fileType) {
@@ -101,12 +101,14 @@ export declare function recordDataProfileWorkflowId(pool: Querier, analysisId: s
101
101
  * write per `running` claim, so `stamped: true` is the exactly-once point of a
102
102
  * profile's terminal transition. It carries the `data_profile_started_at` of the
103
103
  * claim it closed, so the caller measures the profile from the ledger's own start.
104
+ * It also carries the `data_profile_completed_at` that the write stamped.
104
105
  */
105
106
  export type DataProfileTerminalWrite = {
106
107
  readonly stamped: false;
107
108
  } | {
108
109
  readonly stamped: true;
109
110
  readonly startedAt: string | null;
111
+ readonly completedAt: string;
110
112
  };
111
113
  /**
112
114
  * Stamp a claimed-`running` row `completed` and record its result — a terminal
@@ -124,7 +126,7 @@ export type DataProfileTerminalWrite = {
124
126
  * guard only ever refuses a row another writer already moved on from.
125
127
  *
126
128
  * `stamped: true` when this call stamped the row, with the `data_profile_started_at`
127
- * of the claim it closed; `stamped: false` when the guard refused it (the row was
129
+ * of the claim it closed and the `data_profile_completed_at` it stamped; `stamped: false` when the guard refused it (the row was
128
130
  * cleared/expired/replayed away) — a no-op the caller logs, not an error.
129
131
  */
130
132
  export declare function completeDataProfile(pool: Querier, analysisId: string, result?: DataProfileResult): ResultAsync<DataProfileTerminalWrite, DbError>;
@@ -137,7 +139,7 @@ export declare function completeDataProfile(pool: Querier, analysisId: string, r
137
139
  * prior profile survives the failure (the re-profile/retry route can keep serving it).
138
140
  *
139
141
  * `stamped: true` when this call stamped the row, with the `data_profile_started_at`
140
- * of the claim it closed; `stamped: false` when the guard refused it — a logged
142
+ * of the claim it closed and the `data_profile_completed_at` it stamped; `stamped: false` when the guard refused it — a logged
141
143
  * no-op, not an error.
142
144
  */
143
145
  export declare function failDataProfile(pool: Querier, analysisId: string, error: string): ResultAsync<DataProfileTerminalWrite, DbError>;