@clowdops/tsclient 0.6.6 → 0.6.8

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
@@ -1,3 +1,109 @@
1
+ // src/modules/realEstateAdmin/RealEstateAdminClient.ts
2
+ function validInspectionReason(value) {
3
+ const reason = value.trim();
4
+ return reason.length > 0 && new TextEncoder().encode(reason).length <= 512 && !/\p{Cc}/u.test(reason) && !Array.from(reason).some((c) => /^[\uD800-\uDFFF]$/.test(c));
5
+ }
6
+ var root = "/admin/clowd-realestate/projects";
7
+ var projectPath = (id) => `${root}/${encodeURIComponent(id)}/offices`;
8
+ var conversationsPath = (scope) => `${projectPath(scope.projectId)}/${encodeURIComponent(scope.sandboxId)}/conversations`;
9
+ var allowancePath = (t) => `/admin/clowd-realestate/allowance/orgs/${encodeURIComponent(t.orgId)}/projects/${encodeURIComponent(t.projectId)}/offices/${encodeURIComponent(t.sandboxId)}`;
10
+ var canonicalUUIDv4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11
+ var RealEstateAdminClient = class {
12
+ constructor(http) {
13
+ this.http = http;
14
+ }
15
+ async read(path2, request, query = {}, expected = {}) {
16
+ if (!request.orgId || !validInspectionReason(request.reason)) throw new Error("Invalid inspection context or reason");
17
+ const response = await this.http.get(path2, {
18
+ query,
19
+ signal: request.signal,
20
+ sensitive: true,
21
+ headers: { "X-Impersonate-Org-Id": request.orgId, "X-Inspection-Reason": encodeURIComponent(request.reason.trim()) }
22
+ });
23
+ const data = response?.data;
24
+ const scope = data;
25
+ if (response?.success !== true || !data || data.schema !== "realestate.admin.v1" || data.source !== "inmoqueen-realestate" || data.org_id !== request.orgId || expected.projectId && scope.project_id !== expected.projectId || expected.sandboxId && scope.sandbox_id !== expected.sandboxId || expected.sessionId && (scope.session_id ?? scope.conversation?.session_id) !== expected.sessionId) {
26
+ throw new Error("RealEstate inspection response does not match the requested scope");
27
+ }
28
+ request.signal?.throwIfAborted();
29
+ return data;
30
+ }
31
+ projects(request, paging = {}) {
32
+ return this.read(root, request, { cursor: paging.cursor, limit: paging.limit });
33
+ }
34
+ offices(request, projectId, paging = {}) {
35
+ return this.read(projectPath(projectId), request, { cursor: paging.cursor, limit: paging.limit }, { projectId });
36
+ }
37
+ conversations(scope, filters = {}) {
38
+ return this.read(conversationsPath(scope), scope, {
39
+ actor_id: filters.actorId,
40
+ session_id: filters.sessionId,
41
+ correlation_id: filters.correlationId,
42
+ from: filters.from,
43
+ to: filters.to,
44
+ status: filters.status,
45
+ cursor: filters.cursor,
46
+ limit: filters.limit
47
+ }, scope);
48
+ }
49
+ conversation(scope, sessionId, options = {}) {
50
+ return this.read(
51
+ `${conversationsPath(scope)}/${encodeURIComponent(sessionId)}`,
52
+ scope,
53
+ { messages_cursor: options.messagesCursor, limit: options.limit },
54
+ { ...scope, sessionId }
55
+ );
56
+ }
57
+ debug(scope, sessionId, options = {}) {
58
+ return this.read(`${conversationsPath(scope)}/${encodeURIComponent(sessionId)}/debug`, scope, {
59
+ operations_cursor: options.operationsCursor,
60
+ attempts_cursor: options.attemptsCursor,
61
+ audit_cursor: options.auditCursor,
62
+ artifacts_cursor: options.artifactsCursor,
63
+ approvals_cursor: options.approvalsCursor,
64
+ receipts_cursor: options.receiptsCursor,
65
+ limit: options.limit
66
+ }, { ...scope, sessionId });
67
+ }
68
+ checkAllowance(target, response) {
69
+ const data = response?.data;
70
+ if (response?.success !== true || !data || data.schema !== "realestate.allowance.v1" || data.org_id !== target.orgId || data.project_id !== target.projectId || data.sandbox_id !== target.sandboxId || data.allowance?.allowance_ref !== `realestate:office:${target.sandboxId}`) {
71
+ throw new Error("RealEstate allowance response does not match the requested Office");
72
+ }
73
+ target.signal?.throwIfAborted();
74
+ return data;
75
+ }
76
+ /** Reads one Office allowance (audited with the inspection reason). */
77
+ async allowance(target) {
78
+ if (!target.orgId || !validInspectionReason(target.reason)) throw new Error("Invalid allowance context or reason");
79
+ const response = await this.http.get(allowancePath(target), {
80
+ signal: target.signal,
81
+ sensitive: true,
82
+ skipImpersonation: true,
83
+ headers: { "X-Inspection-Reason": encodeURIComponent(target.reason.trim()) }
84
+ });
85
+ return this.checkAllowance(target, response);
86
+ }
87
+ /**
88
+ * Changes one Office allowance at an expected revision. A stale revision is
89
+ * an HTTP 409; resending the same commandId recovers a lost reply.
90
+ */
91
+ async changeAllowance(target, change) {
92
+ if (!target.orgId || !canonicalUUIDv4.test(change.commandId) || !Number.isSafeInteger(change.expectedRevision) || change.expectedRevision < 0 || !validInspectionReason(change.reason)) {
93
+ throw new Error("Invalid allowance change");
94
+ }
95
+ const response = await this.http.post(allowancePath(target), {
96
+ signal: target.signal,
97
+ sensitive: true,
98
+ skipImpersonation: true,
99
+ body: { command_id: change.commandId, expected_revision: change.expectedRevision, reason: change.reason.trim(), limits: change.limits }
100
+ });
101
+ const data = this.checkAllowance(target, response);
102
+ if (data.allowance.command_id !== change.commandId) throw new Error("RealEstate allowance response does not match the command");
103
+ return data;
104
+ }
105
+ };
106
+
1
107
  // src/http/HttpError.ts
