@mossbear/protocol 0.1.0-alpha.114 → 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 (73) 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/comments.d.ts +1405 -0
  10. package/dist/comments.d.ts.map +1 -0
  11. package/dist/comments.js +683 -0
  12. package/dist/comments.js.map +1 -0
  13. package/dist/comments.test.d.ts +2 -0
  14. package/dist/comments.test.d.ts.map +1 -0
  15. package/dist/comments.test.js +64 -0
  16. package/dist/comments.test.js.map +1 -0
  17. package/dist/guideHistory.d.ts +643 -0
  18. package/dist/guideHistory.d.ts.map +1 -0
  19. package/dist/guideHistory.js +343 -0
  20. package/dist/guideHistory.js.map +1 -0
  21. package/dist/guideHistory.test.d.ts +2 -0
  22. package/dist/guideHistory.test.d.ts.map +1 -0
  23. package/dist/guideHistory.test.js +35 -0
  24. package/dist/guideHistory.test.js.map +1 -0
  25. package/dist/guideImport.d.ts +398 -0
  26. package/dist/guideImport.d.ts.map +1 -0
  27. package/dist/guideImport.js +350 -0
  28. package/dist/guideImport.js.map +1 -0
  29. package/dist/guideImport.test.d.ts +2 -0
  30. package/dist/guideImport.test.d.ts.map +1 -0
  31. package/dist/guideImport.test.js +62 -0
  32. package/dist/guideImport.test.js.map +1 -0
  33. package/dist/guideSnapshot.d.ts +105 -0
  34. package/dist/guideSnapshot.d.ts.map +1 -0
  35. package/dist/guideSnapshot.js +101 -0
  36. package/dist/guideSnapshot.js.map +1 -0
  37. package/dist/guideSnapshot.test.d.ts +2 -0
  38. package/dist/guideSnapshot.test.d.ts.map +1 -0
  39. package/dist/guideSnapshot.test.js +49 -0
  40. package/dist/guideSnapshot.test.js.map +1 -0
  41. package/dist/schemas.d.ts +5122 -11710
  42. package/dist/schemas.d.ts.map +1 -1
  43. package/dist/schemas.js +61 -2816
  44. package/dist/schemas.js.map +1 -1
  45. package/dist/search.d.ts +1222 -0
  46. package/dist/search.d.ts.map +1 -0
  47. package/dist/search.js +474 -0
  48. package/dist/search.js.map +1 -0
  49. package/dist/search.test.d.ts +2 -0
  50. package/dist/search.test.d.ts.map +1 -0
  51. package/dist/search.test.js +64 -0
  52. package/dist/search.test.js.map +1 -0
  53. package/dist/sessionContracts.test.d.ts +2 -0
  54. package/dist/sessionContracts.test.d.ts.map +1 -0
  55. package/dist/sessionContracts.test.js +75 -0
  56. package/dist/sessionContracts.test.js.map +1 -0
  57. package/dist/sessionDigest.d.ts +149 -0
  58. package/dist/sessionDigest.d.ts.map +1 -0
  59. package/dist/sessionDigest.js +57 -0
  60. package/dist/sessionDigest.js.map +1 -0
  61. package/dist/sessionGrade.d.ts +184 -0
  62. package/dist/sessionGrade.d.ts.map +1 -0
  63. package/dist/sessionGrade.js +130 -0
  64. package/dist/sessionGrade.js.map +1 -0
  65. package/dist/types.d.ts +4 -27
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/dist/usageOnly.d.ts +5 -5
  69. package/dist/wirePrimitives.d.ts +173 -0
  70. package/dist/wirePrimitives.d.ts.map +1 -0
  71. package/dist/wirePrimitives.js +210 -0
  72. package/dist/wirePrimitives.js.map +1 -0
  73. package/package.json +1 -1
package/dist/schemas.js CHANGED
@@ -8,12 +8,26 @@
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';
12
+ import { ArtifactCommentSchema, MAX_ITEM_THREAD_ENTRIES_ON_WIRE } from './comments.js';
13
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';
14
17
  import { MAX_ARTIFACT_DESCRIPTION_CHARS, MAX_ARTIFACT_NAME_CHARS, MAX_CONTEXT_CONTENT_BYTES, MAX_RAW_GUIDE_CONTENT_BYTES, } from './limits.js';
15
- import { MachineIdSchema } from './pairing.js';
16
18
  import { PhotoAssetSchema } from './photos.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';
27
+ export * from './comments.js';
28
+ export * from './search.js';
29
+ export { SessionGradeRequestSchema, SessionGradeStateSchema, SessionGradeGuideSchema, SessionGradeSchema, GradedSessionSchema, SessionGradeResponseSchema, parseRunGradeRequest, parseSessionGradeResponse, } from './sessionGrade.js';
30
+ export * from './sessionDigest.js';
17
31
  // ---------------------------------------------------------------------------
18
32
  // Core enum schemas
19
33
  // ---------------------------------------------------------------------------
@@ -31,31 +45,6 @@ export const PlatformKindSchema = v.picklist([
31
45
  'copilot',
32
46
  'other',
33
47
  ]);
34
- /**
35
- * Which agent harness produced a run — the CLI's harness registry, on the wire.
36
- *
37
- * **Deliberately not {@link PlatformKindSchema}, and not a widening of it.**
38
- * That picklist answers a different question — which transcript format a
39
- * *suggestion* was extracted from — over a set that includes harnesses
40
- * `mossbear init` cannot wire (`cursor`, `copilot`) and excludes one it can
41
- * (`antigravity`). Two questions, two sets; collapsing them would need both a
42
- * new member and an overloaded meaning.
43
- *
44
- * Declared here rather than in the CLI so there is exactly one list: the CLI's
45
- * `HarnessId` is `v.InferOutput` of this, imported as a type, so a manifest for
46
- * a harness this schema does not name fails typecheck instead of failing at the
47
- * sync boundary. The import is type-only on purpose — `mossbear-hook` runs once
48
- * per agent tool call, and nothing here may enter its runtime import graph.
49
- *
50
- * Rides `metadata.harness` on each action (see {@link ActionMetadataSchema});
51
- * the server reduces a session's actions to one value and writes `runs.harness`.
52
- */
53
- export const HarnessIdSchema = v.picklist([
54
- 'claude_code',
55
- 'codex',
56
- 'antigravity',
57
- 'opencode',
58
- ]);
59
48
  /**
60
49
  * Where a session ran, recorded only when the hook can see it ran in a cloud
61
50
  * container: a claude.ai/code session, a Codespace, a CI runner.
@@ -74,35 +63,6 @@ export const HarnessIdSchema = v.picklist([
74
63
  * The server writes `cloud` onto a session when any of its actions carry it.
75
64
  */
76
65
  export const SessionEnvironmentSchema = v.picklist(['cloud']);
77
- /** Longest accepted repository name. An `owner/repo` path is far shorter; this bounds a folder name. */
78
- export const MAX_REPOSITORY_NAME_LENGTH = 200;
79
- /**
80
- * The name of the repository a session ran in, as a person would recognise it:
81
- * the `owner/repo` path of the checkout's git remote, or the checkout's folder
82
- * name when it has no remote the CLI can read a path from.
83
- *
84
- * A display name, not an identity. Two forks share a name, and a folder name
85
- * says nothing beyond itself; `projectId` and `repoId` stay the keys a reader
86
- * joins on. The CLI keeps only the path of a remote: never its scheme,
87
- * credentials, host, port or query, so a URL carrying a token does not leave
88
- * the machine.
89
- *
90
- * Rides `metadata.repository` on each action (see {@link ActionMetadataSchema}).
91
- * The server reduces a session's stamps to one value; absent is "unnamed",
92
- * which is every session a CLI predating the field recorded.
93
- */
94
- export const RepositoryNameSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(MAX_REPOSITORY_NAME_LENGTH), v.check((value) => value.trim() === value && !/\p{Cc}/u.test(value), 'repository must be trimmed and hold no control characters'));
95
- export const GuideFileFormatSchema = v.picklist([
96
- 'agents-md',
97
- 'agents-dir',
98
- 'claude-md',
99
- 'claude-rules',
100
- 'cursorrules',
101
- 'cursor-rules',
102
- 'skill-md',
103
- ]);
104
- const NonEmptyStringSchema = v.pipe(v.string(), v.minLength(1));
105
- const Sha256HexSchema = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/i));
106
66
  // No eval-provider schemas here. They described the LLM credentials the CLI
107
67
  // needed to grade on-device; grading is server-side and the CLI holds no
108
68
  // provider config. The server's own provider settings are environment
@@ -112,199 +72,7 @@ const Sha256HexSchema = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/i));
112
72
  // `typeof body.token === 'string'` by hand — and nothing else imported them.
113
73
  // Deleted rather than kept as a parallel contract that had already drifted
114
74
  // from the route's `{ valid }` response.
115
- // The guide snapshot schemas live further down, after
116
- // `SafeRelativePosixPathSchema` and `GuideDiscoveryRootSchema`: the bundle now
117
- // carries the same `(root, path)` pair the import payload does, and a `const`
118
- // cannot be referenced above its own declaration.
119
75
  export { MAX_ARTIFACT_DESCRIPTION_CHARS, MAX_ARTIFACT_NAME_CHARS, MAX_RAW_GUIDE_CONTENT_BYTES, };
