@unson/brainbase-mcp 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
1
+ {
2
+ "schemaVersion": "1.0.0",
3
+ "package": {
4
+ "name": "@unson/brainbase-mcp",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "bin": {
8
+ "brainbase": "dist/cli.js",
9
+ "brainbase-mcp": "dist/index.js"
10
+ }
11
+ },
12
+ "mcp": {
13
+ "toolGroups": [
14
+ {
15
+ "id": "local",
16
+ "condition": "createServer() with both personal knowledge modes set to local",
17
+ "tools": [
18
+ {
19
+ "name": "audit_ontology",
20
+ "requiredInput": []
21
+ },
22
+ {
23
+ "name": "brainbase_onboarding_first_value",
24
+ "requiredInput": [
25
+ "action",
26
+ "runId"
27
+ ]
28
+ },
29
+ {
30
+ "name": "brainbase_onboarding_get",
31
+ "requiredInput": [
32
+ "runId"
33
+ ]
34
+ },
35
+ {
36
+ "name": "brainbase_onboarding_ingest",
37
+ "requiredInput": [
38
+ "candidates",
39
+ "runId",
40
+ "source"
41
+ ]
42
+ },
43
+ {
44
+ "name": "brainbase_onboarding_review",
45
+ "requiredInput": [
46
+ "actions",
47
+ "runId"
48
+ ]
49
+ },
50
+ {
51
+ "name": "brainbase_onboarding_start",
52
+ "requiredInput": [
53
+ "sources",
54
+ "valueTarget"
55
+ ]
56
+ },
57
+ {
58
+ "name": "get_context",
59
+ "requiredInput": []
60
+ },
61
+ {
62
+ "name": "get_ontology",
63
+ "requiredInput": []
64
+ },
65
+ {
66
+ "name": "infer_decisions",
67
+ "requiredInput": []
68
+ },
69
+ {
70
+ "name": "list_entities",
71
+ "requiredInput": []
72
+ },
73
+ {
74
+ "name": "onboarding_status",
75
+ "requiredInput": []
76
+ },
77
+ {
78
+ "name": "ontology_impact",
79
+ "requiredInput": []
80
+ },
81
+ {
82
+ "name": "personal_knowledge_context",
83
+ "requiredInput": []
84
+ },
85
+ {
86
+ "name": "personal_knowledge_register",
87
+ "requiredInput": [
88
+ "event"
89
+ ]
90
+ },
91
+ {
92
+ "name": "personal_knowledge_search",
93
+ "requiredInput": [
94
+ "query"
95
+ ]
96
+ },
97
+ {
98
+ "name": "resolve_entity",
99
+ "requiredInput": [
100
+ "asOf",
101
+ "text"
102
+ ]
103
+ },
104
+ {
105
+ "name": "search",
106
+ "requiredInput": [
107
+ "query"
108
+ ]
109
+ },
110
+ {
111
+ "name": "search_personal_kg",
112
+ "requiredInput": [
113
+ "query"
114
+ ]
115
+ }
116
+ ]
117
+ },
118
+ {
119
+ "id": "managed_cloud",
120
+ "condition": "createServer() with both personal knowledge modes set to managed_cloud",
121
+ "selectsFrom": "local",
122
+ "toolNames": [
123
+ "personal_knowledge_context",
124
+ "personal_knowledge_register",
125
+ "personal_knowledge_search"
126
+ ]
127
+ },
128
+ {
129
+ "id": "foundation_connected",
130
+ "condition": "createServer({ foundation }) with both personal knowledge modes set to local",
131
+ "extends": "local",
132
+ "tools": [
133
+ {
134
+ "name": "foundation_describe",
135
+ "requiredInput": []
136
+ },
137
+ {
138
+ "name": "foundation_read",
139
+ "requiredInput": [
140
+ "id",
141
+ "revision",
142
+ "type"
143
+ ]
144
+ },
145
+ {
146
+ "name": "foundation_validate_problem",
147
+ "requiredInput": [
148
+ "snapshot"
149
+ ]
150
+ },
151
+ {
152
+ "name": "foundation_validate_reference",
153
+ "requiredInput": [
154
+ "reference"
155
+ ]
156
+ }
157
+ ]
158
+ },
159
+ {
160
+ "id": "queue_task_tools",
161
+ "condition": "createQueueTaskTools({ backend, resolveAgent }) with the reference backend",
162
+ "tools": [
163
+ {
164
+ "name": "attach_evidence",
165
+ "requiredInput": [
166
+ "expected_version",
167
+ "kind",
168
+ "ref",
169
+ "task_id"
170
+ ]
171
+ },
172
+ {
173
+ "name": "claim_next",
174
+ "requiredInput": []
175
+ },
176
+ {
177
+ "name": "claim_task",
178
+ "requiredInput": [
179
+ "task_id"
180
+ ]
181
+ },
182
+ {
183
+ "name": "get_task",
184
+ "requiredInput": [
185
+ "task_id"
186
+ ]
187
+ },
188
+ {
189
+ "name": "list_my_tasks",
190
+ "requiredInput": []
191
+ },
192
+ {
193
+ "name": "renew_claim",
194
+ "requiredInput": [
195
+ "task_id"
196
+ ]
197
+ },
198
+ {
199
+ "name": "update_status",
200
+ "requiredInput": [
201
+ "expected_version",
202
+ "task_id",
203
+ "to_status"
204
+ ]
205
+ }
206
+ ],
207
+ "releaseStatus": "unreleased"
208
+ }
209
+ ],
210
+ "internalTools": [
211
+ {
212
+ "name": "foundation_adopt",
213
+ "requiredInput": [
214
+ "digest",
215
+ "id",
216
+ "revision",
217
+ "scope_id",
218
+ "type"
219
+ ]
220
+ },
221
+ {
222
+ "name": "foundation_describe",
223
+ "requiredInput": [
224
+ "scope_id"
225
+ ]
226
+ },
227
+ {
228
+ "name": "foundation_read",
229
+ "requiredInput": [
230
+ "id",
231
+ "revision",
232
+ "scope_id",
233
+ "type"
234
+ ]
235
+ },
236
+ {
237
+ "name": "foundation_validate_problem",
238
+ "requiredInput": [
239
+ "scope_id",
240
+ "snapshot"
241
+ ]
242
+ },
243
+ {
244
+ "name": "foundation_validate_reference",
245
+ "requiredInput": [
246
+ "reference",
247
+ "scope_id"
248
+ ]
249
+ }
250
+ ]
251
+ },
252
+ "cli": {
253
+ "bin": "brainbase",
254
+ "commands": [
255
+ "doctor",
256
+ "graph:bundles",
257
+ "graph:upgrade",
258
+ "judgment:hook",
259
+ "judgment:install",
260
+ "mcp",
261
+ "memory:list",
262
+ "memory:register",
263
+ "onboard:agent",
264
+ "onboard:apply",
265
+ "onboard:candidates",
266
+ "onboard:demo",
267
+ "onboard:diagnose-sources",
268
+ "onboard:extract",
269
+ "onboard:import",
270
+ "onboard:init",
271
+ "onboard:install",
272
+ "onboard:plan",
273
+ "onboard:projects",
274
+ "onboard:recommend",
275
+ "onboard:routines",
276
+ "onboard:seed",
277
+ "onboard:skills",
278
+ "onboard:start",
279
+ "ontology:audit",
280
+ "ontology:migrate",
281
+ "ontology:show",
282
+ "web:serve"
283
+ ],
284
+ "aliases": {
285
+ "review:serve": "web:serve"
286
+ }
287
+ }
288
+ }
@@ -1,7 +1,7 @@
1
1
  import { type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
2
2
  import type { AuthorizationServerMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
3
3
  import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
4
- import { type MeetingSourceAccessDetail, type MeetingSourceCallTool, type MeetingSourceFailure, type MeetingSourceFailureReason, type MeetingSourceMeeting, type MeetingSourceProvider, type MeetingSourceSegment, type TactiqTranscriptBudget, type TactiqTranscriptRead } from './meeting-source-reader.js';
4
+ import { type MeetingSourceAccessDetail, type MeetingSourceCallTool, type MeetingSourceFailure, type MeetingSourceFailureReason, type MeetingSourceMeeting, type MeetingSourceProvider, type MeetingSourceSegment, type MeetingSourceSummaryState, type TactiqTranscriptBudget, type TactiqTranscriptRead } from './meeting-source-reader.js';
5
5
  import type { OrganizationConnectionBinding, OrganizationConnectionProviderAdapter } from './organization-connection.js';
6
6
  export declare const MEETING_SOURCE_LIST_REVISION = 2;
7
7
  export declare const MEETING_SOURCE_RELIST_LOOKBACK_MS: number;
@@ -152,6 +152,25 @@ export interface MeetingSourceDeliveredMeeting {
152
152
  version: number;
153
153
  deliveredAt: string;
154
154
  }
155
+ /**
156
+ * The provider's own meeting summary (Tactiq `detailedSummary`, Plaud `get_note`)
157
+ * saved beside the transcript. It is never merged into the transcript text. A
158
+ * `generating` summary is saved as unfinished and re-read on a later sync.
159
+ */
160
+ export interface MeetingSourceDeliveredSummary {
161
+ state: MeetingSourceSummaryState;
162
+ text: string | null;
163
+ jobId: string | null;
164
+ retrievedAt: string;
165
+ }
166
+ /** A summary that was generating or unreadable when its transcript was delivered. */
167
+ export interface MeetingSourcePendingSummary {
168
+ meeting: MeetingSourceMeeting;
169
+ jobId: string | null;
170
+ retryAt: string | null;
171
+ attempts: number;
172
+ firstSeenAt: string;
173
+ }
155
174
  export interface MeetingSourceSyncState {
156
175
  schemaVersion: 1;
157
176
  connectionId: string;
@@ -161,6 +180,15 @@ export interface MeetingSourceSyncState {
161
180
  /** List-reader revision that produced listedThrough; older cursors are re-listed once. */
162
181
  listRevision?: number;
163
182
  pending: MeetingSourcePendingMeeting[];
183
+ /** Delivered meetings whose provider summary was generating or unreadable; re-read later. */
184
+ pendingSummaries?: MeetingSourcePendingSummary[];
185
+ /** Terminal summary retries; never suppresses transcript re-checks. */
186
+ unobtainableSummaries?: Array<{
187
+ meetingId: string;
188
+ reason: 'summary_retry_exhausted';
189
+ message: string;
190
+ decidedAt: string;
191
+ }>;
164
192
  unobtainable: Array<{
165
193
  meetingId: string;
166
194
  reason: string;
@@ -194,6 +222,8 @@ export interface MeetingSourceDelivery {
194
222
  segments: MeetingSourceSegment[];
195
223
  digest: string;
196
224
  };
225
+ /** The provider summary read at ingest, or `null` when it could not be read. */
226
+ summary: MeetingSourceDeliveredSummary | null;
197
227
  version: number;
198
228
  retrievedAt: string;
199
229
  }
@@ -233,6 +263,8 @@ export declare function syncMeetingSourceConnection(input: {
233
263
  initialLookbackMs?: number;
234
264
  overlapMs?: number;
235
265
  maxAttempts?: number;
266
+ /** Earliest a generating or unreadable summary is re-read on a later sync. Default 15 min. */
267
+ summaryRetryMs?: number;
236
268
  }): Promise<MeetingSourceSyncResult>;
237
269
  export interface MeetingSourceListedMeeting {
238
270
  connection: MeetingSourceConnectionRecord;
@@ -4,7 +4,7 @@ import { dirname } from 'node:path';
4
4
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
5
  import { discoverOAuthServerInfo, exchangeAuthorization, registerClient, startAuthorization, } from '@modelcontextprotocol/sdk/client/auth.js';
6
6
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
7
- import { createTactiqTranscriptBudget, listMeetings, probeTranscript, readTranscript, } from './meeting-source-reader.js';
7
+ import { createTactiqTranscriptBudget, listMeetings, probeTranscript, readProviderSummary, readTranscript, } from './meeting-source-reader.js';
8
8
  /**
9
9
  * Connections to meeting sources (Plaud, Tactiq) and per-connection sync.
10
10
  * Persistence, tenant and owner authorization, scheduling, and the delivery
@@ -370,6 +370,8 @@ export function emptyMeetingSourceSyncState(connection) {
370
370
  syncEnabled: true,
371
371
  listedThrough: null,
372
372
  pending: [],
373
+ pendingSummaries: [],
374
+ unobtainableSummaries: [],
373
375
  unobtainable: [],
374
376
  delivered: {},
375
377
  tactiqReads: [],
@@ -455,7 +457,120 @@ export async function syncMeetingSourceConnection(input) {
455
457
  const budget = connection.provider === 'tactiq' ? createTactiqTranscriptBudget({ reads: state.tactiqReads }) : undefined;
456
458
  const delivered = [];
457
459
  let failure = null;
460
+ let connectionScopeFailed = false;
458
461
  const queue = newestFirst([...candidates.values()]);
462
+ const summaryRetryMs = input.summaryRetryMs ?? 15 * 60 * 1000;
463
+ const pendingSummariesById = new Map((state.pendingSummaries ?? []).map((entry) => [entry.meeting.externalId, entry]));
464
+ // Meetings whose summary was read this run; the refresh pass skips them.
465
+ const summaryHandled = new Set();
466
+ /** Reads the provider summary at ingest. A failure is non-fatal: it is saved as `null`. */
467
+ const readDeliveredSummary = async (meeting) => {
468
+ const result = await readProviderSummary({ provider: connection.provider, callTool, meetingId: meeting.externalId, now });
469
+ if (result.status !== 'ok')
470
+ return null;
471
+ return { state: result.state, text: result.summary?.text ?? null, jobId: result.jobId, retrievedAt: now().toISOString() };
472
+ };
473
+ const trackSummary = (meeting, summary) => {
474
+ summaryHandled.add(meeting.externalId);
475
+ if (summary === null || summary.state === 'generating') {
476
+ const previous = pendingSummariesById.get(meeting.externalId);
477
+ pendingSummariesById.set(meeting.externalId, {
478
+ meeting,
479
+ jobId: summary?.jobId ?? null,
480
+ retryAt: new Date(now().getTime() + summaryRetryMs).toISOString(),
481
+ attempts: previous?.attempts ?? 0,
482
+ firstSeenAt: previous?.firstSeenAt ?? now().toISOString(),
483
+ });
484
+ }
485
+ else {
486
+ // ready or empty: nothing left to re-read.
487
+ pendingSummariesById.delete(meeting.externalId);
488
+ }
489
+ };
490
+ const bumpSummaryRetry = (entry) => {
491
+ const attempts = entry.attempts + 1;
492
+ if (attempts >= (input.maxAttempts ?? 5)) {
493
+ pendingSummariesById.delete(entry.meeting.externalId);
494
+ (state.unobtainableSummaries ??= []).push({
495
+ meetingId: entry.meeting.externalId,
496
+ reason: 'summary_retry_exhausted',
497
+ message: 'Provider summary could not be resolved and delivered within maxAttempts.',
498
+ decidedAt: now().toISOString(),
499
+ });
500
+ return;
501
+ }
502
+ pendingSummariesById.set(entry.meeting.externalId, {
503
+ ...entry,
504
+ attempts,
505
+ retryAt: new Date(now().getTime() + summaryRetryMs).toISOString(),
506
+ });
507
+ };
508
+ /**
509
+ * Re-reads summaries that were generating or unreadable on an earlier sync. The summary
510
+ * call (`get_meeting` / `get_note`) does not spend the Tactiq transcript budget;
511
+ * the transcript is re-read only once the summary resolves, so the saved record
512
+ * carries both together.
513
+ */
514
+ const refreshGeneratingSummaries = async () => {
515
+ for (const entry of [...pendingSummariesById.values()]) {
516
+ const meetingId = entry.meeting.externalId;
517
+ if (summaryHandled.has(meetingId))
518
+ continue;
519
+ if (entry.retryAt && Date.parse(entry.retryAt) > currentTime)
520
+ continue;
521
+ const summaryResult = await readProviderSummary({ provider: connection.provider, callTool, meetingId, now });
522
+ if (summaryResult.status !== 'ok') {
523
+ bumpSummaryRetry(entry);
524
+ continue;
525
+ }
526
+ if (summaryResult.state === 'generating') {
527
+ bumpSummaryRetry({ ...entry, jobId: summaryResult.jobId });
528
+ continue;
529
+ }
530
+ if (budget) {
531
+ const slot = budget.tryAcquire(meetingId, now());
532
+ if (!slot.ok) {
533
+ pendingSummariesById.set(meetingId, { ...entry, retryAt: slot.retryAt });
534
+ continue;
535
+ }
536
+ }
537
+ const transcript = await readTranscript({ provider: connection.provider, callTool, meetingId, budget, now });
538
+ if (transcript.status !== 'complete') {
539
+ bumpSummaryRetry(entry);
540
+ continue;
541
+ }
542
+ const summary = {
543
+ state: summaryResult.state,
544
+ text: summaryResult.summary?.text ?? null,
545
+ jobId: summaryResult.jobId,
546
+ retrievedAt: now().toISOString(),
547
+ };
548
+ const previous = state.delivered[meetingId];
549
+ const version = (previous?.version ?? 0) + 1;
550
+ try {
551
+ await input.deliver({
552
+ connectionId: connection.connectionId,
553
+ tenantId: connection.tenantId,
554
+ provider: connection.provider,
555
+ scope: connection.scope,
556
+ ownerPersonId: connection.ownerPersonId,
557
+ orgId: connection.orgId,
558
+ meeting: entry.meeting,
559
+ transcript: { text: transcript.text, segments: transcript.segments, digest: transcript.digest },
560
+ summary,
561
+ version,
562
+ retrievedAt: now().toISOString(),
563
+ });
564
+ }
565
+ catch {
566
+ bumpSummaryRetry(entry);
567
+ continue;
568
+ }
569
+ state.delivered[meetingId] = { digest: transcript.digest, version, deliveredAt: now().toISOString() };
570
+ pendingSummariesById.delete(meetingId);
571
+ delivered.push({ meetingId, version });
572
+ }
573
+ };
459
574
  const keepPending = (meeting, reason, message, retryAt, countAttempt) => {
460
575
  const previous = pendingById.get(meeting.externalId);
461
576
  const attempts = (previous?.attempts ?? 0) + (countAttempt ? 1 : 0);
@@ -492,6 +607,7 @@ export async function syncMeetingSourceConnection(input) {
492
607
  for (const rest of queue.slice(index))
493
608
  keepPending(rest, reason, message, retryAt, false);
494
609
  failure = { reason, message };
610
+ connectionScopeFailed = true;
495
611
  break;
496
612
  }
497
613
  keepPending(meeting, reason, message, retryAt, isFailure);
@@ -504,6 +620,7 @@ export async function syncMeetingSourceConnection(input) {
504
620
  pendingById.delete(meeting.externalId);
505
621
  continue;
506
622
  }
623
+ const summary = await readDeliveredSummary(meeting);
507
624
  const version = (previous?.version ?? 0) + 1;
508
625
  try {
509
626
  await input.deliver({
@@ -515,6 +632,7 @@ export async function syncMeetingSourceConnection(input) {
515
632
  orgId: connection.orgId,
516
633
  meeting,
517
634
  transcript: { text: result.text, segments: result.segments, digest: result.digest },
635
+ summary,
518
636
  version,
519
637
  retrievedAt: now().toISOString(),
520
638
  });
@@ -527,9 +645,14 @@ export async function syncMeetingSourceConnection(input) {
527
645
  }
528
646
  state.delivered[meeting.externalId] = { digest: result.digest, version, deliveredAt: now().toISOString() };
529
647
  pendingById.delete(meeting.externalId);
648
+ trackSummary(meeting, summary);
530
649
  delivered.push({ meetingId: meeting.externalId, version });
531
650
  }
651
+ if (!connectionScopeFailed) {
652
+ await refreshGeneratingSummaries();
653
+ }
532
654
  state.pending = [...pendingById.values()];
655
+ state.pendingSummaries = [...pendingSummariesById.values()];
533
656
  if (budget)
534
657
  state.tactiqReads = budget.reads(now());
535
658
  if (!listed.complete) {
@@ -68,9 +68,18 @@ export interface MeetingSourceProviderSummary {
68
68
  kind: 'provider_summary';
69
69
  text: string;
70
70
  }
71
+ /**
72
+ * `ready`: a usable summary is present. `generating`: the provider is still
73
+ * producing it (Tactiq), so it should be saved as unfinished and re-read later.
74
+ * `empty`: the provider has no summary for this meeting.
75
+ */
76
+ export type MeetingSourceSummaryState = 'ready' | 'generating' | 'empty';
71
77
  export type MeetingSourceSummaryResult = {
72
78
  status: 'ok';
79
+ state: MeetingSourceSummaryState;
73
80
  summary: MeetingSourceProviderSummary | null;
81
+ /** Tactiq generation job id while `state` is `generating`; `null` otherwise. */
82
+ jobId: string | null;
74
83
  } | {
75
84
  status: 'unavailable';
76
85
  failure: MeetingSourceFailure;
@@ -99,13 +99,20 @@ export async function readProviderSummary(input) {
99
99
  try {
100
100
  if (input.provider === 'plaud') {
101
101
  const payload = await invoke(input.callTool, 'get_note', { file_id: input.meetingId });
102
- return { status: 'ok', summary: toSummary(extractText(payload)) };
102
+ const summary = toSummary(extractText(payload));
103
+ return { status: 'ok', state: summary ? 'ready' : 'empty', summary, jobId: null };
103
104
  }
104
105
  const payload = asRecord(await invoke(input.callTool, 'get_meeting', { meetingId: input.meetingId }));
105
106
  const detailed = asRecord(payload?.detailedSummary);
107
+ // A summary still being produced is saved as unfinished so it can be
108
+ // re-read with its jobId; it is never returned as a finished summary.
109
+ if (detailed?.status === 'generating') {
110
+ return { status: 'ok', state: 'generating', summary: null, jobId: stringValue(detailed.jobId) };
111
+ }
106
112
  if (!detailed || detailed.status !== 'ready')
107
- return { status: 'ok', summary: null };
108
- return { status: 'ok', summary: toSummary(extractText(detailed.content)) };
113
+ return { status: 'ok', state: 'empty', summary: null, jobId: null };
114
+ const summary = toSummary(extractText(detailed.content));
115
+ return { status: 'ok', state: summary ? 'ready' : 'empty', summary, jobId: null };
109
116
  }
110
117
  catch (error) {
111
118
  return { status: 'unavailable', failure: await classifyFailure(error, input.provider, input.callTool, 'meeting', now()) };
@@ -0,0 +1,28 @@
1
+ /** Repository-neutral validation for a caller-supplied ownership ledger and survey.
2
+ * Measurements and tenant data remain with the caller; validation performs no I/O.
3
+ */
4
+ export interface OwnershipSurveyComponent {
5
+ id: string;
6
+ lifecycle: string;
7
+ current_paths?: string[];
8
+ retained_source_paths?: string[];
9
+ }
10
+ export interface OwnershipSurveyEntry {
11
+ id: string;
12
+ wave: string;
13
+ duplicate: string;
14
+ production_use: string;
15
+ disposition: string;
16
+ files?: Array<{
17
+ path?: string;
18
+ }>;
19
+ }
20
+ export interface OwnershipSurvey {
21
+ version: number;
22
+ components?: OwnershipSurveyEntry[];
23
+ }
24
+ export interface OwnershipSurveyContract {
25
+ components?: OwnershipSurveyComponent[];
26
+ }
27
+ export declare const OWNERSHIP_SURVEY_WAVES: readonly string[];
28
+ export declare function validateOwnershipSurvey(contract: OwnershipSurveyContract | null | undefined, survey: OwnershipSurvey | null | undefined): string[];
@@ -0,0 +1,60 @@
1
+ export const OWNERSHIP_SURVEY_WAVES = Object.freeze(['1', '2', '3a', '3b', '3c', '3d', '4a', '4b', '4c', '4d', '4e', '5']);
2
+ const SURVEY_DUPLICATES = new Set(['same', 'partial', 'none']);
3
+ const SURVEY_PRODUCTION_USES = new Set(['used', 'conditional', 'scripts_only', 'shim_only', 'schema_only',
4
+ 'shim_and_schema', 'config_only', 'unused']);
5
+ const SURVEY_DISPOSITIONS = new Set(['move', 'switch_and_delete', 'delete_shim', 'inline_or_delete', 'delete', 'readback_and_close']);
6
+ export function validateOwnershipSurvey(contract, survey) {
7
+ if (!survey)
8
+ return [];
9
+ const errors = [];
10
+ if (survey.version !== 1)
11
+ errors.push('所有台帳の調査結果の version は 1 である必要があります');
12
+ const entries = new Map();
13
+ const components = new Map((contract?.components ?? []).map((component) => [component.id, component]));
14
+ for (const entry of Array.isArray(survey.components) ? survey.components : []) {
15
+ if (entries.has(entry?.id))
16
+ errors.push(`所有台帳の調査結果に項目が重複しています: ${entry?.id}`);
17
+ entries.set(entry?.id, entry);
18
+ const component = components.get(entry?.id);
19
+ if (!component || !['migration_pending', 'retired'].includes(component.lifecycle)) {
20
+ errors.push(`調査結果の項目は台帳の移設待ちか退役である必要があります: ${entry?.id}`);
21
+ }
22
+ }
23
+ for (const component of contract?.components ?? []) {
24
+ if (component?.lifecycle !== 'migration_pending')
25
+ continue;
26
+ const entry = entries.get(component.id);
27
+ if (!entry) {
28
+ errors.push(`移設待ちの項目に調査結果(段・重複・本番での利用)がありません: ${component.id}`);
29
+ continue;
30
+ }
31
+ if (!OWNERSHIP_SURVEY_WAVES.includes(entry.wave))
32
+ errors.push(`${component.id} の調査結果の wave が不正です: ${entry.wave}`);
33
+ if (!SURVEY_DUPLICATES.has(entry.duplicate))
34
+ errors.push(`${component.id} の調査結果の duplicate が不正です: ${entry.duplicate}`);
35
+ if (!SURVEY_PRODUCTION_USES.has(entry.production_use)) {
36
+ errors.push(`${component.id} の調査結果の production_use が不正です: ${entry.production_use}`);
37
+ }
38
+ if (!SURVEY_DISPOSITIONS.has(entry.disposition))
39
+ errors.push(`${component.id} の調査結果の disposition が不正です: ${entry.disposition}`);
40
+ const expectedPaths = new Set([...(component.current_paths ?? []), ...(component.retained_source_paths ?? [])]);
41
+ if (!Array.isArray(entry.files)) {
42
+ errors.push(`${component.id} の調査結果に files 配列がありません`);
43
+ continue;
44
+ }
45
+ const actualPaths = new Set();
46
+ for (const file of entry.files) {
47
+ if (typeof file?.path !== 'string' || !expectedPaths.has(file.path)) {
48
+ errors.push(`${component.id} の調査結果に台帳にないパスがあります: ${file?.path}`);
49
+ }
50
+ if (actualPaths.has(file?.path))
51
+ errors.push(`${component.id} の調査結果のパスが重複しています: ${file?.path}`);
52
+ actualPaths.add(file?.path);
53
+ }
54
+ for (const expectedPath of expectedPaths) {
55
+ if (!actualPaths.has(expectedPath))
56
+ errors.push(`${component.id} の調査結果に台帳のパスがありません: ${expectedPath}`);
57
+ }
58
+ }
59
+ return errors.sort();
60
+ }