@mossbear/protocol 0.1.0-alpha.115 → 0.1.0-alpha.116

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 (45) hide show
  1. package/dist/bundles.d.ts +662 -0
  2. package/dist/bundles.d.ts.map +1 -0
  3. package/dist/bundles.js +454 -0
  4. package/dist/bundles.js.map +1 -0
  5. package/dist/bundles.test.d.ts +2 -0
  6. package/dist/bundles.test.d.ts.map +1 -0
  7. package/dist/bundles.test.js +61 -0
  8. package/dist/bundles.test.js.map +1 -0
  9. package/dist/guideHistory.d.ts +643 -0
  10. package/dist/guideHistory.d.ts.map +1 -0
  11. package/dist/guideHistory.js +343 -0
  12. package/dist/guideHistory.js.map +1 -0
  13. package/dist/guideHistory.test.d.ts +2 -0
  14. package/dist/guideHistory.test.d.ts.map +1 -0
  15. package/dist/guideHistory.test.js +35 -0
  16. package/dist/guideHistory.test.js.map +1 -0
  17. package/dist/guideImport.d.ts +398 -0
  18. package/dist/guideImport.d.ts.map +1 -0
  19. package/dist/guideImport.js +350 -0
  20. package/dist/guideImport.js.map +1 -0
  21. package/dist/guideImport.test.d.ts +2 -0
  22. package/dist/guideImport.test.d.ts.map +1 -0
  23. package/dist/guideImport.test.js +62 -0
  24. package/dist/guideImport.test.js.map +1 -0
  25. package/dist/guideSnapshot.d.ts +105 -0
  26. package/dist/guideSnapshot.d.ts.map +1 -0
  27. package/dist/guideSnapshot.js +101 -0
  28. package/dist/guideSnapshot.js.map +1 -0
  29. package/dist/guideSnapshot.test.d.ts +2 -0
  30. package/dist/guideSnapshot.test.d.ts.map +1 -0
  31. package/dist/guideSnapshot.test.js +49 -0
  32. package/dist/guideSnapshot.test.js.map +1 -0
  33. package/dist/pairing.d.ts +1 -1
  34. package/dist/schemas.d.ts +14 -2042
  35. package/dist/schemas.d.ts.map +1 -1
  36. package/dist/schemas.js +13 -1358
  37. package/dist/schemas.js.map +1 -1
  38. package/dist/types.d.ts +4 -27
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/types.js.map +1 -1
  41. package/dist/wirePrimitives.d.ts +87 -0
  42. package/dist/wirePrimitives.d.ts.map +1 -1
  43. package/dist/wirePrimitives.js +121 -0
  44. package/dist/wirePrimitives.js.map +1 -1
  45. package/package.json +1 -1
package/dist/schemas.js CHANGED
@@ -8,15 +8,22 @@
8
8
  * input) or call `v.safeParse(Schema, data)` directly for non-throwing checks.
9
9
  */
10
10
  import * as v from 'valibot';
11
- import { DISPLAY_NAME_REFUSED_CHARACTERS } from './bundleSlug.js';
12
- import { isBundleSlug } from './bundleSlug.js';
11
+ import { BundleSlugSchema } from './bundles.js';
13
12
  import { ArtifactCommentSchema, MAX_ITEM_THREAD_ENTRIES_ON_WIRE } from './comments.js';
14
13
  import { CONTEXT_CONTENT_KINDS, CONTEXT_ITEM_TYPES, CONTEXT_ITEM_TYPE_FILTER_VALUES, contextItemTypeOf, CAPTURE_CONTENT_TYPES, } from './contextKinds.js';
14
+ import { GuideHistoryResponseSchema } from './guideHistory.js';
15
+ import { MAX_SKILL_MEMBER_FILES, MAX_SKILL_SKIPPED_MEMBER_PATHS, GuideFileFormatSchema, SkillMemberPathSchema, } from './guideImport.js';
16
+ import { RuleFileManifestSchema } from './guideSnapshot.js';
15
17
  import { MAX_ARTIFACT_DESCRIPTION_CHARS, MAX_ARTIFACT_NAME_CHARS, MAX_CONTEXT_CONTENT_BYTES, MAX_RAW_GUIDE_CONTENT_BYTES, } from './limits.js';
16
- import { MachineIdSchema } from './pairing.js';
17
18
  import { PhotoAssetSchema } from './photos.js';
18
- import { NonEmptyStringSchema, GuideHistoryUntrustedSchema, HarnessIdSchema, RepositoryNameSchema, ProjectIdSchema, MAX_ARTIFACT_FEEDBACK_BATCH, } from './wirePrimitives.js';
19
- export { HarnessIdSchema, MAX_REPOSITORY_NAME_LENGTH, RepositoryNameSchema, ProjectIdSchema, MAX_ARTIFACT_FEEDBACK_BATCH, CommentAuthorKindSchema, GuideHistoryUntrustedSchema, SESSION_GUIDE_VERDICTS, SessionGuideVerdictValueSchema, } from './wirePrimitives.js';
19
+ import { ArtifactDescriptionSchema, displayNameSchema, BoundedRawContentSchema, SkippedMemberPathSchema, Sha256HexSchema, RepoIdSchema, GuideDiscoveryRootSchema, SafeRelativePosixPathSchema, NonEmptyStringSchema, GuideHistoryUntrustedSchema, HarnessIdSchema, RepositoryNameSchema, ProjectIdSchema, MAX_ARTIFACT_FEEDBACK_BATCH, } from './wirePrimitives.js';
20
+ export { GuideDiscoveryRootSchema, SafeRelativePosixPathSchema, PATH_ISSUE_MESSAGES, HarnessIdSchema, MAX_REPOSITORY_NAME_LENGTH, RepositoryNameSchema, ProjectIdSchema, MAX_ARTIFACT_FEEDBACK_BATCH, CommentAuthorKindSchema, GuideHistoryUntrustedSchema, SESSION_GUIDE_VERDICTS, SessionGuideVerdictValueSchema, } from './wirePrimitives.js';
21
+ export { RepoIdSchema, WorkspaceIdSchema } from './wirePrimitives.js';
22
+ export { ArtifactDescriptionSchema, displayNameSchema, DISPLAY_NAME_CONTROL_CHARACTER_MESSAGE, } from './wirePrimitives.js';
23
+ export * from './bundles.js';
24
+ export * from './guideImport.js';
25
+ export * from './guideSnapshot.js';
26
+ export * from './guideHistory.js';
20
27
  export * from './comments.js';
21
28
  export * from './search.js';
22
29
  export { SessionGradeRequestSchema, SessionGradeStateSchema, SessionGradeGuideSchema, SessionGradeSchema, GradedSessionSchema, SessionGradeResponseSchema, parseRunGradeRequest, parseSessionGradeResponse, } from './sessionGrade.js';
@@ -56,16 +63,6 @@ export const PlatformKindSchema = v.picklist([
56
63
  * The server writes `cloud` onto a session when any of its actions carry it.
57
64
  */
58
65
  export const SessionEnvironmentSchema = v.picklist(['cloud']);
59
- export const GuideFileFormatSchema = v.picklist([
60
- 'agents-md',
61
- 'agents-dir',
62
- 'claude-md',
63
- 'claude-rules',
64
- 'cursorrules',
65
- 'cursor-rules',
66
- 'skill-md',
67
- ]);
68
- const Sha256HexSchema = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/i));
69
66
  // No eval-provider schemas here. They described the LLM credentials the CLI
70
67
  // needed to grade on-device; grading is server-side and the CLI holds no
71
68
  // provider config. The server's own provider settings are environment
@@ -75,191 +72,7 @@ const Sha256HexSchema = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/i));
75
72
  // `typeof body.token === 'string'` by hand — and nothing else imported them.
76
73
  // Deleted rather than kept as a parallel contract that had already drifted
77
74
  // from the route's `{ valid }` response.
78
- // The guide snapshot schemas live further down, after
79
- // `SafeRelativePosixPathSchema` and `GuideDiscoveryRootSchema`: the bundle now
80
- // carries the same `(root, path)` pair the import payload does, and a `const`
81
- // cannot be referenced above its own declaration.
82
75
  export { MAX_ARTIFACT_DESCRIPTION_CHARS, MAX_ARTIFACT_NAME_CHARS, MAX_RAW_GUIDE_CONTENT_BYTES, };