120
- /** Max member files a single skill-md payload may carry. */
121
- export const MAX_SKILL_MEMBER_FILES = 64;
122
- 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`));
123
- // A path that is safe to re-create on disk and safe to store as identity:
124
- // forward slashes only, never absolute (POSIX or Windows drive-letter form),
125
- // no empty / `.` / `..` segments, no control characters. Every path this
126
- // protocol carries can end up written into a project tree, so the rule
127
- // belongs at the schema boundary rather than in each consumer, at the boundary
128
- // where untrusted data crosses in.
129
- //
130
- // Exported so the server and the CLI enforce the identical rule.
131
- //
132
- // The check messages each name the one edit that fixes the path, so they are
133
- // written for the reader and exported for a server boundary to pass through.
134
- export const PATH_ISSUE_MESSAGES = {
135
- backslash: 'path must use forward slashes',
136
- absolute: 'path must be relative',
137
- control: 'path must not contain control characters',
138
- segments: 'path must not contain empty, "." or ".." segments',
139
- skillMd: 'path must not shadow the skill’s own SKILL.md',
140
- };
141
- 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(
142
- // eslint-disable-next-line no-control-regex
143
- (path) => !/[\u0000-\u001f\u007f]/.test(path), PATH_ISSUE_MESSAGES.control), v.check((path) => path
144
- .split('/')
145
- .every((segment) => segment !== '' && segment !== '.' && segment !== '..'), PATH_ISSUE_MESSAGES.segments));
146
- // Member paths are relative to the skill directory, and additionally may never
147
- // name the skill's own SKILL.md (the payload itself).
148
- export const SkillMemberPathSchema = v.pipe(SafeRelativePosixPathSchema, v.check((path) => path.toLowerCase() !== 'skill.md', PATH_ISSUE_MESSAGES.skillMd));
149
- // A sibling file of a skill's SKILL.md (scripts/, references/, assets/,
150
- // supporting docs), imported alongside it as a guide_file row.
151
- export const RawSkillMemberFileSchema = v.object({
152
- path: SkillMemberPathSchema,
153
- rawContent: BoundedRawContentSchema,
154
- lastModified: v.pipe(v.number(), v.integer(), v.minValue(0)),
155
- content_hash: Sha256HexSchema,
156
- /**
157
- * Whether the file is executable (`100755` in git), so delivery writes it
158
- * `0o755` or `0o644`. A boolean rather than a mode because git records only
159
- * those two for a blob, and a numeric mode would be a channel for bits
160
- * nothing here should set. **Absent is not `false`**: a CLI that predates the
161
- * field sends none, and the server then keeps whatever it already holds.
162
- */
163
- executable: v.optional(v.boolean()),
164
- });
165
- /** Max skipped-member paths a skill-md payload may report alongside `members`. */
166
- export const MAX_SKILL_SKIPPED_MEMBER_PATHS = 256;
167
- // Paths (relative to the skill directory) that discovery found but could not
168
- // import this run — binary/non-UTF-8, oversized, unreadable, or beyond the
169
- // member cap. Deliberately looser than SkillMemberPathSchema: these describe
170
- // what is on the user's disk and are only ever string-matched against stored
171
- // member paths server-side (never re-created as files), so an odd on-disk
172
- // filename must not fail the whole payload.
173
- const SkippedMemberPathSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(512));
174
- /**
175
- * Which root a discovered guide file's `path` is relative to: the repo checkout
176
- * (`project`) or the user's homedir (`global`, e.g. `.claude/CLAUDE.md`).
177
- * Part of the import resolution key — see `RawGuideFilePayloadSchema.root`.
178
- */
179
- export const GuideDiscoveryRootSchema = v.picklist(['project', 'global']);
180
- // ---------------------------------------------------------------------------
181
- // Guide snapshot schemas
182
- // ---------------------------------------------------------------------------
183
- export const GuideSnapshotSchema = v.object({
184
- id: v.string(),
185
- title: v.string(),
186
- content: v.string(),
187
- enabled: v.boolean(),
188
- updatedAt: v.string(),
189
- // origin is `file:{format}:{path}` for imported guides, null/absent
190
- // otherwise. contentHash is the SHA-256 of the canonical bytes; the CLI uses
191
- // the pair to round-trip imported files back to disk without re-encoding.
192
- //
193
- // **`origin` is not superseded by `(root, path)`.** Nothing on the write side
194
- // reconciles on it after this slice, but `resolveRuleFileDelivery` still
195
- // matches delivery evidence on `(origin, contentHash)`, so dropping it
196
- // would make every guide read as undelivered — silently, since runs still
197
- // grade and verdicts still appear. It stays as provenance.
198
- origin: v.optional(v.nullable(v.string())),
199
- contentHash: v.optional(v.nullable(Sha256HexSchema)),
200
- // Which scope root `path` is relative to, and the path itself — the write
201
- // side's half of the identity the read side already stores on
202
- // `guide_files.root` / `guide_files.path`
203
- // (`guide-write-side-identity-plan.md` → "Carry `root` on every write path").
204
- //
205
- // Without them the bundle could not express "global": `origin` is
206
- // `file:{format}:{path}` with no root component, so every writer resolved it
207
- // against the repo and a guide imported from `~/.claude/CLAUDE.md` came back
208
- // down as `<repo>/.claude/CLAUDE.md`.
209
- //
210
- // **Both optional and nullable, and their absence is not an error.** A guide
211
- // authored in the dashboard has no path; a row imported before the columns
212
- // existed has neither. Such a guide keeps resolving from `origin` alone —
213
- // today's behaviour — rather than becoming undeliverable. A missing `root` is
214
- // read as `project`, which is what every pre-existing row meant.
215
- root: v.optional(v.nullable(GuideDiscoveryRootSchema)),
216
- path: v.optional(v.nullable(SafeRelativePosixPathSchema)),
217
- });
218
- export const GuideBundleResponseSchema = v.object({
219
- guides: v.array(GuideSnapshotSchema),
220
- pulledAt: v.string(),
221
- });
222
- export const RawGuideFilePayloadSchema = v.pipe(v.object({
223
- // Relative to the discovery root the CLI walked (`payloadPath`,
224
- // `packages/cli/src/guides/discover.ts`). Two things depend on it
225
- // being a safe relative path, which is why it is parsed here rather than
226
- // guarded downstream:
227
- //
228
- // - it is embedded verbatim in the guide's `origin` (`file:{format}:{path}`)
229
- // and parsed back out to place the file on disk. The writer that does so
230
- // is now the docs phase's projection resolver
231
- // (`packages/cli/src/artifacts/guide-projection.ts`), which rejects anything
232
- // absolute, traversing or uncontained — so an unsafe path stores a guide
233
- // that can never round-trip. (`mossbear guides export` was the original
234
- // writer and skipped such a path *silently*; it was deleted by
235
- // `unified-item-sync` Slice 5.);
236
- // - it is stored as `guide_files.path`, the column import reconciles on
237
- // (`guide-versioned-identity-plan.md` → Decision 4), and identity must
238
- // not be keyable on a value the exporter refuses to honour.
239
- path: SafeRelativePosixPathSchema,
240
- // Which discovery root `path` is relative to — `guide-versioned-identity-plan.md`
241
- // → Decision 6. Without it, `(repoId, path)` collapses a project skill onto
242
- // its `~/.claude/skills` twin: `.claude/skills` is in both of the CLI's root
243
- // lists and both scans emit the same relative string, while `repoId` is
244
- // envelope-level so both files carry the same one.
245
- //
246
- // **Optional, and its absence is not an error** — a CLI predating this field
247
- // sends none, exactly as it may send no `repoId`. A payload missing either
248
- // does not participate in reconciliation and keeps the content-hash insert
249
- // behaviour it was created under, rather than being defaulted to `'project'`:
250
- // guessing would let an old client's `--global` file adopt a project row.
251
- root: v.optional(GuideDiscoveryRootSchema),
252
- format: GuideFileFormatSchema,
253
- rawContent: BoundedRawContentSchema,
254
- lastModified: v.pipe(v.number(), v.integer(), v.minValue(0)),
255
- content_hash: Sha256HexSchema,
256
- // Only meaningful on `skill-md` payloads. `[]` asserts the skill has no
257
- // member files (stale synced rows are removed server-side); omitting the
258
- // field means "no member information" and leaves member rows untouched.
259
- // No CLI caller omits it today — every sender reaches this schema through
260
- // a directory scan that populates it — but the distinction is load-bearing
261
- // on the wire and must not collapse: reading an absent `members` as an
262
- // empty skill would hard-delete a client's member rows.
263
- members: v.optional(v.pipe(v.array(RawSkillMemberFileSchema), v.maxLength(MAX_SKILL_MEMBER_FILES))),
264
- /**
265
- * The body-item version this machine last agreed with the server about for
266
- * this `(scope, root, path)` — the machine-local baseline
267
- * (`guide-versioned-identity-plan.md` → slice 2b-B, D10 in
268
- * `context-bundle-authoring-plan.md`).
269
- *
270
- * It is the *client* half of the reconcile precondition, and it exists to
271
- * answer a question the server cannot: whether the bytes on this disk were
272
- * edited **from** the version the server currently holds, or from an older
273
- * one. The server-only guard shipped in 2b-A can see that a dashboard edit
274
- * exists, never that this machine has already seen it — so a guide the
275
- * dashboard edited and the user then re-synced to disk forks forever.
276
- *
277
- * **Optional, and its absence is not an error.** A CLI predating the
278
- * baseline store, a fresh machine, or a deleted `~/.mossbear/state/` sends
279
- * none, and the payload falls back to the server-only guard exactly as it
280
- * behaves today. Absence therefore degrades to "decline and fork", never to
281
- * an overwrite; a *stale* value degrades to a reported conflict.
282
- */
283
- expectedVersion: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
284
- // Only alongside `members`: member paths present on disk but not imported
285
- // this run. The server must NOT treat their absence from `members` as
286
- // removal — a transiently unreadable or newly-oversized file would
287
- // otherwise hard-delete its previously synced row.
288
- skippedMemberPaths: v.optional(v.pipe(v.array(SkippedMemberPathSchema), v.maxLength(MAX_SKILL_SKIPPED_MEMBER_PATHS))),
289
- }), 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'),
290
- // Case-insensitive uniqueness: the export round-trip re-creates these files
291
- // on disk, where the default macOS/Windows filesystems fold case — two
292
- // members differing only by case would silently overwrite each other.
293
- v.check((payload) => payload.members === undefined ||
294
- new Set(payload.members.map((member) => member.path.toLowerCase())).size ===
295
- payload.members.length, 'member paths must be unique (case-insensitive)'));
296
- /** Max number of rules accepted in a single `POST /api/rules/import` request. */
297
- export const MAX_RULES_IMPORT_BATCH = 100;
298
- /** Opaque checkout digest shared by run logs, manifests, and `runs.repo_id`. */
299
- export const RepoIdSchema = v.pipe(v.string(), v.regex(/^repo_[0-9a-f]{32}$/, 'repoId must be repo_ followed by 32 hex chars'));
300
- /** Longest accepted `projectId`. Generated ids are far shorter; this bounds a hand-declared one. */
301
- const MAX_PROJECT_ID_LENGTH = 128;
302
- /**
303
- * A repo's declared portable identity. See `RulesImportRequestSchema.projectId`
304
- * for why this is looser than {@link RepoIdSchema} — a declared id is
305
- * human-authored and predates any prefix rule.
306
- */
307
- export const ProjectIdSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_PROJECT_ID_LENGTH), v.regex(/^[A-Za-z0-9_.-]+$/, 'projectId must contain only letters, digits, underscore, dot or hyphen'));
308
76
  /**
309
77
  * A checkout's committed `project.id` as a context write declares it: trimmed
310
78
  * and non-empty, exactly the rule the CLI's config reader applies — and no
@@ -317,391 +85,9 @@ export const ProjectIdSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.ma
317
85
  * on it would read as foreign in every repo.
318
86
  */
319
87
  export const DeclaredProjectIdSchema = v.pipe(v.string(), v.trim(), v.minLength(1));
320
- /** Longest accepted `workspaceId`. Server-minted ids are `nanoid()`; this bounds a hand-edited one. */
321
- const MAX_WORKSPACE_ID_LENGTH = 128;
322
- /**
323
- * The workspace a repo declares its project-scoped guidance belongs to. See
324
- * `RulesImportRequestSchema.workspaceId`.
325
- *
326
- * Same shape as {@link ProjectIdSchema}, and for the same reason: the id is
327
- * minted by the server (`nanoid()`, whose alphabet this character class covers)
328
- * but it reaches us out of a **committed, hand-editable** file, so it is
329
- * constrained only as far as it must be to serve as a lookup key — no
330
- * whitespace, no path separators, no control characters, bounded length.
331
- * Whether it names a workspace this caller may reach is a membership question,
332
- * answered against the database, not a question a regex can answer.
333
- */
334
- 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'));
335
- // Envelope-only schema: caps request shape/size before the per-item
336
- // parseRawGuideFilePayload loop validates each rule in detail, which is what
337
- // preserves the import route's index-aware error reporting.
338
- export const RulesImportRequestSchema = v.object({
339
- rules: v.pipe(v.array(v.unknown()), v.maxLength(MAX_RULES_IMPORT_BATCH)),
340
- /**
341
- * Which checkout these files came from — the same opaque digest the hook and
342
- * the rule manifest already carry (`packages/cli/src/repo-id.ts`,
343
- * `RuleManifestSchema.repoId`). Envelope-level, not per-file: every file in
344
- * one import comes from one repo, and the per-file payload stays lean (the
345
- * "Import endpoint payload" resolved decision).
346
- *
347
- * It is what lets the server reconcile an edited file back onto the guide it
348
- * already created instead of inserting a second one. `origin` alone cannot:
349
- * it is `file:{format}:{path}` with no repo component, so two checkouts
350
- * sharing `.agents/code-style.md` would collide.
351
- *
352
- * **Optional, and its absence is not an error.** A CLI predating this field
353
- * sends none, and the server falls back to the content-hash dedupe it always
354
- * used. Never send a repo id derived anywhere but `repoIdFromRoot` — the
355
- * digest is keyed by a machine-local secret precisely so the server never
356
- * learns a path.
357
- *
358
- * Shaped by the canonical `RepoIdSchema` (shared with run logs and manifests)
359
- * rather than a looser local check: a row storing anything but
360
- * a real digest could never match one, so a malformed identity has to be
361
- * rejected at the boundary instead of persisted as a permanent orphan.
362
- */
363
- repoId: v.optional(RepoIdSchema),
364
- /**
365
- * The repo's **portable** identity — `project.id` from the committed
366
- * `<repo>/.mossbear/config.json` (`guide-write-side-identity` slice 1, shipped in
367
- * #540). This is what makes `(scope, path)` reconciliation portable, and it is
368
- * the field `unified-item-sync` slice 2 exists to put on the wire.
369
- *
370
- * **Why `repoId` is not enough, even though it is already here.**
371
- * `repoIdFromRoot` is an HMAC keyed by a machine-local secret
372
- * (`packages/cli/src/repo-id.ts`), so the same checkout on two machines — or
373
- * one teammate's clone versus another's — produces two different digests. A
374
- * guide reconciled on it therefore forks the moment anyone else edits the
375
- * file, which is the one-way trip this item is closing. `projectId` is
376
- * declared in a committed file, so every clone agrees on it.
377
- *
378
- * **Optional, and its absence is not an error.** A CLI predating this field
379
- * sends none and the server falls back to `repoId` scoping, which is exactly
380
- * the behaviour those clients already have. A repo that has never run
381
- * `mossbear init` also has no declaration, and must keep importing.
382
- *
383
- * Deliberately looser than `RepoIdSchema`: a generated id is
384
- * `proj_`+hex, but a *declared* one is whatever a human committed —
385
- * `readRepoProjectId` accepts any non-empty trimmed string
386
- * (`packages/cli/src/artifacts/repo-config.ts`), and rejecting those here would
387
- * break a shipped contract. Constrained only as far as it must be to serve as
388
- * a storage key: no whitespace, no path separators, no control characters,
389
- * bounded length.
390
- */
391
- projectId: v.optional(ProjectIdSchema),
392
- /**
393
- * The workspace this repo declares its project-scoped guidance belongs to —
394
- * `workspace.id` from the committed `<repo>/.mossbear/config.json`
395
- * (`workspace-declaration` slice 1).
396
- *
397
- * **What it changes: which of the caller's workspaces a project path resolves
398
- * in.** Import identity is already scoped by workspace *membership* rather
399
- * than authorship, so a caller in several workspaces has several candidate
400
- * rows at one `(project, root, path)` and the resolver picked between them by
401
- * row age. The declaration is the narrower lookup that removes the guess, and
402
- * it is committed so every clone of the repo narrows the same way.
403
- *
404
- * **Membership stays the boundary; this only narrows inside it.** The
405
- * declaration cannot widen what a caller may reach: a workspace they are not a
406
- * member of is refused by name rather than resolved, and never quietly
407
- * replaced by their personal one — falling back would recreate the fork the
408
- * declaration exists to close.
409
- *
410
- * **Envelope-level, and never sent on a global batch.** It is the *repo's*
411
- * declaration, so it travels with the same batch that carries `repoId` and
412
- * `projectId`; a `root: 'global'` file belongs to no checkout and to no
413
- * project, and by the same rule to no repo-declared workspace.
414
- *
415
- * **Optional, and its absence is not an error.** A CLI predating this field
416
- * sends none, and a repo that has never declared one has none to send; both
417
- * keep the resolution they have today.
418
- */
419
- workspaceId: v.optional(WorkspaceIdSchema),
420
- });
421
- /**
422
- * What the server did with one payload, reported per file so the CLI can update
423
- * its machine-local baseline (`guide-versioned-identity-plan.md` → slice 2b-B).
424
- *
425
- * The distinction that matters is not "did something change" but **do disk and
426
- * server now agree**: `imported`, `updated` and `skipped` all mean they do, and
427
- * only those license recording a new baseline. `conflict` means the disk bytes
428
- * did *not* land — recording the server's version for one would hand the next
429
- * import a matching `expectedVersion` and turn a refused overwrite into an
430
- * automatic one on the following run, which is the failure this whole precondition
431
- * exists to prevent.
432
- */
433
- export const GuideImportOutcomeSchema = v.picklist([
434
- 'imported',
435
- 'updated',
436
- 'skipped',
437
- 'conflict',
438
- ]);
439
- /**
440
- * Per-payload import outcome, addressed by the same `(root, path)` pair the
441
- * server reconciles on so the CLI can key its baseline identically without
442
- * re-deriving anything.
443
- *
444
- * `version` is the body item's version **as the server holds it after this
445
- * request** — the value a later import should send as `expectedVersion` once
446
- * disk and server agree. It is reported for a `conflict` too, deliberately: the
447
- * conflict report needs it to offer explicit resolution, and reporting it is not
448
- * the same as recording it.
449
- *
450
- * Entries are omitted for a payload the server could not address at all (no
451
- * `root`, or a pre-R0 row): there is no identity to key a baseline on, and
452
- * inventing one would let a later import claim a precondition it never observed.
453
- */
454
- export const GuideImportResultSchema = v.object({
455
- /** Canonical guide identity for review links; absent on older servers. */
456
- guideId: v.optional(NonEmptyStringSchema),
457
- root: GuideDiscoveryRootSchema,
458
- path: SafeRelativePosixPathSchema,
459
- outcome: GuideImportOutcomeSchema,
460
- version: v.pipe(v.number(), v.integer(), v.minValue(1)),
461
- });
462
- /** Max alias sets one import response reports as divergent. */
463
- export const MAX_GUIDE_IMPORT_DIVERGENCES = 64;
464
- /**
465
- * An alias set the server found in one import but **did not** collapse, because
466
- * the files do not hold the same rules
467
- * (`alias-instruction-file-identity-plan.md` → second addendum,
468
- * 2026-09-03).
469
- *
470
- * Reporting rather than refusing is the whole point. An identical
471
- * `AGENTS.md`/`.cursorrules` pair becomes one guide; a divergent one imports as
472
- * two guides exactly as it does today, and this names the paths so the user can
473
- * see the drift the product would otherwise have kept silent. Nothing about the
474
- * import fails, and nothing the user does today stops working.
475
- *
476
- * `paths` carries every path in the set this request saw, in the order the
477
- * server ranks them — so the first is the one that would have kept the body had
478
- * they matched.
479
- */
480
- export const GuideImportDivergenceSchema = v.object({
481
- root: GuideDiscoveryRootSchema,
482
- paths: v.pipe(v.array(SafeRelativePosixPathSchema), v.minLength(2)),
483
- });
484
- /**
485
- * An alias pair one import left as **two guides**, because a guide was already
486
- * stored at the incoming file's alias partner path and the pair could not be
487
- * collapsed onto it (`skill-alias-collapse-managed-file-plan.md` →
488
- * *Reporting*).
489
- *
490
- * Distinct from {@link GuideImportDivergenceSchema}, which says the files
491
- * differ. This one says only that the fork happened — the reasons are several
492
- * (the bodies differ, the skill directories around them could not be proven to
493
- * match, the partner path already answers to a second guide) and the import
494
- * cannot always tell them apart, so it names the pair and leaves the reading to
495
- * whoever wrote the files. Reported only when a guide was *created* at the
496
- * incoming path, so a repo re-importing a pair that forked long ago stays
497
- * quiet.
498
- *
499
- * `paths` is the incoming file first, then the partner already stored.
500
- */
501
- export const GuideImportAliasForkSchema = v.object({
502
- root: GuideDiscoveryRootSchema,
503
- paths: v.pipe(v.array(SafeRelativePosixPathSchema), v.minLength(2)),
504
- });
505
88
  // ---------------------------------------------------------------------------
506
- // `mossbear unlink` — un-enrol a guide from the default bundle
89
+ // Workspace listing
507
90
  // ---------------------------------------------------------------------------
508
- /**
509
- * One guide to stop delivering, addressed the way the **import** route already
510
- * resolves an existing guide: `(root, path)` plus the envelope's checkout and
511
- * project identity.
512
- *
513
- * **Deliberately not `origin`.** `file:{format}:{path}` is not unique — every
514
- * repo has an `AGENTS.md`, so an origin-keyed request disables the matching
515
- * guide in every repo in the workspace. That is the defect that sank the first
516
- * implementation of this verb. `(root, path)` scoped by `repoId`/`projectId`
517
- * is the key the import route reconciles on, so unlink addresses exactly the
518
- * row link created and no other.
519
- */
520
- export const RawGuideUnlinkSchema = v.object({
521
- root: GuideDiscoveryRootSchema,
522
- /**
523
- * The canonical guide-path validator, not a fresh `v.string()`: it already
524
- * rejects absolute paths, control characters and `..` traversal, and a second
525
- * hand-rolled constraint here would be a place for the two to disagree.
526
- */
527
- path: SafeRelativePosixPathSchema,
528
- });
529
- /** Max guides accepted in a single `POST /api/rules/unlink` request. */
530
- export const MAX_RULE_UNLINK_BATCH = 500;
531
- export const RuleUnlinkRequestSchema = v.object({
532
- unlinks: v.pipe(v.array(RawGuideUnlinkSchema), v.maxLength(MAX_RULE_UNLINK_BATCH)),
533
- /** Same envelope identity the import route carries, and for the same reason. */
534
- repoId: v.optional(v.string()),
535
- projectId: v.optional(v.string()),
536
- });
537
- /**
538
- * `unlinked` counts guides removed from the default bundle; `skipped` counts
539
- * requested paths that resolved to nothing, or were already out of it.
540
- *
541
- * `stillDelivered` names guides that remain in *other* bundles the caller can
542
- * reach — including a teammate's, since a bundle shared into a workspace they
543
- * belong to keeps arriving whoever owns it. Unlink is the exact inverse of what
544
- * link does — it removes the default-bundle membership link created — so a
545
- * guide someone deliberately added to a curated bundle stays there, and saying
546
- * so is the difference between a true report and a reassuring one.
547
- *
548
- * `released` names the requested paths whose guide is now in **no** bundle the
549
- * caller can reach, so nothing delivers it any more. It exists because the
550
- * caller holds a fact the server does not: the local placement record that
551
- * marks a path as managed by a bundle. A path taken out of every bundle and
552
- * still recorded as bundle-managed is two answers to one question, and only the
553
- * server can tell which paths genuinely stopped being delivered. Note this is
554
- * not on its own enough to make a re-link restore delivery — the import route
555
- * enrols only the guide rows its insert creates — so a caller acting on this
556
- * should not report the path as re-adoptable.
557
- *
558
- * Optional with an empty default, so a client on this version still parses a
559
- * response from a deployment that predates the field.
560
- */
561
- export const RuleUnlinkResponseSchema = v.object({
562
- unlinked: v.number(),
563
- skipped: v.number(),
564
- stillDelivered: v.array(v.string()),
565
- released: v.optional(v.array(RawGuideUnlinkSchema), []),
566
- });
567
- export function parseRuleUnlinkRequest(data) {
568
- return v.parse(RuleUnlinkRequestSchema, data);
569
- }
570
- // ---------------------------------------------------------------------------
571
- // Display names
572
- // ---------------------------------------------------------------------------
573
- /**
574
- * The sentence a caller gets back when a display name carries a character that
575
- * cannot be seen. It is written for the person who typed the name, not for the
576
- * developer reading the schema. This repo's error-message rules put the
577
- * reader first, keep the blame off them, and ask a refusal to leave them
578
- * something to do — so the action leads and "control character",
579
- * which is not a phrase most people can act on, never appears.
580
- *
581
- * "often" is doing real work in the second clause. This branch cannot tell a
582
- * pasted name from a typed one, so it does not claim to; it names
583
- * where such characters usually come from, which is what makes the advice
584
- * actionable without overclaiming.
585
- */
586
- export const DISPLAY_NAME_CONTROL_CHARACTER_MESSAGE = 'Remove the invisible characters from this name — copying text from another app often brings them along.';
587
- /**
588
- * A user-typed display name that is safe to print into a terminal line.
589
- *
590
- * Refuses every character in {@link DISPLAY_NAME_REFUSED_CHARACTERS}
591
- * (`bundleSlug.ts`, where the class is defined once and explained): the control
592
- * characters, where ESC and CR live — a CR can overwrite the line a user is
593
- * reading, which in a tool whose job is reporting what reached their agents
594
- * means the sentence on screen can be made to say something other than what
595
- * happened — and the explicit bidi controls, which reorder a rendered line
596
- * without changing a byte of it. The rest of `\p{Cf}` is admitted: the
597
- * zero-width joiners Persian, Hindi and Bengali need, the join inside a
598
- * multi-person emoji, a soft hyphen. Sharing the class with `displayable` is
599
- * what keeps the boundary and the derivation saying the same thing.
600
- *
601
- * **Refuse, never strip.** A user typing a name is present and can be told;
602
- * rewriting their input silently is what those same rules argue against. The
603
- * one strip in the codebase — `displayable`, reached through
604
- * `defaultGuidesBundleFor` in `bundleSlug.ts` — is a *derivation* with no user
605
- * to report to, which is the exception that fixes the rule rather than a
606
- * precedent for a second one.
607
- *
608
- * **Then requires one character outside `\p{Cf}`.** Admitting the joiners
609
- * admits a name made of nothing but them, which `v.trim()` cannot see and
610
- * `minLength(1)` counts. Such a name is refused as empty, with the same
611
- * sentence — to the person typing it, it is a name of invisible characters
612
- * either way.
613
- *
614
- * **A factory, because the max length is per-field** (64 for a workspace name,
615
- * 200 for a bundle name) while the character rule is not. Exported rather than
616
- * inlined so a fourth display-name field meets the rule while reading its
617
- * neighbours — nothing enforces that it is called.
618
- */
619
- export function displayNameSchema(maxLength) {
620
- 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));
621
- }
622
- /** A bundle's display name. Bundles are addressed by slug; this is the label. */
623
- export const BUNDLE_NAME_MAX_LENGTH = 200;
624
- // ---------------------------------------------------------------------------
625
- // Context bundle schemas
626
- // ---------------------------------------------------------------------------
627
- // url-safe slug, unique per user. Lowercase alphanumerics + hyphens, must start
628
- // with an alphanumeric so it reads cleanly in a URL/path.
629
- export const BundleSlugSchema = v.pipe(v.string(), v.check(isBundleSlug, 'slug must be lowercase alphanumeric with hyphens, at most 64 characters'));
630
- /**
631
- * A publisher's lowercase handle: the prefix of a published bundle's address,
632
- * `<handle>/<slug>` (`mossbear/guides`). Slugs are unique per workspace, so a
633
- * bare slug names one of the caller's own bundles and a published bundle is
634
- * named through its publisher.
635
- */
636
- export const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,38}$/;
637
- export const PublisherHandleSchema = v.pipe(v.string(), v.regex(PUBLISHER_HANDLE_PATTERN, 'handle must be lowercase alphanumeric with hyphens'));
638
- /** The longest publisher name a reader is shown. */
639
- export const PUBLISHER_NAME_MAX_LENGTH = 100;
640
- /**
641
- * Who publishes a bundle, as a reader sees it. Present only on a bundle that is
642
- * published; absent is the ordinary case, a bundle of the caller's own.
643
- */
644
- export const BundlePublisherSchema = v.object({
645
- name: v.pipe(v.string(), v.maxLength(PUBLISHER_NAME_MAX_LENGTH)),
646
- handle: PublisherHandleSchema,
647
- });
648
- /** A published bundle's address, `<handle>/<slug>`. */
649
- export const PublishedBundleAddressSchema = v.pipe(v.string(), v.maxLength(104), v.check((value) => {
650
- const at = value.indexOf('/');
651
- if (at <= 0)
652
- return false;
653
- return (PUBLISHER_HANDLE_PATTERN.test(value.slice(0, at)) &&
654
- isBundleSlug(value.slice(at + 1)));
655
- }, 'address must be <publisher handle>/<bundle slug>'));
656
- /**
657
- * The two marks a subscribed bundle carries wherever it is listed: who
658
- * publishes it, and that the caller may read it but not write it. `readOnly`
659
- * is sent only as `true`, for a caller that reaches the bundle by publication
660
- * rather than membership; the publisher's own members edit it as any bundle.
661
- * Both optional, so a CLI built before them parses a new server unchanged.
662
- */
663
- const publishedBundleMarks = {
664
- publisher: v.optional(BundlePublisherSchema),
665
- readOnly: v.optional(v.literal(true)),
666
- };
667
- /**
668
- * An artifact's description as a writer sends it: one paragraph of plain text,
669
- * with no line breaks or other control characters, so it saves on Enter like a
670
- * title, prints safely in a terminal, and stays a plain YAML
671
- * scalar in a Markdown artifact's frontmatter. Blank text is refused rather than
672
- * stored: `null` is how a description is cleared, so "none" has one shape.
673
- */
674
- export const ArtifactDescriptionSchema = v.pipe(v.string(),
675
- // Blank includes text made only of invisible format characters, which
676
- // `trim` cannot see, as `displayNameSchema` refuses a name of them.
677
- 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`),
678
- // The display-name class (control characters and the bidi controls, which
679
- // reorder a printed line), plus the two Unicode line breaks: one line, and
680
- // nothing a terminal printing it would act on.
681
- v.check((value) => !DISPLAY_NAME_REFUSED_CHARACTERS.test(value) && !/[\u2028\u2029]/.test(value), 'description must be one line of text, with no control characters'));
682
- export const BundleSchema = v.object({
683
- id: v.string(),
684
- slug: BundleSlugSchema,
685
- name: v.string(),
686
- createdAt: v.string(),
687
- description: v.optional(v.nullable(v.string())),
688
- ...publishedBundleMarks,
689
- /**
690
- * The project id of the repo that owns this bundle's items, when one claims it
691
- * (`subscription-delivery-target-plan.md` → slice 3). Absent is the ordinary
692
- * case: a bundle with no home is edited wherever its owner likes.
693
- *
694
- * A home makes the named checkout the only writer — a PR there is the review
695
- * — and every other writer, the dashboard included, is refused by name.
696
- *
697
- * Optional rather than nullable so a CLI built before this field parses a new
698
- * server's listing unchanged.
699
- */
700
- home: v.optional(v.string()),
701
- });
702
- export const BundleListResponseSchema = v.object({
703
- bundles: v.array(BundleSchema),
704
- });
705
91
  /**
706
92
  * One workspace the caller belongs to, as `GET /api/v1/workspaces` returns it.
707
93
  *
@@ -720,243 +106,6 @@ export const WorkspaceSummarySchema = v.object({
720
106
  export const WorkspaceListResponseSchema = v.object({
721
107
  workspaces: v.array(WorkspaceSummarySchema),
722
108
  });
723
- /**
724
- * How a bundle reaches a repo. Two scopes and no third:
725
- *
726
- * - `repo` — named by the committed `.mossbear/config.json`, shared with
727
- * teammates by `git clone`.
728
- * - `user` — recorded against the account, private, and on every machine.
729
- *
730
- * A bundle both scopes name carries **both** labels. An earlier shape reported a
731
- * single winning `scope`, which made `status` and `doctor` — both of which count
732
- * the account's subscriptions by filtering for `user` — report zero for a bundle
733
- * that is genuinely subscribed at the account level and will keep delivering to
734
- * every other repo. The scopes are not mutually exclusive, so the wire shape
735
- * must not say they are. Raised by Codex on #735.
736
- */
737
- export const SubscriptionScopeSchema = v.picklist(['repo', 'user']);
738
- /**
739
- * Where a subscription's items are delivered, independent of where their source
740
- * lives (`subscription-delivery-target-plan.md` → slice 2).
741
- *
742
- * - `repo` — land at the item's path in the checkout doing the sync, under the
743
- * same git-owned write rule every project item obeys.
744
- * - `global` — land in the machine-global namespace, unattended.
745
- *
746
- * **Absent is not a third value.** A subscription that names no target routes on
747
- * the item's own `root`, which is what every subscription meant before this
748
- * field existed — so the column and the config key are both nullable and the
749
- * default bundle keeps behaving exactly as it does today.
750
- */
751
- export const DeliverTargetSchema = v.picklist(['repo', 'global']);
752
- export const ResolvedSubscriptionSchema = v.object({
753
- id: v.string(),
754
- slug: BundleSlugSchema,
755
- name: v.string(),
756
- /** Every scope that names this bundle. Never empty; may hold both. */
757
- scopes: v.pipe(v.array(SubscriptionScopeSchema), v.minLength(1)),
758
- /**
759
- * The **account** subscription's delivery target, when there is an account
760
- * subscription and it names one.
761
- *
762
- * Only the account side, and deliberately so: the repo side's target lives in
763
- * the committed `.mossbear/config.json` on the caller's own disk, which the
764
- * server cannot read — the same asymmetry that makes this endpoint a round
765
- * trip at all. Echoing a value the caller just sent would make the server look
766
- * like the authority on a fact it does not hold. The caller pairs this with
767
- * its own committed `deliver` to build the per-scope target set
768
- * (`packages/cli/src/artifacts/delivery.ts` → `deliveryBundles`).
769
- *
770
- * Optional rather than nullable so a CLI built before this field parses a new
771
- * server's response unchanged, and a new CLI reads an old server's response as
772
- * "names no target" — which is the absent-field default either way.
773
- */
774
- deliver: v.optional(DeliverTargetSchema),
775
- /**
776
- * The bundle's home repo, when one claims it. Sent on every resolved
777
- * subscription regardless of scope, because it is a property of the *bundle*
778
- * rather than of either subscription — unlike `deliver`, which each scope
779
- * answers for itself.
780
- */
781
- home: v.optional(v.string()),
782
- /**
783
- * Ids this account has switched off for the asking machine, on a bundle that
784
- * reaches it through the account subscription alone. An item whose own id or
785
- * `guideId` is listed is not delivered.
786
- *
787
- * The server computes it per machine: artifacts switched off everywhere or
788
- * on this machine that this bundle can deliver, plus every member when the
789
- * bundle itself is switched off. Account-scoped and nowhere else: a repo
790
- * subscription is a committed file shared by everyone who clones it, so a
791
- * mute there would be one member deciding for the team. A muted guide leaves
792
- * the desired delivery list, and the global namespace prunes it once no repo
793
- * still refers to it — repo by repo, as each syncs, because the referrer
794
- * record is machine-local repo ids.
795
- */
796
- muted: v.optional(v.array(v.string())),
797
- /**
798
- * The same set as `muted`, sent instead of it when the calling repo's
799
- * committed config also subscribes this bundle. It applies to the account
800
- * target only: the repo's own subscription still delivers into the checkout,
801
- * because an off removes only what reaches the machine through the account.
802
- *
803
- * A separate key rather than `muted`, because a CLI that predates it applies
804
- * `muted` before either target is planned and would drop the repo delivery
805
- * too. That CLI ignores this key and delivers to both targets, which fails
806
- * toward the agent having the content.
807
- */
808
- accountMuted: v.optional(v.array(v.string())),
809
- ...publishedBundleMarks,
810
- /**
811
- * The address this bundle was resolved from, when the caller named it as
812
- * `<handle>/<slug>` in `repoBundleAddresses` rather than by id. Lets the
813
- * caller pair each committed address with the id it stands for.
814
- */
815
- address: v.optional(PublishedBundleAddressSchema),
816
- });
817
- /**
818
- * The ids a repo's committed config names. Sent rather than looked up, because
819
- * the committed file is on the caller's disk and the server has no way to read
820
- * it — that asymmetry is the whole reason delivery used to be written back into
821
- * the repo.
822
- */
823
- /**
824
- * Capped, like the other batch endpoints. The route expands this into
825
- * `inArray(bundles.id, …)`, one Postgres bind parameter per id, and the wire
826
- * protocol tops out at 65,535 of them — so an uncapped array lets a body well
827
- * under the request-size limit reach the database and fail as a 500 rather than
828
- * being refused as bad input. Raised by Codex on #735.
829
- */
830
- export const MAX_REPO_BUNDLE_IDS = 500;
831
- /** Capped for the reason `MAX_REPO_BUNDLE_IDS` gives. */
832
- export const MAX_REPO_BUNDLE_ADDRESSES = 64;
833
- export const ResolveSubscriptionsRequestSchema = v.object({
834
- repoBundleIds: v.pipe(v.array(v.string()), v.maxLength(MAX_REPO_BUNDLE_IDS)),
835
- /**
836
- * Published bundles the committed config names by address,
837
- * `<handle>/<slug>`, rather than by id. Optional, so a CLI that sends only
838
- * ids is answered as before.
839
- */
840
- repoBundleAddresses: v.optional(v.pipe(v.array(PublishedBundleAddressSchema), v.maxLength(MAX_REPO_BUNDLE_ADDRESSES))),
841
- /**
842
- * The calling machine's stable id (`MachineIdSchema`). Optional, so an older
843
- * CLI is answered as before; the server records it for the calling key only
844
- * when that key has none yet.
845
- */
846
- machineId: v.optional(MachineIdSchema),
847
- });
848
- export const ResolveSubscriptionsResponseSchema = v.object({
849
- /** The effective delivery set, de-duplicated by bundle id. */
850
- bundles: v.array(ResolvedSubscriptionSchema),
851
- /**
852
- * Committed ids the caller cannot see. **Reported, never dropped** — the line
853
- * was put in the config deliberately by whoever owns the repo, so a non-member
854
- * gets a named failure rather than deletion advice.
855
- *
856
- * It also names the caller's **account** subscriptions whose bundle they can
857
- * no longer read: one unpublished, or in a workspace they left. The row is
858
- * still theirs, so a sync must hold retirement for it as for a repo id it
859
- * cannot see, rather than read its absence as an empty bundle.
860
- */
861
- unresolved: v.array(v.object({ id: v.string() })),
862
- /**
863
- * Committed addresses (`repoBundleAddresses`) that name no published bundle.
864
- * Kept apart from `unresolved`, whose entries are ids, so a CLI that reads
865
- * `id` off every entry is never handed one without it. Absent when the
866
- * request named no address.
867
- */
868
- unresolvedAddresses: v.optional(v.array(v.object({ address: PublishedBundleAddressSchema }))),
869
- /**
870
- * Account-level settings the sync needs, carried on the response every sync
871
- * already fetches rather than on a request of their own.
872
- *
873
- * `deliverGlobalSkills` is the account's "Deliver my global skills" switch:
874
- * whether guides scoped to every repo may be written to the global skills
875
- * directories of every machine and cloud session this account syncs. Only a
876
- * signed-in browser session can change it; it is reported here, never
877
- * accepted. **Optional**, so a response from a server that predates it parses,
878
- * and the CLI reads its absence as "the server did not say", which delivers
879
- * nothing and removes nothing.
880
- */
881
- account: v.optional(v.object({
882
- deliverGlobalSkills: v.boolean(),
883
- })),
884
- /**
885
- * True when the caller's token is limited to certain bundles. Such a token
886
- * resolves only what it was granted, so an id in `unresolved` may be a bundle
887
- * the account can reach and the token cannot. Said once for the response,
888
- * never per id, so it confirms nothing about any one bundle. Optional: absent
889
- * means an ordinary token, and a server that predates it never sends it.
890
- */
891
- limitedToken: v.optional(v.boolean()),
892
- });
893
- /**
894
- * Subscribe the calling account to a bundle it can see, or change the delivery
895
- * target of a subscription it already has.
896
- *
897
- * **The product path to a non-default bundle** (`subscription-delivery-target-plan.md`
898
- * → slice 2). Before this, the only insert into `user_bundle_subscriptions` was
899
- * the one that mints an account's own capture bundle, so an account could not
900
- * subscribe to anything else without a hand-written row.
901
- *
902
- * Idempotent by the table's composite key: subscribing twice is one
903
- * subscription, and a second call carrying a different `deliver` updates it
904
- * rather than failing.
905
- */
906
- /** No account should be able to make one sync unboundedly expensive. */
907
- export const MAX_MUTED_GUIDE_IDS = 1000;
908
- export const SubscribeBundleRequestSchema = v.object({
909
- bundleId: v.string(),
910
- /**
911
- * Where this account's subscription delivers. **Three states, and all three
912
- * are reachable**: a value sets the target, an explicit `null` clears it back
913
- * to "route on the item's root", and omitting the field leaves whatever is
914
- * stored.
915
- *
916
- * The first shipped version made omission clear the target, so that "route on
917
- * the item's root" would stay reachable. It made a bare re-subscribe — the
918
- * commonest call there is — silently reset routing the caller never mentioned:
919
- * `mossbear pull <bundle> --account` a second time would wipe a target set the
920
- * first time, and print a success line saying nothing about it. Found by the
921
- * automated reviewer on #1246. A nullable field reaches the same state without
922
- * making silence mean a write.
923
- */
924
- deliver: v.optional(v.nullable(DeliverTargetSchema)),
925
- /**
926
- * The ids to have switched off on every machine, as far as this bundle can
927
- * deliver them — the whole set, replacing what is stored. `[]` switches them
928
- * all back on, and omitting the field leaves the stored set alone.
929
- *
930
- * An id switched off here is off for the account, through every bundle that
931
- * carries it. Switching one back on (an id this bundle delivers that is off
932
- * now and absent here) needs a dashboard session: a CLI key is refused with
933
- * 403, because an agent may narrow what it receives but never widen it.
934
- *
935
- * The same three states as `deliver` above, reached the same way: an explicit
936
- * empty clears, and silence never means a write. So changing a delivery target
937
- * cannot unmute anything, and muting cannot move a target.
938
- */
939
- muted: v.optional(v.pipe(v.array(v.string()), v.maxLength(MAX_MUTED_GUIDE_IDS))),
940
- });
941
- export const SubscribeBundleResponseSchema = v.object({
942
- bundleId: v.string(),
943
- /** False when the subscription was already there and only its target moved. */
944
- created: v.boolean(),
945
- deliver: v.optional(DeliverTargetSchema),
946
- /** The stored mute set after this write. Omitted when nothing is muted. */
947
- muted: v.optional(v.array(v.string())),
948
- });
949
- export const CreateBundleRequestSchema = v.object({
950
- description: v.optional(v.nullable(ArtifactDescriptionSchema)),
951
- slug: BundleSlugSchema,
952
- name: displayNameSchema(BUNDLE_NAME_MAX_LENGTH),
953
- // The workspace to create the bundle in. Omitted means the caller's default
954
- // workspace; a workspace the caller is not a member of is refused.
955
- workspaceId: v.optional(v.pipe(v.string(), v.minLength(1))),
956
- });
957
- export const CreateBundleResponseSchema = v.object({
958
- bundle: BundleSchema,
959
- });
960
109
  // Scoped tokens: a CLI key limited to chosen bundles, read or write on each.
