create-freeholder 0.2.0-beta.4 → 0.2.0-beta.6

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 (158) hide show
  1. package/dist/template/.changeset/blog-playground-content.md +4 -0
  2. package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
  3. package/dist/template/.changeset/managed-preview-assistant.md +4 -0
  4. package/dist/template/.changeset/native-linux-install.md +6 -0
  5. package/dist/template/.changeset/public-beta-5.md +4 -0
  6. package/dist/template/.changeset/public-beta-6.md +4 -0
  7. package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
  8. package/dist/template/.github/workflows/release-tarballs.yml +117 -0
  9. package/dist/template/AGENTS.md +15 -2
  10. package/dist/template/Dockerfile +3 -0
  11. package/dist/template/MASTER.md +114 -11
  12. package/dist/template/README.md +1 -1
  13. package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
  14. package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
  15. package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
  16. package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
  17. package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
  18. package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
  19. package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
  20. package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
  21. package/dist/template/app/(admin)/assistant-actions.ts +13 -6
  22. package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
  23. package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
  24. package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
  25. package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
  26. package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
  27. package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
  28. package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
  29. package/dist/template/db/migrations/meta/_journal.json +14 -0
  30. package/dist/template/deploy/README.md +26 -9
  31. package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
  32. package/dist/template/deploy/docker-selfhost/.env.example +11 -1
  33. package/dist/template/deploy/docker-selfhost/README.md +79 -50
  34. package/dist/template/deploy/docker-selfhost/infra/backup.sh +81 -0
  35. package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +37 -1
  36. package/dist/template/deploy/docker-selfhost/infra/compose.yml +37 -1
  37. package/dist/template/deploy/docker-selfhost/migrate.md +8 -5
  38. package/dist/template/deploy/docker-selfhost/recipe.yaml +9 -10
  39. package/dist/template/deploy/docker-selfhost/selfhost.sh +206 -0
  40. package/dist/template/deploy/docker-selfhost/verify.md +11 -4
  41. package/dist/template/deploy/f-criteria-matrix.md +89 -0
  42. package/dist/template/deploy/linux/.env.example +28 -0
  43. package/dist/template/deploy/linux/README.md +181 -0
  44. package/dist/template/deploy/linux/freeholder +655 -0
  45. package/dist/template/deploy/linux/install.sh +173 -0
  46. package/dist/template/deploy/linux/migrate.md +17 -0
  47. package/dist/template/deploy/linux/recipe.yaml +50 -0
  48. package/dist/template/deploy/linux/share/Caddyfile.template +19 -0
  49. package/dist/template/deploy/linux/share/systemd/freeholder-backup.service +13 -0
  50. package/dist/template/deploy/linux/share/systemd/freeholder-backup.timer +12 -0
  51. package/dist/template/deploy/linux/share/systemd/freeholder.service +41 -0
  52. package/dist/template/deploy/linux/verify.md +22 -0
  53. package/dist/template/deploy/managed-preview-assistant.md +99 -0
  54. package/dist/template/eslint.config.mjs +3 -1
  55. package/dist/template/gitignore.template +1 -0
  56. package/dist/template/locales/ar.json +85 -6
  57. package/dist/template/locales/en.json +83 -4
  58. package/dist/template/locales/es.json +83 -4
  59. package/dist/template/locales/fr.json +85 -6
  60. package/dist/template/next.config.ts +2 -0
  61. package/dist/template/package.json +3 -2
  62. package/dist/template/packages/cli/package.json +1 -1
  63. package/dist/template/packages/create-freeholder/package.json +1 -1
  64. package/dist/template/packages/freeholder-app/package.json +1 -1
  65. package/dist/template/packages/mobile-app/package.json +1 -1
  66. package/dist/template/packages/plugin-kit/package.json +1 -1
  67. package/dist/template/packages/sdk/package.json +1 -1
  68. package/dist/template/packages/sdk/src/generated.ts +177 -9
  69. package/dist/template/packages/sdk/src/version.ts +1 -1
  70. package/dist/template/packages/templates/package.json +1 -1
  71. package/dist/template/proxy.ts +18 -1
  72. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
  73. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
  74. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
  75. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
  76. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
  77. package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
  78. package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
  79. package/dist/template/scripts/build-release.d.mts +4 -0
  80. package/dist/template/scripts/build-release.mjs +171 -0
  81. package/dist/template/scripts/launch-prepare.mjs +6 -3
  82. package/dist/template/scripts/license-headers.mjs +3 -0
  83. package/dist/template/scripts/recipe-matrix.sh +22 -7
  84. package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
  85. package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
  86. package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
  87. package/dist/template/src/adapters/ai/types.ts +5 -0
  88. package/dist/template/src/adapters/paradise/assistant.ts +37 -0
  89. package/dist/template/src/adapters/paradise/http.ts +4 -3
  90. package/dist/template/src/adapters/storage/local-mode.ts +54 -0
  91. package/dist/template/src/adapters/storage/local.ts +53 -26
  92. package/dist/template/src/core/contract/json-schema.ts +8 -0
  93. package/dist/template/src/core/demo/playground-inserts.ts +29 -0
  94. package/dist/template/src/core/demo/playground-policy.ts +9 -0
  95. package/dist/template/src/core/doctor/index.ts +19 -10
  96. package/dist/template/src/core/env.ts +8 -1
  97. package/dist/template/src/core/http/csp.ts +10 -2
  98. package/dist/template/src/core/http/csrf-client.ts +10 -0
  99. package/dist/template/src/core/import/service.ts +217 -12
  100. package/dist/template/src/core/import/wordpress.ts +80 -15
  101. package/dist/template/src/core/notifications/service.ts +1 -0
  102. package/dist/template/src/core/retention/registry.ts +2 -0
  103. package/dist/template/src/core/search/registry.ts +2 -0
  104. package/dist/template/src/core/seo/feeds.ts +2 -0
  105. package/dist/template/src/core/seo/jsonld.ts +46 -2
  106. package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
  107. package/dist/template/src/core/seo/meta.ts +10 -7
  108. package/dist/template/src/core/seo/service.ts +14 -1
  109. package/dist/template/src/core/update/preflight.ts +3 -2
  110. package/dist/template/src/core/update/release-declaration.json +1 -1
  111. package/dist/template/src/core/update/service.ts +7 -17
  112. package/dist/template/src/modules/assistant/contract.ts +1 -1
  113. package/dist/template/src/modules/assistant/limits.ts +3 -0
  114. package/dist/template/src/modules/assistant/preview.ts +124 -0
  115. package/dist/template/src/modules/assistant/provider.ts +7 -0
  116. package/dist/template/src/modules/assistant/service.ts +21 -5
  117. package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
  118. package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
  119. package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
  120. package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
  121. package/dist/template/src/modules/cms/blog-comments.ts +111 -0
  122. package/dist/template/src/modules/cms/blog-schema.ts +146 -0
  123. package/dist/template/src/modules/cms/blog-service.ts +999 -0
  124. package/dist/template/src/modules/cms/blog.tsx +245 -25
  125. package/dist/template/src/modules/cms/manifest.ts +7 -1
  126. package/dist/template/src/modules/cms/read.ts +18 -0
  127. package/dist/template/src/modules/cms/service.ts +22 -4
  128. package/dist/template/src/modules/cms/tables.ts +2 -0
  129. package/dist/template/src/modules/seed/launch.ts +31 -3
  130. package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
  131. package/dist/template/tests/core/agent-launch.test.ts +7 -2
  132. package/dist/template/tests/core/analytics-consent.test.ts +1 -1
  133. package/dist/template/tests/core/blog-playground.test.ts +106 -0
  134. package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
  135. package/dist/template/tests/core/client-readiness-security.test.ts +3 -1
  136. package/dist/template/tests/core/csp.test.ts +1 -1
  137. package/dist/template/tests/core/deploy-recipe.test.ts +54 -4
  138. package/dist/template/tests/core/internal-services.test.ts +4 -0
  139. package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
  140. package/dist/template/tests/core/linux-install.test.ts +169 -0
  141. package/dist/template/tests/core/local-storage-mode.test.ts +29 -0
  142. package/dist/template/tests/core/locale-routing.test.ts +1 -1
  143. package/dist/template/tests/core/playground-cache.test.ts +1 -1
  144. package/dist/template/tests/core/playground.test.ts +3 -3
  145. package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
  146. package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
  147. package/dist/template/tests/core/private-preview.test.ts +1 -1
  148. package/dist/template/tests/core/proxy-locale.test.ts +1 -1
  149. package/dist/template/tests/core/sdk-schema.test.ts +20 -0
  150. package/dist/template/tests/core/seo.test.ts +1 -1
  151. package/dist/template/tests/core/site-chat-client.test.ts +50 -0
  152. package/dist/template/tests/core/storage.test.ts +38 -2
  153. package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
  154. package/dist/template/tests/core/wordpress-import.test.ts +25 -12
  155. package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
  156. package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
  157. package/dist/template-manifest.json +490 -175
  158. package/package.json +1 -1
