@mfdaves/okf-mcp 0.9.1 → 0.13.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +452 -26
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/distribution/reference-bundle.md +10 -3
  5. package/okf/okf-mcp/index.md +2 -1
  6. package/okf/okf-mcp/interfaces/http-authoring-api.md +11 -2
  7. package/okf/okf-mcp/interfaces/mcp-http.md +64 -0
  8. package/okf/okf-mcp/interfaces/mcp-tools.md +25 -6
  9. package/okf/okf-mcp/overview/okf-mcp.md +16 -6
  10. package/okf/okf-mcp/policies/authoring-safety.md +28 -5
  11. package/okf/okf-mcp/runtime/indexer.md +14 -1
  12. package/okf/okf-mcp/runtime/mcp-server.md +16 -8
  13. package/okf/okf-mcp/specs/producer-api.md +16 -2
  14. package/package.json +17 -5
  15. package/server.json +38 -2
  16. package/src/assets.js +165 -73
  17. package/src/authoring/candidates.js +434 -0
  18. package/src/authoring/git-preflight.js +225 -0
  19. package/src/authoring/git-publish.js +783 -0
  20. package/src/authoring/live.js +757 -0
  21. package/src/authoring/paths.js +112 -0
  22. package/src/authoring/policy-hook.js +221 -0
  23. package/src/authoring/proposal-policy.js +159 -0
  24. package/src/authoring/receipts.js +373 -0
  25. package/src/authoring/render.js +38 -0
  26. package/src/authoring/shared.js +75 -0
  27. package/src/authoring/staging.js +216 -0
  28. package/src/authoring.js +386 -287
  29. package/src/cache/files.js +147 -0
  30. package/src/cache/lock.js +201 -0
  31. package/src/cache/paths.js +197 -0
  32. package/src/cache/store.js +703 -0
  33. package/src/catalog-text.js +19 -0
  34. package/src/cli/commands.js +448 -0
  35. package/src/cli/http-options.js +193 -0
  36. package/src/cli/options.js +554 -0
  37. package/src/cli/usage.js +96 -0
  38. package/src/cli.js +18 -932
  39. package/src/computation.js +99 -61
  40. package/src/context/assemble.js +567 -0
  41. package/src/context/cli-options.js +88 -0
  42. package/src/context/score.js +234 -0
  43. package/src/context/sections.js +274 -0
  44. package/src/embed/interface.js +160 -0
  45. package/src/embed/openai.js +715 -0
  46. package/src/embed/prepare.js +182 -0
  47. package/src/embed/units.js +96 -0
  48. package/src/error-details.js +53 -0
  49. package/src/git-source.js +112 -52
  50. package/src/graph.js +95 -37
  51. package/src/http-server.js +36 -17
  52. package/src/index.js +15 -0
  53. package/src/indexer/assemble.js +566 -0
  54. package/src/indexer/build.js +290 -0
  55. package/src/indexer/cache.js +81 -0
  56. package/src/indexer/edges.js +430 -0
  57. package/src/indexer/index.js +44 -0
  58. package/src/indexer/paths.js +178 -0
  59. package/src/indexer/resolve.js +282 -0
  60. package/src/indexer/update.js +720 -0
  61. package/src/indexer.js +3 -1068
  62. package/src/live-authoring.js +4 -2329
  63. package/src/markdown.js +21 -16
  64. package/src/mcp/auth.js +409 -0
  65. package/src/mcp/http.js +317 -0
  66. package/src/mcp/principal.js +59 -0
  67. package/src/mcp/registry.js +356 -0
  68. package/src/mcp/resources.js +45 -0
  69. package/src/mcp/server.js +567 -0
  70. package/src/mcp/tools/catalog.js +247 -0
  71. package/src/mcp/tools/computation.js +83 -0
  72. package/src/mcp/tools/context.js +133 -0
  73. package/src/mcp/tools/graph.js +167 -0
  74. package/src/mcp/tools/live-authoring.js +316 -0
  75. package/src/mcp/tools/migration.js +86 -0
  76. package/src/mcp/tools/producers.js +79 -0
  77. package/src/mcp/tools/proposals.js +225 -0
  78. package/src/mcp/tools/provenance.js +87 -0
  79. package/src/mcp/tools/remote.js +79 -0
  80. package/src/mcp/tools/search.js +242 -0
  81. package/src/mcp-server.js +3 -1611
  82. package/src/migration.js +431 -253
  83. package/src/parser.js +245 -130
  84. package/src/plugins.js +71 -48
  85. package/src/policy/write-policy.js +713 -0
  86. package/src/producer-publisher.js +202 -78
  87. package/src/producers.js +311 -103
  88. package/src/project.js +346 -93
  89. package/src/remote.js +96 -61
  90. package/src/search/cli-options.js +107 -0
  91. package/src/search/confidence.js +61 -0
  92. package/src/search/dense.js +304 -0
  93. package/src/search/embedding-cli.js +57 -0
  94. package/src/search/embedding-config.js +217 -0
  95. package/src/search/fusion.js +249 -0
  96. package/src/search/hybrid.js +526 -0
  97. package/src/search/languages.js +200 -0
  98. package/src/search/lexical.js +695 -0
  99. package/src/search/query.js +620 -0
  100. package/src/search/stem/among.js +43 -0
  101. package/src/search/stem/base-stemmer.js +311 -0
  102. package/src/search/stem/en-regions.js +456 -0
  103. package/src/search/stem/en-suffixes.js +664 -0
  104. package/src/search/stem/en-tables.js +176 -0
  105. package/src/search/stem/en.js +238 -0
  106. package/src/search/stem/it-regions.js +459 -0
  107. package/src/search/stem/it-suffixes.js +471 -0
  108. package/src/search/stem/it-tables.js +257 -0
  109. package/src/search/stem/it.js +155 -0
  110. package/src/search-index.js +2 -81
  111. package/src/search.js +2 -252
  112. package/src/store.js +134 -81
  113. package/src/tool-packs.js +346 -0
  114. package/src/v02.js +301 -105
  115. package/src/validation.js +24 -20