961
110
  // The server enforces the limit; a key with no grants listed here is refused.
962
111
  export const SCOPED_TOKEN_MAX_GRANTS = 200;
@@ -995,107 +144,6 @@ export const ListScopedTokensResponseSchema = v.object({
995
144
  export const RevokeScopedTokenRequestSchema = v.object({
996
145
  id: NonEmptyStringSchema,
997
146
  });
998
- // A membership is addressed by the artifact id alone: a guide and its body are
999
- // one id, so no membership kind travels the wire. An older client may still send
1000
- // `itemType` on attach (or `?itemType=` on detach); this schema is not strict, so
1001
- // the field is dropped on parse rather than refused.
1002
- /**
1003
- * The member to attach, by its artifact id. `itemId` is the name a CLI from before
1004
- * release step 2 sends; both are read, and the parsed value is always `artifactId`.
1005
- * Drop `itemId` once no such CLI is left to send it.
1006
- */
1007
- /** The most artifacts one attach request may name. */
1008
- export const MAX_BUNDLE_MEMBERS_PER_ATTACH = 200;
1009
- export const AttachBundleMemberRequestSchema = v.pipe(v.object({
1010
- artifactId: v.optional(v.pipe(v.string(), v.minLength(1))),
1011
- itemId: v.optional(v.pipe(v.string(), v.minLength(1))),
1012
- // A list files them in one request and is answered per id, once for a
1013
- // repeated id (match results by `artifactId`, not by position)
1014
- // (`AttachBundleMembersResponseSchema`). The single-id forms keep their
1015
- // body and their `{ attached }` answer for CLIs that predate the list.
1016
- artifactIds: v.optional(v.pipe(v.array(v.pipe(v.string(), v.minLength(1))),
1017
- // Before the cap, so the cap counts distinct artifacts.
1018
- v.transform((ids) => [...new Set(ids)]), v.minLength(1), v.maxLength(MAX_BUNDLE_MEMBERS_PER_ATTACH))),
1019
- }), v.check((request) => request.artifactIds === undefined
1020
- ? request.artifactId !== undefined || request.itemId !== undefined
1021
- : request.artifactId === undefined && request.itemId === undefined, 'A member needs an artifactId, or a list of artifactIds on its own.'), v.transform((request) => request.artifactIds
1022
- ? { artifactIds: request.artifactIds }
1023
- : { artifactId: (request.artifactId ?? request.itemId) }));
1024
- export const AttachBundleMemberResponseSchema = v.object({
1025
- // False when the item was already a member — attach is idempotent, and the
1026
- // caller (multi-select menu applying a diff) treats both as success.
1027
- attached: v.boolean(),
1028
- });
1029
- /**
1030
- * One id's outcome in a list attach. `unavailable` is every refusal that is not
1031
- * a path collision, and reads the same whether the artifact is missing, not the
1032
- * caller's to file or in another workspace, so a list cannot probe which ids
1033
- * exist.
1034
- */
1035
- export const AttachBundleMembersResultSchema = v.object({
1036
- artifactId: v.string(),
1037
- status: v.picklist(['added', 'already_there', 'unavailable', 'path_taken']),
1038
- });
1039
- export const AttachBundleMembersResponseSchema = v.object({
1040
- results: v.array(AttachBundleMembersResultSchema),
1041
- });
1042
- export const DetachBundleMemberResponseSchema = v.object({
1043
- detached: v.boolean(),
1044
- });
1045
- /**
1046
- * The most field keys a bundle's shared column list may hold, and the longest
1047
- * one. A key is a frontmatter key as written, so the bound is on what a
1048
- * dashboard could ever show as a column rather than on any real key's length;
1049
- * both are generous enough that a refusal means a client bug.
1050
- */
1051
- export const BUNDLE_COLUMNS_MAX_COUNT = 100;
1052
- export const BUNDLE_COLUMN_KEY_MAX_LENGTH = 200;
1053
- /**
1054
- * A bundle's shared column list: field keys in display order, no key twice.
1055
- * An array that repeats a key is refused rather than deduplicated, since the
1056
- * order is the content and a client that sent one has lost track of its own
1057
- * list.
1058
- */
1059
- 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'));
1060
- // Rename changes the display name only. The slug is the bundle's identity —
1061
- // repos subscribe by slug in `.mossbear/config.json` → `bundles`, and
1062
- // `mossbear pull <slug>` addresses it — so a slug change would silently break
1063
- // every subscribed repo (context-bundle-authoring-plan.md → D14).
1064
- /**
1065
- * What `PATCH /api/v1/context/bundles/:id` may change: the display name, the
1066
- * home repo, the shared column list, or any of them. The slug stays immutable
1067
- * — repos address a bundle by id and name it by slug, so a slug change would
1068
- * rename a folder in every subscriber's checkout.
1069
- *
1070
- * Every field optional, with a check that at least one is present: a body that
1071
- * changes nothing is a request the caller did not mean to send, and answering it
1072
- * 200 would hide a client bug. `home: null` clears the claim, which is how a
1073
- * repo hands a bundle back — distinct from omitting the field, which leaves it.
1074
- * `columns: null` is the same for the column list: it returns the bundle to
1075
- * "not chosen", where every shared field shows.
1076
- */
1077
- export const UpdateBundleRequestSchema = v.pipe(v.object({
1078
- name: v.optional(displayNameSchema(BUNDLE_NAME_MAX_LENGTH)),
1079
- home: v.optional(v.nullable(v.pipe(v.string(), v.minLength(1), v.maxLength(200)))),
1080
- columns: v.optional(v.nullable(BundleColumnsSchema)),
1081
- description: v.optional(v.nullable(ArtifactDescriptionSchema)),
1082
- }), v.check((value) => value.name !== undefined ||
1083
- value.home !== undefined ||
1084
- value.columns !== undefined ||
1085
- value.description !== undefined, 'name, home, columns or description is required'));
1086
- export const UpdateBundleResponseSchema = v.object({
1087
- bundle: BundleSchema,
1088
- });
1089
- export const DeleteBundleResponseSchema = v.object({
1090
- deleted: v.boolean(),
1091
- // `movedToInbox` was removed in `inbox-as-view` slice 2. Deleting a bundle no
1092
- // longer re-parents anything: an item that loses its last membership is
1093
- // unfiled, which is what the inbox view shows, rather than stranded. The
1094
- // field could only ever have reported 0 afterwards, and a number that can
1095
- // never be non-zero is a discriminator carrying no decision. Nothing on the
1096
- // CLI wire parsed it — `parseDeleteBundleResponse` has one caller, the
1097
- // dashboard's own bundles client.
1098
- });
1099
147
  // ---------------------------------------------------------------------------
1100
148
  // Context item + inbox schemas (context-layer-mcp-inbox-plan.md — Phase 1a)
1101
149
  // ---------------------------------------------------------------------------
@@ -1142,223 +190,6 @@ export const GuideAliasSchema = v.object({
1142
190
  root: GuideDiscoveryRootSchema,
1143
191
  path: SafeRelativePosixPathSchema,
1144
192
  });
1145
- /**
1146
- * The markers every untrusted block in a response is wrapped in, plus a
1147
- * statement of what they mean.
1148
- *
1149
- * Generated per response from the content itself, so no marker-like text
1150
- * inside a block can end it early — a property `deriveDelimiterToken` checks
1151
- * rather than assumes.
1152
- *
1153
- * Named for the guide-history response it was written for and shared by every
1154
- * payload that places somebody else's words in front of an agent: a grade's
1155
- * reasoning, and now an item's comments. One marker scheme, not one per payload —
1156
- * a second scheme is a second thing a reader has to be taught to respect.
1157
- * Declared here, above its first user, rather than beside that response.
1158
- */
1159
- export const GuideHistoryUntrustedSchema = v.object({
1160
- token: NonEmptyStringSchema,
1161
- startMarker: NonEmptyStringSchema,
1162
- endMarker: NonEmptyStringSchema,
1163
- note: v.string(),
1164
- });
1165
- /**
1166
- * How many open comments one item carries on the wire, newest first.
1167
- *
1168
- * A wire bound, not a product limit: the write side refuses the comment that
1169
- * would exceed it *by name* (see the dashboard's note mutator), so this cap is
1170
- * never the thing that silently drops a comment a person left.
1171
- */
1172
- export const MAX_ITEM_COMMENTS_ON_WIRE = 20;
1173
- /**
1174
- * How many replies one delivered thread carries, the newest kept. A thread past
1175
- * it says how many it held back (`repliesWithheld`), so a cut is never silent.
1176
- */
1177
- export const MAX_REPLIES_PER_THREAD_ON_WIRE = 10;
1178
- /**
1179
- * The most entries one item's `comments` can hold once threads ride it: a
1180
- * person's allowance of roots plus an agent's own, each followed by its replies.
1181
- * A client that does not render threads is sent roots alone, which stay within
1182
- * `MAX_ITEM_COMMENTS_ON_WIRE`.
1183
- */
1184
- export const MAX_ITEM_THREAD_ENTRIES_ON_WIRE = 2 * MAX_ITEM_COMMENTS_ON_WIRE * (1 + MAX_REPLIES_PER_THREAD_ON_WIRE);
1185
- /**
1186
- * Who wrote a comment. An agent writes under its person's account, so the
1187
- * author's name alone cannot tell a person's answer from an agent's message.
1188
- */
1189
- export const CommentAuthorKindSchema = v.picklist(['person', 'agent', 'mossbear']);
1190
- /** What a finding rests on: graded sessions, how loads read a skill, or the rubric alone. */
1191
- export const FindingTierSchema = v.picklist(['observed', 'usage', 'practice']);
1192
- /**
1193
- * What a Mossbear finding carries on the comment read, besides its claim.
1194
- *
1195
- * `tierLine` and `blindSpot` are written by the server from data it holds —
1196
- * the cited sessions, the load counts, the rubric check — never by a model, so
1197
- * they sit outside the response's untrusted markers. `prediction` is
1198
- * model-authored and arrives inside them. A finding never carries replacement
1199
- * text: the reader's agent has the repository and writes the fix.
1200
- */
1201
- export const CommentFindingSchema = v.object({
1202
- tier: FindingTierSchema,
1203
- /** How the finding is known, in one line: "Seen in 3 sessions (2026-09-15 – 2026-10-03)". */
1204
- tierLine: v.pipe(v.string(), v.maxLength(300)),
1205
- /** What the drafter did not read, fixed per tier. */
1206
- blindSpot: v.pipe(v.string(), v.maxLength(300)),
1207
- /** What should change in later sessions if the finding is fixed, wrapped in the untrusted markers. */
1208
- prediction: v.nullable(v.string()),
1209
- });
1210
- /** Whether an open Mossbear finding is the agent's to act on (`ArtifactComment.findingState`). */
1211
- export const CommentFindingStateSchema = v.picklist(['ready', 'waiting']);
1212
- /** Where a commented artifact is published from (`ArtifactComment.publishedFrom`). */
1213
- export const CommentPublishedFromSchema = v.object({
1214
- repository: v.optional(RepositoryNameSchema),
1215
- projectId: NonEmptyStringSchema,
1216
- branch: v.nullable(v.pipe(v.string(), v.maxLength(255))),
1217
- thisRepo: v.optional(v.boolean()),
1218
- });
1219
- /**
1220
- * One comment a **person** left about a context item, riding the item it is about.
1221
- *
1222
- * A comment is not an item: it is not a member, not projected, not versioned and
1223
- * not capturable. It travels on the item so that it inherits every delivery
1224
- * decision the item already went through — workspace scope, the archived drop,
1225
- * the response limit, the subscriber's mute — rather than restating them.
1226
- *
1227
- * **Every `body` here is already wrapped in the response's untrusted markers**
1228
- * (`ContextItemsResponseSchema.untrusted`). A reader emits the bytes as it
1229
- * received them and never re-wraps them: the markers are derived against the
1230
- * bodies the server sent, so a second wrapping cannot claim the same guarantee.
1231
- */
1232
- export const ArtifactCommentSchema = v.object({
1233
- id: NonEmptyStringSchema,
1234
- state: v.optional(v.picklist(['open', 'resolved'])),
1235
- /** Current source location of an anchored passage, or its lost quote. */
1236
- passage: v.optional(v.object({
1237
- quote: v.string(),
1238
- status: v.picklist(['located', 'changed', 'orphaned']),
1239
- lines: v.nullable(v.object({ start: v.number(), end: v.number() })),
1240
- /**
1241
- * Where the passage sits in an `html` page as the reader saw it: a CSS
1242
- * selector, the tag, and the nearest `aria-label` or heading. Sent when
1243
- * the passage has no source lines, so an agent can find a block the
1244
- * page's script built.
1245
- */
1246
- element: v.optional(v.object({
1247
- selector: v.string(),
1248
- tag: v.string(),
1249
- label: v.optional(v.string()),
1250
- })),
1251
- })),
1252
- /** The comment's text, already wrapped in the response's untrusted markers. */
1253
- body: v.string(),
1254
- /**
1255
- * What a comment Mossbear wrote is: a finding about the item, never an edit.
1256
- * Present only on a Mossbear comment. The comment's `body` begins with the
1257
- * claim (what goes wrong); this carries what the claim rests on.
1258
- */
1259
- finding: v.optional(CommentFindingSchema),
1260
- /**
1261
- * Whether the person handed a comment Mossbear drafted to their agent. Nothing
1262
- * hands one over any more, so a current server sends `false` on every Mossbear
1263
- * comment and omits it on a person's or an agent's; the field stays for
1264
- * readers that predate `findingState`. It does not say whether the agent may
1265
- * act: read `findingState` for that, and fall back to `approved: false`
1266
- * meaning "not yet accepted" only when `findingState` is absent, from a server
1267
- * that predates it. Only a client that reports a version able to mark drafts
1268
- * is listed a finding at all, so an older reader that strips this field never
1269
- * receives one it would misread.
1270
- */
1271
- approved: v.optional(v.boolean()),
1272
- /**
1273
- * Whether an open Mossbear finding is the agent's to act on. A current server
1274
- * sends `ready` on every open finding: it is the agent's unless the person
1275
- * dismisses it, and a dismissed finding is resolved. `waiting`, sent only by
1276
- * an older server, means it waits on the person: show it to the user and
1277
- * change nothing unless they say so. Present only on an open Mossbear
1278
- * comment. A server that predates the field omits it, and a reader then
1279
- * falls back to `approved`. This is a new name rather than a new meaning for
1280
- * `state`, which already says open or resolved.
1281
- */
1282
- findingState: v.optional(CommentFindingStateSchema),
1283
- /**
1284
- * Where the artifact is published from, when Mossbear records one: the
1285
- * committed `project.id` of the repository whose commits own it, and the
1286
- * branch it was published from (null when none was recorded). `thisRepo` is
1287
- * true when that is the repo the read declared, false when it is another repo,
1288
- * and absent when the read declared no repo. The field is absent when Mossbear
1289
- * records no publishing repo, which is not a claim that the artifact is
1290
- * Mossbear-owned.
1291
- */
1292
- publishedFrom: v.optional(CommentPublishedFromSchema),
1293
- /** The author's display name as the workspace shows it, or null. Never an email. */
1294
- authorName: v.nullable(v.string()),
1295
- /**
1296
- * Who wrote it. Optional because a server that predates the field omits it;
1297
- * a reader that meets a reply without it cannot tell whose it is, and a
1298
- * server never sends a reply to a client too old to read this.
1299
- */
1300
- authorKind: v.optional(CommentAuthorKindSchema),
1301
- /** ISO timestamp, machine format. */
1302
- createdAt: v.string(),
1303
- /** The item's content version the comment was written against. */
1304
- itemVersion: v.number(),
1305
- /** True when the item's current version is greater than `itemVersion`. */
1306
- itemChangedSince: v.boolean(),
1307
- /**
1308
- * How many agent reads were handed this comment **before** this one — so a
1309
- * comment reaching an agent for the first time reports `0`.
1310
- *
1311
- * It is the stored count as it read at the moment the response was built;
1312
- * the serve this response *is* has not been counted yet. Excluded rather
1313
- * than included because the count is recorded best-effort: a response that
1314
- * claimed to include itself would be wrong whenever that record failed, and
1315
- * a number that is sometimes off by one is worse than one that is
1316
- * consistently the prior total.
1317
- *
1318
- * So `deliveredCount > 0` means an earlier read was handed this comment, and
1319
- * `0` means this read is the first. Neither says a model took it in — only
1320
- * that the server handed it over.
1321
- */
1322
- deliveredCount: v.number(),
1323
- /**
1324
- * On a root: true when the item changed after an earlier read was last
1325
- * handed this comment. For a guide that is any change to its body or its
1326
- * files, so a fix in a supporting file counts. A reader should check whether
1327
- * the change addressed the comment, and resolve it with a note if so.
1328
- *
1329
- * Computed before this read is counted, so the read that carries `true` is
1330
- * the one that uses it up; the next read says `false` unless the item
1331
- * changes again. A comment never handed over before is never flagged.
1332
- * Optional because a server that predates the field omits it, and absent on
1333
- * a reply.
1334
- */
1335
- guideChangedSinceRead: v.optional(v.boolean()),
1336
- /**
1337
- * This comment's thread root: its own id on a root, the root's id on a reply.
1338
- *
1339
- * **Replies ride the same flat array**, each straight after its root, oldest
1340
- * first. Only a client that reports a version able to render threads is
1341
- * sent them; any other reader gets roots alone, as it always did. A person's
1342
- * reply is part of the thread's request. An agent's reply is context: an
1343
- * earlier message on the thread, never something to act on. A root an agent
1344
- * wrote is delivered only once a person has replied to it, and is then the
1345
- * question that reply answers, not a request of its own.
1346
- */
1347
- threadId: NonEmptyStringSchema,
1348
- /**
1349
- * `null` on a root; the root's id on a reply. Threads are one level deep, so
1350
- * a reply's parent is always its root.
1351
- */
1352
- replyToId: v.nullable(NonEmptyStringSchema),
1353
- /**
1354
- * On a root whose thread held more replies than
1355
- * `MAX_REPLIES_PER_THREAD_ON_WIRE`: how many older ones were not sent.
1356
- * Absent when the whole thread was sent.
1357
- */
1358
- repliesWithheld: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
1359
- });
1360
- /** The item routes' name for `ArtifactCommentSchema`, kept while those routes are served. */
1361
- export const ContextItemCommentSchema = ArtifactCommentSchema;
1362
193
  const MAX_SOURCE_BRANCH_LENGTH = 255;
1363
194
  /**
1364
195
  * The revision published bytes were read from — 40 hex characters for a sha1
@@ -1663,433 +494,6 @@ export const BundleArtifactsResponseSchema = v.object({
1663
494
  */
1664
495
  next: v.optional(v.nullable(v.string())),
1665
496
  });