83
- /** Max member files a single skill-md payload may carry. */
84
- export const MAX_SKILL_MEMBER_FILES = 64;
85
- const BoundedRawContentSchema = v.pipe(v.string(), v.check((value) => new TextEncoder().encode(value).length <= MAX_RAW_GUIDE_CONTENT_BYTES, `rawContent must be at most ${MAX_RAW_GUIDE_CONTENT_BYTES} bytes`));
86
- // A path that is safe to re-create on disk and safe to store as identity:
87
- // forward slashes only, never absolute (POSIX or Windows drive-letter form),
88
- // no empty / `.` / `..` segments, no control characters. Every path this
89
- // protocol carries can end up written into a project tree, so the rule
90
- // belongs at the schema boundary rather than in each consumer, at the boundary
91
- // where untrusted data crosses in.
92
- //
93
- // Exported so the server and the CLI enforce the identical rule.
94
- //
95
- // The check messages each name the one edit that fixes the path, so they are
96
- // written for the reader and exported for a server boundary to pass through.
97
- export const PATH_ISSUE_MESSAGES = {
98
- backslash: 'path must use forward slashes',
99
- absolute: 'path must be relative',
100
- control: 'path must not contain control characters',
101
- segments: 'path must not contain empty, "." or ".." segments',
102
- skillMd: 'path must not shadow the skill’s own SKILL.md',
103
- };
104
- export const SafeRelativePosixPathSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(512), v.check((path) => !path.includes('\\'), PATH_ISSUE_MESSAGES.backslash), v.check((path) => !path.startsWith('/') && !/^[a-zA-Z]:/.test(path), PATH_ISSUE_MESSAGES.absolute), v.check(
105
- // eslint-disable-next-line no-control-regex
106
- (path) => !/[\u0000-\u001f\u007f]/.test(path), PATH_ISSUE_MESSAGES.control), v.check((path) => path
107
- .split('/')
108
- .every((segment) => segment !== '' && segment !== '.' && segment !== '..'), PATH_ISSUE_MESSAGES.segments));
109
- // Member paths are relative to the skill directory, and additionally may never
110
- // name the skill's own SKILL.md (the payload itself).
111
- export const SkillMemberPathSchema = v.pipe(SafeRelativePosixPathSchema, v.check((path) => path.toLowerCase() !== 'skill.md', PATH_ISSUE_MESSAGES.skillMd));
112
- // A sibling file of a skill's SKILL.md (scripts/, references/, assets/,
113
- // supporting docs), imported alongside it as a guide_file row.
114
- export const RawSkillMemberFileSchema = v.object({
115
- path: SkillMemberPathSchema,
116
- rawContent: BoundedRawContentSchema,
117
- lastModified: v.pipe(v.number(), v.integer(), v.minValue(0)),
118
- content_hash: Sha256HexSchema,
119
- /**
120
- * Whether the file is executable (`100755` in git), so delivery writes it
121
- * `0o755` or `0o644`. A boolean rather than a mode because git records only
122
- * those two for a blob, and a numeric mode would be a channel for bits
123
- * nothing here should set. **Absent is not `false`**: a CLI that predates the
124
- * field sends none, and the server then keeps whatever it already holds.
125
- */
126
- executable: v.optional(v.boolean()),
127
- });
128
- /** Max skipped-member paths a skill-md payload may report alongside `members`. */
129
- export const MAX_SKILL_SKIPPED_MEMBER_PATHS = 256;
130
- // Paths (relative to the skill directory) that discovery found but could not
131
- // import this run — binary/non-UTF-8, oversized, unreadable, or beyond the
132
- // member cap. Deliberately looser than SkillMemberPathSchema: these describe
133
- // what is on the user's disk and are only ever string-matched against stored
134
- // member paths server-side (never re-created as files), so an odd on-disk
135
- // filename must not fail the whole payload.
136
- const SkippedMemberPathSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(512));
137
- /**
138
- * Which root a discovered guide file's `path` is relative to: the repo checkout
139
- * (`project`) or the user's homedir (`global`, e.g. `.claude/CLAUDE.md`).
140
- * Part of the import resolution key — see `RawGuideFilePayloadSchema.root`.
141
- */
142
- export const GuideDiscoveryRootSchema = v.picklist(['project', 'global']);
143
- // ---------------------------------------------------------------------------
144
- // Guide snapshot schemas
145
- // ---------------------------------------------------------------------------
146
- export const GuideSnapshotSchema = v.object({
147
- id: v.string(),
148
- title: v.string(),
149
- content: v.string(),
150
- enabled: v.boolean(),
151
- updatedAt: v.string(),
152
- // origin is `file:{format}:{path}` for imported guides, null/absent
153
- // otherwise. contentHash is the SHA-256 of the canonical bytes; the CLI uses
154
- // the pair to round-trip imported files back to disk without re-encoding.
155
- //
156
- // **`origin` is not superseded by `(root, path)`.** Nothing on the write side
157
- // reconciles on it after this slice, but `resolveRuleFileDelivery` still
158
- // matches delivery evidence on `(origin, contentHash)`, so dropping it
159
- // would make every guide read as undelivered — silently, since runs still
160
- // grade and verdicts still appear. It stays as provenance.
161
- origin: v.optional(v.nullable(v.string())),
162
- contentHash: v.optional(v.nullable(Sha256HexSchema)),
163
- // Which scope root `path` is relative to, and the path itself — the write
164
- // side's half of the identity the read side already stores on
165
- // `guide_files.root` / `guide_files.path`
166
- // (`guide-write-side-identity-plan.md` → "Carry `root` on every write path").
167
- //
168
- // Without them the bundle could not express "global": `origin` is
169
- // `file:{format}:{path}` with no root component, so every writer resolved it
170
- // against the repo and a guide imported from `~/.claude/CLAUDE.md` came back
171
- // down as `<repo>/.claude/CLAUDE.md`.
172
- //
173
- // **Both optional and nullable, and their absence is not an error.** A guide
174
- // authored in the dashboard has no path; a row imported before the columns
175
- // existed has neither. Such a guide keeps resolving from `origin` alone —
176
- // today's behaviour — rather than becoming undeliverable. A missing `root` is
177
- // read as `project`, which is what every pre-existing row meant.
178
- root: v.optional(v.nullable(GuideDiscoveryRootSchema)),
179
- path: v.optional(v.nullable(SafeRelativePosixPathSchema)),
180
- });
181
- export const GuideBundleResponseSchema = v.object({
182
- guides: v.array(GuideSnapshotSchema),
183
- pulledAt: v.string(),
184
- });
185
- export const RawGuideFilePayloadSchema = v.pipe(v.object({
186
- // Relative to the discovery root the CLI walked (`payloadPath`,
187
- // `packages/cli/src/guides/discover.ts`). Two things depend on it
188
- // being a safe relative path, which is why it is parsed here rather than
189
- // guarded downstream:
190
- //
191
- // - it is embedded verbatim in the guide's `origin` (`file:{format}:{path}`)
192
- // and parsed back out to place the file on disk. The writer that does so
193
- // is now the docs phase's projection resolver
194
- // (`packages/cli/src/artifacts/guide-projection.ts`), which rejects anything
195
- // absolute, traversing or uncontained — so an unsafe path stores a guide
196
- // that can never round-trip. (`mossbear guides export` was the original
197
- // writer and skipped such a path *silently*; it was deleted by
198
- // `unified-item-sync` Slice 5.);
199
- // - it is stored as `guide_files.path`, the column import reconciles on
200
- // (`guide-versioned-identity-plan.md` → Decision 4), and identity must
201
- // not be keyable on a value the exporter refuses to honour.
202
- path: SafeRelativePosixPathSchema,
203
- // Which discovery root `path` is relative to — `guide-versioned-identity-plan.md`
204
- // → Decision 6. Without it, `(repoId, path)` collapses a project skill onto
205
- // its `~/.claude/skills` twin: `.claude/skills` is in both of the CLI's root
206
- // lists and both scans emit the same relative string, while `repoId` is
207
- // envelope-level so both files carry the same one.
208
- //
209
- // **Optional, and its absence is not an error** — a CLI predating this field
210
- // sends none, exactly as it may send no `repoId`. A payload missing either
211
- // does not participate in reconciliation and keeps the content-hash insert
212
- // behaviour it was created under, rather than being defaulted to `'project'`:
213
- // guessing would let an old client's `--global` file adopt a project row.
214
- root: v.optional(GuideDiscoveryRootSchema),
215
- format: GuideFileFormatSchema,
216
- rawContent: BoundedRawContentSchema,
217
- lastModified: v.pipe(v.number(), v.integer(), v.minValue(0)),
218
- content_hash: Sha256HexSchema,
219
- // Only meaningful on `skill-md` payloads. `[]` asserts the skill has no
220
- // member files (stale synced rows are removed server-side); omitting the
221
- // field means "no member information" and leaves member rows untouched.
222
- // No CLI caller omits it today — every sender reaches this schema through
223
- // a directory scan that populates it — but the distinction is load-bearing
224
- // on the wire and must not collapse: reading an absent `members` as an
225
- // empty skill would hard-delete a client's member rows.
226
- members: v.optional(v.pipe(v.array(RawSkillMemberFileSchema), v.maxLength(MAX_SKILL_MEMBER_FILES))),
227
- /**
228
- * The body-item version this machine last agreed with the server about for
229
- * this `(scope, root, path)` — the machine-local baseline
230
- * (`guide-versioned-identity-plan.md` → slice 2b-B, D10 in
231
- * `context-bundle-authoring-plan.md`).
232
- *
233
- * It is the *client* half of the reconcile precondition, and it exists to
234
- * answer a question the server cannot: whether the bytes on this disk were
235
- * edited **from** the version the server currently holds, or from an older
236
- * one. The server-only guard shipped in 2b-A can see that a dashboard edit
237
- * exists, never that this machine has already seen it — so a guide the
238
- * dashboard edited and the user then re-synced to disk forks forever.
239
- *
240
- * **Optional, and its absence is not an error.** A CLI predating the
241
- * baseline store, a fresh machine, or a deleted `~/.mossbear/state/` sends
242
- * none, and the payload falls back to the server-only guard exactly as it
243
- * behaves today. Absence therefore degrades to "decline and fork", never to
244
- * an overwrite; a *stale* value degrades to a reported conflict.
245
- */
246
- expectedVersion: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
247
- // Only alongside `members`: member paths present on disk but not imported
248
- // this run. The server must NOT treat their absence from `members` as
249
- // removal — a transiently unreadable or newly-oversized file would
250
- // otherwise hard-delete its previously synced row.
251
- skippedMemberPaths: v.optional(v.pipe(v.array(SkippedMemberPathSchema), v.maxLength(MAX_SKILL_SKIPPED_MEMBER_PATHS))),
252
- }), v.check((payload) => payload.members === undefined || payload.format === 'skill-md', 'members are only supported on skill-md payloads'), v.check((payload) => payload.skippedMemberPaths === undefined || payload.members !== undefined, 'skippedMemberPaths requires members'),
253
- // Case-insensitive uniqueness: the export round-trip re-creates these files
254
- // on disk, where the default macOS/Windows filesystems fold case — two
255
- // members differing only by case would silently overwrite each other.
256
- v.check((payload) => payload.members === undefined ||
257
- new Set(payload.members.map((member) => member.path.toLowerCase())).size ===
258
- payload.members.length, 'member paths must be unique (case-insensitive)'));
259
- /** Max number of rules accepted in a single `POST /api/rules/import` request. */
260
- export const MAX_RULES_IMPORT_BATCH = 100;
261
- /** Opaque checkout digest shared by run logs, manifests, and `runs.repo_id`. */
262
- export const RepoIdSchema = v.pipe(v.string(), v.regex(/^repo_[0-9a-f]{32}$/, 'repoId must be repo_ followed by 32 hex chars'));
263
76
  /**
264
77
  * A checkout's committed `project.id` as a context write declares it: trimmed
265
78
  * and non-empty, exactly the rule the CLI's config reader applies — and no
@@ -272,391 +85,9 @@ export const RepoIdSchema = v.pipe(v.string(), v.regex(/^repo_[0-9a-f]{32}$/, 'r
272
85
  * on it would read as foreign in every repo.
273
86
  */
274
87
  export const DeclaredProjectIdSchema = v.pipe(v.string(), v.trim(), v.minLength(1));