2
108
  var HttpError = class extends Error {
3
109
  constructor(status, statusText, body) {
@@ -11,10 +117,13 @@ var HttpError = class extends Error {
11
117
  this.body = body;
12
118
  }
13
119
  };
120
+ var ERROR_CODE_KEYS = ["error_code", "errorCode", "code", "refusal"];
14
121
  function extractErrorCode(body) {
15
122
  if (body && typeof body === "object") {
16
- const code = body.error_code ?? body.errorCode ?? body.code;
17
- if (typeof code === "string") return code;
123
+ for (const key of ERROR_CODE_KEYS) {
124
+ const code = body[key];
125
+ if (typeof code === "string") return code;
126
+ }
18
127
  }
19
128
  return null;
20
129
  }
@@ -45,29 +154,29 @@ var BaseClient = class {
45
154
  this.getImpersonateOrgId = options.getImpersonateOrgId;
46
155
  this.credentials = options.credentials ?? "include";
47
156
  }
48
- get(path, options) {
49
- return this.request("GET", path, options);
157
+ get(path2, options) {
158
+ return this.request("GET", path2, options);
50
159
  }
51
- post(path, options) {
52
- return this.request("POST", path, options);
160
+ post(path2, options) {
161
+ return this.request("POST", path2, options);
53
162
  }
54
- put(path, options) {
55
- return this.request("PUT", path, options);
163
+ put(path2, options) {
164
+ return this.request("PUT", path2, options);
56
165
  }
57
- patch(path, options) {
58
- return this.request("PATCH", path, options);
166
+ patch(path2, options) {
167
+ return this.request("PATCH", path2, options);
59
168
  }
60
- delete(path, options) {
61
- return this.request("DELETE", path, options);
169
+ delete(path2, options) {
170
+ return this.request("DELETE", path2, options);
62
171
  }
63
- async request(method, path, options = {}, retrying = false) {
64
- const url = this.buildUrl(path, options.query);
172
+ async request(method, path2, options = {}, retrying = false) {
173
+ const url = this.buildUrl(path2, options.query);
65
174
  const headers = { ...this.defaultHeaders, ...options.headers ?? {} };
66
175
  if (!options.skipAuth && this.getToken) {
67
176
  const token = await this.getToken();
68
177
  if (token) headers["Authorization"] = `Bearer ${token}`;
69
178
  }
70
- if (!options.skipAuth && this.getImpersonateOrgId && !("X-Impersonate-Org-Id" in headers) && !("x-impersonate-org-id" in headers)) {
179
+ if (!options.skipAuth && !options.skipImpersonation && this.getImpersonateOrgId && !("X-Impersonate-Org-Id" in headers) && !("x-impersonate-org-id" in headers)) {
71
180
  const target = await this.getImpersonateOrgId();
72
181
  if (target) headers["X-Impersonate-Org-Id"] = target;
73
182
  }
@@ -82,10 +191,11 @@ var BaseClient = class {
82
191
  body = JSON.stringify(options.body);
83
192
  }
84
193
  }
85
- if (this.debug) {
194
+ if (this.debug && !options.sensitive) {
86
195
  console.debug("[clowdops/tsclient] \u2192", method, url, options.body ?? "");
87
196
  }
88
- const res = await this.fetchImpl(url, { method, headers, body, credentials: this.credentials });
197
+ const res = await this.fetchImpl(url, { method, headers, body, credentials: this.credentials, signal: options.signal });
198
+ if (res.ok && options.blob) return await res.blob();
89
199
  let parsed = null;
90
200
  const text = await res.text();
91
201
  if (text.length > 0) {
@@ -95,7 +205,7 @@ var BaseClient = class {
95
205
  parsed = text;
96
206
  }
97
207
  }
98
- if (this.debug) {
208
+ if (this.debug && !options.sensitive) {
99
209
  console.debug("[clowdops/tsclient] \u2190", res.status, url, parsed);
100
210
  }
101
211
  if (!res.ok) {
@@ -106,15 +216,15 @@ var BaseClient = class {
106
216
  } catch {
107
217
  }
108
218
  if (refreshed) {
109
- return this.request(method, path, options, true);
219
+ return this.request(method, path2, options, true);
110
220
  }
111
221
  }
112
222
  throw new HttpError(res.status, res.statusText, parsed);
113
223
  }
114
224
  return parsed;
115
225
  }
116
- buildUrl(path, query) {
117
- const base = path.startsWith("http") ? path : `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
226
+ buildUrl(path2, query) {
227
+ const base = path2.startsWith("http") ? path2 : `${this.baseUrl}${path2.startsWith("/") ? path2 : `/${path2}`}`;
118
228
  if (!query) return base;
119
229
  const params = new URLSearchParams();
120
230
  for (const [key, value] of Object.entries(query)) {
@@ -396,122 +506,2357 @@ var OrganizationClient = class {
396
506
  cancelOrgInvite(userId) {
397
507
  return this.http.post(`/admin/org-invites/${userId}/cancel`, {});
398
508
  }
399
- /**
400
- * Platform-admin only: enable or disable the debug surface for an org.
401
- * Returns the updated org entry with the new allowDebug value.
402
- */
403
- async setAllowDebug(orgId, allow) {
404
- const res = await this.http.patch(`/orgs/${orgId}/allow-debug`, { body: { allow } });
405
- return res.data;
509
+ /**
510
+ * Platform-admin only: enable or disable the debug surface for an org.
511
+ * Returns the updated org entry with the new allowDebug value.
512
+ */
513
+ async setAllowDebug(orgId, allow) {
514
+ const res = await this.http.patch(`/orgs/${orgId}/allow-debug`, { body: { allow } });
515
+ return res.data;
516
+ }
517
+ /**
518
+ * Platform-admin only: replace an org's product entitlement. `products` is
519
+ * the full desired set ('cloud' | 'bi'); unknown codes are rejected 400.
520
+ * Returns the updated org's id, name and enabledProducts.
521
+ */
522
+ async setEnabledProducts(orgId, products) {
523
+ const res = await this.http.patch(`/orgs/${orgId}/enabled-products`, { body: { products } });
524
+ return res.data;
525
+ }
526
+ /**
527
+ * Platform-admin only: add a new member to an existing org.
528
+ * Creates the user without a password and sends an invite email via the
529
+ * same TokenOrgInvite flow as the regular member invite.
530
+ * Returns 403 unless platform admin; 409 when the email already exists.
531
+ */
532
+ async addUserToOrg(orgId, body) {
533
+ const res = await this.http.post(
534
+ `/orgs/${orgId}/users`,
535
+ { body }
536
+ );
537
+ return unwrapData(res);
538
+ }
539
+ /**
540
+ * Platform-admin only: fetch an org's two-bucket credit balance.
541
+ * Returns 403 unless platform admin; 404 when the org doesn't exist.
542
+ */
543
+ async getOrgCreditBalance(orgId) {
544
+ const res = await this.http.get(
545
+ `/orgs/${orgId}/credits`
546
+ );
547
+ return unwrapData(res);
548
+ }
549
+ /**
550
+ * Platform-admin only: grant or revoke credits on an org.
551
+ * amountMicros is signed: positive = grant, negative = revoke.
552
+ * Records a CreditKindAdminAdjust ledger entry and returns the updated balance.
553
+ */
554
+ async adjustOrgCredits(orgId, body) {
555
+ const res = await this.http.post(
556
+ `/orgs/${orgId}/credits/adjust`,
557
+ { body }
558
+ );
559
+ return unwrapData(res);
560
+ }
561
+ };
562
+
563
+ // src/modules/projects/types.ts
564
+ var PRODUCT_KINDS = ["cloud", "bi", "meeting", "marketing", "pm", "startup", "realestate"];
565
+ function isProductKind(value) {
566
+ return typeof value === "string" && PRODUCT_KINDS.includes(value);
567
+ }
568
+ function newProjectRequestKey() {
569
+ const webcrypto = globalThis.crypto;
570
+ if (typeof webcrypto?.randomUUID === "function") return webcrypto.randomUUID();
571
+ return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
572
+ }
573
+ var PM_RECORD_FAMILIES = [
574
+ "tailoring",
575
+ "phase_gate",
576
+ "baseline",
577
+ "deliverable",
578
+ "wbs_node",
579
+ "activity",
580
+ "decision",
581
+ "action",
582
+ "risk",
583
+ "stakeholder",
584
+ "issue",
585
+ "assumption",
586
+ "communication"
587
+ ];
588
+ function isPmRecordFamily(value) {
589
+ return typeof value === "string" && value.trim().length > 0;
590
+ }
591
+ var PM_ORIGINS = ["human", "extracted", "delegated"];
592
+ function isPmOrigin(value) {
593
+ return typeof value === "string" && PM_ORIGINS.includes(value);
594
+ }
595
+ var PM_RECIPIENT_NOT_REGISTERED = "recipient-not-registered";
596
+ var PM_RISK_RESPONSE_TYPES = [
597
+ "avoid",
598
+ "mitigate",
599
+ "transfer",
600
+ "escalate",
601
+ "accept",
602
+ "exploit",
603
+ "enhance",
604
+ "share"
605
+ ];
606
+ function isPmRiskResponseType(value) {
607
+ return typeof value === "string" && PM_RISK_RESPONSE_TYPES.includes(value);
608
+ }
609
+ var PM_RISK_RESPONSE_STATES = ["proposed", "accepted", "rejected", "superseded"];
610
+ function isPmRiskResponseState(value) {
611
+ return typeof value === "string" && PM_RISK_RESPONSE_STATES.includes(value);
612
+ }
613
+
614
+ // src/adapters/projectAdapter.ts
615
+ var projectAdapter = {
616
+ fromListResponse(payload) {
617
+ const list = payload?.workspaces ?? payload?.projects ?? [];
618
+ return list.filter((wire) => wire.product == null || isProductKind(wire.product)).map(normalize);
619
+ },
620
+ fromGetResponse(payload) {
621
+ const wire = payload;
622
+ const value = wire?.workspace ?? wire?.project ?? wire?.data;
623
+ if (!value) throw new Error("Project response missing body.");
624
+ return normalize(value);
625
+ },
626
+ normalize
627
+ };
628
+ function normalize(wire) {
629
+ const product = normalizeProduct(wire.product);
630
+ return {
631
+ id: wire.id,
632
+ name: wire.name,
633
+ orgId: wire.orgId,
634
+ default: wire.default ?? false,
635
+ isReferenceProject: wire.isReferenceProject ?? false,
636
+ preferredAiProvider: wire.preferredAiProvider ?? null,
637
+ product,
638
+ users: wire.users ?? []
639
+ };
640
+ }
641
+ function normalizeProduct(raw) {
642
+ if (raw == null) return "cloud";
643
+ if (isProductKind(raw)) return raw;
644
+ throw new Error(`Unsupported project product ${JSON.stringify(raw)}.`);
645
+ }
646
+
647
+ // src/modules/projects/pm/common.ts
648
+ var MONEY_AMOUNT = /^-?\d{1,30}$/;
649
+ var DECIMAL = /^-?\d{1,30}(\.\d{1,12})?$/;
650
+ function isPmMoney(value) {
651
+ if (!value || typeof value !== "object") return false;
652
+ const m = value;
653
+ return typeof m.currency === "string" && /^[A-Z]{3}$/.test(m.currency) && Number.isInteger(m.minorUnitScale) && m.minorUnitScale >= 0 && m.minorUnitScale <= 4 && typeof m.minorAmount === "string" && MONEY_AMOUNT.test(m.minorAmount);
654
+ }
655
+ function isPmDecimal(value) {
656
+ return typeof value === "string" && DECIMAL.test(value);
657
+ }
658
+ var PM_ERROR_CODES = [
659
+ "invalid_input",
660
+ "not_found",
661
+ "forbidden",
662
+ "unsupported_mode",
663
+ "human_act_required",
664
+ "act_mismatch",
665
+ "revision_conflict",
666
+ "idempotency_conflict",
667
+ "stale_snapshot",
668
+ "typed_operation_required",
669
+ "decision_not_permitted",
670
+ "limit_exceeded",
671
+ "capability_limitation",
672
+ "horizon_exceeded",
673
+ "typed_writes_disabled",
674
+ "unavailable",
675
+ /** Permanent: ClowdPM is off for the org or project (unlike the transient `unavailable`). */
676
+ "component_disabled",
677
+ "last_manager",
678
+ "use_change_process",
679
+ "project_closed",
680
+ /** Permanent for a delegate: no standing delivery authority covers the send, so a person approves it. */
681
+ "standing_authority_absent",
682
+ /** A new send intent whose original outcome is unknown: `details` is the disclosure plan; resend with the acknowledgement. */
683
+ "duplicate_acknowledgement_required",
684
+ /** A new communication of bytes an earlier send already holds for a recipient: `details` names it; send that one again (`resendMode: 'new_intent'`). */
685
+ "resend_intent_required",
686
+ /** Transient for an operator: the action engine cannot confirm a deliberate resend as its own delivery (deploy the engine first); nothing was sent. */
687
+ "engine_upgrade_required"
688
+ ];
689
+ function isPmErrorCode(value) {
690
+ return typeof value === "string" && PM_ERROR_CODES.includes(value);
691
+ }
692
+ function pmErrorOf(err) {
693
+ if (!(err instanceof HttpError) || !isPmErrorCode(err.errorCode)) return void 0;
694
+ const body = err.body && typeof err.body === "object" ? err.body : {};
695
+ const out = { status: err.status, code: err.errorCode, message: err.message };
696
+ if (body.current !== void 0) out.current = body.current;
697
+ if (body.details !== void 0) out.details = body.details;
698
+ return out;
699
+ }
700
+ var PM_OBJECT_KINDS = [
701
+ "record",
702
+ "proposal",
703
+ "risk_response",
704
+ "document",
705
+ "disposition_request",
706
+ "report_version",
707
+ "export",
708
+ "analysis",
709
+ "operation",
710
+ "decision",
711
+ "result_set",
712
+ "coordination"
713
+ ];
714
+ function isPmObjectKind(value) {
715
+ return typeof value === "string" && PM_OBJECT_KINDS.includes(value);
716
+ }
717
+ var PM_OPERATION_OUTCOMES = [
718
+ "admitted",
719
+ "awaiting_decision",
720
+ "completed",
721
+ "partially_completed",
722
+ "blocked",
723
+ "refused",
724
+ "conflicted",
725
+ "unknown",
726
+ "expired"
727
+ ];
728
+ function isPmOperationOutcome(value) {
729
+ return typeof value === "string" && PM_OPERATION_OUTCOMES.includes(value);
730
+ }
731
+ var PM_DECISION_KINDS = [
732
+ "record_proposal",
733
+ "charter",
734
+ "baseline",
735
+ "budget",
736
+ "ownership",
737
+ "risk_response",
738
+ "change",
739
+ "acceptance",
740
+ "exception",
741
+ "handover",
742
+ "closure",
743
+ "reopen",
744
+ "coordination_item",
745
+ "communication",
746
+ "disposition"
747
+ ];
748
+ function isPmDecisionKind(value) {
749
+ return typeof value === "string" && PM_DECISION_KINDS.includes(value);
750
+ }
751
+ var PmApiBase = class {
752
+ constructor(http) {
753
+ this.http = http;
754
+ }
755
+ /** `/project/:id/pm/<segments>`, each segment encoded; throws on a blank segment. */
756
+ path(projectId, ...segments) {
757
+ for (const s of [projectId, ...segments]) {
758
+ if (typeof s !== "string" || !s.trim()) throw new Error("PM request ids must be non-blank.");
759
+ }
760
+ return ["/project", encodeURIComponent(projectId), "pm", ...segments.map(encodeURIComponent)].join("/");
761
+ }
762
+ };
763
+ function operationOf(raw) {
764
+ return {
765
+ ...raw,
766
+ outcome: isPmOperationOutcome(raw.outcome) ? raw.outcome : "unknown",
767
+ nativeRefs: raw.nativeRefs ?? [],
768
+ pendingObligationRefs: raw.pendingObligationRefs ?? []
769
+ };
770
+ }
771
+ var PmCommonApi = class extends PmApiBase {
772
+ /** `pm.object.read`: the current head, or the exact `revision` when given. */
773
+ async readObject(projectId, kind, objectId, options = {}) {
774
+ if (!isPmObjectKind(kind)) throw new Error(`Unsupported PM object kind: ${String(kind)}.`);
775
+ if (options.revision !== void 0 && !options.revision.trim()) {
776
+ throw new Error("A requested revision must be non-blank.");
777
+ }
778
+ return this.http.get(this.path(projectId, "objects", kind, objectId), {
779
+ query: { revision: options.revision }
780
+ });
781
+ }
782
+ /** `pm.object.history`: one bounded page (≤50), newest first. */
783
+ async objectHistory(projectId, kind, objectId, options = {}) {
784
+ if (!isPmObjectKind(kind)) throw new Error(`Unsupported PM object kind: ${String(kind)}.`);
785
+ const { cursor, limit } = options;
786
+ if (limit !== void 0 && !(Number.isInteger(limit) && limit >= 1 && limit <= 50)) {
787
+ throw new Error("A history page limit must be an integer between 1 and 50.");
788
+ }
789
+ const res = await this.http.get(this.path(projectId, "objects", kind, objectId, "history"), {
790
+ query: { cursor, limit }
791
+ });
792
+ return { items: res.items ?? [], cursor: res.cursor ?? null };
793
+ }
794
+ /** `pm.operation.inspect` by operation id, or by operation name + the control request key. */
795
+ async inspectOperation(projectId, lookup) {
796
+ if ("operationId" in lookup) {
797
+ return operationOf(await this.http.get(this.path(projectId, "operations", lookup.operationId)));
798
+ }
799
+ if (!lookup.name?.trim() || !lookup.requestKey?.trim()) {
800
+ throw new Error("An operation lookup needs a name and a requestKey.");
801
+ }
802
+ return operationOf(
803
+ await this.http.get(this.path(projectId, "operations"), {
804
+ query: { name: lookup.name, requestKey: lookup.requestKey }
805
+ })
806
+ );
807
+ }
808
+ /** `pm.operation.reconcile`: rereads native references; never starts a new effect. */
809
+ async reconcileOperation(projectId, operationId) {
810
+ return operationOf(
811
+ await this.http.post(this.path(projectId, "operations", operationId, "reconcile"), { body: {} })
812
+ );
813
+ }
814
+ /** Pending decision candidates visible to the caller, with what the caller may decide. */
815
+ async pendingDecisions(projectId, options = {}) {
816
+ const res = await this.http.get(this.path(projectId, "decisions", "pending"), {
817
+ query: { cursor: options.cursor }
818
+ });
819
+ return {
820
+ items: (res.items ?? []).map((d) => ({ ...d, permittedDecisions: d.permittedDecisions ?? [] })),
821
+ cursor: res.cursor ?? null
822
+ };
823
+ }
824
+ /** `pm.proposal.inspect`: re-reads a record proposal under current authority. */
825
+ async getRecordProposal(projectId, proposalId) {
826
+ return this.http.get(this.path(projectId, "chat", "record-proposals", proposalId));
827
+ }
828
+ /** The operations this deployment currently advertises for the caller. */
829
+ async capabilities(projectId) {
830
+ const res = await this.http.get(this.path(projectId, "capabilities"));
831
+ return { ...res, operations: res.operations ?? [] };
832
+ }
833
+ /** The server family catalog, including each family's coverage area. */
834
+ async families(projectId) {
835
+ const res = await this.http.get(this.path(projectId, "families"));
836
+ return { families: res.families ?? [] };
837
+ }
838
+ };
839
+
840
+ // src/modules/projects/pm/planning.ts
841
+ var PM_ANALYSIS_STATES = ["calculated", "conditional", "invalid"];
842
+ function isPmAnalysisState(value) {
843
+ return typeof value === "string" && PM_ANALYSIS_STATES.includes(value);
844
+ }
845
+ var PM_APPROVAL_DECISIONS = ["approve", "reject"];
846
+ var MAX_KEY = 256;
847
+ var PmWriteApiBase = class extends PmApiBase {
848
+ /** The control request key: non-blank and at most 256 UTF-8 bytes (the server's bound). */
849
+ key(requestKey) {
850
+ if (typeof requestKey !== "string" || !requestKey.trim() || new TextEncoder().encode(requestKey).length > MAX_KEY) {
851
+ throw new Error("A PM write needs a non-blank requestKey of at most 256 bytes.");
852
+ }
853
+ return requestKey;
854
+ }
855
+ text(value, what) {
856
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-blank.`);
857
+ return value;
858
+ }
859
+ oneOf(value, allowed, what) {
860
+ if (!allowed.includes(value)) {
861
+ throw new Error(`Unsupported ${what}: ${String(value)}.`);
862
+ }
863
+ return value;
864
+ }
865
+ money(value, what) {
866
+ if (!isPmMoney(value)) throw new Error(`${what} must be PM money {currency, minorUnitScale, minorAmount: string}.`);
867
+ }
868
+ decimal(value, what) {
869
+ if (!isPmDecimal(value)) throw new Error(`${what} must be an exact decimal string.`);
870
+ }
871
+ minutes(value, what) {
872
+ if (value !== void 0 && value !== null && !Number.isSafeInteger(value)) {
873
+ throw new Error(`${what} must be a whole number of minutes.`);
874
+ }
875
+ }
876
+ /** A non-empty plain object: a typed patch never travels as a string or array. */
877
+ patch(value) {
878
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length === 0) {
879
+ throw new Error("A PM update needs a non-empty patch object.");
880
+ }
881
+ return value;
882
+ }
883
+ op(raw) {
884
+ return {
885
+ ...raw,
886
+ outcome: isPmOperationOutcome(raw.outcome) ? raw.outcome : "unknown",
887
+ nativeRefs: raw.nativeRefs ?? [],
888
+ pendingObligationRefs: raw.pendingObligationRefs ?? []
889
+ };
890
+ }
891
+ written(raw) {
892
+ return { ...raw, operation: this.op(raw.operation) };
893
+ }
894
+ decided(raw) {
895
+ return { ...this.written(raw), outcome: isPmOperationOutcome(raw.outcome) ? raw.outcome : "unknown" };
896
+ }
897
+ postDecision(path2, req, allowed, extra = {}) {
898
+ const body = {
899
+ expectedVersion: this.text(req.expectedVersion, "expectedVersion"),
900
+ decision: this.oneOf(req.decision, allowed, "decision"),
901
+ reason: req.reason,
902
+ ...extra,
903
+ requestKey: this.key(req.requestKey)
904
+ };
905
+ return this.http.post(path2, { body }).then((r) => this.decided(r));
906
+ }
907
+ };
908
+ var PM_WORK_FAMILIES = ["activity", "action", "deliverable", "wbs_node", "phase_gate"];
909
+ var PM_WORK_KINDS = ["task", "milestone", "deliverable", "summary", "gate"];
910
+ function isPmWorkKind(value) {
911
+ return typeof value === "string" && PM_WORK_KINDS.includes(value);
912
+ }
913
+ var PM_DEPENDENCY_RELATIONS = ["FS", "SS", "FF", "SF"];
914
+ var PM_AVAILABILITY_BASES = ["project_allocation", "person_capacity"];
915
+ var PM_EVIDENCE_SOURCE_KINDS = ["source-doc", "pm-evidence", "pm-record", "artifact-version"];
916
+ var WORK_CREATE_FAMILIES = [...PM_WORK_FAMILIES, "iteration"];
917
+ var PmPlanningApi = class extends PmWriteApiBase {
918
+ write(method, path2, body) {
919
+ return this.http.request(method, path2, { body }).then((r) => this.written(r));
920
+ }
921
+ update(projectId, segment2, recordId, req) {
922
+ return this.write("PATCH", this.path(projectId, segment2, recordId), {
923
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
924
+ patch: this.patch(req.patch),
925
+ requestKey: this.key(req.requestKey)
926
+ });
927
+ }
928
+ calculate(projectId, segment2, req) {
929
+ const { horizonDays } = req;
930
+ if (horizonDays !== void 0 && !(Number.isInteger(horizonDays) && horizonDays >= 1 && horizonDays <= 3650)) {
931
+ throw new Error("horizonDays must be an integer between 1 and 3650.");
932
+ }
933
+ const body = { asOf: req.asOf, horizonDays, requestKey: this.key(req.requestKey) };
934
+ return this.http.post(this.path(projectId, segment2, "calculations"), { body }).then((r) => this.written(r));
935
+ }
936
+ /** `pm.work.create` → `POST work`. */
937
+ async createWork(projectId, req) {
938
+ const family = this.oneOf(req.family, WORK_CREATE_FAMILIES, "work family");
939
+ const body = { family, proposedOwnerContactId: req.proposedOwnerContactId };
940
+ if ("iteration" in req && family === "iteration") {
941
+ this.text(req.iteration?.name, "An iteration name");
942
+ body.iteration = req.iteration;
943
+ } else if ("work" in req && family !== "iteration") {
944
+ this.oneOf(req.work?.kind, PM_WORK_KINDS, "work kind");
945
+ this.text(req.work.title, "A work title");
946
+ this.minutes(req.work.totalDurationMin, "totalDurationMin");
947
+ this.minutes(req.work.totalEffortMin, "totalEffortMin");
948
+ body.work = req.work;
949
+ } else {
950
+ throw new Error("A work family takes `work`; the iteration family takes `iteration`.");
951
+ }
952
+ body.requestKey = this.key(req.requestKey);
953
+ return this.write("POST", this.path(projectId, "work"), body);
954
+ }
955
+ /** `pm.work.update` → `PATCH work/:recordId`. */
956
+ async updateWork(projectId, recordId, req) {
957
+ return this.update(projectId, "work", recordId, req);
958
+ }
959
+ /** `pm.work.retire` → `POST work/:recordId/retire` (refused while dependents or obligations remain). */
960
+ async retireWork(projectId, recordId, req) {
961
+ return this.write("POST", this.path(projectId, "work", recordId, "retire"), {
962
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
963
+ requestKey: this.key(req.requestKey)
964
+ });
965
+ }
966
+ /** `pm.progress.record` → `POST work/:recordId/progress`. Actuals never rewrite a baseline. */
967
+ async recordProgress(projectId, recordId, req) {
968
+ const patch = this.patch(req.patch);
969
+ if (patch.percentComplete != null) this.decimal(patch.percentComplete, "percentComplete");
970
+ if (req.source) this.oneOf(req.source.kind, PM_EVIDENCE_SOURCE_KINDS, "progress source kind");
971
+ return this.write("POST", this.path(projectId, "work", recordId, "progress"), {
972
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
973
+ patch,
974
+ source: req.source,
975
+ requestKey: this.key(req.requestKey)
976
+ });
977
+ }
978
+ /** `pm.dependency.set` → `PUT dependencies`. */
979
+ async setDependency(projectId, req) {
980
+ this.minutes(req.lagMinutes, "lagMinutes");
981
+ return this.write("PUT", this.path(projectId, "dependencies"), {
982
+ recordId: req.recordId,
983
+ expectedRevisionId: req.expectedRevisionId,
984
+ predecessorRecordId: this.text(req.predecessorRecordId, "predecessorRecordId"),
985
+ predecessorProjectId: req.predecessorProjectId,
986
+ predecessorRevisionId: req.predecessorRevisionId,
987
+ successorRecordId: this.text(req.successorRecordId, "successorRecordId"),
988
+ successorRevisionId: req.successorRevisionId,
989
+ relation: this.oneOf(req.relation, PM_DEPENDENCY_RELATIONS, "dependency relation"),
990
+ lagMinutes: req.lagMinutes ?? 0,
991
+ requestKey: this.key(req.requestKey)
992
+ });
993
+ }
994
+ /** `pm.dependency.remove` → `POST dependencies/:recordId/remove` (retires the relation). */
995
+ async removeDependency(projectId, recordId, req) {
996
+ return this.write("POST", this.path(projectId, "dependencies", recordId, "remove"), {
997
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
998
+ requestKey: this.key(req.requestKey)
999
+ });
1000
+ }
1001
+ /** `pm.calendar.create` → `POST calendars`. */
1002
+ async createCalendar(projectId, req) {
1003
+ if (!Array.isArray(req.weekly)) throw new Error("A calendar declares its weekly working intervals.");
1004
+ return this.write("POST", this.path(projectId, "calendars"), {
1005
+ title: this.text(req.title, "A calendar title"),
1006
+ timezone: this.text(req.timezone, "A calendar timezone"),
1007
+ standardDayMinutes: req.standardDayMinutes,
1008
+ weekly: req.weekly,
1009
+ exceptions: req.exceptions,
1010
+ requestKey: this.key(req.requestKey)
1011
+ });
1012
+ }
1013
+ /** `pm.calendar.update` → `PATCH calendars/:recordId`. */
1014
+ async updateCalendar(projectId, recordId, req) {
1015
+ return this.update(projectId, "calendars", recordId, req);
1016
+ }
1017
+ /** `pm.availability.set` → `PUT availability`. */
1018
+ async setAvailability(projectId, req) {
1019
+ if (!req.minutesByDate && !req.recurring) {
1020
+ throw new Error("Declare minutesByDate or a recurring weekly allowance; nothing is assumed.");
1021
+ }
1022
+ if (!req.recordId) this.text(req.contactId, "A new availability contactId");
1023
+ return this.write("PUT", this.path(projectId, "availability"), {
1024
+ recordId: req.recordId,
1025
+ expectedRevisionId: req.expectedRevisionId,
1026
+ contactId: req.contactId,
1027
+ calendarRecordId: req.calendarRecordId,
1028
+ effectiveFrom: this.text(req.effectiveFrom, "effectiveFrom"),
1029
+ effectiveToExclusive: req.effectiveToExclusive,
1030
+ basis: this.oneOf(req.basis, PM_AVAILABILITY_BASES, "availability basis"),
1031
+ source: this.text(req.source, "An availability source"),
1032
+ minutesByDate: req.minutesByDate,
1033
+ recurring: req.recurring,
1034
+ requestKey: this.key(req.requestKey)
1035
+ });
1036
+ }
1037
+ /** `pm.assignment.create` → `POST assignments`. */
1038
+ async createAssignment(projectId, req) {
1039
+ this.minutes(req.dailyDemandMin, "dailyDemandMin");
1040
+ this.minutes(req.totalEffortMin, "totalEffortMin");
1041
+ return this.write("POST", this.path(projectId, "assignments"), {
1042
+ workRecordId: this.text(req.workRecordId, "workRecordId"),
1043
+ contactId: this.text(req.contactId, "contactId"),
1044
+ intervalStart: req.intervalStart,
1045
+ intervalEndExclusive: req.intervalEndExclusive,
1046
+ dailyDemandMin: req.dailyDemandMin,
1047
+ totalEffortMin: req.totalEffortMin,
1048
+ requestKey: this.key(req.requestKey)
1049
+ });
1050
+ }
1051
+ /** `pm.assignment.update` → `PATCH assignments/:recordId` (interval and demand only). */
1052
+ async updateAssignment(projectId, recordId, req) {
1053
+ return this.update(projectId, "assignments", recordId, req);
1054
+ }
1055
+ /** `pm.plan.calculate` → `POST plan/calculations` (`pm.schedule.v1` over a pinned snapshot). */
1056
+ async calculatePlan(projectId, req) {
1057
+ return this.calculate(projectId, "plan", req);
1058
+ }
1059
+ /** `pm.capacity.calculate` → `POST capacity/calculations` (`pm.capacity.v1`). */
1060
+ async calculateCapacity(projectId, req) {
1061
+ return this.calculate(projectId, "capacity", req);
1062
+ }
1063
+ /** `pm.baseline.prepare` → `POST baselines`. A stale analysis is refused with `stale_snapshot`. */
1064
+ async prepareBaseline(projectId, req) {
1065
+ return this.write("POST", this.path(projectId, "baselines"), {
1066
+ analysisId: this.text(req.analysisId, "analysisId"),
1067
+ rationale: req.rationale,
1068
+ acceptedConditions: req.acceptedConditions,
1069
+ requestKey: this.key(req.requestKey)
1070
+ });
1071
+ }
1072
+ /** `pm.baseline.decide` → `POST baselines/:recordId/decision` (designated baseline approver, else the PM). */
1073
+ async decideBaseline(projectId, recordId, req) {
1074
+ return this.postDecision(this.path(projectId, "baselines", recordId, "decision"), req, PM_APPROVAL_DECISIONS);
1075
+ }
1076
+ };
1077
+
1078
+ // src/modules/projects/pm/acceptance.ts
1079
+ var PM_REQUIREMENT_PRIORITIES = ["must", "should", "could", "wont"];
1080
+ var PM_REQUIREMENT_SCOPE_STATUSES = ["in_scope", "proposed", "removed"];
1081
+ var PM_CRITERION_CHECK_METHODS = ["test", "inspection", "demonstration", "analysis", "review"];
1082
+ var PM_CRITERION_COMPARATORS = ["lt", "le", "eq", "ge", "gt", "between"];
1083
+ var PM_CRITERION_EXCEPTION_POLICIES = ["none", "permitted_with_reason"];
1084
+ var PM_CRITERION_REVIEWER_RULES = ["pm", "sponsor", "designated_acceptor"];
1085
+ var PM_VERIFICATION_RESULTS = ["pass", "fail", "unknown"];
1086
+ var PM_DEFECT_SEVERITIES = ["low", "medium", "high", "critical"];
1087
+ var PM_DEFECT_STATES = ["open", "fixed", "verified", "wont_fix"];
1088
+ var PM_ACCEPTANCE_STATES = [
1089
+ "not_submitted",
1090
+ "awaiting_decision",
1091
+ "accepted",
1092
+ "accepted_with_exception",
1093
+ "rejected"
1094
+ ];
1095
+ function isPmAcceptanceState(value) {
1096
+ return typeof value === "string" && PM_ACCEPTANCE_STATES.includes(value);
1097
+ }
1098
+ var PM_ACCEPTANCE_DECISIONS = ["accept", "reject"];
1099
+ var PmAcceptanceApi = class extends PmWriteApiBase {
1100
+ write(method, path2, body) {
1101
+ return this.http.request(method, path2, { body }).then((r) => this.written(r));
1102
+ }
1103
+ update(projectId, segment2, recordId, req) {
1104
+ return this.write("PATCH", this.path(projectId, segment2, recordId), {
1105
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1106
+ patch: this.patch(req.patch),
1107
+ requestKey: this.key(req.requestKey)
1108
+ });
1109
+ }
1110
+ criterion(c) {
1111
+ if (c.checkMethod !== void 0) this.oneOf(c.checkMethod, PM_CRITERION_CHECK_METHODS, "check method");
1112
+ if (c.comparator != null) this.oneOf(c.comparator, PM_CRITERION_COMPARATORS, "comparator");
1113
+ if (c.exceptionPolicy !== void 0) this.oneOf(c.exceptionPolicy, PM_CRITERION_EXCEPTION_POLICIES, "exception policy");
1114
+ if (c.reviewerRule !== void 0) this.oneOf(c.reviewerRule, PM_CRITERION_REVIEWER_RULES, "reviewer rule");
1115
+ if (c.threshold != null) this.decimal(c.threshold, "threshold");
1116
+ if (c.thresholdUpper != null) this.decimal(c.thresholdUpper, "thresholdUpper");
1117
+ }
1118
+ /** `pm.requirement.create` → `POST requirements`. */
1119
+ async createRequirement(projectId, req) {
1120
+ if (req.priority !== void 0) this.oneOf(req.priority, PM_REQUIREMENT_PRIORITIES, "priority");
1121
+ if (req.scopeStatus !== void 0) this.oneOf(req.scopeStatus, PM_REQUIREMENT_SCOPE_STATUSES, "scope status");
1122
+ return this.write("POST", this.path(projectId, "requirements"), {
1123
+ statement: this.text(req.statement, "A requirement statement"),
1124
+ rationale: req.rationale,
1125
+ priority: req.priority,
1126
+ scopeStatus: req.scopeStatus,
1127
+ objectiveRecordIds: req.objectiveRecordIds,
1128
+ deliverableRecordIds: req.deliverableRecordIds,
1129
+ requestKey: this.key(req.requestKey)
1130
+ });
1131
+ }
1132
+ /** `pm.requirement.update` → `PATCH requirements/:recordId` (scope removal via the change process). */
1133
+ async updateRequirement(projectId, recordId, req) {
1134
+ return this.update(projectId, "requirements", recordId, req);
1135
+ }
1136
+ /** `pm.criterion.create` → `POST criteria`. */
1137
+ async createCriterion(projectId, req) {
1138
+ this.oneOf(req.checkMethod, PM_CRITERION_CHECK_METHODS, "check method");
1139
+ this.criterion(req);
1140
+ return this.write("POST", this.path(projectId, "criteria"), {
1141
+ title: this.text(req.title, "A criterion title"),
1142
+ checkMethod: req.checkMethod,
1143
+ expectedResult: req.expectedResult,
1144
+ comparator: req.comparator,
1145
+ unit: req.unit,
1146
+ threshold: req.threshold,
1147
+ thresholdUpper: req.thresholdUpper,
1148
+ blocking: req.blocking,
1149
+ exceptionPolicy: req.exceptionPolicy,
1150
+ reviewerRule: req.reviewerRule,
1151
+ requirementRecordIds: req.requirementRecordIds,
1152
+ deliverableRecordIds: req.deliverableRecordIds,
1153
+ requestKey: this.key(req.requestKey)
1154
+ });
1155
+ }
1156
+ /** `pm.criterion.update` → `PATCH criteria/:recordId` (a criterion an accepted submission froze changes via S06). */
1157
+ async updateCriterion(projectId, recordId, req) {
1158
+ this.criterion(this.patch(req.patch));
1159
+ return this.update(projectId, "criteria", recordId, req);
1160
+ }
1161
+ /** `pm.verification.record` → `POST verifications`. */
1162
+ async recordVerification(projectId, req) {
1163
+ if (req.result !== void 0) this.oneOf(req.result, PM_VERIFICATION_RESULTS, "verification result");
1164
+ if (req.measuredValue !== void 0) this.decimal(req.measuredValue, "measuredValue");
1165
+ for (const e of req.evidence ?? []) this.oneOf(e.kind, PM_EVIDENCE_SOURCE_KINDS, "evidence kind");
1166
+ return this.write("POST", this.path(projectId, "verifications"), {
1167
+ criterionRecordId: this.text(req.criterionRecordId, "criterionRecordId"),
1168
+ criterionRevisionId: req.criterionRevisionId,
1169
+ deliverableRecordId: this.text(req.deliverableRecordId, "deliverableRecordId"),
1170
+ deliverableRevisionId: req.deliverableRevisionId,
1171
+ result: req.result,
1172
+ measuredValue: req.measuredValue,
1173
+ unit: req.unit,
1174
+ observedAt: this.text(req.observedAt, "observedAt"),
1175
+ method: req.method,
1176
+ evidence: req.evidence,
1177
+ modelInterpretation: req.modelInterpretation,
1178
+ requestKey: this.key(req.requestKey)
1179
+ });
1180
+ }
1181
+ /** `pm.acceptance.submit` → `POST acceptance/submissions`: freezes what is being accepted. */
1182
+ async submit(projectId, req) {
1183
+ return this.write("POST", this.path(projectId, "acceptance", "submissions"), {
1184
+ deliverableRecordId: this.text(req.deliverableRecordId, "deliverableRecordId"),
1185
+ expectedDeliverableRevisionId: req.expectedDeliverableRevisionId,
1186
+ requestKey: this.key(req.requestKey)
1187
+ });
1188
+ }
1189
+ /** `pm.acceptance.decide` → `POST acceptance/submissions/:recordId/decision` (designated acceptor; stale submissions refuse). */
1190
+ async decide(projectId, recordId, req) {
1191
+ const corrective = req.correctiveWorkRecordId !== void 0 || req.correctiveWorkTitle !== void 0;
1192
+ if (req.decision === "accept" && corrective) throw new Error("An acceptance names no corrective work.");
1193
+ if (req.decision === "reject" && !req.correctiveWorkRecordId === !req.correctiveWorkTitle) {
1194
+ throw new Error("A rejection names exactly one of correctiveWorkRecordId or correctiveWorkTitle.");
1195
+ }
1196
+ const params = corrective ? { correctiveWorkRecordId: req.correctiveWorkRecordId, correctiveWorkTitle: req.correctiveWorkTitle } : void 0;
1197
+ return this.postDecision(this.path(projectId, "acceptance", "submissions", recordId, "decision"), req, PM_ACCEPTANCE_DECISIONS, { params });
1198
+ }
1199
+ /** `pm.exception.decide` → `POST acceptance/submissions/:recordId/exception-decision` (accept with a permitted exception). */
1200
+ async decideException(projectId, recordId, req) {
1201
+ const e = req.exception;
1202
+ if (!e || !Array.isArray(e.criterionRecordIds) || e.criterionRecordIds.length === 0) {
1203
+ throw new Error("An exception names the failed criteria it covers.");
1204
+ }
1205
+ this.text(e.reason, "An exception reason");
1206
+ this.text(e.ownerContactId, "An exception owner");
1207
+ this.text(e.consequence, "An exception consequence");
1208
+ const body = {
1209
+ expectedVersion: this.text(req.expectedVersion, "expectedVersion"),
1210
+ reason: req.reason,
1211
+ exception: e,
1212
+ requestKey: this.key(req.requestKey)
1213
+ };
1214
+ const res = await this.http.post(this.path(projectId, "acceptance", "submissions", recordId, "exception-decision"), {
1215
+ body
1216
+ });
1217
+ return this.decided(res);
1218
+ }
1219
+ /** `pm.defect.create` → `POST defects`. */
1220
+ async createDefect(projectId, req) {
1221
+ if (req.severity !== void 0) this.oneOf(req.severity, PM_DEFECT_SEVERITIES, "defect severity");
1222
+ return this.write("POST", this.path(projectId, "defects"), {
1223
+ title: this.text(req.title, "A defect title"),
1224
+ severity: req.severity,
1225
+ failedCriterionRecordId: req.failedCriterionRecordId,
1226
+ verificationRecordId: req.verificationRecordId,
1227
+ submissionRecordId: req.submissionRecordId,
1228
+ proposedOwnerContactId: req.proposedOwnerContactId,
1229
+ correctiveWorkRecordIds: req.correctiveWorkRecordIds,
1230
+ requestKey: this.key(req.requestKey)
1231
+ });
1232
+ }
1233
+ /** `pm.defect.update` → `PATCH defects/:recordId` (title, severity, state). */
1234
+ async updateDefect(projectId, recordId, req) {
1235
+ const patch = this.patch(req.patch);
1236
+ if (patch.severity != null) this.oneOf(patch.severity, PM_DEFECT_SEVERITIES, "defect severity");
1237
+ if (patch.state !== void 0) this.oneOf(patch.state, PM_DEFECT_STATES, "defect state");
1238
+ return this.update(projectId, "defects", recordId, req);
1239
+ }
1240
+ /** `pm.corrective_work.link` → `POST defects/:recordId/corrective-work`: an existing work item or a new titled one. */
1241
+ async linkCorrectiveWork(projectId, recordId, req) {
1242
+ if (!req.workRecordId === !req.workTitle) throw new Error("Name exactly one of workRecordId or workTitle.");
1243
+ return this.write("POST", this.path(projectId, "defects", recordId, "corrective-work"), {
1244
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1245
+ workRecordId: req.workRecordId,
1246
+ workTitle: req.workTitle,
1247
+ requestKey: this.key(req.requestKey)
1248
+ });
1249
+ }
1250
+ };
1251
+
1252
+ // src/modules/projects/pm/bootstrap.ts
1253
+ var PM_BOOTSTRAP_STATES = ["project_pending", "setup_pending", "conversation_pending", "ready", "blocked"];
1254
+ function isPmBootstrapState(value) {
1255
+ return typeof value === "string" && PM_BOOTSTRAP_STATES.includes(value);
1256
+ }
1257
+ var PM_BOOTSTRAP_MAX_BRIEF_BYTES = 65536;
1258
+ var PM_BOOTSTRAP_MAX_TITLE_BYTES = 200;
1259
+ var utf8Bytes = (s) => new TextEncoder().encode(s).length;
1260
+ var PmBootstrapApi = class extends PmWriteApiBase {
1261
+ bootstrapPath(requestKey, ...rest) {
1262
+ if (requestKey === void 0) return "/pm/projects/bootstrap";
1263
+ const key = this.key(requestKey);
1264
+ if (key.includes("/")) throw new Error('A bootstrap requestKey cannot contain "/".');
1265
+ return ["/pm/projects/bootstrap", encodeURIComponent(key), ...rest].join("/");
1266
+ }
1267
+ /** `pm.project.bootstrap` → `POST /pm/projects/bootstrap`: creates (or finds) and advances as far as it can. */
1268
+ async bootstrapProject(req) {
1269
+ this.bootstrapPath(req.requestKey);
1270
+ const brief = this.text(req.initialBrief, "A bootstrap brief");
1271
+ if (utf8Bytes(brief) > PM_BOOTSTRAP_MAX_BRIEF_BYTES) throw new Error("A bootstrap brief is at most 64 KiB.");
1272
+ if (req.title !== void 0 && utf8Bytes(req.title.trim()) > PM_BOOTSTRAP_MAX_TITLE_BYTES) {
1273
+ throw new Error("A project title is at most 200 bytes.");
1274
+ }
1275
+ const body = { requestKey: req.requestKey, initialBrief: brief, title: req.title, timezone: req.timezone };
1276
+ return this.http.post(this.bootstrapPath(), { body });
1277
+ }
1278
+ /** `GET /pm/projects/bootstrap/:requestKey`: the caller's continuation, with its brief. */
1279
+ async getContinuation(requestKey) {
1280
+ return this.http.get(this.bootstrapPath(requestKey));
1281
+ }
1282
+ /** `pm.project.resume` → `POST …/:requestKey/resume`: reauthorizes and runs the next durable step. */
1283
+ async resume(requestKey) {
1284
+ return this.http.post(this.bootstrapPath(requestKey, "resume"), { body: {} });
1285
+ }
1286
+ /** `GET /pm/projects/bootstrap?state=pending`: the caller's resumable bootstraps, newest first (≤20, no briefs). */
1287
+ async listPending() {
1288
+ const res = await this.http.get(this.bootstrapPath(), {
1289
+ query: { state: "pending" }
1290
+ });
1291
+ return res.items ?? [];
1292
+ }
1293
+ };
1294
+
1295
+ // src/modules/projects/pm/change.ts
1296
+ var PM_SCENARIO_OPS = [
1297
+ "work.update",
1298
+ "work.create",
1299
+ "dependency.set",
1300
+ "dependency.remove",
1301
+ "assignment.update",
1302
+ "assignment.create",
1303
+ "availability.set",
1304
+ "calendar.update",
1305
+ "cost_item.update",
1306
+ "cost_item.create",
1307
+ "supplier_commitment.update",
1308
+ "criterion.update",
1309
+ "requirement.update"
1310
+ ];
1311
+ var PM_SCENARIO_STATES = ["draft", "prepared", "applied", "stale", "withdrawn"];
1312
+ function isPmScenarioState(value) {
1313
+ return typeof value === "string" && PM_SCENARIO_STATES.includes(value);
1314
+ }
1315
+ var PM_CHANGE_ROLES = ["project_manager", "baseline", "budget"];
1316
+ var PM_CHANGE_PREPARE_ACTIONS = ["prepare", "withdraw"];
1317
+ var PATCH_OPS = [
1318
+ "work.update",
1319
+ "assignment.update",
1320
+ "calendar.update",
1321
+ "cost_item.update",
1322
+ "supplier_commitment.update",
1323
+ "criterion.update",
1324
+ "requirement.update"
1325
+ ];
1326
+ var INPUT_OPS = ["work.create", "assignment.create", "cost_item.create", "dependency.set", "availability.set"];
1327
+ var DETAIL_LISTS = [
1328
+ "patchSet",
1329
+ "beforeAnalysisIds",
1330
+ "afterAnalysisIds",
1331
+ "acceptanceImpacts",
1332
+ "assumptions",
1333
+ "constraints",
1334
+ "requiredDeciders",
1335
+ "notifyContactIds"
1336
+ ];
1337
+ var PmChangeApi = class extends PmWriteApiBase {
1338
+ /** Absent lists (a Go nil slice) read as empty, never as a crash. */
1339
+ scenarioOf(s) {
1340
+ const detail = { ...s.detail };
1341
+ for (const k of DETAIL_LISTS) detail[k] ?? (detail[k] = []);
1342
+ detail.expectedHeads ?? (detail.expectedHeads = {});
1343
+ const c = s.comparison;
1344
+ const comparison = c && {
1345
+ schedule: { ...c.schedule, changed: c.schedule?.changed ?? [] },
1346
+ capacity: c.capacity,
1347
+ finance: { ...c.finance, currencies: c.finance?.currencies ?? [], items: c.finance?.items ?? [] }
1348
+ };
1349
+ return { ...s, detail, comparison, decisions: s.decisions ?? [] };
1350
+ }
1351
+ post(path2, body) {
1352
+ return this.http.post(path2, { body });
1353
+ }
1354
+ /** `pm.scenario.create` → `POST scenarios`: validates the patch set without changing anything. */
1355
+ async createScenario(projectId, req) {
1356
+ if (!Array.isArray(req.patchSet) || req.patchSet.length < 1 || req.patchSet.length > 200) {
1357
+ throw new Error("A scenario carries 1 to 200 typed ops.");
1358
+ }
1359
+ for (const op of req.patchSet) {
1360
+ this.oneOf(op.op, PM_SCENARIO_OPS, "scenario op");
1361
+ if (PATCH_OPS.includes(op.op) || op.op === "dependency.remove") {
1362
+ this.text(op.recordId, `${op.op} recordId`);
1363
+ this.text(op.expectedRevisionId, `${op.op} expectedRevisionId`);
1364
+ if (op.op !== "dependency.remove") this.patch(op.patch);
1365
+ } else if (INPUT_OPS.includes(op.op) && (!op.input || typeof op.input !== "object")) {
1366
+ throw new Error(`${op.op} carries its operation input.`);
1367
+ }
1368
+ }
1369
+ const res = await this.post(this.path(projectId, "scenarios"), {
1370
+ title: this.text(req.title, "A scenario title"),
1371
+ patchSet: req.patchSet,
1372
+ assumptions: req.assumptions,
1373
+ constraints: req.constraints,
1374
+ includesNewBaseline: req.includesNewBaseline,
1375
+ asOf: req.asOf,
1376
+ requestKey: this.key(req.requestKey)
1377
+ });
1378
+ return { scenario: this.scenarioOf(res.scenario), operation: this.op(res.operation) };
1379
+ }
1380
+ /** `pm.scenario.compare` → `POST scenarios/compare` (read-only; at most 10). */
1381
+ async compareScenarios(projectId, req) {
1382
+ const scenarioRecordIds = req?.scenarioRecordIds;
1383
+ if (!Array.isArray(scenarioRecordIds) || scenarioRecordIds.length < 1 || scenarioRecordIds.length > 10) {
1384
+ throw new Error("Compare 1 to 10 scenarios.");
1385
+ }
1386
+ for (const id of scenarioRecordIds) this.text(id, "A scenario record id");
1387
+ const res = await this.post(this.path(projectId, "scenarios", "compare"), { scenarioRecordIds });
1388
+ return { ...res, scenarios: (res.scenarios ?? []).map((s) => this.scenarioOf(s)) };
1389
+ }
1390
+ /** `pm.change.prepare` → `POST scenarios/:recordId/prepare` (or `action: withdraw`). */
1391
+ async prepareChange(projectId, recordId, req) {
1392
+ if (req.action !== void 0) this.oneOf(req.action, PM_CHANGE_PREPARE_ACTIONS, "change action");
1393
+ if (req.action === "withdraw" && req.notifyContactIds?.length) throw new Error("A withdrawal notifies no one.");
1394
+ const res = await this.post(this.path(projectId, "scenarios", recordId, "prepare"), {
1395
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1396
+ action: req.action,
1397
+ rationale: req.rationale,
1398
+ notifyContactIds: req.notifyContactIds,
1399
+ requestKey: this.key(req.requestKey)
1400
+ });
1401
+ return { scenario: this.scenarioOf(res.scenario), operation: this.op(res.operation) };
1402
+ }
1403
+ /** `pm.change.decide` → `POST scenarios/:recordId/decision`: one required decider on the exact prepared revision. */
1404
+ async decideChange(projectId, recordId, req) {
1405
+ return this.postDecision(this.path(projectId, "scenarios", recordId, "decision"), req, PM_APPROVAL_DECISIONS);
1406
+ }
1407
+ /** `pm.change.apply` → `POST scenarios/:recordId/apply`: atomic, or `stale_snapshot` with zero writes. */
1408
+ async applyChange(projectId, recordId, req) {
1409
+ const res = await this.post(this.path(projectId, "scenarios", recordId, "apply"), {
1410
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1411
+ requestKey: this.key(req.requestKey)
1412
+ });
1413
+ return {
1414
+ applied: { ...res.applied, records: res.applied?.records ?? [] },
1415
+ downstream: res.downstream ?? [],
1416
+ operation: this.op(res.operation)
1417
+ };
1418
+ }
1419
+ };
1420
+
1421
+ // src/modules/projects/pm/closure.ts
1422
+ var PM_CLOSURE_STATES = ["assessment", "closed", "reopened"];
1423
+ function isPmClosureState(value) {
1424
+ return typeof value === "string" && PM_CLOSURE_STATES.includes(value);
1425
+ }
1426
+ var PM_PROJECT_LIFECYCLE_STATES = ["active", "closed"];
1427
+ function isPmProjectLifecycleState(value) {
1428
+ return typeof value === "string" && PM_PROJECT_LIFECYCLE_STATES.includes(value);
1429
+ }
1430
+ var PM_CLOSURE_DISPOSITIONS = ["accepted", "accepted_with_exception", "removed_by_change", "unresolved"];
1431
+ var PM_CLOSURE_BLOCKER_CODES = [
1432
+ "deliverable_not_accepted",
1433
+ "residual_not_handed_over",
1434
+ "handover_unacknowledged",
1435
+ "finance_unreconciled"
1436
+ ];
1437
+ function isPmClosureBlockerCode(value) {
1438
+ return typeof value === "string" && PM_CLOSURE_BLOCKER_CODES.includes(value);
1439
+ }
1440
+ var PM_RESIDUAL_COVERAGES = ["owner_accepted", "handover_acknowledged", "none"];
1441
+ var PM_RESIDUAL_KINDS = ["commitment", "supplier_commitment", "defect", "cost_item", "benefit"];
1442
+ var PM_BENEFIT_POSITION_STATES = ["unmeasured", "measured", "basis_mismatch"];
1443
+ function isPmBenefitPositionState(value) {
1444
+ return typeof value === "string" && PM_BENEFIT_POSITION_STATES.includes(value);
1445
+ }
1446
+ var PM_HANDOVER_STATES = ["pending", "acknowledged", "declined"];
1447
+ function isPmHandoverState(value) {
1448
+ return typeof value === "string" && PM_HANDOVER_STATES.includes(value);
1449
+ }
1450
+ var PM_HANDOVER_DECISIONS = ["acknowledge", "decline"];
1451
+ var PM_CLOSURE_FAMILIES = ["closure", "handover", "benefit", "benefit_observation", "lesson"];
1452
+ var DAY = /^\d{4}-\d{2}-\d{2}$/;
1453
+ function assertPmBenefitInput(b) {
1454
+ if (!b || typeof b.measure !== "string" || !b.measure.trim() || typeof b.unit !== "string" || !b.unit.trim()) {
1455
+ throw new Error("A benefit names its measure and unit.");
1456
+ }
1457
+ if (!isPmDecimal(b.targetValue)) throw new Error("A benefit target must be an exact decimal string.");
1458
+ if (b.baselineValue != null && !isPmDecimal(b.baselineValue)) throw new Error("A benefit baseline must be an exact decimal string.");
1459
+ for (const d of [b.windowStart, b.windowEnd]) {
1460
+ if (d != null && !DAY.test(d)) throw new Error("Benefit window dates are YYYY-MM-DD.");
1461
+ }
1462
+ if (!b.reviewCondition?.trim() && !b.nextReviewAt) throw new Error("A benefit names its review condition or next review time.");
1463
+ }
1464
+ var MAX_TAG = 64;
1465
+ var PmClosureApi = class extends PmWriteApiBase {
1466
+ async run(path2, body) {
1467
+ return this.written(await this.http.post(path2, { body }));
1468
+ }
1469
+ citations(list, what) {
1470
+ for (const c of list ?? []) {
1471
+ this.text(c?.kind, `${what} kind`);
1472
+ this.text(c?.ref, `${what} ref`);
1473
+ }
1474
+ }
1475
+ assessment(a) {
1476
+ return {
1477
+ ...a,
1478
+ acceptanceSummary: a.acceptanceSummary ?? {},
1479
+ deliverableDispositions: a.deliverableDispositions ?? [],
1480
+ residualObligations: a.residualObligations ?? [],
1481
+ blockers: a.blockers ?? [],
1482
+ decisions: a.decisions ?? []
1483
+ };
1484
+ }
1485
+ /** `pm.closure.assess` → `POST closure/assessments`: freezes the position and lists blockers. */
1486
+ async assess(projectId, req) {
1487
+ for (const r of req.rates ?? []) this.decimal(r.rate, "An FX rate");
1488
+ const out = await this.run(this.path(projectId, "closure", "assessments"), {
1489
+ asOf: req.asOf,
1490
+ reportingCurrency: req.reportingCurrency,
1491
+ rates: req.rates,
1492
+ requestKey: this.key(req.requestKey)
1493
+ });
1494
+ return { ...out, result: this.assessment(out.result) };
1495
+ }
1496
+ /**
1497
+ * `pm.closure.decide` → `POST closure/assessments/:recordId/decision` (the
1498
+ * closing authority). Refuses with `stale_snapshot` once the project changed
1499
+ * after the assessment.
1500
+ */
1501
+ async decideClosure(projectId, recordId, req) {
1502
+ const ex = req.exception;
1503
+ if (ex !== void 0) {
1504
+ if (req.decision !== "approve") throw new Error("An exception goes only with approve.");
1505
+ if (!Array.isArray(ex?.blockers) || ex.blockers.length === 0) throw new Error("An exception names each assessment blocker.");
1506
+ for (const b of ex.blockers) {
1507
+ this.oneOf(b.code, PM_CLOSURE_BLOCKER_CODES, "closure blocker code");
1508
+ this.text(b.recordId, "A blocker recordId");
1509
+ this.text(b.disposition, "A blocker disposition");
1510
+ }
1511
+ }
1512
+ if ((ex !== void 0 || req.decision === "reject") && !req.reason?.trim()) {
1513
+ throw new Error("A rejection, or an approval over blockers, states its reason.");
1514
+ }
1515
+ return this.postDecision(this.path(projectId, "closure", "assessments", recordId, "decision"), req, PM_APPROVAL_DECISIONS, {
1516
+ exception: ex
1517
+ });
1518
+ }
1519
+ /** `pm.closure.decide{reopen}` → `POST closure/reopen` on the closed revision, with a reason. */
1520
+ async reopen(projectId, req) {
1521
+ const body = {
1522
+ recordId: this.text(req.recordId, "recordId"),
1523
+ expectedVersion: this.text(req.expectedVersion, "expectedVersion"),
1524
+ reason: this.text(req.reason, "A reopen reason"),
1525
+ requestKey: this.key(req.requestKey)
1526
+ };
1527
+ return this.decided(await this.http.post(this.path(projectId, "closure", "reopen"), { body }));
1528
+ }
1529
+ /** `pm.handover.prepare` → `POST handovers`. */
1530
+ async prepareHandover(projectId, req) {
1531
+ const ids = req.residualRecordIds;
1532
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > 200) throw new Error("A handover lists 1 to 200 residual obligations.");
1533
+ for (const id of ids) this.text(id, "A residual record id");
1534
+ return this.run(this.path(projectId, "handovers"), {
1535
+ title: this.text(req.title, "A handover title"),
1536
+ receiverContactId: this.text(req.receiverContactId, "receiverContactId"),
1537
+ summary: req.summary,
1538
+ residualRecordIds: ids,
1539
+ requestKey: this.key(req.requestKey)
1540
+ });
1541
+ }
1542
+ /** `pm.handover.decide` → `POST handovers/:recordId/decision` (allowed after closure). */
1543
+ async decideHandover(projectId, recordId, req) {
1544
+ if (req.evidence !== void 0 && (!Array.isArray(req.evidence) || req.evidence.length > 20)) {
1545
+ throw new Error("A handover decision cites at most 20 evidence references.");
1546
+ }
1547
+ this.citations(req.evidence, "An evidence");
1548
+ return this.postDecision(this.path(projectId, "handovers", recordId, "decision"), req, PM_HANDOVER_DECISIONS, {
1549
+ params: req.evidence ? { evidence: req.evidence } : void 0
1550
+ });
1551
+ }
1552
+ /** `pm.benefit.record_observation` → `POST benefits/:recordId/observations` (allowed after closure). */
1553
+ async recordBenefitObservation(projectId, benefitRecordId, req) {
1554
+ this.decimal(req.actualValue, "actualValue");
1555
+ for (const d of [req.periodStart, req.periodEnd]) {
1556
+ if (typeof d !== "string" || !DAY.test(d)) throw new Error("An observation period is YYYY-MM-DD to YYYY-MM-DD.");
1557
+ }
1558
+ if (req.periodEnd < req.periodStart) throw new Error("An observation period ends on or after it starts.");
1559
+ if (!Array.isArray(req.citations) || req.citations.length === 0) throw new Error("A benefit observation cites at least one source.");
1560
+ this.citations(req.citations, "A citation");
1561
+ return this.run(this.path(projectId, "benefits", benefitRecordId, "observations"), {
1562
+ expectedBenefitRevisionId: this.text(req.expectedBenefitRevisionId, "expectedBenefitRevisionId"),
1563
+ periodStart: req.periodStart,
1564
+ periodEnd: req.periodEnd,
1565
+ actualValue: req.actualValue,
1566
+ unit: this.text(req.unit, "A unit"),
1567
+ method: this.text(req.method, "A measurement method"),
1568
+ citations: req.citations,
1569
+ requestKey: this.key(req.requestKey)
1570
+ });
1571
+ }
1572
+ tags(tags) {
1573
+ if (!Array.isArray(tags) || tags.length > 20) throw new Error("At most 20 applicability tags.");
1574
+ for (const t of tags) {
1575
+ if (typeof t !== "string" || !t.trim() || new TextEncoder().encode(t.trim()).length > MAX_TAG || t.includes(",")) {
1576
+ throw new Error("An applicability tag is 1 to 64 bytes without commas.");
1577
+ }
1578
+ }
1579
+ return tags;
1580
+ }
1581
+ /** `pm.lesson.record` → `POST lessons` (allowed after closure). */
1582
+ async recordLesson(projectId, req) {
1583
+ this.tags(req.applicability?.tags);
1584
+ this.citations(req.citations, "A citation");
1585
+ if (req.references !== void 0 && (!Array.isArray(req.references) || req.references.length > 20)) {
1586
+ throw new Error("A lesson cites at most 20 peer lessons.");
1587
+ }
1588
+ for (const r of req.references ?? []) {
1589
+ this.text(r.projectId, "A peer lesson projectId");
1590
+ this.text(r.recordId, "A peer lesson recordId");
1591
+ this.text(r.revisionId, "A peer lesson revisionId");
1592
+ }
1593
+ return this.run(this.path(projectId, "lessons"), {
1594
+ title: this.text(req.title, "A lesson title"),
1595
+ context: this.text(req.context, "A lesson context"),
1596
+ observation: this.text(req.observation, "A lesson observation"),
1597
+ recommendation: this.text(req.recommendation, "A lesson recommendation"),
1598
+ applicability: req.applicability,
1599
+ citations: req.citations,
1600
+ references: req.references,
1601
+ requestKey: this.key(req.requestKey)
1602
+ });
1603
+ }
1604
+ /** `pm.lesson.search` → `GET lessons/search`: lessons of readable projects sharing a tag (all without tags). */
1605
+ async searchLessons(projectId, req = {}) {
1606
+ const tags = req.tags === void 0 ? [] : this.tags(req.tags);
1607
+ if (req.limit !== void 0 && !(Number.isInteger(req.limit) && req.limit >= 1 && req.limit <= 50)) {
1608
+ throw new Error("A lesson search limit is an integer between 1 and 50.");
1609
+ }
1610
+ const res = await this.http.get(this.path(projectId, "lessons", "search"), {
1611
+ query: { tags: tags.length ? tags.map((t) => t.trim()).join(",") : void 0, limit: req.limit }
1612
+ });
1613
+ return (res.lessons ?? []).map((l) => ({ ...l, applicability: { ...l.applicability, tags: l.applicability?.tags ?? [] } }));
1614
+ }
1615
+ };
1616
+
1617
+ // src/modules/projects/pm/communication.ts
1618
+ var PM_COMMUNICATION_PURPOSES = ["status_report", "message", "change_notice"];
1619
+ var PM_COMMUNICATION_DELIVERY_MODES = ["inline", "link_only"];
1620
+ var PM_COMMUNICATION_RECEIPT_OUTCOMES = ["pending", "transport_accepted", "failed", "outcome_unknown", "not_sent", "already_sent"];
1621
+ function isPmCommunicationReceiptOutcome(value) {
1622
+ return typeof value === "string" && PM_COMMUNICATION_RECEIPT_OUTCOMES.includes(value);
1623
+ }
1624
+ var PM_SENT_UNDER = ["standing_authority", "person"];
1625
+ function isPmSentUnder(value) {
1626
+ return typeof value === "string" && PM_SENT_UNDER.includes(value);
1627
+ }
1628
+ var PM_RESEND_MODES = ["recovery", "new_intent"];
1629
+ var PM_DUPLICATE_ACKNOWLEDGEMENT_REQUIRED = "duplicate_acknowledgement_required";
1630
+ var PM_RESEND_INTENT_REQUIRED = "resend_intent_required";
1631
+ function pmResendIntentRequiredOf(err) {
1632
+ const e = pmErrorOf(err);
1633
+ if (e?.code !== PM_RESEND_INTENT_REQUIRED || !e.details || typeof e.details !== "object") return void 0;
1634
+ const d = e.details;
1635
+ return {
1636
+ plan: { ...d.plan, recipients: d.plan?.recipients ?? [] },
1637
+ affectedRecipients: d.affectedRecipients ?? [],
1638
+ earlier: (d.earlier ?? []).map((x) => ({ ...x, delivery: { ...x.delivery, recipients: x.delivery?.recipients ?? [] } }))
1639
+ };
1640
+ }
1641
+ function pmDuplicateDisclosureOf(err) {
1642
+ const e = pmErrorOf(err);
1643
+ if (e?.code !== PM_DUPLICATE_ACKNOWLEDGEMENT_REQUIRED || !e.details || typeof e.details !== "object") return void 0;
1644
+ const plan = e.details;
1645
+ return { ...plan, recipients: plan.recipients ?? [], possibleDuplicateRecipients: plan.possibleDuplicateRecipients ?? [] };
1646
+ }
1647
+ var PM_STANDING_AUTHORITY_PURPOSES = ["follow_up_reminder"];
1648
+ var PM_STANDING_MIN_INTERVAL_HOURS = 24;
1649
+ var PM_STANDING_MAX_INTERVAL_HOURS = 720;
1650
+ var PM_STANDING_AUTHORITY_EVIDENCE_KIND = "standing_delivery_authority";
1651
+ var PM_STANDING_REFUSAL_REASONS = ["commitment-changed", "frequency-bound"];
1652
+ function pmStandingRefusalOf(err) {
1653
+ const e = pmErrorOf(err);
1654
+ const d = e?.code === "capability_limitation" && e.details && typeof e.details === "object" ? e.details : void 0;
1655
+ if (!d || !PM_STANDING_REFUSAL_REASONS.includes(d.reason)) return void 0;
1656
+ return { reason: d.reason, ...typeof d.notBefore === "string" ? { notBefore: d.notBefore } : {} };
1657
+ }
1658
+ var PmCommunicationApi = class extends PmWriteApiBase {
1659
+ result(r) {
1660
+ const plan = r.plan && {
1661
+ ...r.plan,
1662
+ recipients: r.plan.recipients ?? [],
1663
+ original: r.plan.original && { ...r.plan.original, recipients: r.plan.original.recipients ?? [] }
1664
+ };
1665
+ return { ...r, plan, operation: r.operation && this.op(r.operation) };
1666
+ }
1667
+ /** `pm.communication.prepare` → `POST communications`: pins content and recipients; sends nothing. */
1668
+ async prepare(projectId, req) {
1669
+ const ids = req.recipientContactIds;
1670
+ if (!Array.isArray(ids) || ids.length === 0) throw new Error("A communication names at least one recipient.");
1671
+ for (const id of ids) this.text(id, "A recipient contact id");
1672
+ const body = {
1673
+ purpose: this.oneOf(req.purpose, PM_COMMUNICATION_PURPOSES, "communication purpose"),
1674
+ contentArtifactId: this.text(req.contentArtifactId, "contentArtifactId"),
1675
+ contentVersionId: this.text(req.contentVersionId, "contentVersionId"),
1676
+ recipientContactIds: ids,
1677
+ resendOfRecordId: req.resendOfRecordId,
1678
+ resendMode: req.resendMode === void 0 ? void 0 : this.oneOf(req.resendMode, PM_RESEND_MODES, "resend mode"),
1679
+ acknowledgePossibleDuplicate: req.acknowledgePossibleDuplicate || void 0,
1680
+ requestKey: this.key(req.requestKey)
1681
+ };
1682
+ return this.result(await this.http.post(this.path(projectId, "communications"), { body }));
1683
+ }
1684
+ /** `pm.communication.dispatch` → `POST communications/:recordId/dispatch`: queues the exact revision for approval. */
1685
+ async dispatch(projectId, recordId, req) {
1686
+ const body = {
1687
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
1688
+ requestKey: this.key(req.requestKey)
1689
+ };
1690
+ return this.result(await this.http.post(this.path(projectId, "communications", recordId, "dispatch"), { body }));
1691
+ }
1692
+ /** `pm.communication.inspect` → `GET communications/:recordId`: the record, its operation and per-recipient delivery. */
1693
+ async inspect(projectId, recordId) {
1694
+ const v = await this.http.get(this.path(projectId, "communications", recordId));
1695
+ return {
1696
+ ...v,
1697
+ operation: v.operation && this.op(v.operation),
1698
+ delivery: v.delivery && { ...v.delivery, recipients: v.delivery.recipients ?? [] }
1699
+ };
1700
+ }
1701
+ standing(r) {
1702
+ return { ...r, authority: r.authority ?? null, operation: r.operation && this.op(r.operation) };
1703
+ }
1704
+ /** `pm.delivery_authority.inspect` → `GET delivery-authority/standing`: the live authority (or null) and whether the caller may change it. */
1705
+ async getStandingAuthority(projectId) {
1706
+ return this.standing(await this.http.get(this.path(projectId, "delivery-authority", "standing")));
1707
+ }
1708
+ /** `pm.delivery_authority.grant` → `POST delivery-authority/standing`: owner or PM; supersedes a live one of another scope or interval. */
1709
+ async grantStandingAuthority(projectId, req) {
1710
+ const hours = req.minIntervalHours;
1711
+ if (hours !== void 0 && !(Number.isInteger(hours) && hours >= PM_STANDING_MIN_INTERVAL_HOURS && hours <= PM_STANDING_MAX_INTERVAL_HOURS)) {
1712
+ throw new Error(`minIntervalHours must be a whole number between ${PM_STANDING_MIN_INTERVAL_HOURS} and ${PM_STANDING_MAX_INTERVAL_HOURS}.`);
1713
+ }
1714
+ if (req.responsibilityId !== void 0 && this.text(req.responsibilityId, "responsibilityId").length > 128) {
1715
+ throw new Error("responsibilityId is too long.");
1716
+ }
1717
+ const body = {
1718
+ purpose: this.oneOf(req.purpose, PM_STANDING_AUTHORITY_PURPOSES, "standing authority purpose"),
1719
+ responsibilityId: req.responsibilityId,
1720
+ minIntervalHours: hours,
1721
+ requestKey: this.key(req.requestKey)
1722
+ };
1723
+ return this.standing(await this.http.post(this.path(projectId, "delivery-authority", "standing"), { body }));
1724
+ }
1725
+ /** `pm.delivery_authority.revoke` → `POST delivery-authority/standing/revoke`: queued sends fall back to the owner+PM approval. */
1726
+ async revokeStandingAuthority(projectId, req) {
1727
+ const body = { authorityId: this.text(req.authorityId, "authorityId"), requestKey: this.key(req.requestKey) };
1728
+ return this.standing(await this.http.post(this.path(projectId, "delivery-authority", "standing", "revoke"), { body }));
1729
+ }
1730
+ };
1731
+
1732
+ // src/modules/projects/pm/finance.ts
1733
+ var PM_COST_ENTRY_KINDS = ["item", "actual_posting"];
1734
+ var PM_COST_BINDING_KINDS = ["explicit_quantity", "assignment_effort", "scheduled_work", "date_interval"];
1735
+ var PM_COST_ITEM_LINK_KINDS = ["cost_for_work", "cost_for_supplier_commitment", "cost_for_milestone"];
1736
+ var PM_SUPPLIER_LINK_KINDS = ["supplier_for_deliverable", "supplier_for_milestone"];
1737
+ var PM_SUPPLIER_CONFIRMATION_POSTURES = ["recorded", "supplier_evidence", "contract_evidence"];
1738
+ var PM_SUPPLIER_OUTCOMES = ["open", "delivered", "late", "cancelled", "disputed"];
1739
+ function isPmSupplierOutcome(value) {
1740
+ return typeof value === "string" && PM_SUPPLIER_OUTCOMES.includes(value);
1741
+ }
1742
+ var PmFinanceApi = class extends PmWriteApiBase {
1743
+ write(method, path2, body) {
1744
+ return this.http.request(method, path2, { body }).then((r) => ({ ...this.written(r), records: r.records ?? [] }));
1745
+ }
1746
+ posting(p, what) {
1747
+ if (!p) throw new Error(`${what} is required.`);
1748
+ this.text(p.costItemRecordId, "A posting costItemRecordId");
1749
+ this.money(p.amount, "A posting amount");
1750
+ this.text(p.incurredOn, "A posting incurredOn");
1751
+ for (const a of p.allocations ?? []) this.money(a.amount, "An allocation amount");
1752
+ if (p.forecastConsumption !== void 0) this.money(p.forecastConsumption, "forecastConsumption");
1753
+ if (p.fx) this.decimal(p.fx.rate, "An FX rate");
1754
+ }
1755
+ costItem(item) {
1756
+ if (!item) throw new Error("A cost item entry needs its item.");
1757
+ this.text(item.title, "A cost item title");
1758
+ this.text(item.category, "A cost item category");
1759
+ this.text(item.currency, "A cost item currency");
1760
+ if (item.remainingEstimate !== void 0) this.money(item.remainingEstimate, "remainingEstimate");
1761
+ if (item.binding) {
1762
+ this.oneOf(item.binding.kind, PM_COST_BINDING_KINDS, "cost binding kind");
1763
+ this.money(item.binding.rate, "A binding rate");
1764
+ if (item.binding.quantity !== void 0) this.decimal(item.binding.quantity, "A binding quantity");
1765
+ }
1766
+ }
1767
+ /** `pm.cost_item.create` → `POST costs`. */
1768
+ async createCostEntry(projectId, req) {
1769
+ const entry = this.oneOf(req.entry, PM_COST_ENTRY_KINDS, "cost entry");
1770
+ const body = { entry };
1771
+ if (req.entry === "item") {
1772
+ this.costItem(req.item);
1773
+ body.item = req.item;
1774
+ } else {
1775
+ this.posting(req.posting, "An actual posting entry needs its posting");
1776
+ body.posting = req.posting;
1777
+ }
1778
+ body.requestKey = this.key(req.requestKey);
1779
+ return this.write("POST", this.path(projectId, "costs"), body);
1780
+ }
1781
+ /** `pm.cost_item.update` → `PATCH costs/:recordId` (cost items only; postings are immutable). */
1782
+ async updateCostItem(projectId, recordId, req) {
1783
+ const patch = this.patch(req.patch);
1784
+ if (patch.remainingEstimate != null) this.money(patch.remainingEstimate, "remainingEstimate");
1785
+ return this.write("PATCH", this.path(projectId, "costs", recordId), {
1786
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1787
+ patch,
1788
+ requestKey: this.key(req.requestKey)
1789
+ });
1790
+ }
1791
+ /** `pm.cost_item.reverse` → `POST costs/:recordId/reverse`: the exact reversal plus an optional replacement. */
1792
+ async reversePosting(projectId, recordId, req) {
1793
+ if (req.replacement) this.posting(req.replacement, "The replacement posting");
1794
+ return this.write("POST", this.path(projectId, "costs", recordId, "reverse"), {
1795
+ reason: this.text(req.reason, "A reversal reason"),
1796
+ incurredOn: req.incurredOn,
1797
+ replacement: req.replacement,
1798
+ requestKey: this.key(req.requestKey)
1799
+ });
1800
+ }
1801
+ /** `pm.finance.calculate` → `POST finance/calculations` (`pm.finance.v1`; stores an immutable analysis). */
1802
+ async calculate(projectId, req = {}) {
1803
+ for (const r of req.rates ?? []) this.decimal(r.rate, "An FX rate");
1804
+ const body = { asOf: req.asOf, reportingCurrency: req.reportingCurrency, rates: req.rates };
1805
+ const res = await this.http.post(this.path(projectId, "finance", "calculations"), { body });
1806
+ return { ...res, reused: res.reused === true };
1807
+ }
1808
+ /** `pm.finance.reconcile` → `POST finance/reconciliations`: records late forecast consumption once. */
1809
+ async reconcile(projectId, req) {
1810
+ if (!Array.isArray(req.items) || req.items.length === 0) throw new Error("A reconciliation names at least one posting.");
1811
+ for (const item of req.items) {
1812
+ this.text(item.postingRecordId, "A reconciliation postingRecordId");
1813
+ this.money(item.consume, "A reconciliation amount");
1814
+ }
1815
+ return this.write("POST", this.path(projectId, "finance", "reconciliations"), {
1816
+ items: req.items,
1817
+ requestKey: this.key(req.requestKey)
1818
+ });
1819
+ }
1820
+ /** `pm.budget.prepare` → `POST budgets`: an immutable candidate, decided separately. */
1821
+ async prepareBudget(projectId, req) {
1822
+ if (!Array.isArray(req.lines) || req.lines.length === 0) throw new Error("A budget needs at least one line.");
1823
+ for (const line of req.lines) this.money(line.approved, "A budget line amount");
1824
+ if (req.contingency !== void 0) this.money(req.contingency, "contingency");
1825
+ return this.write("POST", this.path(projectId, "budgets"), {
1826
+ title: req.title,
1827
+ currency: this.text(req.currency, "A budget currency"),
1828
+ lines: req.lines,
1829
+ contingency: req.contingency,
1830
+ rationale: req.rationale,
1831
+ requestKey: this.key(req.requestKey)
1832
+ });
1833
+ }
1834
+ /** `pm.budget.decide` → `POST budgets/:recordId/decision` (designated budget authority, else the PM). */
1835
+ async decideBudget(projectId, recordId, req) {
1836
+ return this.postDecision(this.path(projectId, "budgets", recordId, "decision"), req, PM_APPROVAL_DECISIONS);
1837
+ }
1838
+ /** `pm.supplier_commitment.create` → `POST supplier-commitments`. */
1839
+ async createSupplierCommitment(projectId, req) {
1840
+ this.money(req.authorizedTotal, "authorizedTotal");
1841
+ if (req.consumesEstimate !== void 0) this.money(req.consumesEstimate, "consumesEstimate");
1842
+ return this.write("POST", this.path(projectId, "supplier-commitments"), {
1843
+ title: this.text(req.title, "A supplier commitment title"),
1844
+ supplierContactId: this.text(req.supplierContactId, "supplierContactId"),
1845
+ accountableContactId: req.accountableContactId,
1846
+ costItemRecordId: this.text(req.costItemRecordId, "costItemRecordId"),
1847
+ authorizedTotal: req.authorizedTotal,
1848
+ contractualRef: req.contractualRef,
1849
+ startDate: req.startDate,
1850
+ endDate: req.endDate,
1851
+ confirmationPosture: this.oneOf(req.confirmationPosture, PM_SUPPLIER_CONFIRMATION_POSTURES, "confirmation posture"),
1852
+ consumesEstimate: req.consumesEstimate,
1853
+ links: req.links,
1854
+ evidenceAdmissionIds: req.evidenceAdmissionIds,
1855
+ requestKey: this.key(req.requestKey)
1856
+ });
1857
+ }
1858
+ /** `pm.supplier_commitment.update` → `PATCH supplier-commitments/:recordId`. */
1859
+ async updateSupplierCommitment(projectId, recordId, req) {
1860
+ const patch = this.patch(req.patch);
1861
+ if (patch.authorizedTotal !== void 0) this.money(patch.authorizedTotal, "authorizedTotal");
1862
+ if (patch.confirmationPosture !== void 0) {
1863
+ this.oneOf(patch.confirmationPosture, PM_SUPPLIER_CONFIRMATION_POSTURES, "confirmation posture");
1864
+ }
1865
+ if (req.consumesEstimate !== void 0) this.money(req.consumesEstimate, "consumesEstimate");
1866
+ return this.write("PATCH", this.path(projectId, "supplier-commitments", recordId), {
1867
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1868
+ patch,
1869
+ consumesEstimate: req.consumesEstimate,
1870
+ evidenceAdmissionIds: req.evidenceAdmissionIds,
1871
+ requestKey: this.key(req.requestKey)
1872
+ });
1873
+ }
1874
+ /** `pm.supplier_commitment.record_outcome` → `POST supplier-commitments/:recordId/outcome`. */
1875
+ async recordSupplierOutcome(projectId, recordId, req) {
1876
+ return this.write("POST", this.path(projectId, "supplier-commitments", recordId, "outcome"), {
1877
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1878
+ outcome: this.oneOf(req.outcome, PM_SUPPLIER_OUTCOMES, "supplier outcome"),
1879
+ observedAt: this.text(req.observedAt, "observedAt"),
1880
+ expectedDeliveryOn: req.expectedDeliveryOn,
1881
+ note: req.note,
1882
+ evidenceAdmissionIds: req.evidenceAdmissionIds,
1883
+ requestKey: this.key(req.requestKey)
1884
+ });
1885
+ }
1886
+ };
1887
+
1888
+ // src/modules/projects/pm/followup.ts
1889
+ var PM_FOLLOWUP_KINDS = [
1890
+ "commitment_due",
1891
+ "commitment_overdue",
1892
+ "risk_review",
1893
+ "pending_record_proposal",
1894
+ "pending_risk_fact",
1895
+ "ownership_decision",
1896
+ "response_decision",
1897
+ "evidence_freshness",
1898
+ "acceptance_pending",
1899
+ "handover_pending",
1900
+ "residual_obligation",
1901
+ "benefit_review"
1902
+ ];
1903
+ function isPmFollowUpKind(value) {
1904
+ return typeof value === "string" && PM_FOLLOWUP_KINDS.includes(value);
1905
+ }
1906
+ var PM_CLOSURE_PREDICATES = [
1907
+ "pm.closure.decision@1",
1908
+ "pm.closure.commitment_outcome@1",
1909
+ "pm.closure.deliverable_acceptance@1",
1910
+ "pm.closure.handover@1",
1911
+ "pm.closure.risk_reviewed@1",
1912
+ "pm.closure.evidence_refreshed@1",
1913
+ "pm.closure.benefit_reviewed@1"
1914
+ ];
1915
+ function isPmClosurePredicate(value) {
1916
+ return typeof value === "string" && PM_CLOSURE_PREDICATES.includes(value);
1917
+ }
1918
+ var PM_FOLLOWUP_STATES = ["open", "blocked", "due", "scheduled", "waiting_decision", "fresh", "stale"];
1919
+ function isPmFollowUpState(value) {
1920
+ return typeof value === "string" && PM_FOLLOWUP_STATES.includes(value);
1921
+ }
1922
+ var PM_FOLLOWUP_RESOLUTIONS = ["pending", "decided", "superseded", "expired", "withdrawn", "not_applicable"];
1923
+ function isPmFollowUpResolution(value) {
1924
+ return typeof value === "string" && PM_FOLLOWUP_RESOLUTIONS.includes(value);
1925
+ }
1926
+ function refOf(r, what) {
1927
+ for (const [v, n] of [[r?.kind, "kind"], [r?.id, "id"]]) {
1928
+ if (typeof v !== "string" || !v.trim() || v.length > 256) throw new Error(`${what} needs a non-blank ${n}.`);
1929
+ }
1930
+ if (r.revision !== void 0 && (typeof r.revision !== "string" || !r.revision.trim() || r.revision.length > 256)) {
1931
+ throw new Error(`${what} revision must be non-blank when given.`);
1932
+ }
1933
+ return { kind: r.kind, id: r.id, revision: r.revision };
1934
+ }
1935
+ var PmFollowupApi = class extends PmApiBase {
1936
+ /** `pm.followup.context` → `POST followup/context`: one bounded, versioned page. */
1937
+ async context(projectId, req = {}) {
1938
+ if (req.limit !== void 0 && !(Number.isInteger(req.limit) && req.limit >= 1 && req.limit <= 200)) {
1939
+ throw new Error("A follow-up page limit is an integer between 1 and 200.");
1940
+ }
1941
+ if (req.obligationRefs !== void 0 && (!Array.isArray(req.obligationRefs) || req.obligationRefs.length > 200)) {
1942
+ throw new Error("Narrow follow-up to at most 200 obligation refs.");
1943
+ }
1944
+ const res = await this.http.post(this.path(projectId, "followup", "context"), {
1945
+ body: {
1946
+ limit: req.limit,
1947
+ cursor: req.cursor,
1948
+ asOf: req.asOf,
1949
+ obligationRefs: req.obligationRefs?.map((r) => refOf(r, "An obligation ref"))
1950
+ }
1951
+ });
1952
+ return {
1953
+ ...res,
1954
+ subjects: (res.subjects ?? []).map(
1955
+ (s) => s.pendingDecision ? { ...s, pendingDecision: { ...s.pendingDecision, decisionOwnerUserIds: s.pendingDecision.decisionOwnerUserIds ?? [] } } : s
1956
+ ),
1957
+ coverage: { ...res.coverage, missing: res.coverage?.missing ?? [] }
1958
+ };
1959
+ }
1960
+ /** `pm.followup.evaluate` → `POST followup/evaluate`: one predicate on one exact subject. */
1961
+ async evaluate(projectId, req) {
1962
+ if (!isPmClosurePredicate(req?.predicate)) throw new Error(`Unsupported closure predicate: ${String(req?.predicate)}.`);
1963
+ const res = await this.http.post(this.path(projectId, "followup", "evaluate"), {
1964
+ body: { subject: refOf(req.subject, "A follow-up subject"), predicate: req.predicate }
1965
+ });
1966
+ return { ...res, evidenceRefs: res.evidenceRefs ?? [] };
1967
+ }
1968
+ };
1969
+
1970
+ // src/modules/projects/pm/governance.ts
1971
+ var PM_LINKABLE_EVIDENCE_KINDS = ["source-doc", "pm-evidence", "pm-record"];
1972
+ var PM_UNLINKABLE_EVIDENCE_KINDS = [
1973
+ ...PM_LINKABLE_EVIDENCE_KINDS,
1974
+ "pm-computation",
1975
+ "pm-analysis",
1976
+ "artifact-version",
1977
+ "chat"
1978
+ ];
1979
+ var PM_EVIDENCE_REF_KINDS = ["observation", "interpretation", "proposal", "decision", "execution"];
1980
+ var PM_EVIDENCE_ADMISSION_STATES = ["admitted", "withdrawn"];
1981
+ var PM_DISPOSITION_HOLD_KINDS = ["authority_unresolved", "execution_unavailable"];
1982
+ function isPmDispositionHoldKind(value) {
1983
+ return typeof value === "string" && PM_DISPOSITION_HOLD_KINDS.includes(value);
1984
+ }
1985
+ var PmGovernanceApi = class extends PmWriteApiBase {
1986
+ async run(path2, body) {
1987
+ return this.written(await this.http.post(path2, { body }));
1988
+ }
1989
+ change(req, kinds) {
1990
+ const e = req.evidence;
1991
+ return {
1992
+ recordId: this.text(req.recordId, "recordId"),
1993
+ expectedRevisionId: this.text(req.expectedRevisionId, "expectedRevisionId"),
1994
+ evidence: { kind: this.oneOf(e?.kind, kinds, "evidence kind"), ref: this.text(e.ref, "An evidence ref"), version: e.version, field: e.field, span: e.span },
1995
+ requestKey: this.key(req.requestKey)
1996
+ };
1997
+ }
1998
+ /** `pm.evidence.link` → `POST evidence/links`: a new revision citing the evidence. */
1999
+ async linkEvidence(projectId, req) {
2000
+ return this.run(this.path(projectId, "evidence", "links"), this.change(req, PM_LINKABLE_EVIDENCE_KINDS));
2001
+ }
2002
+ /** `pm.evidence.unlink` → `POST evidence/unlinks`: removes every entry of that kind and ref (audit retained). */
2003
+ async unlinkEvidence(projectId, req) {
2004
+ return this.run(this.path(projectId, "evidence", "unlinks"), this.change(req, PM_UNLINKABLE_EVIDENCE_KINDS));
2005
+ }
2006
+ /** `pm.evidence.admit` → `POST evidence/admissions`: admits one exact source version for a destination use. */
2007
+ async admitEvidence(projectId, req) {
2008
+ const r = req.ref;
2009
+ this.text(r?.sourceProduct, "A source product");
2010
+ this.text(r.sourceObjectRef, "A source object ref");
2011
+ this.text(r.versionOrDigest, "An exact version or digest");
2012
+ this.oneOf(r.kind, PM_EVIDENCE_REF_KINDS, "evidence ref kind");
2013
+ if (this.text(req.use, "A destination use").startsWith("current:") && !r.observedAt) {
2014
+ throw new Error("Current-state evidence needs its observation time.");
2015
+ }
2016
+ const body = { ref: r, use: req.use, requestKey: this.key(req.requestKey) };
2017
+ return this.written(await this.http.post(this.path(projectId, "evidence", "admissions"), { body }));
2018
+ }
2019
+ /** `pm.document.register` → `POST documents/registrations`. */
2020
+ async registerDocument(projectId, req) {
2021
+ if (!req.source === !req.content) throw new Error("A registration carries either content or an exact source version.");
2022
+ if (req.source) {
2023
+ this.text(req.source.artifactId, "A source artifactId");
2024
+ this.text(req.source.versionId, "A source versionId");
2025
+ }
2026
+ return this.run(this.path(projectId, "documents", "registrations"), {
2027
+ title: req.title,
2028
+ classification: req.classification,
2029
+ contentType: req.contentType,
2030
+ content: req.content,
2031
+ source: req.source && { artifactId: req.source.artifactId, versionId: req.source.versionId },
2032
+ declaredSource: req.declaredSource,
2033
+ attested: req.attested,
2034
+ attestNote: req.attestNote,
2035
+ requestKey: this.key(req.requestKey)
2036
+ });
2037
+ }
2038
+ /** `pm.attestation.withdraw` → `POST documents/:docId/attestation/withdraw` (append-only). */
2039
+ async withdrawAttestation(projectId, docId, req) {
2040
+ return this.run(this.path(projectId, "documents", docId, "attestation", "withdraw"), {
2041
+ attestationEventId: this.text(req.attestationEventId, "attestationEventId"),
2042
+ reason: this.text(req.reason, "A withdrawal reason"),
2043
+ requestKey: this.key(req.requestKey)
2044
+ });
2045
+ }
2046
+ /** `pm.document.revise` → `POST documents/:docId/revisions`; the new version is unattested until attested; a removed document is restored first. */
2047
+ async reviseDocument(projectId, docId, req) {
2048
+ if (!req.content) throw new Error("A revision carries the new content.");
2049
+ return this.run(this.path(projectId, "documents", docId, "revisions"), {
2050
+ expectedVersionId: this.text(req.expectedVersionId, "expectedVersionId"),
2051
+ content: req.content,
2052
+ contentType: req.contentType,
2053
+ changeNote: req.changeNote,
2054
+ requestKey: this.key(req.requestKey)
2055
+ });
2056
+ }
2057
+ /**
2058
+ * `pm.document.disposition.decide` → `POST disposition-requests/:reqId/decide`.
2059
+ * Only the resolved disposition authority may decide; an approval executes
2060
+ * server-side as an append-only logical removal (PC-D02) — nothing is erased.
2061
+ */
2062
+ async decideDisposition(projectId, reqId, req) {
2063
+ const body = {
2064
+ expectedVersion: this.text(req.expectedVersion, "expectedVersion"),
2065
+ decision: this.oneOf(req.decision, ["denied", "deferred", "approved"], "decision"),
2066
+ reason: this.text(req.reason, "A decision reason"),
2067
+ policyBasis: this.text(req.policyBasis, "A policy basis"),
2068
+ requestKey: this.key(req.requestKey)
2069
+ };
2070
+ return this.decided(await this.http.post(this.path(projectId, "disposition-requests", reqId, "decide"), { body }));
2071
+ }
2072
+ /**
2073
+ * `pm.document.restore` → `POST documents/:docId/restore`. Only the CURRENT
2074
+ * disposition authority with write access; appends a restoration naming the
2075
+ * removal. It revives no attestation or approval (authority to share needs a
2076
+ * fresh attestation), grants no access and replays no send.
2077
+ */
2078
+ async restoreDocument(projectId, docId, req) {
2079
+ return this.run(this.path(projectId, "documents", docId, "restore"), {
2080
+ removalEventId: this.text(req.removalEventId, "removalEventId"),
2081
+ reason: this.text(req.reason, "A restoration reason"),
2082
+ requestKey: this.key(req.requestKey)
2083
+ });
2084
+ }
2085
+ /** `pm.document.disposition.inspect` → `GET disposition-requests/:reqId`. */
2086
+ async getDisposition(projectId, reqId) {
2087
+ return this.http.get(this.path(projectId, "disposition-requests", reqId));
2088
+ }
2089
+ };
2090
+
2091
+ // src/modules/projects/pm/people.ts
2092
+ var PM_PROJECT_ROLES = ["manager", "member", "reader"];
2093
+ var PM_CURRENCY_POLICIES = ["single", "multi_explicit_fx"];
2094
+ var PM_STAKEHOLDER_INFLUENCES = ["low", "medium", "high"];
2095
+ var PM_DECISION_AUTHORITY_KINDS = ["charter", "baseline", "budget", "acceptance", "closure", "handover_receiver"];
2096
+ var PM_DELIVERY_AUTHORITY_KINDS = ["delivery_owner", "delivery_pm", "delivery_escalation_manager", "delivery_sponsor"];
2097
+ var AUTHORITY_KINDS = [...PM_DECISION_AUTHORITY_KINDS, ...PM_DELIVERY_AUTHORITY_KINDS];
2098
+ var PM_OWNERSHIP_DECISIONS = ["accept", "decline"];
2099
+ var PM_COMMITMENT_SOURCE_KINDS = ["meeting", "chat", "risk_response", "change", "other"];
2100
+ var PM_COMMITMENT_OUTCOMES = ["met", "missed", "cancelled", "superseded"];
2101
+ var PM_RESPONSE_REVIEW_OUTCOMES = ["on_track", "completed", "ineffective", "abandoned"];
2102
+ var OUTCOMES = [...PM_COMMITMENT_OUTCOMES, ...PM_RESPONSE_REVIEW_OUTCOMES];
2103
+ var PmPeopleApi = class extends PmWriteApiBase {
2104
+ async run(method, path2, body) {
2105
+ return this.written(await this.http.request(method, path2, { body }));
2106
+ }
2107
+ citations(list) {
2108
+ for (const c of list ?? []) {
2109
+ this.text(c?.kind, "A citation kind");
2110
+ this.text(c?.ref, "A citation ref");
2111
+ }
2112
+ }
2113
+ commitmentFields(c) {
2114
+ if (c.checks != null && (!Array.isArray(c.checks) || c.checks.length > 20)) throw new Error("A commitment has at most 20 checks.");
2115
+ for (const check of c.checks ?? []) this.text(check, "A commitment check");
2116
+ }
2117
+ /** `pm.project.update` → `PATCH context`: the name and/or the project context. */
2118
+ async updateProject(projectId, req) {
2119
+ if (req.name === void 0 && req.context === void 0) throw new Error("An update names the project or patches its context.");
2120
+ if (req.name !== void 0 && this.text(req.name, "A project name").trim().length > 255) {
2121
+ throw new Error("A project name is at most 255 characters.");
2122
+ }
2123
+ if (req.context !== void 0) {
2124
+ const c = this.patch(req.context);
2125
+ if (c.standardDayMinutes !== void 0 && !(Number.isInteger(c.standardDayMinutes) && c.standardDayMinutes >= 1 && c.standardDayMinutes <= 1440)) {
2126
+ throw new Error("standardDayMinutes is a whole number between 1 and 1440.");
2127
+ }
2128
+ if (c.currencyPolicy != null) this.oneOf(c.currencyPolicy, PM_CURRENCY_POLICIES, "currency policy");
2129
+ }
2130
+ return this.run("PATCH", this.path(projectId, "context"), {
2131
+ name: req.name,
2132
+ expectedContextRevisionId: req.expectedContextRevisionId,
2133
+ context: req.context,
2134
+ requestKey: this.key(req.requestKey)
2135
+ });
2136
+ }
2137
+ /** `pm.brief.update` → `PATCH brief`: scope text, the complete objective list and benefits. */
2138
+ async updateBrief(projectId, req) {
2139
+ if (req.patch === void 0 && req.objectives === void 0 && req.benefits === void 0) {
2140
+ throw new Error("A brief update patches the brief, its objectives or its benefits.");
2141
+ }
2142
+ if (req.patch !== void 0) this.patch(req.patch);
2143
+ if (req.objectives !== void 0 && (!Array.isArray(req.objectives) || req.objectives.length > 20)) {
2144
+ throw new Error("A brief has at most 20 objectives.");
2145
+ }
2146
+ for (const o of req.objectives ?? []) {
2147
+ this.text(o.statement, "An objective statement");
2148
+ for (const m of o.successMeasures ?? []) {
2149
+ this.text(m.measure, "A success measure");
2150
+ this.decimal(m.target, "A success measure target");
2151
+ if (m.baseline !== void 0) this.decimal(m.baseline, "A success measure baseline");
2152
+ }
2153
+ }
2154
+ for (const b of req.benefits ?? []) assertPmBenefitInput(b);
2155
+ return this.run("PATCH", this.path(projectId, "brief"), {
2156
+ expectedContextRevisionId: req.expectedContextRevisionId,
2157
+ patch: req.patch,
2158
+ objectives: req.objectives,
2159
+ benefits: req.benefits,
2160
+ requestKey: this.key(req.requestKey)
2161
+ });
2162
+ }
2163
+ /** `pm.charter.read` → `GET charter`. */
2164
+ async getCharter(projectId) {
2165
+ return this.http.get(this.path(projectId, "charter"));
2166
+ }
2167
+ /** `pm.charter.draft` → `POST charter/drafts`: a new charter version (never approval). */
2168
+ async draftCharter(projectId, req) {
2169
+ if (req.expectedVersionId !== null) this.text(req.expectedVersionId, "expectedVersionId (null for the first draft)");
2170
+ this.citations(req.citations);
2171
+ return this.run("POST", this.path(projectId, "charter", "drafts"), {
2172
+ expectedVersionId: req.expectedVersionId,
2173
+ content: this.text(req.content, "Charter content"),
2174
+ changeNote: req.changeNote,
2175
+ classification: req.classification,
2176
+ citations: req.citations,
2177
+ requestKey: this.key(req.requestKey)
2178
+ });
2179
+ }
2180
+ /** `pm.charter.decide` → `POST charter/decision` (the designated charter authority, else the PM). */
2181
+ async decideCharter(projectId, req) {
2182
+ return this.postDecision(this.path(projectId, "charter", "decision"), req, PM_APPROVAL_DECISIONS, {
2183
+ artifactId: this.text(req.artifactId, "artifactId")
2184
+ });
2185
+ }
2186
+ /** `pm.stakeholder.set` → `PUT stakeholders`. */
2187
+ async setStakeholder(projectId, req) {
2188
+ if (req.patch !== void 0) {
2189
+ const p = this.patch(req.patch);
2190
+ if (p.influence != null) this.oneOf(p.influence, PM_STAKEHOLDER_INFLUENCES, "influence");
2191
+ const prefs = p.communicationPrefs;
2192
+ if (prefs != null && (typeof prefs !== "object" || Array.isArray(prefs))) throw new Error("communicationPrefs is an object.");
2193
+ }
2194
+ return this.run("PUT", this.path(projectId, "stakeholders"), {
2195
+ contactId: this.text(req.contactId, "contactId"),
2196
+ expectedCurrentRevisionId: req.expectedCurrentRevisionId,
2197
+ patch: req.patch,
2198
+ requestKey: this.key(req.requestKey)
2199
+ });
2200
+ }
2201
+ /** `pm.stakeholder.retire` → `POST stakeholders/:recordId/retire` at the exact revision. */
2202
+ async retireStakeholder(projectId, recordId, req) {
2203
+ return this.run("POST", this.path(projectId, "stakeholders", recordId, "retire"), {
2204
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2205
+ requestKey: this.key(req.requestKey)
2206
+ });
2207
+ }
2208
+ membership(projectId, action, body) {
2209
+ return this.run("POST", this.path(projectId, "membership", action), body);
2210
+ }
2211
+ /** `pm.membership.grant` → `POST membership/grant` (the manager's; a same-org user). */
2212
+ async grantMembership(projectId, req) {
2213
+ return this.membership(projectId, "grant", {
2214
+ userId: this.text(req.userId, "userId"),
2215
+ role: this.oneOf(req.role, PM_PROJECT_ROLES, "project role"),
2216
+ requestKey: this.key(req.requestKey)
2217
+ });
2218
+ }
2219
+ /** `pm.membership.change` → `POST membership/change` (removing the last manager refuses with `last_manager`). */
2220
+ async changeMembership(projectId, req) {
2221
+ return this.membership(projectId, "change", {
2222
+ userId: this.text(req.userId, "userId"),
2223
+ role: this.oneOf(req.role, PM_PROJECT_ROLES, "project role"),
2224
+ requestKey: this.key(req.requestKey)
2225
+ });
2226
+ }
2227
+ /** `pm.membership.revoke` → `POST membership/revoke` (takes no role). */
2228
+ async revokeMembership(projectId, req) {
2229
+ return this.membership(projectId, "revoke", { userId: this.text(req.userId, "userId"), requestKey: this.key(req.requestKey) });
2230
+ }
2231
+ /** `pm.membership.list_recoverable` → `GET /pm/projects/recoverable` (org roles only; recover via `recoverPMManagement`). */
2232
+ async listRecoverable() {
2233
+ const res = await this.http.get("/pm/projects/recoverable");
2234
+ return res.projects ?? [];
2235
+ }
2236
+ /** `pm.authority.read` → `GET decision-authority`: every designated and resolved decision-maker. */
2237
+ async getAuthority(projectId) {
2238
+ const res = await this.http.get(this.path(projectId, "decision-authority"));
2239
+ return { ...res, decisions: res.decisions ?? [] };
2240
+ }
2241
+ /** `pm.authority.designate` → `PUT decision-authority` (the manager's). */
2242
+ async designateAuthority(projectId, req) {
2243
+ if (req.userId !== null) this.text(req.userId, "userId (null clears the designation)");
2244
+ const out = await this.run("PUT", this.path(projectId, "decision-authority"), {
2245
+ kind: this.oneOf(req.kind, AUTHORITY_KINDS, "authority kind"),
2246
+ userId: req.userId,
2247
+ requestKey: this.key(req.requestKey)
2248
+ });
2249
+ return { ...out, result: { ...out.result, decisions: out.result?.decisions ?? [] } };
2250
+ }
2251
+ /** `pm.ownership.propose` → `POST ownership/proposals`. */
2252
+ async proposeOwnership(projectId, req) {
2253
+ return this.run("POST", this.path(projectId, "ownership", "proposals"), {
2254
+ recordId: this.text(req.recordId, "recordId"),
2255
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2256
+ contactId: this.text(req.contactId, "contactId"),
2257
+ requestKey: this.key(req.requestKey)
2258
+ });
2259
+ }
2260
+ /** `pm.ownership.decide` → `POST ownership/:recordId/decision` (the proposed owner's linked user). */
2261
+ async decideOwnership(projectId, recordId, req) {
2262
+ return this.postDecision(this.path(projectId, "ownership", recordId, "decision"), req, PM_OWNERSHIP_DECISIONS);
2263
+ }
2264
+ /** `pm.commitment.create` → `POST commitments`. */
2265
+ async createCommitment(projectId, req) {
2266
+ this.commitmentFields(req);
2267
+ this.citations(req.citations);
2268
+ return this.run("POST", this.path(projectId, "commitments"), {
2269
+ terms: this.text(req.terms, "Commitment terms"),
2270
+ dueCondition: req.dueCondition,
2271
+ dueAt: req.dueAt,
2272
+ sourceKind: this.oneOf(req.sourceKind, PM_COMMITMENT_SOURCE_KINDS, "commitment source kind"),
2273
+ sourceRef: req.sourceRef,
2274
+ checks: req.checks,
2275
+ subjectRecordIds: req.subjectRecordIds,
2276
+ ownerContactId: req.ownerContactId,
2277
+ citations: req.citations,
2278
+ requestKey: this.key(req.requestKey)
2279
+ });
2280
+ }
2281
+ /** `pm.commitment.update` → `PATCH commitments/:recordId` (owner via ownership, outcome via `recordCommitmentOutcome`). */
2282
+ async updateCommitment(projectId, recordId, req) {
2283
+ const patch = this.patch(req.patch);
2284
+ if (patch.terms !== void 0) this.text(patch.terms, "Commitment terms");
2285
+ this.commitmentFields(patch);
2286
+ return this.run("PATCH", this.path(projectId, "commitments", recordId), {
2287
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2288
+ patch: req.patch,
2289
+ requestKey: this.key(req.requestKey)
2290
+ });
2291
+ }
2292
+ /** `pm.commitment.record_outcome` → `POST commitments/:recordId/outcome` (allowed after closure). */
2293
+ async recordCommitmentOutcome(projectId, recordId, req) {
2294
+ this.citations(req.citations);
2295
+ return this.run("POST", this.path(projectId, "commitments", recordId, "outcome"), {
2296
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2297
+ outcome: this.oneOf(req.outcome, OUTCOMES, "commitment outcome"),
2298
+ observedAt: this.text(req.observedAt, "observedAt"),
2299
+ note: req.note,
2300
+ observedProgress: req.observedProgress,
2301
+ residual: req.residual,
2302
+ citations: req.citations,
2303
+ requestKey: this.key(req.requestKey)
2304
+ });
2305
+ }
2306
+ };
2307
+
2308
+ // src/modules/projects/pm/portfolio.ts
2309
+ var PM_PORTFOLIO_RELATIONS = ["shares_resource", "shares_supplier", "program_member", "depends_on"];
2310
+ var PM_COORDINATION_STATES = ["prepared", "deciding", "applying", "completed", "partial", "cancelled"];
2311
+ function isPmCoordinationState(value) {
2312
+ return typeof value === "string" && PM_COORDINATION_STATES.includes(value);
2313
+ }
2314
+ var PM_COORDINATION_ITEM_OUTCOMES = ["pending", "applied", "refused", "stale", "unknown", "withdrawn"];
2315
+ function isPmCoordinationItemOutcome(value) {
2316
+ return typeof value === "string" && PM_COORDINATION_ITEM_OUTCOMES.includes(value);
2317
+ }
2318
+ var PM_COORDINATION_DECISION_STATES = ["pending", "approved", "rejected"];
2319
+ var PM_INCOMPARABILITY_CODES = ["currency_mismatch", "estimate_unknown", "horizon_mismatch", "finish_unknown", "timezone_mismatch"];
2320
+ var PmPortfolioApi = class extends PmWriteApiBase {
2321
+ org(...segments) {
2322
+ for (const s of segments) this.text(s, "A portfolio id");
2323
+ return ["/pm/portfolio", ...segments.map(encodeURIComponent)].join("/");
2324
+ }
2325
+ ids(ids, min, max, what) {
2326
+ if (!Array.isArray(ids) || ids.length < min || ids.length > max) throw new Error(`${what} names ${min} to ${max} projects.`);
2327
+ for (const id of ids) this.text(id, "A project id");
2328
+ return ids;
2329
+ }
2330
+ coordination(c) {
2331
+ return { ...c, items: (c.items ?? []).map((i) => ({ ...i, waitingFor: i.waitingFor ?? [], rejectedBy: i.rejectedBy ?? [] })) };
2332
+ }
2333
+ /** `pm.portfolio.associate` → `POST /project/:id/pm/portfolio/associations`. */
2334
+ async setAssociation(projectId, req) {
2335
+ if (req.priorityRank !== void 0 && !(Number.isInteger(req.priorityRank) && req.priorityRank >= 1 && req.priorityRank <= 1e3)) {
2336
+ throw new Error("priorityRank is an integer between 1 and 1000.");
2337
+ }
2338
+ if (!req.peerRecordId !== !req.peerRevisionId) throw new Error("A peer record needs its exact revision.");
2339
+ if (!req.recordId !== !req.expectedRevisionId) throw new Error("An existing association needs its expected revision.");
2340
+ const body = {
2341
+ recordId: req.recordId,
2342
+ expectedRevisionId: req.expectedRevisionId,
2343
+ peerProjectId: this.text(req.peerProjectId, "peerProjectId"),
2344
+ relation: this.oneOf(req.relation, PM_PORTFOLIO_RELATIONS, "portfolio relation"),
2345
+ peerRecordId: req.peerRecordId,
2346
+ peerRevisionId: req.peerRevisionId,
2347
+ priorityRank: req.priorityRank,
2348
+ investmentCategory: req.investmentCategory,
2349
+ active: req.active,
2350
+ requestKey: this.key(req.requestKey)
2351
+ };
2352
+ return this.written(await this.http.post(this.path(projectId, "portfolio", "associations"), { body }));
2353
+ }
2354
+ /** `pm.portfolio.query` → `POST /pm/portfolio/query`: the named (or all readable, ≤50) projects. */
2355
+ async query(req = {}) {
2356
+ const projectIds = req.projectIds === void 0 ? void 0 : this.ids(req.projectIds, 1, 50, "A portfolio query");
2357
+ const res = await this.http.post(this.org("query"), { body: { projectIds } });
2358
+ return {
2359
+ ...res,
2360
+ projects: (res.projects ?? []).map((p) => ({ ...p, associations: p.associations ?? [] })),
2361
+ notAvailable: res.notAvailable ?? []
2362
+ };
2363
+ }
2364
+ /** `pm.portfolio.compare` → `POST /pm/portfolio/compare`: per-project pinned analyses; incomparability listed. */
2365
+ async compare(req) {
2366
+ const p = req.personCapacity;
2367
+ if (p) for (const v of [p.projectId, p.recordId, p.revisionId]) this.text(v, "A personCapacity reference");
2368
+ const body = { projectIds: this.ids(req.projectIds, 1, 10, "A comparison"), asOf: req.asOf, personCapacity: p };
2369
+ const res = await this.http.post(this.org("compare"), { body });
2370
+ const c = res.comparison ?? {};
2371
+ return {
2372
+ ...res,
2373
+ projects: res.projects ?? [],
2374
+ notAvailable: res.notAvailable ?? [],
2375
+ comparison: {
2376
+ ...c,
2377
+ projects: (c.projects ?? []).map((pos) => ({ ...pos, currencies: pos.currencies ?? [] })),
2378
+ incomparable: c.incomparable ?? []
2379
+ }
2380
+ };
2381
+ }
2382
+ /** `pm.portfolio.prepare_coordination` → `POST /pm/portfolio/coordinations` (or `action: cancel`; applied items stay). */
2383
+ async prepareCoordination(req) {
2384
+ let body;
2385
+ if (req.action === "cancel") {
2386
+ body = { action: "cancel", coordinationId: this.text(req.coordinationId, "coordinationId"), requestKey: this.key(req.requestKey) };
2387
+ } else {
2388
+ if (req.action !== void 0 && req.action !== "prepare") throw new Error(`Unsupported coordination action: ${String(req.action)}.`);
2389
+ const projects = req.projects;
2390
+ this.ids(projects?.map((p) => p.projectId), 2, 10, "A coordination");
2391
+ if (new Set(projects.map((p) => p.projectId)).size !== projects.length) throw new Error("A coordination changes distinct projects.");
2392
+ for (const { scenario } of projects) {
2393
+ this.text(scenario?.title, "A scenario title");
2394
+ if (!Array.isArray(scenario.patchSet) || scenario.patchSet.length < 1 || scenario.patchSet.length > 200) {
2395
+ throw new Error("A scenario carries 1 to 200 typed ops.");
2396
+ }
2397
+ for (const op of scenario.patchSet) this.oneOf(op.op, PM_SCENARIO_OPS, "scenario op");
2398
+ }
2399
+ body = { action: req.action, title: this.text(req.title, "A coordination title"), rationale: req.rationale, projects, requestKey: this.key(req.requestKey) };
2400
+ }
2401
+ const res = this.written(await this.http.post(this.org("coordinations"), { body }));
2402
+ return { ...res, coordination: this.coordination(res.coordination) };
2403
+ }
2404
+ /** `pm.portfolio.inspect_coordination` → `GET /pm/portfolio/coordinations/:coordinationId`. */
2405
+ async inspectCoordination(coordinationId) {
2406
+ return this.coordination(await this.http.get(this.org("coordinations", coordinationId)));
2407
+ }
2408
+ /** `pm.portfolio.continue_coordination` → `POST …/continue`: applies decided items, one project at a time. */
2409
+ async continueCoordination(coordinationId) {
2410
+ const res = await this.http.post(this.org("coordinations", coordinationId, "continue"), { body: {} });
2411
+ return {
2412
+ coordination: this.coordination(res.coordination),
2413
+ attempts: (res.attempts ?? []).map((a) => a.applyOperation ? { ...a, applyOperation: this.op(a.applyOperation) } : a)
2414
+ };
2415
+ }
2416
+ /**
2417
+ * `pm.portfolio.decide_coordination` → `POST …/projects/:projectId/decision`:
2418
+ * that project's change decision on its scenario revision (`expectedVersion`).
2419
+ */
2420
+ async decideCoordinationItem(coordinationId, projectId, req) {
2421
+ return this.postDecision(this.org("coordinations", coordinationId, "projects", projectId, "decision"), req, PM_APPROVAL_DECISIONS);
2422
+ }
2423
+ };
2424
+
2425
+ // src/modules/projects/pm/reports.ts
2426
+ var PM_REPORT_TYPES = ["pm.status-report/v1", "pm.risk-brief/v1", "pm.change-brief/v1", "pm.closure-report/v1"];
2427
+ function isPmReportType(value) {
2428
+ return typeof value === "string" && PM_REPORT_TYPES.includes(value);
2429
+ }
2430
+ var PM_REPORT_VERSION_KINDS = ["generate", "revise", "refresh"];
2431
+ function isPmReportVersionKind(value) {
2432
+ return typeof value === "string" && PM_REPORT_VERSION_KINDS.includes(value);
2433
+ }
2434
+ var PM_REPORT_NARRATIVE_LIMITS = { title: 200, audience: 200, summary: 4e3, commentary: 8e3 };
2435
+ var PM_REPORT_PAGE_SIZES = ["A4", "LETTER"];
2436
+ var MAX_BRIEF_RISKS = 200;
2437
+ var LANGUAGE = /^[a-z]{2,3}(-[A-Za-z0-9]{1,8}){0,3}$/;
2438
+ var UNPRINTABLE = /[\p{Cc}\p{Cf}\p{Co}\p{Cs}]/u;
2439
+ var UNPRINTABLE_MULTILINE = /[^\P{Cc}\n\t]|[\p{Cf}\p{Co}\p{Cs}]/u;
2440
+ var PmReportsApi = class extends PmWriteApiBase {
2441
+ narrative(n) {
2442
+ if (n === void 0) return void 0;
2443
+ if (!n || typeof n !== "object" || Array.isArray(n)) throw new Error("A report narrative must be an object.");
2444
+ for (const field of ["title", "audience", "summary", "commentary"]) {
2445
+ const v = n[field];
2446
+ if (v === void 0) continue;
2447
+ const multiline = field === "summary" || field === "commentary";
2448
+ if (typeof v !== "string" || [...v].length > PM_REPORT_NARRATIVE_LIMITS[field] || (multiline ? UNPRINTABLE_MULTILINE : UNPRINTABLE).test(v)) {
2449
+ throw new Error(
2450
+ `A narrative ${field} must be text of at most ${PM_REPORT_NARRATIVE_LIMITS[field]} characters without control or format characters.`
2451
+ );
2452
+ }
2453
+ }
2454
+ return { title: n.title, audience: n.audience, summary: n.summary, commentary: n.commentary };
2455
+ }
2456
+ write(path2, body) {
2457
+ return this.http.post(path2, { body }).then((r) => this.written(r));
2458
+ }
2459
+ /** `pm.report.generate` → `POST reports`. */
2460
+ async generate(projectId, req) {
2461
+ const reportType = this.oneOf(req.reportType, PM_REPORT_TYPES, "report type");
2462
+ const status = reportType === "pm.status-report/v1";
2463
+ if (status && (req.narrative !== void 0 || req.riskIds !== void 0 || req.scenarioRecordId !== void 0)) {
2464
+ throw new Error("A status report takes only expectedVersionId and focus.");
2465
+ }
2466
+ if (!status && req.focus !== void 0) throw new Error("focus applies to the status report only.");
2467
+ if (req.riskIds !== void 0 && (reportType !== "pm.risk-brief/v1" || !Array.isArray(req.riskIds) || req.riskIds.length > MAX_BRIEF_RISKS)) {
2468
+ throw new Error(`riskIds select at most ${MAX_BRIEF_RISKS} risks of a risk brief.`);
2469
+ }
2470
+ if (reportType === "pm.change-brief/v1" !== (req.scenarioRecordId !== void 0)) {
2471
+ throw new Error("A change brief, and only a change brief, names its scenarioRecordId.");
2472
+ }
2473
+ const body = {
2474
+ reportType,
2475
+ expectedVersionId: req.expectedVersionId === void 0 ? void 0 : this.text(req.expectedVersionId, "expectedVersionId"),
2476
+ narrative: this.narrative(req.narrative),
2477
+ riskIds: req.riskIds,
2478
+ scenarioRecordId: req.scenarioRecordId === void 0 ? void 0 : this.text(req.scenarioRecordId, "scenarioRecordId"),
2479
+ focus: req.focus,
2480
+ requestKey: this.key(req.requestKey)
2481
+ };
2482
+ return this.write(this.path(projectId, "reports"), body);
2483
+ }
2484
+ /** `pm.report.revise` → `POST reports/:reportId/revisions`: a new narrative on the exact head; facts stay frozen. */
2485
+ async revise(projectId, reportId, req) {
2486
+ if (req.narrative === void 0) throw new Error("A report revision needs a narrative.");
2487
+ return this.write(this.path(projectId, "reports", reportId, "revisions"), {
2488
+ expectedVersionId: this.text(req.expectedVersionId, "expectedVersionId"),
2489
+ narrative: this.narrative(req.narrative),
2490
+ requestKey: this.key(req.requestKey)
2491
+ });
2492
+ }
2493
+ /** `pm.report.refresh` → `POST reports/:reportId/refresh`: the head's selection over current data, as a new version. */
2494
+ async refresh(projectId, reportId, req) {
2495
+ return this.write(this.path(projectId, "reports", reportId, "refresh"), {
2496
+ expectedVersionId: this.text(req.expectedVersionId, "expectedVersionId"),
2497
+ requestKey: this.key(req.requestKey)
2498
+ });
2499
+ }
2500
+ /**
2501
+ * `pm.report.export` → `POST reports/:reportId/versions/:versionId/exports`.
2502
+ * Answers when the render settles: `ready` (download the output), `failed`
2503
+ * (with its stage; retry with the SAME key) or `blocked`.
2504
+ */
2505
+ async export(projectId, reportId, versionId, req) {
2506
+ if (req.format !== void 0) this.oneOf(req.format, ["pdf"], "export format");
2507
+ if (req.pageSize !== void 0) this.oneOf(req.pageSize, PM_REPORT_PAGE_SIZES, "page size");
2508
+ if (req.language !== void 0 && !LANGUAGE.test(req.language)) throw new Error("language must be a BCP 47 tag.");
2509
+ const body = { format: req.format, pageSize: req.pageSize, language: req.language, requestKey: this.key(req.requestKey) };
2510
+ const res = await this.http.post(this.path(projectId, "reports", reportId, "versions", versionId, "exports"), { body });
2511
+ return this.written(res);
2512
+ }
2513
+ /** `pm.report.inspect` → `GET reports/:reportId[/versions/:versionId]`. */
2514
+ async inspect(projectId, reportId, options = {}) {
2515
+ const path2 = options.versionId === void 0 ? this.path(projectId, "reports", reportId) : this.path(projectId, "reports", reportId, "versions", options.versionId);
2516
+ const res = await this.http.get(path2);
2517
+ return { ...res, versions: res.versions ?? [], exports: res.exports ?? [] };
2518
+ }
2519
+ /** `pm.report.inspect` for one export → `GET exports/:exportId`: state, failed stage, retryability. */
2520
+ async inspectExport(projectId, exportId) {
2521
+ return this.http.get(this.path(projectId, "exports", exportId));
2522
+ }
2523
+ };
2524
+
2525
+ // src/modules/projects/pm/risk.ts
2526
+ var PM_RISK_POLARITIES = ["threat", "opportunity"];
2527
+ var PM_RISK_OCCURRENCE_STATES = ["open", "occurred", "closed_not_occurred", "expired"];
2528
+ function isPmRiskOccurrenceState(value) {
2529
+ return typeof value === "string" && PM_RISK_OCCURRENCE_STATES.includes(value);
2530
+ }
2531
+ var PM_RISK_OUTCOME_MEASURES = ["cost_delta", "duration_delta", "benefit_delta"];
2532
+ var PM_RISK_CALCULATION_METHODS = ["pm.risk.v1", "pm.sensitivity.v1", "monte_carlo"];
2533
+ var PM_RAID_LIFECYCLE_STATES = ["open", "monitoring", "resolved", "invalidated", "recorded"];
2534
+ function isPmRaidLifecycleState(value) {
2535
+ return typeof value === "string" && PM_RAID_LIFECYCLE_STATES.includes(value);
2536
+ }
2537
+ var DECIMAL_FIELDS = ["probability", "lower", "base", "upper"];
2538
+ var PmRiskApi = class extends PmWriteApiBase {
2539
+ outcomes(list) {
2540
+ for (const o of list ?? []) {
2541
+ this.oneOf(o.measure, PM_RISK_OUTCOME_MEASURES, "risk outcome measure");
2542
+ for (const f of DECIMAL_FIELDS) if (o[f] !== void 0 || f === "base") this.decimal(o[f], `An outcome ${f}`);
2543
+ }
2544
+ }
2545
+ withOperation(raw) {
2546
+ const { success: _success, ...rest } = raw;
2547
+ return rest.operation ? { ...rest, operation: this.op(rest.operation) } : rest;
2548
+ }
2549
+ riskWrite(method, path2, body) {
2550
+ return this.http.request(method, path2, { body }).then((r) => this.withOperation(r));
2551
+ }
2552
+ raidWrite(method, path2, req) {
2553
+ if (req.lifecycleState !== void 0) this.oneOf(req.lifecycleState, PM_RAID_LIFECYCLE_STATES, "lifecycle state");
2554
+ const body = {
2555
+ title: this.text(req.title, "A title"),
2556
+ description: req.description,
2557
+ lifecycleState: req.lifecycleState,
2558
+ reviewDueAt: req.reviewDueAt,
2559
+ reviewTrigger: req.reviewTrigger,
2560
+ source: req.source,
2561
+ ownerContactId: req.ownerContactId,
2562
+ affectedWorkIds: req.affectedWorkIds,
2563
+ relatedRiskIds: req.relatedRiskIds,
2564
+ citations: req.citations,
2565
+ requestKey: this.key(req.requestKey)
2566
+ };
2567
+ return this.http.request(method, path2, { body }).then((r) => this.withOperation(r));
2568
+ }
2569
+ raidUpdate(path2, req) {
2570
+ const patch = this.patch(req.patch);
2571
+ if (patch.lifecycleState !== void 0) this.oneOf(patch.lifecycleState, PM_RAID_LIFECYCLE_STATES, "lifecycle state");
2572
+ const body = {
2573
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2574
+ patch,
2575
+ requestKey: this.key(req.requestKey)
2576
+ };
2577
+ return this.http.patch(path2, { body }).then((r) => this.withOperation(r));
2578
+ }
2579
+ /** `pm.risk.create` → `POST risks` (the extended confirmation body). */
2580
+ async createRisk(projectId, req) {
2581
+ if (req.polarity !== void 0) this.oneOf(req.polarity, PM_RISK_POLARITIES, "risk polarity");
2582
+ this.outcomes(req.outcomes);
2583
+ return this.riskWrite("POST", this.path(projectId, "risks"), {
2584
+ condition: this.text(req.condition, "A risk condition"),
2585
+ consequence: req.consequence,
2586
+ assessment: req.assessment,
2587
+ ownerContactId: req.ownerContactId,
2588
+ citations: req.citations,
2589
+ candidateRef: req.candidateRef,
2590
+ polarity: req.polarity,
2591
+ horizonStart: req.horizonStart,
2592
+ horizonEnd: req.horizonEnd,
2593
+ horizonLabel: req.horizonLabel,
2594
+ qualitative: req.qualitative,
2595
+ outcomes: req.outcomes,
2596
+ impactedWorkIds: req.impactedWorkIds,
2597
+ requestKey: this.key(req.requestKey)
2598
+ });
2599
+ }
2600
+ /** `pm.risk.update` → `PATCH risks/:riskId`; supersedes a pending response in the same write. */
2601
+ async updateRisk(projectId, riskId, req) {
2602
+ const patch = this.patch(req.patch);
2603
+ if (patch.polarity != null) this.oneOf(patch.polarity, PM_RISK_POLARITIES, "risk polarity");
2604
+ this.outcomes(patch.outcomes);
2605
+ return this.riskWrite("PATCH", this.path(projectId, "risks", riskId), {
2606
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2607
+ patch,
2608
+ requestKey: this.key(req.requestKey)
2609
+ });
2610
+ }
2611
+ /** `pm.risk.record_outcome` → `POST risks/:riskId/outcome` (occurrence state and residual exposure). */
2612
+ async recordRiskOutcome(projectId, riskId, req) {
2613
+ return this.riskWrite("POST", this.path(projectId, "risks", riskId, "outcome"), {
2614
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2615
+ occurrenceState: this.oneOf(req.occurrenceState, PM_RISK_OCCURRENCE_STATES, "occurrence state"),
2616
+ residual: req.residual,
2617
+ citations: req.citations,
2618
+ requestKey: this.key(req.requestKey)
2619
+ });
2620
+ }
2621
+ /** `pm.risk_response.propose` → `POST risks/:riskId/response` under the request key's operation identity. */
2622
+ async proposeRiskResponse(projectId, riskId, req) {
2623
+ const body = {
2624
+ type: this.oneOf(req.type, PM_RISK_RESPONSE_TYPES, "risk response type"),
2625
+ description: this.text(req.description, "A response description"),
2626
+ dueAt: this.text(req.dueAt, "A response dueAt"),
2627
+ expectedCurrentRevisionId: this.text(req.expectedCurrentRevisionId, "expectedCurrentRevisionId"),
2628
+ requestKey: this.key(req.requestKey)
2629
+ };
2630
+ const res = await this.http.post(this.path(projectId, "risks", riskId, "response"), { body });
2631
+ return this.withOperation(res);
2632
+ }
2633
+ /** `pm.risk_response.decide` → `POST risks/:riskId/response/decision` on the exact versions. */
2634
+ async decideRiskResponse(projectId, riskId, req) {
2635
+ const body = {
2636
+ proposalId: this.text(req.proposalId, "proposalId"),
2637
+ decision: this.oneOf(req.decision, ["accept", "reject"], "decision"),
2638
+ expectedRiskRevisionId: this.text(req.expectedRiskRevisionId, "expectedRiskRevisionId"),
2639
+ proposalUpdatedAt: this.text(req.proposalVersion, "proposalVersion")
2640
+ };
2641
+ const res = await this.http.post(this.path(projectId, "risks", riskId, "response", "decision"), { body });
2642
+ return this.withOperation(res);
2643
+ }
2644
+ /** Re-reads one response proposal, including a superseded or retired one (`pm.risk_response.supersede` is read here). */
2645
+ async getRiskResponse(projectId, proposalId) {
2646
+ return this.http.get(this.path(projectId, "chat", "risk-responses", proposalId));
2647
+ }
2648
+ /** `pm.risk.calculate` → `POST risks/calculations` (stores an immutable analysis). */
2649
+ async calculate(projectId, req) {
2650
+ const method = this.oneOf(req.method, PM_RISK_CALCULATION_METHODS, "risk calculation method");
2651
+ let body = { method };
2652
+ if (req.method === "pm.risk.v1") {
2653
+ body = { method, riskIds: req.riskIds, additiveRiskIds: req.additiveRiskIds, weightedIndex: req.weightedIndex };
2654
+ } else if (req.method === "pm.sensitivity.v1") {
2655
+ if (!Array.isArray(req.inputs) || req.inputs.length < 1 || req.inputs.length > 20) {
2656
+ throw new Error("pm.sensitivity.v1 varies 1 to 20 inputs of one risk.");
2657
+ }
2658
+ for (const i of req.inputs) {
2659
+ this.oneOf(i.field, ["probability", "impact"], "sensitivity field");
2660
+ this.decimal(i.lower, "A sensitivity lower bound");
2661
+ this.decimal(i.upper, "A sensitivity upper bound");
2662
+ }
2663
+ body = { method, riskId: this.text(req.riskId, "riskId"), inputs: req.inputs };
2664
+ }
2665
+ return this.http.post(this.path(projectId, "risks", "calculations"), { body });
2666
+ }
2667
+ /** `pm.issue.create` → `POST issues`. */
2668
+ async createIssue(projectId, req) {
2669
+ return this.raidWrite("POST", this.path(projectId, "issues"), req);
2670
+ }
2671
+ /** `pm.issue.update` → `PATCH issues/:recordId`. */
2672
+ async updateIssue(projectId, recordId, req) {
2673
+ return this.raidUpdate(this.path(projectId, "issues", recordId), req);
2674
+ }
2675
+ /** `pm.assumption.create` → `POST assumptions`. */
2676
+ async createAssumption(projectId, req) {
2677
+ return this.raidWrite("POST", this.path(projectId, "assumptions"), req);
2678
+ }
2679
+ /** `pm.assumption.update` → `PATCH assumptions/:recordId`. */
2680
+ async updateAssumption(projectId, recordId, req) {
2681
+ return this.raidUpdate(this.path(projectId, "assumptions", recordId), req);
2682
+ }
2683
+ /** `pm.decision.record` → `POST decisions`: records a decision taken by the calling human. */
2684
+ async recordDecision(projectId, req) {
2685
+ return this.raidWrite("POST", this.path(projectId, "decisions"), req);
2686
+ }
2687
+ };
2688
+
2689
+ // src/modules/projects/pm/views.ts
2690
+ var PM_VIEW_TYPES = [
2691
+ "project_brief",
2692
+ "work_plan",
2693
+ "capacity",
2694
+ "people_commitments",
2695
+ "finance",
2696
+ "supplier_commitments",
2697
+ "risk_register",
2698
+ "issues_assumptions_decisions",
2699
+ "change_comparison",
2700
+ "acceptance",
2701
+ "evidence_governance",
2702
+ "assistant_followthrough",
2703
+ "portfolio",
2704
+ "closure_handover",
2705
+ "activity"
2706
+ ];
2707
+ function isPmViewType(value) {
2708
+ return typeof value === "string" && PM_VIEW_TYPES.includes(value);
2709
+ }
2710
+ var PM_VIEW_RESULT_SCHEMA_VERSION = 1;
2711
+ var PM_RESULT_COVERAGE_STATES = ["complete", "partial", "unknown"];
2712
+ function isPmResultCoverageState(value) {
2713
+ return typeof value === "string" && PM_RESULT_COVERAGE_STATES.includes(value);
2714
+ }
2715
+ var PM_SELECTABLE_KINDS = PM_OBJECT_KINDS.filter(
2716
+ (k) => k !== "result_set"
2717
+ );
2718
+ function isPmSelectableKind(value) {
2719
+ return typeof value === "string" && PM_SELECTABLE_KINDS.includes(value);
2720
+ }
2721
+ function pmContextAccepted(sent, ack) {
2722
+ if (!sent) return true;
2723
+ if (!ack || typeof ack !== "object") return false;
2724
+ const a = ack;
2725
+ return a.schema_version === 1 && typeof a.act_id === "string" && a.act_id.trim() !== "" && a.selected_count === sent.selected.length;
2726
+ }
2727
+ var PM_VIEW_MAX_LIMIT = 200;
2728
+ var PM_VIEW_LAYOUT_MODES = ["compact", "expanded"];
2729
+ var PM_CATCH_UP_BASES = ["acknowledged", "requested", "default"];
2730
+ function isPmCatchUpBasis(value) {
2731
+ return typeof value === "string" && PM_CATCH_UP_BASES.includes(value);
2732
+ }
2733
+ var RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
2734
+ function decisions(list) {
2735
+ return (list ?? []).map((d) => ({ ...d, permittedDecisions: d.permittedDecisions ?? [] }));
2736
+ }
2737
+ var PmViewsApi = class extends PmWriteApiBase {
2738
+ limit(limit) {
2739
+ if (limit !== void 0 && !(Number.isInteger(limit) && limit >= 1 && limit <= PM_VIEW_MAX_LIMIT)) {
2740
+ throw new Error(`A view page limit must be an integer between 1 and ${PM_VIEW_MAX_LIMIT}.`);
2741
+ }
2742
+ }
2743
+ time(value, what) {
2744
+ if (typeof value !== "string" || !RFC3339.test(value) || Number.isNaN(Date.parse(value))) {
2745
+ throw new Error(`${what} must be an RFC 3339 time.`);
2746
+ }
2747
+ return value;
2748
+ }
2749
+ revision(value) {
2750
+ if (!Number.isInteger(value) || value < 1) throw new Error("expectedRevision must be a positive integer.");
2751
+ return value;
406
2752
  }
407
- /**
408
- * Platform-admin only: replace an org's product entitlement. `products` is
409
- * the full desired set ('cloud' | 'bi'); unknown codes are rejected 400.
410
- * Returns the updated org's id, name and enabledProducts.
411
- */
412
- async setEnabledProducts(orgId, products) {
413
- const res = await this.http.patch(`/orgs/${orgId}/enabled-products`, { body: { products } });
414
- return res.data;
2753
+ /** `pm.view.query` → `POST views/query`: one bounded, pinned page. */
2754
+ async query(projectId, req) {
2755
+ const viewType = this.oneOf(req.viewType, PM_VIEW_TYPES, "view type");
2756
+ if (req.query !== void 0 && (!req.query || typeof req.query !== "object" || Array.isArray(req.query))) {
2757
+ throw new Error("A view query must be an object.");
2758
+ }
2759
+ this.limit(req.limit);
2760
+ if (req.cursor !== void 0) this.text(req.cursor, "A cursor");
2761
+ const body = { viewType, query: req.query, sort: req.sort, limit: req.limit, cursor: req.cursor };
2762
+ return this.http.post(this.path(projectId, "views", "query"), { body });
415
2763
  }
416
- /**
417
- * Platform-admin only: add a new member to an existing org.
418
- * Creates the user without a password and sends an invite email via the
419
- * same TokenOrgInvite flow as the regular member invite.
420
- * Returns 403 unless platform admin; 409 when the email already exists.
421
- */
422
- async addUserToOrg(orgId, body) {
423
- const res = await this.http.post(
424
- `/orgs/${orgId}/users`,
425
- { body }
426
- );
427
- return unwrapData(res);
2764
+ /** `GET views/results/:resultSetRef`: re-reads one of the caller's pinned pages as it was issued. */
2765
+ async getResultSet(projectId, resultSetRef) {
2766
+ return this.http.get(this.path(projectId, "views", "results", resultSetRef));
428
2767
  }
429
- /**
430
- * Platform-admin only: fetch an org's two-bucket credit balance.
431
- * Returns 403 unless platform admin; 404 when the org doesn't exist.
432
- */
433
- async getOrgCreditBalance(orgId) {
434
- const res = await this.http.get(
435
- `/orgs/${orgId}/credits`
2768
+ /** `GET views/definitions`: the caller's current named views in the project. */
2769
+ async list(projectId) {
2770
+ const res = await this.http.get(this.path(projectId, "views", "definitions"));
2771
+ return res.items ?? [];
2772
+ }
2773
+ /** `pm.view.save` → `POST views/definitions` (new) or `PUT views/definitions/:viewId` (new revision). */
2774
+ async save(projectId, req) {
2775
+ if (req.viewType !== void 0) this.oneOf(req.viewType, PM_VIEW_TYPES, "view type");
2776
+ if (req.name !== void 0) this.text(req.name, "A view name");
2777
+ if (req.query != null && (typeof req.query !== "object" || Array.isArray(req.query))) {
2778
+ throw new Error("A view query must be an object.");
2779
+ }
2780
+ if (req.layout?.mode !== void 0) this.oneOf(req.layout.mode, PM_VIEW_LAYOUT_MODES, "view layout mode");
2781
+ const amend = req.viewId !== void 0;
2782
+ if (amend) this.revision(req.expectedRevision);
2783
+ else if (req.expectedRevision !== void 0 || req.name === void 0 || req.viewType === void 0) {
2784
+ throw new Error("A new named view needs a name and a view type, and no expectedRevision.");
2785
+ }
2786
+ const body = {
2787
+ expectedRevision: req.expectedRevision,
2788
+ name: req.name,
2789
+ viewType: req.viewType,
2790
+ query: req.query,
2791
+ sort: req.sort,
2792
+ layout: req.layout,
2793
+ requestKey: this.key(req.requestKey)
2794
+ };
2795
+ const res = amend ? await this.http.put(this.path(projectId, "views", "definitions", req.viewId), { body }) : await this.http.post(this.path(projectId, "views", "definitions"), { body });
2796
+ return this.written(res);
2797
+ }
2798
+ /** `pm.view.reopen` → `POST views/definitions/:viewId/reopen`: reauthorizes and issues a new result set. */
2799
+ async reopen(projectId, viewId, options = {}) {
2800
+ this.limit(options.limit);
2801
+ return this.http.post(this.path(projectId, "views", "definitions", viewId, "reopen"), {
2802
+ body: { limit: options.limit }
2803
+ });
2804
+ }
2805
+ /** `pm.view.remove` → `DELETE views/definitions/:viewId`: retires the view; no record is removed. */
2806
+ async remove(projectId, viewId, req) {
2807
+ const query = { revision: this.revision(req.expectedRevision), requestKey: this.key(req.requestKey) };
2808
+ return this.written(
2809
+ await this.http.delete(this.path(projectId, "views", "definitions", viewId), { query })
436
2810
  );
437
- return unwrapData(res);
438
2811
  }
439
2812
  /**
440
- * Platform-admin only: grant or revoke credits on an org.
441
- * amountMicros is signed: positive = grant, negative = revoke.
442
- * Records a CreditKindAdminAdjust ledger entry and returns the updated balance.
2813
+ * `pm.catch_up.summary` → `GET catch-up`: since `since` (else the caller's
2814
+ * acknowledgment, else the last week). `limit` bounds the first changes page.
443
2815
  */
444
- async adjustOrgCredits(orgId, body) {
445
- const res = await this.http.post(
446
- `/orgs/${orgId}/credits/adjust`,
447
- { body }
448
- );
449
- return unwrapData(res);
2816
+ async catchUp(projectId, options = {}) {
2817
+ if (options.since !== void 0) this.time(options.since, "since");
2818
+ this.limit(options.limit);
2819
+ const res = await this.http.get(this.path(projectId, "catch-up"), {
2820
+ query: { since: options.since, limit: options.limit }
2821
+ });
2822
+ return {
2823
+ ...res,
2824
+ newDecisions: decisions(res.newDecisions),
2825
+ olderObligations: {
2826
+ decisions: decisions(res.olderObligations?.decisions),
2827
+ findings: res.olderObligations?.findings ?? []
2828
+ },
2829
+ upcoming: res.upcoming ?? []
2830
+ };
2831
+ }
2832
+ /** `pm.catch_up.acknowledge` → `POST catch-up/ack`: moves the watermark forward to `through` (never back). */
2833
+ async acknowledgeCatchUp(projectId, req) {
2834
+ return this.http.post(this.path(projectId, "catch-up", "ack"), {
2835
+ body: { through: this.time(req.through, "through") }
2836
+ });
450
2837
  }
451
2838
  };
452
2839
 
453
- // src/modules/projects/types.ts
454
- var PRODUCT_KINDS = ["cloud", "bi", "meeting", "marketing", "pm", "startup"];
455
- function isProductKind(value) {
456
- return typeof value === "string" && PRODUCT_KINDS.includes(value);
457
- }
458
- function newProjectRequestKey() {
459
- const webcrypto = globalThis.crypto;
460
- if (typeof webcrypto?.randomUUID === "function") return webcrypto.randomUUID();
461
- return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
462
- }
463
- var PM_RECORD_FAMILIES = [
464
- "tailoring",
465
- "phase_gate",
466
- "baseline",
467
- "deliverable",
468
- "wbs_node",
469
- "activity",
470
- "decision",
471
- "action",
472
- "risk",
473
- "stakeholder",
474
- "issue",
475
- "assumption",
476
- "communication"
477
- ];
478
- function isPmRecordFamily(value) {
479
- return typeof value === "string" && value.trim().length > 0;
480
- }
481
- var PM_RECIPIENT_NOT_REGISTERED = "recipient-not-registered";
482
-
483
- // src/adapters/projectAdapter.ts
484
- var projectAdapter = {
485
- fromListResponse(payload) {
486
- const list = payload?.workspaces ?? payload?.projects ?? [];
487
- return list.filter((wire) => wire.product == null || isProductKind(wire.product)).map(normalize);
488
- },
489
- fromGetResponse(payload) {
490
- const wire = payload;
491
- const value = wire?.workspace ?? wire?.project ?? wire?.data;
492
- if (!value) throw new Error("Project response missing body.");
493
- return normalize(value);
494
- },
495
- normalize
2840
+ // src/modules/projects/pm/index.ts
2841
+ var PmApi = class {
2842
+ constructor(http) {
2843
+ this.common = new PmCommonApi(http);
2844
+ this.views = new PmViewsApi(http);
2845
+ this.bootstrap = new PmBootstrapApi(http);
2846
+ this.people = new PmPeopleApi(http);
2847
+ this.planning = new PmPlanningApi(http);
2848
+ this.finance = new PmFinanceApi(http);
2849
+ this.risk = new PmRiskApi(http);
2850
+ this.change = new PmChangeApi(http);
2851
+ this.acceptance = new PmAcceptanceApi(http);
2852
+ this.communication = new PmCommunicationApi(http);
2853
+ this.followup = new PmFollowupApi(http);
2854
+ this.portfolio = new PmPortfolioApi(http);
2855
+ this.closure = new PmClosureApi(http);
2856
+ this.governance = new PmGovernanceApi(http);
2857
+ this.reports = new PmReportsApi(http);
2858
+ }
496
2859
  };
497
- function normalize(wire) {
498
- const product = normalizeProduct(wire.product);
499
- return {
500
- id: wire.id,
501
- name: wire.name,
502
- orgId: wire.orgId,
503
- default: wire.default ?? false,
504
- isReferenceProject: wire.isReferenceProject ?? false,
505
- preferredAiProvider: wire.preferredAiProvider ?? null,
506
- product,
507
- users: wire.users ?? []
508
- };
509
- }
510
- function normalizeProduct(raw) {
511
- if (raw == null) return "cloud";
512
- if (isProductKind(raw)) return raw;
513
- throw new Error(`Unsupported project product ${JSON.stringify(raw)}.`);
514
- }
515
2860
 
516
2861
  // src/modules/projects/ProjectsClient.ts
517
2862
  function directHumanRevisionError(input) {
@@ -527,6 +2872,7 @@ function directHumanRevisionError(input) {
527
2872
  var ProjectsClient = class {
528
2873
  constructor(http) {
529
2874
  this.http = http;
2875
+ this.pm = new PmApi(http);
530
2876
  }
531
2877
  /**
532
2878
  * Lists the caller's projects in one product partition. Omitting `product`
@@ -534,8 +2880,8 @@ var ProjectsClient = class {
534
2880
  * 'bi' so it only ever sees data projects.
535
2881
  */
536
2882
  async list(product) {
537
- const path = product ? `/project?product=${encodeURIComponent(product)}` : "/project";
538
- const res = await this.http.get(path);
2883
+ const path2 = product ? `/project?product=${encodeURIComponent(product)}` : "/project";
2884
+ const res = await this.http.get(path2);
539
2885
  return projectAdapter.fromListResponse(res);
540
2886
  }
541
2887
  async get(projectId) {
@@ -622,8 +2968,8 @@ var ProjectsClient = class {
622
2968
  * to `[]` (the wire sends a nil slice as `null`).
623
2969
  */
624
2970
  listPMRecords(projectId, family) {
625
- const path = family ? `/project/${projectId}/pm/records?family=${encodeURIComponent(family)}` : `/project/${projectId}/pm/records`;
626
- return this.http.get(path).then((res) => res.records ?? []);
2971
+ const path2 = family ? `/project/${projectId}/pm/records?family=${encodeURIComponent(family)}` : `/project/${projectId}/pm/records`;
2972
+ return this.http.get(path2).then((res) => res.records ?? []);
627
2973
  }
628
2974
  /**
629
2975
  * Creates a project-memory record with its first revision in one POST. The
@@ -666,6 +3012,18 @@ var ProjectsClient = class {
666
3012
  listPMRevisions(projectId, recordId) {
667
3013
  return this.http.get(`/project/${projectId}/pm/records/${recordId}/revisions`).then((res) => res.revisions ?? []);
668
3014
  }
3015
+ /** Re-read a PM chat proposal under current project membership and grants. */
3016
+ getPMRecordProposal(projectId, proposalId) {
3017
+ return this.http.get(`/project/${encodeURIComponent(projectId)}/pm/chat/record-proposals/${encodeURIComponent(proposalId)}`);
3018
+ }
3019
+ /** Human confirmation/rejection; a stale, expired or already decided proposal is refused. */
3020
+ decidePMRecordProposal(projectId, proposalId, body) {
3021
+ if (!body.expectedVersion?.trim()) return Promise.reject(new Error("expectedVersion is required to decide an exact proposal."));
3022
+ if (body.decision !== "confirmed" && body.decision !== "rejected") return Promise.reject(new Error("A PM record proposal decision must be confirmed or rejected."));
3023
+ return this.http.post(`/project/${encodeURIComponent(projectId)}/pm/chat/record-proposals/${encodeURIComponent(proposalId)}/decision`, {
3024
+ body: { expectedVersion: body.expectedVersion, decision: body.decision }
3025
+ });
3026
+ }
669
3027
  // ── Customer documents (PJM-IP03) ──────────────────────────────────────────
670
3028
  /**
671
3029
  * Uploads a customer document (immutable v1) and records its provenance +
@@ -704,12 +3062,12 @@ var ProjectsClient = class {
704
3062
  }
705
3063
  // ── Governed disposition (deletion is a decision, not a click) ─────────────
706
3064
  /**
707
- * Files a deletion-disposition request against a document — INPUT, not
708
- * authority. Any active member may file one (a request never deletes on its
709
- * own). It lands in `requested` and is routed through review by the resolved
710
- * PJ-D039 authority. There is deliberately NO method that deletes a document or
711
- * executes a disposition on this client: execution is non-expressible until the
712
- * shared governed-disposition contract (F-PJM-047) lands.
3065
+ * Files a disposition (removal) request against a document — INPUT, not
3066
+ * authority. Any active member may file one. It lands in `requested` and is
3067
+ * routed through review by the resolved PJ-D039 authority. There is no method
3068
+ * that deletes a document: an approved request is executed by the server as an
3069
+ * append-only logical removal (PC-D02), restorable through
3070
+ * `pm.governance.restoreDocument`.
713
3071
  */
714
3072
  requestPMDocumentDisposition(projectId, documentId, body) {
715
3073
  return this.http.post(`/project/${projectId}/pm/documents/${documentId}/disposition-requests`, { body }).then((res) => res.request);
@@ -728,9 +3086,10 @@ var ProjectsClient = class {
728
3086
  }
729
3087
  /**
730
3088
  * Records the resolved authority's decision. `denied`/`deferred` persist with
731
- * the reason and policy basis; `approved` CANNOT delete — it settles to `held`
732
- * with an honest hold statement (the shared execution contract has not landed).
733
- * The server rejects a caller who is not the PJ-D039-resolved authority (403).
3089
+ * the reason and policy basis; `approved` executes as an append-only logical
3090
+ * removal (PC-D02; `executed`, nothing erased). The server rejects a caller who
3091
+ * is not the PJ-D039-resolved authority (403). Prefer
3092
+ * `pm.governance.decideDisposition`, which carries a request key.
734
3093
  */
735
3094
  decidePMDispositionRequest(projectId, requestId, body) {
736
3095
  return this.http.post(`/project/${projectId}/pm/disposition-requests/${requestId}/decision`, { body }).then((res) => res.request);
@@ -758,8 +3117,8 @@ var ProjectsClient = class {
758
3117
  */
759
3118
  generatePMStatusReport(projectId, opts) {
760
3119
  const focus = opts?.focus?.trim();
761
- const path = focus ? `/project/${projectId}/pm/status-reports?focus=${encodeURIComponent(focus)}` : `/project/${projectId}/pm/status-reports`;
762
- return this.http.post(path, { body: {} }).then((res) => res.report);
3120
+ const path2 = focus ? `/project/${projectId}/pm/status-reports?focus=${encodeURIComponent(focus)}` : `/project/${projectId}/pm/status-reports`;
3121
+ return this.http.post(path2, { body: {} }).then((res) => res.report);
763
3122
  }
764
3123
  /**
765
3124
  * Lists a project's status-report versions (oldest first) with the report
@@ -885,6 +3244,14 @@ var ProjectsClient = class {
885
3244
  // by the shared-rail receipt read on the approvals/activity surface. The confirmed
886
3245
  // risk, its register version and the response survive an owner decline or a
887
3246
  // notification failure.
3247
+ /** Loads saved risk proposals and current decision authority without appending a register version. */
3248
+ getPMRiskRegister(projectId) {
3249
+ return this.http.get(`/project/${encodeURIComponent(projectId)}/pm/chat/risk-register`);
3250
+ }
3251
+ /** Reloads one exact response proposal, including its terminal decision. */
3252
+ getPMRiskResponse(projectId, proposalId) {
3253
+ return this.http.get(`/project/${encodeURIComponent(projectId)}/pm/chat/risk-responses/${encodeURIComponent(proposalId)}`);
3254
+ }
888
3255
  /**
889
3256
  * Confirms a told/derived risk as a human-authored `risk` record (member with
890
3257
  * WRITE). A named `ownerContactId` is PROPOSED — never assigned — and must be a
@@ -1009,7 +3376,8 @@ function normalize2(wire) {
1009
3376
  userId: wire.userId,
1010
3377
  projectId: wire.projectId ?? wire.workspaceId ?? null,
1011
3378
  createdAt: wire.createdAt,
1012
- disabled: wire.disabled ?? false
3379
+ disabled: wire.disabled ?? false,
3380
+ product: wire.product
1013
3381
  };
1014
3382
  }
1015
3383
 
@@ -4212,6 +6580,22 @@ var ArtifactsClient = class {
4212
6580
  );
4213
6581
  return unwrapData(res);
4214
6582
  }
6583
+ /**
6584
+ * The exact version's bytes as a download (`GET …/versions/:vid/raw`): a
6585
+ * `Blob` with the server-chosen media type, never the head in its place. For
6586
+ * an export, pass the export's `outputArtifactId`/`outputVersionId`, and only
6587
+ * once its state is `ready`. Throws 410 `content_retention_deleted` when the
6588
+ * content (or an export's source) was removed under a retention policy.
6589
+ */
6590
+ async downloadRaw(container, artifactId, versionId) {
6591
+ for (const id of [container?.containerRef, artifactId, versionId]) {
6592
+ if (typeof id !== "string" || !id.trim()) throw new Error("A download names a container, an artifact and an exact version.");
6593
+ }
6594
+ return this.http.get(
6595
+ `/artifacts/${encodeURIComponent(artifactId)}/versions/${encodeURIComponent(versionId)}/raw${this.query(this.container(container))}`,
6596
+ { blob: true }
6597
+ );
6598
+ }
4215
6599
  /** Every approval for an artifact, newest first. */
4216
6600
  async listApprovals(id, container) {
4217
6601
  const res = await this.http.get(
@@ -4376,6 +6760,544 @@ var SignalsClient = class {
4376
6760
  }
4377
6761
  };
4378
6762
 
6763
+ // src/modules/assistants/AssistantsClient.ts
6764
+ var AssistantsClient = class {
6765
+ constructor(http) {
6766
+ this.http = http;
6767
+ }
6768
+ /** Responsibilities the caller may see, newest first. */
6769
+ async list(query = {}) {
6770
+ const res = await this.http.get("/assistants", {
6771
+ query: {
6772
+ product: query.product,
6773
+ projectId: query.projectId,
6774
+ sandboxId: query.sandboxId,
6775
+ lifecycle: query.lifecycle,
6776
+ cursor: query.cursor,
6777
+ limit: query.limit
6778
+ }
6779
+ });
6780
+ return unwrapData(res);
6781
+ }
6782
+ /** One responsibility, redacted for this viewer; absent and not visible are the same 404. */
6783
+ async get(id) {
6784
+ const res = await this.http.get(path(id));
6785
+ return unwrapData(res);
6786
+ }
6787
+ /** Creates a draft (nothing executes) with mandate revision 1 proposed; 201, or 200 on replay. */
6788
+ async create(body) {
6789
+ return this.command("/assistants", {
6790
+ commandKey: commandKey(body.commandKey),
6791
+ product: body.product,
6792
+ projectId: body.projectId,
6793
+ sandboxId: body.sandboxId,
6794
+ title: body.title,
6795
+ spec: body.spec
6796
+ });
6797
+ }
6798
+ /** Propose, accept (exact revision and digest, accountable owner only) or reject a mandate revision. */
6799
+ async mandateRevisions(id, body) {
6800
+ const base = revisioned(body);
6801
+ switch (body.action) {
6802
+ case "propose":
6803
+ return this.command(path(id, "mandate-revisions"), { ...base, action: body.action, spec: body.spec });
6804
+ case "accept":
6805
+ return this.command(path(id, "mandate-revisions"), {
6806
+ ...base,
6807
+ action: body.action,
6808
+ mandateRevisionId: body.mandateRevisionId,
6809
+ proposalDigest: body.proposalDigest
6810
+ });
6811
+ case "reject":
6812
+ return this.command(path(id, "mandate-revisions"), {
6813
+ ...base,
6814
+ action: body.action,
6815
+ mandateRevisionId: body.mandateRevisionId
6816
+ });
6817
+ }
6818
+ throw refused("mandate action must be propose, accept or reject");
6819
+ }
6820
+ /** Activate, pause, resume or retire; retire may dispose of open obligations in the same command. */
6821
+ async lifecycle(id, body) {
6822
+ const base = revisioned(body);
6823
+ switch (body.action) {
6824
+ case "activate":
6825
+ case "pause":
6826
+ case "resume":
6827
+ return this.command(path(id, "lifecycle"), { ...base, action: body.action });
6828
+ case "retire":
6829
+ return this.command(path(id, "lifecycle"), {
6830
+ ...base,
6831
+ action: body.action,
6832
+ dispositions: body.dispositions?.map((d) => ({ obligationId: d.obligationId, ...disposition(d) }))
6833
+ });
6834
+ }
6835
+ throw refused("lifecycle action must be activate, pause, resume or retire");
6836
+ }
6837
+ /** Records that this exact attention revision was seen; it never resolves the condition. */
6838
+ async acknowledge(id, body) {
6839
+ if (typeof body.attentionId !== "string" || !body.attentionId.trim()) throw refused("attentionId is required");
6840
+ if (!Number.isSafeInteger(body.attentionRevision) || body.attentionRevision < 1) {
6841
+ throw refused("attentionRevision must be a positive integer");
6842
+ }
6843
+ return this.command(path(id, "acknowledgments"), {
6844
+ commandKey: commandKey(body.commandKey),
6845
+ attentionId: body.attentionId,
6846
+ attentionRevision: body.attentionRevision
6847
+ });
6848
+ }
6849
+ /** Relinquish (with a reason) or transfer one open obligation; `expectedRevision` is the obligation's. */
6850
+ async disposeObligation(id, obligationId, body) {
6851
+ return this.command(`${path(id, "obligations")}/${segment("obligationId", obligationId)}/disposition`, {
6852
+ ...revisioned(body),
6853
+ ...disposition(body)
6854
+ });
6855
+ }
6856
+ /** Propose, accept (the proposed user, in the app), decline or cancel an owner transfer. */
6857
+ async ownerTransfer(id, body) {
6858
+ const base = revisioned(body);
6859
+ switch (body.action) {
6860
+ case "propose":
6861
+ return this.command(path(id, "owner-transfers"), { ...base, action: body.action, toUserId: body.toUserId });
6862
+ case "accept":
6863
+ return this.command(path(id, "owner-transfers"), {
6864
+ ...base,
6865
+ action: body.action,
6866
+ transferId: body.transferId,
6867
+ spec: body.spec
6868
+ });
6869
+ case "decline":
6870
+ case "cancel":
6871
+ return this.command(path(id, "owner-transfers"), { ...base, action: body.action, transferId: body.transferId });
6872
+ }
6873
+ throw refused("owner transfer action must be propose, accept, decline or cancel");
6874
+ }
6875
+ async command(url, body) {
6876
+ const res = await this.http.post(url, { body });
6877
+ return unwrapData(res);
6878
+ }
6879
+ };
6880
+ function refused(message) {
6881
+ return new Error(`Assistants: ${message}.`);
6882
+ }
6883
+ function segment(name, value) {
6884
+ if (typeof value !== "string" || !value.trim() || value === "." || value === "..") {
6885
+ throw refused(`${name} is required`);
6886
+ }
6887
+ return encodeURIComponent(value);
6888
+ }
6889
+ function path(id, sub) {
6890
+ const base = `/assistants/${segment("id", id)}`;
6891
+ return sub ? `${base}/${sub}` : base;
6892
+ }
6893
+ function commandKey(key) {
6894
+ if (typeof key !== "string" || !key.trim() || key !== key.trim()) {
6895
+ throw refused("commandKey must be a non-blank string without surrounding whitespace");
6896
+ }
6897
+ return key;
6898
+ }
6899
+ function revisioned(body) {
6900
+ if (!Number.isSafeInteger(body.expectedRevision) || body.expectedRevision < 0) {
6901
+ throw refused("expectedRevision must be the non-negative integer revision last read");
6902
+ }
6903
+ return { commandKey: commandKey(body.commandKey), expectedRevision: body.expectedRevision };
6904
+ }
6905
+ function disposition(d) {
6906
+ switch (d.action) {
6907
+ case "relinquish":
6908
+ return { action: d.action, reason: d.reason };
6909
+ case "transfer":
6910
+ return { action: d.action, reason: d.reason, toResponsibilityId: d.toResponsibilityId };
6911
+ }
6912
+ throw refused("disposition action must be relinquish or transfer");
6913
+ }
6914
+
6915
+ // src/modules/work/types.ts
6916
+ var SCHEMA_CAPABILITIES = "clowdops.capabilities/1";
6917
+ var SCHEMA_WORK = "clowdops.work/1";
6918
+ var INVOCATION_RESULT_KINDS = ["completed", "admitted", "waiting", "refused"];
6919
+ var REFUSAL_REASONS = [
6920
+ "unsupported_mode",
6921
+ "unknown_capability",
6922
+ "invalid_target",
6923
+ "invalid_arguments",
6924
+ "stale_input",
6925
+ "missing_decision",
6926
+ "denied",
6927
+ "unavailable",
6928
+ "budget_unavailable",
6929
+ "conflict",
6930
+ /** The attended human's authority lapsed or was revoked (HTTP 401). */
6931
+ "reauth_required",
6932
+ /** A product record is missing or not visible; existence never leaks (HTTP 404). */
6933
+ "not_found"
6934
+ ];
6935
+ var WORK_TASK_ERROR_CODES = [
6936
+ "denied",
6937
+ "conflict",
6938
+ "stale_revision",
6939
+ "terminal",
6940
+ "invalid_spec",
6941
+ "unavailable",
6942
+ "unsupported_mode"
6943
+ ];
6944
+
6945
+ // src/modules/work/WorkClient.ts
6946
+ var MAX_PAGE_SIZE = 100;
6947
+ var MAX_KEY_BYTES = 200;
6948
+ var RFC33392 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
6949
+ var REFUSAL_STATUSES = /* @__PURE__ */ new Set([400, 402, 403, 404, 409, 422, 503]);
6950
+ var MAX_LABEL_CHARS = 100;
6951
+ var MAX_GRANT_SCOPES = 8;
6952
+ var VERSIONED_REF = /^[^\s@]+@[1-9]\d*$/;
6953
+ var GRANT_STATUSES = ["active", "revoked"];
6954
+ var WorkTaskError = class extends HttpError {
6955
+ constructor(err, code) {
6956
+ super(err.status, err.statusText, err.body);
6957
+ this.name = "WorkTaskError";
6958
+ this.code = code;
6959
+ const body = isObject(err.body) ? err.body : {};
6960
+ const rev = body.currentRevision ?? (isObject(body.data) ? body.data.currentRevision : void 0);
6961
+ if (Number.isSafeInteger(rev)) this.currentRevision = rev;
6962
+ }
6963
+ };
6964
+ var OperationsScope = class {
6965
+ constructor(http) {
6966
+ this.http = http;
6967
+ }
6968
+ /**
6969
+ * Caller-filtered descriptors for the given project and/or sandbox. An
6970
+ * available descriptor is not a grant: invoke re-authorizes the target.
6971
+ */
6972
+ async list(query) {
6973
+ const projectId = nonBlank(query?.projectId) ? query.projectId : void 0;
6974
+ const sandboxId = nonBlank(query?.sandboxId) ? query.sandboxId : void 0;
6975
+ if (!projectId && !sandboxId) throw new Error("projectId or sandboxId is required to list product operations.");
6976
+ const d = dataOf(await this.http.get("/product-operations", { query: { projectId, sandboxId } }), "list");
6977
+ if (d.schemaVersion !== SCHEMA_CAPABILITIES || !("operations" in d) || d.operations !== null && !Array.isArray(d.operations)) {
6978
+ throw new Error("list response has no operations.");
6979
+ }
6980
+ return { ...d, operations: d.operations ?? [] };
6981
+ }
6982
+ /**
6983
+ * Invokes one descriptor version on an exact target. Domain refusals
6984
+ * (denied, invalid_arguments, unsupported_mode, …) are RETURNED as
6985
+ * `{kind: 'refused', reason}` so callers can tell them from transport/auth
6986
+ * failures, which throw (401, 5xx without a refusal body, network).
6987
+ */
6988
+ async invoke(capabilityId, request) {
6989
+ requireText(capabilityId, "capabilityId");
6990
+ if (request?.capabilityId !== capabilityId) throw new Error("request.capabilityId must equal the invoked capabilityId.");
6991
+ if (request.schemaVersion !== SCHEMA_CAPABILITIES) throw new Error(`schemaVersion must be ${SCHEMA_CAPABILITIES}.`);
6992
+ requireInt(request.capabilityVersion, "capabilityVersion", 1);
6993
+ requireArguments(request.arguments);
6994
+ const pageSize = request.arguments?.pageSize;
6995
+ if (pageSize !== void 0 && requireInt(pageSize, "pageSize", 1) > MAX_PAGE_SIZE) {
6996
+ throw new Error(`pageSize must be at most ${MAX_PAGE_SIZE}.`);
6997
+ }
6998
+ if (request.deadline != null) requireTimestamp(request.deadline, "deadline");
6999
+ const body = {
7000
+ schemaVersion: request.schemaVersion,
7001
+ capabilityId,
7002
+ capabilityVersion: request.capabilityVersion,
7003
+ target: pickTarget(request.target),
7004
+ arguments: request.arguments,
7005
+ requestKey: request.requestKey,
7006
+ operationRef: request.operationRef,
7007
+ expectedVersion: request.expectedVersion,
7008
+ evidenceRefs: request.evidenceRefs,
7009
+ budgetRef: request.budgetRef,
7010
+ deadline: request.deadline
7011
+ };
7012
+ let res;
7013
+ try {
7014
+ res = await this.http.post(`/product-operations/${encodeURIComponent(capabilityId)}/invoke`, { body });
7015
+ } catch (err) {
7016
+ const refused2 = refusalOf(err);
7017
+ if (refused2) return refused2;
7018
+ throw err;
7019
+ }
7020
+ const result = dataOf(res, "invoke");
7021
+ if (!INVOCATION_RESULT_KINDS.includes(result.kind)) {
7022
+ throw new Error("invoke response has no result kind.");
7023
+ }
7024
+ return result;
7025
+ }
7026
+ };
7027
+ var TasksScope = class {
7028
+ constructor(http) {
7029
+ this.http = http;
7030
+ }
7031
+ /**
7032
+ * Admits a bounded task. Resend the SAME requestKey after a lost reply:
7033
+ * an equivalent spec returns the admitted task (`replayed: true`); a
7034
+ * different spec under that key is a `conflict` WorkTaskError.
7035
+ */
7036
+ async commission(commission) {
7037
+ const requestKey = requireKey(commission?.requestKey, "requestKey");
7038
+ const s = commission.spec;
7039
+ if (s?.schemaVersion !== SCHEMA_WORK) throw new Error(`spec.schemaVersion must be ${SCHEMA_WORK}.`);
7040
+ requireText(s.templateId, "templateId");
7041
+ requireInt(s.templateVersion, "templateVersion", 1);
7042
+ requireInt(s.completionPolicyVersion, "completionPolicyVersion", 0);
7043
+ requireTimestamp(s.deadline, "deadline");
7044
+ if (!Array.isArray(s.targets) || s.targets.length === 0) throw new Error("spec.targets must name at least one target.");
7045
+ requireArguments(s.arguments);
7046
+ const body = {
7047
+ requestKey,
7048
+ spec: {
7049
+ schemaVersion: s.schemaVersion,
7050
+ templateId: s.templateId,
7051
+ templateVersion: s.templateVersion,
7052
+ targets: s.targets.map(pickTarget),
7053
+ arguments: s.arguments,
7054
+ evidenceRefs: s.evidenceRefs,
7055
+ budgetRef: s.budgetRef,
7056
+ deadline: s.deadline,
7057
+ limits: s.limits && { maxAttempts: s.limits.maxAttempts, maxSteps: s.limits.maxSteps },
7058
+ completionPolicyVersion: s.completionPolicyVersion,
7059
+ sourceOccurrenceRef: s.sourceOccurrenceRef
7060
+ }
7061
+ };
7062
+ const d = await taskCall(() => this.http.post("/delegated-tasks", { body }), "commission");
7063
+ return requireHandle(d, void 0, "commission");
7064
+ }
7065
+ /**
7066
+ * Current authorized projection. Possession of a task id is never enough:
7067
+ * an absent, foreign or unauthorized task is the same `denied` error, and
7068
+ * steps the viewer can no longer see come back `withheld`. `conversationId`
7069
+ * names the viewing conversation so audience-bound results are disclosed
7070
+ * only there.
7071
+ */
7072
+ async inspect(taskId, options) {
7073
+ requireText(taskId, "taskId");
7074
+ const conversationId = nonBlank(options?.conversationId) ? options.conversationId : void 0;
7075
+ const d = await taskCall(() => this.http.get(taskPath(taskId), { query: { conversationId } }), "inspect");
7076
+ requireHandle(d, taskId, "inspect");
7077
+ if (d.authorizedSteps != null && !Array.isArray(d.authorizedSteps)) throw new Error("inspect response has no steps.");
7078
+ return { ...d, authorizedSteps: d.authorizedSteps ?? [] };
7079
+ }
7080
+ /**
7081
+ * Supplies a requested input slot or resumes a waiting task. Idempotent by
7082
+ * commandKey: resending the same command returns its stored result
7083
+ * (`replayed: true`) even after the revision moved; a NEW command at a
7084
+ * stale revision is a `stale_revision` WorkTaskError carrying
7085
+ * `currentRevision`. There is no approval here — product decisions use the
7086
+ * owning product's decision path.
7087
+ */
7088
+ async continue(taskId, command) {
7089
+ requireText(taskId, "taskId");
7090
+ const commandKey2 = requireKey(command?.commandKey, "commandKey");
7091
+ const expectedRevision = requireInt(command.expectedRevision, "expectedRevision", 0);
7092
+ const body = { taskId, commandKey: commandKey2, expectedRevision, input: pickContinueInput(command.input) };
7093
+ const d = await taskCall(() => this.http.post(`${taskPath(taskId)}/continue`, { body }), "continue");
7094
+ return requireHandle(d, taskId, "continue");
7095
+ }
7096
+ /**
7097
+ * Records cancellation intent for this task's own interest. Cancellation is
7098
+ * not rollback: inspect reports completed effects and unresolved
7099
+ * liabilities. A terminal task answers `already_terminal`.
7100
+ */
7101
+ async cancel(taskId, command) {
7102
+ requireText(taskId, "taskId");
7103
+ const commandKey2 = requireKey(command?.commandKey, "commandKey");
7104
+ const expectedRevision = requireInt(command.expectedRevision, "expectedRevision", 0);
7105
+ if (command.reason !== void 0 && typeof command.reason !== "string") throw new Error("reason must be a string.");
7106
+ const body = { taskId, commandKey: commandKey2, expectedRevision, reason: command.reason };
7107
+ const d = await taskCall(() => this.http.post(`${taskPath(taskId)}/cancel`, { body }), "cancel");
7108
+ return requireHandle(d, taskId, "cancel");
7109
+ }
7110
+ };
7111
+ var GrantsScope = class {
7112
+ constructor(http) {
7113
+ this.http = http;
7114
+ }
7115
+ /** Creates a grant with its first credential. The creator must currently read every scope target. */
7116
+ async create(request) {
7117
+ const label = requireText(request?.label, "label");
7118
+ if ([...label].length > MAX_LABEL_CHARS) throw new Error(`label must be at most ${MAX_LABEL_CHARS} characters.`);
7119
+ const body = { label, ...pickGrantVersion(request) };
7120
+ const res = await this.http.post("/external-grants", { body });
7121
+ return withToken(grantOf(dataOf(res, "create"), void 0, "create"), "create");
7122
+ }
7123
+ /** The caller's own grants in the current organization. */
7124
+ async list() {
7125
+ const res = await this.http.get("/external-grants");
7126
+ if (!isObject(res) || !("data" in res) || res.data !== null && !Array.isArray(res.data)) throw new Error("list response missing data.");
7127
+ return (res.data ?? []).map((g) => grantOf(g, void 0, "list"));
7128
+ }
7129
+ async get(grantId) {
7130
+ requireText(grantId, "grantId");
7131
+ const res = await this.http.get(grantPath(grantId));
7132
+ return grantOf(dataOf(res, "get"), grantId, "get");
7133
+ }
7134
+ /** Appends a narrower version; it applies to the very next external call. */
7135
+ async narrow(grantId, request) {
7136
+ requireText(grantId, "grantId");
7137
+ const body = pickGrantVersion(request);
7138
+ const res = await this.http.post(`${grantPath(grantId)}/narrow`, { body });
7139
+ return grantOf(dataOf(res, "narrow"), grantId, "narrow");
7140
+ }
7141
+ /**
7142
+ * Replaces an active credential: the new one is inserted and the old one
7143
+ * revoked `rotated` atomically. Tasks keep their grant identity, so a
7144
+ * replacement credential recovers them by admission key.
7145
+ */
7146
+ async rotate(grantId, request) {
7147
+ requireText(grantId, "grantId");
7148
+ const body = { credentialId: requireText(request?.credentialId, "credentialId") };
7149
+ const res = await this.http.post(`${grantPath(grantId)}/rotate`, { body });
7150
+ return withToken(grantOf(dataOf(res, "rotate"), grantId, "rotate"), "rotate");
7151
+ }
7152
+ /** Revokes the grant and every credential. Task rows and committed evidence remain. */
7153
+ async revoke(grantId) {
7154
+ requireText(grantId, "grantId");
7155
+ const res = await this.http.post(`${grantPath(grantId)}/revoke`, { body: {} });
7156
+ return grantOf(dataOf(res, "revoke"), grantId, "revoke");
7157
+ }
7158
+ /** Revokes one credential; the grant and its other credentials stay. */
7159
+ async revokeCredential(grantId, credentialId) {
7160
+ requireText(grantId, "grantId");
7161
+ requireText(credentialId, "credentialId");
7162
+ const res = await this.http.post(`${grantPath(grantId)}/credentials/${encodeURIComponent(credentialId)}/revoke`, { body: {} });
7163
+ return grantOf(dataOf(res, "revokeCredential"), grantId, "revokeCredential");
7164
+ }
7165
+ };
7166
+ var WorkClient = class {
7167
+ constructor(http) {
7168
+ this.operations = new OperationsScope(http);
7169
+ this.tasks = new TasksScope(http);
7170
+ this.grants = new GrantsScope(http);
7171
+ }
7172
+ };
7173
+ function isObject(v) {
7174
+ return typeof v === "object" && v !== null && !Array.isArray(v);
7175
+ }
7176
+ function nonBlank(v) {
7177
+ return typeof v === "string" && v.trim() !== "";
7178
+ }
7179
+ function requireText(v, name) {
7180
+ if (!nonBlank(v)) throw new Error(`${name} is required.`);
7181
+ return v;
7182
+ }
7183
+ function requireKey(v, name) {
7184
+ const key = requireText(v, name);
7185
+ if (new TextEncoder().encode(key).length > MAX_KEY_BYTES) throw new Error(`${name} must be at most ${MAX_KEY_BYTES} bytes.`);
7186
+ return key;
7187
+ }
7188
+ function requireTimestamp(v, name) {
7189
+ const s = requireText(v, name);
7190
+ if (!RFC33392.test(s) || Number.isNaN(Date.parse(s))) throw new Error(`${name} must be an RFC 3339 timestamp.`);
7191
+ return s;
7192
+ }
7193
+ function requireInt(v, name, min) {
7194
+ if (!Number.isSafeInteger(v) || v < min) throw new Error(`${name} must be an integer of at least ${min}.`);
7195
+ return v;
7196
+ }
7197
+ function requireArguments(v) {
7198
+ if (v !== void 0 && !isObject(v)) throw new Error("arguments must be an object.");
7199
+ }
7200
+ function pickTarget(t) {
7201
+ if (!isObject(t)) throw new Error("target is required.");
7202
+ return {
7203
+ organizationId: requireText(t.organizationId, "target.organizationId"),
7204
+ product: requireText(t.product, "target.product"),
7205
+ projectId: t.projectId,
7206
+ sandboxId: t.sandboxId,
7207
+ resourceRefs: t.resourceRefs,
7208
+ destinationRef: t.destinationRef
7209
+ };
7210
+ }
7211
+ function pickContinueInput(input) {
7212
+ if (input?.kind === "resume") return { kind: "resume" };
7213
+ if (input?.kind !== "requested_input") throw new Error("input.kind must be requested_input or resume.");
7214
+ const requestRef = requireText(input.requestRef, "input.requestRef");
7215
+ const requestVersion = requireInt(input.requestVersion, "input.requestVersion", 0);
7216
+ if (input.payload === void 0) throw new Error("input.payload is required for requested_input.");
7217
+ return { kind: "requested_input", requestRef, requestVersion, payload: input.payload };
7218
+ }
7219
+ function pickGrantScope(s) {
7220
+ if (s?.product === "cloud") return { product: "cloud", sandboxId: requireText(s.sandboxId, "scope.sandboxId") };
7221
+ if (s?.product === "pm") return { product: "pm", projectId: requireText(s.projectId, "scope.projectId") };
7222
+ if (s?.product === "meeting") {
7223
+ return { product: "meeting", projectId: requireText(s.projectId, "scope.projectId"), sandboxId: requireText(s.sandboxId, "scope.sandboxId") };
7224
+ }
7225
+ throw new Error("scope.product must be cloud, pm or meeting.");
7226
+ }
7227
+ function versionedRefs(v, name) {
7228
+ if (!Array.isArray(v) || !v.every((r) => typeof r === "string" && VERSIONED_REF.test(r))) {
7229
+ throw new Error(`${name} must be a list of "id@version" references.`);
7230
+ }
7231
+ return [...v];
7232
+ }
7233
+ function pickGrantVersion(request) {
7234
+ const scopes = request?.scopes;
7235
+ if (!Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_GRANT_SCOPES) {
7236
+ throw new Error(`scopes must name 1 to ${MAX_GRANT_SCOPES} targets.`);
7237
+ }
7238
+ return {
7239
+ scopes: scopes.map(pickGrantScope),
7240
+ capabilities: versionedRefs(request.capabilities, "capabilities"),
7241
+ templates: versionedRefs(request.templates, "templates"),
7242
+ expiresAt: requireTimestamp(request.expiresAt, "expiresAt")
7243
+ };
7244
+ }
7245
+ function grantPath(grantId) {
7246
+ return `/external-grants/${encodeURIComponent(grantId)}`;
7247
+ }
7248
+ function grantOf(d, grantId, what) {
7249
+ if (!isObject(d) || !nonBlank(d.id) || grantId !== void 0 && d.id !== grantId) throw new Error(`${what} response is not for the requested grant.`);
7250
+ const listOrNull = (v) => v === null || v === void 0 || Array.isArray(v);
7251
+ if (!GRANT_STATUSES.includes(d.status) || !Number.isSafeInteger(d.currentVersion) || !listOrNull(d.versions) || !listOrNull(d.credentials)) {
7252
+ throw new Error(`${what} response is not a grant.`);
7253
+ }
7254
+ const versions = (d.versions ?? []).map((v) => ({
7255
+ ...v,
7256
+ scopes: v.scopes ?? [],
7257
+ capabilities: v.capabilities ?? [],
7258
+ templates: v.templates ?? []
7259
+ }));
7260
+ return { ...d, versions, credentials: d.credentials ?? [] };
7261
+ }
7262
+ function withToken(grant, what) {
7263
+ const token = grant.token;
7264
+ if (!nonBlank(token)) throw new Error(`${what} response has no token.`);
7265
+ return grant;
7266
+ }
7267
+ function taskPath(taskId) {
7268
+ return `/delegated-tasks/${encodeURIComponent(taskId)}`;
7269
+ }
7270
+ function dataOf(res, what) {
7271
+ const d = isObject(res) ? res.data : void 0;
7272
+ if (!isObject(d)) throw new Error(`${what} response missing data.`);
7273
+ return d;
7274
+ }
7275
+ function requireHandle(d, taskId, what) {
7276
+ if (!nonBlank(d.taskId) || taskId !== void 0 && d.taskId !== taskId) throw new Error(`${what} response is not for the requested task.`);
7277
+ if (!Number.isSafeInteger(d.revision) || typeof d.phase !== "string") throw new Error(`${what} response has no revision or phase.`);
7278
+ return d;
7279
+ }
7280
+ async function taskCall(send, what) {
7281
+ let res;
7282
+ try {
7283
+ res = await send();
7284
+ } catch (err) {
7285
+ if (err instanceof HttpError && WORK_TASK_ERROR_CODES.includes(err.errorCode)) {
7286
+ throw new WorkTaskError(err, err.errorCode);
7287
+ }
7288
+ throw err;
7289
+ }
7290
+ return dataOf(res, what);
7291
+ }
7292
+ function refusalOf(err) {
7293
+ if (!(err instanceof HttpError) || !REFUSAL_STATUSES.has(err.status) || !isObject(err.body)) return void 0;
7294
+ const { success, code, data } = err.body;
7295
+ if (success !== false || !REFUSAL_REASONS.includes(code) || !isObject(data) || data.kind !== "refused") {
7296
+ return void 0;
7297
+ }
7298
+ return { ...data, kind: "refused", reason: code };
7299
+ }
7300
+
4379
7301
  // src/client.ts
4380
7302
  var AgentEngineFacade = class {
4381
7303
  constructor(templates, scheduledTasks) {
@@ -4392,6 +7314,7 @@ var BillingFacade = class {
4392
7314
  var CloudAgentClient = class {
4393
7315
  constructor(options) {
4394
7316
  this.http = new BaseClient(options);
7317
+ this.realEstateAdmin = new RealEstateAdminClient(this.http);
4395
7318
  this.auth = new AuthClient(this.http);
4396
7319
  this.mfa = new MfaClient(this.http);
4397
7320
  this.user = new UserClient(this.http);
@@ -4432,6 +7355,8 @@ var CloudAgentClient = class {
4432
7355
  this.personExport = new PersonExportClient(this.http);
4433
7356
  this.artifacts = new ArtifactsClient(this.http);
4434
7357
  this.signals = new SignalsClient(this.http);
7358
+ this.assistants = new AssistantsClient(this.http);
7359
+ this.work = new WorkClient(this.http);
4435
7360
  }
4436
7361
  };
4437
7362
 
@@ -4468,6 +7393,16 @@ var MFAType = /* @__PURE__ */ ((MFAType2) => {
4468
7393
  return MFAType2;
4469
7394
  })(MFAType || {});
4470
7395
 
7396
+ // src/modules/artifacts/exports.ts
7397
+ var PM_EXPORT_STATES = ["preparing", "ready", "failed", "blocked", "cancelled"];
7398
+ function isPmExportState(value) {
7399
+ return typeof value === "string" && PM_EXPORT_STATES.includes(value);
7400
+ }
7401
+ var PM_EXPORT_FAILURE_STAGES = ["capture", "render", "validate", "persist"];
7402
+ function isPmExportFailureStage(value) {
7403
+ return typeof value === "string" && PM_EXPORT_FAILURE_STAGES.includes(value);
7404
+ }
7405
+
4471
7406
  // src/modules/projects/pmCoverage.ts
4472
7407
  var FAMILY_LABELS = {
4473
7408
  tailoring: "Tailoring",
@@ -4526,10 +7461,12 @@ function readDisciplines(records) {
4526
7461
  }
4527
7462
  return out;
4528
7463
  }
4529
- function applicabilityOf(family, disciplines) {
7464
+ function applicabilityOf(family, disciplines, coverageArea) {
4530
7465
  if (ALWAYS_APPLICABLE.has(family)) return true;
4531
7466
  if (!disciplines) return null;
4532
- const keys = [family, ...DISCIPLINE_ALIASES[family] ?? []].map((k) => k.toLowerCase());
7467
+ const keys = [family, ...DISCIPLINE_ALIASES[family] ?? [], ...coverageArea ? [coverageArea] : []].map(
7468
+ (k) => k.toLowerCase()
7469
+ );
4533
7470
  let sawKey = false;
4534
7471
  for (const key of keys) {
4535
7472
  if (key in disciplines) {
@@ -4562,15 +7499,19 @@ function declaresCadence(rev) {
4562
7499
  const cadence = o.cadence ?? o.reviewCadence ?? o.review_cadence;
4563
7500
  return typeof cadence === "string" && cadence.trim().length > 0;
4564
7501
  }
4565
- function derivePmCoverage(records) {
7502
+ function derivePmCoverage(records, catalog) {
4566
7503
  const disciplines = readDisciplines(records);
4567
7504
  const tailoringDeclared = records.some(
4568
7505
  (r) => r.family === "tailoring" && isViable(r)
4569
7506
  );
7507
+ const coverageAreas = catalog ? new Map(catalog.families.map((f) => [f.family, f.coverageArea ?? void 0])) : void 0;
4570
7508
  const families = [
4571
7509
  ...PM_RECORD_FAMILIES,
4572
- ...records.map((r) => r.family).filter((family) => !PM_RECORD_FAMILIES.includes(family))
4573
- ].filter((family, index, all) => all.indexOf(family) === index);
7510
+ ...catalog?.families.map((f) => f.family) ?? [],
7511
+ ...records.map((r) => r.family)
7512
+ ].filter(
7513
+ (family, index, all) => all.indexOf(family) === index && (!coverageAreas || coverageAreas.get(family) !== void 0)
7514
+ );
4574
7515
  const areas = families.map((family) => {
4575
7516
  const family_records = records.filter((r) => r.family === family && r.current);
4576
7517
  const totalCount = family_records.length;
@@ -4583,7 +7524,7 @@ function derivePmCoverage(records) {
4583
7524
  if (rev.provisional) provisionalCount += 1;
4584
7525
  if (declaresCadence(rev)) cadenceDeclared = true;
4585
7526
  }
4586
- const declared = applicabilityOf(family, disciplines);
7527
+ const declared = applicabilityOf(family, disciplines, coverageAreas?.get(family));
4587
7528
  const applicable = declared !== false;
4588
7529
  const label = FAMILY_LABELS[family] ?? family.split("_").join(" ");
4589
7530
  let state;
@@ -4741,15 +7682,19 @@ function resolveCitation(citation, docs) {
4741
7682
  versionVerified: false,
4742
7683
  attestationState: "unknown",
4743
7684
  pinsCurrentVersion: false,
7685
+ documentRemoved: false,
4744
7686
  ...parts
4745
7687
  };
4746
7688
  }
4747
7689
  const pinsCurrentVersion = parts.versionId === doc.headVersionId;
4748
7690
  const versionVerified = pinsCurrentVersion && citation.ref.content_hash === doc.contentHash;
7691
+ const documentRemoved = isPmDocumentRemoved(doc);
4749
7692
  return {
4750
7693
  ...citation,
4751
7694
  ...parts,
4752
- resolved: versionVerified,
7695
+ // A removed document never resolves as current grounding.
7696
+ resolved: versionVerified && !documentRemoved,
7697
+ documentRemoved,
4753
7698
  documentVisible: true,
4754
7699
  versionVerified,
4755
7700
  title: doc.title,
@@ -4761,21 +7706,32 @@ function resolveCitation(citation, docs) {
4761
7706
  function resolveClaimCitations(payload, docs) {
4762
7707
  return readClaimCitations(payload).map((c) => resolveCitation(c, docs));
4763
7708
  }
7709
+ function isPmDocumentRemoved(doc) {
7710
+ return doc.lifecycleState === "removed";
7711
+ }
7712
+ function activePmDocuments(docs) {
7713
+ return docs.filter((d) => !isPmDocumentRemoved(d));
7714
+ }
7715
+ function pmDocumentRemoval(doc) {
7716
+ return isPmDocumentRemoved(doc) && doc.removal ? doc.removal : void 0;
7717
+ }
4764
7718
  var DISPOSITION_LABELS = {
4765
7719
  requested: "Requested \u2014 awaiting review",
4766
7720
  under_review: "Under review by the disposition authority",
4767
7721
  denied: "Denied \u2014 the document is retained",
4768
7722
  deferred: "Deferred \u2014 revisit later",
4769
- held: "Approved in principle; deletion held (governed execution not yet available)"
7723
+ held: "Held \u2014 not carried out (an older approval, or no disposition authority resolves)",
7724
+ executed: "Approved \u2014 the document is removed from active use; its content and history are kept and it can be restored"
4770
7725
  };
4771
7726
  function summarizeDisposition(req) {
4772
- const decided = req.state === "denied" || req.state === "deferred" || req.state === "held";
7727
+ const decided = req.state === "denied" || req.state === "deferred" || req.state === "held" || req.state === "executed";
4773
7728
  return {
4774
7729
  id: req.id,
4775
7730
  documentId: req.documentId,
4776
7731
  state: req.state,
4777
7732
  executable: false,
4778
- heldForExecution: req.state === "held",
7733
+ executed: req.state === "executed",
7734
+ heldForExecution: req.state === "held" && req.decision === "approved",
4779
7735
  decided,
4780
7736
  label: DISPOSITION_LABELS[req.state] ?? req.state,
4781
7737
  reason: req.decisionReason ?? req.resolutionReason ?? req.requestReason ?? void 0,
@@ -5453,23 +8409,23 @@ function getSpec(specs, id) {
5453
8409
  }
5454
8410
  var SECRET_PATH = "secret";
5455
8411
  var METADATA_PREFIX = "metadata.";
5456
- function isSecretPath(path) {
5457
- return path === SECRET_PATH;
8412
+ function isSecretPath(path2) {
8413
+ return path2 === SECRET_PATH;
5458
8414
  }
5459
- function isMetadataPath(path) {
5460
- return path.startsWith(METADATA_PREFIX);
8415
+ function isMetadataPath(path2) {
8416
+ return path2.startsWith(METADATA_PREFIX);
5461
8417
  }
5462
- function metadataKey(path) {
5463
- return isMetadataPath(path) ? path.slice(METADATA_PREFIX.length) : void 0;
8418
+ function metadataKey(path2) {
8419
+ return isMetadataPath(path2) ? path2.slice(METADATA_PREFIX.length) : void 0;
5464
8420
  }
5465
- function getValueAt(secret, metadata, path) {
5466
- if (path === SECRET_PATH) return secret;
5467
- const k = metadataKey(path);
8421
+ function getValueAt(secret, metadata, path2) {
8422
+ if (path2 === SECRET_PATH) return secret;
8423
+ const k = metadataKey(path2);
5468
8424
  return k ? metadata[k] : void 0;
5469
8425
  }
5470
- function setValueAt(secret, metadata, path, value) {
5471
- if (path === SECRET_PATH) return { secret: typeof value === "string" ? value : "", metadata };
5472
- const k = metadataKey(path);
8426
+ function setValueAt(secret, metadata, path2, value) {
8427
+ if (path2 === SECRET_PATH) return { secret: typeof value === "string" ? value : "", metadata };
8428
+ const k = metadataKey(path2);
5473
8429
  if (!k) return { secret, metadata };
5474
8430
  const nextMeta = { ...metadata };
5475
8431
  if (value === void 0 || value === null || value === "") delete nextMeta[k];
@@ -5514,8 +8470,8 @@ function fieldAppliesToShape(f, shapeId) {
5514
8470
  if (!f.shapes || f.shapes.length === 0) return true;
5515
8471
  return f.shapes.includes(shapeId);
5516
8472
  }
5517
- function isFieldPresent(secret, metadata, path) {
5518
- const v = getValueAt(secret, metadata, path);
8473
+ function isFieldPresent(secret, metadata, path2) {
8474
+ const v = getValueAt(secret, metadata, path2);
5519
8475
  if (v === void 0 || v === null) return false;
5520
8476
  if (typeof v === "string") return v.trim() !== "";
5521
8477
  if (Array.isArray(v)) return v.length > 0;
@@ -5752,6 +8708,16 @@ var CHAT_CARD_ACTIONS = [
5752
8708
  "decide_confirmation",
5753
8709
  "refresh"
5754
8710
  ];
8711
+ var PM_CARD_DURABLE_KINDS = [
8712
+ "pm_record_proposal",
8713
+ "pm_risk_response",
8714
+ "pm_view_result",
8715
+ "pm_operation",
8716
+ "pm_decision_candidate"
8717
+ ];
8718
+ function isPmCardDurableKind(kind) {
8719
+ return typeof kind === "string" && PM_CARD_DURABLE_KINDS.includes(kind);
8720
+ }
5755
8721
  function isKnownChatCard(card) {
5756
8722
  return card.card_type !== "unknown";
5757
8723
  }
@@ -5848,7 +8814,8 @@ var COMPONENT_IDS = [
5848
8814
  "artifact_substrate",
5849
8815
  "evidence_citation",
5850
8816
  "fact_governance",
5851
- "signal_store"
8817
+ "signal_store",
8818
+ "assistants"
5852
8819
  ];
5853
8820
 
5854
8821
  // src/modules/budgets/types.ts
@@ -5874,7 +8841,7 @@ var PANEL_TYPES = /* @__PURE__ */ new Set([
5874
8841
  "tick",
5875
8842
  "rect"
5876
8843
  ]);
5877
- function isObject(v) {
8844
+ function isObject2(v) {
5878
8845
  return typeof v === "object" && v !== null && !Array.isArray(v);
5879
8846
  }
5880
8847
  function nonEmptyString(v) {
@@ -5882,13 +8849,13 @@ function nonEmptyString(v) {
5882
8849
  }
5883
8850
  function measureColumnKey(term) {
5884
8851
  if (typeof term === "string") return term;
5885
- if (isObject(term) && nonEmptyString(term.as)) return `[${term.as}]`;
8852
+ if (isObject2(term) && nonEmptyString(term.as)) return `[${term.as}]`;
5886
8853
  return void 0;
5887
8854
  }
5888
8855
  function validateDashboardSpec(input) {
5889
8856
  const errors = [];
5890
- const push = (path, keyword, message) => errors.push({ path, keyword, message });
5891
- if (!isObject(input)) {
8857
+ const push = (path2, keyword, message) => errors.push({ path: path2, keyword, message });
8858
+ if (!isObject2(input)) {
5892
8859
  return { ok: false, errors: [{ path: "", keyword: "type", message: "spec must be a JSON object" }] };
5893
8860
  }
5894
8861
  if (input.schema !== DASHBOARD_SCHEMA_VERSION) {
@@ -5897,7 +8864,7 @@ function validateDashboardSpec(input) {
5897
8864
  if (!nonEmptyString(input.title)) {
5898
8865
  push("/title", "required", "title is required and must be a non-empty string");
5899
8866
  }
5900
- if (!isObject(input.scope) || !nonEmptyString(input.scope.repoId)) {
8867
+ if (!isObject2(input.scope) || !nonEmptyString(input.scope.repoId)) {
5901
8868
  push("/scope", "required", "scope.repoId is required");
5902
8869
  }
5903
8870
  const layout = Array.isArray(input.layout) ? input.layout : [];
@@ -5910,7 +8877,7 @@ function validateDashboardSpec(input) {
5910
8877
  }
5911
8878
  const panelIds = /* @__PURE__ */ new Map();
5912
8879
  panels.forEach((p, i) => {
5913
- if (!isObject(p)) {
8880
+ if (!isObject2(p)) {
5914
8881
  push(`/panels/${i}`, "type", "panel must be an object");
5915
8882
  return;
5916
8883
  }
@@ -5924,9 +8891,9 @@ function validateDashboardSpec(input) {
5924
8891
  push(`/panels/${i}/type`, "enum", `panel type "${String(p.type)}" is not a known type`);
5925
8892
  }
5926
8893
  if (!nonEmptyString(p.title)) push(`/panels/${i}/title`, "required", "panel title is required");
5927
- if (!isObject(p.viz)) push(`/panels/${i}/viz`, "required", "panel viz is required");
5928
- const hasBinding = isObject(p.binding);
5929
- const hasComposite = isObject(p.compositeBinding);
8894
+ if (!isObject2(p.viz)) push(`/panels/${i}/viz`, "required", "panel viz is required");
8895
+ const hasBinding = isObject2(p.binding);
8896
+ const hasComposite = isObject2(p.compositeBinding);
5930
8897
  if (!hasBinding && !hasComposite) {
5931
8898
  push(`/panels/${i}/binding`, "required", "panel needs a binding or a compositeBinding");
5932
8899
  } else if (hasBinding && hasComposite) {
@@ -5941,7 +8908,7 @@ function validateDashboardSpec(input) {
5941
8908
  });
5942
8909
  const layoutIds = /* @__PURE__ */ new Map();
5943
8910
  layout.forEach((l, i) => {
5944
- if (!isObject(l) || !nonEmptyString(l.i)) {
8911
+ if (!isObject2(l) || !nonEmptyString(l.i)) {
5945
8912
  push(`/layout/${i}/i`, "required", 'layout entry needs a string id "i"');
5946
8913
  return;
5947
8914
  }
@@ -5955,25 +8922,25 @@ function validateDashboardSpec(input) {
5955
8922
  const paramIds = /* @__PURE__ */ new Set();
5956
8923
  if (Array.isArray(input.parameters)) {
5957
8924
  for (const p of input.parameters) {
5958
- if (isObject(p) && nonEmptyString(p.id)) paramIds.add(p.id);
8925
+ if (isObject2(p) && nonEmptyString(p.id)) paramIds.add(p.id);
5959
8926
  }
5960
8927
  }
5961
8928
  panels.forEach((p, pi) => {
5962
- if (!isObject(p)) return;
5963
- const b = isObject(p.binding) ? p.binding : void 0;
8929
+ if (!isObject2(p)) return;
8930
+ const b = isObject2(p.binding) ? p.binding : void 0;
5964
8931
  const filters = b && Array.isArray(b.filters) ? b.filters : [];
5965
8932
  filters.forEach((f, fi) => {
5966
- if (isObject(f) && typeof f.param === "string" && f.param.length > 0 && !paramIds.has(f.param)) {
8933
+ if (isObject2(f) && typeof f.param === "string" && f.param.length > 0 && !paramIds.has(f.param)) {
5967
8934
  push(`/panels/${pi}/binding/filters/${fi}/param`, "integrity.paramRef", `filter references undeclared parameter "${f.param}"`);
5968
8935
  }
5969
8936
  });
5970
- const cb = isObject(p.compositeBinding) ? p.compositeBinding : void 0;
8937
+ const cb = isObject2(p.compositeBinding) ? p.compositeBinding : void 0;
5971
8938
  const sources = cb && Array.isArray(cb.sources) ? cb.sources : [];
5972
8939
  sources.forEach((s, si) => {
5973
- if (!isObject(s) || !isObject(s.binding)) return;
8940
+ if (!isObject2(s) || !isObject2(s.binding)) return;
5974
8941
  const sFilters = Array.isArray(s.binding.filters) ? s.binding.filters : [];
5975
8942
  sFilters.forEach((f, fi) => {
5976
- if (isObject(f) && typeof f.param === "string" && f.param.length > 0 && !paramIds.has(f.param)) {
8943
+ if (isObject2(f) && typeof f.param === "string" && f.param.length > 0 && !paramIds.has(f.param)) {
5977
8944
  push(
5978
8945
  `/panels/${pi}/compositeBinding/sources/${si}/binding/filters/${fi}/param`,
5979
8946
  "integrity.paramRef",
@@ -5982,10 +8949,10 @@ function validateDashboardSpec(input) {
5982
8949
  }
5983
8950
  });
5984
8951
  });
5985
- const inter = isObject(p.interaction) ? p.interaction : void 0;
8952
+ const inter = isObject2(p.interaction) ? p.interaction : void 0;
5986
8953
  const emits = inter && Array.isArray(inter.emits) ? inter.emits : [];
5987
8954
  emits.forEach((e, ei) => {
5988
- if (isObject(e) && typeof e.param === "string" && e.param.length > 0 && !paramIds.has(e.param)) {
8955
+ if (isObject2(e) && typeof e.param === "string" && e.param.length > 0 && !paramIds.has(e.param)) {
5989
8956
  push(`/panels/${pi}/interaction/emits/${ei}/param`, "integrity.paramRef", `interaction emits undeclared parameter "${e.param}"`);
5990
8957
  }
5991
8958
  });
@@ -6025,7 +8992,7 @@ function validateComposite(cb, base, push) {
6025
8992
  }
6026
8993
  const roles = /* @__PURE__ */ new Set();
6027
8994
  sources.forEach((s, si) => {
6028
- if (!isObject(s)) {
8995
+ if (!isObject2(s)) {
6029
8996
  push(`${base}/sources/${si}`, "type", "source must be an object");
6030
8997
  return;
6031
8998
  }
@@ -6036,7 +9003,7 @@ function validateComposite(cb, base, push) {
6036
9003
  } else {
6037
9004
  roles.add(s.role);
6038
9005
  }
6039
- if (!isObject(s.binding)) {
9006
+ if (!isObject2(s.binding)) {
6040
9007
  push(`${base}/sources/${si}/binding`, "required", "source binding is required");
6041
9008
  return;
6042
9009
  }
@@ -6062,7 +9029,7 @@ function validateComposite(cb, base, push) {
6062
9029
  }
6063
9030
  const aliases = /* @__PURE__ */ new Set();
6064
9031
  on.forEach((o, oi) => {
6065
- if (!isObject(o) || !nonEmptyString(o.as)) {
9032
+ if (!isObject2(o) || !nonEmptyString(o.as)) {
6066
9033
  push(`${base}/on/${oi}/as`, "required", 'every on pair needs a bare alias "as"');
6067
9034
  return;
6068
9035
  }
@@ -6071,10 +9038,10 @@ function validateComposite(cb, base, push) {
6071
9038
  aliases.add(norm);
6072
9039
  });
6073
9040
  sources.forEach((s, si) => {
6074
- if (!isObject(s)) return;
9041
+ if (!isObject2(s)) return;
6075
9042
  const carry = Array.isArray(s.carry) ? s.carry : [];
6076
9043
  carry.forEach((c, ci) => {
6077
- if (!isObject(c) || !nonEmptyString(c.as)) {
9044
+ if (!isObject2(c) || !nonEmptyString(c.as)) {
6078
9045
  push(`${base}/sources/${si}/carry/${ci}/as`, "required", 'every carry field needs a bare alias "as"');
6079
9046
  return;
6080
9047
  }
@@ -6088,7 +9055,7 @@ function validateComposite(cb, base, push) {
6088
9055
  });
6089
9056
  const derived = Array.isArray(cb.derived) ? cb.derived : [];
6090
9057
  derived.forEach((d, di) => {
6091
- if (!isObject(d) || !nonEmptyString(d.as)) {
9058
+ if (!isObject2(d) || !nonEmptyString(d.as)) {
6092
9059
  push(`${base}/derived/${di}/as`, "required", 'every derived term needs an alias "as"');
6093
9060
  return;
6094
9061
  }
@@ -6099,7 +9066,7 @@ function validateComposite(cb, base, push) {
6099
9066
  if (aliases.has(norm)) push(`${base}/derived/${di}/as`, "integrity.alias", `derived alias "${d.as}" duplicates a joined-column alias`);
6100
9067
  aliases.add(norm);
6101
9068
  });
6102
- const out = isObject(cb.output) ? cb.output : void 0;
9069
+ const out = isObject2(cb.output) ? cb.output : void 0;
6103
9070
  if (!out) {
6104
9071
  push(`${base}/output`, "required", "compositeBinding.output is required");
6105
9072
  return;
@@ -6116,7 +9083,7 @@ function validateComposite(cb, base, push) {
6116
9083
  }
6117
9084
  const outAliases = /* @__PURE__ */ new Set();
6118
9085
  select.forEach((t, ti) => {
6119
- if (!isObject(t) || !nonEmptyString(t.as)) {
9086
+ if (!isObject2(t) || !nonEmptyString(t.as)) {
6120
9087
  push(`${base}/output/select/${ti}/as`, "required", 'every output term needs an alias "as"');
6121
9088
  return;
6122
9089
  }
@@ -6129,7 +9096,7 @@ function validateComposite(cb, base, push) {
6129
9096
  });
6130
9097
  const outDerived = Array.isArray(out.derived) ? out.derived : [];
6131
9098
  outDerived.forEach((d, di) => {
6132
- if (!isObject(d) || !nonEmptyString(d.as)) {
9099
+ if (!isObject2(d) || !nonEmptyString(d.as)) {
6133
9100
  push(`${base}/output/derived/${di}/as`, "required", 'every output.derived term needs an alias "as"');
6134
9101
  return;
6135
9102
  }
@@ -6657,6 +9624,6 @@ var schema_default = {
6657
9624
  // src/modules/dashboards/schema.ts
6658
9625
  var DASHBOARD_SCHEMA = schema_default;
6659
9626
 
6660
- export { AccessType, ApprovalsClient, ArtifactsClient, BIClient, BI_VERIFICATION_METADATA_KEY, BaseClient, BrandAuthorityClient, BudgetsClient, CAP_AI, CAP_BI, CAP_COMPUTE, CAP_GENERAL, CAP_MM, CAP_NOTIFY, CAP_STORAGE, CAP_VCS, CHAT_CARD_ACTIONS, CHAT_CARD_SCHEMA_VERSION, CHAT_CARD_TYPES, CHAT_MESSAGE_KIND_CARD, CHAT_SCHEDULE_RUN_STATUSES, CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE, CLAIM_ANNOTATIONS_METADATA_KEY, COMPONENT_IDS, CONNECTION_DISCONNECT_V1, CONNECT_AUTHORIZE_V1, CONNECT_CAPABILITY_DISPLAY_STATES, CONNECT_RESULT_V1, CapabilitiesClient, CapacityClient, CloudAgentClient, ConnectCatalogValidationError, ConnectClient, ConnectionsClient, ContactsClient, CrmHandoffsClient, DASHBOARD_SCHEMA, DASHBOARD_SCHEMA_VERSION, DashboardsClient, DeploymentsClient, FactsClient, FollowThroughClient, HttpError, MFAType, MarketingConsentClient, MeetingMinutesClient, MeteringClient, NotImplementedError, OrgRoles, PM_RECIPIENT_NOT_REGISTERED, PM_RECORD_FAMILIES, PRODUCT_KINDS, PROVIDER_CATALOG, PROVIDER_LIFECYCLE_SURFACE, PacksClient, PersonExportClient, PlatformAdminClient, ProviderType, ReferralsClient, ResellerClient, ResourcesClient, SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS, SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION, SignalsClient, TelegramClient, biVerificationOf, brandRoleAffordances, buildDocumentCitation, chatCardOf, claimAnnotationsOf, claimClassLabel, commitmentActStateLabel, commitmentTrackerStatusLabel, computationByKey, computeDisplayHint, coverageStateLabel, crmHandoffAwaitingDisposition, crmHandoffOutcomeLabel, derivePmCoverage, getProvider, getSpec, getValueAt, groundClaimPayload, groupClaimsByClass, hasMaterialDiff, isCommitmentConflicted, isDashboardSpec, isFailedScheduleRunStatus, isKnownChatCard, isKnownChatCardAction, isKnownChatCardType, isMeetingCommitmentOverdue, isMetadataPath, isPmDocumentCitation, isPmRecordFamily, isProductKind, isSecretPath, listProviders, meetingGateBehavior, meetingRoleAffordances, metadataKey, newProjectRequestKey, parseChatCard, parseConnectCatalog, parseConnectCatalogRow, parseConnectResultV1, parsePmDocumentCitation, personExportIsEmpty, personExportIsLimited, readClaimCitations, resolveCitation, resolveClaimCitations, resolveClaimComputations, resolveMeetingField, resolveProviderCatalog, setValueAt, statusHeadline, summarizeDisposition, ungroundClaimPayload, usdMicros, validate, validateDashboardSpec, validateSpec };
9627
+ export { AccessType, ApprovalsClient, ArtifactsClient, AssistantsClient, BIClient, BI_VERIFICATION_METADATA_KEY, BaseClient, BrandAuthorityClient, BudgetsClient, CAP_AI, CAP_BI, CAP_COMPUTE, CAP_GENERAL, CAP_MM, CAP_NOTIFY, CAP_STORAGE, CAP_VCS, CHAT_CARD_ACTIONS, CHAT_CARD_SCHEMA_VERSION, CHAT_CARD_TYPES, CHAT_MESSAGE_KIND_CARD, CHAT_SCHEDULE_RUN_STATUSES, CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE, CLAIM_ANNOTATIONS_METADATA_KEY, COMPONENT_IDS, CONNECTION_DISCONNECT_V1, CONNECT_AUTHORIZE_V1, CONNECT_CAPABILITY_DISPLAY_STATES, CONNECT_RESULT_V1, CapabilitiesClient, CapacityClient, CloudAgentClient, ConnectCatalogValidationError, ConnectClient, ConnectionsClient, ContactsClient, CrmHandoffsClient, DASHBOARD_SCHEMA, DASHBOARD_SCHEMA_VERSION, DashboardsClient, DeploymentsClient, FactsClient, FollowThroughClient, HttpError, INVOCATION_RESULT_KINDS, MFAType, MarketingConsentClient, MeetingMinutesClient, MeteringClient, NotImplementedError, OrgRoles, PM_ACCEPTANCE_DECISIONS, PM_ACCEPTANCE_STATES, PM_ANALYSIS_STATES, PM_APPROVAL_DECISIONS, PM_AVAILABILITY_BASES, PM_BENEFIT_POSITION_STATES, PM_BOOTSTRAP_MAX_BRIEF_BYTES, PM_BOOTSTRAP_MAX_TITLE_BYTES, PM_BOOTSTRAP_STATES, PM_CARD_DURABLE_KINDS, PM_CATCH_UP_BASES, PM_CHANGE_PREPARE_ACTIONS, PM_CHANGE_ROLES, PM_CLOSURE_BLOCKER_CODES, PM_CLOSURE_DISPOSITIONS, PM_CLOSURE_FAMILIES, PM_CLOSURE_PREDICATES, PM_CLOSURE_STATES, PM_COMMITMENT_OUTCOMES, PM_COMMITMENT_SOURCE_KINDS, PM_COMMUNICATION_DELIVERY_MODES, PM_COMMUNICATION_PURPOSES, PM_COMMUNICATION_RECEIPT_OUTCOMES, PM_COORDINATION_DECISION_STATES, PM_COORDINATION_ITEM_OUTCOMES, PM_COORDINATION_STATES, PM_COST_BINDING_KINDS, PM_COST_ENTRY_KINDS, PM_COST_ITEM_LINK_KINDS, PM_CRITERION_CHECK_METHODS, PM_CRITERION_COMPARATORS, PM_CRITERION_EXCEPTION_POLICIES, PM_CRITERION_REVIEWER_RULES, PM_CURRENCY_POLICIES, PM_DECISION_AUTHORITY_KINDS, PM_DECISION_KINDS, PM_DEFECT_SEVERITIES, PM_DEFECT_STATES, PM_DELIVERY_AUTHORITY_KINDS, PM_DEPENDENCY_RELATIONS, PM_DISPOSITION_HOLD_KINDS, PM_DUPLICATE_ACKNOWLEDGEMENT_REQUIRED, PM_ERROR_CODES, PM_EVIDENCE_ADMISSION_STATES, PM_EVIDENCE_REF_KINDS, PM_EVIDENCE_SOURCE_KINDS, PM_EXPORT_FAILURE_STAGES, PM_EXPORT_STATES, PM_FOLLOWUP_KINDS, PM_FOLLOWUP_RESOLUTIONS, PM_FOLLOWUP_STATES, PM_HANDOVER_DECISIONS, PM_HANDOVER_STATES, PM_INCOMPARABILITY_CODES, PM_LINKABLE_EVIDENCE_KINDS, PM_OBJECT_KINDS, PM_OPERATION_OUTCOMES, PM_ORIGINS, PM_OWNERSHIP_DECISIONS, PM_PORTFOLIO_RELATIONS, PM_PROJECT_LIFECYCLE_STATES, PM_PROJECT_ROLES, PM_RAID_LIFECYCLE_STATES, PM_RECIPIENT_NOT_REGISTERED, PM_RECORD_FAMILIES, PM_REPORT_NARRATIVE_LIMITS, PM_REPORT_PAGE_SIZES, PM_REPORT_TYPES, PM_REPORT_VERSION_KINDS, PM_REQUIREMENT_PRIORITIES, PM_REQUIREMENT_SCOPE_STATUSES, PM_RESEND_INTENT_REQUIRED, PM_RESEND_MODES, PM_RESIDUAL_COVERAGES, PM_RESIDUAL_KINDS, PM_RESPONSE_REVIEW_OUTCOMES, PM_RESULT_COVERAGE_STATES, PM_RISK_CALCULATION_METHODS, PM_RISK_OCCURRENCE_STATES, PM_RISK_OUTCOME_MEASURES, PM_RISK_POLARITIES, PM_RISK_RESPONSE_STATES, PM_RISK_RESPONSE_TYPES, PM_SCENARIO_OPS, PM_SCENARIO_STATES, PM_SELECTABLE_KINDS, PM_SENT_UNDER, PM_STAKEHOLDER_INFLUENCES, PM_STANDING_AUTHORITY_EVIDENCE_KIND, PM_STANDING_AUTHORITY_PURPOSES, PM_STANDING_MAX_INTERVAL_HOURS, PM_STANDING_MIN_INTERVAL_HOURS, PM_STANDING_REFUSAL_REASONS, PM_SUPPLIER_CONFIRMATION_POSTURES, PM_SUPPLIER_LINK_KINDS, PM_SUPPLIER_OUTCOMES, PM_UNLINKABLE_EVIDENCE_KINDS, PM_VERIFICATION_RESULTS, PM_VIEW_LAYOUT_MODES, PM_VIEW_MAX_LIMIT, PM_VIEW_RESULT_SCHEMA_VERSION, PM_VIEW_TYPES, PM_WORK_FAMILIES, PM_WORK_KINDS, PRODUCT_KINDS, PROVIDER_CATALOG, PROVIDER_LIFECYCLE_SURFACE, PacksClient, PersonExportClient, PlatformAdminClient, PmAcceptanceApi, PmApi, PmApiBase, PmBootstrapApi, PmChangeApi, PmClosureApi, PmCommonApi, PmCommunicationApi, PmFinanceApi, PmFollowupApi, PmGovernanceApi, PmPeopleApi, PmPlanningApi, PmPortfolioApi, PmReportsApi, PmRiskApi, PmViewsApi, PmWriteApiBase, ProviderType, REFUSAL_REASONS, RealEstateAdminClient, ReferralsClient, ResellerClient, ResourcesClient, SCHEMA_CAPABILITIES, SCHEMA_WORK, SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS, SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION, SignalsClient, TelegramClient, WORK_TASK_ERROR_CODES, WorkClient, WorkTaskError, activePmDocuments, assertPmBenefitInput, biVerificationOf, brandRoleAffordances, buildDocumentCitation, chatCardOf, claimAnnotationsOf, claimClassLabel, commitmentActStateLabel, commitmentTrackerStatusLabel, computationByKey, computeDisplayHint, coverageStateLabel, crmHandoffAwaitingDisposition, crmHandoffOutcomeLabel, derivePmCoverage, getProvider, getSpec, getValueAt, groundClaimPayload, groupClaimsByClass, hasMaterialDiff, isCommitmentConflicted, isDashboardSpec, isFailedScheduleRunStatus, isKnownChatCard, isKnownChatCardAction, isKnownChatCardType, isMeetingCommitmentOverdue, isMetadataPath, isPmAcceptanceState, isPmAnalysisState, isPmBenefitPositionState, isPmBootstrapState, isPmCardDurableKind, isPmCatchUpBasis, isPmClosureBlockerCode, isPmClosurePredicate, isPmClosureState, isPmCommunicationReceiptOutcome, isPmCoordinationItemOutcome, isPmCoordinationState, isPmDecimal, isPmDecisionKind, isPmDispositionHoldKind, isPmDocumentCitation, isPmDocumentRemoved, isPmErrorCode, isPmExportFailureStage, isPmExportState, isPmFollowUpKind, isPmFollowUpResolution, isPmFollowUpState, isPmHandoverState, isPmMoney, isPmObjectKind, isPmOperationOutcome, isPmOrigin, isPmProjectLifecycleState, isPmRaidLifecycleState, isPmRecordFamily, isPmReportType, isPmReportVersionKind, isPmResultCoverageState, isPmRiskOccurrenceState, isPmRiskResponseState, isPmRiskResponseType, isPmScenarioState, isPmSelectableKind, isPmSentUnder, isPmSupplierOutcome, isPmViewType, isPmWorkKind, isProductKind, isSecretPath, listProviders, meetingGateBehavior, meetingRoleAffordances, metadataKey, newProjectRequestKey, parseChatCard, parseConnectCatalog, parseConnectCatalogRow, parseConnectResultV1, parsePmDocumentCitation, personExportIsEmpty, personExportIsLimited, pmContextAccepted, pmDocumentRemoval, pmDuplicateDisclosureOf, pmErrorOf, pmResendIntentRequiredOf, pmStandingRefusalOf, readClaimCitations, resolveCitation, resolveClaimCitations, resolveClaimComputations, resolveMeetingField, resolveProviderCatalog, setValueAt, statusHeadline, summarizeDisposition, ungroundClaimPayload, usdMicros, validInspectionReason, validate, validateDashboardSpec, validateSpec };
6661
9628
  //# sourceMappingURL=index.js.map
6662
9629
  //# sourceMappingURL=index.js.map