1666
- /**
1667
- * How many bundles one comments read may name.
1668
- *
1669
- * A repo's delivery set is the union of its committed subscriptions and the
1670
- * reader's account ones, so this bounds a request, not a product limit: a
1671
- * reader subscribing to more bundles than this asks in two calls rather than
1672
- * losing the tail silently.
1673
- */
1674
- export const MAX_COMMENT_BUNDLE_IDS = 100;
1675
- /**
1676
- * The agent session behind a comment, a reply or a resolution note, as the
1677
- * caller's harness reported it. Stored on the row so the reply is named after
1678
- * that session; it is the caller's claim, read only among its own comments.
1679
- */
1680
- export const AgentIdentitySchema = v.object({
1681
- sessionId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),
1682
- harness: HarnessIdSchema,
1683
- /** The agent's own statement of its model, when it knows it. */
1684
- model: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))),
1685
- cliVersion: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64))),
1686
- });
1687
- /**
1688
- * `POST /api/v1/context/comments/resolve`: close one open comment and leave the
1689
- * agent's note as a reply in its thread.
1690
- *
1691
- * **Two ways to find the comment, never both at once.** Without `artifactId`,
1692
- * the id is looked up among the comments the named bundles deliver, which is
1693
- * what `list_comments` listed. With it, the id is looked up among that one
1694
- * artifact's open comments, which is what its feedback read listed, after the
1695
- * same read check that read makes. A request with `artifactId` does not fall
1696
- * back to the bundles when the id is not on that artifact.
1697
- */
1698
- export const ResolveItemCommentRequestSchema = v.object({
1699
- /** The comment's id, or a unique prefix of it as a read printed it. */
1700
- id: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
1701
- /** One line, kept in the thread as the agent's reply. */
1702
- note: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(500), v.regex(/^[^\r\n]+$/)),
1703
- /** The bundles this repo receives. Ignored when `artifactId` is sent. */
1704
- bundleIds: v.optional(v.pipe(v.array(NonEmptyStringSchema), v.maxLength(MAX_COMMENT_BUNDLE_IDS)), []),
1705
- /** The artifact the comment is on, as its feedback read was asked for it. */
1706
- artifactId: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(128))),
1707
- /**
1708
- * The reader's repo, as its committed `project.id`. A comment drafted from
1709
- * one repo's corrections is listed only to a read that declares that repo,
1710
- * so it is resolvable only by one that declares it too.
1711
- */
1712
- projectId: v.optional(ProjectIdSchema),
1713
- /** The CLI's version, so a draft resolves only for a client that marks drafts. */
1714
- cliVersion: v.optional(v.pipe(v.string(), v.maxLength(64))),
1715
- /**
1716
- * The agent session resolving it, stored on the note so the thread names
1717
- * who closed it. Optional: releases before it was sent resolve without one,
1718
- * and their notes read as an unnamed agent.
1719
- */
1720
- agent: v.optional(AgentIdentitySchema),
1721
- });
1722
- /** A resolve the server carried out. Every refusal is an error response instead. */
1723
- export const ResolveItemCommentResponseSchema = v.object({
1724
- resolved: v.literal(true),
1725
- });
1726
- /**
1727
- * How many times one subscriber is told, in one repo, that a given comment is
1728
- * waiting before the hook falls silent about it.
1729
- *
1730
- * **A cap on the interruption, never on the comment.** After it is reached the
1731
- * comment is still open, still on the item page, and still returned in full by
1732
- * the on-demand read — it simply stops being announced in front of the first
1733
- * turn of every session. So silence here means "nothing new to interrupt you
1734
- * about", never "nobody left anything".
1735
- *
1736
- * Three rather than one, for the reason the announcement exists: the first
1737
- * session in a repo is often doing unrelated work, so a one-shot announcement
1738
- * would routinely spend itself on the session least likely to act. Three is a
1739
- * judgement, named so replacing it is one edit — the same discipline the live
1740
- * session window is held to.
1741
- */
1742
- export const MAX_COMMENT_ANNOUNCEMENTS_PER_REPO = 3;
1743
- /**
1744
- * Ask which comments are waiting for this reader in this repo, and be counted as
1745
- * told.
1746
- *
1747
- * **A write, because being told is a fact the server has to keep.** The count
1748
- * cannot be `item_comments.delivered_count` — that is one global number across
1749
- * every subscriber and every repo, so one reader's fill of a comment would
1750
- * silence it for everyone — and it cannot live in the checkout, because the
1751
- * disposable environments this exists for rebuild the clone every session and
1752
- * a counter there resets with it, announcing every unresolved comment as new
1753
- * forever.
1754
- */
1755
- export const AnnounceItemCommentsRequestSchema = v.object({
1756
- /**
1757
- * The repo, as its committed config declares it. Required: it is the scope
1758
- * the count is kept under, and a request with nothing to key on could only
1759
- * be answered by an uncapped announcement — which is the repeating broadcast
1760
- * this route exists to end.
1761
- */
1762
- projectId: ProjectIdSchema,
1763
- /**
1764
- * The bundles this repo receives — the union the caller already resolved.
1765
- *
1766
- * Sent rather than derived, because only half of it is the server's to know:
1767
- * a repo-scoped subscription lives in the committed config and travels by
1768
- * `git clone`. Declaring a bundle grants nothing: every one of them is still
1769
- * filtered by the caller's own workspace membership.
1770
- */
1771
- bundleIds: v.pipe(v.array(NonEmptyStringSchema), v.maxLength(MAX_COMMENT_BUNDLE_IDS)),
1772
- /**
1773
- * The release asking. A person's reply on a thread counts as waiting only
1774
- * for a release that renders threads; without it the answer is the roots-only
1775
- * count every older release was given.
1776
- */
1777
- cliVersion: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64))),
1778
- });
1779
- /**
1780
- * What an announcement answers: how many comments are waiting, and how many of
1781
- * them this call was counted as announcing.
1782
- *
1783
- * **Two numbers because they answer two questions and a reader needs both.**
1784
- * `open` is the true state of this repo's comments and is what a caller shows a
1785
- * person — a number that is sometimes a subset of the truth would be worse
1786
- * than the silence it replaced. `announced` is how many of those were still
1787
- * under the cap, and it is the one that decides whether to speak at all: zero
1788
- * means this reader has already been told about every one of them as often as
1789
- * the cap allows.
1790
- */
1791
- export const AnnounceItemCommentsResponseSchema = v.object({
1792
- /** Open, unmuted comments about the items these bundles deliver to this reader. */
1793
- open: v.pipe(v.number(), v.integer(), v.minValue(0)),
1794
- /** How many of those were under the cap and have now been counted as announced. */
1795
- announced: v.pipe(v.number(), v.integer(), v.minValue(0)),
1796
- });
1797
- /**
1798
- * How many comments one agent session may leave on one subject, not counting its
1799
- * whole-subject comment. Anchored comments and replies share it.
1800
- */
1801
- export const MAX_AGENT_COMMENTS_PER_SUBJECT = 50;
1802
- /** The longest an agent comment's text may be, in characters. */
1803
- export const MAX_AGENT_COMMENT_BODY_CHARS = 4000;
1804
- /**
1805
- * Why an agent comment was refused, as the `code` on the error body. A caller
1806
- * branches on these; the message beside one is for a person.
1807
- */
1808
- export const AGENT_COMMENT_ERROR_CODES = [
1809
- /** The request named no agent session. The CLI never makes one up. */
1810
- 'agent_session_required',
1811
- /** This agent session has used its comments on the subject. */
1812
- 'agent_comment_limit_reached',
1813
- /** An agent comment is text only: it may not carry replacement text. */
1814
- 'agent_comment_text_only',
1815
- /** The subject or comment is not one this account can comment on. */
1816
- 'agent_comment_target_missing',
1817
- /** A comment names a passage that is not whole lines of the item as it is now. */
1818
- 'agent_comment_passage_not_found',
1819
- /** The passage appears more than once, so which one is meant is unknown. */
1820
- 'agent_comment_passage_ambiguous',
1821
- /** The item already carries as many open comments as it may. */
1822
- 'item_comment_limit_reached',
1823
- ];
1824
- export const AgentCommentErrorCodeSchema = v.picklist(AGENT_COMMENT_ERROR_CODES);
1825
- const AgentCommentTargetIdSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(128));
1826
- /**
1827
- * Leave a comment, or reply to one, as an agent (`POST /api/v1/context/comments`).
1828
- *
1829
- * **`target` names what the comment is about, one way.** `artifact` is the id
1830
- * a bundle read gave for a guide or document, and `item` is its older name for
1831
- * the same thing, accepted until every client sends `artifact`. `session` is an
1832
- * agent session id of the caller's own (the key a search hit and the session digest hand out), and
1833
- * `reply` is the id of a comment to answer. A reply joins that comment's thread
1834
- * and the subject it is about.
1835
- *
1836
- * **Who the agent is comes from `agent`, and `sessionId` is the harness's own
1837
- * id as the CLI read it.** A request without one is refused with
1838
- * `agent_session_required`, and the CLI and tool offer no way to type one. The
1839
- * server cannot check it against the harness, so it is a claim by the holder of
1840
- * the token: the comment is always written under that token's account, and the
1841
- * handle shown for it names a session only as far as the claim is true.
1842
- *
1843
- * **Text only.** There is no replacement-text field, and a request that carries
1844
- * one is refused with `agent_comment_text_only` rather than having it dropped.
1845
- */
1846
- export const AgentCommentRequestSchema = v.object({
1847
- target: v.variant('kind', [
1848
- v.object({ kind: v.literal('artifact'), id: AgentCommentTargetIdSchema }),
1849
- v.object({ kind: v.literal('session'), id: AgentCommentTargetIdSchema }),
1850
- v.object({ kind: v.literal('reply'), id: AgentCommentTargetIdSchema }),
1851
- ]),
1852
- body: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_AGENT_COMMENT_BODY_CHARS)),
1853
- /**
1854
- * The passage an item comment is about, as the exact text of one or more whole
1855
- * lines of the item (a paragraph, a heading, a list). None means the item as a
1856
- * whole. The server finds the lines; a passage that is not in the item as it is
1857
- * now is refused with `agent_comment_passage_not_found`.
1858
- */
1859
- passage: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(8000))),
1860
- agent: AgentIdentitySchema,
1861
- /**
1862
- * The reader's repo, as its committed `project.id`. A reply may name a
1863
- * comment by the unique id prefix `list_comments` printed, and a comment
1864
- * drafted from one repo's corrections is listed only to a read that declares
1865
- * that repo, so it is matched only by a reply that declares it too.
1866
- */
1867
- projectId: v.optional(ProjectIdSchema),
1868
- /**
1869
- * The bundles the reader's `list_comments` was scoped to, so an id prefix
1870
- * printed there is matched among exactly those bundles. Without it the prefix
1871
- * is matched among every bundle the caller can reach.
1872
- */
1873
- bundleIds: v.optional(v.pipe(v.array(NonEmptyStringSchema), v.maxLength(MAX_COMMENT_BUNDLE_IDS))),
1874
- });
1875
- /** A batch may cover findings across several guides without one write per finding. */
1876
- export const MAX_FINDING_DISMISSALS_PER_REQUEST = 100;
1877
- export const FindingDismissalInputSchema = v.object({
1878
- id: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),
1879
- reason: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(1000), v.check((reason) => !/[\r\n]/.test(reason), 'Use one line for the reason.')),
1880
- });
1881
- export const FindingDismissalInputsSchema = v.pipe(v.array(FindingDismissalInputSchema), v.minLength(1), v.maxLength(MAX_FINDING_DISMISSALS_PER_REQUEST), v.check((rows) => new Set(rows.map((row) => row.id)).size === rows.length, 'Name each finding only once.'));
1882
- export const SuggestFindingDismissalsRequestSchema = v.object({
1883
- suggestions: FindingDismissalInputsSchema,
1884
- agent: AgentCommentRequestSchema.entries.agent,
1885
- });
1886
- /** Recommendations are separate from the finding's open/resolved state. */
1887
- export const FindingDismissalSuggestionSchema = v.object({
1888
- id: NonEmptyStringSchema,
1889
- commentId: NonEmptyStringSchema,
1890
- reason: NonEmptyStringSchema,
1891
- agent: AgentCommentRequestSchema.entries.agent,
1892
- guideVersion: v.number(),
1893
- createdAt: v.string(),
1894
- });
1895
- export const SuggestFindingDismissalsResponseSchema = v.object({
1896
- results: v.array(v.object({
1897
- suggestion: FindingDismissalSuggestionSchema,
1898
- created: v.boolean(),
1899
- valid: v.boolean(),
1900
- })),
1901
- });
1902
- export const FindingDismissalSuggestionsCursorSchema = v.object({
1903
- id: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
1904
- createdAt: v.pipe(v.string(), v.isoTimestamp()),
1905
- });
1906
- export const FindingDismissalSuggestionsResponseSchema = v.object({
1907
- suggestions: v.array(FindingDismissalSuggestionSchema),
1908
- nextCursor: v.nullable(FindingDismissalSuggestionsCursorSchema),
1909
- });
1910
- /**
1911
- * The comment a create settled on. `created` is false when this agent session
1912
- * already had a whole-subject comment on the subject: that comment comes back
1913
- * unchanged and nothing was written.
1914
- */
1915
- export const AgentCommentResponseSchema = v.object({
1916
- created: v.boolean(),
1917
- comment: v.object({
1918
- id: v.string(),
1919
- threadId: v.string(),
1920
- subject: v.object({
1921
- kind: v.picklist(['artifact', 'session']),
1922
- id: v.string(),
1923
- }),
1924
- body: v.string(),
1925
- createdAt: v.string(),
1926
- }),
1927
- });
1928
- /**
1929
- * One comment on the on-demand read, with the item it is about named on the comment.
1930
- *
1931
- * The item is named here rather than the comments riding an item, because this
1932
- * read answers "what has been left for me" rather than "what is in this
1933
- * bundle": there is no item payload to hang them off, and an agent that has to
1934
- * ask for every item to find out whether one carries a comment is the round trip
1935
- * the announcement exists to avoid.
1936
- */
1937
- export const ItemCommentWithSubjectSchema = v.object({
1938
- ...ContextItemCommentSchema.entries,
1939
- /** The item the comment is about, as the wire names it. */
1940
- itemName: v.string(),
1941
- /** The item's declared repo-relative path, or null when it has none. */
1942
- itemPath: v.nullable(v.string()),
1943
- });
1944
- /**
1945
- * Every open comment waiting for this reader across the bundles they named.
1946
- *
1947
- * **This read is a delivery and is counted as one**, exactly as comments riding
1948
- * an item are: a body reached an agent. What it is *not* is an announcement —
1949
- * nothing here touches the per-repo announcement count, so asking to read your
1950
- * comments never spends the interruptions the hook is allowed.
1951
- *
1952
- * **Never capped.** The announcement cap governs whether a hook speaks; a
1953
- * reader who asked is owed every open comment, and hiding one here would retire a
1954
- * person's request without anybody deciding to.
1955
- */
1956
- export const ItemCommentsResponseSchema = v.object({
1957
- comments: v.array(ItemCommentWithSubjectSchema),
1958
- cursor: v.optional(v.string()),
1959
- /**
1960
- * The markers every `body` above is wrapped in, plus a statement of what
1961
- * they mean. Present exactly when at least one comment came back.
1962
- */
1963
- untrusted: v.optional(v.nullable(GuideHistoryUntrustedSchema)),
1964
- });
1965
- /**
1966
- * The evidence behind one Mossbear finding an agent was handed
1967
- * (`GET /api/v1/context/comments/evidence`).
1968
- *
1969
- * `list_comments` carries the claim and a one-line tier; this is the finding
1970
- * in full: the claim, the change it predicts in future sessions, what the
1971
- * drafter did not read, and the evidence for its tier. Readable only through a
1972
- * comment the comment read itself would deliver to this reader, so another
1973
- * person's finding, one drafted from another repo, or a draft listed only to a
1974
- * newer client has no evidence here either. A draft the reader was listed
1975
- * does: an agent can say why it was raised before the person approves it.
1976
- *
1977
- * Citations (observed and usage findings) are reduced to what the reader may
1978
- * see: their own sessions, with a date and a short excerpt of the grader's
1979
- * reasoning or of their own redacted correction turn. A `navigation` citation
1980
- * has an empty excerpt: it is dated evidence that a session loaded the skill,
1981
- * and nothing more. `citationsWithheld` counts any that were dropped, so a
1982
- * short list is never mistaken for the whole of it.
1983
- */
1984
- export const CommentEvidenceCitationSchema = v.object({
1985
- /**
1986
- * `navigation` is a skill load counted when a finding was drafted from how
1987
- * the skill's files were read: evidence of how a skill was used, not of a
1988
- * failure. `action` is a recorded step of a workflow repeated across
1989
- * sessions. `discrepancy` is a grader's note that a session's closing report
1990
- * contradicted its recorded actions; its excerpt is the agent's quoted claim
1991
- * and the record. `artifact_comment` is a person's comment on an artifact the
1992
- * cited session wrote; its excerpt is the comment. A server sends `action`,
1993
- * `discrepancy` and `artifact_comment` only to a client that names a version
1994
- * new enough to parse them.
1995
- */
1996
- kind: v.picklist([
1997
- 'verdict',
1998
- 'turn',
1999
- 'navigation',
2000
- 'action',
2001
- 'discrepancy',
2002
- 'artifact_comment',
2003
- ]),
2004
- sessionId: NonEmptyStringSchema,
2005
- /** ISO, when the verdict was graded, the turn was said, the skill loaded, or the action was recorded. */
2006
- at: v.string(),
2007
- /** Wrapped in the response's untrusted markers. */
2008
- excerpt: v.string(),
2009
- });
2010
- /** What a usage finding adds to its citations: the counts for one reference file. */
2011
- export const CommentEvidenceUsageSchema = v.object({
2012
- /** The reference's skill-relative path, wrapped in the response's untrusted markers. */
2013
- path: v.string(),
2014
- /** Eligible loads of the skill. */
2015
- loads: v.pipe(v.number(), v.integer()),
2016
- /** Distinct sessions those loads span. */
2017
- sessions: v.pipe(v.number(), v.integer()),
2018
- /** Loads followed by a successful read of the reference. */
2019
- loadsWithRead: v.pipe(v.number(), v.integer()),
2020
- });
2021
- /**
2022
- * What a practice finding adds: the rubric check it answers and the rubric's
2023
- * version, the practice lines it weighs with their sources, the facts measured
2024
- * from the file, and the answer to each item of evidence the check asks for.
2025
- * `answers[].answer` is model-written, so it travels wrapped in the response's
2026
- * untrusted markers.
2027
- */
2028
- export const CommentEvidencePracticeSchema = v.object({
2029
- check: v.object({ id: v.string(), name: v.string() }),
2030
- rubricVersion: v.pipe(v.number(), v.integer()),
2031
- // Optional, so a CLI reads a dashboard that has not shipped these fields yet:
2032
- // the two release independently.
2033
- practices: v.optional(v.array(v.object({
2034
- text: v.string(),
2035
- source: v.object({ title: v.string(), url: v.string() }),
2036
- })), []),
2037
- facts: v.optional(v.array(v.string()), []),
2038
- answers: v.optional(v.array(v.object({ item: v.string(), answer: v.string() })), []),
2039
- });
2040
- /**
2041
- * A comment the person (or Mossbear) left on one of the sessions a finding
2042
- * cites — the person's own account of what the agent should have known, set
2043
- * beside the grader's excerpt (`guide-findings-plan.md` → Your note on a
2044
- * session).
2045
- *
2046
- * **Reachable only here.** A comment about a session is never listed by
2047
- * `list_comments` or announced at session start: it is context for a finding,
2048
- * found by following the finding's citation, not a request.
2049
- */
2050
- export const CommentEvidenceSessionCommentSchema = v.object({
2051
- sessionId: NonEmptyStringSchema,
2052
- /** Only the person's own notes are sent today; `mossbear` is reserved. */
2053
- authorKind: v.picklist(['person', 'mossbear']),
2054
- /** ISO, when the comment was written. */
2055
- at: v.string(),
2056
- /** Wrapped in the response's untrusted markers. */
2057
- body: v.string(),
2058
- });
2059
- export const CommentEvidenceResponseSchema = v.object({
2060
- /** The comment's full id, even when the request named a prefix. */
2061
- commentId: NonEmptyStringSchema,
2062
- itemName: v.string(),
2063
- itemPath: v.nullable(v.string()),
2064
- tier: FindingTierSchema,
2065
- /** One line saying how the finding is known; server-written, outside the markers. */
2066
- tierLine: v.string(),
2067
- /** What the drafter did not read; server-written, outside the markers. */
2068
- blindSpot: v.string(),
2069
- /** What goes wrong, wrapped in the response's untrusted markers. */
2070
- claim: v.string(),
2071
- /** What future sessions should show if the finding is fixed, wrapped; null if none. */
2072
- prediction: v.nullable(v.string()),
2073
- /** A usage finding's counts; null on every other tier. */
2074
- usage: v.nullable(CommentEvidenceUsageSchema),
2075
- /** A practice finding's rubric check; null on every other tier. */
2076
- practice: v.nullable(CommentEvidencePracticeSchema),
2077
- citations: v.array(CommentEvidenceCitationSchema),
2078
- citationsWithheld: v.pipe(v.number(), v.integer()),
2079
- /**
2080
- * Comments on the cited sessions, newest first, wrapped in the untrusted
2081
- * markers. Defaulted so a response from a server that predates the field
2082
- * still parses.
2083
- */
2084
- sessionComments: v.optional(v.array(CommentEvidenceSessionCommentSchema), []),
2085
- /**
2086
- * Comments on the cited sessions that were left out to keep the response
2087
- * bounded (the newest few per session are sent), so a short list is never
2088
- * mistaken for the whole of it. Zero when none were.
2089
- */
2090
- sessionCommentsWithheld: v.optional(v.pipe(v.number(), v.integer()), 0),
2091
- untrusted: GuideHistoryUntrustedSchema,
2092
- });
2093
497
  // A capture id the *client* minted, so a capture has a name before it has a