275
- /** Longest accepted `workspaceId`. Server-minted ids are `nanoid()`; this bounds a hand-edited one. */
276
- const MAX_WORKSPACE_ID_LENGTH = 128;
277
- /**
278
- * The workspace a repo declares its project-scoped guidance belongs to. See
279
- * `RulesImportRequestSchema.workspaceId`.
280
- *
281
- * Same shape as {@link ProjectIdSchema}, and for the same reason: the id is
282
- * minted by the server (`nanoid()`, whose alphabet this character class covers)
283
- * but it reaches us out of a **committed, hand-editable** file, so it is
284
- * constrained only as far as it must be to serve as a lookup key — no
285
- * whitespace, no path separators, no control characters, bounded length.
286
- * Whether it names a workspace this caller may reach is a membership question,
287
- * answered against the database, not a question a regex can answer.
288
- */
289
- export const WorkspaceIdSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_WORKSPACE_ID_LENGTH), v.regex(/^[A-Za-z0-9_.-]+$/, 'workspaceId must contain only letters, digits, underscore, dot or hyphen'));
290
- // Envelope-only schema: caps request shape/size before the per-item
291
- // parseRawGuideFilePayload loop validates each rule in detail, which is what
292
- // preserves the import route's index-aware error reporting.
293
- export const RulesImportRequestSchema = v.object({
294
- rules: v.pipe(v.array(v.unknown()), v.maxLength(MAX_RULES_IMPORT_BATCH)),
295
- /**
296
- * Which checkout these files came from — the same opaque digest the hook and
297
- * the rule manifest already carry (`packages/cli/src/repo-id.ts`,
298
- * `RuleManifestSchema.repoId`). Envelope-level, not per-file: every file in
299
- * one import comes from one repo, and the per-file payload stays lean (the
300
- * "Import endpoint payload" resolved decision).
301
- *
302
- * It is what lets the server reconcile an edited file back onto the guide it
303
- * already created instead of inserting a second one. `origin` alone cannot:
304
- * it is `file:{format}:{path}` with no repo component, so two checkouts
305
- * sharing `.agents/code-style.md` would collide.
306
- *
307
- * **Optional, and its absence is not an error.** A CLI predating this field
308
- * sends none, and the server falls back to the content-hash dedupe it always
309
- * used. Never send a repo id derived anywhere but `repoIdFromRoot` — the
310
- * digest is keyed by a machine-local secret precisely so the server never
311
- * learns a path.
312
- *
313
- * Shaped by the canonical `RepoIdSchema` (shared with run logs and manifests)
314
- * rather than a looser local check: a row storing anything but
315
- * a real digest could never match one, so a malformed identity has to be
316
- * rejected at the boundary instead of persisted as a permanent orphan.
317
- */
318
- repoId: v.optional(RepoIdSchema),
319
- /**
320
- * The repo's **portable** identity — `project.id` from the committed
321
- * `<repo>/.mossbear/config.json` (`guide-write-side-identity` slice 1, shipped in
322
- * #540). This is what makes `(scope, path)` reconciliation portable, and it is
323
- * the field `unified-item-sync` slice 2 exists to put on the wire.
324
- *
325
- * **Why `repoId` is not enough, even though it is already here.**
326
- * `repoIdFromRoot` is an HMAC keyed by a machine-local secret
327
- * (`packages/cli/src/repo-id.ts`), so the same checkout on two machines — or
328
- * one teammate's clone versus another's — produces two different digests. A
329
- * guide reconciled on it therefore forks the moment anyone else edits the
330
- * file, which is the one-way trip this item is closing. `projectId` is
331
- * declared in a committed file, so every clone agrees on it.
332
- *
333
- * **Optional, and its absence is not an error.** A CLI predating this field
334
- * sends none and the server falls back to `repoId` scoping, which is exactly
335
- * the behaviour those clients already have. A repo that has never run
336
- * `mossbear init` also has no declaration, and must keep importing.
337
- *
338
- * Deliberately looser than `RepoIdSchema`: a generated id is
339
- * `proj_`+hex, but a *declared* one is whatever a human committed —
340
- * `readRepoProjectId` accepts any non-empty trimmed string
341
- * (`packages/cli/src/artifacts/repo-config.ts`), and rejecting those here would
342
- * break a shipped contract. Constrained only as far as it must be to serve as
343
- * a storage key: no whitespace, no path separators, no control characters,
344
- * bounded length.
345
- */
346
- projectId: v.optional(ProjectIdSchema),
347
- /**
348
- * The workspace this repo declares its project-scoped guidance belongs to —
349
- * `workspace.id` from the committed `<repo>/.mossbear/config.json`
350
- * (`workspace-declaration` slice 1).
351
- *
352
- * **What it changes: which of the caller's workspaces a project path resolves
353
- * in.** Import identity is already scoped by workspace *membership* rather
354
- * than authorship, so a caller in several workspaces has several candidate
355
- * rows at one `(project, root, path)` and the resolver picked between them by
356
- * row age. The declaration is the narrower lookup that removes the guess, and
357
- * it is committed so every clone of the repo narrows the same way.
358
- *
359
- * **Membership stays the boundary; this only narrows inside it.** The
360
- * declaration cannot widen what a caller may reach: a workspace they are not a
361
- * member of is refused by name rather than resolved, and never quietly
362
- * replaced by their personal one — falling back would recreate the fork the
363
- * declaration exists to close.
364
- *
365
- * **Envelope-level, and never sent on a global batch.** It is the *repo's*
366
- * declaration, so it travels with the same batch that carries `repoId` and
367
- * `projectId`; a `root: 'global'` file belongs to no checkout and to no
368
- * project, and by the same rule to no repo-declared workspace.
369
- *
370
- * **Optional, and its absence is not an error.** A CLI predating this field
371
- * sends none, and a repo that has never declared one has none to send; both
372
- * keep the resolution they have today.
373
- */
374
- workspaceId: v.optional(WorkspaceIdSchema),
375
- });
376
- /**
377
- * What the server did with one payload, reported per file so the CLI can update
378
- * its machine-local baseline (`guide-versioned-identity-plan.md` → slice 2b-B).
379
- *
380
- * The distinction that matters is not "did something change" but **do disk and
381
- * server now agree**: `imported`, `updated` and `skipped` all mean they do, and
382
- * only those license recording a new baseline. `conflict` means the disk bytes
383
- * did *not* land — recording the server's version for one would hand the next
384
- * import a matching `expectedVersion` and turn a refused overwrite into an
385
- * automatic one on the following run, which is the failure this whole precondition
386
- * exists to prevent.
387
- */
388
- export const GuideImportOutcomeSchema = v.picklist([
389
- 'imported',
390
- 'updated',
391
- 'skipped',
392
- 'conflict',
393
- ]);
394
- /**
395
- * Per-payload import outcome, addressed by the same `(root, path)` pair the
396
- * server reconciles on so the CLI can key its baseline identically without
397
- * re-deriving anything.
398
- *
399
- * `version` is the body item's version **as the server holds it after this
400
- * request** — the value a later import should send as `expectedVersion` once
401
- * disk and server agree. It is reported for a `conflict` too, deliberately: the
402
- * conflict report needs it to offer explicit resolution, and reporting it is not
403
- * the same as recording it.
404
- *
405
- * Entries are omitted for a payload the server could not address at all (no
406
- * `root`, or a pre-R0 row): there is no identity to key a baseline on, and
407
- * inventing one would let a later import claim a precondition it never observed.
408
- */
409
- export const GuideImportResultSchema = v.object({
410
- /** Canonical guide identity for review links; absent on older servers. */
411
- guideId: v.optional(NonEmptyStringSchema),
412
- root: GuideDiscoveryRootSchema,
413
- path: SafeRelativePosixPathSchema,
414
- outcome: GuideImportOutcomeSchema,
415
- version: v.pipe(v.number(), v.integer(), v.minValue(1)),
416
- });
417
- /** Max alias sets one import response reports as divergent. */
418
- export const MAX_GUIDE_IMPORT_DIVERGENCES = 64;
419
- /**
420
- * An alias set the server found in one import but **did not** collapse, because
421
- * the files do not hold the same rules
422
- * (`alias-instruction-file-identity-plan.md` → second addendum,
423
- * 2026-09-03).
424
- *
425
- * Reporting rather than refusing is the whole point. An identical
426
- * `AGENTS.md`/`.cursorrules` pair becomes one guide; a divergent one imports as
427
- * two guides exactly as it does today, and this names the paths so the user can
428
- * see the drift the product would otherwise have kept silent. Nothing about the
429
- * import fails, and nothing the user does today stops working.
430
- *
431
- * `paths` carries every path in the set this request saw, in the order the
432
- * server ranks them — so the first is the one that would have kept the body had
433
- * they matched.
434
- */
435
- export const GuideImportDivergenceSchema = v.object({
436
- root: GuideDiscoveryRootSchema,
437
- paths: v.pipe(v.array(SafeRelativePosixPathSchema), v.minLength(2)),
438
- });
439
- /**
440
- * An alias pair one import left as **two guides**, because a guide was already
441
- * stored at the incoming file's alias partner path and the pair could not be
442
- * collapsed onto it (`skill-alias-collapse-managed-file-plan.md` →
443
- * *Reporting*).
444
- *
445
- * Distinct from {@link GuideImportDivergenceSchema}, which says the files
446
- * differ. This one says only that the fork happened — the reasons are several
447
- * (the bodies differ, the skill directories around them could not be proven to
448
- * match, the partner path already answers to a second guide) and the import
449
- * cannot always tell them apart, so it names the pair and leaves the reading to
450
- * whoever wrote the files. Reported only when a guide was *created* at the
451
- * incoming path, so a repo re-importing a pair that forked long ago stays
452
- * quiet.
453
- *
454
- * `paths` is the incoming file first, then the partner already stored.
455
- */
456
- export const GuideImportAliasForkSchema = v.object({
457
- root: GuideDiscoveryRootSchema,
458
- paths: v.pipe(v.array(SafeRelativePosixPathSchema), v.minLength(2)),
459
- });
460
- // ---------------------------------------------------------------------------
461
- // `mossbear unlink` — un-enrol a guide from the default bundle
462
- // ---------------------------------------------------------------------------
463
- /**
464
- * One guide to stop delivering, addressed the way the **import** route already
465
- * resolves an existing guide: `(root, path)` plus the envelope's checkout and
466
- * project identity.
467
- *
468
- * **Deliberately not `origin`.** `file:{format}:{path}` is not unique — every
469
- * repo has an `AGENTS.md`, so an origin-keyed request disables the matching
470
- * guide in every repo in the workspace. That is the defect that sank the first
471
- * implementation of this verb. `(root, path)` scoped by `repoId`/`projectId`
472
- * is the key the import route reconciles on, so unlink addresses exactly the
473
- * row link created and no other.
474
- */
475
- export const RawGuideUnlinkSchema = v.object({
476
- root: GuideDiscoveryRootSchema,
477
- /**
478
- * The canonical guide-path validator, not a fresh `v.string()`: it already
479
- * rejects absolute paths, control characters and `..` traversal, and a second
480
- * hand-rolled constraint here would be a place for the two to disagree.
481
- */
482
- path: SafeRelativePosixPathSchema,
483
- });
484
- /** Max guides accepted in a single `POST /api/rules/unlink` request. */
485
- export const MAX_RULE_UNLINK_BATCH = 500;
486
- export const RuleUnlinkRequestSchema = v.object({
487
- unlinks: v.pipe(v.array(RawGuideUnlinkSchema), v.maxLength(MAX_RULE_UNLINK_BATCH)),
488
- /** Same envelope identity the import route carries, and for the same reason. */
489
- repoId: v.optional(v.string()),
490
- projectId: v.optional(v.string()),
491
- });
492
- /**
493
- * `unlinked` counts guides removed from the default bundle; `skipped` counts
494
- * requested paths that resolved to nothing, or were already out of it.
495
- *
496
- * `stillDelivered` names guides that remain in *other* bundles the caller can
497
- * reach — including a teammate's, since a bundle shared into a workspace they
498
- * belong to keeps arriving whoever owns it. Unlink is the exact inverse of what
499
- * link does — it removes the default-bundle membership link created — so a
500
- * guide someone deliberately added to a curated bundle stays there, and saying
501
- * so is the difference between a true report and a reassuring one.
502
- *
503
- * `released` names the requested paths whose guide is now in **no** bundle the
504
- * caller can reach, so nothing delivers it any more. It exists because the
505
- * caller holds a fact the server does not: the local placement record that
506
- * marks a path as managed by a bundle. A path taken out of every bundle and
507
- * still recorded as bundle-managed is two answers to one question, and only the
508
- * server can tell which paths genuinely stopped being delivered. Note this is
509
- * not on its own enough to make a re-link restore delivery — the import route
510
- * enrols only the guide rows its insert creates — so a caller acting on this
511
- * should not report the path as re-adoptable.
512
- *
513
- * Optional with an empty default, so a client on this version still parses a
514
- * response from a deployment that predates the field.
515
- */
516
- export const RuleUnlinkResponseSchema = v.object({
517
- unlinked: v.number(),
518
- skipped: v.number(),
519
- stillDelivered: v.array(v.string()),
520
- released: v.optional(v.array(RawGuideUnlinkSchema), []),
521
- });
522
- export function parseRuleUnlinkRequest(data) {
523
- return v.parse(RuleUnlinkRequestSchema, data);
524
- }
525
88
  // ---------------------------------------------------------------------------