@@ -156,6 +156,8 @@ export const RETENTION_TABLE_OPT_OUTS: Record<string, string> = {
156
156
  rental_agreements: "Hire documents; contractual hold.",
157
157
  time_entries: "Time against a project; business work record.",
158
158
  reviews: "Published review evidence, not a notes-style TTL.",
159
+ blog_reader_comments:
160
+ "Published discussion and moderation history belongs to its page; page purge and cms.readerComments privacy erasure govern it, not a notes-style TTL.",
159
161
  review_requests: "Solicitation workflow.",
160
162
  contact_stages: "Join table of a contact to a pipeline stage.",
161
163
  advertisers: "Ad-account counterparties.",
@@ -129,6 +129,8 @@ export const SEARCH_TABLE_OPT_OUTS: Record<string, string> = {
129
129
  rental_agreements: "Find from hire; the agreement is the document, not a search hit.",
130
130
  time_entries: "Time against a project; find the project.",
131
131
  reviews: "Find the contact or the listing they reviewed.",
132
+ blog_reader_comments:
133
+ "Untitled reader contributions; review through the scoped blog moderation queue, not global contact search.",
132
134
  review_requests: "Solicitation workflow.",
133
135
  contact_stages: "Join table of a contact to a pipeline stage.",
134
136
  advertisers: "Ad-account counterparties.",
@@ -13,6 +13,7 @@ import type { PublicEntity, PublicEntityKind } from "@/core/seo/entities";
13
13
  import { entitiesOfKind } from "@/core/seo/entities";
14
14
 
15
15
  export const FEED_KINDS = [
16
+ "blog",
16
17
  "products",
17
18
  "locations",
18
19
  "events",
@@ -22,6 +23,7 @@ export const FEED_KINDS = [
22
23
  export type FeedKind = (typeof FEED_KINDS)[number];
23
24
 
24
25
  const KIND_FOR_FEED: Record<FeedKind, PublicEntityKind> = {
26
+ blog: "article",
25
27
  products: "product",
26
28
  locations: "location",
27
29
  events: "event",
@@ -213,21 +213,65 @@ export function articleJsonLd(input: {
213
213
  url: string;
214
214
  description?: string | null;
215
215
  dateModified?: Date;
216
+ /** C2.27: the original publication date, for posts. */
217
+ datePublished?: Date | null;
216
218
  authorName?: string | null;
219
+ /** The author's archive, so the Person is an entity rather than a string. */
220
+ authorUrl?: string | null;
221
+ /** `BlogPosting` for blog posts; plain `Article` otherwise. */
222
+ type?: "Article" | "BlogPosting";
223
+ section?: string | null;
224
+ keywords?: string[];
225
+ image?: string | null;
226
+ publisherName?: string | null;
227
+ commentCount?: number;
217
228
  }): JsonLd {
218
229
  return {
219
230
  "@context": CONTEXT,
220
- "@type": "Article",
231
+ "@type": input.type ?? "Article",
221
232
  headline: input.headline,
222
233
  url: input.url,
223
234
  mainEntityOfPage: input.url,
224
235
  ...(input.description ? { description: input.description } : {}),
236
+ ...(input.datePublished
237
+ ? { datePublished: input.datePublished.toISOString() }
238
+ : {}),
225
239
  ...(input.dateModified
226
240
  ? { dateModified: input.dateModified.toISOString() }
227
241
  : {}),
228
242
  ...(input.authorName
229
- ? { author: { "@type": "Person", name: input.authorName } }
243
+ ? {
244
+ author: {
245
+ "@type": "Person",
246
+ name: input.authorName,
247
+ ...(input.authorUrl ? { url: input.authorUrl } : {}),
248
+ },
249
+ }
230
250
  : {}),
251
+ ...(input.section ? { articleSection: input.section } : {}),
252
+ ...(input.keywords?.length ? { keywords: input.keywords.join(", ") } : {}),
253
+ ...(input.image ? { image: input.image } : {}),
254
+ ...(input.publisherName
255
+ ? { publisher: { "@type": "Organization", name: input.publisherName } }
256
+ : {}),
257
+ ...(input.commentCount !== undefined ? { commentCount: input.commentCount } : {}),
258
+ };
259
+ }
260
+
261
+ /** A breadcrumb from explicit steps, for pages whose path is not their place. */
262
+ export function breadcrumbTrailJsonLd(
263
+ items: Array<{ name: string; item: string }>,
264
+ ): JsonLd | undefined {
265
+ if (items.length < 2) return undefined;
266
+ return {
267
+ "@context": CONTEXT,
268
+ "@type": "BreadcrumbList",
269
+ itemListElement: items.map((entry, index) => ({
270
+ "@type": "ListItem",
271
+ position: index + 1,
272
+ name: entry.name,
273
+ item: entry.item,
274
+ })),
231
275
  };
232
276
  }
233
277
 
@@ -0,0 +1,53 @@
1
+ // Copyright (C) 2026 Tony Aly
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // This leaf adapter asks the public service over the configured origin. No
4
+ // request cookies, forwarded headers or caller-supplied origin cross that seam.
5
+ import { siteOrigin } from "./origin";
6
+
7
+ const INTERNAL = /^\/(?:_next|admin|login|setup|preview|portal|api|media|embed|og|go|ap|feeds|\.well-known)(?:\/|$)/;
8
+ const FILE = /\.(?:css|js|map|json|xml|txt|ico|png|jpe?g|gif|svg|webp|avif|woff2?|mp[34]|pdf)$/i;
9
+ const PREFIX = /^\/([a-z]{2}(?:-[A-Za-z]{2,4})?)(\/.*)?$/;
10
+
11
+ export async function legacyRedirect(request: Request): Promise<Response | null> {
12
+ if (!["GET", "HEAD"].includes(request.method)) return null;
13
+ const requestUrl = new URL(request.url);
14
+ const pathname = requestUrl.pathname;
15
+ if (INTERNAL.test(pathname) || FILE.test(pathname)) return null;
16
+ const prefix = PREFIX.exec(pathname);
17
+ const locale = prefix?.[1] ?? "en";
18
+ const localPath = prefix ? prefix[2] ?? "/" : pathname;
19
+ if (INTERNAL.test(localPath)) return null;
20
+ let path = localPath.replace(/^\/+|\/+$/g, "");
21
+ try { path = decodeURIComponent(path); } catch { /* An invalid escape stays a structural miss. */ }
22
+ const queryKeys = ["p", "page_id", "attachment_id", "feed"] as const;
23
+ const query = queryKeys.find(key => requestUrl.searchParams.has(key));
24
+ // ID query aliases belong to the site's root/index.php, never to arbitrary
25
+ // paths. A tracking query on a page keeps that page's meaning.
26
+ const candidate = query && ["", "index.php"].includes(path)
27
+ ? `${path}?${query}=${requestUrl.searchParams.get(query)}` : path;
28
+ try {
29
+ const endpoint = new URL("/api/v1/seo.resolveRedirect", siteOrigin());
30
+ endpoint.searchParams.set("path", candidate);
31
+ endpoint.searchParams.set("locale", locale);
32
+ const response = await fetch(endpoint, { cache: "no-store", redirect: "error", signal: AbortSignal.timeout(1500), headers: { accept: "application/json" } });
33
+ if (response.ok) {
34
+ const moved: unknown = await response.json();
35
+ if (moved && typeof moved === "object" && "toPath" in moved && typeof moved.toPath === "string" && "status" in moved && ["301", "302"].includes(String(moved.status))) {
36
+ const target = new URL(`/${prefix ? `${locale}/` : ""}${moved.toPath.replace(/^\/+/, "")}`, siteOrigin());
37
+ if (target.origin === new URL(siteOrigin()).origin && target.href !== requestUrl.href) {
38
+ return Response.redirect(target, Number(moved.status));
39
+ }
40
+ }
41
+ }
42
+ } catch {
43
+ // A resolver outage never takes the page down. The route still resolves
44
+ // content and its historical redirect fallback; acceptance checks must
45
+ // detect a degraded redirect rather than declaring this path verified.
46
+ }
47
+ if (pathname.length > 1 && pathname.endsWith("/")) {
48
+ const target = new URL(requestUrl.href);
49
+ target.pathname = pathname.replace(/\/+$/, "");
50
+ return Response.redirect(target, 301);
51
+ }
52
+ return null;
53
+ }
@@ -2,11 +2,9 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // Per-page SEO fields (MASTER.md §5).
4
4
  //
5
- // Titles and descriptions are unique *and* short. An owner-supplied override
6
- // already has a 60/155 character ceiling in the write schema; the renderer
7
- // still has to keep the composed title (page · site) inside that budget, or
8
- // the search snippet is whatever the engine truncated — usually the unique
9
- // half of the title.
5
+ // Newly composed titles and descriptions use 60/155-character suggestions.
6
+ // Imported originals carry an explicit preservation flag: migration must not
7
+ // silently change a publisher’s existing search title or description.
10
8
  //
11
9
  // Filter query strings are a different page to a crawler and the same page
12
10
  // to a visitor. They are noindexed and canonicalised to the clean path so
@@ -27,6 +25,7 @@ export const FILTER_QUERY_KEYS = new Set([
27
25
  "min",
28
26
  "max",
29
27
  "page",
28
+ "commentPage",
30
29
  "facet",
31
30
  ]);
32
31
 
@@ -52,7 +51,11 @@ export function composeDocumentTitle(
52
51
  title: string,
53
52
  siteName: string | undefined,
54
53
  isHome: boolean,
54
+ preserve = false,
55
55
  ): string {
56
+ // Imported search titles already carry the publisher's deliberate wording.
57
+ // Keep them byte-for-byte instead of silently clipping or appending a brand.
58
+ if (preserve) return title;
56
59
  const own = clipSeoText(title, TITLE_LIMIT);
57
60
  // A title that already names the business ("About Aurora Coast
58
61
  // Photography") would otherwise come out doubled: "About Aurora Coast
@@ -76,9 +79,9 @@ function namesBrand(title: string, brand: string): boolean {
76
79
  return new RegExp(`^(?:${escaped})(?:$|${edge})|(?:^|${edge})(?:${escaped})$`, "iu").test(title.trim());
77
80
  }
78
81
 
79
- export function composeDescription(description: string | undefined): string | undefined {
82
+ export function composeDescription(description: string | undefined, preserve = false): string | undefined {
80
83
  if (!description) return undefined;
81
- return clipSeoText(description, DESCRIPTION_LIMIT);
84
+ return preserve ? description : clipSeoText(description, DESCRIPTION_LIMIT);
82
85
  }
83
86
 
84
87
  export function isFilterQuery(
@@ -5,7 +5,7 @@ import { z } from "zod";
5
5
  import { and, desc, eq } from "drizzle-orm";
6
6
  import { listed, okResult, row, timestamp, uuid } from "@/core/contract";
7
7
  import { redirects } from "@/core/seo/schema";
8
- import { defineService, ServiceError } from "@/core/service";
8
+ import { defineService, getService, ServiceError } from "@/core/service";
9
9
  import { isUniqueViolation } from "@/core/db";
10
10
 
11
11
  const redirectRow = row({
@@ -58,6 +58,19 @@ export const resolveRedirect = defineService({
58
58
  )
59
59
  .limit(1);
60
60
  if (!row) {
61
+ if (hop === 0) {
62
+ const pagination = /^(.*)\/page\/([1-9]\d*)$/.exec(current);
63
+ if (pagination && !/\/page\/\d+$/.test(pagination[1]!) && Number(pagination[2]) <= 10000) {
64
+ const originalRoot = pagination[1]!;
65
+ const movedRoot = z.object({ toPath: z.string(), status: z.enum(["301", "302"]) }).nullable().parse(await ctx.call(getService("seo.resolveRedirect"), { path: originalRoot, locale: input.locale }));
66
+ const root = movedRoot?.toPath ?? originalRoot;
67
+ const archive = z.object({ posts: z.number() }).nullable().parse(await ctx.call(getService("cms.resolveBlogArchive"), { path: root }));
68
+ const listing = root === "blog" ? await ctx.call(getService("cms.resolvePage"), { slug: root, locale: input.locale }) : null;
69
+ const settings = z.object({ postsPerPage: z.number() }).parse(await ctx.call(getService("cms.blogSettings"), {}));
70
+ const count = listing ? z.object({ pages: z.number() }).parse(await ctx.call(getService("cms.listBlogPosts"), { locale: input.locale, limit: settings.postsPerPage })).pages : Math.ceil((archive?.posts ?? 0) / settings.postsPerPage);
71
+ if ((archive || listing) && Number(pagination[2]) <= count) return { toPath: Number(pagination[2]) === 1 ? root : `${root}?page=${pagination[2]}`, status: movedRoot?.status ?? "301" as const };
72
+ }
73
+ }
61
74
  return hop === 0 ? null : { toPath: current, status };
62
75
  }
63
76
  // A 302 anywhere in the chain makes the whole journey temporary: the
@@ -1,6 +1,7 @@
1
1
  // Copyright (C) 2026 Tony Aly
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // Update preflight (MASTER.md §39.4, C10.05). Honest about what it cannot know.
4
+ import { describeLocalStorage, localStorageMode } from "@/adapters/storage/local-mode";
4
5
  import { randomUUID } from "node:crypto";
5
6
  import { statfs } from "node:fs/promises";
6
7
  import { sql } from "drizzle-orm";
@@ -114,8 +115,8 @@ export async function environmentPreflight(): Promise<PreflightStep[]> {
114
115
 
115
116
  const e = env();
116
117
  const storage = e.FREEHOLDER_STORAGE ?? instanceConfig.adapters.storage;
117
- if (storage === "local" && e.NODE_ENV === "production" && e.FREEHOLDER_UNSAFE_LOCAL_STORAGE !== "1") {
118
- steps.push(step("adapters", "fail", "Uploads are on local disk in production, which does not survive a rebuild."));
118
+ if (storage === "local" && localStorageMode(e) === "refused") {
119
+ steps.push(step("adapters", "fail", describeLocalStorage(e)));
119
120
  } else {
120
121
  steps.push(step("adapters", "ok", `Storage adapter is ${storage}.`));
121
122
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.2.0-beta.4",
2
+ "version": "0.2.0-beta.6",
3
3
  "channel": "edge",
4
4
  "minFromVersion": "0.1.0",
5
5
  "schemaRisk": "breaking",
@@ -1,6 +1,7 @@
1
1
  // Copyright (C) 2026 Tony Aly
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // Customization seams (C10.01), channels (C10.02), signed feed (C10.03), daily check (C10.04), preflight (C10.05), apply (C10.06).
4
+ import { describeLocalStorage, localStorageMode, type LocalStorageEnvironment } from "@/adapters/storage/local-mode";
4
5
  import { z } from "zod";
5
6
  import { desc, eq, inArray, sql } from "drizzle-orm";
6
7
  import { access } from "node:fs/promises";
@@ -91,7 +92,7 @@ export const inspectSeams = defineService({
91
92
  () => false,
92
93
  );
93
94
  const storage = e.FREEHOLDER_STORAGE ?? instanceConfig.adapters.storage;
94
- const uploads = uploadsStatus(storage, e.NODE_ENV, e.FREEHOLDER_UNSAFE_LOCAL_STORAGE === "1");
95
+ const uploads = uploadsStatus(storage, e);
95
96
  const core = await inspectCoreFiles({
96
97
  root,
97
98
  expectedDigest: e.FREEHOLDER_CORE_DIGEST ?? null,
@@ -191,8 +192,7 @@ export const describeRelease = defineService({
191
192
 
192
193
  function uploadsStatus(
193
194
  storage: string,
194
- nodeEnv: string,
195
- unsafeLocal: boolean,
195
+ e: LocalStorageEnvironment,
196
196
  ): { status: "ok" | "warn" | "fail"; detail: string } {
197
197
  if (storage !== "local") {
198
198
  return {
@@ -200,21 +200,11 @@ function uploadsStatus(
200
200
  detail: `Uploads use ${storage} object storage, not instance disk.`,
201
201
  };
202
202
  }
203
- if (nodeEnv !== "production") {
204
- return {
205
- status: "ok",
206
- detail: "Local disk storage is for development. Production must use object storage.",
207
- };
208
- }
209
- if (unsafeLocal) {
210
- return {
211
- status: "warn",
212
- detail: "Uploads are on this machine's disk because FREEHOLDER_UNSAFE_LOCAL_STORAGE=1.",
213
- };
214
- }
203
+ // C3.44: one rule for adapter, Doctor, preflight and this screen.
204
+ const mode = localStorageMode(e);
215
205
  return {
216
- status: "fail",
217
- detail: "Uploads are configured for local disk in production, which does not survive a rebuild.",
206
+ status: mode === "refused" ? "fail" : mode === "unsafe" ? "warn" : "ok",
207
+ detail: describeLocalStorage(e),
218
208
  };
219
209
  }
220
210
 
@@ -5,7 +5,7 @@
5
5
  // Separate from `schema.ts` so a screen can name a provider or an outcome
6
6
  // without importing a Drizzle table — `app/**` is barred from module schemas
7
7
  // (§15.5), and a value list is not a database.
8
- export const ASSISTANT_PROVIDERS = ["none", "anthropic", "openai"] as const;
8
+ export const ASSISTANT_PROVIDERS = ["none", "anthropic", "openai", "paradise"] as const;
9
9
  export type AssistantProvider = (typeof ASSISTANT_PROVIDERS)[number];
10
10
 
11
11
  export const ASSISTANT_SPEND_PERIODS = ["day", "week", "month"] as const;
@@ -96,6 +96,9 @@ export async function repliesOnConversation(
96
96
  * fail-closed direction, because a cap enforced against a guess is not a cap.
97
97
  */
98
98
  export function assistantPrice(settings: AssistantSettings): ModelPrice | null {
99
+ // Managed calls reserve the entire remaining cap and receive an actual
100
+ // list-price receipt. They do not pretend to have a token price.
101
+ if (settings.provider === "paradise") return { inputCentsPerMillion: 0, outputCentsPerMillion: 0 };
99
102
  return modelPrice(settings.model, {
100
103
  ...(settings.inputCentsPerMillion === null
101
104
  ? {}
@@ -0,0 +1,124 @@
1
+ // Copyright (C) 2026 Tony Aly
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // PM owns admission and transport grants; the site binds every operation to
4
+ // its validated chat cookie. No caller can select a persona, account or key.
5
+ import { createHash } from "node:crypto";
6
+ import { eq, sql } from "drizzle-orm";
7
+ import { z } from "zod";
8
+ import { sessionForToken } from "@/core/messaging/chat";
9
+ import { defineOrchestratedService, defineService, getService, ServiceError } from "@/core/service";
10
+ import { paradiseRequest } from "@/adapters/paradise/http";
11
+ import { assistantSettings } from "./schema";
12
+ import { env } from "@/core/env";
13
+ import { parseCspOrigins } from "@/core/http/csp";
14
+
15
+ const token = z.string().trim().min(32).max(200);
16
+ const caption = z.object({
17
+ speaker: z.enum(["member", "muse"]), text: z.string().trim().min(1).max(2000),
18
+ startedAt: z.number().int().positive(), endedAt: z.number().int().positive(),
19
+ }).strict().refine(value => value.endedAt >= value.startedAt && value.endedAt - value.startedAt <= 300000, "Invalid caption timing.");
20
+ const previewAccess = defineService({
21
+ name: "assistant.previewAccess", summary: "Bind a managed call to an existing site chat.",
22
+ kind: "query", permission: "public", external: false, agentCallable: false,
23
+ input: z.object({ token, ending: z.boolean() }),
24
+ output: z.object({ visitorRef: z.string() }),
25
+ handler: async (input, ctx) => {
26
+ await sessionForToken(ctx.tx, input.token, { allowClosed: input.ending });
27
+ const [settings] = await ctx.tx.select().from(assistantSettings).where(eq(assistantSettings.id, 1)).limit(1);
28
+ // Stopping remains possible after the owner switches the assistant off.
29
+ if ((!settings?.enabled || settings.provider !== "paradise") && !input.ending) {
30
+ throw new ServiceError("not_found", "The managed assistant is not enabled.");
31
+ }
32
+ return { visitorRef: createHash("sha256").update(`pm-preview-assistant-visitor-v1\n${input.token}`).digest("hex") };
33
+ },
34
+ });
35
+
36
+ const control = z.discriminatedUnion("action", [
37
+ z.object({ action: z.literal("config"), token }).strict(),
38
+ z.object({ action: z.literal("start"), token, want: z.enum(["voice", "video"]) }).strict(),
39
+ z.object({ action: z.literal("poll"), token, sessionId: z.string().uuid() }).strict(),
40
+ z.object({ action: z.literal("queued"), token, sessionId: z.string().uuid(), want: z.enum(["voice", "video"]) }).strict(),
41
+ z.object({ action: z.literal("lease"), token, sessionId: z.string().uuid(), authorizedUntilMs: z.number().int().positive() }).strict(),
42
+ z.object({ action: z.literal("end"), token, sessionId: z.string().uuid() }).strict(),
43
+ z.object({ action: z.literal("caption"), token, sessionId: z.string().uuid(), caption }).strict(),
44
+ ]);
45
+
46
+ const saveCaption = defineService({
47
+ name: "assistant.saveCallCaption", summary: "Put browser-observed call captions on the existing conversation.",
48
+ kind: "mutation", permission: "public", writeClass: "message", external: false, agentCallable: false,
49
+ input: z.object({ token, sessionId: z.string().uuid(), caption }), output: z.object({ saved: z.boolean() }),
50
+ rateLimit: { limit: 90, windowSeconds: 300, subject: input => createHash("sha256").update(input.token).digest("hex"), message: "Some call captions could not be saved. You can still type a message." },
51
+ handler: async (input, ctx) => {
52
+ const session = await sessionForToken(ctx.tx, input.token);
53
+ const hash = createHash("sha256").update(JSON.stringify(input.caption)).digest("hex");
54
+ const providerRef = `pm-call-caption:${input.sessionId}:${hash}`;
55
+ await ctx.tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${providerRef}))`);
56
+ // These are explicitly browser observations, not worker/audio receipts.
57
+ // They can never be used as authority for billing, consent or identity.
58
+ const who = input.caption.speaker === "member" ? "visitor" : "AI assistant";
59
+ await ctx.callAsSystem(getService("conversations.record"), {
60
+ conversationId: session.conversationId, contactId: session.contactId, chatSessionId: session.id,
61
+ direction: input.caption.speaker === "member" ? "inbound" : "outbound",
62
+ channel: input.caption.speaker === "member" ? "chat" : "assistant",
63
+ sentBy: input.caption.speaker === "member" ? "contact" : "automation", providerRef,
64
+ body: `[Call caption: ${who}; browser-observed]\n${input.caption.text}`,
65
+ });
66
+ ctx.setSubject("conversation", session.conversationId);
67
+ return { saved: true };
68
+ },
69
+ });
70
+
71
+ export const previewCall = defineOrchestratedService({
72
+ name: "assistant.previewCall", summary: "Control this browser's managed assistant call.",
73
+ kind: "mutation", permission: "public", writeClass: "message",
74
+ // PM bounds starts; end is always available without a spending/rate gate.
75
+ input: control, output: z.unknown(),
76
+ handler: async (input, actor) => {
77
+ const { visitorRef } = await previewAccess.call({ token: input.token, ending: input.action === "end" }, actor);
78
+ const base = "/v1/ai/assistant";
79
+ if (input.action === "config") {
80
+ const result = await paradiseRequest<Record<string, unknown>>(`${base}/config`, { method: "GET" });
81
+ return parseCspOrigins(env().PARADISEMODERN_ASSISTANT_ORIGINS).length ? result.body : { ...result.body, modes: ["text"] };
82
+ }
83
+ if (input.action === "start") return (await paradiseRequest(`${base}/sessions`, { body: { visitor_ref: visitorRef, want: input.want } })).body;
84
+ const session = `${base}/sessions/${input.sessionId}`;
85
+ if (input.action === "caption") {
86
+ const observed = await paradiseRequest<{ status: string; mode: string }>(session, { method: "GET", query: { visitor_ref: visitorRef } });
87
+ if (!["live", "ending", "ended"].includes(observed.body.status) || !["voice", "video"].includes(observed.body.mode)) {
88
+ throw new ServiceError("conflict", "There is no admitted call for these captions.");
89
+ }
90
+ return saveCaption.call({ token: input.token, sessionId: input.sessionId, caption: input.caption }, actor);
91
+ }
92
+ if (input.action === "poll") return (await paradiseRequest(session, { method: "GET", query: { visitor_ref: visitorRef } })).body;
93
+ const body = input.action === "lease"
94
+ ? { visitor_ref: visitorRef, authorized_until_ms: input.authorizedUntilMs }
95
+ : { visitor_ref: visitorRef };
96
+ return (await paradiseRequest(`${session}/${input.action === "queued" ? "start" : input.action}`, { body })).body;
97
+ },
98
+ });
99
+
100
+ export const managedDetails = defineOrchestratedService({
101
+ name: "assistant.managedDetails", summary: "Read this preview's managed settings and cleared Canon talent.",
102
+ kind: "query", permission: "scoped", input: z.object({}),
103
+ output: z.object({
104
+ settings: z.object({ enabled: z.boolean(), talentSlug: z.string(), dailyCapUsd: z.number() }),
105
+ talent: z.array(z.object({ slug: z.string(), name: z.string(), style: z.string() })),
106
+ }),
107
+ handler: async () => {
108
+ const [settings, talent] = await Promise.all([
109
+ paradiseRequest<{ settings: { enabled: boolean; talentSlug: string; dailyCapUsd: number } }>("/v1/ai/assistant/settings", { method: "GET" }),
110
+ paradiseRequest<{ talent: Array<{ slug: string; name: string; style: string }> }>("/v1/ai/assistant/talent", { method: "GET" }),
111
+ ]);
112
+ return { settings: settings.body.settings, talent: talent.body.talent };
113
+ },
114
+ });
115
+
116
+ export const syncManagedSettings = defineOrchestratedService({
117
+ name: "assistant.syncManagedSettings", summary: "Apply an authorized owner's assistant off switch, talent and daily cap at PM.",
118
+ kind: "mutation", permission: "scoped", writeClass: "write",
119
+ input: z.object({ enabled: z.boolean(), talentSlug: z.string().trim().min(1).max(80), dailyCapUsd: z.number().finite().min(0).max(10) }).strict(),
120
+ output: z.object({ settings: z.object({ enabled: z.boolean(), talentSlug: z.string(), dailyCapUsd: z.number() }) }),
121
+ handler: async input => (await paradiseRequest<{ settings: typeof input }>("/v1/ai/assistant/settings", { method: "PATCH", body: input })).body,
122
+ });
123
+
124
+ export default [previewAccess, saveCaption, previewCall, managedDetails, syncManagedSettings];
@@ -26,11 +26,13 @@ import { env } from "@/core/env";
26
26
  import { createAnthropicAi, createOpenAiAi, type AiAdapter } from "@/adapters/ai";
27
27
  import type { AssistantProvider } from "./contract";
28
28
  import type { AssistantSettings } from "./schema";
29
+ import { createParadiseAssistantAi } from "@/adapters/paradise/assistant";
29
30
 
30
31
  /** The conventional variable per provider, when the owner names none. */
31
32
  const DEFAULT_CREDENTIAL_REF: Record<Exclude<AssistantProvider, "none">, string> = {
32
33
  anthropic: "ANTHROPIC_API_KEY",
33
34
  openai: "OPENAI_API_KEY",
35
+ paradise: "PARADISEMODERN_API_KEY",
34
36
  };
35
37
 
36
38
  export function credentialRefFor(settings: {
@@ -80,6 +82,11 @@ export function assistantAdapter(settings: AssistantSettings): AdapterResolution
80
82
  if (settings.provider === "none") {
81
83
  return { unconfigured: "No model provider is chosen for the assistant." };
82
84
  }
85
+ if (settings.provider === "paradise") {
86
+ return credentialPresent(settings)
87
+ ? { adapter: createParadiseAssistantAi() }
88
+ : { unconfigured: "The managed assistant is not connected to this deployment." };
89
+ }
83
90
  if (!settings.model?.trim()) {
84
91
  return { unconfigured: "No model is chosen for the assistant." };
85
92
  }
@@ -38,6 +38,8 @@
38
38
  // conversation, because §31's "every conversation lands on the spine" is
39
39
  // exactly the sentence a private transcript table would break.
40
40
  import { createHash } from "node:crypto";
41
+ export { previewCall, managedDetails, syncManagedSettings } from "./preview";
42
+ import previewServices from "./preview";
41
43
  import { and, desc, eq, inArray, sql } from "drizzle-orm";
42
44
  import { z } from "zod";
43
45
  import { listed, okResult, row, timestamp, uuid } from "@/core/contract";
@@ -554,6 +556,7 @@ const answerPlan = z.object({
554
556
  system: z.string(),
555
557
  asked: z.string(),
556
558
  maxOutputTokens: z.number().int(),
559
+ reservedCents: z.number().int().nonnegative(),
557
560
  price: z.object({
558
561
  inputCentsPerMillion: z.number(),
559
562
  outputCentsPerMillion: z.number(),
@@ -584,6 +587,9 @@ const prepareAnswer = defineService({
584
587
  output: answerPrepared,
585
588
  handler: async (input, ctx) => {
586
589
  const startedAt = Date.now();
590
+ // Serialize budget reads and claims across chats, including managed
591
+ // turns which hold the whole remaining cap until a provider receipt.
592
+ await ctx.tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('assistant-budget'))`);
587
593
  const current = await readSettings(ctx.tx);
588
594
  // The off fallback, first and cheapest: no provider, no session lookup, no
589
595
  // row. An instance that never switched this on is an instance where this
@@ -715,14 +721,14 @@ const prepareAnswer = defineService({
715
721
  // Everything that can refuse is decided here, from reads, before a single
716
722
  // insert — see the file header for why that ordering is not optional.
717
723
  const price = assistantPrice(current);
718
- const estimateCents = price
719
- ? estimateTurnCents(price, `${system}\n${asked}`, current.maxOutputTokens)
720
- : 0;
721
724
  const [spentCents, repliesThisHour, repliesHere] = await Promise.all([
722
725
  periodSpend(ctx.tx, current.spendPeriod),
723
726
  repliesInLastHour(ctx.tx),
724
727
  repliesOnConversation(ctx.tx, session.conversationId),
725
728
  ]);
729
+ const estimateCents = current.provider === "paradise"
730
+ ? Math.max(0, current.spendCapCents - spentCents)
731
+ : price ? estimateTurnCents(price, `${system}\n${asked}`, current.maxOutputTokens) : 0;
726
732
  const verdict = allowance({
727
733
  settings: current,
728
734
  spentCents,
@@ -801,6 +807,7 @@ const prepareAnswer = defineService({
801
807
  system,
802
808
  asked,
803
809
  maxOutputTokens: current.maxOutputTokens,
810
+ reservedCents: estimateCents,
804
811
  price: verdict.price,
805
812
  notes,
806
813
  lastQuestion: transcript.at(-1)?.body ?? "",
@@ -814,6 +821,7 @@ const generatedAnswer = z.object({
814
821
  structured: z.unknown().optional(),
815
822
  provider: z.string(),
816
823
  model: z.string(),
824
+ meteredCents: z.number().int().nonnegative().optional(),
817
825
  usage: z.object({
818
826
  inputTokens: z.number(),
819
827
  outputTokens: z.number(),
@@ -894,13 +902,17 @@ const applyAnswer = defineService({
894
902
  // An adapter failure is an HTTP failure that happened with no
895
903
  // transaction open; this one records it.
896
904
  const detail = input.failure ?? "The model could not be reached.";
897
- await finish({ outcome: "failed", detail });
905
+ // An unknown managed timeout may follow a charged turn. Preserve its
906
+ // reservation until the owner reconciles the managed ledger receipt.
907
+ await finish({ outcome: "failed", detail, ...(turn.provider === "paradise" ? { costCents: turn.costCents } : {}) });
898
908
  await noteError(ctx.tx, detail);
899
909
  ctx.setSubject("conversation", session.conversationId);
900
910
  return { status: "failed" as const, reply: null, action: null };
901
911
  }
902
912
 
903
- const costCents = turnCostCents(plan.price, generated.usage);
913
+ const costCents = generated.provider === "paradise"
914
+ ? Math.min(plan.reservedCents, generated.meteredCents ?? plan.reservedCents)
915
+ : turnCostCents(plan.price, generated.usage);
904
916
  const usage = {
905
917
  provider: generated.provider,
906
918
  model: generated.model,
@@ -1108,6 +1120,8 @@ export const answer = defineOrchestratedService({
1108
1120
  maxOutputTokens: plan.maxOutputTokens,
1109
1121
  responseSchema: ASSISTANT_RESPONSE_SCHEMA,
1110
1122
  idempotencyKey: `assistant.answer:${plan.messageId}`,
1123
+ visitorRef: createHash("sha256").update(`pm-preview-assistant-visitor-v1\n${input.token}`).digest("hex"),
1124
+ maxChargeCents: plan.reservedCents,
1111
1125
  });
1112
1126
  } catch (error) {
1113
1127
  failure = error instanceof Error ? error.message : "The model could not be reached.";
@@ -1125,6 +1139,7 @@ export const answer = defineOrchestratedService({
1125
1139
  provider: generated.provider,
1126
1140
  model: generated.model,
1127
1141
  usage: generated.usage,
1142
+ meteredCents: generated.meteredCents,
1128
1143
  }
1129
1144
  : null,
1130
1145
  failure,
@@ -1494,6 +1509,7 @@ registerContactPrivacySource({
1494
1509
  });
1495
1510
 
1496
1511
  export default [
1512
+ ...previewServices,
1497
1513
  settings,
1498
1514
  updateSettings,
1499
1515
  scopes,