2094
498
  // server — `offline-doc-editing-plan.md` → slice 4.
2095
499
  //
@@ -3466,57 +1870,6 @@ export const DashboardGuideSuggestionSchema = v.object({
3466
1870
  export const MAX_SYNC_ACTIONS_BATCH = 500;
3467
1871
  /** Max number of guideSuggestions/runUsage entries per sync request. */
3468
1872
  export const MAX_SYNC_AUX_BATCH = 100;
3469
- /**
3470
- * Max rule files one delivery manifest enumerates. Well above what a real repo
3471
- * carries (this one: ~20), and bounded because the manifest rides every
3472
- * action-carrying batch: an unbounded list would multiply across a chunked
3473
- * sync. Overflow sets `truncated` rather than being dropped silently.
3474
- */
3475
- export const MAX_RULE_MANIFEST_FILES = 500;
3476
- /**
3477
- * A rule file observed on disk in the repo `mossbear report` ran from.
3478
- *
3479
- * `path` is relative to that repo root, in exactly the form `payloadPath`
3480
- * takes at import time (`packages/cli/src/guides/discover.ts`), so
3481
- * `file:{format}:{path}` reconstructs the `origin` the dashboard stored for
3482
- * the guide this file produced. That reconstruction is the whole join; nothing
3483
- * else about the file is needed and nothing else is sent.
3484
- *
3485
- * **Never any content.** `contentHash` is the same sha256 the import payload
3486
- * carries, present so a later slice can tell "delivered" from "delivered but
3487
- * edited since import" without shipping the bytes again.
3488
- */
3489
- export const RuleManifestFileSchema = v.object({
3490
- path: v.pipe(v.string(), v.minLength(1), v.maxLength(512)),
3491
- format: GuideFileFormatSchema,
3492
- contentHash: Sha256HexSchema,
3493
- });
3494
- /**
3495
- * Which rule files were actually on disk in the repo this sync ran from —
3496
- * observed delivery, replacing the assumption that every non-skill active
3497
- * guide reached the agent. Without it, an account with several repos, or a
3498
- * dashboard-authored guide never exported anywhere, is graded against
3499
- * instructions the agent never received.
3500
- *
3501
- * `repoId` is an opaque, machine-local digest — deliberately not a path, a
3502
- * remote URL, or a repo name. Its only job is to keep two checkouts on the
3503
- * same account distinguishable, which is the half of review finding 5 that
3504
- * repo-root-relative origins cannot express: two repos each holding
3505
- * `.claude/skills/review` produce byte-identical origins by construction. See
3506
- * `repoIdFromRoot` (`packages/cli/src/guides/manifest.ts`) for how it is
3507
- * derived and why that derivation is privacy-safe.
3508
- */
3509
- export const RuleFileManifestSchema = v.object({
3510
- repoId: RepoIdSchema,
3511
- files: v.pipe(v.array(RuleManifestFileSchema), v.maxLength(MAX_RULE_MANIFEST_FILES)),
3512
- /**
3513
- * The repo held more rule files than the cap, so `files` is a prefix. Set
3514
- * rather than silently trimmed: a manifest read as complete would mark the
3515
- * omitted files' guides undelivered, which is the exact wrong-verdict
3516
- * failure this field exists to prevent.
3517
- */
3518
- truncated: v.optional(v.boolean()),
3519
- });
3520
1873
  /**
3521
1874
  * Where the checkout stood when a run closed — the git head the `SessionEnd`
3522
1875
  * hook observed, and the branch it was on.
@@ -3881,394 +2234,61 @@ export const ActionEntrySchema = v.object({
3881
2234
  */
3882
2235
  harness: v.optional(HarnessIdSchema),
3883
2236
  /**
3884
- * `cloud` when the hook saw a cloud marker in its own process environment;
3885
- * see {@link SessionEnvironmentSchema}. Absent otherwise, and absent never
3886
- * means local.
3887
- */
3888
- environment: v.optional(SessionEnvironmentSchema),
3889
- /**
3890
- * The repository's display name, read by the logger hook from the event's
3891
- * `cwd` beside `projectId`; see {@link RepositoryNameSchema}.
3892
- *
3893
- * Optional: run logs written before this field existed must stay readable,
3894
- * and a session in the home directory carries no name.
3895
- */
3896
- repository: v.optional(RepositoryNameSchema),
3897
- /**
3898
- * Whether the tool call succeeded, when the hook could tell.
3899
- *
3900
- * Optional twice over: run logs written before this field existed must stay
3901
- * readable, and a recognized response shape is not guaranteed even now. See
3902
- * {@link ActionOutcomeSchema} — absent is "unknown", not "fine".
3903
- */
3904
- outcome: v.optional(ActionOutcomeSchema),
3905
- });
3906
- /**
3907
- * Action types the CLI maps agent tool calls onto.
3908
- *
3909
- * Deliberately **not** a closed schema. `DashboardSyncAction.actionType` stays
3910
- * an open string so a tool the CLI has never seen still syncs as itself
3911
- * (`packages/cli/src/action-queue.ts` normalizes an unknown tool name rather
3912
- * than collapsing it into a catch-all) — a closed picklist would silently drop
3913
- * those. This list is the *known* vocabulary: what the CLI produces on purpose.
3914
- *
3915
- * It lives here because it is a contract between two packages that never import
3916
- * each other. It used to also be the vocabulary the guide-trigger picker
3917
- * offered; that picker is gone
3918
- * and nothing matches against this list any more — relevance is observed from
3919
- * what was in the agent's context, not asserted against an action type.
3920
- *
3921
- * `SKILL_LOAD_ACTION_TYPE` is the one type the CLI emits on purpose that is
3922
- * deliberately absent here; see its own comment for why.
3923
- */
3924
- const KNOWN_ACTION_TYPES = [
3925
- 'file_edit',
3926
- 'file_read',
3927
- 'shell_command',
3928
- 'search',
3929
- 'web_access',
3930
- ];
3931
- /** True when `value` is one of the action types the CLI produces on purpose. */
3932
- export function isKnownActionType(value) {
3933
- return KNOWN_ACTION_TYPES.includes(value);
3934
- }
3935
- // No run-eval result schema here. It was the contract for the CLI's on-device
3936
- // grader, which is gone. The only grader left runs on the server and owns its
3937
- // own output contract there — one shape of that fact, not two packages holding
3938
- // copies that a comment has to keep in step.
3939
- // ---------------------------------------------------------------------------
3940
- // Guide verdict history (guide-history-for-agents)
3941
- // ---------------------------------------------------------------------------
3942
- /**
3943
- * The read an agent makes of a guide's own grading record, so the improvement
3944
- * loop the user already runs in-conversation ("what could be improved in this
3945
- * skill?") has the evidence Mossbear holds and the agent does not.
3946
- *
3947
- * **Evidence out, never instructions out.** Nothing in this contract carries a
3948
- * directive to change anything, and nothing on the server writes as a result of
3949
- * it. It is a read, and the decision stays in the user's conversation.
3950
- */
3951
- /**
3952
- * How the agent names the guide.
3953
- *
3954
- * Either a repo-relative path exactly as the guide file declares it
3955
- * (`.claude/skills/reviewer/SKILL.md`, `AGENTS.md`), or the bare name of a
3956
- * skill (`reviewer`), which the server expands to the skill layouts it knows.
3957
- * Both resolve through the `(root, path)` identity import already reconciles
3958
- * on, rather than a second one invented here.
3959
- *
3960
- * Bounded and shape-checked at the boundary rather than at the query string: it
3961
- * reaches a SQL predicate, and an identifier is not free text.
3962
- */
3963
- 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'));
3964
- /**
3965
- * The request an agent sends.
3966
- *
3967
- * `root` is optional and is the disambiguator, not decoration: `.claude/skills`
3968
- * is scanned under **both** discovery roots
3969
- * (`packages/cli/src/guides/discover.ts`), so a project skill and its
3970
- * `~/.claude/skills` twin declare the same path string. When the identifier
3971
- * reaches guides under more than one root and no root was given, the server
3972
- * refuses and names both rather than picking one — answering a question about
3973
- * the wrong file's history is worse than not answering it.
3974
- */
3975
- export const GuideHistoryRequestSchema = v.object({
3976
- guide: GuideHistoryIdentifierSchema,
3977
- root: v.optional(GuideDiscoveryRootSchema),
3978
- /**
3979
- * Which repo's copy — **the axis import itself reconciles on**, and the one
3980
- * that actually resolves the common collision.
3981
- *
3982
- * `root` alone does not, and assuming it did was the first version's defect:
3983
- * import's resolution key is `(userId, repoId, root, path)` and two files at
3984
- * one path under different repos deliberately stay two rows. So any
3985
- * user with two repos has two guides at `(project, AGENTS.md)`, and a refusal
3986
- * telling them to pass `root` names the one field that cannot separate those.
3987
- *
3988
- * `projectId` is the portable identity a repo commits and every clone agrees
3989
- * on; `repoId` is the machine-local digest. Both are optional and both are
3990
- * what the caller already sends at import time, so an agent running inside a
3991
- * repo supplies them without being asked.
3992
- */
3993
- projectId: v.optional(NonEmptyStringSchema),
3994
- repoId: v.optional(NonEmptyStringSchema),
3995
- /**
3996
- * The exact guide, when the caller has already been shown the candidates.
3997
- *
3998
- * The escape hatch that makes the refusal always satisfiable: two repos can
3999
- * be indistinguishable to a caller that knows neither id (a guide imported
4000
- * before repo identity was recorded carries neither), and an error whose
4001
- * remedy cannot be carried out is worse than no remedy at all. The 409 names
4002
- * this id for every candidate.
4003
- */
4004
- guideId: v.optional(NonEmptyStringSchema),
4005
- });
4006
- /**
4007
- * One revision of a guide's wording: the body file and the version it stood at.
4008
- *
4009
- * The pair, never a bare version number — `guide_files.version` restarts at 1
4010
- * per row, so a number alone compares equal across two different files.
4011
- */
4012
- export const GuideHistoryRevisionSchema = v.object({
4013
- bodyItemId: NonEmptyStringSchema,
4014
- version: v.pipe(v.number(), v.integer()),
4015
- });
4016
- /**
4017
- * Which of three states the guide's record is in — a required field rather than
4018
- * something a reader infers from empty arrays.
4019
- *
4020
- * The distinction is the whole point of returning it: `unevaluated` means no
4021
- * graded run has ever produced a verdict, while `awaiting_current_revision`
4022
- * means the guide has a real record that is entirely about wording the user has
4023
- * since rewritten. Collapsing those two onto "no data" is exactly the claim the
4024
- * dashboard stopped making with its awaiting-current-revision check, and an
4025
- * agent reading an absence as a verdict is the same error one screen further
4026
- * out.
4027
- */
4028
- export const GuideHistoryStateSchema = v.picklist([
4029
- 'evaluated',
4030
- 'awaiting_current_revision',
4031
- 'unevaluated',
4032
- ]);
4033
- /**
4034
- * The verdict window, scoped to the revision named beside it.
4035
- *
4036
- * Both denominators travel: `applicable` is the rate's own denominator
4037
- * (`aligned + misaligned`), `total` is the window's row count including the runs
4038
- * that never engaged the guide. Rendering one as the other is the defect
4039
- * `alignment-rate-sample-disclosure` was filed for, and a payload carrying only
4040
- * one of them would hand an agent the same mistake.
4041
- */
4042
- export const GuideHistoryWindowSchema = v.object({
4043
- /** Rows summarized, after the revision narrow. */
4044
- total: v.pipe(v.number(), v.integer()),
4045
- aligned: v.pipe(v.number(), v.integer()),
4046
- misaligned: v.pipe(v.number(), v.integer()),
4047
- /** In context, never engaged. Neither a pass nor a failure. */
4048
- notApplicable: v.pipe(v.number(), v.integer()),
4049
- /** `aligned + misaligned` — the rate's own denominator. */
4050
- applicable: v.pipe(v.number(), v.integer()),
4051
- /** `aligned / applicable`, or **null when no run engaged the guide**. */
4052
- alignmentRate: v.nullable(v.number()),
4053
- /** The rows hit the per-guide cap: a bounded window, never a lifetime total. */
4054
- isWindowed: v.boolean(),
4055
- /** The cap the rows were fetched under, so a reader can say what "windowed" means. */
4056
- windowSize: v.pipe(v.number(), v.integer()),
4057
- /**
4058
- * Verdicts fetched and then dropped by the revision narrow — about wording
4059
- * that is no longer current, or citing no revision at all. A **floor** rather
4060
- * than a total whenever `isWindowed`, because rows past the cap were never
4061
- * fetched.
4062
- */
4063
- olderRevisionRows: v.pipe(v.number(), v.integer()),
4064
- /**
4065
- * `applicable` is too small for the percentage to mean anything — threshold
4066
- * `applicable < 3` (founder, 2026-08-22). Read the counts, not the rate.
4067
- */
4068
- isLowConfidence: v.boolean(),
4069
- });
4070
- /**
4071
- * One side of a guide edit's before/after pair — the wording, and what the runs
4072
- * that engaged it did.
4073
- *
4074
- * Structurally a window like `GuideHistoryWindow` and deliberately not that
4075
- * schema: these two sides are bounded **per revision** by a different
4076
- * server-side query, so `isSaturated` is
4077
- * the server's own measurement of its partition rather than the client-side
4078
- * `isWindowed` inference, and the span each side covers is part of what makes
4079
- * the pair readable.
4080
- *
4081
- * Both denominators travel here for the same reason they travel on the window:
4082
- * a delta between two undisclosed denominators is worse than no number at all.
4083
- */
4084
- export const GuideHistoryChangeSideSchema = v.object({
4085
- /** The wording this side judges. */
4086
- revision: GuideHistoryRevisionSchema,
4087
- /** Rows in this side's window, including the runs that never engaged it. */
4088
- total: v.pipe(v.number(), v.integer()),
4089
- aligned: v.pipe(v.number(), v.integer()),
4090
- misaligned: v.pipe(v.number(), v.integer()),
4091
- notApplicable: v.pipe(v.number(), v.integer()),
4092
- /** `aligned + misaligned` — this side's own denominator. */
4093
- applicable: v.pipe(v.number(), v.integer()),
4094
- /** `aligned / applicable`, or null when no run engaged this wording. */
4095
- alignmentRate: v.nullable(v.number()),
4096
- /** This side is below the sample floor, so read its counts and not its rate. */
4097
- isLowConfidence: v.boolean(),
4098
- /**
4099
- * This side is a bounded sample of its revision rather than the whole record.
4100
- * A saturated side beside an unsaturated one is two different kinds of
4101
- * number, and comparing them without saying so is the defect the flag exists
4102
- * to stop.
4103
- */
4104
- isSaturated: v.boolean(),
4105
- /** The span this side covers, ISO. Both null on a side with no rows. */
4106
- newestAt: v.nullable(v.string()),
4107
- oldestAt: v.nullable(v.string()),
4108
- });
4109
- /**
4110
- * Which side is too thin for a delta to mean anything.
4111
- *
4112
- * Named rather than a boolean because the two take different sentences: too few
4113
- * runs *since* the change is the ordinary state right after an edit, while too
4114
- * few *before* it means there was never a baseline to compare against.
4115
- */
4116
- export const GuideHistoryChangeSuppressionSchema = v.picklist(['since', 'before', 'both']);
4117
- /**
4118
- * Which way the pair points, or null while the delta is withheld.
4119
- *
4120
- * A reading of a *set* of runs, never a verdict on one — the vocabulary
4121
- * `aligned | misaligned | not_applicable` is untouched, and nothing derived
4122
- * here is written back to a row.
4123
- */
4124
- export const GuideHistoryChangeDirectionSchema = v.picklist([
4125
- 'improved',
4126
- 'regressed',
4127
- 'unchanged',
4128
- ]);
4129
- /**
4130
- * The guide's last edit, read as two windows
4131
- * (`insight-to-proven-change` §A, surfaced by `guide-history-for-agents`
4132
- * deliverable 3).
4133
- *
4134
- * > Changed 12 Aug. Before: misaligned in 6 of 8 runs that engaged it.
4135
- * > Since: 0 of 11.
4136
- *
4137
- * **Null on the response is a state, not a missing field.** It means this guide
4138
- * has no earlier wording that produced evidence — a guide on its first
4139
- * revision, which is the normal state and not an error.
4140
- *
4141
- * **Paired, never merged**, and **never causal**: this states two windows and
4142
- * their denominators and stops. The model changed, the task mix changed and the
4143
- * codebase changed too, so "since" is the strongest word the evidence supports.
4144
- */
4145
- export const GuideHistoryChangeSchema = v.object({
4146
- /** The revision that preceded the change. */
4147
- before: GuideHistoryChangeSideSchema,
4148
- /** The wording the guide stands at now. */
4149
- since: GuideHistoryChangeSideSchema,
4150
- /**
4151
- * `since` minus `before`, in `[-1, 1]`, or **null whenever the pair is
4152
- * suppressed** or either side never engaged the guide. Null is not zero: one
4153
- * says the evidence does not support a number, the other would be a claim.
2237
+ * `cloud` when the hook saw a cloud marker in its own process environment;
2238
+ * see {@link SessionEnvironmentSchema}. Absent otherwise, and absent never
2239
+ * means local.
4154
2240
  */
4155
- alignmentRateDelta: v.nullable(v.number()),
2241
+ environment: v.optional(SessionEnvironmentSchema),
4156
2242
  /**
4157
- * Which side is below the sample floor, or null when neither is and the delta
4158
- * stands. `'since'` is the ordinary post-edit state — *not enough runs since
4159
- * this change* — and is reported rather than omitted.
2243
+ * The repository's display name, read by the logger hook from the event's
2244
+ * `cwd` beside `projectId`; see {@link RepositoryNameSchema}.
2245
+ *
2246
+ * Optional: run logs written before this field existed must stay readable,
2247
+ * and a session in the home directory carries no name.
4160
2248
  */
4161
- suppressedBy: v.nullable(GuideHistoryChangeSuppressionSchema),
4162
- /** The delta's sign, or null while it is withheld. `unchanged` is exactly zero. */
4163
- direction: v.nullable(GuideHistoryChangeDirectionSchema),
4164
- /** Either side is a bounded sample, so neither is a lifetime total. */
4165
- isWindowed: v.boolean(),
4166
- /** The per-revision cap each side was bounded by, so "sample" has a size. */
4167
- windowSize: v.pipe(v.number(), v.integer()),
2249
+ repository: v.optional(RepositoryNameSchema),
4168
2250
  /**
4169
- * When the current wording was recorded, ISO — the boundary between the two
4170
- * windows, and null when no version row carries it.
2251
+ * Whether the tool call succeeded, when the hook could tell.
4171
2252
  *
4172
- * A date, never an attribution: it says when the window opened, not that the
4173
- * edit caused what happened inside it.
2253
+ * Optional twice over: run logs written before this field existed must stay
2254
+ * readable, and a recognized response shape is not guaranteed even now. See
2255
+ * {@link ActionOutcomeSchema} — absent is "unknown", not "fine".
4174
2256
  */
4175
- changedAt: v.nullable(v.string()),
4176
- });
4177
- /** Findings returned per response, and the character bound on each reasoning. */
4178
- export const MAX_GUIDE_HISTORY_FINDINGS = 5;
4179
- export const MAX_GUIDE_HISTORY_REASONING_CHARS = 1200;
4180
- /**
4181
- * One recorded finding: a run that judged this guide misaligned, and why.
4182
- *
4183
- * `reasoning` arrives **already wrapped in the response's untrusted markers**
4184
- * rather than raw. It is model-authored text derived from a transcript, so the
4185
- * discipline the run grader applies to such text on the way in applies on the
4186
- * way out; wrapping it at the source is what makes the boundary
4187
- * unforgeable, since a consumer handed raw text plus separate markers can
4188
- * simply not use them.
4189
- *
4190
- * `isCurrentRevision` is not optional detail. A payload that scopes its *rate*
4191
- * to the current wording and then hands over reasoning about deleted sentences,
4192
- * unlabelled, reproduces inside one response the conflation
4193
- * `pattern-evidence-guide-revision` removed from the dashboard.
4194
- */
4195
- export const GuideHistoryFindingSchema = v.object({
4196
- sessionId: NonEmptyStringSchema,
4197
- occurredAt: v.string(),
4198
- revision: v.nullable(GuideHistoryRevisionSchema),
4199
- isCurrentRevision: v.boolean(),
4200
- reasoning: v.string(),
4201
- });
4202
- /** The guide the identifier resolved to, echoed so the agent can check itself. */
4203
- export const GuideHistoryGuideSchema = v.object({
4204
- id: NonEmptyStringSchema,
4205
- title: v.string(),
4206
- path: v.nullable(SafeRelativePosixPathSchema),
4207
- root: v.nullable(GuideDiscoveryRootSchema),
2257
+ outcome: v.optional(ActionOutcomeSchema),
4208
2258
  });