526
- // Display names
89
+ // Workspace listing
527
90
  // ---------------------------------------------------------------------------
528
- /**
529
- * The sentence a caller gets back when a display name carries a character that
530
- * cannot be seen. It is written for the person who typed the name, not for the
531
- * developer reading the schema. This repo's error-message rules put the
532
- * reader first, keep the blame off them, and ask a refusal to leave them
533
- * something to do — so the action leads and "control character",
534
- * which is not a phrase most people can act on, never appears.
535
- *
536
- * "often" is doing real work in the second clause. This branch cannot tell a
537
- * pasted name from a typed one, so it does not claim to; it names
538
- * where such characters usually come from, which is what makes the advice
539
- * actionable without overclaiming.
540
- */
541
- export const DISPLAY_NAME_CONTROL_CHARACTER_MESSAGE = 'Remove the invisible characters from this name — copying text from another app often brings them along.';
542
- /**
543
- * A user-typed display name that is safe to print into a terminal line.
544
- *
545
- * Refuses every character in {@link DISPLAY_NAME_REFUSED_CHARACTERS}
546
- * (`bundleSlug.ts`, where the class is defined once and explained): the control
547
- * characters, where ESC and CR live — a CR can overwrite the line a user is
548
- * reading, which in a tool whose job is reporting what reached their agents
549
- * means the sentence on screen can be made to say something other than what
550
- * happened — and the explicit bidi controls, which reorder a rendered line
551
- * without changing a byte of it. The rest of `\p{Cf}` is admitted: the
552
- * zero-width joiners Persian, Hindi and Bengali need, the join inside a
553
- * multi-person emoji, a soft hyphen. Sharing the class with `displayable` is
554
- * what keeps the boundary and the derivation saying the same thing.
555
- *
556
- * **Refuse, never strip.** A user typing a name is present and can be told;
557
- * rewriting their input silently is what those same rules argue against. The
558
- * one strip in the codebase — `displayable`, reached through
559
- * `defaultGuidesBundleFor` in `bundleSlug.ts` — is a *derivation* with no user
560
- * to report to, which is the exception that fixes the rule rather than a
561
- * precedent for a second one.
562
- *
563
- * **Then requires one character outside `\p{Cf}`.** Admitting the joiners
564
- * admits a name made of nothing but them, which `v.trim()` cannot see and
565
- * `minLength(1)` counts. Such a name is refused as empty, with the same
566
- * sentence — to the person typing it, it is a name of invisible characters
567
- * either way.
568
- *
569
- * **A factory, because the max length is per-field** (64 for a workspace name,
570
- * 200 for a bundle name) while the character rule is not. Exported rather than
571
- * inlined so a fourth display-name field meets the rule while reading its
572
- * neighbours — nothing enforces that it is called.
573
- */
574
- export function displayNameSchema(maxLength) {
575
- return v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(maxLength), v.check((name) => !DISPLAY_NAME_REFUSED_CHARACTERS.test(name), DISPLAY_NAME_CONTROL_CHARACTER_MESSAGE), v.regex(/\P{Cf}/u, DISPLAY_NAME_CONTROL_CHARACTER_MESSAGE));
576
- }
577
- /** A bundle's display name. Bundles are addressed by slug; this is the label. */
578
- export const BUNDLE_NAME_MAX_LENGTH = 200;
579
- // ---------------------------------------------------------------------------
580
- // Context bundle schemas
581
- // ---------------------------------------------------------------------------
582
- // url-safe slug, unique per user. Lowercase alphanumerics + hyphens, must start
583
- // with an alphanumeric so it reads cleanly in a URL/path.
584
- export const BundleSlugSchema = v.pipe(v.string(), v.check(isBundleSlug, 'slug must be lowercase alphanumeric with hyphens, at most 64 characters'));
585
- /**
586
- * A publisher's lowercase handle: the prefix of a published bundle's address,
587
- * `<handle>/<slug>` (`mossbear/guides`). Slugs are unique per workspace, so a
588
- * bare slug names one of the caller's own bundles and a published bundle is
589
- * named through its publisher.
590
- */
591
- export const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,38}$/;
592
- export const PublisherHandleSchema = v.pipe(v.string(), v.regex(PUBLISHER_HANDLE_PATTERN, 'handle must be lowercase alphanumeric with hyphens'));
593
- /** The longest publisher name a reader is shown. */
594
- export const PUBLISHER_NAME_MAX_LENGTH = 100;
595
- /**
596
- * Who publishes a bundle, as a reader sees it. Present only on a bundle that is
597
- * published; absent is the ordinary case, a bundle of the caller's own.
598
- */
599
- export const BundlePublisherSchema = v.object({
600
- name: v.pipe(v.string(), v.maxLength(PUBLISHER_NAME_MAX_LENGTH)),
601
- handle: PublisherHandleSchema,
602
- });
603
- /** A published bundle's address, `<handle>/<slug>`. */
604
- export const PublishedBundleAddressSchema = v.pipe(v.string(), v.maxLength(104), v.check((value) => {
605
- const at = value.indexOf('/');
606
- if (at <= 0)
607
- return false;
608
- return (PUBLISHER_HANDLE_PATTERN.test(value.slice(0, at)) &&
609
- isBundleSlug(value.slice(at + 1)));
610
- }, 'address must be <publisher handle>/<bundle slug>'));
611
- /**
612
- * The two marks a subscribed bundle carries wherever it is listed: who
613
- * publishes it, and that the caller may read it but not write it. `readOnly`
614
- * is sent only as `true`, for a caller that reaches the bundle by publication
615
- * rather than membership; the publisher's own members edit it as any bundle.
616
- * Both optional, so a CLI built before them parses a new server unchanged.
617
- */
618
- const publishedBundleMarks = {
619
- publisher: v.optional(BundlePublisherSchema),
620
- readOnly: v.optional(v.literal(true)),
621
- };
622
- /**
623
- * An artifact's description as a writer sends it: one paragraph of plain text,
624
- * with no line breaks or other control characters, so it saves on Enter like a
625
- * title, prints safely in a terminal, and stays a plain YAML
626
- * scalar in a Markdown artifact's frontmatter. Blank text is refused rather than
627
- * stored: `null` is how a description is cleared, so "none" has one shape.
628
- */
629
- export const ArtifactDescriptionSchema = v.pipe(v.string(),
630
- // Blank includes text made only of invisible format characters, which
631
- // `trim` cannot see, as `displayNameSchema` refuses a name of them.
632
- v.regex(/[^\s\p{Cf}]/u, 'description must not be blank'), v.maxLength(MAX_ARTIFACT_DESCRIPTION_CHARS, `description must be at most ${MAX_ARTIFACT_DESCRIPTION_CHARS} characters`),
633
- // The display-name class (control characters and the bidi controls, which
634
- // reorder a printed line), plus the two Unicode line breaks: one line, and
635
- // nothing a terminal printing it would act on.
636
- v.check((value) => !DISPLAY_NAME_REFUSED_CHARACTERS.test(value) && !/[\u2028\u2029]/.test(value), 'description must be one line of text, with no control characters'));
637
- export const BundleSchema = v.object({
638
- id: v.string(),
639
- slug: BundleSlugSchema,
640
- name: v.string(),
641
- createdAt: v.string(),
642
- description: v.optional(v.nullable(v.string())),
643
- ...publishedBundleMarks,
644
- /**
645
- * The project id of the repo that owns this bundle's items, when one claims it
646
- * (`subscription-delivery-target-plan.md` → slice 3). Absent is the ordinary
647
- * case: a bundle with no home is edited wherever its owner likes.
648
- *
649
- * A home makes the named checkout the only writer — a PR there is the review
650
- * — and every other writer, the dashboard included, is refused by name.
651
- *
652
- * Optional rather than nullable so a CLI built before this field parses a new
653
- * server's listing unchanged.
654
- */
655
- home: v.optional(v.string()),
656
- });
657
- export const BundleListResponseSchema = v.object({
658
- bundles: v.array(BundleSchema),
659
- });
660
91
  /**
661
92
  * One workspace the caller belongs to, as `GET /api/v1/workspaces` returns it.
662
93
  *
@@ -675,243 +106,6 @@ export const WorkspaceSummarySchema = v.object({
675
106
  export const WorkspaceListResponseSchema = v.object({
676
107
  workspaces: v.array(WorkspaceSummarySchema),
677
108
  });
678
- /**
679
- * How a bundle reaches a repo. Two scopes and no third:
680
- *
681
- * - `repo` — named by the committed `.mossbear/config.json`, shared with
682
- * teammates by `git clone`.
683
- * - `user` — recorded against the account, private, and on every machine.
684
- *
685
- * A bundle both scopes name carries **both** labels. An earlier shape reported a
686
- * single winning `scope`, which made `status` and `doctor` — both of which count
687
- * the account's subscriptions by filtering for `user` — report zero for a bundle
688
- * that is genuinely subscribed at the account level and will keep delivering to
689
- * every other repo. The scopes are not mutually exclusive, so the wire shape
690
- * must not say they are. Raised by Codex on #735.
691
- */
692
- export const SubscriptionScopeSchema = v.picklist(['repo', 'user']);
693
- /**
694
- * Where a subscription's items are delivered, independent of where their source
695
- * lives (`subscription-delivery-target-plan.md` → slice 2).
696
- *
697
- * - `repo` — land at the item's path in the checkout doing the sync, under the
698
- * same git-owned write rule every project item obeys.
699
- * - `global` — land in the machine-global namespace, unattended.
700
- *
701
- * **Absent is not a third value.** A subscription that names no target routes on
702
- * the item's own `root`, which is what every subscription meant before this
703
- * field existed — so the column and the config key are both nullable and the
704
- * default bundle keeps behaving exactly as it does today.
705
- */
706
- export const DeliverTargetSchema = v.picklist(['repo', 'global']);
707
- export const ResolvedSubscriptionSchema = v.object({
708
- id: v.string(),
709
- slug: BundleSlugSchema,
710
- name: v.string(),
711
- /** Every scope that names this bundle. Never empty; may hold both. */
712
- scopes: v.pipe(v.array(SubscriptionScopeSchema), v.minLength(1)),
713
- /**
714
- * The **account** subscription's delivery target, when there is an account
715
- * subscription and it names one.
716
- *
717
- * Only the account side, and deliberately so: the repo side's target lives in
718
- * the committed `.mossbear/config.json` on the caller's own disk, which the
719
- * server cannot read — the same asymmetry that makes this endpoint a round
720
- * trip at all. Echoing a value the caller just sent would make the server look
721
- * like the authority on a fact it does not hold. The caller pairs this with
722
- * its own committed `deliver` to build the per-scope target set
723
- * (`packages/cli/src/artifacts/delivery.ts` → `deliveryBundles`).
724
- *
725
- * Optional rather than nullable so a CLI built before this field parses a new
726
- * server's response unchanged, and a new CLI reads an old server's response as
727
- * "names no target" — which is the absent-field default either way.
728
- */
729
- deliver: v.optional(DeliverTargetSchema),
730
- /**
731
- * The bundle's home repo, when one claims it. Sent on every resolved
732
- * subscription regardless of scope, because it is a property of the *bundle*
733
- * rather than of either subscription — unlike `deliver`, which each scope
734
- * answers for itself.
735
- */
736
- home: v.optional(v.string()),
737
- /**
738
- * Ids this account has switched off for the asking machine, on a bundle that
739
- * reaches it through the account subscription alone. An item whose own id or
740
- * `guideId` is listed is not delivered.
741
- *
742
- * The server computes it per machine: artifacts switched off everywhere or
743
- * on this machine that this bundle can deliver, plus every member when the
744
- * bundle itself is switched off. Account-scoped and nowhere else: a repo
745
- * subscription is a committed file shared by everyone who clones it, so a
746
- * mute there would be one member deciding for the team. A muted guide leaves
747
- * the desired delivery list, and the global namespace prunes it once no repo
748
- * still refers to it — repo by repo, as each syncs, because the referrer
749
- * record is machine-local repo ids.
750
- */
751
- muted: v.optional(v.array(v.string())),
752
- /**
753
- * The same set as `muted`, sent instead of it when the calling repo's
754
- * committed config also subscribes this bundle. It applies to the account
755
- * target only: the repo's own subscription still delivers into the checkout,
756
- * because an off removes only what reaches the machine through the account.
757
- *
758
- * A separate key rather than `muted`, because a CLI that predates it applies
759
- * `muted` before either target is planned and would drop the repo delivery
760
- * too. That CLI ignores this key and delivers to both targets, which fails
761
- * toward the agent having the content.
762
- */
763
- accountMuted: v.optional(v.array(v.string())),
764
- ...publishedBundleMarks,
765
- /**
766
- * The address this bundle was resolved from, when the caller named it as
767
- * `<handle>/<slug>` in `repoBundleAddresses` rather than by id. Lets the
768
- * caller pair each committed address with the id it stands for.
769
- */
770
- address: v.optional(PublishedBundleAddressSchema),
771
- });
772
- /**
773
- * The ids a repo's committed config names. Sent rather than looked up, because
774
- * the committed file is on the caller's disk and the server has no way to read
775
- * it — that asymmetry is the whole reason delivery used to be written back into
776
- * the repo.
777
- */
778
- /**
779
- * Capped, like the other batch endpoints. The route expands this into
780
- * `inArray(bundles.id, …)`, one Postgres bind parameter per id, and the wire
781
- * protocol tops out at 65,535 of them — so an uncapped array lets a body well
782
- * under the request-size limit reach the database and fail as a 500 rather than
783
- * being refused as bad input. Raised by Codex on #735.
784
- */
785
- export const MAX_REPO_BUNDLE_IDS = 500;
786
- /** Capped for the reason `MAX_REPO_BUNDLE_IDS` gives. */
787
- export const MAX_REPO_BUNDLE_ADDRESSES = 64;
788
- export const ResolveSubscriptionsRequestSchema = v.object({
789
- repoBundleIds: v.pipe(v.array(v.string()), v.maxLength(MAX_REPO_BUNDLE_IDS)),
790
- /**
791
- * Published bundles the committed config names by address,
792
- * `<handle>/<slug>`, rather than by id. Optional, so a CLI that sends only
793
- * ids is answered as before.
794
- */
795
- repoBundleAddresses: v.optional(v.pipe(v.array(PublishedBundleAddressSchema), v.maxLength(MAX_REPO_BUNDLE_ADDRESSES))),
796
- /**
797
- * The calling machine's stable id (`MachineIdSchema`). Optional, so an older
798
- * CLI is answered as before; the server records it for the calling key only
799
- * when that key has none yet.
800
- */
801
- machineId: v.optional(MachineIdSchema),
802
- });
803
- export const ResolveSubscriptionsResponseSchema = v.object({
804
- /** The effective delivery set, de-duplicated by bundle id. */
805
- bundles: v.array(ResolvedSubscriptionSchema),
806
- /**
807
- * Committed ids the caller cannot see. **Reported, never dropped** — the line
808
- * was put in the config deliberately by whoever owns the repo, so a non-member
809
- * gets a named failure rather than deletion advice.
810
- *
811
- * It also names the caller's **account** subscriptions whose bundle they can
812
- * no longer read: one unpublished, or in a workspace they left. The row is
813
- * still theirs, so a sync must hold retirement for it as for a repo id it
814
- * cannot see, rather than read its absence as an empty bundle.
815
- */
816
- unresolved: v.array(v.object({ id: v.string() })),
817
- /**
818
- * Committed addresses (`repoBundleAddresses`) that name no published bundle.
819
- * Kept apart from `unresolved`, whose entries are ids, so a CLI that reads
820
- * `id` off every entry is never handed one without it. Absent when the
821
- * request named no address.
822
- */
823
- unresolvedAddresses: v.optional(v.array(v.object({ address: PublishedBundleAddressSchema }))),
824
- /**
825
- * Account-level settings the sync needs, carried on the response every sync
826
- * already fetches rather than on a request of their own.
827
- *
828
- * `deliverGlobalSkills` is the account's "Deliver my global skills" switch:
829
- * whether guides scoped to every repo may be written to the global skills
830
- * directories of every machine and cloud session this account syncs. Only a
831
- * signed-in browser session can change it; it is reported here, never
832
- * accepted. **Optional**, so a response from a server that predates it parses,
833
- * and the CLI reads its absence as "the server did not say", which delivers
834
- * nothing and removes nothing.
835
- */
836
- account: v.optional(v.object({
837
- deliverGlobalSkills: v.boolean(),
838
- })),
839
- /**
840
- * True when the caller's token is limited to certain bundles. Such a token
841
- * resolves only what it was granted, so an id in `unresolved` may be a bundle
842
- * the account can reach and the token cannot. Said once for the response,
843
- * never per id, so it confirms nothing about any one bundle. Optional: absent
844
- * means an ordinary token, and a server that predates it never sends it.
845
- */
846
- limitedToken: v.optional(v.boolean()),
847
- });
848
- /**
849
- * Subscribe the calling account to a bundle it can see, or change the delivery
850
- * target of a subscription it already has.
851
- *
852
- * **The product path to a non-default bundle** (`subscription-delivery-target-plan.md`
853
- * → slice 2). Before this, the only insert into `user_bundle_subscriptions` was
854
- * the one that mints an account's own capture bundle, so an account could not
855
- * subscribe to anything else without a hand-written row.
856
- *
857
- * Idempotent by the table's composite key: subscribing twice is one
858
- * subscription, and a second call carrying a different `deliver` updates it
859
- * rather than failing.
860
- */
861
- /** No account should be able to make one sync unboundedly expensive. */
862
- export const MAX_MUTED_GUIDE_IDS = 1000;
863
- export const SubscribeBundleRequestSchema = v.object({
864
- bundleId: v.string(),
865
- /**
866
- * Where this account's subscription delivers. **Three states, and all three
867
- * are reachable**: a value sets the target, an explicit `null` clears it back
868
- * to "route on the item's root", and omitting the field leaves whatever is
869
- * stored.
870
- *
871
- * The first shipped version made omission clear the target, so that "route on
872
- * the item's root" would stay reachable. It made a bare re-subscribe — the
873
- * commonest call there is — silently reset routing the caller never mentioned:
874
- * `mossbear pull <bundle> --account` a second time would wipe a target set the
875
- * first time, and print a success line saying nothing about it. Found by the
876
- * automated reviewer on #1246. A nullable field reaches the same state without
877
- * making silence mean a write.
878
- */
879
- deliver: v.optional(v.nullable(DeliverTargetSchema)),
880
- /**
881
- * The ids to have switched off on every machine, as far as this bundle can
882
- * deliver them — the whole set, replacing what is stored. `[]` switches them
883
- * all back on, and omitting the field leaves the stored set alone.
884
- *
885
- * An id switched off here is off for the account, through every bundle that
886
- * carries it. Switching one back on (an id this bundle delivers that is off
887
- * now and absent here) needs a dashboard session: a CLI key is refused with
888
- * 403, because an agent may narrow what it receives but never widen it.
889
- *
890
- * The same three states as `deliver` above, reached the same way: an explicit
891
- * empty clears, and silence never means a write. So changing a delivery target
892
- * cannot unmute anything, and muting cannot move a target.
893
- */
894
- muted: v.optional(v.pipe(v.array(v.string()), v.maxLength(MAX_MUTED_GUIDE_IDS))),
895
- });
896
- export const SubscribeBundleResponseSchema = v.object({
897
- bundleId: v.string(),
898
- /** False when the subscription was already there and only its target moved. */
899
- created: v.boolean(),
900
- deliver: v.optional(DeliverTargetSchema),
901
- /** The stored mute set after this write. Omitted when nothing is muted. */
902
- muted: v.optional(v.array(v.string())),
903
- });
904
- export const CreateBundleRequestSchema = v.object({
905
- description: v.optional(v.nullable(ArtifactDescriptionSchema)),
906
- slug: BundleSlugSchema,
907
- name: displayNameSchema(BUNDLE_NAME_MAX_LENGTH),
908
- // The workspace to create the bundle in. Omitted means the caller's default
909
- // workspace; a workspace the caller is not a member of is refused.
910
- workspaceId: v.optional(v.pipe(v.string(), v.minLength(1))),
911
- });
912
- export const CreateBundleResponseSchema = v.object({
913
- bundle: BundleSchema,
914
- });
915
109
  // Scoped tokens: a CLI key limited to chosen bundles, read or write on each.
