@devpad/api 2.6.11 → 2.6.12

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/dist/index.js CHANGED
@@ -16,15 +16,15 @@ import {
16
16
  upsert_project,
17
17
  upsert_task_link,
18
18
  upsert_todo
19
- } from "./chunk-AXQWQXZR.js";
19
+ } from "./chunk-DHYAC4LG.js";
20
20
  import {
21
21
  CategoryCreateSchema,
22
22
  PostCreateSchema,
23
23
  PostListParamsSchema,
24
24
  PostUpdateSchema
25
- } from "./chunk-5L3AUVMM.js";
25
+ } from "./chunk-V6CM3V4I.js";
26
26
 
27
- // ../schema/dist/pulse/types.js
27
+ // ../schema/src/pulse/types.ts
28
28
  import { z } from "zod";
29
29
  var PulseEventRowSchema = z.object({
30
30
  id: z.number(),
@@ -84,10 +84,14 @@ var PulseLatencyResultSchema = z.object({
84
84
  percentiles: z.record(z.string(), z.number().nullable()),
85
85
  by_minute: z.array(PulseLatencyByMinuteSchema)
86
86
  });
87
- var pulseSummaryHasData = (summary) => Boolean(summary && (summary.pageviews || summary.sessions || summary.events_total || summary.errors || summary.request_count));
87
+ var pulseSummaryHasData = (summary) => Boolean(
88
+ summary && (summary.pageviews || summary.sessions || summary.events_total || summary.errors || summary.request_count)
89
+ );
88
90
 
89
91
  // src/errors.ts
90
92
  var ApiError = class _ApiError extends Error {
93
+ code;
94
+ statusCode;
91
95
  constructor(message, options = {}) {
92
96
  super(message);
93
97
  this.name = "ApiError";
@@ -280,11 +284,12 @@ function getUserFriendlyErrorMessage(error) {
280
284
  var ArrayBufferedQueue = class {
281
285
  constructor(capacity) {
282
286
  this.capacity = capacity;
283
- this.entries = [];
284
- this.head = 0;
285
- this.tail = 0;
286
- this.count = 0;
287
287
  }
288
+ capacity;
289
+ entries = [];
290
+ head = 0;
291
+ tail = 0;
292
+ count = 0;
288
293
  latest() {
289
294
  if (this.count === 0) return null;
290
295
  return this.entries[this.tail - 1] ?? null;
@@ -316,8 +321,16 @@ var ArrayBufferedQueue = class {
316
321
  }
317
322
  };
318
323
  var ApiClient = class {
324
+ base_url;
325
+ api_key;
326
+ request_history;
327
+ category = "api";
328
+ default_headers;
329
+ custom_fetch;
330
+ credentials;
331
+ auth_mode;
332
+ debug;
319
333
  constructor(options) {
320
- this.category = "api";
321
334
  this.auth_mode = options.auth_mode ?? (options.api_key?.startsWith("jwt:") ? "session" : "key");
322
335
  if (this.auth_mode !== "cookie") {
323
336
  if (!options.api_key) throw new Error("API key is required");
@@ -515,1224 +528,1227 @@ function wrap(fn) {
515
528
 
516
529
  // src/api-client.ts
517
530
  var ApiClient2 = class {
531
+ clients;
532
+ api_key_field;
533
+ auth_mode_field;
518
534
  constructor(options) {
535
+ const base_url = options.base_url || "http://localhost:4321/api/v1";
536
+ this.api_key_field = options.api_key ?? "";
537
+ this.auth_mode_field = options.auth_mode ?? (options.api_key?.startsWith("jwt:") ? "session" : options.api_key ? "key" : "cookie");
538
+ const clientOptions = {
539
+ base_url,
540
+ api_key: options.api_key,
541
+ max_history_size: options.max_history_size,
542
+ auth_mode: this.auth_mode_field,
543
+ credentials: options.credentials,
544
+ default_headers: options.default_headers,
545
+ custom_fetch: options.custom_fetch
546
+ };
547
+ const auth_base_url = base_url.replace(/\/v1\/?$/, "");
548
+ this.clients = {
549
+ auth: new ApiClient({ ...clientOptions, category: "auth" }),
550
+ auth_root: new ApiClient({
551
+ ...clientOptions,
552
+ base_url: auth_base_url,
553
+ category: "auth"
554
+ }),
555
+ projects: new ApiClient({ ...clientOptions, category: "projects" }),
556
+ tasks: new ApiClient({ ...clientOptions, category: "tasks" }),
557
+ milestones: new ApiClient({ ...clientOptions, category: "milestones" }),
558
+ goals: new ApiClient({ ...clientOptions, category: "goals" }),
559
+ github: new ApiClient({ ...clientOptions, category: "github" }),
560
+ tags: new ApiClient({ ...clientOptions, category: "tags" }),
561
+ blog: new ApiClient({ ...clientOptions, category: "blog" }),
562
+ media: new ApiClient({ ...clientOptions, category: "media" }),
563
+ pulse: new ApiClient({ ...clientOptions, base_url: `${base_url}/pulse`, category: "pulse" }),
564
+ pipelines: new ApiClient({ ...clientOptions, category: "pipelines" }),
565
+ hooks: new ApiClient({ ...clientOptions, category: "hooks" }),
566
+ docs: new ApiClient({ ...clientOptions, category: "docs" }),
567
+ signoffs: new ApiClient({ ...clientOptions, category: "signoffs" }),
568
+ reviews: new ApiClient({ ...clientOptions, category: "reviews" }),
569
+ admin: new ApiClient({ ...clientOptions, category: "admin" })
570
+ };
571
+ }
572
+ /**
573
+ * Auth namespace with Result-wrapped operations
574
+ */
575
+ auth = {
576
+ session: () => wrap(
577
+ () => this.clients.auth_root.get("/auth/session")
578
+ ),
579
+ keys: {
580
+ list: () => wrap(() => this.clients.auth.get("/keys")),
581
+ create: (input) => {
582
+ const body = typeof input === "string" ? { name: input } : input ?? {};
583
+ return wrap(
584
+ () => this.clients.auth.post("/keys", { body })
585
+ );
586
+ },
587
+ revoke: (key_id) => wrap(() => this.clients.auth.delete(`/keys/${key_id}`)),
588
+ remove: (key_id) => wrap(() => this.clients.auth.delete(`/keys/${key_id}`))
589
+ }
590
+ };
591
+ /**
592
+ * Projects namespace with Result-wrapped operations
593
+ */
594
+ projects = {
519
595
  /**
520
- * Auth namespace with Result-wrapped operations
596
+ * List projects with optional filtering
521
597
  */
522
- this.auth = {
523
- session: () => wrap(
524
- () => this.clients.auth_root.get("/auth/session")
525
- ),
526
- keys: {
527
- list: () => wrap(() => this.clients.auth.get("/keys")),
528
- create: (input) => {
529
- const body = typeof input === "string" ? { name: input } : input ?? {};
530
- return wrap(
531
- () => this.clients.auth.post("/keys", { body })
532
- );
533
- },
534
- revoke: (key_id) => wrap(() => this.clients.auth.delete(`/keys/${key_id}`)),
535
- remove: (key_id) => wrap(() => this.clients.auth.delete(`/keys/${key_id}`))
536
- }
537
- };
598
+ list: (filters) => wrap(() => this.clients.projects.get(filters?.private === false ? "/projects/public" : "/projects")),
538
599
  /**
539
- * Projects namespace with Result-wrapped operations
600
+ * Get project map
540
601
  */
541
- this.projects = {
542
- /**
543
- * List projects with optional filtering
544
- */
545
- list: (filters) => wrap(() => this.clients.projects.get(filters?.private === false ? "/projects/public" : "/projects")),
546
- /**
547
- * Get project map
548
- */
549
- map: async (filters) => wrap(async () => {
550
- const result = await this.projects.list(filters);
551
- if (!result.ok) throw new Error(result.error.message);
552
- return result.value.reduce((acc, project) => {
553
- acc[project.id] = project;
554
- return acc;
555
- }, {});
556
- }),
557
- /**
558
- * Get project by ID
559
- */
560
- find: (id) => wrap(() => this.clients.projects.get("/projects", { query: { id } })),
561
- /**
562
- * Get project by name
563
- */
564
- getByName: (name) => wrap(() => this.clients.projects.get("/projects", { query: { name } })),
565
- /**
566
- * Get project by ID (throws if not found)
567
- */
568
- getById: (id) => wrap(() => this.clients.projects.get("/projects", { query: { id } })),
569
- /**
570
- * Create a new project
571
- */
572
- create: (data) => wrap(() => this.clients.projects.patch("/projects", { body: data })),
573
- /**
574
- * Update an existing project
575
- */
576
- update: async (idOrData, changes) => wrap(async () => {
577
- if (typeof idOrData === "object" && idOrData.id) {
578
- return this.clients.projects.patch("/projects", {
579
- body: idOrData
580
- });
581
- }
582
- const id = idOrData;
583
- if (!changes) {
584
- throw new Error("Changes parameter required for update");
585
- }
586
- const result = await this.projects.find(id);
587
- if (!result.ok) throw new Error(result.error.message);
588
- if (!result.value) throw new Error(`Project with id ${id} not found`);
589
- const project = result.value;
590
- const updateData = {
591
- id: project.id,
592
- project_id: project.project_id,
593
- owner_id: project.owner_id,
594
- name: project.name,
595
- description: project.description,
596
- specification: project.specification,
597
- repo_url: project.repo_url,
598
- repo_id: project.repo_id,
599
- icon_url: project.icon_url,
600
- status: project.status,
601
- deleted: project.deleted,
602
- link_url: project.link_url,
603
- link_text: project.link_text,
604
- visibility: project.visibility,
605
- current_version: project.current_version,
606
- ...changes
607
- };
602
+ map: async (filters) => wrap(async () => {
603
+ const result = await this.projects.list(filters);
604
+ if (!result.ok) throw new Error(result.error.message);
605
+ return result.value.reduce((acc, project) => {
606
+ acc[project.id] = project;
607
+ return acc;
608
+ }, {});
609
+ }),
610
+ /**
611
+ * Get project by ID
612
+ */
613
+ find: (id) => wrap(() => this.clients.projects.get("/projects", { query: { id } })),
614
+ /**
615
+ * Get project by name
616
+ */
617
+ getByName: (name) => wrap(() => this.clients.projects.get("/projects", { query: { name } })),
618
+ /**
619
+ * Get project by ID (throws if not found)
620
+ */
621
+ getById: (id) => wrap(() => this.clients.projects.get("/projects", { query: { id } })),
622
+ /**
623
+ * Create a new project
624
+ */
625
+ create: (data) => wrap(() => this.clients.projects.patch("/projects", { body: data })),
626
+ /**
627
+ * Update an existing project
628
+ */
629
+ update: async (idOrData, changes) => wrap(async () => {
630
+ if (typeof idOrData === "object" && idOrData.id) {
608
631
  return this.clients.projects.patch("/projects", {
609
- body: updateData
632
+ body: idOrData
610
633
  });
611
- }),
612
- /**
613
- * Project configuration operations
614
- */
615
- config: {
616
- /**
617
- * Get project configuration
618
- */
619
- load: (project_id) => wrap(
620
- () => this.clients.projects.get("/projects/config", {
621
- query: { project_id }
622
- })
623
- ),
624
- /**
625
- * Save project configuration
626
- */
627
- save: (request) => wrap(
628
- () => this.clients.projects.patch("/projects/save_config", {
629
- body: request
630
- })
631
- )
632
- },
633
- /**
634
- * Scanning operations
635
- */
636
- scan: {
637
- /**
638
- * Initiate a repository scan (returns stream)
639
- */
640
- initiate: async (project_id) => {
641
- const response = await fetch(`${this.clients.projects.url()}/projects/scan?project_id=${project_id}`, {
642
- method: "POST",
643
- headers: this.clients.projects.headers()
644
- });
645
- if (!response.body) {
646
- throw new Error("No response body");
647
- }
648
- const stream = response.body.pipeThrough(new TextDecoderStream());
649
- return stream;
650
- },
651
- /**
652
- * Get pending scan updates for a project
653
- */
654
- updates: (project_id) => wrap(
655
- () => this.clients.projects.get("/projects/updates", { query: { project_id } }).then((response) => response.updates)
656
- ),
657
- /**
658
- * Process scan results
659
- */
660
- update: (project_id, data) => wrap(
661
- () => this.clients.projects.post("/projects/scan_status", {
662
- query: { project_id },
663
- body: data
664
- })
665
- )
666
- },
667
- /**
668
- * Get project history
669
- */
670
- history: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/history`)),
671
- /**
672
- * Legacy methods (keeping for compatibility)
673
- */
674
- upsert: (data) => wrap(() => this.clients.projects.patch("/projects", { body: data })),
634
+ }
635
+ const id = idOrData;
636
+ if (!changes) {
637
+ throw new Error("Changes parameter required for update");
638
+ }
639
+ const result = await this.projects.find(id);
640
+ if (!result.ok) throw new Error(result.error.message);
641
+ if (!result.value) throw new Error(`Project with id ${id} not found`);
642
+ const project = result.value;
643
+ const updateData = {
644
+ id: project.id,
645
+ project_id: project.project_id,
646
+ owner_id: project.owner_id,
647
+ name: project.name,
648
+ description: project.description,
649
+ specification: project.specification,
650
+ repo_url: project.repo_url,
651
+ repo_id: project.repo_id,
652
+ icon_url: project.icon_url,
653
+ status: project.status,
654
+ deleted: project.deleted,
655
+ link_url: project.link_url,
656
+ link_text: project.link_text,
657
+ visibility: project.visibility,
658
+ current_version: project.current_version,
659
+ ...changes
660
+ };
661
+ return this.clients.projects.patch("/projects", {
662
+ body: updateData
663
+ });
664
+ }),
665
+ /**
666
+ * Project configuration operations
667
+ */
668
+ config: {
675
669
  /**
676
- * Fetch project specification from GitHub
670
+ * Get project configuration
677
671
  */
678
- specification: (project_id) => wrap(
679
- () => this.clients.projects.get("/projects/fetch_spec", {
672
+ load: (project_id) => wrap(
673
+ () => this.clients.projects.get("/projects/config", {
680
674
  query: { project_id }
681
675
  })
682
676
  ),
683
677
  /**
684
- * Delete project (soft delete)
678
+ * Save project configuration
685
679
  */
686
- deleteProject: (project) => wrap(
687
- () => this.clients.projects.patch("/projects", {
688
- body: { ...project, deleted: true }
680
+ save: (request) => wrap(
681
+ () => this.clients.projects.patch("/projects/save_config", {
682
+ body: request
689
683
  })
690
- ),
691
- /**
692
- * Whole-project graph read (v2.5, canvas home task P2.2) — every task
693
- * in the project (fold kinds included), every in-project task_link,
694
- * and batched rollups. Backs the canvas' spatial view of the project.
695
- */
696
- graph: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/graph`)),
697
- /**
698
- * Canvas view-state (v2.5, task P3.1) — pinned node positions.
699
- * Last-write-wins; `putViewState` always sends the full layout.
700
- */
701
- getViewState: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/view-state`)),
702
- putViewState: (project_id, layout) => wrap(
703
- () => this.clients.projects.put(`/projects/${project_id}/view-state`, { body: layout })
704
684
  )
705
- };
685
+ },
706
686
  /**
707
- * Milestones namespace with Result-wrapped operations
687
+ * Scanning operations
708
688
  */
709
- this.milestones = {
689
+ scan: {
710
690
  /**
711
- * List milestones for authenticated user
691
+ * Initiate a repository scan (returns stream)
712
692
  */
713
- list: () => wrap(() => this.clients.milestones.get("/milestones")),
714
- /**
715
- * Get milestones by project ID
716
- */
717
- getByProject: (project_id) => wrap(() => this.clients.milestones.get(`/projects/${project_id}/milestones`)),
718
- /**
719
- * v2.4 (B2 critic carry-over) — the milestone lens's one batched read:
720
- * rollups/edge-summaries computed once across every milestone's
721
- * combined subtree, plus the real `blocks` edges between milestones for
722
- * the lens's sequencing arrows. Replaces N `tasks.tree()` calls.
723
- */
724
- lens: (project_id, depth) => wrap(
725
- () => this.clients.milestones.get(`/projects/${project_id}/milestones/lens`, {
726
- query: depth ? { depth: String(depth) } : {}
727
- })
728
- ),
729
- /**
730
- * Get milestone by ID
731
- */
732
- find: (id) => wrap(async () => {
733
- try {
734
- return await this.clients.milestones.get(`/milestones/${id}`);
735
- } catch {
736
- return null;
737
- }
738
- }),
739
- /**
740
- * Create new milestone
741
- */
742
- create: (data) => wrap(() => this.clients.milestones.post("/milestones", { body: data })),
743
- /**
744
- * Update milestone
745
- */
746
- update: async (id, data) => wrap(async () => {
747
- const result = await this.milestones.find(id);
748
- if (!result.ok) throw new Error(result.error.message);
749
- if (!result.value) throw new Error(`Milestone with id ${id} not found`);
750
- const milestone = result.value;
751
- const updateData = {
752
- id: milestone.id,
753
- project_id: milestone.project_id,
754
- name: data.name ?? milestone.name,
755
- description: data.description ?? milestone.description,
756
- target_time: data.target_time ?? milestone.target_time,
757
- target_version: data.target_version ?? milestone.target_version,
758
- finished_at: data.finished_at !== void 0 ? data.finished_at : milestone.finished_at
759
- };
760
- return this.clients.milestones.patch(`/milestones/${id}`, {
761
- body: updateData
693
+ initiate: async (project_id) => {
694
+ const response = await fetch(`${this.clients.projects.url()}/projects/scan?project_id=${project_id}`, {
695
+ method: "POST",
696
+ headers: this.clients.projects.headers()
762
697
  });
763
- }),
698
+ if (!response.body) {
699
+ throw new Error("No response body");
700
+ }
701
+ const stream = response.body.pipeThrough(new TextDecoderStream());
702
+ return stream;
703
+ },
764
704
  /**
765
- * Delete milestone (soft delete)
705
+ * Get pending scan updates for a project
766
706
  */
767
- delete: (id) => wrap(() => this.clients.milestones.delete(`/milestones/${id}`)),
707
+ updates: (project_id) => wrap(
708
+ () => this.clients.projects.get("/projects/updates", { query: { project_id } }).then((response) => response.updates)
709
+ ),
768
710
  /**
769
- * Get goals for a milestone
711
+ * Process scan results
770
712
  */
771
- goals: (id) => wrap(() => this.clients.milestones.get(`/milestones/${id}/goals`))
772
- };
773
- /**
774
- * Hooks namespace (task A3.2) — automation registry + delivery ledger.
775
- * Webhook secrets are write-only: `secret_encrypted` never round-trips.
776
- */
777
- this.hooks = {
778
- list: (project_id) => wrap(() => this.clients.hooks.get("/hooks", { query: { project_id } })),
779
- upsert: (data) => wrap(
780
- () => data.id ? this.clients.hooks.patch(`/hooks/${data.id}`, { body: data }) : this.clients.hooks.post("/hooks", { body: data })
781
- ),
782
- delete: (id) => wrap(() => this.clients.hooks.delete(`/hooks/${id}`)),
783
- /** v2.4 (B3.4) — settings panel enable/disable toggle; never touches trigger/action (see registry.ts's `set_hook_enabled`). */
784
- setEnabled: (id, enabled) => wrap(() => this.clients.hooks.patch(`/hooks/${id}/enabled`, { body: { enabled } })),
785
- deliveries: (id, status) => wrap(
786
- () => this.clients.hooks.get(`/hooks/${id}/deliveries`, status ? { query: { status } } : {})
713
+ update: (project_id, data) => wrap(
714
+ () => this.clients.projects.post("/projects/scan_status", {
715
+ query: { project_id },
716
+ body: data
717
+ })
787
718
  )
788
- };
719
+ },
789
720
  /**
790
- * Goals namespace with Result-wrapped operations
721
+ * Get project history
791
722
  */
792
- this.goals = {
793
- /**
794
- * List goals for authenticated user
795
- */
796
- list: () => wrap(() => this.clients.goals.get("/goals")),
797
- /**
798
- * Get goal by ID
799
- */
800
- find: (id) => wrap(() => this.clients.goals.get(`/goals/${id}`)),
801
- /**
802
- * Create new goal
803
- */
804
- create: (data) => wrap(() => this.clients.goals.post("/goals", { body: data })),
805
- /**
806
- * Update goal
807
- */
808
- update: async (id, data) => wrap(async () => {
809
- const result = await this.goals.find(id);
810
- if (!result.ok) throw new Error(result.error.message);
811
- if (!result.value) throw new Error(`Goal with id ${id} not found`);
812
- const goal = result.value;
813
- const updateData = {
814
- id: goal.id,
815
- milestone_id: goal.milestone_id,
816
- name: data.name ?? goal.name,
817
- description: data.description ?? goal.description,
818
- target_time: data.target_time ?? goal.target_time,
819
- finished_at: data.finished_at !== void 0 ? data.finished_at : goal.finished_at
820
- };
821
- return this.clients.goals.patch(`/goals/${id}`, {
822
- body: updateData
823
- });
824
- }),
825
- /**
826
- * Delete goal (soft delete)
827
- */
828
- delete: (id) => wrap(() => this.clients.goals.delete(`/goals/${id}`))
829
- };
723
+ history: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/history`)),
830
724
  /**
831
- * Tasks namespace with Result-wrapped operations
725
+ * Legacy methods (keeping for compatibility)
832
726
  */
833
- this.tasks = {
834
- /**
835
- * List tasks with optional filtering
836
- */
837
- list: (filters) => wrap(() => {
838
- const query = {};
839
- if (filters?.project_id) query.project = filters.project_id;
840
- if (filters?.tag_id) query.tag = filters.tag_id;
841
- return this.clients.tasks.get("/tasks", Object.keys(query).length > 0 ? { query } : {});
842
- }),
843
- /**
844
- * Get task by ID
845
- */
846
- find: (id) => wrap(() => this.clients.tasks.get("/tasks", { query: { id } })),
847
- /**
848
- * Get tasks by project ID
849
- */
850
- getByProject: (project_id) => wrap(
851
- () => this.clients.tasks.get(`/tasks`, {
852
- query: { project: project_id }
853
- })
854
- ),
855
- /**
856
- * Create a new task
857
- */
858
- create: (data) => wrap(() => this.clients.tasks.patch("/tasks", { body: data })),
859
- /**
860
- * Update an existing task
861
- */
862
- update: async (id, changes) => wrap(async () => {
863
- const result = await this.tasks.find(id);
864
- if (!result.ok) throw new Error(result.error.message);
865
- if (!result.value) throw new Error(`Task with id ${id} not found`);
866
- const task = result.value;
867
- const updateData = {
868
- id,
869
- title: task.task.title,
870
- summary: task.task.summary,
871
- description: task.task.description,
872
- progress: task.task.progress,
873
- visibility: task.task.visibility,
874
- start_time: task.task.start_time,
875
- end_time: task.task.end_time,
876
- priority: task.task.priority,
877
- owner_id: task.task.owner_id,
878
- project_id: task.task.project_id,
879
- ...changes
880
- };
881
- return this.clients.tasks.patch("/tasks", {
882
- body: updateData
883
- });
884
- }),
885
- /**
886
- * Upsert task (create or update)
887
- */
888
- upsert: (data) => wrap(() => this.clients.tasks.patch("/tasks", { body: data })),
889
- /**
890
- * Save tags for tasks
891
- */
892
- saveTags: (data) => wrap(() => this.clients.tasks.patch("/tasks/save_tags", { body: data })),
893
- /**
894
- * Delete task (soft delete)
895
- */
896
- deleteTask: (task) => wrap(
897
- () => this.clients.tasks.patch("/tasks", {
898
- body: { ...task.task, deleted: true }
899
- })
900
- ),
901
- /**
902
- * Task history operations
903
- */
904
- history: {
905
- /**
906
- * Get task history by task ID
907
- */
908
- get: (task_id) => wrap(() => this.clients.tasks.get(`/tasks/history/${task_id}`))
909
- },
910
- /**
911
- * Ready-to-work tasks: not completed, not blocked by an incomplete
912
- * `blocks` edge, no incomplete children, start_time null-or-passed.
913
- */
914
- ready: (filters) => wrap(() => {
915
- const query = {};
916
- if (filters?.project_id) query.project = filters.project_id;
917
- if (filters?.limit) query.limit = String(filters.limit);
918
- if (filters?.cursor) query.cursor = filters.cursor;
919
- return this.clients.tasks.get("/tasks/ready", Object.keys(query).length > 0 ? { query } : {});
920
- }),
921
- /** Bounded descendant subtree of a task. */
922
- tree: (id, depth) => wrap(
923
- () => this.clients.tasks.get(`/tasks/${id}/tree`, depth ? { query: { depth: String(depth) } } : {})
924
- ),
925
- /** Link neighborhood around a task (default depth 2, capped server-side at 3 — the graph lens' 1/2/3 toggle), including backlinks. */
926
- near: (id, depth) => wrap(
927
- () => this.clients.tasks.get(`/tasks/${id}/near`, depth ? { query: { depth: String(depth) } } : {})
928
- ),
929
- /** Immediate-parent-first ancestor chain — feeds the outline's zoom breadcrumbs. */
930
- ancestors: (id) => wrap(() => this.clients.tasks.get(`/tasks/${id}/ancestors`)),
931
- /** Atomic claim: sets claimed_by/claimed_at + IN_PROGRESS, guarded on claimed_by IS NULL and base_rev. */
932
- claim: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/claim`, { body: data })),
933
- /**
934
- * Completes a task through the single completion entrypoint
935
- * (CompletionEngine) — the response's `bubbled` chain is the ordered
936
- * list of ancestors an auto_children cascade also completed, exactly
937
- * what a ripple animation would replay. `hooks_fired` is a placeholder
938
- * until phase A3.
939
- */
940
- done: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/done`, { body: data })),
941
- /**
942
- * Policy-only reopen (v2.4 B2) — the server (`SqlCompletionEngine.reopen`)
943
- * is the sole enforcement point: a task whose `completed_via` isn't
944
- * `'policy'` 409s. No request body — the actor comes from the caller's
945
- * own auth channel.
946
- */
947
- reopen: (id) => wrap(() => this.clients.tasks.post(`/tasks/${id}/reopen`)),
948
- /**
949
- * SDLC stage transition (v2.4, task A4.5) — gently enforced: a gated
950
- * hop missing its checkpoint 409s naming what's missing; `override:
951
- * true` always succeeds but audits.
952
- */
953
- advanceStage: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/stage`, { body: data })),
954
- /** Create a typed edge between two tasks (or a task and an external ref). */
955
- link: (data) => wrap(() => this.clients.tasks.post("/tasks/link", { body: data })),
956
- /** Remove a typed edge by its own id. */
957
- unlink: (link_id) => wrap(() => this.clients.tasks.delete(`/tasks/link/${link_id}`)),
958
- /**
959
- * Batch apply — create/update/reparent/link/unlink/claim/complete in one
960
- * atomic call, with `$0`/`$1`… temp handles for subtree creation.
961
- * Replaying the same `idempotency_key` returns the stored response
962
- * verbatim rather than re-executing.
963
- */
964
- apply: (data) => wrap(() => this.clients.tasks.post("/tasks/apply", { body: data }))
965
- };
727
+ upsert: (data) => wrap(() => this.clients.projects.patch("/projects", { body: data })),
966
728
  /**
967
- * Tags namespace with Result-wrapped operations
729
+ * Fetch project specification from GitHub
968
730
  */
969
- this.tags = {
970
- /**
971
- * List tags for authenticated user
972
- */
973
- list: () => wrap(() => this.clients.tags.get("/tags"))
974
- };
731
+ specification: (project_id) => wrap(
732
+ () => this.clients.projects.get("/projects/fetch_spec", {
733
+ query: { project_id }
734
+ })
735
+ ),
975
736
  /**
976
- * Docs namespace (v2.4, task A4.1) — corpus-backed doc store. `push`
977
- * creates a new document (omit `document_id`) or a new version on an
978
- * existing one; content is sanitized server-side before it ever reaches
979
- * corpus.
737
+ * Delete project (soft delete)
980
738
  */
981
- this.docs = {
982
- list: (filters) => wrap(() => {
983
- const query = { project_id: filters.project_id };
984
- if (filters.task_id) query.task_id = filters.task_id;
985
- return this.clients.docs.get("/docs", { query });
986
- }),
987
- push: (data) => wrap(() => this.clients.docs.post("/docs", { body: data })),
988
- /** Pulls a document's content at `version` (default: head). `content` is null for a document that's never been pushed to. */
989
- pull: (id, version) => wrap(() => this.clients.docs.get(`/docs/${id}`, version ? { query: { version } } : {})),
990
- /** Full version history, newest first — the lineage walk. */
991
- versions: (id) => wrap(() => this.clients.docs.get(`/docs/${id}/versions`)),
992
- /**
993
- * v2.4 (B3.1) — the DocViewer's sandboxed-iframe `src`: a standalone
994
- * HTML document with its own CSP (defense in depth over
995
- * sanitize-on-push), never a JSON payload injected into the main app's
996
- * DOM. Not a `fetch` call — the browser navigates the iframe here
997
- * directly, carrying the same session cookie as any same-origin nav.
998
- */
999
- renderUrl: (id, version) => {
1000
- const query = version ? `?version=${encodeURIComponent(version)}` : "";
1001
- return `${this.clients.docs.url()}/docs/${id}/render${query}`;
1002
- },
1003
- /**
1004
- * Annotation engine (task A4.2) — markers-in-doc threads. Every
1005
- * mutation pushes a new corpus version; the doc itself is the thread
1006
- * history (locked decision 3).
1007
- */
1008
- createThread: (document_id, data) => wrap(() => this.clients.docs.post(`/docs/${document_id}/threads`, { body: data })),
1009
- replyThread: (document_id, thread_id, body) => wrap(
1010
- () => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/reply`, { body: { body } })
1011
- ),
1012
- resolveThread: (document_id, thread_id) => wrap(() => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/resolve`, {})),
1013
- toggleBlocking: (document_id, thread_id, blocking) => wrap(
1014
- () => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/blocking`, { body: { blocking } })
1015
- ),
1016
- /** Pending annotation threads (anything not `resolved`) — scope to one document, or every document in a project. */
1017
- unresolved: (filters) => wrap(() => {
1018
- const query = {};
1019
- if (filters.project_id) query.project_id = filters.project_id;
1020
- if (filters.document_id) query.document_id = filters.document_id;
1021
- return this.clients.docs.get("/docs/annotations/unresolved", { query });
1022
- }),
1023
- /**
1024
- * Interface report v1 (task A4.4). `push` submits already-normalized
1025
- * declaration text; the server independently recomputes the
1026
- * additive-vs-breaking classification against its own stored previous
1027
- * content and auto-approves additive diffs against an approved base.
1028
- */
1029
- pushInterfaceReport: (data) => wrap(() => this.clients.docs.post("/docs/interface", { body: data })),
1030
- interfaceStatus: (filters) => wrap(() => {
1031
- const query = { project_id: filters.project_id, title: filters.title };
1032
- if (filters.task_id) query.task_id = filters.task_id;
1033
- return this.clients.docs.get(
1034
- "/docs/interface/status",
1035
- { query }
1036
- );
739
+ deleteProject: (project) => wrap(
740
+ () => this.clients.projects.patch("/projects", {
741
+ body: { ...project, deleted: true }
1037
742
  })
1038
- };
743
+ ),
1039
744
  /**
1040
- * Signoffs namespace (v2.4, task A4.3) — the generalized human-approval
1041
- * ledger. `decide` is human-only; an api-channel key gets 403.
745
+ * Whole-project graph read (v2.5, canvas home task P2.2) — every task
746
+ * in the project (fold kinds included), every in-project task_link,
747
+ * and batched rollups. Backs the canvas' spatial view of the project.
1042
748
  */
1043
- this.signoffs = {
1044
- request: (data) => wrap(() => this.clients.signoffs.post("/signoffs", { body: data })),
1045
- find: (id) => wrap(() => this.clients.signoffs.get(`/signoffs/${id}`)),
1046
- /** v2.4 (B3) — the pending (undecided) signoff for a subject+checkpoint, or `null` if none has been requested yet. */
1047
- findPending: (filters) => wrap(() => this.clients.signoffs.get("/signoffs", { query: filters })),
1048
- decide: (id, data) => wrap(() => this.clients.signoffs.post(`/signoffs/${id}/decide`, { body: data }))
1049
- };
749
+ graph: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/graph`)),
1050
750
  /**
1051
- * Reviews namespace (v2.4, task A4.6) — the human's queue: one typed
1052
- * aggregate across pending signoffs, open blocking annotation threads,
1053
- * pending pipeline manual gates, and pending scanner diffs.
751
+ * Canvas view-state (v2.5, task P3.1) — pinned node positions.
752
+ * Last-write-wins; `putViewState` always sends the full layout.
1054
753
  */
1055
- this.reviews = {
1056
- pending: () => wrap(() => this.clients.reviews.get("/reviews/pending"))
1057
- };
754
+ getViewState: (project_id) => wrap(() => this.clients.projects.get(`/projects/${project_id}/view-state`)),
755
+ putViewState: (project_id, layout) => wrap(
756
+ () => this.clients.projects.put(`/projects/${project_id}/view-state`, { body: layout })
757
+ )
758
+ };
759
+ /**
760
+ * Milestones namespace with Result-wrapped operations
761
+ */
762
+ milestones = {
1058
763
  /**
1059
- * GitHub namespace with Result-wrapped operations
764
+ * List milestones for authenticated user
1060
765
  */
1061
- this.github = {
1062
- /**
1063
- * List repositories for authenticated user
1064
- */
1065
- repos: () => wrap(() => this.clients.github.get("/repos")),
1066
- /**
1067
- * List branches for a GitHub repository
1068
- */
1069
- branches: (owner, repo) => wrap(() => this.clients.github.get(`/repos/${owner}/${repo}/branches`))
1070
- };
1071
- this.blog = {
1072
- posts: {
1073
- list: (params) => wrap(() => {
1074
- const query = {};
1075
- if (params?.category) query.category = params.category;
1076
- if (params?.tag) query.tag = params.tag;
1077
- if (params?.project) query.project = params.project;
1078
- if (params?.status) query.status = params.status;
1079
- if (params?.archived !== void 0) query.archived = String(params.archived);
1080
- if (params?.limit) query.limit = String(params.limit);
1081
- if (params?.offset !== void 0) query.offset = String(params.offset);
1082
- if (params?.sort) query.sort = params.sort;
1083
- return this.clients.blog.get("/blog/posts", Object.keys(query).length ? { query } : {});
1084
- }),
1085
- getBySlug: (slug) => wrap(() => this.clients.blog.get(`/blog/posts/${slug}`)),
1086
- create: (data) => wrap(() => this.clients.blog.post("/blog/posts", { body: data })),
1087
- update: (uuid, data) => wrap(() => this.clients.blog.put(`/blog/posts/${uuid}`, { body: data })),
1088
- delete: (uuid) => wrap(() => this.clients.blog.delete(`/blog/posts/${uuid}`)),
1089
- versions: (uuid) => wrap(() => this.clients.blog.get(`/blog/posts/${uuid}/versions`)),
1090
- version: (uuid, hash) => wrap(() => this.clients.blog.get(`/blog/posts/${uuid}/version/${hash}`)),
1091
- restore: (uuid, hash) => wrap(() => this.clients.blog.post(`/blog/posts/${uuid}/restore/${hash}`))
1092
- },
1093
- tags: {
1094
- list: () => wrap(() => this.clients.blog.get("/blog/tags")),
1095
- getForPost: (uuid) => wrap(() => this.clients.blog.get(`/blog/tags/posts/${uuid}/tags`)),
1096
- setForPost: (uuid, tags) => wrap(() => this.clients.blog.put(`/blog/tags/posts/${uuid}/tags`, { body: { tags } })),
1097
- addToPost: (uuid, tags) => wrap(() => this.clients.blog.post(`/blog/tags/posts/${uuid}/tags`, { body: { tags } })),
1098
- removeFromPost: (uuid, tag) => wrap(() => this.clients.blog.delete(`/blog/tags/posts/${uuid}/tags/${tag}`))
1099
- },
1100
- categories: {
1101
- tree: () => wrap(() => this.clients.blog.get("/blog/categories")),
1102
- create: (data) => wrap(() => this.clients.blog.post("/blog/categories", { body: data })),
1103
- update: (name, data) => wrap(
1104
- () => this.clients.blog.put(`/blog/categories/${name}`, {
1105
- body: data
1106
- })
1107
- ),
1108
- delete: (name) => wrap(() => this.clients.blog.delete(`/blog/categories/${name}`))
1109
- },
1110
- tokens: {
1111
- list: () => wrap(() => this.clients.blog.get("/blog/tokens")),
1112
- create: (data) => wrap(() => this.clients.blog.post("/blog/tokens", { body: data })),
1113
- update: (id, data) => wrap(
1114
- () => this.clients.blog.put(`/blog/tokens/${id}`, {
1115
- body: data
1116
- })
1117
- ),
1118
- delete: (id) => wrap(() => this.clients.blog.delete(`/blog/tokens/${id}`))
1119
- }
1120
- };
1121
- this.media = {
1122
- profiles: {
1123
- list: () => wrap(async () => {
1124
- const res = await this.clients.media.get("/profiles");
1125
- return res.profiles;
1126
- }),
1127
- create: (data) => wrap(() => this.clients.media.post("/profiles", { body: data })),
1128
- get: (id) => wrap(() => this.clients.media.get(`/profiles/${id}`)),
1129
- update: (id, data) => wrap(() => this.clients.media.patch(`/profiles/${id}`, { body: data })),
1130
- delete: (id) => wrap(() => this.clients.media.delete(`/profiles/${id}`)),
1131
- filters: {
1132
- list: (profile_id) => wrap(async () => {
1133
- const res = await this.clients.media.get(`/profiles/${profile_id}/filters`);
1134
- return res.filters;
1135
- }),
1136
- add: (profile_id, data) => wrap(() => this.clients.media.post(`/profiles/${profile_id}/filters`, { body: data })),
1137
- remove: (profile_id, filter_id) => wrap(() => this.clients.media.delete(`/profiles/${profile_id}/filters/${filter_id}`))
1138
- },
1139
- timeline: (slug, params) => wrap(() => {
1140
- const query = {};
1141
- if (params?.limit) query.limit = String(params.limit);
1142
- if (params?.before) query.before = params.before;
1143
- return this.clients.media.get(
1144
- `/profiles/${slug}/timeline`,
1145
- Object.keys(query).length ? { query } : {}
1146
- );
1147
- })
1148
- },
1149
- connections: {
1150
- list: (profile_id, options) => wrap(async () => {
1151
- const query = { profile_id };
1152
- if (options?.include_settings) query.include_settings = "true";
1153
- const res = await this.clients.media.get("/connections", { query });
1154
- return res.accounts;
1155
- }),
1156
- create: (data) => wrap(() => this.clients.media.post("/connections", { body: data })),
1157
- delete: (account_id) => wrap(() => this.clients.media.delete(`/connections/${account_id}`)),
1158
- refresh: (account_id) => wrap(() => this.clients.media.post(`/connections/${account_id}/refresh`)),
1159
- refreshAll: () => wrap(() => this.clients.media.post("/connections/refresh-all")),
1160
- updateStatus: (account_id, is_active) => wrap(
1161
- () => this.clients.media.patch(`/connections/${account_id}`, {
1162
- body: { is_active }
1163
- })
1164
- ),
1165
- settings: {
1166
- get: (account_id) => wrap(() => this.clients.media.get(`/connections/${account_id}/settings`)),
1167
- update: (account_id, settings) => wrap(
1168
- () => this.clients.media.put(`/connections/${account_id}/settings`, {
1169
- body: { settings }
1170
- })
1171
- )
1172
- },
1173
- repos: (account_id) => wrap(async () => {
1174
- const res = await this.clients.media.get(`/connections/${account_id}/repos`);
1175
- return res.repos;
1176
- }),
1177
- subreddits: (account_id) => wrap(async () => {
1178
- const res = await this.clients.media.get(`/connections/${account_id}/subreddits`);
1179
- return res.subreddits;
1180
- })
1181
- },
1182
- credentials: {
1183
- check: (platform, profile_id) => wrap(
1184
- () => this.clients.media.get(`/credentials/${platform}`, { query: { profile_id } })
1185
- ),
1186
- save: (platform, data) => wrap(
1187
- () => this.clients.media.post(`/credentials/${platform}`, { body: data })
1188
- ),
1189
- delete: (platform, profile_id) => wrap(
1190
- () => this.clients.media.delete(`/credentials/${platform}`, { query: { profile_id } })
1191
- )
1192
- },
1193
- timeline: {
1194
- get: (user_id, params) => wrap(() => {
1195
- const query = {};
1196
- if (params?.from) query.from = params.from;
1197
- if (params?.to) query.to = params.to;
1198
- return this.clients.media.get(`/timeline/${user_id}`, Object.keys(query).length ? { query } : {});
1199
- }),
1200
- getRaw: (user_id, platform, account_id) => wrap(
1201
- () => this.clients.media.get(`/timeline/${user_id}/raw/${platform}`, {
1202
- query: { account_id }
1203
- })
1204
- )
1205
- }
1206
- };
766
+ list: () => wrap(() => this.clients.milestones.get("/milestones")),
1207
767
  /**
1208
- * User namespace with Result-wrapped operations
768
+ * Get milestones by project ID
1209
769
  */
1210
- this.activity = {
1211
- ai: (options) => wrap(() => {
1212
- const query = {};
1213
- if (options?.limit) query.limit = String(options.limit);
1214
- if (options?.since) query.since = options.since;
1215
- return this.clients.projects.get(
1216
- "/activity/ai",
1217
- Object.keys(query).length ? { query } : {}
1218
- );
770
+ getByProject: (project_id) => wrap(() => this.clients.milestones.get(`/projects/${project_id}/milestones`)),
771
+ /**
772
+ * v2.4 (B2 critic carry-over) — the milestone lens's one batched read:
773
+ * rollups/edge-summaries computed once across every milestone's
774
+ * combined subtree, plus the real `blocks` edges between milestones for
775
+ * the lens's sequencing arrows. Replaces N `tasks.tree()` calls.
776
+ */
777
+ lens: (project_id, depth) => wrap(
778
+ () => this.clients.milestones.get(`/projects/${project_id}/milestones/lens`, {
779
+ query: depth ? { depth: String(depth) } : {}
1219
780
  })
1220
- };
1221
- /** v2.4 (task A5.3) — the fold's dual-read verification verb. */
1222
- this.admin = {
1223
- verifyFold: () => wrap(() => this.clients.admin.get("/admin/verify-fold")),
1224
- /** v2.4 (B3, CSS-exfil fix) — re-scrubs `<style>` blocks in every already-stored doc the caller owns. */
1225
- reconcileDocsCss: () => wrap(() => this.clients.admin.post("/admin/reconcile-docs-css"))
1226
- };
1227
- this.user = {
1228
- /**
1229
- * Get the authenticated user's identity (id, name, github_id, task_view).
1230
- * Single source of truth for resolving `owner_id` on task/milestone/goal
1231
- * upserts — the API rejects any owner_id that doesn't match the caller.
1232
- */
1233
- me: () => wrap(
1234
- () => this.clients.auth.get(
1235
- "/user/me"
1236
- )
1237
- ),
1238
- /**
1239
- * Get user activity history
1240
- */
1241
- history: () => wrap(() => this.clients.auth.get("/user/history")),
781
+ ),
782
+ /**
783
+ * Get milestone by ID
784
+ */
785
+ find: (id) => wrap(async () => {
786
+ try {
787
+ return await this.clients.milestones.get(`/milestones/${id}`);
788
+ } catch {
789
+ return null;
790
+ }
791
+ }),
792
+ /**
793
+ * Create new milestone
794
+ */
795
+ create: (data) => wrap(() => this.clients.milestones.post("/milestones", { body: data })),
796
+ /**
797
+ * Update milestone
798
+ */
799
+ update: async (id, data) => wrap(async () => {
800
+ const result = await this.milestones.find(id);
801
+ if (!result.ok) throw new Error(result.error.message);
802
+ if (!result.value) throw new Error(`Milestone with id ${id} not found`);
803
+ const milestone = result.value;
804
+ const updateData = {
805
+ id: milestone.id,
806
+ project_id: milestone.project_id,
807
+ name: data.name ?? milestone.name,
808
+ description: data.description ?? milestone.description,
809
+ target_time: data.target_time ?? milestone.target_time,
810
+ target_version: data.target_version ?? milestone.target_version,
811
+ finished_at: data.finished_at !== void 0 ? data.finished_at : milestone.finished_at
812
+ };
813
+ return this.clients.milestones.patch(`/milestones/${id}`, {
814
+ body: updateData
815
+ });
816
+ }),
817
+ /**
818
+ * Delete milestone (soft delete)
819
+ */
820
+ delete: (id) => wrap(() => this.clients.milestones.delete(`/milestones/${id}`)),
821
+ /**
822
+ * Get goals for a milestone
823
+ */
824
+ goals: (id) => wrap(() => this.clients.milestones.get(`/milestones/${id}/goals`))
825
+ };
826
+ /**
827
+ * Hooks namespace (task A3.2) — automation registry + delivery ledger.
828
+ * Webhook secrets are write-only: `secret_encrypted` never round-trips.
829
+ */
830
+ hooks = {
831
+ list: (project_id) => wrap(() => this.clients.hooks.get("/hooks", { query: { project_id } })),
832
+ upsert: (data) => wrap(
833
+ () => data.id ? this.clients.hooks.patch(`/hooks/${data.id}`, { body: data }) : this.clients.hooks.post("/hooks", { body: data })
834
+ ),
835
+ delete: (id) => wrap(() => this.clients.hooks.delete(`/hooks/${id}`)),
836
+ /** v2.4 (B3.4) — settings panel enable/disable toggle; never touches trigger/action (see registry.ts's `set_hook_enabled`). */
837
+ setEnabled: (id, enabled) => wrap(() => this.clients.hooks.patch(`/hooks/${id}/enabled`, { body: { enabled } })),
838
+ deliveries: (id, status) => wrap(
839
+ () => this.clients.hooks.get(`/hooks/${id}/deliveries`, status ? { query: { status } } : {})
840
+ )
841
+ };
842
+ /**
843
+ * Goals namespace with Result-wrapped operations
844
+ */
845
+ goals = {
846
+ /**
847
+ * List goals for authenticated user
848
+ */
849
+ list: () => wrap(() => this.clients.goals.get("/goals")),
850
+ /**
851
+ * Get goal by ID
852
+ */
853
+ find: (id) => wrap(() => this.clients.goals.get(`/goals/${id}`)),
854
+ /**
855
+ * Create new goal
856
+ */
857
+ create: (data) => wrap(() => this.clients.goals.post("/goals", { body: data })),
858
+ /**
859
+ * Update goal
860
+ */
861
+ update: async (id, data) => wrap(async () => {
862
+ const result = await this.goals.find(id);
863
+ if (!result.ok) throw new Error(result.error.message);
864
+ if (!result.value) throw new Error(`Goal with id ${id} not found`);
865
+ const goal = result.value;
866
+ const updateData = {
867
+ id: goal.id,
868
+ milestone_id: goal.milestone_id,
869
+ name: data.name ?? goal.name,
870
+ description: data.description ?? goal.description,
871
+ target_time: data.target_time ?? goal.target_time,
872
+ finished_at: data.finished_at !== void 0 ? data.finished_at : goal.finished_at
873
+ };
874
+ return this.clients.goals.patch(`/goals/${id}`, {
875
+ body: updateData
876
+ });
877
+ }),
878
+ /**
879
+ * Delete goal (soft delete)
880
+ */
881
+ delete: (id) => wrap(() => this.clients.goals.delete(`/goals/${id}`))
882
+ };
883
+ /**
884
+ * Tasks namespace with Result-wrapped operations
885
+ */
886
+ tasks = {
887
+ /**
888
+ * List tasks with optional filtering
889
+ */
890
+ list: (filters) => wrap(() => {
891
+ const query = {};
892
+ if (filters?.project_id) query.project = filters.project_id;
893
+ if (filters?.tag_id) query.tag = filters.tag_id;
894
+ return this.clients.tasks.get("/tasks", Object.keys(query).length > 0 ? { query } : {});
895
+ }),
896
+ /**
897
+ * Get task by ID
898
+ */
899
+ find: (id) => wrap(() => this.clients.tasks.get("/tasks", { query: { id } })),
900
+ /**
901
+ * Get tasks by project ID
902
+ */
903
+ getByProject: (project_id) => wrap(
904
+ () => this.clients.tasks.get(`/tasks`, {
905
+ query: { project: project_id }
906
+ })
907
+ ),
908
+ /**
909
+ * Create a new task
910
+ */
911
+ create: (data) => wrap(() => this.clients.tasks.patch("/tasks", { body: data })),
912
+ /**
913
+ * Update an existing task
914
+ */
915
+ update: async (id, changes) => wrap(async () => {
916
+ const result = await this.tasks.find(id);
917
+ if (!result.ok) throw new Error(result.error.message);
918
+ if (!result.value) throw new Error(`Task with id ${id} not found`);
919
+ const task = result.value;
920
+ const updateData = {
921
+ id,
922
+ title: task.task.title,
923
+ summary: task.task.summary,
924
+ description: task.task.description,
925
+ progress: task.task.progress,
926
+ visibility: task.task.visibility,
927
+ start_time: task.task.start_time,
928
+ end_time: task.task.end_time,
929
+ priority: task.task.priority,
930
+ owner_id: task.task.owner_id,
931
+ project_id: task.task.project_id,
932
+ ...changes
933
+ };
934
+ return this.clients.tasks.patch("/tasks", {
935
+ body: updateData
936
+ });
937
+ }),
938
+ /**
939
+ * Upsert task (create or update)
940
+ */
941
+ upsert: (data) => wrap(() => this.clients.tasks.patch("/tasks", { body: data })),
942
+ /**
943
+ * Save tags for tasks
944
+ */
945
+ saveTags: (data) => wrap(() => this.clients.tasks.patch("/tasks/save_tags", { body: data })),
946
+ /**
947
+ * Delete task (soft delete)
948
+ */
949
+ deleteTask: (task) => wrap(
950
+ () => this.clients.tasks.patch("/tasks", {
951
+ body: { ...task.task, deleted: true }
952
+ })
953
+ ),
954
+ /**
955
+ * Task history operations
956
+ */
957
+ history: {
1242
958
  /**
1243
- * Update user preferences
959
+ * Get task history by task ID
1244
960
  */
1245
- preferences: (data) => wrap(
1246
- () => this.clients.auth.patch("/user/preferences", {
961
+ get: (task_id) => wrap(() => this.clients.tasks.get(`/tasks/history/${task_id}`))
962
+ },
963
+ /**
964
+ * Ready-to-work tasks: not completed, not blocked by an incomplete
965
+ * `blocks` edge, no incomplete children, start_time null-or-passed.
966
+ */
967
+ ready: (filters) => wrap(() => {
968
+ const query = {};
969
+ if (filters?.project_id) query.project = filters.project_id;
970
+ if (filters?.limit) query.limit = String(filters.limit);
971
+ if (filters?.cursor) query.cursor = filters.cursor;
972
+ return this.clients.tasks.get("/tasks/ready", Object.keys(query).length > 0 ? { query } : {});
973
+ }),
974
+ /** Bounded descendant subtree of a task. */
975
+ tree: (id, depth) => wrap(
976
+ () => this.clients.tasks.get(`/tasks/${id}/tree`, depth ? { query: { depth: String(depth) } } : {})
977
+ ),
978
+ /** Link neighborhood around a task (default depth 2, capped server-side at 3 — the graph lens' 1/2/3 toggle), including backlinks. */
979
+ near: (id, depth) => wrap(
980
+ () => this.clients.tasks.get(`/tasks/${id}/near`, depth ? { query: { depth: String(depth) } } : {})
981
+ ),
982
+ /** Immediate-parent-first ancestor chain — feeds the outline's zoom breadcrumbs. */
983
+ ancestors: (id) => wrap(() => this.clients.tasks.get(`/tasks/${id}/ancestors`)),
984
+ /** Atomic claim: sets claimed_by/claimed_at + IN_PROGRESS, guarded on claimed_by IS NULL and base_rev. */
985
+ claim: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/claim`, { body: data })),
986
+ /**
987
+ * Completes a task through the single completion entrypoint
988
+ * (CompletionEngine) — the response's `bubbled` chain is the ordered
989
+ * list of ancestors an auto_children cascade also completed, exactly
990
+ * what a ripple animation would replay. `hooks_fired` is a placeholder
991
+ * until phase A3.
992
+ */
993
+ done: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/done`, { body: data })),
994
+ /**
995
+ * Policy-only reopen (v2.4 B2) — the server (`SqlCompletionEngine.reopen`)
996
+ * is the sole enforcement point: a task whose `completed_via` isn't
997
+ * `'policy'` 409s. No request body — the actor comes from the caller's
998
+ * own auth channel.
999
+ */
1000
+ reopen: (id) => wrap(() => this.clients.tasks.post(`/tasks/${id}/reopen`)),
1001
+ /**
1002
+ * SDLC stage transition (v2.4, task A4.5) — gently enforced: a gated
1003
+ * hop missing its checkpoint 409s naming what's missing; `override:
1004
+ * true` always succeeds but audits.
1005
+ */
1006
+ advanceStage: (id, data) => wrap(() => this.clients.tasks.post(`/tasks/${id}/stage`, { body: data })),
1007
+ /** Create a typed edge between two tasks (or a task and an external ref). */
1008
+ link: (data) => wrap(() => this.clients.tasks.post("/tasks/link", { body: data })),
1009
+ /** Remove a typed edge by its own id. */
1010
+ unlink: (link_id) => wrap(() => this.clients.tasks.delete(`/tasks/link/${link_id}`)),
1011
+ /**
1012
+ * Batch apply — create/update/reparent/link/unlink/claim/complete in one
1013
+ * atomic call, with `$0`/`$1`… temp handles for subtree creation.
1014
+ * Replaying the same `idempotency_key` returns the stored response
1015
+ * verbatim rather than re-executing.
1016
+ */
1017
+ apply: (data) => wrap(() => this.clients.tasks.post("/tasks/apply", { body: data }))
1018
+ };
1019
+ /**
1020
+ * Tags namespace with Result-wrapped operations
1021
+ */
1022
+ tags = {
1023
+ /**
1024
+ * List tags for authenticated user
1025
+ */
1026
+ list: () => wrap(() => this.clients.tags.get("/tags"))
1027
+ };
1028
+ /**
1029
+ * Docs namespace (v2.4, task A4.1) — corpus-backed doc store. `push`
1030
+ * creates a new document (omit `document_id`) or a new version on an
1031
+ * existing one; content is sanitized server-side before it ever reaches
1032
+ * corpus.
1033
+ */
1034
+ docs = {
1035
+ list: (filters) => wrap(() => {
1036
+ const query = { project_id: filters.project_id };
1037
+ if (filters.task_id) query.task_id = filters.task_id;
1038
+ return this.clients.docs.get("/docs", { query });
1039
+ }),
1040
+ push: (data) => wrap(() => this.clients.docs.post("/docs", { body: data })),
1041
+ /** Pulls a document's content at `version` (default: head). `content` is null for a document that's never been pushed to. */
1042
+ pull: (id, version) => wrap(() => this.clients.docs.get(`/docs/${id}`, version ? { query: { version } } : {})),
1043
+ /** Full version history, newest first — the lineage walk. */
1044
+ versions: (id) => wrap(() => this.clients.docs.get(`/docs/${id}/versions`)),
1045
+ /**
1046
+ * v2.4 (B3.1) — the DocViewer's sandboxed-iframe `src`: a standalone
1047
+ * HTML document with its own CSP (defense in depth over
1048
+ * sanitize-on-push), never a JSON payload injected into the main app's
1049
+ * DOM. Not a `fetch` call — the browser navigates the iframe here
1050
+ * directly, carrying the same session cookie as any same-origin nav.
1051
+ */
1052
+ renderUrl: (id, version) => {
1053
+ const query = version ? `?version=${encodeURIComponent(version)}` : "";
1054
+ return `${this.clients.docs.url()}/docs/${id}/render${query}`;
1055
+ },
1056
+ /**
1057
+ * Annotation engine (task A4.2) — markers-in-doc threads. Every
1058
+ * mutation pushes a new corpus version; the doc itself is the thread
1059
+ * history (locked decision 3).
1060
+ */
1061
+ createThread: (document_id, data) => wrap(() => this.clients.docs.post(`/docs/${document_id}/threads`, { body: data })),
1062
+ replyThread: (document_id, thread_id, body) => wrap(
1063
+ () => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/reply`, { body: { body } })
1064
+ ),
1065
+ resolveThread: (document_id, thread_id) => wrap(() => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/resolve`, {})),
1066
+ toggleBlocking: (document_id, thread_id, blocking) => wrap(
1067
+ () => this.clients.docs.post(`/docs/${document_id}/threads/${thread_id}/blocking`, { body: { blocking } })
1068
+ ),
1069
+ /** Pending annotation threads (anything not `resolved`) — scope to one document, or every document in a project. */
1070
+ unresolved: (filters) => wrap(() => {
1071
+ const query = {};
1072
+ if (filters.project_id) query.project_id = filters.project_id;
1073
+ if (filters.document_id) query.document_id = filters.document_id;
1074
+ return this.clients.docs.get("/docs/annotations/unresolved", { query });
1075
+ }),
1076
+ /**
1077
+ * Interface report v1 (task A4.4). `push` submits already-normalized
1078
+ * declaration text; the server independently recomputes the
1079
+ * additive-vs-breaking classification against its own stored previous
1080
+ * content and auto-approves additive diffs against an approved base.
1081
+ */
1082
+ pushInterfaceReport: (data) => wrap(() => this.clients.docs.post("/docs/interface", { body: data })),
1083
+ interfaceStatus: (filters) => wrap(() => {
1084
+ const query = { project_id: filters.project_id, title: filters.title };
1085
+ if (filters.task_id) query.task_id = filters.task_id;
1086
+ return this.clients.docs.get(
1087
+ "/docs/interface/status",
1088
+ { query }
1089
+ );
1090
+ })
1091
+ };
1092
+ /**
1093
+ * Signoffs namespace (v2.4, task A4.3) — the generalized human-approval
1094
+ * ledger. `decide` is human-only; an api-channel key gets 403.
1095
+ */
1096
+ signoffs = {
1097
+ request: (data) => wrap(() => this.clients.signoffs.post("/signoffs", { body: data })),
1098
+ find: (id) => wrap(() => this.clients.signoffs.get(`/signoffs/${id}`)),
1099
+ /** v2.4 (B3) — the pending (undecided) signoff for a subject+checkpoint, or `null` if none has been requested yet. */
1100
+ findPending: (filters) => wrap(() => this.clients.signoffs.get("/signoffs", { query: filters })),
1101
+ decide: (id, data) => wrap(() => this.clients.signoffs.post(`/signoffs/${id}/decide`, { body: data }))
1102
+ };
1103
+ /**
1104
+ * Reviews namespace (v2.4, task A4.6) — the human's queue: one typed
1105
+ * aggregate across pending signoffs, open blocking annotation threads,
1106
+ * pending pipeline manual gates, and pending scanner diffs.
1107
+ */
1108
+ reviews = {
1109
+ pending: () => wrap(() => this.clients.reviews.get("/reviews/pending"))
1110
+ };
1111
+ /**
1112
+ * GitHub namespace with Result-wrapped operations
1113
+ */
1114
+ github = {
1115
+ /**
1116
+ * List repositories for authenticated user
1117
+ */
1118
+ repos: () => wrap(() => this.clients.github.get("/repos")),
1119
+ /**
1120
+ * List branches for a GitHub repository
1121
+ */
1122
+ branches: (owner, repo) => wrap(() => this.clients.github.get(`/repos/${owner}/${repo}/branches`))
1123
+ };
1124
+ blog = {
1125
+ posts: {
1126
+ list: (params) => wrap(() => {
1127
+ const query = {};
1128
+ if (params?.category) query.category = params.category;
1129
+ if (params?.tag) query.tag = params.tag;
1130
+ if (params?.project) query.project = params.project;
1131
+ if (params?.status) query.status = params.status;
1132
+ if (params?.archived !== void 0) query.archived = String(params.archived);
1133
+ if (params?.limit) query.limit = String(params.limit);
1134
+ if (params?.offset !== void 0) query.offset = String(params.offset);
1135
+ if (params?.sort) query.sort = params.sort;
1136
+ return this.clients.blog.get("/blog/posts", Object.keys(query).length ? { query } : {});
1137
+ }),
1138
+ getBySlug: (slug) => wrap(() => this.clients.blog.get(`/blog/posts/${slug}`)),
1139
+ create: (data) => wrap(() => this.clients.blog.post("/blog/posts", { body: data })),
1140
+ update: (uuid, data) => wrap(() => this.clients.blog.put(`/blog/posts/${uuid}`, { body: data })),
1141
+ delete: (uuid) => wrap(() => this.clients.blog.delete(`/blog/posts/${uuid}`)),
1142
+ versions: (uuid) => wrap(() => this.clients.blog.get(`/blog/posts/${uuid}/versions`)),
1143
+ version: (uuid, hash) => wrap(() => this.clients.blog.get(`/blog/posts/${uuid}/version/${hash}`)),
1144
+ restore: (uuid, hash) => wrap(() => this.clients.blog.post(`/blog/posts/${uuid}/restore/${hash}`))
1145
+ },
1146
+ tags: {
1147
+ list: () => wrap(() => this.clients.blog.get("/blog/tags")),
1148
+ getForPost: (uuid) => wrap(() => this.clients.blog.get(`/blog/tags/posts/${uuid}/tags`)),
1149
+ setForPost: (uuid, tags) => wrap(() => this.clients.blog.put(`/blog/tags/posts/${uuid}/tags`, { body: { tags } })),
1150
+ addToPost: (uuid, tags) => wrap(() => this.clients.blog.post(`/blog/tags/posts/${uuid}/tags`, { body: { tags } })),
1151
+ removeFromPost: (uuid, tag) => wrap(() => this.clients.blog.delete(`/blog/tags/posts/${uuid}/tags/${tag}`))
1152
+ },
1153
+ categories: {
1154
+ tree: () => wrap(() => this.clients.blog.get("/blog/categories")),
1155
+ create: (data) => wrap(() => this.clients.blog.post("/blog/categories", { body: data })),
1156
+ update: (name, data) => wrap(
1157
+ () => this.clients.blog.put(`/blog/categories/${name}`, {
1158
+ body: data
1159
+ })
1160
+ ),
1161
+ delete: (name) => wrap(() => this.clients.blog.delete(`/blog/categories/${name}`))
1162
+ },
1163
+ tokens: {
1164
+ list: () => wrap(() => this.clients.blog.get("/blog/tokens")),
1165
+ create: (data) => wrap(() => this.clients.blog.post("/blog/tokens", { body: data })),
1166
+ update: (id, data) => wrap(
1167
+ () => this.clients.blog.put(`/blog/tokens/${id}`, {
1247
1168
  body: data
1248
1169
  })
1170
+ ),
1171
+ delete: (id) => wrap(() => this.clients.blog.delete(`/blog/tokens/${id}`))
1172
+ }
1173
+ };
1174
+ media = {
1175
+ profiles: {
1176
+ list: () => wrap(async () => {
1177
+ const res = await this.clients.media.get("/profiles");
1178
+ return res.profiles;
1179
+ }),
1180
+ create: (data) => wrap(() => this.clients.media.post("/profiles", { body: data })),
1181
+ get: (id) => wrap(() => this.clients.media.get(`/profiles/${id}`)),
1182
+ update: (id, data) => wrap(() => this.clients.media.patch(`/profiles/${id}`, { body: data })),
1183
+ delete: (id) => wrap(() => this.clients.media.delete(`/profiles/${id}`)),
1184
+ filters: {
1185
+ list: (profile_id) => wrap(async () => {
1186
+ const res = await this.clients.media.get(`/profiles/${profile_id}/filters`);
1187
+ return res.filters;
1188
+ }),
1189
+ add: (profile_id, data) => wrap(() => this.clients.media.post(`/profiles/${profile_id}/filters`, { body: data })),
1190
+ remove: (profile_id, filter_id) => wrap(() => this.clients.media.delete(`/profiles/${profile_id}/filters/${filter_id}`))
1191
+ },
1192
+ timeline: (slug, params) => wrap(() => {
1193
+ const query = {};
1194
+ if (params?.limit) query.limit = String(params.limit);
1195
+ if (params?.before) query.before = params.before;
1196
+ return this.clients.media.get(
1197
+ `/profiles/${slug}/timeline`,
1198
+ Object.keys(query).length ? { query } : {}
1199
+ );
1200
+ })
1201
+ },
1202
+ connections: {
1203
+ list: (profile_id, options) => wrap(async () => {
1204
+ const query = { profile_id };
1205
+ if (options?.include_settings) query.include_settings = "true";
1206
+ const res = await this.clients.media.get("/connections", { query });
1207
+ return res.accounts;
1208
+ }),
1209
+ create: (data) => wrap(() => this.clients.media.post("/connections", { body: data })),
1210
+ delete: (account_id) => wrap(() => this.clients.media.delete(`/connections/${account_id}`)),
1211
+ refresh: (account_id) => wrap(() => this.clients.media.post(`/connections/${account_id}/refresh`)),
1212
+ refreshAll: () => wrap(() => this.clients.media.post("/connections/refresh-all")),
1213
+ updateStatus: (account_id, is_active) => wrap(
1214
+ () => this.clients.media.patch(`/connections/${account_id}`, {
1215
+ body: { is_active }
1216
+ })
1217
+ ),
1218
+ settings: {
1219
+ get: (account_id) => wrap(() => this.clients.media.get(`/connections/${account_id}/settings`)),
1220
+ update: (account_id, settings) => wrap(
1221
+ () => this.clients.media.put(`/connections/${account_id}/settings`, {
1222
+ body: { settings }
1223
+ })
1224
+ )
1225
+ },
1226
+ repos: (account_id) => wrap(async () => {
1227
+ const res = await this.clients.media.get(`/connections/${account_id}/repos`);
1228
+ return res.repos;
1229
+ }),
1230
+ subreddits: (account_id) => wrap(async () => {
1231
+ const res = await this.clients.media.get(`/connections/${account_id}/subreddits`);
1232
+ return res.subreddits;
1233
+ })
1234
+ },
1235
+ credentials: {
1236
+ check: (platform, profile_id) => wrap(
1237
+ () => this.clients.media.get(`/credentials/${platform}`, { query: { profile_id } })
1238
+ ),
1239
+ save: (platform, data) => wrap(
1240
+ () => this.clients.media.post(`/credentials/${platform}`, { body: data })
1241
+ ),
1242
+ delete: (platform, profile_id) => wrap(
1243
+ () => this.clients.media.delete(`/credentials/${platform}`, { query: { profile_id } })
1244
+ )
1245
+ },
1246
+ timeline: {
1247
+ get: (user_id, params) => wrap(() => {
1248
+ const query = {};
1249
+ if (params?.from) query.from = params.from;
1250
+ if (params?.to) query.to = params.to;
1251
+ return this.clients.media.get(`/timeline/${user_id}`, Object.keys(query).length ? { query } : {});
1252
+ }),
1253
+ getRaw: (user_id, platform, account_id) => wrap(
1254
+ () => this.clients.media.get(`/timeline/${user_id}/raw/${platform}`, {
1255
+ query: { account_id }
1256
+ })
1249
1257
  )
1250
- };
1258
+ }
1259
+ };
1260
+ /**
1261
+ * User namespace with Result-wrapped operations
1262
+ */
1263
+ activity = {
1264
+ ai: (options) => wrap(() => {
1265
+ const query = {};
1266
+ if (options?.limit) query.limit = String(options.limit);
1267
+ if (options?.since) query.since = options.since;
1268
+ return this.clients.projects.get(
1269
+ "/activity/ai",
1270
+ Object.keys(query).length ? { query } : {}
1271
+ );
1272
+ })
1273
+ };
1274
+ /** v2.4 (task A5.3) — the fold's dual-read verification verb. */
1275
+ admin = {
1276
+ verifyFold: () => wrap(() => this.clients.admin.get("/admin/verify-fold")),
1277
+ /** v2.4 (B3, CSS-exfil fix) — re-scrubs `<style>` blocks in every already-stored doc the caller owns. */
1278
+ reconcileDocsCss: () => wrap(() => this.clients.admin.post("/admin/reconcile-docs-css"))
1279
+ };
1280
+ user = {
1281
+ /**
1282
+ * Get the authenticated user's identity (id, name, github_id, task_view).
1283
+ * Single source of truth for resolving `owner_id` on task/milestone/goal
1284
+ * upserts — the API rejects any owner_id that doesn't match the caller.
1285
+ */
1286
+ me: () => wrap(
1287
+ () => this.clients.auth.get(
1288
+ "/user/me"
1289
+ )
1290
+ ),
1291
+ /**
1292
+ * Get user activity history
1293
+ */
1294
+ history: () => wrap(() => this.clients.auth.get("/user/history")),
1295
+ /**
1296
+ * Update user preferences
1297
+ */
1298
+ preferences: (data) => wrap(
1299
+ () => this.clients.auth.patch("/user/preferences", {
1300
+ body: data
1301
+ })
1302
+ )
1303
+ };
1304
+ /**
1305
+ * Get request history for debugging
1306
+ */
1307
+ history() {
1308
+ return this.clients.projects.history();
1309
+ }
1310
+ /**
1311
+ * Pulse analytics and monitoring namespace
1312
+ */
1313
+ pulse = {
1314
+ /**
1315
+ * Get summary analytics for a project
1316
+ */
1317
+ summary: (input) => wrap(async () => {
1318
+ const raw = await this.clients.pulse.get(
1319
+ "/summary/:project_id".replace(":project_id", input.project_id),
1320
+ {
1321
+ query: typeof input.range === "string" ? { range: input.range } : { from: String(input.range.from), to: String(input.range.to) }
1322
+ }
1323
+ );
1324
+ return PulseSummarySchema.parse(raw);
1325
+ }),
1326
+ /**
1327
+ * List events for a project
1328
+ */
1329
+ events: (input) => wrap(async () => {
1330
+ const query = {};
1331
+ if (input.name) query.name = input.name;
1332
+ if (input.level) query.level = input.level;
1333
+ if (typeof input.ts_from === "number") query.ts_from = String(input.ts_from);
1334
+ if (typeof input.ts_to === "number") query.ts_to = String(input.ts_to);
1335
+ if (input.search) query.search = input.search;
1336
+ if (input.limit) query.limit = String(input.limit);
1337
+ if (input.cursor) query.cursor = input.cursor;
1338
+ const raw = await this.clients.pulse.get(
1339
+ "/events/:project_id".replace(":project_id", input.project_id),
1340
+ {
1341
+ query
1342
+ }
1343
+ );
1344
+ return PulseEventsPageSchema.parse(raw);
1345
+ }),
1346
+ /**
1347
+ * List error issues for a project
1348
+ */
1349
+ errors: (input) => wrap(async () => {
1350
+ const query = {};
1351
+ if (typeof input.range === "string") {
1352
+ query.range = input.range;
1353
+ } else {
1354
+ query.from = String(input.range.from);
1355
+ query.to = String(input.range.to);
1356
+ }
1357
+ if (input.group_by_fingerprint) query.group_by_fingerprint = "true";
1358
+ const raw = await this.clients.pulse.get(
1359
+ "/errors/:project_id".replace(":project_id", input.project_id),
1360
+ {
1361
+ query
1362
+ }
1363
+ );
1364
+ return PulseErrorsResultSchema.parse(raw);
1365
+ }),
1366
+ /**
1367
+ * List logs for a project
1368
+ */
1369
+ logs: (input) => wrap(async () => {
1370
+ const query = {};
1371
+ if (typeof input.range === "string") {
1372
+ query.range = input.range;
1373
+ } else {
1374
+ query.from = String(input.range.from);
1375
+ query.to = String(input.range.to);
1376
+ }
1377
+ if (input.level) query.level = input.level;
1378
+ if (input.search) query.search = input.search;
1379
+ const raw = await this.clients.pulse.get(
1380
+ "/logs/:project_id".replace(":project_id", input.project_id),
1381
+ { query }
1382
+ );
1383
+ return PulseLogsResultSchema.parse(raw);
1384
+ }),
1251
1385
  /**
1252
- * Pulse analytics and monitoring namespace
1386
+ * Get latency metrics for a project
1253
1387
  */
1254
- this.pulse = {
1388
+ latency: (input) => wrap(async () => {
1389
+ const query = {};
1390
+ if (typeof input.range === "string") {
1391
+ query.range = input.range;
1392
+ } else {
1393
+ query.from = String(input.range.from);
1394
+ query.to = String(input.range.to);
1395
+ }
1396
+ if (input.route) query.route = input.route;
1397
+ if (input.percentiles && input.percentiles.length > 0) query.percentiles = input.percentiles.join(",");
1398
+ const raw = await this.clients.pulse.get(
1399
+ "/latency/:project_id".replace(":project_id", input.project_id),
1400
+ {
1401
+ query
1402
+ }
1403
+ );
1404
+ return PulseLatencyResultSchema.parse(raw);
1405
+ }),
1406
+ /**
1407
+ * Subscription management
1408
+ */
1409
+ subs: {
1255
1410
  /**
1256
- * Get summary analytics for a project
1411
+ * List subscriptions for a project
1257
1412
  */
1258
- summary: (input) => wrap(async () => {
1259
- const raw = await this.clients.pulse.get(
1260
- "/summary/:project_id".replace(":project_id", input.project_id),
1261
- {
1262
- query: typeof input.range === "string" ? { range: input.range } : { from: String(input.range.from), to: String(input.range.to) }
1263
- }
1264
- );
1265
- return PulseSummarySchema.parse(raw);
1266
- }),
1413
+ list: (input) => wrap(() => this.clients.pulse.get("/admin/subs", { query: { project_id: input.project_id } })),
1267
1414
  /**
1268
- * List events for a project
1415
+ * Create a subscription
1269
1416
  */
1270
- events: (input) => wrap(async () => {
1271
- const query = {};
1272
- if (input.name) query.name = input.name;
1273
- if (input.level) query.level = input.level;
1274
- if (typeof input.ts_from === "number") query.ts_from = String(input.ts_from);
1275
- if (typeof input.ts_to === "number") query.ts_to = String(input.ts_to);
1276
- if (input.search) query.search = input.search;
1277
- if (input.limit) query.limit = String(input.limit);
1278
- if (input.cursor) query.cursor = input.cursor;
1279
- const raw = await this.clients.pulse.get(
1280
- "/events/:project_id".replace(":project_id", input.project_id),
1281
- {
1282
- query
1417
+ create: (input) => wrap(
1418
+ () => this.clients.pulse.post("/admin/subs", {
1419
+ body: {
1420
+ project_id: input.project_id,
1421
+ name: input.name,
1422
+ filter: input.filter,
1423
+ channel: input.channel,
1424
+ cooldown_seconds: input.cooldown_seconds
1283
1425
  }
1284
- );
1285
- return PulseEventsPageSchema.parse(raw);
1286
- }),
1426
+ })
1427
+ ),
1287
1428
  /**
1288
- * List error issues for a project
1429
+ * Get a subscription by ID
1289
1430
  */
1290
- errors: (input) => wrap(async () => {
1291
- const query = {};
1292
- if (typeof input.range === "string") {
1293
- query.range = input.range;
1294
- } else {
1295
- query.from = String(input.range.from);
1296
- query.to = String(input.range.to);
1297
- }
1298
- if (input.group_by_fingerprint) query.group_by_fingerprint = "true";
1299
- const raw = await this.clients.pulse.get(
1300
- "/errors/:project_id".replace(":project_id", input.project_id),
1301
- {
1302
- query
1303
- }
1304
- );
1305
- return PulseErrorsResultSchema.parse(raw);
1306
- }),
1431
+ get: (id) => wrap(() => this.clients.pulse.get(`/admin/subs/${id}`)),
1307
1432
  /**
1308
- * List logs for a project
1433
+ * Update a subscription
1309
1434
  */
1310
- logs: (input) => wrap(async () => {
1311
- const query = {};
1312
- if (typeof input.range === "string") {
1313
- query.range = input.range;
1314
- } else {
1315
- query.from = String(input.range.from);
1316
- query.to = String(input.range.to);
1317
- }
1318
- if (input.level) query.level = input.level;
1319
- if (input.search) query.search = input.search;
1320
- const raw = await this.clients.pulse.get(
1321
- "/logs/:project_id".replace(":project_id", input.project_id),
1322
- { query }
1323
- );
1324
- return PulseLogsResultSchema.parse(raw);
1325
- }),
1435
+ update: (id, patch) => wrap(() => this.clients.pulse.patch(`/admin/subs/${id}`, { body: patch })),
1326
1436
  /**
1327
- * Get latency metrics for a project
1437
+ * Delete a subscription
1328
1438
  */
1329
- latency: (input) => wrap(async () => {
1330
- const query = {};
1331
- if (typeof input.range === "string") {
1332
- query.range = input.range;
1333
- } else {
1334
- query.from = String(input.range.from);
1335
- query.to = String(input.range.to);
1336
- }
1337
- if (input.route) query.route = input.route;
1338
- if (input.percentiles && input.percentiles.length > 0) query.percentiles = input.percentiles.join(",");
1339
- const raw = await this.clients.pulse.get(
1340
- "/latency/:project_id".replace(":project_id", input.project_id),
1341
- {
1342
- query
1343
- }
1344
- );
1345
- return PulseLatencyResultSchema.parse(raw);
1346
- }),
1439
+ delete: (id) => wrap(() => this.clients.pulse.delete(`/admin/subs/${id}`))
1440
+ },
1441
+ /**
1442
+ * Ingest key management
1443
+ */
1444
+ keys: {
1347
1445
  /**
1348
- * Subscription management
1446
+ * List ingest keys for a project
1349
1447
  */
1350
- subs: {
1351
- /**
1352
- * List subscriptions for a project
1353
- */
1354
- list: (input) => wrap(() => this.clients.pulse.get("/admin/subs", { query: { project_id: input.project_id } })),
1355
- /**
1356
- * Create a subscription
1357
- */
1358
- create: (input) => wrap(
1359
- () => this.clients.pulse.post("/admin/subs", {
1360
- body: {
1361
- project_id: input.project_id,
1362
- name: input.name,
1363
- filter: input.filter,
1364
- channel: input.channel,
1365
- cooldown_seconds: input.cooldown_seconds
1366
- }
1367
- })
1368
- ),
1369
- /**
1370
- * Get a subscription by ID
1371
- */
1372
- get: (id) => wrap(() => this.clients.pulse.get(`/admin/subs/${id}`)),
1373
- /**
1374
- * Update a subscription
1375
- */
1376
- update: (id, patch) => wrap(() => this.clients.pulse.patch(`/admin/subs/${id}`, { body: patch })),
1377
- /**
1378
- * Delete a subscription
1379
- */
1380
- delete: (id) => wrap(() => this.clients.pulse.delete(`/admin/subs/${id}`))
1381
- },
1448
+ list: (input) => wrap(() => this.clients.pulse.get("/admin/keys", { query: { project_id: input.project_id } })),
1382
1449
  /**
1383
- * Ingest key management
1450
+ * Create a new ingest key (returns plaintext only once)
1384
1451
  */
1385
- keys: {
1386
- /**
1387
- * List ingest keys for a project
1388
- */
1389
- list: (input) => wrap(() => this.clients.pulse.get("/admin/keys", { query: { project_id: input.project_id } })),
1390
- /**
1391
- * Create a new ingest key (returns plaintext only once)
1392
- */
1393
- create: (input) => wrap(
1394
- () => this.clients.pulse.post("/admin/keys", {
1395
- body: {
1396
- project_id: input.project_id,
1397
- name: input.name,
1398
- rate_limit_per_min: input.rate_limit_per_min
1399
- }
1400
- })
1401
- ),
1402
- /**
1403
- * Delete an ingest key
1404
- */
1405
- delete: (id, input) => wrap(
1406
- () => this.clients.pulse.delete(`/admin/keys/${id}`, {
1407
- query: { project_id: input.project_id }
1408
- })
1409
- )
1452
+ create: (input) => wrap(
1453
+ () => this.clients.pulse.post("/admin/keys", {
1454
+ body: {
1455
+ project_id: input.project_id,
1456
+ name: input.name,
1457
+ rate_limit_per_min: input.rate_limit_per_min
1458
+ }
1459
+ })
1460
+ ),
1461
+ /**
1462
+ * Delete an ingest key
1463
+ */
1464
+ delete: (id, input) => wrap(
1465
+ () => this.clients.pulse.delete(`/admin/keys/${id}`, {
1466
+ query: { project_id: input.project_id }
1467
+ })
1468
+ )
1469
+ }
1470
+ };
1471
+ /**
1472
+ * Pipelines namespace with Result-wrapped operations
1473
+ */
1474
+ pipelines = {
1475
+ /**
1476
+ * Dashboard namespace — Phase 2.D observability slice. Aggregates
1477
+ * `pipeline_run`, `pipeline_stage_event`, and `pipeline_approval`
1478
+ * for the project's pipeline_package(s) over `window_ms` and
1479
+ * enriches the response with pulse `/summary` when configured.
1480
+ *
1481
+ * Lives at `GET /v1/pipelines/dashboard?project_id=...&window_ms=...`
1482
+ * on the main worker (unified D1 binding — no orchestrator hop).
1483
+ * Auth: session cookie + ownership check on the project_id.
1484
+ * Cache: `public, max-age=30`.
1485
+ */
1486
+ dashboard: {
1487
+ get: (input) => {
1488
+ const query = { project_id: input.project_id };
1489
+ if (input.window_ms !== void 0) query.window_ms = String(input.window_ms);
1490
+ return wrap(
1491
+ () => this.clients.pipelines.get(
1492
+ "/pipelines/dashboard",
1493
+ { query }
1494
+ )
1495
+ );
1410
1496
  }
1411
- };
1497
+ },
1498
+ /**
1499
+ * List pipeline runs ordered by `created_at` DESC. Optional filters
1500
+ * narrow by package and/or status; `limit` defaults to 50 server-side
1501
+ * and is capped at 200.
1502
+ */
1503
+ list: (filter) => {
1504
+ const query = {};
1505
+ if (filter?.package_id !== void 0) query.package_id = filter.package_id;
1506
+ if (filter?.status !== void 0) query.status = filter.status;
1507
+ if (filter?.limit !== void 0) query.limit = String(filter.limit);
1508
+ return wrap(
1509
+ () => this.clients.pipelines.get("/runs", Object.keys(query).length > 0 ? { query } : void 0)
1510
+ );
1511
+ },
1512
+ /**
1513
+ * Get a pipeline run by ID
1514
+ */
1515
+ get: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}`)),
1516
+ /**
1517
+ * Create a new pipeline run
1518
+ */
1519
+ create: (input) => wrap(
1520
+ () => this.clients.pipelines.post("/runs", {
1521
+ body: input
1522
+ })
1523
+ ),
1524
+ /**
1525
+ * Approve a stage in a pipeline run. Identity is resolved
1526
+ * server-side by the worker proxy (`X-Devpad-Actor` header) — the
1527
+ * caller never supplies a `user_id`. Approvals are human-only:
1528
+ * api-channel callers get `403 human_approval_required`; approve
1529
+ * from the devpad web UI while signed in.
1530
+ */
1531
+ approve: (run_id, input) => wrap(
1532
+ () => this.clients.pipelines.post(`/runs/${run_id}/approve`, {
1533
+ body: input
1534
+ })
1535
+ ),
1536
+ /**
1537
+ * Cancel a pipeline run
1538
+ */
1539
+ cancel: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/cancel`, { body: {} })),
1412
1540
  /**
1413
- * Pipelines namespace with Result-wrapped operations
1541
+ * Rollback a pipeline run
1414
1542
  */
1415
- this.pipelines = {
1543
+ rollback: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/rollback`, { body: {} })),
1544
+ /**
1545
+ * Re-dispatch a FAILED external production dispatch (#155). Human-only:
1546
+ * only valid when the run's production dispatch row is `failed` —
1547
+ * any other state is a 4xx from the orchestrator. api-channel callers
1548
+ * get `403 human_approval_required` from the worker proxy; call from
1549
+ * the devpad web UI while signed in.
1550
+ */
1551
+ redispatch: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/redispatch`, { body: {} })),
1552
+ /**
1553
+ * Read a run's dispatch ledger (`GET /v1/runs/:id/dispatches`): one
1554
+ * row per stage with claim/dispatch status, error text and actor.
1555
+ */
1556
+ dispatches: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}/dispatches`)),
1557
+ /**
1558
+ * Stage-event namespace — Phase 2.C webhook ingestion + read-back.
1559
+ *
1560
+ * `ingest` posts a webhook event against an in-flight run; auth
1561
+ * mode is the standard bearer/session header (admin bypass; session
1562
+ * must carry `runs:events` and matching `package_id`). Server-side
1563
+ * stamps `payload.source = "external"`. Idempotency: same
1564
+ * `idempotency_key` + same payload returns `{ duplicated: true }`;
1565
+ * same key + different payload returns a 400 validation_error.
1566
+ *
1567
+ * `list` is read-only and returns the run's events newest-first.
1568
+ */
1569
+ events: {
1570
+ ingest: (run_id, input) => wrap(
1571
+ () => this.clients.pipelines.post(
1572
+ `/runs/${run_id}/events`,
1573
+ {
1574
+ body: input
1575
+ }
1576
+ )
1577
+ ),
1578
+ list: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}/events`))
1579
+ },
1580
+ /**
1581
+ * Grants namespace
1582
+ */
1583
+ grants: {
1416
1584
  /**
1417
- * Dashboard namespace — Phase 2.D observability slice. Aggregates
1418
- * `pipeline_run`, `pipeline_stage_event`, and `pipeline_approval`
1419
- * for the project's pipeline_package(s) over `window_ms` and
1420
- * enriches the response with pulse `/summary` when configured.
1421
- *
1422
- * Lives at `GET /v1/pipelines/dashboard?project_id=...&window_ms=...`
1423
- * on the main worker (unified D1 binding — no orchestrator hop).
1424
- * Auth: session cookie + ownership check on the project_id.
1425
- * Cache: `public, max-age=30`.
1585
+ * List grants for a package
1426
1586
  */
1427
- dashboard: {
1428
- get: (input) => {
1429
- const query = { project_id: input.project_id };
1430
- if (input.window_ms !== void 0) query.window_ms = String(input.window_ms);
1431
- return wrap(
1432
- () => this.clients.pipelines.get(
1433
- "/pipelines/dashboard",
1434
- { query }
1435
- )
1436
- );
1437
- }
1438
- },
1587
+ list: (package_id) => wrap(
1588
+ () => this.clients.pipelines.get("/grants", {
1589
+ query: package_id ? { package_id } : {}
1590
+ })
1591
+ ),
1439
1592
  /**
1440
- * List pipeline runs ordered by `created_at` DESC. Optional filters
1441
- * narrow by package and/or status; `limit` defaults to 50 server-side
1442
- * and is capped at 200.
1593
+ * Approve a pending grant. Human-only — the actor is resolved
1594
+ * server-side by the worker proxy; api-channel callers get
1595
+ * `403 human_approval_required`.
1596
+ */
1597
+ approve: (grant_id) => wrap(
1598
+ () => this.clients.pipelines.post(`/grants/${grant_id}/approve`, {
1599
+ body: {}
1600
+ })
1601
+ ),
1602
+ /**
1603
+ * Deny a pending grant. Human-only — same actor resolution as
1604
+ * `approve`.
1605
+ */
1606
+ deny: (grant_id, reason) => wrap(
1607
+ () => this.clients.pipelines.post(`/grants/${grant_id}/deny`, {
1608
+ body: reason !== void 0 ? { reason } : {}
1609
+ })
1610
+ )
1611
+ },
1612
+ /**
1613
+ * Packages namespace — full CRUD over pipeline_package rows. Writes
1614
+ * (create/update/delete) require the orchestrator bearer token; the
1615
+ * HttpClient picks it up via the standard auth header injection.
1616
+ */
1617
+ packages: {
1618
+ /**
1619
+ * List packages, optionally filtered by linked devpad project.
1620
+ * Packages with `project_id = null` are not yet linked.
1443
1621
  */
1444
1622
  list: (filter) => {
1445
1623
  const query = {};
1446
- if (filter?.package_id !== void 0) query.package_id = filter.package_id;
1447
- if (filter?.status !== void 0) query.status = filter.status;
1448
- if (filter?.limit !== void 0) query.limit = String(filter.limit);
1624
+ if (filter?.project_id !== void 0) query.project_id = filter.project_id;
1449
1625
  return wrap(
1450
- () => this.clients.pipelines.get("/runs", Object.keys(query).length > 0 ? { query } : void 0)
1626
+ () => this.clients.pipelines.get(
1627
+ "/packages",
1628
+ Object.keys(query).length > 0 ? { query } : void 0
1629
+ )
1451
1630
  );
1452
1631
  },
1453
1632
  /**
1454
- * Get a pipeline run by ID
1633
+ * Get a single package by id
1455
1634
  */
1456
- get: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}`)),
1635
+ get: (package_id) => wrap(() => this.clients.pipelines.get(`/packages/${package_id}`)),
1457
1636
  /**
1458
- * Create a new pipeline run
1637
+ * Register a new pipeline package. `id` is canonically the same as
1638
+ * `name` per existing convention but is supplied explicitly so the
1639
+ * orchestrator can disambiguate renames without conflicts.
1459
1640
  */