4209
2259
  /**
4210
- * The caller's newest stored failure-pattern analysis of the guide
4211
- * (`drafted-guide-suggestions` slice 7), served through artifact feedback.
2260
+ * Action types the CLI maps agent tool calls onto.
4212
2261
  *
4213
- * **The caller's own analysis only.** An analysis reads the caller's verdicts,
4214
- * so a workspace-mate's is never returned, the same rule the verdicts follow.
2262
+ * Deliberately **not** a closed schema. `DashboardSyncAction.actionType` stays
2263
+ * an open string so a tool the CLI has never seen still syncs as itself
2264
+ * (`packages/cli/src/action-queue.ts` normalizes an unknown tool name rather
2265
+ * than collapsing it into a catch-all) — a closed picklist would silently drop
2266
+ * those. This list is the *known* vocabulary: what the CLI produces on purpose.
4215
2267
  *
4216
- * **Staleness is derived on read**: the
4217
- * guide's wording changed since (`revision_changed`), or failures of the same
4218
- * wording arrived that it has not read (`new_failures`, with how many). A stale
4219
- * analysis is still what it found; it is reported, never withheld.
2268
+ * It lives here because it is a contract between two packages that never import
2269
+ * each other. It used to also be the vocabulary the guide-trigger picker
2270
+ * offered; that picker is gone
2271
+ * and nothing matches against this list any more — relevance is observed from
2272
+ * what was in the agent's context, not asserted against an action type.
4220
2273
  *
4221
- * `summary` arrives wrapped in the response's untrusted markers. It is
4222
- * model-authored text derived from session transcripts. On `no_pattern` it may
4223
- * be empty between them, because the dashboard supplies that sentence itself.
2274
+ * `SKILL_LOAD_ACTION_TYPE` is the one type the CLI emits on purpose that is
2275
+ * deliberately absent here; see its own comment for why.
4224
2276
  */
4225
- export const GuideHistoryAnalysisSchema = v.object({
4226
- id: NonEmptyStringSchema,
4227
- /** When it was written, ISO. */
4228
- createdAt: v.string(),
4229
- outcome: v.picklist(['pattern', 'no_pattern']),
4230
- summary: v.string(),
4231
- /** Failed sessions the analysis read. */
4232
- sessionsAnalysed: v.pipe(v.number(), v.integer()),
4233
- /** Failed sessions it left out to stay within its prompt's cap. */
4234
- sessionsOmitted: v.pipe(v.number(), v.integer()),
4235
- stale: v.boolean(),
4236
- /** Why it is out of date, or null while it is current. */
4237
- staleReason: v.nullable(v.picklist(['revision_changed', 'new_failures'])),
4238
- /** Failures it has not read, when `staleReason` is `new_failures`; else null. */
4239
- newFailures: v.nullable(v.pipe(v.number(), v.integer())),
4240
- });
4241
- export const GuideHistoryResponseSchema = v.object({
4242
- guide: GuideHistoryGuideSchema,
4243
- /** The wording the window is about, or null when the guide has no revision identity. */
4244
- currentRevision: v.nullable(GuideHistoryRevisionSchema),
4245
- state: GuideHistoryStateSchema,
4246
- window: GuideHistoryWindowSchema,
4247
- /**
4248
- * The last edit's two windows, or **null when there is no earlier wording to
4249
- * compare against**.
4250
- *
4251
- * Present-and-null rather than omitted: a guide on its first revision has no
4252
- * delta, and that is an answer. An absent key would leave a reader unable to
4253
- * tell "no edit to measure" from "this server does not report deltas".
4254
- */
4255
- change: v.nullable(GuideHistoryChangeSchema),
4256
- findings: v.array(GuideHistoryFindingSchema),
4257
- /**
4258
- * Misaligned rows in the window beyond the `MAX_GUIDE_HISTORY_FINDINGS`
4259
- * returned. Reported rather than silently truncated: a caller reading five
4260
- * findings has no other way to know it is reading five of forty.
4261
- */
4262
- findingsOmitted: v.pipe(v.number(), v.integer()),
4263
- /**
4264
- * The caller's newest stored failure-pattern analysis of this guide, or
4265
- * **null when they have never asked for one**. Optional because a server
4266
- * that predates it sends no key; a reader must not take absence for "never
4267
- * analysed".
4268
- */
4269
- analysis: v.optional(v.nullable(GuideHistoryAnalysisSchema)),
4270
- untrusted: GuideHistoryUntrustedSchema,
4271
- });
2277
+ const KNOWN_ACTION_TYPES = [
2278
+ 'file_edit',
2279
+ 'file_read',
2280
+ 'shell_command',
2281
+ 'search',
2282
+ 'web_access',
2283
+ ];
2284
+ /** True when `value` is one of the action types the CLI produces on purpose. */
2285
+ export function isKnownActionType(value) {
2286
+ return KNOWN_ACTION_TYPES.includes(value);
2287
+ }
2288
+ // No run-eval result schema here. It was the contract for the CLI's on-device
2289
+ // grader, which is gone. The only grader left runs on the server and owns its
2290
+ // own output contract there — one shape of that fact, not two packages holding
2291
+ // copies that a comment has to keep in step.
4272
2292
  // ---------------------------------------------------------------------------
4273
2293
  // Artifact feedback — open comments and grading for one artifact
4274
2294
  // (`GET /api/v1/artifacts/:id/feedback`)
@@ -4325,8 +2345,6 @@ export const ArtifactFeedbackResponseSchema = v.object({
4325
2345
  /** Present exactly when `grading` is null. */
4326
2346
  gradingUnavailable: v.optional(ArtifactGradingUnavailableSchema),
4327
2347
  });