916
110
  // The server enforces the limit; a key with no grants listed here is refused.
917
111
  export const SCOPED_TOKEN_MAX_GRANTS = 200;
@@ -950,107 +144,6 @@ export const ListScopedTokensResponseSchema = v.object({
950
144
  export const RevokeScopedTokenRequestSchema = v.object({
951
145
  id: NonEmptyStringSchema,
952
146
  });
953
- // A membership is addressed by the artifact id alone: a guide and its body are
954
- // one id, so no membership kind travels the wire. An older client may still send
955
- // `itemType` on attach (or `?itemType=` on detach); this schema is not strict, so
956
- // the field is dropped on parse rather than refused.
957
- /**
958
- * The member to attach, by its artifact id. `itemId` is the name a CLI from before
959
- * release step 2 sends; both are read, and the parsed value is always `artifactId`.
960
- * Drop `itemId` once no such CLI is left to send it.
961
- */
962
- /** The most artifacts one attach request may name. */
963
- export const MAX_BUNDLE_MEMBERS_PER_ATTACH = 200;
964
- export const AttachBundleMemberRequestSchema = v.pipe(v.object({
965
- artifactId: v.optional(v.pipe(v.string(), v.minLength(1))),
966
- itemId: v.optional(v.pipe(v.string(), v.minLength(1))),
967
- // A list files them in one request and is answered per id, once for a
968
- // repeated id (match results by `artifactId`, not by position)
969
- // (`AttachBundleMembersResponseSchema`). The single-id forms keep their
970
- // body and their `{ attached }` answer for CLIs that predate the list.
971
- artifactIds: v.optional(v.pipe(v.array(v.pipe(v.string(), v.minLength(1))),
972
- // Before the cap, so the cap counts distinct artifacts.
973
- v.transform((ids) => [...new Set(ids)]), v.minLength(1), v.maxLength(MAX_BUNDLE_MEMBERS_PER_ATTACH))),
974
- }), v.check((request) => request.artifactIds === undefined
975
- ? request.artifactId !== undefined || request.itemId !== undefined
976
- : request.artifactId === undefined && request.itemId === undefined, 'A member needs an artifactId, or a list of artifactIds on its own.'), v.transform((request) => request.artifactIds
977
- ? { artifactIds: request.artifactIds }
978
- : { artifactId: (request.artifactId ?? request.itemId) }));
979
- export const AttachBundleMemberResponseSchema = v.object({
980
- // False when the item was already a member — attach is idempotent, and the
981
- // caller (multi-select menu applying a diff) treats both as success.
982
- attached: v.boolean(),
983
- });
984
- /**
985
- * One id's outcome in a list attach. `unavailable` is every refusal that is not
986
- * a path collision, and reads the same whether the artifact is missing, not the
987
- * caller's to file or in another workspace, so a list cannot probe which ids
988
- * exist.
989
- */
990
- export const AttachBundleMembersResultSchema = v.object({
991
- artifactId: v.string(),
992
- status: v.picklist(['added', 'already_there', 'unavailable', 'path_taken']),
993
- });
994
- export const AttachBundleMembersResponseSchema = v.object({
995
- results: v.array(AttachBundleMembersResultSchema),
996
- });
997
- export const DetachBundleMemberResponseSchema = v.object({
998
- detached: v.boolean(),
999
- });
1000
- /**
1001
- * The most field keys a bundle's shared column list may hold, and the longest
1002
- * one. A key is a frontmatter key as written, so the bound is on what a
1003
- * dashboard could ever show as a column rather than on any real key's length;
1004
- * both are generous enough that a refusal means a client bug.
1005
- */
1006
- export const BUNDLE_COLUMNS_MAX_COUNT = 100;
1007
- export const BUNDLE_COLUMN_KEY_MAX_LENGTH = 200;
1008
- /**
1009
- * A bundle's shared column list: field keys in display order, no key twice.
1010
- * An array that repeats a key is refused rather than deduplicated, since the
1011
- * order is the content and a client that sent one has lost track of its own
1012
- * list.
1013
- */
1014
- export const BundleColumnsSchema = v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(BUNDLE_COLUMN_KEY_MAX_LENGTH))), v.maxLength(BUNDLE_COLUMNS_MAX_COUNT), v.check((keys) => new Set(keys).size === keys.length, 'columns must not repeat a key'));
1015
- // Rename changes the display name only. The slug is the bundle's identity —
1016
- // repos subscribe by slug in `.mossbear/config.json` → `bundles`, and
1017
- // `mossbear pull <slug>` addresses it — so a slug change would silently break
1018
- // every subscribed repo (context-bundle-authoring-plan.md → D14).
1019
- /**
1020
- * What `PATCH /api/v1/context/bundles/:id` may change: the display name, the
1021
- * home repo, the shared column list, or any of them. The slug stays immutable
1022
- * — repos address a bundle by id and name it by slug, so a slug change would
1023
- * rename a folder in every subscriber's checkout.
1024
- *
1025
- * Every field optional, with a check that at least one is present: a body that
1026
- * changes nothing is a request the caller did not mean to send, and answering it
1027
- * 200 would hide a client bug. `home: null` clears the claim, which is how a
1028
- * repo hands a bundle back — distinct from omitting the field, which leaves it.
1029
- * `columns: null` is the same for the column list: it returns the bundle to
1030
- * "not chosen", where every shared field shows.
1031
- */
1032
- export const UpdateBundleRequestSchema = v.pipe(v.object({
1033
- name: v.optional(displayNameSchema(BUNDLE_NAME_MAX_LENGTH)),
1034
- home: v.optional(v.nullable(v.pipe(v.string(), v.minLength(1), v.maxLength(200)))),
1035
- columns: v.optional(v.nullable(BundleColumnsSchema)),
1036
- description: v.optional(v.nullable(ArtifactDescriptionSchema)),
1037
- }), v.check((value) => value.name !== undefined ||
1038
- value.home !== undefined ||
1039
- value.columns !== undefined ||
1040
- value.description !== undefined, 'name, home, columns or description is required'));
1041
- export const UpdateBundleResponseSchema = v.object({
1042
- bundle: BundleSchema,
1043
- });
1044
- export const DeleteBundleResponseSchema = v.object({
1045
- deleted: v.boolean(),
1046
- // `movedToInbox` was removed in `inbox-as-view` slice 2. Deleting a bundle no
1047
- // longer re-parents anything: an item that loses its last membership is
1048
- // unfiled, which is what the inbox view shows, rather than stranded. The
1049
- // field could only ever have reported 0 afterwards, and a number that can
1050
- // never be non-zero is a discriminator carrying no decision. Nothing on the
1051
- // CLI wire parsed it — `parseDeleteBundleResponse` has one caller, the
1052
- // dashboard's own bundles client.
1053
- });
1054
147
  // ---------------------------------------------------------------------------