1460
- create: (input) => wrap(
1461
- () => this.clients.pipelines.post("/runs", {
1462
- body: input
1463
- })
1464
- ),
1641
+ create: (input) => wrap(() => this.clients.pipelines.post("/packages", { body: input })),
1642
+ /**
1643
+ * Partially update a package row. Missing keys preserve existing
1644
+ * values; explicit `null` clears the field.
1645
+ */
1646
+ update: (package_id, input) => wrap(() => this.clients.pipelines.patch(`/packages/${package_id}`, { body: input })),
1465
1647
  /**
1466
- * Approve a stage in a pipeline run. Identity is resolved
1467
- * server-side by the worker proxy (`X-Devpad-Actor` header) — the
1468
- * caller never supplies a `user_id`. Approvals are human-only:
1469
- * api-channel callers get `403 human_approval_required`; approve
1470
- * from the devpad web UI while signed in.
1648
+ * Remove a package. Refuses (409) if pipeline_run rows still
1649
+ * reference the package — clean up runs first.
1471
1650
  */
1472
- approve: (run_id, input) => wrap(
1473
- () => this.clients.pipelines.post(`/runs/${run_id}/approve`, {
1474
- body: input
1651
+ delete: (package_id) => wrap(() => this.clients.pipelines.delete(`/packages/${package_id}`))
1652
+ },
1653
+ /**
1654
+ * Analysis-template namespace — admin-gated CRUD for the
1655
+ * `pipeline_analysis_template` table. Phase 2.A surface; each
1656
+ * call requires the orchestrator's bearer token (literal
1657
+ * `PIPELINES_TOKEN`). `owner_id` is required on every operation
1658
+ * — single-tenant today, but the column is in place so multi-user
1659
+ * ACLs slot in later.
1660
+ */
1661
+ analysis_templates: {
1662
+ /**
1663
+ * List templates for an owner.
1664
+ */
1665
+ list: (input) => wrap(
1666
+ () => this.clients.pipelines.get("/analysis-templates", {
1667
+ query: { owner_id: input.owner_id }
1475
1668
  })
1476
1669
  ),
1477
1670
  /**
1478
- * Cancel a pipeline run
1671
+ * Get a single template by id, scoped to its owner. 404 when
1672
+ * unknown or owned by a different user.
1479
1673
  */
1480
- cancel: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/cancel`, { body: {} })),
1674
+ get: (id, input) => wrap(
1675
+ () => this.clients.pipelines.get(`/analysis-templates/${id}`, {
1676
+ query: { owner_id: input.owner_id }
1677
+ })
1678
+ ),
1481
1679
  /**
1482
- * Rollback a pipeline run
1680
+ * Create a new analysis template. `threshold_dsl` is parsed
1681
+ * server-side; parse failure returns 400 `validation_error`
1682
+ * with `field: "threshold_dsl"` and a descriptive message.
1683
+ * `window_ms` defaults to 600_000 (10 min) when omitted.
1483
1684
  */
1484
- rollback: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/rollback`, { body: {} })),
1685
+ create: (input) => wrap(() => this.clients.pipelines.post("/analysis-templates", { body: input })),
1485
1686
  /**
1486
- * Re-dispatch a FAILED external production dispatch (#155). Human-only:
1487
- * only valid when the run's production dispatch row is `failed` —
1488
- * any other state is a 4xx from the orchestrator. api-channel callers
1489
- * get `403 human_approval_required` from the worker proxy; call from
1490
- * the devpad web UI while signed in.
1687
+ * Partial patch — only the supplied fields are touched.
1688
+ * Re-validates `threshold_dsl` when supplied; same
1689
+ * `validation_error` shape as create on parse failure.
1491
1690
  */
1492
- redispatch: (run_id) => wrap(() => this.clients.pipelines.post(`/runs/${run_id}/redispatch`, { body: {} })),
1691
+ update: (id, input) => wrap(
1692
+ () => this.clients.pipelines.patch(`/analysis-templates/${id}`, { body: input })
1693
+ ),
1493
1694
  /**
1494
- * Read a run's dispatch ledger (`GET /v1/runs/:id/dispatches`): one
1495
- * row per stage with claim/dispatch status, error text and actor.
1695
+ * Hard-delete the template. Does NOT consult
1696
+ * `pipeline_run.resolved_gates` — runs snapshot their gate
1697
+ * template at resolve-time, so deletion never orphans
1698
+ * in-flight runs.
1496
1699
  */
1497
- dispatches: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}/dispatches`)),
1700
+ delete: (id, input) => wrap(
1701
+ () => this.clients.pipelines.delete(`/analysis-templates/${id}`, {
1702
+ query: { owner_id: input.owner_id }
1703
+ })
1704
+ )
1705
+ },
1706
+ /**
1707
+ * OIDC trust-policy namespace — admin-gated CRUD for the
1708
+ * `pipeline_oidc_trust` table. Phase 15.D surface; each call requires
1709
+ * the orchestrator's bearer token (literal `PIPELINES_TOKEN`).
1710
+ * `owner_id` is required on every operation — single-tenant today,
1711
+ * but the column is in place so multi-user ACLs slot in later.
1712
+ */
1713
+ oidc_trust: {
1498
1714
  /**
1499
- * Stage-event namespace — Phase 2.C webhook ingestion + read-back.
1500
- *
1501
- * `ingest` posts a webhook event against an in-flight run; auth
1502
- * mode is the standard bearer/session header (admin bypass; session
1503
- * must carry `runs:events` and matching `package_id`). Server-side
1504
- * stamps `payload.source = "external"`. Idempotency: same
1505
- * `idempotency_key` + same payload returns `{ duplicated: true }`;
1506
- * same key + different payload returns a 400 validation_error.
1507
- *
1508
- * `list` is read-only and returns the run's events newest-first.
1715
+ * List policies for an owner, ordered created_at DESC, id ASC —
1716
+ * matches the trust-matcher resolution order so the management UI
1717
+ * shows the policy that would be picked first.
1509
1718
  */
1510
- events: {
1511
- ingest: (run_id, input) => wrap(
1512
- () => this.clients.pipelines.post(
1513
- `/runs/${run_id}/events`,
1514
- {
1515
- body: input
1516
- }
1517
- )
1518
- ),
1519
- list: (run_id) => wrap(() => this.clients.pipelines.get(`/runs/${run_id}/events`))
1520
- },
1719
+ list: (input) => wrap(
1720
+ () => this.clients.pipelines.get("/oidc-trust", { query: { owner_id: input.owner_id } })
1721
+ ),
1521
1722
  /**
1522
- * Grants namespace
1723
+ * Get a single policy by id, scoped to its owner. 404 when
1724
+ * unknown, soft-deleted, or owned by a different user.
1523
1725
  */
1524
- grants: {
1525
- /**
1526
- * List grants for a package
1527
- */
1528
- list: (package_id) => wrap(
1529
- () => this.clients.pipelines.get("/grants", {
1530
- query: package_id ? { package_id } : {}
1531
- })
1532
- ),
1533
- /**
1534
- * Approve a pending grant. Human-only — the actor is resolved
1535
- * server-side by the worker proxy; api-channel callers get
1536
- * `403 human_approval_required`.
1537
- */
1538
- approve: (grant_id) => wrap(
1539
- () => this.clients.pipelines.post(`/grants/${grant_id}/approve`, {
1540
- body: {}
1541
- })
1542
- ),
1543
- /**
1544
- * Deny a pending grant. Human-only — same actor resolution as
1545
- * `approve`.
1546
- */
1547
- deny: (grant_id, reason) => wrap(
1548
- () => this.clients.pipelines.post(`/grants/${grant_id}/deny`, {
1549
- body: reason !== void 0 ? { reason } : {}
1550
- })
1551
- )
1552
- },
1726
+ get: (id, input) => wrap(
1727
+ () => this.clients.pipelines.get(`/oidc-trust/${id}`, { query: { owner_id: input.owner_id } })
1728
+ ),
1553
1729
  /**
1554
- * Packages namespace — full CRUD over pipeline_package rows. Writes
1555
- * (create/update/delete) require the orchestrator bearer token; the
1556
- * HttpClient picks it up via the standard auth header injection.
1730
+ * Create a new policy. Defaults per plan §I.5: `repo_pattern: "*"`,
1731
+ * `allowed_actions: ["artifacts:upload","runs:start"]`,
1732
+ * `session_ttl_seconds: 900`.
1557
1733
  */
1558
- packages: {
1559
- /**
1560
- * List packages, optionally filtered by linked devpad project.
1561
- * Packages with `project_id = null` are not yet linked.
1562
- */
1563
- list: (filter) => {
1564
- const query = {};
1565
- if (filter?.project_id !== void 0) query.project_id = filter.project_id;
1566
- return wrap(
1567
- () => this.clients.pipelines.get(
1568
- "/packages",
1569
- Object.keys(query).length > 0 ? { query } : void 0
1570
- )
1571
- );
1572
- },
1573
- /**
1574
- * Get a single package by id
1575
- */
1576
- get: (package_id) => wrap(() => this.clients.pipelines.get(`/packages/${package_id}`)),
1577
- /**
1578
- * Register a new pipeline package. `id` is canonically the same as
1579
- * `name` per existing convention but is supplied explicitly so the
1580
- * orchestrator can disambiguate renames without conflicts.
1581
- */
1582
- create: (input) => wrap(() => this.clients.pipelines.post("/packages", { body: input })),
1583
- /**
1584
- * Partially update a package row. Missing keys preserve existing
1585
- * values; explicit `null` clears the field.
1586
- */
1587
- update: (package_id, input) => wrap(() => this.clients.pipelines.patch(`/packages/${package_id}`, { body: input })),
1588
- /**
1589
- * Remove a package. Refuses (409) if pipeline_run rows still
1590
- * reference the package — clean up runs first.
1591
- */
1592
- delete: (package_id) => wrap(() => this.clients.pipelines.delete(`/packages/${package_id}`))
1593
- },
1734
+ create: (input) => wrap(() => this.clients.pipelines.post("/oidc-trust", { body: input })),
1594
1735
  /**
1595
- * Analysis-template namespace — admin-gated CRUD for the
1596
- * `pipeline_analysis_template` table. Phase 2.A surface; each
1597
- * call requires the orchestrator's bearer token (literal
1598
- * `PIPELINES_TOKEN`). `owner_id` is required on every operation
1599
- * — single-tenant today, but the column is in place so multi-user
1600
- * ACLs slot in later.
1736
+ * Partial patch — only the supplied fields are touched. Validation
1737
+ * runs against the merged record server-side.
1601
1738
  */
1602
- analysis_templates: {
1603
- /**
1604
- * List templates for an owner.
1605
- */
1606
- list: (input) => wrap(
1607
- () => this.clients.pipelines.get("/analysis-templates", {
1608
- query: { owner_id: input.owner_id }
1609
- })
1610
- ),
1611
- /**
1612
- * Get a single template by id, scoped to its owner. 404 when
1613
- * unknown or owned by a different user.
1614
- */
1615
- get: (id, input) => wrap(
1616
- () => this.clients.pipelines.get(`/analysis-templates/${id}`, {
1617
- query: { owner_id: input.owner_id }
1618
- })
1619
- ),
1620
- /**
1621
- * Create a new analysis template. `threshold_dsl` is parsed
1622
- * server-side; parse failure returns 400 `validation_error`
1623
- * with `field: "threshold_dsl"` and a descriptive message.
1624
- * `window_ms` defaults to 600_000 (10 min) when omitted.
1625
- */
1626
- create: (input) => wrap(() => this.clients.pipelines.post("/analysis-templates", { body: input })),
1627
- /**
1628
- * Partial patch — only the supplied fields are touched.
1629
- * Re-validates `threshold_dsl` when supplied; same
1630
- * `validation_error` shape as create on parse failure.
1631
- */
1632
- update: (id, input) => wrap(
1633
- () => this.clients.pipelines.patch(`/analysis-templates/${id}`, { body: input })
1634
- ),
1635
- /**
1636
- * Hard-delete the template. Does NOT consult
1637
- * `pipeline_run.resolved_gates` — runs snapshot their gate
1638
- * template at resolve-time, so deletion never orphans
1639
- * in-flight runs.
1640
- */
1641
- delete: (id, input) => wrap(
1642
- () => this.clients.pipelines.delete(`/analysis-templates/${id}`, {
1643
- query: { owner_id: input.owner_id }
1644
- })
1645
- )
1646
- },
1739
+ update: (id, input) => wrap(() => this.clients.pipelines.patch(`/oidc-trust/${id}`, { body: input })),
1647
1740
  /**
1648
- * OIDC trust-policy namespace — admin-gated CRUD for the
1649
- * `pipeline_oidc_trust` table. Phase 15.D surface; each call requires
1650
- * the orchestrator's bearer token (literal `PIPELINES_TOKEN`).
1651
- * `owner_id` is required on every operation — single-tenant today,
1652
- * but the column is in place so multi-user ACLs slot in later.
1741
+ * Soft-delete a policy (sets `deleted = true`; row preserved for
1742
+ * audit). The matcher and management list both skip soft-deleted
1743
+ * rows.
1653
1744
  */
1654
- oidc_trust: {
1655
- /**
1656
- * List policies for an owner, ordered created_at DESC, id ASC —
1657
- * matches the trust-matcher resolution order so the management UI
1658
- * shows the policy that would be picked first.
1659
- */
1660
- list: (input) => wrap(
1661
- () => this.clients.pipelines.get("/oidc-trust", { query: { owner_id: input.owner_id } })
1662
- ),
1663
- /**
1664
- * Get a single policy by id, scoped to its owner. 404 when
1665
- * unknown, soft-deleted, or owned by a different user.
1666
- */
1667
- get: (id, input) => wrap(
1668
- () => this.clients.pipelines.get(`/oidc-trust/${id}`, { query: { owner_id: input.owner_id } })
1669
- ),
1670
- /**
1671
- * Create a new policy. Defaults per plan §I.5: `repo_pattern: "*"`,
1672
- * `allowed_actions: ["artifacts:upload","runs:start"]`,
1673
- * `session_ttl_seconds: 900`.
1674
- */
1675
- create: (input) => wrap(() => this.clients.pipelines.post("/oidc-trust", { body: input })),
1676
- /**
1677
- * Partial patch — only the supplied fields are touched. Validation
1678
- * runs against the merged record server-side.
1679
- */
1680
- update: (id, input) => wrap(() => this.clients.pipelines.patch(`/oidc-trust/${id}`, { body: input })),
1681
- /**
1682
- * Soft-delete a policy (sets `deleted = true`; row preserved for
1683
- * audit). The matcher and management list both skip soft-deleted
1684
- * rows.
1685
- */
1686
- delete: (id, input) => wrap(
1687
- () => this.clients.pipelines.delete(`/oidc-trust/${id}`, {
1688
- query: { owner_id: input.owner_id }
1689
- })
1690
- )
1691
- }
1692
- };
1693
- const base_url = options.base_url || "http://localhost:4321/api/v1";
1694
- this.api_key_field = options.api_key ?? "";
1695
- this.auth_mode_field = options.auth_mode ?? (options.api_key?.startsWith("jwt:") ? "session" : options.api_key ? "key" : "cookie");
1696
- const clientOptions = {
1697
- base_url,
1698
- api_key: options.api_key,
1699
- max_history_size: options.max_history_size,
1700
- auth_mode: this.auth_mode_field,
1701
- credentials: options.credentials,
1702
- default_headers: options.default_headers,
1703
- custom_fetch: options.custom_fetch
1704
- };
1705
- const auth_base_url = base_url.replace(/\/v1\/?$/, "");
1706
- this.clients = {
1707
- auth: new ApiClient({ ...clientOptions, category: "auth" }),
1708
- auth_root: new ApiClient({
1709
- ...clientOptions,
1710
- base_url: auth_base_url,
1711
- category: "auth"
1712
- }),
1713
- projects: new ApiClient({ ...clientOptions, category: "projects" }),
1714
- tasks: new ApiClient({ ...clientOptions, category: "tasks" }),
1715
- milestones: new ApiClient({ ...clientOptions, category: "milestones" }),
1716
- goals: new ApiClient({ ...clientOptions, category: "goals" }),
1717
- github: new ApiClient({ ...clientOptions, category: "github" }),
1718
- tags: new ApiClient({ ...clientOptions, category: "tags" }),
1719
- blog: new ApiClient({ ...clientOptions, category: "blog" }),
1720
- media: new ApiClient({ ...clientOptions, category: "media" }),
1721
- pulse: new ApiClient({ ...clientOptions, base_url: `${base_url}/pulse`, category: "pulse" }),
1722
- pipelines: new ApiClient({ ...clientOptions, category: "pipelines" }),
1723
- hooks: new ApiClient({ ...clientOptions, category: "hooks" }),
1724
- docs: new ApiClient({ ...clientOptions, category: "docs" }),
1725
- signoffs: new ApiClient({ ...clientOptions, category: "signoffs" }),
1726
- reviews: new ApiClient({ ...clientOptions, category: "reviews" }),
1727
- admin: new ApiClient({ ...clientOptions, category: "admin" })
1728
- };
1729
- }
1730
- /**
1731
- * Get request history for debugging
1732
- */
1733
- history() {
1734
- return this.clients.projects.history();
1735
- }
1745
+ delete: (id, input) => wrap(
1746
+ () => this.clients.pipelines.delete(`/oidc-trust/${id}`, {
1747
+ query: { owner_id: input.owner_id }
1748
+ })
1749
+ )
1750
+ }
1751
+ };
1736
1752
  /**
1737
1753
  * Get the API key
1738
1754
  */
@@ -1747,34 +1763,54 @@ var ApiClient2 = class {
1747
1763
  }
1748
1764
  };
1749
1765
 
1750
- // ../schema/dist/blog/index.js
1751
- import { create_cloudflare_backend, create_corpus, create_memory_backend, define_store, err as err2, json_codec, ok as ok2 } from "@f0rbit/corpus";
1766
+ // ../schema/src/blog/index.ts
1767
+ import {
1768
+ create_cloudflare_backend,
1769
+ create_corpus,
1770
+ create_memory_backend,
1771
+ define_store,
1772
+ err as err2,
1773
+ json_codec,
1774
+ ok as ok2
1775
+ } from "@f0rbit/corpus";
1752
1776
 
1753
- // ../schema/dist/database/blog.js
1777
+ // ../schema/src/database/blog.ts
1754
1778
  import { sql } from "drizzle-orm";
1755
1779
  import { integer, primaryKey, sqliteTable, text, unique } from "drizzle-orm/sqlite-core";
1756
- var blog_posts = sqliteTable("blog_posts", {
1757
- id: integer("id").primaryKey({ autoIncrement: true }),
1758
- uuid: text("uuid").notNull().unique(),
1759
- author_id: text("author_id").notNull(),
1760
- slug: text("slug").notNull(),
1761
- corpus_version: text("corpus_version"),
1762
- category: text("category").notNull().default("root"),
1763
- archived: integer("archived", { mode: "boolean" }).notNull().default(false),
1764
- publish_at: integer("publish_at", { mode: "timestamp" }),
1765
- created_at: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
1766
- updated_at: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`)
1767
- }, (table) => [unique("posts_author_slug_unique").on(table.author_id, table.slug)]);
1768
- var blog_categories = sqliteTable("blog_categories", {
1769
- id: integer("id").primaryKey({ autoIncrement: true }),
1770
- owner_id: text("owner_id").notNull(),
1771
- name: text("name").notNull(),
1772
- parent: text("parent").default("root")
1773
- }, (table) => [unique("categories_owner_name_unique").on(table.owner_id, table.name)]);
1774
- var blog_tags = sqliteTable("blog_tags", {
1775
- post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1776
- tag: text("tag").notNull()
1777
- }, (table) => [primaryKey({ columns: [table.post_id, table.tag] })]);
1780
+ var blog_posts = sqliteTable(
1781
+ "blog_posts",
1782
+ {
1783
+ id: integer("id").primaryKey({ autoIncrement: true }),
1784
+ uuid: text("uuid").notNull().unique(),
1785
+ author_id: text("author_id").notNull(),
1786
+ slug: text("slug").notNull(),
1787
+ corpus_version: text("corpus_version"),
1788
+ category: text("category").notNull().default("root"),
1789
+ archived: integer("archived", { mode: "boolean" }).notNull().default(false),
1790
+ publish_at: integer("publish_at", { mode: "timestamp" }),
1791
+ created_at: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
1792
+ updated_at: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`)
1793
+ },
1794
+ (table) => [unique("posts_author_slug_unique").on(table.author_id, table.slug)]
1795
+ );
1796
+ var blog_categories = sqliteTable(
1797
+ "blog_categories",
1798
+ {
1799
+ id: integer("id").primaryKey({ autoIncrement: true }),
1800
+ owner_id: text("owner_id").notNull(),
1801
+ name: text("name").notNull(),
1802
+ parent: text("parent").default("root")
1803
+ },
1804
+ (table) => [unique("categories_owner_name_unique").on(table.owner_id, table.name)]
1805
+ );
1806
+ var blog_tags = sqliteTable(
1807
+ "blog_tags",
1808
+ {
1809
+ post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1810
+ tag: text("tag").notNull()
1811
+ },
1812
+ (table) => [primaryKey({ columns: [table.post_id, table.tag] })]
1813
+ );
1778
1814
  var blog_integrations = sqliteTable("blog_integrations", {
1779
1815
  id: integer("id").primaryKey({ autoIncrement: true }),
1780
1816
  user_id: text("user_id").notNull(),
@@ -1785,17 +1821,25 @@ var blog_integrations = sqliteTable("blog_integrations", {
1785
1821
  status: text("status").default("pending"),
1786
1822
  created_at: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`)
1787
1823
  });