4328
- /** Most artifacts one batch feedback read may name. */
4329
- export const MAX_ARTIFACT_FEEDBACK_BATCH = 25;
4330
2348
  /**
4331
2349
  * `POST /api/v1/artifacts/feedback` body: several artifacts read at once, each
4332
2350
  * paged as `GET .../:id/feedback` pages it (`cursor` is that artifact's own
@@ -4354,704 +2372,9 @@ export const ArtifactFeedbackBatchResponseSchema = v.object({
4354
2372
  unavailable: v.optional(v.literal(true)),
4355
2373
  })),
4356
2374
  });
4357
- /**
4358
- * How many artifacts one prompt-time announcement names. The rest are counted
4359
- * in one line and named on a later prompt, so a session that wrote many
4360
- * artifacts prints a few lines in front of a turn rather than a list.
4361
- */
4362
- export const MAX_SESSION_COMMENT_ANNOUNCEMENT_ARTIFACTS = 5;
4363
- /**
4364
- * Ask which artifacts this agent session wrote carry open comments, and which
4365
- * (`agent-hears-new-artifact-comments` slice 3).
4366
- *
4367
- * **A read, not a write.** Which of those comments the session has already been
4368
- * told about is kept beside the session, by comment id. Not by creation time:
4369
- * a comment can become readable long after it was created (a finding its owner
4370
- * approves, an artifact restored from the Trash), and a time cursor would have
4371
- * passed it by. The session-start announcement's per-repo count is a different
4372
- * question and is not touched.
4373
- */
4374
- export const AnnounceSessionCommentsRequestSchema = v.object({
4375
- /**
4376
- * The harness's own id for the session, as artifact writes record it in a
4377
- * version's metadata. Matched only against versions the caller's account
4378
- * wrote, so naming another account's session finds nothing.
4379
- */
4380
- agentSessionId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(256)),
4381
- /** The repo asking, as its committed config declares it, for repo-scoped findings. */
4382
- projectId: v.optional(ProjectIdSchema),
4383
- });
4384
- export const AnnounceSessionCommentsResponseSchema = v.object({
4385
- /**
4386
- * The session's artifacts that carry open comments, most recently commented
4387
- * first; at most as many as one batch feedback read takes.
4388
- */
4389
- artifacts: v.pipe(v.array(v.object({
4390
- id: NonEmptyStringSchema,
4391
- name: v.string(),
4392
- /** Its open comments, newest first, at most one wire allowance of them. */
4393
- commentIds: v.pipe(v.array(NonEmptyStringSchema), v.minLength(1), v.maxLength(MAX_ITEM_COMMENTS_ON_WIRE)),
4394
- })), v.maxLength(MAX_ARTIFACT_FEEDBACK_BATCH)),
4395
- });
4396
- // ---------------------------------------------------------------------------
4397
- // Run grade — one run's verdict, for the terminal (`GET /api/v1/runs/grade`)
4398
- // ---------------------------------------------------------------------------
4399
- /**
4400
- * One session's grade, read by the MCP `session_digest` tool.
4401
- *
4402
- * The loop this closes: a session ends with "synced N item(s) to the
4403
- * dashboard." and the verdict exists only in the dashboard. This is the read
4404
- * that brings it back to the terminal the work happened in.
4405
- *
4406
- * **Evidence out, never instructions out** — the same contract as the guide
4407
- * history read above. It returns data and never a directive; nothing on the
4408
- * server writes as a result of it.
4409
- */
4410
- /**
4411
- * How the caller names the run. Exactly one of the two.
4412
- *
4413
- * The CLI only ever knows an *agent session* id — the `SessionEnd` hook
4414
- * payload's `session_id`, which `mossbear complete` reports — so
4415
- * the `agent_session` form is the one it uses. The session id is for a caller
4416
- * that already has one, from a dashboard URL say. Both are opaque and both
4417
- * reach a SQL predicate, so they are bounded and shape-checked here.
4418
- */
4419
- const SessionGradeIdentifierSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(256), v.check((value) => !/[\u0000-\u001f\u007f]/.test(value), 'identifier must not contain control characters'));
4420
- export const SessionGradeRequestSchema = v.pipe(v.object({
4421
- session: v.optional(SessionGradeIdentifierSchema),
4422
- agent_session: v.optional(SessionGradeIdentifierSchema),
4423
- /**
4424
- * Opt in to the session digest: the grade plus the turns, self-report and
4425
- * git position of the session. Omitted, the small grade payload is
4426
- * returned unchanged.
4427
- */
4428
- detail: v.optional(v.literal('digest')),
4429
- }), v.check((request) => (request.session !== undefined) !== (request.agent_session !== undefined), 'Pass exactly one of session or agent_session'));
4430
- /**
4431
- * Which of four states the run's grade is in — a required field rather than
4432
- * something a reader infers from a null `grade`.
4433
- *
4434
- * These states need different sentences, and the absence of a grade is never
4435
- * one of them on its own:
4436
- *
4437
- * - `pending` — no grade yet, and the grading sweep can still pick the run
4438
- * up (it is open, or closed inside the grading window). "Not graded yet"
4439
- * is honest here and only here — unless `gradeFailedAttempts` is above
4440
- * zero, when grading has been tried and has not finished.
4441
- * - `graded` — a grader judged it; `grade` carries what it said.
4442
- * - `nothing_to_grade` — a grader ran and found nothing to judge: no
4443
- * gradeable actions, or no guides in the agent's context. The record
4444
- * cannot tell those two apart, so neither can the sentence.
4445
- * - `expired` — no grade, and the run closed too long ago for the sweep to
4446
- * select it. It will never be graded, and telling a reader to wait would
4447
- * promise work the system does not do.
4448
- * - `grading_off` — only usage was synced; no behavioral grade is requested.
4449
- */
4450
- export const SessionGradeStateSchema = v.picklist([
4451
- 'pending',
4452
- 'graded',
4453
- 'nothing_to_grade',
4454
- 'expired',
4455
- 'grading_off',
4456
- ]);
4457
- /**
4458
- * The run-level verdict vocabulary — `aligned | misaligned | not_applicable`.
4459
- * `not_applicable` is a guide that was in the agent's context and that the
4460
- * session never engaged. It is not `unguided`, which is an action-level word,
4461
- * and neither is ever restated in terms of the other.
4462
- */
4463
- export const SESSION_GUIDE_VERDICTS = ['aligned', 'misaligned', 'not_applicable'];
4464
- export const SessionGuideVerdictValueSchema = v.picklist(SESSION_GUIDE_VERDICTS);
4465
- /** One guide's verdict for the run, with the grader's reasoning wrapped. */
4466
- export const SessionGradeGuideSchema = v.object({
4467
- guideId: NonEmptyStringSchema,
4468
- title: v.string(),
4469
- verdict: SessionGuideVerdictValueSchema,
4470
- /**
4471
- * The grader's reasoning, **already wrapped in the response's untrusted
4472
- * markers** — model-authored text derived from a transcript, delimited at the
4473
- * source so a consumer cannot skip the markers. Empty between the markers
4474
- * when the row recorded none.
4475
- */
4476
- reasoning: v.string(),
4477
- });
4478
- export const SessionGradeSchema = v.object({
4479
- /** The grader's one-paragraph judgment of the run, wrapped like `reasoning`; null when the record carries none. */
4480
- summary: v.nullable(v.string()),
4481
- /** ISO timestamp, machine format — display formatting is the reader's job. */
4482
- gradedAt: v.string(),
4483
- /** The model that produced the judgment, or null when the record does not say. */
4484
- model: v.nullable(v.string()),
4485
- /**
4486
- * True when the run grew after this grade was written — a later sync
4487
- * attached more actions — so the judgment describes a smaller run than the
4488
- * one on record. A superseded grade is real and is still reported; it is
4489
- * labelled rather than hidden.
4490
- */
4491
- superseded: v.boolean(),
4492
- guides: v.array(SessionGradeGuideSchema),
4493
- });
4494
- export const GradedSessionSchema = v.object({
4495
- id: NonEmptyStringSchema,
4496
- agentSessionId: NonEmptyStringSchema,
4497
- startedAt: v.string(),
4498
- endedAt: v.nullable(v.string()),
4499
- status: v.picklist(['open', 'closed']),
4500
- });
4501
- /**
4502
- * Grading passes on the run's current content that ended without a grade:
4503
- * a provider error, quota spent, a response that did not parse. It sits
4504
- * beside `state` rather than adding one, because the sweep keeps retrying
4505
- * such a run, so it is still `pending` (or `expired` once the window closes),
4506
- * and a new `state` value would fail every installed client's parse. Above
4507
- * zero beside `pending`, "not graded yet" is no longer the whole answer:
4508
- * grading was tried, did not finish, and is still being retried. Beside a
4509
- * superseded `graded`, it counts failed re-grades of the newer content.
4510
- * Absent from a server that predates it, which means "not reported", never 0.
4511
- */
4512
- const GradeFailedAttemptsSchema = v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)));
4513
- export const SessionGradeResponseSchema = v.object({
4514
- run: GradedSessionSchema,
4515
- state: SessionGradeStateSchema,
4516
- gradeFailedAttempts: GradeFailedAttemptsSchema,
4517
- /** Present exactly when `state` is `graded`. */
4518
- grade: v.nullable(SessionGradeSchema),
4519
- /**
4520
- * The markers every `summary` and `reasoning` in this response is wrapped in.
4521
- * Present exactly when `grade` is — there is nothing to delimit otherwise.
4522
- */
4523
- untrusted: v.nullable(GuideHistoryUntrustedSchema),
4524
- });
4525
- // ---------------------------------------------------------------------------
4526
- // Session digest — `GET /api/v1/runs/grade?detail=digest`
4527
- // ---------------------------------------------------------------------------
4528
- /** Most turns one digest returns; `turnsTotal` says how many the session has. */
4529
- export const SESSION_DIGEST_MAX_TURNS = 50;
4530
- /** What the digest cannot carry yet, named so an absence is never read as "none". */
4531
- export const SESSION_DIGEST_UNAVAILABLE = [
4532
- 'comments',
4533
- 'resumeCommand',
4534
- 'cloudUrl',
4535
- ];
4536
- export const SessionDigestUnavailableSchema = v.picklist(SESSION_DIGEST_UNAVAILABLE);
4537
- export const SessionDigestTurnSchema = v.object({
4538
- ordinal: v.number(),
4539
- /** What the user said, **wrapped in the response's untrusted markers** and bounded. */
4540
- text: v.string(),
4541
- /** The steering classifier's label, or null when the turn was never classified. */
4542
- steeringLabel: v.nullable(v.string()),
4543
- });
4544
- export const SessionDigestSchema = v.object({
4545
- /** The agent's own closing account of the session, wrapped and bounded; null when it gave none. */
4546
- selfReport: v.nullable(v.string()),
4547
- /** The user's turns in order, at most `SESSION_DIGEST_MAX_TURNS`. */
4548
- turns: v.array(SessionDigestTurnSchema),
4549
- /** Every turn the session recorded, so a cut list is not read as the whole. */
4550
- turnsTotal: v.number(),
4551
- /** The repository's identity digest, or null when the session recorded none. */
4552
- repoId: v.nullable(v.string()),
4553
- /** The branch observed at close, wrapped like any text taken from the repo; null when unrecorded. */
4554
- branch: v.nullable(v.string()),
4555
- /** The head commit observed at close, or null. A commit made mid-session is not it. */
4556
- headSha: v.nullable(v.string()),
4557
- /** The session's page on the dashboard, as a path; the client prefixes the dashboard address. */
4558
- dashboardPath: v.string(),
4559
- /** Absolute dashboard link, added by the client that knows the address. */
4560
- dashboardUrl: v.optional(v.string()),
4561
- /** Comments on this session, wrapped; empty until sessions can be commented on. */
4562
- comments: v.array(v.string()),
4563
- /** The parts of a digest no session carries yet. */
4564
- notYetAvailable: v.array(SessionDigestUnavailableSchema),
4565
- });
4566
- export const SessionDigestResponseSchema = v.object({
4567
- run: GradedSessionSchema,
4568
- state: SessionGradeStateSchema,
4569
- gradeFailedAttempts: GradeFailedAttemptsSchema,
4570
- grade: v.nullable(SessionGradeSchema),
4571
- digest: SessionDigestSchema,
4572
- /** One marker pair over every wrapped block in the response, present always. */
4573
- untrusted: GuideHistoryUntrustedSchema,
4574
- });
4575
- // ---------------------------------------------------------------------------
4576
- // Search — one term across the caller's evidence (`GET /api/v1/search`)
4577
- // ---------------------------------------------------------------------------
4578
- /**
4579
- * The corpora a search can reach today.
4580
- *
4581
- * `guides` is guide bodies and their author-written eval criteria; `verdicts`
4582
- * is the grader's reasoning for why a session did or did not follow a guide;
4583
- * `content` is the name and body of the documents saved in bundles; `comments`
4584
- * is the text of comments left on guides and documents and, for a caller that
4585
- * reads them (`SearchRequest.sessionComments`), on its own sessions; `turns` is what the
4586
- * caller themself said to their agents, redacted; `sessions` is the grader's
4587
- * summary of the caller's own sessions and the agent's closing report. One
4588
- * registry on the server declares how each is matched and scoped; this list is
4589
- * only what a caller may name.
4590
- */
4591
- export const SEARCH_CORPUS_IDS = [
4592
- 'guides',
4593
- 'verdicts',
4594
- 'content',
4595
- 'comments',
4596
- 'turns',
4597
- 'sessions',
4598
- ];
4599
- export const SearchCorpusIdSchema = v.picklist(SEARCH_CORPUS_IDS);
4600
- /**
4601
- * Every stored text no search reaches yet — the actions and their narration.
4602
- * Every response names them, so "nothing found" can never be read as covering
4603
- * them. (Earlier wordings of a guide are deliberately never searched, which is a
4604
- * different thing from not yet.)
4605
- */
4606
- export const SEARCH_UNIMPLEMENTED_CORPORA = ['actions'];
4607
- /**
4608
- * What a response still names as not searched for a caller that did not say it
4609
- * reads session comments (`SearchRequest.sessionComments`): they were left out
4610
- * of its `comments`, so saying otherwise would read a zero as covering them.
4611
- */
4612
- export const SEARCH_SESSION_COMMENTS_UNSEARCHED = 'session-comments';
4613
- export const SearchUnimplementedCorpusSchema = v.picklist(SEARCH_UNIMPLEMENTED_CORPORA);
4614
- /** Hits returned per corpus when the caller does not say. */
4615
- export const SEARCH_DEFAULT_LIMIT = 10;
4616
- /** The most hits one corpus returns. Totals are counted past it. */
4617
- export const SEARCH_MAX_LIMIT = 25;
4618
- /**
4619
- * The term. Literal, case-insensitive, with `*` and `?` as the only wildcards —
4620
- * not a regex, which an unindexed shared database cannot afford.
4621
- *
4622
- * At least two characters after trimming, not counting wildcards: every row
4623
- * matches one character (or `**`), so a shorter term is a scan with no question
4624
- * behind it.
4625
- */
4626
- export const SearchTermSchema = v.pipe(v.string(), v.trim(), v.minLength(2, 'q must be at least 2 characters'), v.maxLength(200, 'q must be at most 200 characters'), v.check((value) => !/[\u0000-\u001f\u007f]/.test(value), 'q must not contain control characters'),
4627
- // Wildcards do not count toward the two: `**` is a pattern that matches
4628
- // every row, which is the scan the minimum exists to refuse.
4629
- v.check((value) => value.replace(/[*?]/g, '').length >= 2, 'q must contain at least 2 characters besides * and ?'));
4630
- /**
4631
- * How much of each guide hit to return — progressive disclosure, so a search
4632
- * costs an agent little context until it asks for more.
4633
- *
4634
- * - `excerpt` (the default): a short window around the match, kept inside the
4635
- * match's Markdown section, plus the section's heading path. A short section
4636
- * comes back whole, and a longer one says how long it is (`sectionChars`).
4637
- * - `section`: the whole section that holds the match, capped. Meant for one
4638
- * hit at a time — pass the hit's `fileId` in `fileIds`.
4639
- */
4640
- export const SEARCH_DETAILS = ['excerpt', 'section'];
4641
- export const SearchDetailSchema = v.picklist(SEARCH_DETAILS);
4642
- /** Frontmatter filters a `content` search accepts at once. */
4643
- export const SEARCH_MAX_FRONTMATTER_FILTERS = 3;
4644
- /**
4645
- * One top-level frontmatter field a `content` item must carry, by exact scalar
4646
- * value (`type: recipe`). The key is a plain YAML key so it can be matched
4647
- * without being interpreted; the value is literal text, compared
4648
- * case-insensitively.
4649
- */
4650
- export const SearchFrontmatterSchema = v.pipe(v.record(v.pipe(v.string(), v.regex(/^[A-Za-z][\w-]{0,39}$/, 'frontmatter keys are plain names')), v.pipe(v.string(), v.trim(), v.minLength(1, 'a frontmatter value must not be empty'), v.maxLength(100, 'a frontmatter value must be at most 100 characters'), v.check((value) => !/[\u0000-\u001f\u007f]/.test(value), 'a frontmatter value must not contain control characters'))), v.check((fields) => {
4651
- const count = Object.keys(fields).length;
4652
- return count >= 1 && count <= SEARCH_MAX_FRONTMATTER_FILTERS;
4653
- }, `frontmatter takes between 1 and ${SEARCH_MAX_FRONTMATTER_FILTERS} fields`));
4654
- /** Who wrote a comment: a person, an agent, or Mossbear itself. */
4655
- export const SEARCH_COMMENT_AUTHOR_KINDS = CommentAuthorKindSchema.options;
4656
- export const SearchCommentAuthorKindSchema = CommentAuthorKindSchema;
4657
- /**
4658
- * What a comment is attached to. `artifact` is a guide or a document; `session`
4659
- * is a run the caller made. Session comments are the caller's own and never reach
4660
- * a workspace-mate.
4661
- */
4662
- /**
4663
- * The subject kinds a client names in a search: `artifact`, never its older
4664
- * name `item`.
4665
- */
4666
- export const SEARCH_COMMENT_SUBJECT_KIND_NAMES = ['artifact', 'session'];
4667
- export const SearchCommentSubjectKindFilterSchema = v.picklist(SEARCH_COMMENT_SUBJECT_KIND_NAMES);
4668
- /**
4669
- * What a user turn was, as the session classifier labels it. The same
4670
- * vocabulary the classifier writes; a `turns` search may keep only some.
4671
- */
4672
- export const SEARCH_STEERING_LABELS = [
4673
- 'correction',
4674
- 'steering',
4675
- 'new request',
4676
- 'acknowledgement',
4677
- 'insufficient evidence',
4678
- ];
4679
- export const SearchSteeringLabelSchema = v.picklist(SEARCH_STEERING_LABELS);
4680
- /**
4681
- * One exact value a `sessions` search filters on — a head sha, a branch name or
4682
- * a repo digest. Compared as written, so it is trimmed and bounded but never
4683
- * case-folded or treated as a pattern.
4684
- */
4685
- export const SearchSessionFilterValueSchema = v.pipe(v.string(), v.trim(), v.minLength(1, 'a session filter must not be empty'), v.maxLength(200, 'a session filter must be at most 200 characters'), v.check((value) => !/[\u0000-\u001f\u007f]/.test(value), 'a session filter must not contain control characters'));
4686
- export const SearchRequestObjectSchema = v.object({
4687
- /**
4688
- * The term. Optional only for a `sessions` search that names a filter (`headSha`,
4689
- * `branch` or `repoId`): "which session ended at this commit" has no words to match.
4690
- */
4691
- q: v.optional(SearchTermSchema),
4692
- /** Which corpora to search; every one when absent. */
4693
- corpora: v.optional(v.pipe(v.array(SearchCorpusIdSchema), v.minLength(1))),
4694
- /**
4695
- * The bundles a scoped caller may read content from — `mossbear mcp
4696
- * --bundles` resolved to ids by the CLI, since the server never sees that
4697
- * flag. **Present means narrowed**, even when empty: an allowlist that
4698
- * reaches no bundle narrows the content corpora to nothing, never to
4699
- * everything. Absent means the caller is not bundle-scoped.
4700
- */
4701
- bundleIds: v.optional(v.pipe(v.array(NonEmptyStringSchema), v.maxLength(200))),
4702
- limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(SEARCH_MAX_LIMIT))),
4703
- /** How much of each guide hit to return; `excerpt` when absent. */
4704
- detail: v.optional(SearchDetailSchema),
4705
- /**
4706
- * Restrict the guides corpus to these guide files — the `fileId`s of earlier
4707
- * hits, to expand them. Narrows within the caller's scope, never past it: an
4708
- * id the caller cannot read matches nothing. Does not touch other corpora.
4709
- */
4710
- fileIds: v.optional(v.pipe(v.array(NonEmptyStringSchema), v.minLength(1), v.maxLength(SEARCH_MAX_LIMIT))),
4711
- /**
4712
- * Restrict the `content` corpus to items whose frontmatter carries every one
4713
- * of these fields. Does not touch other corpora.
4714
- */
4715
- frontmatter: v.optional(SearchFrontmatterSchema),
4716
- /**
4717
- * Restrict the `comments` corpus to comments written by these kinds of
4718
- * author. Does not touch other corpora.
4719
- */
4720
- authorKinds: v.optional(v.pipe(v.array(SearchCommentAuthorKindSchema), v.minLength(1))),
4721
- /**
4722
- * Restrict the `comments` corpus to comments on these kinds of subject. Does
4723
- * not touch other corpora.
4724
- */
4725
- subjectKinds: v.optional(v.pipe(v.array(SearchCommentSubjectKindFilterSchema), v.minLength(1))),
4726
- /**
4727
- * Restrict the `turns` corpus to turns the classifier gave one of these
4728
- * labels. A turn with no label never matches. Does not touch other corpora.
4729
- */
4730
- steeringLabels: v.optional(v.pipe(v.array(SearchSteeringLabelSchema), v.minLength(1))),
4731
- /**
4732
- * Restrict the `sessions` corpus to sessions whose recorded head was exactly
4733
- * this commit when they closed. A commit made mid-session matches nothing:
4734
- * the head is the one observed at close. Does not touch other corpora.
4735
- */
4736
- headSha: v.optional(SearchSessionFilterValueSchema),
4737
- /** Restrict the `sessions` corpus to sessions that closed on exactly this branch. Does not touch other corpora. */
4738
- branch: v.optional(SearchSessionFilterValueSchema),
4739
- /** Restrict the `sessions` corpus to sessions recorded under exactly this repo id. Does not touch other corpora. */
4740
- repoId: v.optional(SearchSessionFilterValueSchema),
4741
- /**
4742
- * Whether the caller can read a `comments` hit on a session. A client from
4743
- * before session comments were searchable validates the whole response
4744
- * strictly and would reject one, so the server returns them only to a caller
4745
- * that says it can, and tells every other caller they were not searched.
4746
- * Absent means it cannot.
4747
- */
4748
- sessionComments: v.optional(v.boolean()),
4749
- });
4750
- /**
4751
- * A request with no term searches the caller's sessions by filter alone, so it
4752
- * must name one, and must not name another corpus (which has nothing to match).
4753
- */
4754
- export const SearchRequestSchema = v.pipe(SearchRequestObjectSchema, v.forward(v.check((request) => request.q !== undefined ||
4755
- request.headSha !== undefined ||
4756
- request.branch !== undefined ||
4757
- request.repoId !== undefined, 'q must be at least 2 characters (or filter sessions by headSha, branch or repoId)'), ['q']), v.forward(v.check((request) => request.q !== undefined ||
4758
- request.corpora === undefined ||
4759
- request.corpora.every((id) => id === 'sessions'), 'without q only the sessions corpus can be searched'), ['corpora']));
4760
- /**
4761
- * Why a corpus was not searched. Codes, never prose: each caller writes its own
4762
- * sentence, and the dashboard's has to be a translatable one.
4763
- */
4764
- export const SearchSkipReasonSchema = v.picklist([
4765
- 'excluded-by-caller',
4766
- 'timed-out',
4767
- // The caller's token is limited to certain bundles, and grading results, the
4768
- // caller's turns and sessions, and comments on their sessions are never among
4769
- // what such a token reaches.
4770
- 'not-granted',
4771
- // A filter named only kinds of subject this caller cannot be given: `session`
4772
- // from a client that did not say it reads session comments, which is also what
4773
- // a server from before they were searchable said to every caller.
4774
- 'not-yet-searchable',
4775
- ]);
4776
- /** Why a searched corpus covered less than the caller's whole scope. */
4777
- export const SearchNarrowingSchema = v.picklist(['narrowed-by-bundle-allowlist']);
4778
- /** A guide file whose text matched. The excerpt is wrapped in `untrusted`'s markers. */
4779
- export const SearchGuideHitSchema = v.object({
4780
- guideId: NonEmptyStringSchema,
4781
- /** Wrapped in `untrusted`'s markers; null when nothing names the guide. */
4782
- guideTitle: v.nullable(v.string()),
4783
- fileId: NonEmptyStringSchema,
4784
- path: v.nullable(v.string()),
4785
- /** The guide's own body, or its author-written eval criteria. */
4786
- part: v.picklist(['body', 'criteria']),
4787
- /**
4788
- * The heading path of the Markdown section that holds the match, joined with
4789
- * `SECTION_PATH_SEPARATOR` and wrapped in `untrusted`'s markers — a heading is
4790
- * file text. Null when the match sits above the first heading. Optional
4791
- * because a server that predates sections does not send it.
4792
- */
4793
- section: v.optional(v.nullable(v.string())),
4794
- /**
4795
- * The whole section's length in characters, present only when `excerpt` is
4796
- * less than all of it — what expanding the hit would add. Null when the
4797
- * excerpt is the whole section. Optional for the same reason as `section`.
4798
- */
4799
- sectionChars: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0)))),
4800
- /**
4801
- * Around the match, cut with `…`, never past its section. By default a short
4802
- * window, or the whole section when that is short too; for `detail:
4803
- * 'section'`, the whole section, capped.
4804
- */
4805
- excerpt: v.string(),
4806
- });
4807
- /** One session's verdict on one guide whose reasoning matched, wrapped in markers. */
4808
- export const SearchVerdictHitSchema = v.object({
4809
- sessionId: NonEmptyStringSchema,
4810
- guideId: NonEmptyStringSchema,
4811
- /**
4812
- * Wrapped in `untrusted`'s markers. Null when the guide is no longer one the
4813
- * caller can read, or nothing names it.
4814
- */
4815
- guideTitle: v.nullable(v.string()),
4816
- verdict: SessionGuideVerdictValueSchema,
4817
- occurredAt: v.string(),
4818
- reasoning: v.string(),
4819
- });
4820
- /**
4821
- * A saved document whose name or body matched — an artifact `read_artifact`
4822
- * reads by its `itemId`. The name, workspace name and excerpt are wrapped in
4823
- * `untrusted`'s markers.
4824
- */
4825
- export const SearchContentHitSchema = v.object({
4826
- itemId: NonEmptyStringSchema,
4827
- /** Wrapped in `untrusted`'s markers; null when the item has no name. */
4828
- name: v.nullable(v.string()),
4829
- workspaceId: NonEmptyStringSchema,
4830
- /** Wrapped in `untrusted`'s markers. */
4831
- workspaceName: v.string(),
4832
- /**
4833
- * Slugs of the bundles that hold the item and that the caller may read — the
4834
- * `bundle` argument `pull_artifacts` takes to read the bundle. Never more than
4835
- * a scoped caller's allowlist reaches.
4836
- */
4837
- bundles: v.array(v.string()),
4838
- updatedAt: v.string(),
4839
- /**
4840
- * Where the item opens on the dashboard. Added by the CLI, which knows the
4841
- * dashboard's address; the server does not send it.
4842
- */
4843
- url: v.optional(v.string()),
4844
- /** A window around the match, wrapped in `untrusted`'s markers. */
4845
- excerpt: v.string(),
4846
- });
4847
- /** What every matched comment carries, whatever it is attached to. */
4848
- const searchCommentHitFields = {
4849
- commentId: NonEmptyStringSchema,
4850
- /** The thread's root; equal to `commentId` for a root comment. */
4851
- threadId: NonEmptyStringSchema,
4852
- authorKind: SearchCommentAuthorKindSchema,
4853
- /** Whether the thread has been resolved — a resolved thread is answered, not open. */
4854
- resolved: v.boolean(),
4855
- createdAt: v.string(),
4856
- /**
4857
- * Where the comment's subject opens on the dashboard. Added by the CLI, which
4858
- * knows the dashboard's address; the server does not send it.
4859
- */
4860
- url: v.optional(v.string()),
4861
- /** A window around the match, wrapped in `untrusted`'s markers. */
4862
- excerpt: v.string(),
4863
- };
4864
- /**
4865
- * A comment on a guide or document that matched. `body` and `itemName` and
4866
- * `workspaceName` are wrapped in `untrusted`'s markers.
4867
- */
4868
- export const SearchArtifactCommentHitSchema = v.object({
4869
- ...searchCommentHitFields,
4870
- subjectKind: v.literal('artifact'),
4871
- itemId: NonEmptyStringSchema,
4872
- /**
4873
- * The guide the item belongs to, or null for a standalone document. A comment
4874
- * on a guide sits on its body file, so this is the id the dashboard's guide
4875
- * page takes; `itemId` is the one a document page takes.
4876
- */
4877
- guideId: v.nullable(NonEmptyStringSchema),
4878
- /** Wrapped in `untrusted`'s markers; null when the item has no name. */
4879
- itemName: v.nullable(v.string()),
4880
- workspaceId: NonEmptyStringSchema,
4881
- /** Wrapped in `untrusted`'s markers. */
4882
- workspaceName: v.string(),
4883
- /** Whether the item has been edited since the comment was written. */
4884
- itemChangedSince: v.boolean(),
4885
- /**
4886
- * Where the match is. A current server always says `body`; `suggestion` is
4887
- * what an older one said for a match in a comment's suggested edit, accepted
4888
- * so a CLI talking to one mid-rollout still parses the report. Nothing reads
4889
- * the difference.
4890
- */
4891
- matchedIn: v.picklist(['body', 'suggestion']),
4892
- /**
4893
- * Whether a Mossbear finding's owner handed it to their agents. Nothing hands
4894
- * one over any more, so a current server sends `false`. It does not say
4895
- * whether an agent may act on it: every open finding is ready unless
4896
- * dismissed. Absent on a person's or an agent's comment and on a reply.
4897
- */
4898
- approved: v.optional(v.boolean()),
4899
- });
4900
- /**
4901
- * A comment on one of the caller's own sessions that matched. It has no
4902
- * workspace and no item: `sessionId` is the id the dashboard's session page
4903
- * takes. The excerpt is wrapped in `untrusted`'s markers.
4904
- */
4905
- export const SearchSessionCommentHitSchema = v.object({
4906
- ...searchCommentHitFields,
4907
- subjectKind: v.literal('session'),
4908
- sessionId: NonEmptyStringSchema,
4909
- matchedIn: v.literal('body'),
4910
- });
4911
- export const SearchCommentHitSchema = v.variant('subjectKind', [
4912
- SearchArtifactCommentHitSchema,
4913
- SearchSessionCommentHitSchema,
4914
- ]);
4915
- /**
4916
- * One thing the caller said to an agent, redacted at the source. `excerpt` and
4917
- * `projectId` and `branch` are wrapped in `untrusted`'s markers: a turn is text a
4918
- * person typed (or pasted) and a branch name is whatever git was told.
4919
- */
4920
- export const SearchTurnHitSchema = v.object({
4921
- /** The agent's own session id — the key a session digest takes. */
4922
- agentSessionId: NonEmptyStringSchema,
4923
- /**
4924
- * The dashboard's id for the session, which its session page takes. Null when
4925
- * the session has not been recorded as a run yet.
4926
- */
4927
- sessionId: v.nullable(NonEmptyStringSchema),
4928
- /** Which turn of the session this was, counting from 1. */
4929
- ordinal: v.pipe(v.number(), v.integer(), v.minValue(1)),
4930
- /** Null when the classifier has not labelled the turn. */
4931
- steeringLabel: v.nullable(SearchSteeringLabelSchema),
4932
- /** Wrapped in `untrusted`'s markers; null where the session recorded none. */
4933
- projectId: v.nullable(v.string()),
4934
- /** Wrapped in `untrusted`'s markers; null where the session recorded none. */
4935
- branch: v.nullable(v.string()),
4936
- createdAt: v.string(),
4937
- /**
4938
- * Where the session opens on the dashboard. Added by the CLI, which knows the
4939
- * dashboard's address; the server does not send it.
4940
- */
4941
- url: v.optional(v.string()),
4942
- /** A window around the match, wrapped in `untrusted`'s markers. */
4943
- excerpt: v.string(),
4944
- });
4945
- /** Which of a session's stored texts a `sessions` hit matched. */
4946
- export const SEARCH_SESSION_MATCH_FIELDS = ['grade', 'self_report'];
4947
- export const SearchSessionMatchFieldSchema = v.picklist(SEARCH_SESSION_MATCH_FIELDS);
4948
- /**
4949
- * One of the caller's own sessions, found by what the grader said about it or
4950
- * what the agent reported at the end. `repoId`, `projectId`, `branch`,
4951
- * `headSha` and `excerpt` are wrapped in `untrusted`'s markers: the first four
4952
- * are whatever a checkout reported, and the excerpt is model-authored or
4953
- * written by an agent.
4954
- */
4955
- export const SearchSessionHitSchema = v.object({
4956
- /** The agent's own session id — the key a session digest takes. */
4957
- agentSessionId: NonEmptyStringSchema,
4958
- /** The dashboard's id for the session, which its session page takes. */
4959
- sessionId: NonEmptyStringSchema,
4960
- /** Wrapped in `untrusted`'s markers; null where the session recorded none. */
4961
- repoId: v.nullable(v.string()),
4962
- /** Wrapped in `untrusted`'s markers; null where the session recorded none. */
4963
- projectId: v.nullable(v.string()),
4964
- /** Wrapped in `untrusted`'s markers; null where the session recorded none. */
4965
- branch: v.nullable(v.string()),
4966
- /**
4967
- * The head observed when the session closed, wrapped in `untrusted`'s
4968
- * markers; null where none was observed. A commit made mid-session is not it.
4969
- */
4970
- headSha: v.nullable(v.string()),
4971
- startedAt: v.string(),
4972
- /** Null when the search named no term, only filters. */
4973
- matchedIn: v.nullable(SearchSessionMatchFieldSchema),
4974
- /**
4975
- * Where the session opens on the dashboard. Added by the CLI, which knows the
4976
- * dashboard's address; the server does not send it.
4977
- */
4978
- url: v.optional(v.string()),
4979
- /** A window around the match, wrapped in `untrusted`'s markers; null when the search named no term. */
4980
- excerpt: v.nullable(v.string()),
4981
- });
4982
- function searchCorpusReportSchema(hit) {
4983
- return v.variant('status', [
4984
- v.object({
4985
- status: v.literal('searched'),
4986
- /** Every match in scope, counted past the returned page. */
4987
- total: v.pipe(v.number(), v.integer(), v.minValue(0)),
4988
- narrowedBy: v.nullable(SearchNarrowingSchema),
4989
- /** Newest first, at most the request's limit. */
4990
- hits: v.array(hit),
4991
- }),
4992
- v.object({
4993
- status: v.literal('skipped'),
4994
- reason: SearchSkipReasonSchema,
4995
- }),
4996
- ]);
4997
- }
4998
- export const SearchGuidesReportSchema = searchCorpusReportSchema(SearchGuideHitSchema);
4999
- export const SearchVerdictsReportSchema = searchCorpusReportSchema(SearchVerdictHitSchema);
5000
- export const SearchContentReportSchema = searchCorpusReportSchema(SearchContentHitSchema);
5001
- export const SearchCommentsReportSchema = searchCorpusReportSchema(SearchCommentHitSchema);
5002
- export const SearchTurnsReportSchema = searchCorpusReportSchema(SearchTurnHitSchema);
5003
- export const SearchSessionsReportSchema = searchCorpusReportSchema(SearchSessionHitSchema);
5004
- /**
5005
- * A search's answer: **a report per corpus, never a bare list.**
5006
- *
5007
- * Keyed by corpus so every corpus is always accounted for — searched with its
5008
- * total, or skipped with its reason — and `notYetSearchable` names the ones no
5009
- * search reaches. A caller reading zero hits therefore always knows what the
5010
- * zero covers, which is the difference between "nothing matched here" and "you
5011
- * never said this".
5012
- */
5013
- export const SearchResponseSchema = v.object({
5014
- corpora: v.object({
5015
- guides: SearchGuidesReportSchema,
5016
- verdicts: SearchVerdictsReportSchema,
5017
- /**
5018
- * Optional because a server that predates the `content` corpus does not
5019
- * send it — and then did not search it, which a caller must say rather
5020
- * than read as zero hits.
5021
- */
5022
- content: v.optional(SearchContentReportSchema),
5023
- /** Optional for the same reason as `content`. Covers comments on guides and documents, and the caller's own comments on their sessions. */
5024
- comments: v.optional(SearchCommentsReportSchema),
5025
- /** Optional for the same reason as `content`. The caller's own turns, never a workspace-mate's. */
5026
- turns: v.optional(SearchTurnsReportSchema),
5027
- /** Optional for the same reason as `content`. The caller's own sessions, never a workspace-mate's. */
5028
- sessions: v.optional(SearchSessionsReportSchema),
5029
- }),
5030
- // `comments` is what a server from before session comments were told apart
5031
- // from item comments still sends; a newer client must read that response, not
5032
- // refuse it. `session-comments`, `turns` and `sessions` are what servers sent
5033
- // before those corpora were searchable.
5034
- notYetSearchable: v.array(v.picklist([
5035
- ...SEARCH_UNIMPLEMENTED_CORPORA,
5036
- 'comments',
5037
- 'session-comments',
5038
- 'turns',
5039
- 'sessions',
5040
- ])),
5041
- untrusted: GuideHistoryUntrustedSchema,
5042
- });
5043
2375
  // ---------------------------------------------------------------------------