@@ -0,0 +1,434 @@
1
+ "use strict";
2
+
3
+ const { isDeepStrictEqual } = require("node:util");
4
+
5
+ const { isConfiguredGeneratorOutput } = require("../authoring");
6
+ const {
7
+ conceptIsGeneratedFile,
8
+ conceptMatchSummary,
9
+ normalizeConceptTitle,
10
+ recoverConceptLocator,
11
+ resolveConcept,
12
+ } = require("../indexer");
13
+ const { validActor } = require("../v02");
14
+ const { hasOwn, isPlainObject } = require("./shared");
15
+
16
+ const MANAGED_METADATA_KEYS = new Set([
17
+ "id",
18
+ "type",
19
+ "title",
20
+ "description",
21
+ "tags",
22
+ "sources",
23
+ "relations",
24
+ "generated",
25
+ "generated_file",
26
+ "generatedFile",
27
+ "runtime",
28
+ "parameters",
29
+ "computation",
30
+ "executor",
31
+ "attester",
32
+ ]);
33
+
34
+ function nonEmptyString(value, field) {
35
+ if (typeof value !== "string" || !value.trim()) {
36
+ throw new Error(`${field} must be a non-empty string.`);
37
+ }
38
+ return value.trim();
39
+ }
40
+
41
+ function normalizeBody(value) {
42
+ return String(value || "")
43
+ .replace(/\r\n/g, "\n")
44
+ .trim();
45
+ }
46
+
47
+ function canonicalValue(value) {
48
+ if (Array.isArray(value)) {
49
+ return value.map(canonicalValue);
50
+ }
51
+ if (isPlainObject(value)) {
52
+ return Object.fromEntries(
53
+ Object.keys(value)
54
+ .sort()
55
+ .map((key) => [key, canonicalValue(value[key])]),
56
+ );
57
+ }
58
+ return value;
59
+ }
60
+
61
+ function exactKey(value) {
62
+ return JSON.stringify(canonicalValue(value));
63
+ }
64
+
65
+ function uniqueStrings(values, field) {
66
+ if (values === undefined) {
67
+ return [];
68
+ }
69
+ if (!Array.isArray(values)) {
70
+ throw new Error(`${field} must be an array.`);
71
+ }
72
+ const seen = new Set();
73
+ const normalized = [];
74
+ values.forEach((value, index) => {
75
+ const item = nonEmptyString(value, `${field}[${index}]`);
76
+ if (!seen.has(item)) {
77
+ seen.add(item);
78
+ normalized.push(item);
79
+ }
80
+ });
81
+ return normalized;
82
+ }
83
+
84
+ function normalizeSource(value, field) {
85
+ if (typeof value === "string") {
86
+ return { resource: nonEmptyString(value, field) };
87
+ }
88
+ if (!isPlainObject(value)) {
89
+ throw new Error(`${field} must be a resource string or source object.`);
90
+ }
91
+ return Object.assign({}, value);
92
+ }
93
+
94
+ function sourceIdentity(source) {
95
+ if (typeof source === "string" && source.trim()) {
96
+ return `resource:${source.trim()}`;
97
+ }
98
+ if (isPlainObject(source) && typeof source.id === "string" && source.id.trim()) {
99
+ return `id:${source.id.trim()}`;
100
+ }
101
+ if (isPlainObject(source) && typeof source.resource === "string" && source.resource.trim()) {
102
+ return `resource:${source.resource.trim()}`;
103
+ }
104
+ return `exact:${exactKey(source)}`;
105
+ }
106
+
107
+ function sourceMatches(source, selector) {
108
+ const sourceId = isPlainObject(source) && typeof source.id === "string" ? source.id.trim() : "";
109
+ const sourceResource =
110
+ typeof source === "string"
111
+ ? source.trim()
112
+ : isPlainObject(source) && typeof source.resource === "string"
113
+ ? source.resource.trim()
114
+ : "";
115
+ if (typeof selector === "string") {
116
+ const value = selector.trim();
117
+ return sourceId === value || sourceResource === value;
118
+ }
119
+ if (!isPlainObject(selector)) {
120
+ return false;
121
+ }
122
+ if (typeof selector.id === "string" && selector.id.trim()) {
123
+ return sourceId === selector.id.trim();
124
+ }
125
+ if (typeof selector.resource === "string" && selector.resource.trim()) {
126
+ return sourceResource === selector.resource.trim();
127
+ }
128
+ return false;
129
+ }
130
+
131
+ function validateSourceSelector(selector, field) {
132
+ if (typeof selector === "string") {
133
+ nonEmptyString(selector, field);
134
+ return;
135
+ }
136
+ if (!isPlainObject(selector)) {
137
+ throw new Error(`${field} must select a source by id or resource.`);
138
+ }
139
+ const hasId = typeof selector.id === "string" && selector.id.trim();
140
+ const hasResource = typeof selector.resource === "string" && selector.resource.trim();
141
+ if (!hasId && !hasResource) {
142
+ throw new Error(`${field} must select a source by id or resource.`);
143
+ }
144
+ }
145
+
146
+ function applySourcePatch(existing, patch, field) {
147
+ if (!isPlainObject(patch)) {
148
+ throw new Error(`${field} must be an object containing add and/or remove arrays.`);
149
+ }
150
+ const remove = patch.remove === undefined ? [] : patch.remove;
151
+ if (!Array.isArray(remove)) {
152
+ throw new Error(`${field}.remove must be an array.`);
153
+ }
154
+ remove.forEach((selector, index) =>
155
+ validateSourceSelector(selector, `${field}.remove[${index}]`),
156
+ );
157
+ let result = Array.isArray(existing) ? existing.slice() : [];
158
+ result = result.filter((source) => !remove.some((selector) => sourceMatches(source, selector)));
159
+ const additions = patch.add === undefined ? [] : patch.add;
160
+ if (!Array.isArray(additions)) {
161
+ throw new Error(`${field}.add must be an array.`);
162
+ }
163
+ additions
164
+ .map((source, index) => normalizeSource(source, `${field}.add[${index}]`))
165
+ .forEach((source) => {
166
+ const identity = sourceIdentity(source);
167
+ const existingIndex = result.findIndex((candidate) => sourceIdentity(candidate) === identity);
168
+ if (existingIndex === -1) {
169
+ result.push(source);
170
+ } else if (!isDeepStrictEqual(result[existingIndex], source)) {
171
+ result[existingIndex] = source;
172
+ }
173
+ });
174
+ const seen = new Set();
175
+ return result.filter((source) => {
176
+ const identity = sourceIdentity(source);
177
+ if (seen.has(identity)) {
178
+ return false;
179
+ }
180
+ seen.add(identity);
181
+ return true;
182
+ });
183
+ }
184
+
185
+ function relationParts(value) {
186
+ if (typeof value === "string") {
187
+ const parts = value.trim().split(/\s+/);
188
+ return {
189
+ type: parts.length > 1 ? parts.shift() : "related_to",
190
+ target: parts.join(" ") || value.trim(),
191
+ };
192
+ }
193
+ if (isPlainObject(value)) {
194
+ return {
195
+ type: String(value.type || value.kind || "related_to").trim(),
196
+ target: String(value.target || value.to || "").trim(),
197
+ };
198
+ }
199
+ return { type: "", target: "" };
200
+ }
201
+
202
+ function relationKey(value) {
203
+ const relation = relationParts(value);
204
+ return `${relation.type}\u0000${relation.target}`;
205
+ }
206
+
207
+ function normalizeRelation(value, field) {
208
+ if (!isPlainObject(value)) {
209
+ throw new Error(`${field} must be an object.`);
210
+ }
211
+ const type = nonEmptyString(value.type, `${field}.type`);
212
+ const target = nonEmptyString(value.target, `${field}.target`);
213
+ const relation = { type, target };
214
+ if (hasOwn(value, "label")) {
215
+ relation.label = String(value.label);
216
+ }
217
+ if (hasOwn(value, "description")) {
218
+ relation.description = String(value.description);
219
+ }
220
+ return relation;
221
+ }
222
+
223
+ function applyRelationPatch(existing, patch, field) {
224
+ if (!isPlainObject(patch)) {
225
+ throw new Error(`${field} must be an object containing add and/or remove arrays.`);
226
+ }
227
+ const remove = patch.remove === undefined ? [] : patch.remove;
228
+ if (!Array.isArray(remove)) {
229
+ throw new Error(`${field}.remove must be an array.`);
230
+ }
231
+ const removeKeys = new Set(
232
+ remove.map((relation, index) =>
233
+ relationKey(normalizeRelation(relation, `${field}.remove[${index}]`)),
234
+ ),
235
+ );
236
+ let result = (Array.isArray(existing) ? existing : []).filter(
237
+ (relation) => !removeKeys.has(relationKey(relation)),
238
+ );
239
+ const additions = patch.add === undefined ? [] : patch.add;
240
+ if (!Array.isArray(additions)) {
241
+ throw new Error(`${field}.add must be an array.`);
242
+ }
243
+ additions
244
+ .map((relation, index) => normalizeRelation(relation, `${field}.add[${index}]`))
245
+ .forEach((relation) => {
246
+ const key = relationKey(relation);
247
+ const existingIndex = result.findIndex((candidate) => relationKey(candidate) === key);
248
+ if (existingIndex === -1) {
249
+ result.push(relation);
250
+ } else if (!isDeepStrictEqual(result[existingIndex], relation)) {
251
+ result[existingIndex] = relation;
252
+ }
253
+ });
254
+ const seen = new Set();
255
+ return result.filter((relation) => {
256
+ const key = relationKey(relation);
257
+ if (seen.has(key)) {
258
+ return false;
259
+ }
260
+ seen.add(key);
261
+ return true;
262
+ });
263
+ }
264
+
265
+ function applyTagPatch(existing, patch, field) {
266
+ if (!isPlainObject(patch)) {
267
+ throw new Error(`${field} must be an object containing add and/or remove arrays.`);
268
+ }
269
+ const additions = uniqueStrings(patch.add, `${field}.add`);
270
+ const removals = new Set(uniqueStrings(patch.remove, `${field}.remove`));
271
+ const seen = new Set();
272
+ return (Array.isArray(existing) ? existing : [])
273
+ .filter((tag) => !removals.has(tag))
274
+ .concat(additions)
275
+ .filter((tag) => {
276
+ if (seen.has(tag)) {
277
+ return false;
278
+ }
279
+ seen.add(tag);
280
+ return true;
281
+ });
282
+ }
283
+
284
+ function validateMetadata(metadata, field) {
285
+ if (metadata === undefined) {
286
+ return {};
287
+ }
288
+ if (!isPlainObject(metadata)) {
289
+ throw new Error(`${field} must be an object.`);
290
+ }
291
+ Object.keys(metadata).forEach((key) => {
292
+ if (MANAGED_METADATA_KEYS.has(key)) {
293
+ throw new Error(`${field}.${key} is server-managed; use its dedicated field instead.`);
294
+ }
295
+ });
296
+ return Object.assign({}, metadata);
297
+ }
298
+
299
+ function validateRemovalKeys(keys, field) {
300
+ const values = uniqueStrings(keys, field);
301
+ values.forEach((key) => {
302
+ if (MANAGED_METADATA_KEYS.has(key)) {
303
+ throw new Error(`${field} cannot remove server-managed field: ${key}`);
304
+ }
305
+ });
306
+ return values;
307
+ }
308
+
309
+ function actorValue(value) {
310
+ const actor = nonEmptyString(value, "actor");
311
+ if (!validActor(actor)) {
312
+ throw new Error("actor must use human:<id>, process:<id>, or provider/model syntax.");
313
+ }
314
+ return actor;
315
+ }
316
+
317
+ // Characters git trims from both ends of an ident and refuses an ident made
318
+ // only of: whitespace, control characters and . , : ; < > " \ '.
319
+ const GIT_IDENT_CRUD = /^[\s\p{Cc}.,:;<>"\\']*$/u;
320
+ const AUTHOR_EMAIL = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/;
321
+
322
+ // Author data comes from a principal and must never fail or block a write:
323
+ // angle brackets and control characters are removed and surrounding
324
+ // whitespace trimmed; a name made only of what git refuses is dropped.
325
+ function authorName(value) {
326
+ if (typeof value !== "string") return null;
327
+ const text = value
328
+ .replace(/[<>\p{Cc}]/gu, "")
329
+ .trim()
330
+ .slice(0, 256)
331
+ .trim();
332
+ return text && !GIT_IDENT_CRUD.test(text) ? text : null;
333
+ }
334
+
335
+ // The same cleaning for an email, kept only when it is a plausible address.
336
+ function authorEmail(value) {
337
+ if (typeof value !== "string") return null;
338
+ const text = value.replace(/[<>\p{Cc}]/gu, "").trim();
339
+ return text.length <= 256 && AUTHOR_EMAIL.test(text) ? text : null;
340
+ }
341
+
342
+ // The git author a batch is committed for: the cleaned `name` and `email`,
343
+ // each kept only when usable (a missing one falls back to the repository's
344
+ // configured identity), or null when neither is.
345
+ function authorValue(value) {
346
+ if (!isPlainObject(value)) {
347
+ return null;
348
+ }
349
+ const author = {};
350
+ const name = authorName(value.name);
351
+ const email = authorEmail(value.email);
352
+ if (name) author.name = name;
353
+ if (email) author.email = email;
354
+ return Object.keys(author).length ? author : null;
355
+ }
356
+
357
+ function generatedOwners(document) {
358
+ const owners = [];
359
+ const generated = document && document.frontmatter && document.frontmatter.generated;
360
+ if (isPlainObject(generated) && typeof generated.by === "string") {
361
+ owners.push(generated.by);
362
+ }
363
+ const normalized = document && document.signals && document.signals.generated;
364
+ if (isPlainObject(normalized) && typeof normalized.by === "string") {
365
+ owners.push(normalized.by);
366
+ }
367
+ return owners;
368
+ }
369
+
370
+ function semanticConceptKey(type, title) {
371
+ return `${String(type || "")}\u0000${normalizeConceptTitle(title)}`;
372
+ }
373
+
374
+ function conceptIsManaged(doc, project) {
375
+ return (
376
+ conceptIsGeneratedFile(doc) ||
377
+ generatedOwners(doc).some((owner) => owner.startsWith("process:")) ||
378
+ isConfiguredGeneratorOutput(project, doc && doc.absolutePath)
379
+ );
380
+ }
381
+
382
+ function conceptConflictDetails(matches, project) {
383
+ const candidates = matches.slice(0, 5).map((doc) => conceptMatchSummary(doc));
384
+ const only = candidates.length === 1 ? candidates[0] : null;
385
+ const generated = matches.length === 1 && conceptIsManaged(matches[0], project);
386
+ const updateable = only && !generated && only.type !== "Attested Computation";
387
+ return {
388
+ reason: "same_type_title",
389
+ candidates,
390
+ omitted: Math.max(0, matches.length - candidates.length),
391
+ recommendedOperation: updateable ? "update" : generated ? "change_generator" : "review",
392
+ ...(updateable ? { retryWith: { op: "update", uri: only.uri } } : {}),
393
+ };
394
+ }
395
+
396
+ function staleUpdateDetails(index, uri, bundle, project) {
397
+ const recovery = recoverConceptLocator(index, uri, { bundle, limit: 5 });
398
+ const only = recovery.candidates.length === 1 ? recovery.candidates[0] : null;
399
+ const matched = only && resolveConcept(index, only.uri);
400
+ if (only && (conceptIsManaged(matched, project) || only.type === "Attested Computation")) {
401
+ delete recovery.retryWith;
402
+ recovery.recommendedOperation =
403
+ only.type === "Attested Computation" ? "review_computation_owner" : "change_generator";
404
+ } else if (recovery.retryWith) {
405
+ recovery.retryWith.op = "update";
406
+ recovery.recommendedOperation = "update";
407
+ }
408
+ return { recovery };
409
+ }
410
+
411
+ module.exports = {
412
+ MANAGED_METADATA_KEYS,
413
+ actorValue,
414
+ authorEmail,
415
+ authorName,
416
+ authorValue,
417
+ applyRelationPatch,
418
+ applySourcePatch,
419
+ applyTagPatch,
420
+ conceptConflictDetails,
421
+ conceptIsManaged,
422
+ nonEmptyString,
423
+ normalizeBody,
424
+ normalizeRelation,
425
+ normalizeSource,
426
+ relationKey,
427
+ relationParts,
428
+ semanticConceptKey,
429
+ sourceIdentity,
430
+ staleUpdateDetails,
431
+ uniqueStrings,
432
+ validateMetadata,
433
+ validateRemovalKeys,
434
+ };
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+
5
+ const {
6
+ AuthoringOperationalError,
7
+ MAX_EFFECT_ITEMS,
8
+ commandFailure,
9
+ commandOutput,
10
+ commandSucceeded,
11
+ sortedUnique,
12
+ } = require("./shared");
13
+
14
+ function activeGitFilterAttributes(git, repository, candidates) {
15
+ const tracked = git.runGit(repository, ["ls-files", "-z"], { readOnly: true });
16
+ if (!commandSucceeded(tracked)) {
17
+ throw new AuthoringOperationalError(
18
+ `Could not inspect tracked Git paths: ${commandFailure(tracked, "git ls-files failed")}`,
19
+ );
20
+ }
21
+ const paths = sortedUnique(
22
+ String(tracked.stdout || "")
23
+ .split("\0")
24
+ .filter(Boolean)
25
+ .concat(git.repositoryFiles({ repository }, candidates)),
26
+ );
27
+ const active = [];
28
+ for (let offset = 0; offset < paths.length; offset += 200) {
29
+ const chunk = paths.slice(offset, offset + 200);
30
+ const inspected = git.runGit(repository, ["check-attr", "-z", "--all", "--"].concat(chunk), {
31
+ readOnly: true,
32
+ });
33
+ if (!commandSucceeded(inspected)) {
34
+ throw new AuthoringOperationalError(
35
+ `Could not inspect Git filter attributes: ${commandFailure(inspected, "git check-attr failed")}`,
36
+ );
37
+ }
38
+ const values = String(inspected.stdout || "").split("\0");
39
+ for (let index = 0; index + 2 < values.length; index += 3) {
40
+ const attribute = values[index + 1];
41
+ if (attribute === "filter") {
42
+ active.push({ path: values[index], filter: values[index + 2] || "set" });
43
+ }
44
+ }
45
+ }
46
+ return active;
47
+ }
48
+
49
+ function unsupportedGitIndexFlags(git, repository) {
50
+ const inspected = git.runGit(repository, ["ls-files", "-v", "-z"], { readOnly: true });
51
+ if (!commandSucceeded(inspected)) {
52
+ throw new AuthoringOperationalError(
53
+ `Could not inspect Git index flags: ${commandFailure(inspected, "git ls-files failed")}`,
54
+ );
55
+ }
56
+ return String(inspected.stdout || "")
57
+ .split("\0")
58
+ .filter(Boolean)
59
+ .flatMap((entry) => {
60
+ const tag = entry[0] || "";
61
+ const flagged = tag === "S" || (/[a-z]/.test(tag) && tag === tag.toLowerCase());
62
+ if (!flagged) {
63
+ return [];
64
+ }
65
+ return [
66
+ {
67
+ path: entry.slice(2),
68
+ flag: tag === "S" ? "skip-worktree" : "assume-unchanged",
69
+ },
70
+ ];
71
+ });
72
+ }
73
+
74
+ function prepareGit(git, bundle, candidates) {
75
+ const preflight = {
76
+ enabled: git.gitCommit,
77
+ repository: null,
78
+ repositoryStatus: git.gitCommit ? "not_git_repository" : "not_inspected",
79
+ repositoryRoot: null,
80
+ headBefore: null,
81
+ headRef: null,
82
+ worktreeClean: null,
83
+ identityConfigured: null,
84
+ ready: !git.gitCommit,
85
+ diagnostics: [],
86
+ };
87
+ if (!git.gitCommit) {
88
+ return preflight;
89
+ }
90
+ const discovered = git.runGit(bundle.root, ["rev-parse", "--show-toplevel"], { readOnly: true });
91
+ if (discovered.error) {
92
+ if (git.gitCommit) {
93
+ throw new AuthoringOperationalError(
94
+ `Git executable is unavailable: ${discovered.error.message}`,
95
+ );
96
+ }
97
+ return Object.assign(preflight, {
98
+ repositoryStatus: "unavailable",
99
+ inspectionError: discovered.error.message,
100
+ });
101
+ }
102
+ if (discovered.status !== 0) {
103
+ const detail = commandOutput(discovered);
104
+ if (/not a git repository/i.test(detail)) {
105
+ preflight.ready = true;
106
+ return preflight;
107
+ }
108
+ if (git.gitCommit) {
109
+ throw new AuthoringOperationalError(
110
+ `Could not inspect Git repository: ${detail || `git exited ${discovered.status}`}`,
111
+ );
112
+ }
113
+ return Object.assign(preflight, {
114
+ repositoryStatus: "inspection_failed",
115
+ inspectionError: detail || `git exited ${discovered.status}`,
116
+ });
117
+ }
118
+ const repository = path.resolve(String(discovered.stdout || "").trim());
119
+ preflight.repository = repository;
120
+ preflight.repositoryRoot = repository;
121
+ preflight.repositoryStatus = "detected";
122
+ const symbolicHead = git.runGit(repository, ["symbolic-ref", "-q", "HEAD"], { readOnly: true });
123
+ if (symbolicHead.error || (symbolicHead.status !== 0 && symbolicHead.status !== 1)) {
124
+ throw new AuthoringOperationalError(
125
+ `Could not inspect the checked-out Git ref: ${commandFailure(symbolicHead, "git symbolic-ref failed")}`,
126
+ );
127
+ }
128
+ const headRef = commandSucceeded(symbolicHead) ? String(symbolicHead.stdout || "").trim() : null;
129
+ preflight.headRef = headRef;
130
+ const headBefore = git.readGitValue(repository, ["rev-parse", "--verify", headRef || "HEAD"], {
131
+ readOnly: true,
132
+ });
133
+ preflight.headBefore = headBefore;
134
+ const missingIdentity = [];
135
+ for (const key of ["user.name", "user.email"]) {
136
+ const configured = git.runGit(repository, ["config", "--get", key], { readOnly: true });
137
+ if (configured && configured.error) {
138
+ throw new AuthoringOperationalError(
139
+ `Could not inspect Git ${key}: ${configured.error.message}`,
140
+ );
141
+ }
142
+ if (configured && configured.status !== 0 && configured.status !== 1) {
143
+ throw new AuthoringOperationalError(
144
+ `Could not inspect Git ${key}: ${commandFailure(configured, `git config exited ${configured.status}`)}`,
145
+ );
146
+ }
147
+ if (!commandSucceeded(configured) || !String(configured.stdout || "").trim()) {
148
+ missingIdentity.push(key);
149
+ }
150
+ }
151
+ preflight.identityConfigured = missingIdentity.length === 0;
152
+ const unsupportedIndexFlags = unsupportedGitIndexFlags(git, repository);
153
+ preflight.unsupportedIndexFlags = unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS);
154
+ const activeFilters = activeGitFilterAttributes(git, repository, candidates);
155
+ preflight.activeFilterAttributes = activeFilters.slice(0, MAX_EFFECT_ITEMS);
156
+ if (!activeFilters.length && !unsupportedIndexFlags.length) {
157
+ const status = git.runGit(repository, ["status", "--porcelain=v1", "--untracked-files=all"], {
158
+ readOnly: true,
159
+ });
160
+ if (!commandSucceeded(status)) {
161
+ throw new AuthoringOperationalError(
162
+ `Could not inspect Git status: ${commandFailure(status, "git status failed")}`,
163
+ );
164
+ }
165
+ preflight.worktreeClean = !String(status.stdout || "").trim();
166
+ }
167
+ preflight.ready =
168
+ !git.gitCommit ||
169
+ Boolean(
170
+ headBefore &&
171
+ headRef &&
172
+ preflight.worktreeClean &&
173
+ preflight.identityConfigured &&
174
+ !activeFilters.length &&
175
+ !unsupportedIndexFlags.length,
176
+ );
177
+ if (git.gitCommit && !headBefore) {
178
+ preflight.diagnostics.push({
179
+ code: "git_head_missing",
180
+ message: "Git repository must have an existing HEAD before an automatic OKF commit.",
181
+ });
182
+ }
183
+ if (git.gitCommit && headBefore && !headRef) {
184
+ preflight.diagnostics.push({
185
+ code: "git_detached_head_unsupported",
186
+ message:
187
+ "Automatic OKF commits require a checked-out symbolic branch; detached HEAD is not supported.",
188
+ });
189
+ }
190
+ if (git.gitCommit && preflight.worktreeClean === false) {
191
+ preflight.diagnostics.push({
192
+ code: "git_worktree_dirty",
193
+ message: "Git worktree must be completely clean before an automatic OKF commit.",
194
+ });
195
+ }
196
+ if (git.gitCommit && missingIdentity.length) {
197
+ preflight.diagnostics.push({
198
+ code: "git_identity_missing",
199
+ message: `Git ${missingIdentity[0]} must be configured before an automatic OKF commit.`,
200
+ });
201
+ }
202
+ if (git.gitCommit && activeFilters.length) {
203
+ preflight.diagnostics.push({
204
+ code: "git_filter_attribute_unsupported",
205
+ message:
206
+ "Automatic OKF commits reject active Git filter attributes so validation cannot execute repository-configured filters and committed bytes remain exact.",
207
+ paths: activeFilters.slice(0, MAX_EFFECT_ITEMS),
208
+ omitted: Math.max(0, activeFilters.length - MAX_EFFECT_ITEMS),
209
+ });
210
+ }
211
+ if (git.gitCommit && unsupportedIndexFlags.length) {
212
+ preflight.diagnostics.push({
213
+ code: "git_index_flag_unsupported",
214
+ message:
215
+ "Automatic OKF commits reject assume-unchanged and skip-worktree Git index flags because they can hide user changes from clean-worktree inspection.",
216
+ paths: unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS),
217
+ omitted: Math.max(0, unsupportedIndexFlags.length - MAX_EFFECT_ITEMS),
218
+ });
219
+ }
220
+ return preflight;
221
+ }
222
+
223
+ module.exports = {
224
+ prepareGit,
225
+ };