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