1055
148
  // Context item + inbox schemas (context-layer-mcp-inbox-plan.md — Phase 1a)
1056
149
  // ---------------------------------------------------------------------------
@@ -2777,57 +1870,6 @@ export const DashboardGuideSuggestionSchema = v.object({
2777
1870
  export const MAX_SYNC_ACTIONS_BATCH = 500;
2778
1871
  /** Max number of guideSuggestions/runUsage entries per sync request. */
2779
1872
  export const MAX_SYNC_AUX_BATCH = 100;
2780
- /**
2781
- * Max rule files one delivery manifest enumerates. Well above what a real repo
2782
- * carries (this one: ~20), and bounded because the manifest rides every
2783
- * action-carrying batch: an unbounded list would multiply across a chunked
2784
- * sync. Overflow sets `truncated` rather than being dropped silently.
2785
- */
2786
- export const MAX_RULE_MANIFEST_FILES = 500;
2787
- /**
2788
- * A rule file observed on disk in the repo `mossbear report` ran from.
2789
- *
2790
- * `path` is relative to that repo root, in exactly the form `payloadPath`
2791
- * takes at import time (`packages/cli/src/guides/discover.ts`), so
2792
- * `file:{format}:{path}` reconstructs the `origin` the dashboard stored for
2793
- * the guide this file produced. That reconstruction is the whole join; nothing
2794
- * else about the file is needed and nothing else is sent.
2795
- *
2796
- * **Never any content.** `contentHash` is the same sha256 the import payload
2797
- * carries, present so a later slice can tell "delivered" from "delivered but
2798
- * edited since import" without shipping the bytes again.
2799
- */
2800
- export const RuleManifestFileSchema = v.object({
2801
- path: v.pipe(v.string(), v.minLength(1), v.maxLength(512)),
2802
- format: GuideFileFormatSchema,
2803
- contentHash: Sha256HexSchema,
2804
- });
2805
- /**
2806
- * Which rule files were actually on disk in the repo this sync ran from —
2807
- * observed delivery, replacing the assumption that every non-skill active
2808
- * guide reached the agent. Without it, an account with several repos, or a
2809
- * dashboard-authored guide never exported anywhere, is graded against
2810
- * instructions the agent never received.
2811
- *
2812
- * `repoId` is an opaque, machine-local digest — deliberately not a path, a
2813
- * remote URL, or a repo name. Its only job is to keep two checkouts on the
2814
- * same account distinguishable, which is the half of review finding 5 that
2815
- * repo-root-relative origins cannot express: two repos each holding
2816
- * `.claude/skills/review` produce byte-identical origins by construction. See
2817
- * `repoIdFromRoot` (`packages/cli/src/guides/manifest.ts`) for how it is
2818
- * derived and why that derivation is privacy-safe.
2819
- */
2820
- export const RuleFileManifestSchema = v.object({
2821
- repoId: RepoIdSchema,
2822
- files: v.pipe(v.array(RuleManifestFileSchema), v.maxLength(MAX_RULE_MANIFEST_FILES)),
2823
- /**
2824
- * The repo held more rule files than the cap, so `files` is a prefix. Set
2825
- * rather than silently trimmed: a manifest read as complete would mark the
2826
- * omitted files' guides undelivered, which is the exact wrong-verdict
2827
- * failure this field exists to prevent.
2828
- */
2829
- truncated: v.optional(v.boolean()),
2830
- });
2831
1873
  /**
2832
1874
  * Where the checkout stood when a run closed — the git head the `SessionEnd`
2833
1875
  * hook observed, and the branch it was on.
@@ -3248,339 +2290,6 @@ export function isKnownActionType(value) {
3248
2290
  // own output contract there — one shape of that fact, not two packages holding
3249
2291
  // copies that a comment has to keep in step.
3250
2292
  // ---------------------------------------------------------------------------
3251
- // Guide verdict history (guide-history-for-agents)
3252
- // ---------------------------------------------------------------------------
3253
- /**
3254
- * The read an agent makes of a guide's own grading record, so the improvement
3255
- * loop the user already runs in-conversation ("what could be improved in this
3256
- * skill?") has the evidence Mossbear holds and the agent does not.
3257
- *
3258
- * **Evidence out, never instructions out.** Nothing in this contract carries a
3259
- * directive to change anything, and nothing on the server writes as a result of
3260
- * it. It is a read, and the decision stays in the user's conversation.
3261
- */
3262
- /**
3263
- * How the agent names the guide.
3264
- *
3265
- * Either a repo-relative path exactly as the guide file declares it
3266
- * (`.claude/skills/reviewer/SKILL.md`, `AGENTS.md`), or the bare name of a
3267
- * skill (`reviewer`), which the server expands to the skill layouts it knows.
3268
- * Both resolve through the `(root, path)` identity import already reconciles
3269
- * on, rather than a second one invented here.
3270
- *
3271
- * Bounded and shape-checked at the boundary rather than at the query string: it
3272
- * reaches a SQL predicate, and an identifier is not free text.
3273
- */
3274
- export const GuideHistoryIdentifierSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(512), v.check((value) => !/[\u0000-\u001f\u007f]/.test(value), 'guide must not contain control characters'));
3275
- /**
3276
- * The request an agent sends.
3277
- *
3278
- * `root` is optional and is the disambiguator, not decoration: `.claude/skills`
3279
- * is scanned under **both** discovery roots
3280
- * (`packages/cli/src/guides/discover.ts`), so a project skill and its
3281
- * `~/.claude/skills` twin declare the same path string. When the identifier
3282
- * reaches guides under more than one root and no root was given, the server
3283
- * refuses and names both rather than picking one — answering a question about
3284
- * the wrong file's history is worse than not answering it.
3285
- */
3286
- export const GuideHistoryRequestSchema = v.object({
3287
- guide: GuideHistoryIdentifierSchema,
3288
- root: v.optional(GuideDiscoveryRootSchema),
3289
- /**
3290
- * Which repo's copy — **the axis import itself reconciles on**, and the one
3291
- * that actually resolves the common collision.
3292
- *
3293
- * `root` alone does not, and assuming it did was the first version's defect:
3294
- * import's resolution key is `(userId, repoId, root, path)` and two files at
3295
- * one path under different repos deliberately stay two rows. So any
3296
- * user with two repos has two guides at `(project, AGENTS.md)`, and a refusal
3297
- * telling them to pass `root` names the one field that cannot separate those.
3298
- *
3299
- * `projectId` is the portable identity a repo commits and every clone agrees
3300
- * on; `repoId` is the machine-local digest. Both are optional and both are
3301
- * what the caller already sends at import time, so an agent running inside a
3302
- * repo supplies them without being asked.
3303
- */
3304
- projectId: v.optional(NonEmptyStringSchema),
3305
- repoId: v.optional(NonEmptyStringSchema),
3306
- /**
3307
- * The exact guide, when the caller has already been shown the candidates.
3308
- *
3309
- * The escape hatch that makes the refusal always satisfiable: two repos can
3310
- * be indistinguishable to a caller that knows neither id (a guide imported
3311
- * before repo identity was recorded carries neither), and an error whose
3312
- * remedy cannot be carried out is worse than no remedy at all. The 409 names
3313
- * this id for every candidate.
3314
- */
3315
- guideId: v.optional(NonEmptyStringSchema),
3316
- });
3317
- /**
3318
- * One revision of a guide's wording: the body file and the version it stood at.
3319
- *
3320
- * The pair, never a bare version number — `guide_files.version` restarts at 1
3321
- * per row, so a number alone compares equal across two different files.
3322
- */
3323
- export const GuideHistoryRevisionSchema = v.object({
3324
- bodyItemId: NonEmptyStringSchema,
3325
- version: v.pipe(v.number(), v.integer()),
3326
- });
3327
- /**
3328
- * Which of three states the guide's record is in — a required field rather than
3329
- * something a reader infers from empty arrays.
3330
- *
3331
- * The distinction is the whole point of returning it: `unevaluated` means no
3332
- * graded run has ever produced a verdict, while `awaiting_current_revision`
3333
- * means the guide has a real record that is entirely about wording the user has
3334
- * since rewritten. Collapsing those two onto "no data" is exactly the claim the
3335
- * dashboard stopped making with its awaiting-current-revision check, and an
3336
- * agent reading an absence as a verdict is the same error one screen further
3337
- * out.
3338
- */
3339
- export const GuideHistoryStateSchema = v.picklist([
3340
- 'evaluated',
3341
- 'awaiting_current_revision',
3342
- 'unevaluated',
3343
- ]);
3344
- /**
3345
- * The verdict window, scoped to the revision named beside it.
3346
- *
3347
- * Both denominators travel: `applicable` is the rate's own denominator
3348
- * (`aligned + misaligned`), `total` is the window's row count including the runs
3349
- * that never engaged the guide. Rendering one as the other is the defect
3350
- * `alignment-rate-sample-disclosure` was filed for, and a payload carrying only
3351
- * one of them would hand an agent the same mistake.
3352
- */
3353
- export const GuideHistoryWindowSchema = v.object({
3354
- /** Rows summarized, after the revision narrow. */
3355
- total: v.pipe(v.number(), v.integer()),
3356
- aligned: v.pipe(v.number(), v.integer()),
3357
- misaligned: v.pipe(v.number(), v.integer()),
3358
- /** In context, never engaged. Neither a pass nor a failure. */
3359
- notApplicable: v.pipe(v.number(), v.integer()),
3360
- /** `aligned + misaligned` — the rate's own denominator. */
3361
- applicable: v.pipe(v.number(), v.integer()),
3362
- /** `aligned / applicable`, or **null when no run engaged the guide**. */
3363
- alignmentRate: v.nullable(v.number()),
3364
- /** The rows hit the per-guide cap: a bounded window, never a lifetime total. */
3365
- isWindowed: v.boolean(),
3366
- /** The cap the rows were fetched under, so a reader can say what "windowed" means. */
3367
- windowSize: v.pipe(v.number(), v.integer()),
3368
- /**
3369
- * Verdicts fetched and then dropped by the revision narrow — about wording
3370
- * that is no longer current, or citing no revision at all. A **floor** rather
3371
- * than a total whenever `isWindowed`, because rows past the cap were never
3372
- * fetched.
3373
- */
3374
- olderRevisionRows: v.pipe(v.number(), v.integer()),
3375
- /**
3376
- * `applicable` is too small for the percentage to mean anything — threshold
3377
- * `applicable < 3` (founder, 2026-08-22). Read the counts, not the rate.
3378
- */
3379
- isLowConfidence: v.boolean(),
3380
- });
3381
- /**
3382
- * One side of a guide edit's before/after pair — the wording, and what the runs
3383
- * that engaged it did.
3384
- *
3385
- * Structurally a window like `GuideHistoryWindow` and deliberately not that
3386
- * schema: these two sides are bounded **per revision** by a different
3387
- * server-side query, so `isSaturated` is
3388
- * the server's own measurement of its partition rather than the client-side
3389
- * `isWindowed` inference, and the span each side covers is part of what makes
3390
- * the pair readable.
3391
- *
3392
- * Both denominators travel here for the same reason they travel on the window:
3393
- * a delta between two undisclosed denominators is worse than no number at all.
3394
- */
3395
- export const GuideHistoryChangeSideSchema = v.object({
3396
- /** The wording this side judges. */
3397
- revision: GuideHistoryRevisionSchema,
3398
- /** Rows in this side's window, including the runs that never engaged it. */
3399
- total: v.pipe(v.number(), v.integer()),
3400
- aligned: v.pipe(v.number(), v.integer()),
3401
- misaligned: v.pipe(v.number(), v.integer()),
3402
- notApplicable: v.pipe(v.number(), v.integer()),
3403
- /** `aligned + misaligned` — this side's own denominator. */
3404
- applicable: v.pipe(v.number(), v.integer()),
3405
- /** `aligned / applicable`, or null when no run engaged this wording. */
3406
- alignmentRate: v.nullable(v.number()),
3407
- /** This side is below the sample floor, so read its counts and not its rate. */
3408
- isLowConfidence: v.boolean(),
3409
- /**
3410
- * This side is a bounded sample of its revision rather than the whole record.
3411
- * A saturated side beside an unsaturated one is two different kinds of
3412
- * number, and comparing them without saying so is the defect the flag exists
3413
- * to stop.
3414
- */
3415
- isSaturated: v.boolean(),
3416
- /** The span this side covers, ISO. Both null on a side with no rows. */
3417
- newestAt: v.nullable(v.string()),
3418
- oldestAt: v.nullable(v.string()),
3419
- });
3420
- /**
3421
- * Which side is too thin for a delta to mean anything.
3422
- *
3423
- * Named rather than a boolean because the two take different sentences: too few
3424
- * runs *since* the change is the ordinary state right after an edit, while too
3425
- * few *before* it means there was never a baseline to compare against.
3426
- */
3427
- export const GuideHistoryChangeSuppressionSchema = v.picklist(['since', 'before', 'both']);
3428
- /**
3429
- * Which way the pair points, or null while the delta is withheld.
3430
- *
3431
- * A reading of a *set* of runs, never a verdict on one — the vocabulary
3432
- * `aligned | misaligned | not_applicable` is untouched, and nothing derived
3433
- * here is written back to a row.
3434
- */
3435
- export const GuideHistoryChangeDirectionSchema = v.picklist([
3436
- 'improved',
3437
- 'regressed',
3438
- 'unchanged',
3439
- ]);
3440
- /**
3441
- * The guide's last edit, read as two windows
3442
- * (`insight-to-proven-change` §A, surfaced by `guide-history-for-agents`
3443
- * deliverable 3).
3444
- *
3445
- * > Changed 12 Aug. Before: misaligned in 6 of 8 runs that engaged it.
3446
- * > Since: 0 of 11.
3447
- *
3448
- * **Null on the response is a state, not a missing field.** It means this guide
3449
- * has no earlier wording that produced evidence — a guide on its first
3450
- * revision, which is the normal state and not an error.
3451
- *
3452
- * **Paired, never merged**, and **never causal**: this states two windows and
3453
- * their denominators and stops. The model changed, the task mix changed and the
3454
- * codebase changed too, so "since" is the strongest word the evidence supports.
3455
- */
3456
- export const GuideHistoryChangeSchema = v.object({
3457
- /** The revision that preceded the change. */
3458
- before: GuideHistoryChangeSideSchema,
3459
- /** The wording the guide stands at now. */
3460
- since: GuideHistoryChangeSideSchema,
3461
- /**
3462
- * `since` minus `before`, in `[-1, 1]`, or **null whenever the pair is
3463
- * suppressed** or either side never engaged the guide. Null is not zero: one
3464
- * says the evidence does not support a number, the other would be a claim.
3465
- */
3466
- alignmentRateDelta: v.nullable(v.number()),
3467
- /**
3468
- * Which side is below the sample floor, or null when neither is and the delta
3469
- * stands. `'since'` is the ordinary post-edit state — *not enough runs since
3470
- * this change* — and is reported rather than omitted.
3471
- */
3472
- suppressedBy: v.nullable(GuideHistoryChangeSuppressionSchema),
3473
- /** The delta's sign, or null while it is withheld. `unchanged` is exactly zero. */
3474
- direction: v.nullable(GuideHistoryChangeDirectionSchema),
3475
- /** Either side is a bounded sample, so neither is a lifetime total. */
3476
- isWindowed: v.boolean(),
3477
- /** The per-revision cap each side was bounded by, so "sample" has a size. */
3478
- windowSize: v.pipe(v.number(), v.integer()),
3479
- /**
3480
- * When the current wording was recorded, ISO — the boundary between the two
3481
- * windows, and null when no version row carries it.
3482
- *
3483
- * A date, never an attribution: it says when the window opened, not that the
3484
- * edit caused what happened inside it.
3485
- */
3486
- changedAt: v.nullable(v.string()),
3487
- });
3488
- /** Findings returned per response, and the character bound on each reasoning. */
3489
- export const MAX_GUIDE_HISTORY_FINDINGS = 5;
3490
- export const MAX_GUIDE_HISTORY_REASONING_CHARS = 1200;
3491
- /**
3492
- * One recorded finding: a run that judged this guide misaligned, and why.
3493
- *
3494
- * `reasoning` arrives **already wrapped in the response's untrusted markers**
3495
- * rather than raw. It is model-authored text derived from a transcript, so the
3496
- * discipline the run grader applies to such text on the way in applies on the
3497
- * way out; wrapping it at the source is what makes the boundary
3498
- * unforgeable, since a consumer handed raw text plus separate markers can
3499
- * simply not use them.
3500
- *
3501
- * `isCurrentRevision` is not optional detail. A payload that scopes its *rate*
3502
- * to the current wording and then hands over reasoning about deleted sentences,
3503
- * unlabelled, reproduces inside one response the conflation
3504
- * `pattern-evidence-guide-revision` removed from the dashboard.
3505
- */
3506
- export const GuideHistoryFindingSchema = v.object({
3507
- sessionId: NonEmptyStringSchema,
3508
- occurredAt: v.string(),
3509
- revision: v.nullable(GuideHistoryRevisionSchema),
3510
- isCurrentRevision: v.boolean(),
3511
- reasoning: v.string(),
3512
- });
3513
- /** The guide the identifier resolved to, echoed so the agent can check itself. */
3514
- export const GuideHistoryGuideSchema = v.object({
3515
- id: NonEmptyStringSchema,
3516
- title: v.string(),
3517
- path: v.nullable(SafeRelativePosixPathSchema),
3518
- root: v.nullable(GuideDiscoveryRootSchema),
3519
- });
3520
- /**
3521
- * The caller's newest stored failure-pattern analysis of the guide
3522
- * (`drafted-guide-suggestions` slice 7), served through artifact feedback.
3523
- *
3524
- * **The caller's own analysis only.** An analysis reads the caller's verdicts,
3525
- * so a workspace-mate's is never returned, the same rule the verdicts follow.
3526
- *
3527
- * **Staleness is derived on read**: the
3528
- * guide's wording changed since (`revision_changed`), or failures of the same
3529
- * wording arrived that it has not read (`new_failures`, with how many). A stale
3530
- * analysis is still what it found; it is reported, never withheld.
3531
- *
3532
- * `summary` arrives wrapped in the response's untrusted markers. It is
3533
- * model-authored text derived from session transcripts. On `no_pattern` it may
3534
- * be empty between them, because the dashboard supplies that sentence itself.
3535
- */
3536
- export const GuideHistoryAnalysisSchema = v.object({
3537
- id: NonEmptyStringSchema,
3538
- /** When it was written, ISO. */
3539
- createdAt: v.string(),
3540
- outcome: v.picklist(['pattern', 'no_pattern']),
3541
- summary: v.string(),
3542
- /** Failed sessions the analysis read. */
3543
- sessionsAnalysed: v.pipe(v.number(), v.integer()),
3544
- /** Failed sessions it left out to stay within its prompt's cap. */
3545
- sessionsOmitted: v.pipe(v.number(), v.integer()),
3546
- stale: v.boolean(),
3547
- /** Why it is out of date, or null while it is current. */
3548
- staleReason: v.nullable(v.picklist(['revision_changed', 'new_failures'])),
3549
- /** Failures it has not read, when `staleReason` is `new_failures`; else null. */
3550
- newFailures: v.nullable(v.pipe(v.number(), v.integer())),
3551
- });
3552
- export const GuideHistoryResponseSchema = v.object({
3553
- guide: GuideHistoryGuideSchema,
3554
- /** The wording the window is about, or null when the guide has no revision identity. */
3555
- currentRevision: v.nullable(GuideHistoryRevisionSchema),
3556
- state: GuideHistoryStateSchema,
3557
- window: GuideHistoryWindowSchema,
3558
- /**
3559
- * The last edit's two windows, or **null when there is no earlier wording to
3560
- * compare against**.
3561
- *
3562
- * Present-and-null rather than omitted: a guide on its first revision has no
3563
- * delta, and that is an answer. An absent key would leave a reader unable to
3564
- * tell "no edit to measure" from "this server does not report deltas".
3565
- */
3566
- change: v.nullable(GuideHistoryChangeSchema),
3567
- findings: v.array(GuideHistoryFindingSchema),
3568
- /**
3569
- * Misaligned rows in the window beyond the `MAX_GUIDE_HISTORY_FINDINGS`
3570
- * returned. Reported rather than silently truncated: a caller reading five
3571
- * findings has no other way to know it is reading five of forty.
3572
- */
3573
- findingsOmitted: v.pipe(v.number(), v.integer()),
3574
- /**
3575
- * The caller's newest stored failure-pattern analysis of this guide, or
3576
- * **null when they have never asked for one**. Optional because a server
3577
- * that predates it sends no key; a reader must not take absence for "never
3578
- * analysed".
3579
- */
3580
- analysis: v.optional(v.nullable(GuideHistoryAnalysisSchema)),
3581
- untrusted: GuideHistoryUntrustedSchema,
3582
- });
3583
- // ---------------------------------------------------------------------------
3584
2293
  // Artifact feedback — open comments and grading for one artifact
3585
2294
  // (`GET /api/v1/artifacts/:id/feedback`)
3586
2295
  // ---------------------------------------------------------------------------
@@ -3666,15 +2375,6 @@ export const ArtifactFeedbackBatchResponseSchema = v.object({
3666
2375
  // ---------------------------------------------------------------------------
3667
2376
  // Parse wrappers (throw ValiError on invalid input)
3668
2377
  // ---------------------------------------------------------------------------
3669
- export function parseGuideBundleResponse(data) {
3670
- return v.parse(GuideBundleResponseSchema, data);
3671
- }
3672
- export function parseRawGuideFilePayload(data) {
3673
- return v.parse(RawGuideFilePayloadSchema, data);
3674
- }
3675
- export function parseBundleListResponse(data) {
3676
- return v.parse(BundleListResponseSchema, data);
3677
- }
3678
2378
  export function parseWorkspaceListResponse(data) {
3679
2379
  return v.parse(WorkspaceListResponseSchema, data);
3680
2380
  }
@@ -3684,45 +2384,6 @@ export function parseCreateScopedTokenRequest(data) {
3684
2384
  export function parseRevokeScopedTokenRequest(data) {
3685
2385
  return v.parse(RevokeScopedTokenRequestSchema, data);
3686
2386
  }
3687
- export function parseCreateBundleRequest(data) {
3688
- return v.parse(CreateBundleRequestSchema, data);
3689
- }
3690
- export function parseCreateBundleResponse(data) {
3691
- return v.parse(CreateBundleResponseSchema, data);
3692
- }
3693
- export function parseAttachBundleMemberRequest(data) {
3694
- return v.parse(AttachBundleMemberRequestSchema, data);
3695
- }
3696
- export function parseAttachBundleMemberResponse(data) {
3697
- return v.parse(AttachBundleMemberResponseSchema, data);
3698
- }
3699
- export function parseAttachBundleMembersResponse(data) {
3700
- return v.parse(AttachBundleMembersResponseSchema, data);
3701
- }
3702
- export function parseDetachBundleMemberResponse(data) {
3703
- return v.parse(DetachBundleMemberResponseSchema, data);
3704
- }
3705
- export function parseSubscribeBundleRequest(data) {
3706
- return v.parse(SubscribeBundleRequestSchema, data);
3707
- }
3708
- export function parseSubscribeBundleResponse(data) {
3709
- return v.parse(SubscribeBundleResponseSchema, data);
3710
- }
3711
- export function parseResolveSubscriptionsRequest(data) {
3712
- return v.parse(ResolveSubscriptionsRequestSchema, data);
3713
- }
3714
- export function parseResolveSubscriptionsResponse(data) {
3715
- return v.parse(ResolveSubscriptionsResponseSchema, data);
3716
- }
3717
- export function parseUpdateBundleRequest(data) {
3718
- return v.parse(UpdateBundleRequestSchema, data);
3719
- }
3720
- export function parseUpdateBundleResponse(data) {
3721
- return v.parse(UpdateBundleResponseSchema, data);
3722
- }
3723
- export function parseDeleteBundleResponse(data) {
3724
- return v.parse(DeleteBundleResponseSchema, data);
3725
- }
3726
2387
  export function parseContextItemsResponse(data) {
3727
2388
  return v.parse(ContextItemsResponseSchema, data);
3728
2389
  }
@@ -3772,10 +2433,4 @@ function adoptLegacyAgentSessionId(data) {
3772
2433
  export function parseActionEntry(data) {
3773
2434
  return v.parse(ActionEntrySchema, adoptLegacyAgentSessionId(data));
3774
2435
  }
3775
- export function parseGuideHistoryRequest(data) {
3776
- return v.parse(GuideHistoryRequestSchema, data);
3777
- }
3778
- export function parseGuideHistoryResponse(data) {
3779
- return v.parse(GuideHistoryResponseSchema, data);
3780
- }
3781
2436
  //# sourceMappingURL=schemas.js.map