@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,112 @@
1
+ "use strict";
2
+
3
+ // Concept path rules and the type/title path suggestion, shared by the
4
+ // proposal and live authoring services (split from src/authoring.js, plan
5
+ // Q-1). src/authoring.js re-exports every name for compatibility.
6
+
7
+ const path = require("node:path");
8
+ const { findConceptMatches } = require("../indexer");
9
+ const { normalizeSlashes } = require("../parser");
10
+
11
+ function slug(value, fallback) {
12
+ const text = String(value || fallback || "concept")
13
+ .trim()
14
+ .toLowerCase();
15
+ return text.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || String(fallback || "concept");
16
+ }
17
+
18
+ function hasControlCharacter(text) {
19
+ for (const character of text) {
20
+ const code = character.charCodeAt(0);
21
+ if (code < 0x20 || code === 0x7f) return true;
22
+ }
23
+ return false;
24
+ }
25
+
26
+ function normalizeConceptPath(value) {
27
+ const raw = normalizeSlashes(String(value || "").trim());
28
+ if (!raw) {
29
+ throw new Error("Concept path is required.");
30
+ }
31
+ if (raw.startsWith("/") || /^[A-Za-z]:\//.test(raw) || hasControlCharacter(raw)) {
32
+ throw new Error("Concept path must be a safe relative path.");
33
+ }
34
+ const rawParts = raw.split("/");
35
+ if (rawParts.some((part) => !part || part === "." || part === ".." || part.startsWith("."))) {
36
+ throw new Error(
37
+ "Concept path must be a safe relative path without empty, hidden, dot, or parent segments.",
38
+ );
39
+ }
40
+ if (rawParts.slice(0, -1).some((part) => part.toLowerCase().endsWith(".md"))) {
41
+ throw new Error("Concept path cannot place a Markdown file inside another Markdown path.");
42
+ }
43
+ const normalized = path.posix.normalize(raw);
44
+ if (!normalized || normalized === "." || normalized.startsWith("../") || normalized === "..") {
45
+ throw new Error("Concept path must stay inside the bundle.");
46
+ }
47
+ if (normalized.split("/").some((part) => !part || part === "." || part === "..")) {
48
+ throw new Error("Concept path contains an unsafe segment.");
49
+ }
50
+ if (!normalized.toLowerCase().endsWith(".md")) {
51
+ throw new Error("Concept path must end with .md.");
52
+ }
53
+ const base = path.posix.basename(normalized).toLowerCase();
54
+ if (base === "index.md" || base === "log.md") {
55
+ throw new Error("Concept path cannot be a reserved index.md or log.md file.");
56
+ }
57
+ return normalized;
58
+ }
59
+
60
+ function deriveConceptPathSuggestion(index, bundle, input) {
61
+ const rawPrefix = input?.prefix ? normalizeSlashes(String(input.prefix).trim()) : "";
62
+ if (rawPrefix.startsWith("/") || /^[A-Za-z]:\//.test(rawPrefix)) {
63
+ throw new Error("Path prefix must be a safe relative path inside the bundle.");
64
+ }
65
+ const prefix = rawPrefix.replace(/\/+$/g, "");
66
+ if (prefix) {
67
+ normalizeConceptPath(`${prefix}/placeholder.md`);
68
+ }
69
+ const type = String(input?.type || "").trim();
70
+ const typePart = type === "Attested Computation" ? "computations" : slug(type, "concept");
71
+ const titlePart = slug(input?.title, typePart);
72
+ let parent = prefix ? `${prefix}/${typePart}` : typePart;
73
+ let strategy = prefix ? "explicit_prefix" : "type_slug";
74
+ let evidence = { matchingConcepts: 0, dominantDirectoryCount: 0, dominantDirectoryRatio: 0 };
75
+
76
+ if (type !== "Attested Computation" && index) {
77
+ const matching = findConceptMatches(index, {
78
+ bundle: bundle.id,
79
+ type,
80
+ pathPrefix: prefix,
81
+ });
82
+ const counts = new Map();
83
+ matching.forEach((document) => {
84
+ const directory = path.posix.dirname(document.path);
85
+ const normalizedDirectory = directory === "." ? "" : directory;
86
+ counts.set(normalizedDirectory, (counts.get(normalizedDirectory) || 0) + 1);
87
+ });
88
+ const dominant = Array.from(counts.entries()).sort(
89
+ (left, right) => right[1] - left[1] || left[0].localeCompare(right[0]),
90
+ )[0];
91
+ const dominantCount = dominant ? dominant[1] : 0;
92
+ const ratio = matching.length ? dominantCount / matching.length : 0;
93
+ evidence = {
94
+ matchingConcepts: matching.length,
95
+ dominantDirectoryCount: dominantCount,
96
+ dominantDirectoryRatio: Number(ratio.toFixed(3)),
97
+ };
98
+ if (dominant && dominantCount >= 2 && ratio >= 0.6) {
99
+ parent = dominant[0];
100
+ strategy = "dominant_same_type_directory";
101
+ evidence.dominantDirectory = dominant[0] || ".";
102
+ }
103
+ }
104
+
105
+ return {
106
+ path: normalizeConceptPath([parent, `${titlePart}.md`].filter(Boolean).join("/")),
107
+ strategy,
108
+ evidence,
109
+ };
110
+ }
111
+
112
+ module.exports = { deriveConceptPathSuggestion, normalizeConceptPath, slug };
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+
3
+ const { normalizeSlashes, splitFrontmatter } = require("../parser");
4
+ const { evaluateWritePolicy, isWritePolicy, parseWritePolicy } = require("../policy/write-policy");
5
+ const { renderConceptMarkdown } = require("./render");
6
+ const { revisionFor } = require("./shared");
7
+
8
+ // Where the live authoring service meets the write policy (plan W-1, W-2).
9
+ // The policy is trusted configuration: a host option (the parsed policy a
10
+ // --policy file loads, or the raw mapping) wins, else the project's
11
+ // `writePolicy` from okf.project.yaml; with neither, every write by the
12
+ // configured actor is allowed as before and receipts are unchanged.
13
+ function resolveWritePolicy(config, store) {
14
+ if (config && config.writePolicy !== undefined && config.writePolicy !== null) {
15
+ if (isWritePolicy(config.writePolicy)) {
16
+ return config.writePolicy;
17
+ }
18
+ const parsed = parseWritePolicy(config.writePolicy);
19
+ if (parsed.errors.length || !parsed.policy) {
20
+ const summary = parsed.errors.map((entry) => `${entry.field}: ${entry.message}`).join("; ");
21
+ const error = new Error(`Invalid write policy: ${summary || "no policy mapping"}`);
22
+ error.code = "invalid_write_policy";
23
+ error.details = parsed.errors;
24
+ throw error;
25
+ }
26
+ return parsed.policy;
27
+ }
28
+ const project = store?.project;
29
+ return project && isWritePolicy(project.writePolicy) ? project.writePolicy : null;
30
+ }
31
+
32
+ function describeCandidate(candidate) {
33
+ return {
34
+ op: candidate.op,
35
+ bundleId: candidate.bundle,
36
+ path: candidate.path,
37
+ type: candidate.frontmatter.type,
38
+ frontmatter: candidate.frontmatter,
39
+ uri: candidate.uri,
40
+ };
41
+ }
42
+
43
+ // A created concept that set no status takes the rule's default before
44
+ // validation. Frontmatter, rendered bytes and candidate revision change
45
+ // together, so what is validated is what is written; the status sits ahead
46
+ // of the server-managed `generated` stamp like any other authored field.
47
+ function applyDefaultStatus(candidate, status) {
48
+ const { generated, ...rest } = candidate.frontmatter;
49
+ candidate.frontmatter = Object.assign(
50
+ rest,
51
+ { status },
52
+ generated === undefined ? {} : { generated },
53
+ );
54
+ candidate.markdown = renderConceptMarkdown({
55
+ path: candidate.path,
56
+ frontmatter: candidate.frontmatter,
57
+ body: candidate.body,
58
+ });
59
+ candidate.publishedRevision = revisionFor(candidate.markdown);
60
+ }
61
+
62
+ // Evaluates the planned batch. Returns null without a policy, otherwise
63
+ // { violations, rules } where rules[i] names the rule that decided
64
+ // candidates[i] (null when the default effect did).
65
+ function enforceWritePolicy(policy, context) {
66
+ if (!policy) {
67
+ return null;
68
+ }
69
+ const { actor, candidates, index } = context;
70
+ const evaluation = evaluateWritePolicy(policy, {
71
+ actor,
72
+ index,
73
+ changes: candidates.map(describeCandidate),
74
+ });
75
+ evaluation.decisions.forEach((decision, position) => {
76
+ if (decision?.defaultStatus && candidates[position].op === "create") {
77
+ applyDefaultStatus(candidates[position], decision.defaultStatus);
78
+ }
79
+ });
80
+ return {
81
+ violations: evaluation.violations,
82
+ rules: evaluation.decisions.map((decision) => (decision ? decision.rule : null)),
83
+ };
84
+ }
85
+
86
+ // Messages name rules, reasons, paths and URIs, never catalog text (B-6).
87
+ function violationMessage(violation) {
88
+ const subject = violation.uri || violation.path || "the batch";
89
+ const rule =
90
+ violation.rule === null || violation.rule === undefined
91
+ ? "default effect"
92
+ : `rule ${violation.rule}`;
93
+ if (violation.reason === "missing_required_field") {
94
+ return `Write policy ${rule} requires frontmatter field ${violation.field} on ${subject}.`;
95
+ }
96
+ if (violation.reason === "batch_too_large") {
97
+ return `Write policy ${rule} allows at most ${violation.limit} concepts per batch; this batch has ${violation.count}.`;
98
+ }
99
+ return `Write policy ${rule} denies this write (${violation.reason}): ${subject}`;
100
+ }
101
+
102
+ function policyDiagnostics(violations) {
103
+ return violations.map((violation) =>
104
+ Object.assign({}, violation, {
105
+ severity: "error",
106
+ layer: "policy",
107
+ message: violationMessage(violation),
108
+ }),
109
+ );
110
+ }
111
+
112
+ // Violations join the batch's validation result as policy-layer diagnostics:
113
+ // they invalidate the batch the way a graph error does, so valid,
114
+ // readyToApply, status and the apply refusal follow one code path.
115
+ function withPolicyViolations(validation, policy) {
116
+ if (!policy?.violations.length) {
117
+ return validation;
118
+ }
119
+ const diagnostics = policyDiagnostics(policy.violations);
120
+ return Object.assign({}, validation, {
121
+ valid: false,
122
+ validForProject: false,
123
+ diagnostics: validation.diagnostics.concat(diagnostics),
124
+ errors: validation.errors.concat(diagnostics),
125
+ });
126
+ }
127
+
128
+ // Proposals are writes too (plan W-1): a proposal is judged when it is
129
+ // created, against the proposing actor, and again when it is accepted,
130
+ // against the actor recorded on it (else the accepting one). Without any
131
+ // actor the write is judged as the actor "unknown" (UNKNOWN_ACTOR), which
132
+ // is how proposals stored before a policy or an actor existed are accepted.
133
+ // Returns null without a policy, else { violations, defaultStatus }.
134
+ function evaluateProposal(policy, actor, proposal) {
135
+ if (!policy) {
136
+ return null;
137
+ }
138
+ const frontmatter =
139
+ proposal.frontmatter && typeof proposal.frontmatter === "object" ? proposal.frontmatter : {};
140
+ const evaluation = evaluateWritePolicy(policy, {
141
+ actor: actor || null,
142
+ changes: [
143
+ {
144
+ op: proposal.op === "create" || proposal.op === "create_computation" ? "create" : "update",
145
+ bundleId: proposal.bundle,
146
+ path: proposal.path,
147
+ type: typeof frontmatter.type === "string" ? frontmatter.type : null,
148
+ frontmatter,
149
+ uri: proposal.uri || proposal.targetUri || null,
150
+ },
151
+ ],
152
+ });
153
+ return {
154
+ violations: evaluation.violations,
155
+ defaultStatus: evaluation.decisions[0]?.defaultStatus || null,
156
+ };
157
+ }
158
+
159
+ // A proposal validation refused by the policy: invalid, with the
160
+ // violations as policy-layer errors beside the structured list.
161
+ function refusedProposal(result, validation, violations) {
162
+ const errors = policyDiagnostics(violations);
163
+ return Object.assign(result, {
164
+ validation: Object.assign({}, validation, {
165
+ valid: false,
166
+ errors: (validation.errors || []).concat(errors),
167
+ }),
168
+ policyViolations: violations,
169
+ });
170
+ }
171
+
172
+ // Producers publish under process:<name> and are exempt unless the policy
173
+ // sets applyToProducers. Created and updated concept files are judged as one
174
+ // batch; unchanged and deleted paths, and the reserved index.md and log.md
175
+ // documents, are not writes of a concept. Returns null when the policy does
176
+ // not apply, else the violations.
177
+ function evaluateProducerFiles(policy, instance, files, changes) {
178
+ if (!policy?.applyToProducers) {
179
+ return null;
180
+ }
181
+ const created = new Set(changes.create);
182
+ const written = new Set(changes.create.concat(changes.update));
183
+ const described = files
184
+ .filter((file) => written.has(file.path) && /\.md$/i.test(file.path))
185
+ .filter((file) => !/(^|\/)(index|log)\.md$/i.test(normalizeSlashes(file.path)))
186
+ .map((file) => {
187
+ let frontmatter = {};
188
+ try {
189
+ frontmatter = splitFrontmatter(file.content).frontmatter || {};
190
+ } catch {
191
+ // Unparseable output fails producer validation on its own.
192
+ }
193
+ const relative = normalizeSlashes(file.path);
194
+ return {
195
+ op: created.has(file.path) ? "create" : "update",
196
+ bundleId: instance.bundle,
197
+ path: relative,
198
+ type: typeof frontmatter.type === "string" ? frontmatter.type : null,
199
+ frontmatter,
200
+ uri: `okf://${instance.bundle}/${relative.replace(/\.md$/i, "")}`,
201
+ };
202
+ });
203
+ // Producer bytes are digest-tracked by the publication manifest, so the
204
+ // host never stamps a default status into them: a rule's defaultStatus
205
+ // does not apply and a required status must be in the produced file.
206
+ return evaluateWritePolicy(policy, {
207
+ actor: `process:${instance.name}`,
208
+ changes: described,
209
+ applyDefaultStatus: false,
210
+ }).violations;
211
+ }
212
+
213
+ module.exports = {
214
+ enforceWritePolicy,
215
+ evaluateProducerFiles,
216
+ evaluateProposal,
217
+ policyDiagnostics,
218
+ refusedProposal,
219
+ resolveWritePolicy,
220
+ withPolicyViolations,
221
+ };
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+
3
+ const { validActor } = require("../v02");
4
+ const { evaluateProposal, policyDiagnostics, refusedProposal } = require("./policy-hook");
5
+
6
+ // The write policy applied to the proposal flow of ConceptAuthoringService
7
+ // (plan W-1): every kind of proposal is judged when it would be stored,
8
+ // against the proposing actor, and again before acceptance writes it,
9
+ // against the actor recorded on it, else the accepting one. Kept out of
10
+ // src/authoring.js, which is held under a shrink-only size ratchet (Q-1).
11
+
12
+ // Validates a proposal about to be stored and applies the policy to it:
13
+ // { refused } when invalid or denied; otherwise the request and its
14
+ // validation, re-validated once with the default status a matching rule
15
+ // stamps on a create that set none.
16
+ function checkProposal(service, op, input, validate) {
17
+ const validation = validate(input);
18
+ if (!validation.valid) {
19
+ return { refused: { created: false, validation } };
20
+ }
21
+ const policy = evaluateProposal(service.writePolicy, service.actor, {
22
+ op,
23
+ bundle: validation.bundle,
24
+ path: validation.path,
25
+ uri: validation.uri,
26
+ frontmatter: input.frontmatter,
27
+ });
28
+ if (policy?.violations.length) {
29
+ return { refused: refusedProposal({ created: false }, validation, policy.violations) };
30
+ }
31
+ if (!policy?.defaultStatus) {
32
+ return { request: input, validation };
33
+ }
34
+ const request = Object.assign({}, input, {
35
+ frontmatter: Object.assign({}, input.frontmatter, { status: policy.defaultStatus }),
36
+ });
37
+ const stamped = validate(request);
38
+ return stamped.valid
39
+ ? { request, validation: stamped }
40
+ : { refused: { created: false, validation: stamped } };
41
+ }
42
+
43
+ // An update proposal's refusal, or null when the policy allows it.
44
+ function refuseUpdate(service, validation, existing, frontmatter) {
45
+ const policy = evaluateProposal(service.writePolicy, service.actor, {
46
+ op: "update",
47
+ bundle: validation.bundle,
48
+ path: validation.path,
49
+ uri: existing.uri,
50
+ frontmatter,
51
+ });
52
+ return policy?.violations.length
53
+ ? refusedProposal({ created: false, op: "update" }, validation, policy.violations)
54
+ : null;
55
+ }
56
+
57
+ // Every proposal a migration would store, judged before any is stored: the
58
+ // child updates and the index.md version declaration. Returns the refusal,
59
+ // or null when the policy allows them all.
60
+ function refuseMigration(service, bundleId, plan) {
61
+ if (!service.writePolicy) {
62
+ return null;
63
+ }
64
+ const proposals = plan.conceptProposals.map((step) => {
65
+ const existing = service.resolveConcept(step.target.uri);
66
+ return {
67
+ op: "update",
68
+ bundle: existing.bundle,
69
+ path: existing.path,
70
+ uri: existing.uri,
71
+ frontmatter: Object.assign({}, existing.frontmatter, step.arguments.frontmatter),
72
+ };
73
+ });
74
+ if (plan.versionDeclaration) {
75
+ proposals.push({
76
+ op: "migration_index",
77
+ bundle: bundleId,
78
+ path: "index.md",
79
+ frontmatter: { okf_version: "0.2" },
80
+ });
81
+ }
82
+ const violations = proposals.flatMap(
83
+ (proposal) => evaluateProposal(service.writePolicy, service.actor, proposal).violations,
84
+ );
85
+ return violations.length
86
+ ? { created: false, plan, policyViolations: violations, errors: policyDiagnostics(violations) }
87
+ : null;
88
+ }
89
+
90
+ // Acceptance re-validates the stored frontmatter and publishes the bytes that
91
+ // validation renders. A create the policy stamps with a default status (one
92
+ // stored without it, or before the policy existed) is accepted through this
93
+ // delegate, so the published concept carries the status it was judged with.
94
+ // The stored proposal is not rewritten outside the store's proposal lock.
95
+ function withDefaultStatus(service, status) {
96
+ const stamp = (candidate) =>
97
+ Object.assign({}, candidate, {
98
+ frontmatter: Object.assign({}, candidate.frontmatter, { status }),
99
+ });
100
+ return Object.create(service, {
101
+ validateConcept: {
102
+ value: (candidate, options) => service.validateConcept(stamp(candidate), options),
103
+ },
104
+ validateAttestedComputation: {
105
+ value: (candidate, options) => service.validateAttestedComputation(stamp(candidate), options),
106
+ },
107
+ });
108
+ }
109
+
110
+ // The policy's verdict before acceptance: { refused } with the violations,
111
+ // or { acceptor }, the service (or its status-stamping delegate) the store
112
+ // accepts through. A proposal no longer "proposed" is left to the store,
113
+ // which reports its status.
114
+ async function prepareAcceptance(service, proposalId) {
115
+ if (!service.writePolicy) {
116
+ return { acceptor: service };
117
+ }
118
+ const proposal = await service.store.getProposal(proposalId);
119
+ const policy =
120
+ proposal.status === "proposed"
121
+ ? evaluateProposal(service.writePolicy, proposal.proposedBy || service.actor, proposal)
122
+ : null;
123
+ if (policy?.violations.length) {
124
+ return {
125
+ refused: {
126
+ accepted: false,
127
+ proposal,
128
+ policyViolations: policy.violations,
129
+ errors: policyDiagnostics(policy.violations),
130
+ },
131
+ };
132
+ }
133
+ return {
134
+ acceptor: policy?.defaultStatus ? withDefaultStatus(service, policy.defaultStatus) : service,
135
+ };
136
+ }
137
+
138
+ // The service a call made for `actor` (a per-request principal) proposes,
139
+ // accepts and rejects through: a delegate whose actor is the call's, so
140
+ // `proposedBy` and every policy verdict name it, sharing the store, the
141
+ // write policy and every method with the configured service, which keeps no
142
+ // other per-call state. The configured service itself when the actors agree.
143
+ function proposalServiceFor(service, actor) {
144
+ if (actor === undefined || actor === null || actor === service.actor) {
145
+ return service;
146
+ }
147
+ if (!validActor(actor)) {
148
+ throw new Error("actor must use human:<id>, process:<id>, or provider/model syntax.");
149
+ }
150
+ return Object.create(service, { actor: { value: actor, enumerable: true } });
151
+ }
152
+
153
+ module.exports = {
154
+ checkProposal,
155
+ prepareAcceptance,
156
+ proposalServiceFor,
157
+ refuseMigration,
158
+ refuseUpdate,
159
+ };