1788
- var blog_fetch_links = sqliteTable("blog_fetch_links", {
1789
- id: integer("id").primaryKey({ autoIncrement: true }),
1790
- post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1791
- integration_id: integer("integration_id").notNull().references(() => blog_integrations.id, { onDelete: "cascade" }),
1792
- identifier: text("identifier").notNull()
1793
- }, (table) => [unique("fetch_links_integration_identifier_unique").on(table.integration_id, table.identifier)]);
1794
- var blog_post_projects = sqliteTable("blog_post_projects", {
1795
- post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1796
- project_id: text("project_id").notNull(),
1797
- created_at: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`)
1798
- }, (table) => [primaryKey({ columns: [table.post_id, table.project_id] })]);
1824
+ var blog_fetch_links = sqliteTable(
1825
+ "blog_fetch_links",
1826
+ {
1827
+ id: integer("id").primaryKey({ autoIncrement: true }),
1828
+ post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1829
+ integration_id: integer("integration_id").notNull().references(() => blog_integrations.id, { onDelete: "cascade" }),
1830
+ identifier: text("identifier").notNull()
1831
+ },
1832
+ (table) => [unique("fetch_links_integration_identifier_unique").on(table.integration_id, table.identifier)]
1833
+ );
1834
+ var blog_post_projects = sqliteTable(
1835
+ "blog_post_projects",
1836
+ {
1837
+ post_id: integer("post_id").notNull().references(() => blog_posts.id, { onDelete: "cascade" }),
1838
+ project_id: text("project_id").notNull(),
1839
+ created_at: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`)
1840
+ },
1841
+ (table) => [primaryKey({ columns: [table.post_id, table.project_id] })]
1842
+ );
1799
1843
 
1800
1844
  // src/tools.ts
1801
1845
  import { z as z2 } from "zod";