5044
2376
  // Parse wrappers (throw ValiError on invalid input)
5045
2377
  // ---------------------------------------------------------------------------
5046
- export function parseGuideBundleResponse(data) {
5047
- return v.parse(GuideBundleResponseSchema, data);
5048
- }
5049
- export function parseRawGuideFilePayload(data) {
5050
- return v.parse(RawGuideFilePayloadSchema, data);
5051
- }
5052
- export function parseBundleListResponse(data) {
5053
- return v.parse(BundleListResponseSchema, data);
5054
- }
5055
2378
  export function parseWorkspaceListResponse(data) {
5056
2379
  return v.parse(WorkspaceListResponseSchema, data);
5057
2380
  }
@@ -5061,45 +2384,6 @@ export function parseCreateScopedTokenRequest(data) {
5061
2384
  export function parseRevokeScopedTokenRequest(data) {
5062
2385
  return v.parse(RevokeScopedTokenRequestSchema, data);
5063
2386
  }
5064
- export function parseCreateBundleRequest(data) {
5065
- return v.parse(CreateBundleRequestSchema, data);
5066
- }
5067
- export function parseCreateBundleResponse(data) {
5068
- return v.parse(CreateBundleResponseSchema, data);
5069
- }
5070
- export function parseAttachBundleMemberRequest(data) {
5071
- return v.parse(AttachBundleMemberRequestSchema, data);
5072
- }
5073
- export function parseAttachBundleMemberResponse(data) {
5074
- return v.parse(AttachBundleMemberResponseSchema, data);
5075
- }
5076
- export function parseAttachBundleMembersResponse(data) {
5077
- return v.parse(AttachBundleMembersResponseSchema, data);
5078
- }
5079
- export function parseDetachBundleMemberResponse(data) {
5080
- return v.parse(DetachBundleMemberResponseSchema, data);
5081
- }
5082
- export function parseSubscribeBundleRequest(data) {
5083
- return v.parse(SubscribeBundleRequestSchema, data);
5084
- }
5085
- export function parseSubscribeBundleResponse(data) {
5086
- return v.parse(SubscribeBundleResponseSchema, data);
5087
- }
5088
- export function parseResolveSubscriptionsRequest(data) {
5089
- return v.parse(ResolveSubscriptionsRequestSchema, data);
5090
- }
5091
- export function parseResolveSubscriptionsResponse(data) {
5092
- return v.parse(ResolveSubscriptionsResponseSchema, data);
5093
- }
5094
- export function parseUpdateBundleRequest(data) {
5095
- return v.parse(UpdateBundleRequestSchema, data);
5096
- }
5097
- export function parseUpdateBundleResponse(data) {
5098
- return v.parse(UpdateBundleResponseSchema, data);
5099
- }
5100
- export function parseDeleteBundleResponse(data) {
5101
- return v.parse(DeleteBundleResponseSchema, data);
5102
- }
5103
2387
  export function parseContextItemsResponse(data) {
5104
2388
  return v.parse(ContextItemsResponseSchema, data);
5105
2389
  }
@@ -5149,43 +2433,4 @@ function adoptLegacyAgentSessionId(data) {
5149
2433
  export function parseActionEntry(data) {
5150
2434
  return v.parse(ActionEntrySchema, adoptLegacyAgentSessionId(data));
5151
2435
  }
5152
- export function parseGuideHistoryRequest(data) {
5153
- return v.parse(GuideHistoryRequestSchema, data);
5154
- }
5155
- export function parseGuideHistoryResponse(data) {
5156
- return v.parse(GuideHistoryResponseSchema, data);
5157
- }
5158
- export function parseAnnounceItemCommentsRequest(data) {
5159
- return v.parse(AnnounceItemCommentsRequestSchema, data);
5160
- }
5161
- export function parseResolveItemCommentResponse(data) {
5162
- return v.parse(ResolveItemCommentResponseSchema, data);
5163
- }
5164
- export function parseAnnounceItemCommentsResponse(data) {
5165
- return v.parse(AnnounceItemCommentsResponseSchema, data);
5166
- }
5167
- export function parseAnnounceSessionCommentsResponse(data) {
5168
- return v.parse(AnnounceSessionCommentsResponseSchema, data);
5169
- }
5170
- export function parseAgentCommentResponse(data) {
5171
- return v.parse(AgentCommentResponseSchema, data);
5172
- }
5173
- export function parseItemCommentsResponse(data) {
5174
- return v.parse(ItemCommentsResponseSchema, data);
5175
- }
5176
- export function parseCommentEvidenceResponse(data) {
5177
- return v.parse(CommentEvidenceResponseSchema, data);
5178
- }
5179
- export function parseRunGradeRequest(data) {
5180
- return v.parse(SessionGradeRequestSchema, data);
5181
- }
5182
- export function parseSessionGradeResponse(data) {
5183
- return v.parse(SessionGradeResponseSchema, data);
5184
- }
5185
- export function parseSessionDigestResponse(data) {
5186
- return v.parse(SessionDigestResponseSchema, data);
5187
- }
5188
- export function parseSearchResponse(data) {
5189
- return v.parse(SearchResponseSchema, data);
5190
- }
5191
2436
  //# sourceMappingURL=schemas.js.map