@picassohq/cli 0.0.0-stage → 1.0.2

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 (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,573 @@
1
+ // /review --fresh <path> and /review --drift <path>: review a document with fresh reviewers.
2
+ //
3
+ // Each reviewer is a real engine subagent started through the subagent service's `spawn` provider
4
+ // (the in-process backend that gives every child its own session and zero parent context). A
5
+ // reviewer receives only its task: the document, the files the document references, and its lens.
6
+ // No chat history is passed (the provider must not inherit parent context, and nothing from the
7
+ // calling session's log is read), no agent preset is selected (the child joins the parent's
8
+ // preset, so the tools -> system -> Tier 1 prefix is the same one every agent already sends), and
9
+ // the reviewer instructions travel only as the child's first user message.
10
+ //
11
+ // C1: findings come only from the reviewers' structured results. A reviewer that fails or returns
12
+ // no structured findings is reported as such; nothing is filled in for it.
13
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
14
+ import { createRequire } from 'node:module'
15
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
16
+ import process from 'node:process'
17
+ import { pathToFileURL } from 'node:url'
18
+
19
+ export const RECORD_TYPE = 'plugin:picasso/fresh-review'
20
+ export const SPAWN_PROVIDER = 'spawn'
21
+ export const SEVERITIES = Object.freeze(['critical', 'high', 'medium', 'low'])
22
+
23
+ const MAX_DOC_BYTES = 200 * 1024
24
+ const MAX_FILES = 20
25
+ const MAX_FILE_BYTES = 48 * 1024
26
+ const MAX_TOTAL_FILE_BYTES = 240 * 1024
27
+
28
+ /** The reviewer lenses, in display order. `fresh` runs the first three; `drift` runs the last. */
29
+ export const LENSES = Object.freeze({
30
+ design: {
31
+ id: 'design',
32
+ label: 'Design',
33
+ title: 'Design soundness and missing assumptions',
34
+ focus: [
35
+ 'Judge whether the design holds together: does each part follow from what the document states?',
36
+ 'Find assumptions the document relies on but never writes down (environment, ordering, ownership, failure handling, scale, security, data lifetimes).',
37
+ 'Find gaps: cases, states or failure modes the design does not cover.',
38
+ ],
39
+ },
40
+ clarity: {
41
+ id: 'clarity',
42
+ label: 'Clarity',
43
+ title: 'Clarity and ambiguity of requirements',
44
+ focus: [
45
+ 'Find requirements a reader could implement two different ways, terms used before they are defined, and statements that contradict each other.',
46
+ 'Find missing acceptance criteria: where would two people disagree on whether the work is done?',
47
+ 'Quote the exact ambiguous wording in each finding.',
48
+ ],
49
+ },
50
+ code: {
51
+ id: 'code',
52
+ label: 'Code fit',
53
+ title: 'Fit with the actual code and implementation risk',
54
+ focus: [
55
+ 'Open each referenced file with your read tools and check every claim the document makes about it (names, behaviour, data shapes, call paths).',
56
+ 'Point out where the plan conflicts with how the code works today, and the riskiest parts to implement.',
57
+ 'Cite file paths (and lines when you can) in the location field.',
58
+ ],
59
+ },
60
+ drift: {
61
+ id: 'drift',
62
+ label: 'Drift',
63
+ title: 'Statements that are no longer true of the current source',
64
+ focus: [
65
+ 'This document is checked in; the source may have moved on. Open each referenced file with your read tools and compare it with what the document says.',
66
+ 'Report only statements that are no longer true (renamed or removed names, changed behaviour, wrong paths, stale numbers). Quote the statement and say what the source does now.',
67
+ 'Do not report style or wording issues; a statement that is still true is not a finding.',
68
+ ],
69
+ },
70
+ })
71
+
72
+ export const FRESH_LENSES = Object.freeze(['design', 'clarity', 'code'])
73
+
74
+ /** The structured result every reviewer submits (within the engine's object-rooted schema subset). */
75
+ export const FINDINGS_SCHEMA = Object.freeze({
76
+ type: 'object',
77
+ properties: {
78
+ findings: {
79
+ type: 'array',
80
+ description: 'Every finding, most severe first. An empty list means nothing worth reporting.',
81
+ items: {
82
+ type: 'object',
83
+ properties: {
84
+ severity: { type: 'string', enum: [...SEVERITIES], description: 'critical blocks the work; high must be fixed before building; medium should be fixed; low is minor.' },
85
+ title: { type: 'string', description: 'One short line naming the problem.' },
86
+ detail: { type: 'string', description: 'What is wrong, why it matters, and what would fix it. Two to four sentences.' },
87
+ location: { type: 'string', description: 'Where it is: a document section heading, or a file path with an optional :line.' },
88
+ quote: { type: 'string', description: 'The exact document text the finding is about, when there is one.' },
89
+ },
90
+ required: ['severity', 'title', 'detail'],
91
+ additionalProperties: false,
92
+ },
93
+ },
94
+ },
95
+ required: ['findings'],
96
+ additionalProperties: false,
97
+ })
98
+
99
+ // ---- arguments ---------------------------------------------------------------
100
+
101
+ /**
102
+ * Parse `/review` input. Returns `{fresh, drift, path}` for `--fresh <path>` / `--drift <path>` (both
103
+ * flags may be combined), `undefined` when neither flag is present (plain `/review`), or `{error}`.
104
+ */
105
+ export function parseReviewArgs(rawInput) {
106
+ const tokens = tokenize(String(rawInput ?? ''))
107
+ let fresh = false
108
+ let drift = false
109
+ const rest = []
110
+ for (const token of tokens) {
111
+ if (token === '--fresh') fresh = true
112
+ else if (token === '--drift') drift = true
113
+ else rest.push(token)
114
+ }
115
+ if (!fresh && !drift) return undefined
116
+ if (rest.length === 0) return { error: 'Name the document to review: /review --fresh <path> (add --drift to check it against the current source).' }
117
+ if (rest.length > 1) return { error: `Review one document at a time (got ${rest.join(', ')}).` }
118
+ const unknown = rest[0].startsWith('--') ? rest[0] : undefined
119
+ if (unknown !== undefined) return { error: `Unknown option ${unknown}. Use --fresh or --drift.` }
120
+ return { fresh, drift, path: rest[0] }
121
+ }
122
+
123
+ function tokenize(text) {
124
+ const tokens = []
125
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g
126
+ for (let match = pattern.exec(text); match !== null; match = pattern.exec(text)) {
127
+ tokens.push(match[1] ?? match[2] ?? match[3])
128
+ }
129
+ return tokens
130
+ }
131
+
132
+ /** The lenses a parsed `/review` runs: `--fresh` → design, clarity, code fit; `--drift` adds (or alone runs) drift. */
133
+ export function lensesFor(parsed) {
134
+ const ids = []
135
+ if (parsed.fresh) ids.push(...FRESH_LENSES)
136
+ if (parsed.drift) ids.push('drift')
137
+ return ids.map((id) => LENSES[id])
138
+ }
139
+
140
+ // ---- document and references ---------------------------------------------------
141
+
142
+ const inside = (root, path) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)
143
+
144
+ function realOrUndefined(path) {
145
+ try {
146
+ return realpathSync(path)
147
+ } catch {
148
+ return undefined
149
+ }
150
+ }
151
+
152
+ function isBinary(buffer) {
153
+ const probe = buffer.subarray(0, Math.min(buffer.length, 8000))
154
+ return probe.includes(0)
155
+ }
156
+
157
+ /** Read up to `limit` bytes of a text file; `undefined` for binary or unreadable files. */
158
+ function readText(path, limit) {
159
+ let buffer
160
+ try {
161
+ buffer = readFileSync(path)
162
+ } catch {
163
+ return undefined
164
+ }
165
+ if (isBinary(buffer)) return undefined
166
+ const truncated = buffer.length > limit
167
+ const text = (truncated ? buffer.subarray(0, limit) : buffer).toString('utf8')
168
+ return { text, bytes: buffer.length, truncated }
169
+ }
170
+
171
+ /**
172
+ * Candidate file references in a document: markdown link targets, inline-code spans and bare
173
+ * path-like tokens (`dir/name.ext`). URLs, anchors and globs are skipped; a trailing `:line` or
174
+ * `#anchor` is dropped.
175
+ */
176
+ export function referenceCandidates(text) {
177
+ const found = []
178
+ const add = (raw) => {
179
+ if (typeof raw !== 'string') return
180
+ let value = raw.trim().replace(/^<|>$/g, '').replace(/^["'(]+|["'),.;:]+$/g, '')
181
+ if (value.length === 0 || value.length > 300) return
182
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value) || value.startsWith('mailto:') || value.startsWith('#')) return
183
+ if (/[*?{}<>|$\s]/.test(value)) return
184
+ value = value.replace(/#.*$/, '').replace(/:\d+(?:[-:]\d+)?$/, '').replace(/^\.\//, '')
185
+ if (value.length === 0 || value.startsWith('@')) return
186
+ // Something that looks like a file: has a directory part or a file extension.
187
+ if (!value.includes('/') && !/\.[A-Za-z0-9]{1,8}$/.test(value)) return
188
+ if (!found.includes(value)) found.push(value)
189
+ }
190
+ for (const match of text.matchAll(/\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) add(match[1])
191
+ for (const match of text.matchAll(/`([^`\n]+)`/g)) add(match[1])
192
+ for (const match of text.matchAll(/(?:^|[\s(])((?:\.{0,2}\/)?[A-Za-z0-9_.@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,8})(?=$|[\s),.;:])/gm)) add(match[1])
193
+ return found
194
+ }
195
+
196
+ /**
197
+ * Resolve a document's references to readable text files inside the workspace or the document's
198
+ * own folder. Returns `{files, skipped}`; `files` are `{path (workspace-relative), text, bytes, truncated}`.
199
+ */
200
+ export function collectReferencedFiles(docText, docPath, cwd) {
201
+ const roots = [realOrUndefined(cwd), realOrUndefined(dirname(docPath))].filter(Boolean)
202
+ const docReal = realOrUndefined(docPath)
203
+ const files = []
204
+ const seen = new Set()
205
+ let total = 0
206
+ let skipped = 0
207
+ for (const candidate of referenceCandidates(docText)) {
208
+ const bases = isAbsolute(candidate) ? [''] : [dirname(docPath), cwd]
209
+ let resolved
210
+ for (const base of bases) {
211
+ const real = realOrUndefined(base === '' ? candidate : resolve(base, candidate))
212
+ if (real === undefined) continue
213
+ try {
214
+ if (!statSync(real).isFile()) continue
215
+ } catch {
216
+ continue
217
+ }
218
+ if (!roots.some((root) => inside(root, real))) continue
219
+ resolved = real
220
+ break
221
+ }
222
+ if (resolved === undefined || resolved === docReal || seen.has(resolved)) continue
223
+ seen.add(resolved)
224
+ if (files.length >= MAX_FILES || total >= MAX_TOTAL_FILE_BYTES) {
225
+ skipped += 1
226
+ continue
227
+ }
228
+ const read = readText(resolved, Math.min(MAX_FILE_BYTES, MAX_TOTAL_FILE_BYTES - total))
229
+ if (read === undefined) continue
230
+ total += Buffer.byteLength(read.text, 'utf8')
231
+ files.push({ path: displayPath(resolved, cwd), text: read.text, bytes: read.bytes, truncated: read.truncated })
232
+ }
233
+ return { files, skipped }
234
+ }
235
+
236
+ function displayPath(path, cwd) {
237
+ const root = realOrUndefined(cwd) ?? cwd
238
+ const rel = relative(root, path)
239
+ return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel) ? rel.split(sep).join('/') : path
240
+ }
241
+
242
+ /** Load the document named by `/review`, relative to the session workspace. */
243
+ export function loadDocument(path, cwd) {
244
+ const absolute = isAbsolute(path) ? path : resolve(cwd, path)
245
+ if (!existsSync(absolute)) return { error: `No such file: ${path}` }
246
+ let stat
247
+ try {
248
+ stat = statSync(absolute)
249
+ } catch (error) {
250
+ return { error: `Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}` }
251
+ }
252
+ if (!stat.isFile()) return { error: `${path} is not a file.` }
253
+ const read = readText(absolute, MAX_DOC_BYTES)
254
+ if (read === undefined) return { error: `${path} is not a text document.` }
255
+ if (read.text.trim().length === 0) return { error: `${path} is empty.` }
256
+ return { absolute, path: displayPath(realOrUndefined(absolute) ?? absolute, cwd), ...read }
257
+ }
258
+
259
+ // ---- reviewer task -----------------------------------------------------------------
260
+
261
+ /** A code fence longer than any backtick run inside `text`. */
262
+ function fenceFor(text) {
263
+ let longest = 2
264
+ for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length)
265
+ return '`'.repeat(longest + 1)
266
+ }
267
+
268
+ function fenced(text, info = '') {
269
+ const fence = fenceFor(text)
270
+ return `${fence}${info}\n${text.endsWith('\n') ? text : `${text}\n`}${fence}`
271
+ }
272
+
273
+ /**
274
+ * The complete task one reviewer receives as its first (and only) user message. It is built only
275
+ * from the lens, the document and its referenced files — never from the calling session.
276
+ */
277
+ export function reviewerTask(lens, doc, files, skipped = 0) {
278
+ const lines = [
279
+ `You are a fresh reviewer. Lens: ${lens.title}.`,
280
+ '',
281
+ 'You have not seen any conversation about this document. Work only from the document and the referenced files below (and, where the lens says so, the files you open yourself). If something is not written down, treat it as unstated — do not fill it in from general expectations.',
282
+ '',
283
+ 'What to look for:',
284
+ ...lens.focus.map((line) => `- ${line}`),
285
+ '',
286
+ 'Rules:',
287
+ '- Review only. Do not edit, create, move or delete files, and do not run commands that change anything.',
288
+ '- Do not delegate to other agents.',
289
+ '- Each finding gets a severity: critical, high, medium or low. Report real problems only; an empty list is a valid answer.',
290
+ '- When you are done, submit your findings as the structured result.',
291
+ '',
292
+ `Document: ${doc.path}${doc.truncated ? ` (first ${MAX_DOC_BYTES / 1024} KB of ${Math.round(doc.bytes / 1024)} KB)` : ''}`,
293
+ fenced(doc.text, 'markdown'),
294
+ ]
295
+ if (files.length === 0) {
296
+ lines.push('', 'The document references no files that could be read from the workspace.')
297
+ } else {
298
+ lines.push('', `Referenced files (${files.length}${skipped > 0 ? `; ${skipped} more not included` : ''}):`)
299
+ for (const file of files) {
300
+ lines.push('', `File: ${file.path}${file.truncated ? ` (first ${Math.round(Buffer.byteLength(file.text, 'utf8') / 1024)} KB of ${Math.round(file.bytes / 1024)} KB)` : ''}`)
301
+ lines.push(fenced(file.text))
302
+ }
303
+ }
304
+ return lines.join('\n')
305
+ }
306
+
307
+ // ---- findings ----------------------------------------------------------------------
308
+
309
+ const SEVERITY_RANK = new Map(SEVERITIES.map((severity, index) => [severity, index]))
310
+
311
+ export function normalizeSeverity(value) {
312
+ const text = String(value ?? '').trim().toLowerCase()
313
+ if (SEVERITY_RANK.has(text)) return text
314
+ if (text === 'blocker' || text === 'severe') return 'critical'
315
+ if (text === 'major' || text === 'error') return 'high'
316
+ if (text === 'moderate' || text === 'warning' || text === 'warn') return 'medium'
317
+ if (text === 'minor' || text === 'nit' || text === 'info' || text === 'note' || text === 'trivial') return 'low'
318
+ return 'medium'
319
+ }
320
+
321
+ const STOP_WORDS = new Set(['a', 'an', 'the', 'is', 'are', 'of', 'to', 'in', 'on', 'for', 'and', 'or', 'not', 'no', 'does', 'do', 'it', 'its', 'be', 'by', 'with', 'this', 'that'])
322
+
323
+ function titleTokens(title) {
324
+ return new Set(
325
+ String(title ?? '')
326
+ .toLowerCase()
327
+ .replace(/[`'"*_]/g, '')
328
+ .split(/[^a-z0-9./-]+/)
329
+ .filter((word) => word.length > 1 && !STOP_WORDS.has(word)),
330
+ )
331
+ }
332
+
333
+ function locationKey(location) {
334
+ return String(location ?? '').trim().toLowerCase().replace(/[`]/g, '').replace(/:\d+(?:[-:]\d+)?$/, '').replace(/^\.\//, '')
335
+ }
336
+
337
+ function similarity(a, b) {
338
+ if (a.size === 0 || b.size === 0) return 0
339
+ let shared = 0
340
+ for (const word of a) if (b.has(word)) shared += 1
341
+ return shared / (a.size + b.size - shared)
342
+ }
343
+
344
+ /** Same problem? Same title, or close titles at the same (or an unstated) location, or the same quote. */
345
+ function sameFinding(a, b) {
346
+ if (a.titleKey === b.titleKey && a.titleKey.length > 0) return true
347
+ if (a.quoteKey.length > 12 && a.quoteKey === b.quoteKey) return true
348
+ const sameSpot = a.locationKey === b.locationKey || a.locationKey === '' || b.locationKey === ''
349
+ return sameSpot && similarity(a.tokens, b.tokens) >= 0.6
350
+ }
351
+
352
+ /**
353
+ * Merge the reviewers' findings into one list: each duplicate group keeps its most severe rating,
354
+ * the longest detail, and every lens that raised it; sorted by severity, then by how many lenses
355
+ * agree, then by first appearance. `reviews` is `[{lens, findings}]`.
356
+ */
357
+ export function mergeFindings(reviews) {
358
+ const merged = []
359
+ let order = 0
360
+ for (const review of reviews) {
361
+ for (const raw of review.findings ?? []) {
362
+ if (raw === null || typeof raw !== 'object') continue
363
+ const title = String(raw.title ?? '').trim()
364
+ const detail = String(raw.detail ?? '').trim()
365
+ if (title.length === 0 && detail.length === 0) continue
366
+ const finding = {
367
+ severity: normalizeSeverity(raw.severity),
368
+ title: title || detail.split(/(?<=[.!?])\s/)[0],
369
+ detail,
370
+ ...(typeof raw.location === 'string' && raw.location.trim() ? { location: raw.location.trim() } : {}),
371
+ ...(typeof raw.quote === 'string' && raw.quote.trim() ? { quote: raw.quote.trim() } : {}),
372
+ lenses: [review.lens],
373
+ }
374
+ const key = {
375
+ titleKey: finding.title.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(),
376
+ quoteKey: (finding.quote ?? '').toLowerCase().replace(/\s+/g, ' '),
377
+ locationKey: locationKey(finding.location),
378
+ tokens: titleTokens(finding.title),
379
+ }
380
+ const existing = merged.find((entry) => sameFinding(entry.key, key))
381
+ if (existing === undefined) {
382
+ merged.push({ finding, key, order: order++ })
383
+ continue
384
+ }
385
+ const into = existing.finding
386
+ if (SEVERITY_RANK.get(finding.severity) < SEVERITY_RANK.get(into.severity)) into.severity = finding.severity
387
+ if (finding.detail.length > into.detail.length) into.detail = finding.detail
388
+ if (into.location === undefined && finding.location !== undefined) into.location = finding.location
389
+ if (into.quote === undefined && finding.quote !== undefined) into.quote = finding.quote
390
+ if (!into.lenses.includes(review.lens)) into.lenses.push(review.lens)
391
+ }
392
+ }
393
+ return merged
394
+ .sort((a, b) =>
395
+ SEVERITY_RANK.get(a.finding.severity) - SEVERITY_RANK.get(b.finding.severity)
396
+ || b.finding.lenses.length - a.finding.lenses.length
397
+ || a.order - b.order)
398
+ .map((entry) => entry.finding)
399
+ }
400
+
401
+ const SEVERITY_LABEL = { critical: 'Critical', high: 'High', medium: 'Medium', low: 'Low' }
402
+
403
+ function countLine(findings) {
404
+ if (findings.length === 0) return 'no findings'
405
+ const counts = SEVERITIES.map((severity) => [severity, findings.filter((finding) => finding.severity === severity).length])
406
+ .filter(([, count]) => count > 0)
407
+ .map(([severity, count]) => `${count} ${severity}`)
408
+ return `${findings.length} finding${findings.length === 1 ? '' : 's'} (${counts.join(', ')})`
409
+ }
410
+
411
+ const quoteLines = (text) => text.split('\n').map((line) => (line.length > 0 ? `> ${line}` : '>'))
412
+
413
+ /**
414
+ * The merged review as markdown: a heading, one summary line, then each finding as its own
415
+ * block-quote card (the transcript draws a quote as a ruled card), then any reviewer that failed.
416
+ */
417
+ export function renderReview(report) {
418
+ const lensLabel = (id) => LENSES[id]?.label ?? id
419
+ const lines = [`## ${report.mode === 'drift' ? 'Drift check' : 'Fresh review'} · ${report.document}`, '']
420
+ const finished = report.reviewers.filter((reviewer) => reviewer.status === 'completed').length
421
+ lines.push(
422
+ `${report.reviewers.length} fresh reviewer${report.reviewers.length === 1 ? '' : 's'} (${report.reviewers.map((reviewer) => lensLabel(reviewer.lens)).join(', ')}) · `
423
+ + `${countLine(report.findings)} · each saw only the document and ${report.files.length} referenced file${report.files.length === 1 ? '' : 's'}`
424
+ + (finished < report.reviewers.length ? ` · ${report.reviewers.length - finished} did not finish` : ''),
425
+ )
426
+ for (const finding of report.findings) {
427
+ const card = [`**${SEVERITY_LABEL[finding.severity]}** · ${finding.title}`]
428
+ if (finding.detail) card.push(finding.detail)
429
+ if (finding.quote) card.push(`“${finding.quote.replace(/\s+/g, ' ')}”`)
430
+ const meta = [finding.location ? `\`${finding.location}\`` : undefined, finding.lenses.map(lensLabel).join(', ')].filter(Boolean)
431
+ card.push(`_${meta.join(' · ')}_`)
432
+ lines.push('', ...quoteLines(card.join('\n\n')))
433
+ }
434
+ const failed = report.reviewers.filter((reviewer) => reviewer.status !== 'completed')
435
+ if (failed.length > 0) {
436
+ lines.push('')
437
+ for (const reviewer of failed) {
438
+ lines.push(`- ${lensLabel(reviewer.lens)} reviewer did not finish: ${reviewer.reason ?? reviewer.status}`)
439
+ }
440
+ }
441
+ return lines.join('\n')
442
+ }
443
+
444
+ // ---- running the reviewers ------------------------------------------------------------
445
+
446
+ function outputText(blocks) {
447
+ return (Array.isArray(blocks) ? blocks : [])
448
+ .map((block) => (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string' ? block.text : ''))
449
+ .join('')
450
+ .trim()
451
+ }
452
+
453
+ /** Load `appendPluginRecord` from the running engine install (bare specifiers do not resolve from this file). */
454
+ async function engineAppendPluginRecord() {
455
+ const anchors = [process.argv[1], process.env.PICASSO_DSH_INSTALL_DIR && join(process.env.PICASSO_DSH_INSTALL_DIR, 'package.json')].filter(Boolean)
456
+ for (const anchor of anchors) {
457
+ try {
458
+ const require = createRequire(realpathSync(anchor))
459
+ const mod = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-session')).href)
460
+ if (typeof mod.appendPluginRecord === 'function') return mod.appendPluginRecord
461
+ } catch {
462
+ // not an engine install — try the next anchor
463
+ }
464
+ }
465
+ return undefined
466
+ }
467
+
468
+ /** The session's current working directory, else the one it was created in. */
469
+ function sessionCwd(ctx, agent) {
470
+ try {
471
+ const service = ctx.get?.('workingDirectory') ?? ctx.workingDirectory
472
+ const cwd = service?.get?.(agent.session)
473
+ if (typeof cwd === 'string' && cwd.length > 0) return cwd
474
+ } catch {
475
+ // fall back to the session header
476
+ }
477
+ const header = agent?.session?.header?.cwd
478
+ return typeof header === 'string' && header.length > 0 ? header : undefined
479
+ }
480
+
481
+ /**
482
+ * Run one `/review --fresh|--drift <path>` invocation. `deps.subagents` and `deps.appendPluginRecord`
483
+ * override the engine services (tests). Returns the command result `{kind, text}`.
484
+ */
485
+ export async function runFreshReview(ctx, invocation, parsed, deps = {}) {
486
+ const agent = invocation?.agent
487
+ if (agent === undefined || agent === null) return { kind: 'error', text: 'Review needs a session to run in.' }
488
+ const cwd = deps.cwd ?? sessionCwd(ctx, agent)
489
+ if (cwd === undefined) return { kind: 'error', text: 'Review needs a session workspace — this session has no working directory.' }
490
+ const subagents = deps.subagents ?? ctx.get?.('subagents') ?? ctx.subagents
491
+ if (subagents === undefined || subagents === null || typeof subagents.startActivation !== 'function') {
492
+ return { kind: 'error', text: 'Review needs subagents, and this session cannot start them.' }
493
+ }
494
+ const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(SPAWN_PROVIDER) : undefined
495
+ if (provider === undefined) return { kind: 'error', text: 'Review needs fresh subagents, and this session cannot start them.' }
496
+ // Fresh means fresh: a provider that seeds the child with this conversation would defeat the review.
497
+ if (provider.inheritsParentContext !== false) {
498
+ return { kind: 'error', text: 'Review needs reviewers that start without this conversation, and this session cannot start them.' }
499
+ }
500
+
501
+ const doc = loadDocument(parsed.path, cwd)
502
+ if (doc.error !== undefined) return { kind: 'error', text: doc.error }
503
+ const { files, skipped } = collectReferencedFiles(doc.text, doc.absolute, cwd)
504
+ const lenses = lensesFor(parsed)
505
+ const mode = parsed.fresh ? 'fresh' : 'drift'
506
+
507
+ // The reviewers outlive the UI request that started them: a client that stops waiting (a
508
+ // closed window, a request timeout) must not cancel work whose findings land in the log.
509
+ const controller = new AbortController()
510
+ const maxDepth = typeof subagents.resolveMaxDepth === 'function' ? subagents.resolveMaxDepth() : undefined
511
+ const started = await Promise.allSettled(lenses.map((lens) => subagents.startActivation({
512
+ provider: SPAWN_PROVIDER,
513
+ label: `${lens.label} review`,
514
+ request: {
515
+ cwd,
516
+ prompt: [{ type: 'text', text: reviewerTask(lens, doc, files, skipped) }],
517
+ parent: agent,
518
+ outputSchema: FINDINGS_SCHEMA,
519
+ ...(maxDepth === undefined ? {} : { maxDepth }),
520
+ },
521
+ signal: controller.signal,
522
+ delivery: 'caller',
523
+ })))
524
+
525
+ const settled = await Promise.all(started.map(async (start, index) => {
526
+ const lens = lenses[index].id
527
+ if (start.status === 'rejected') {
528
+ return { lens, status: 'error', reason: start.reason instanceof Error ? start.reason.message : String(start.reason), findings: [] }
529
+ }
530
+ const activation = start.value
531
+ try {
532
+ const result = await activation.result
533
+ const structured = result?.structured
534
+ const findings = structured && typeof structured === 'object' && Array.isArray(structured.findings) ? structured.findings : undefined
535
+ if (result?.stopReason === 'completed' && findings !== undefined) {
536
+ return { lens, status: 'completed', childId: activation.childId, findings }
537
+ }
538
+ const text = outputText(result?.output)
539
+ const reason = result?.diagnostic
540
+ ?? (result?.stopReason === 'completed' ? 'it returned no structured findings' : `it stopped (${result?.stopReason ?? 'unknown'})`)
541
+ return { lens, status: result?.stopReason === 'completed' ? 'unstructured' : (result?.stopReason ?? 'error'), childId: activation.childId, reason, findings: [], ...(text ? { output: text.slice(0, 4000) } : {}) }
542
+ } catch (error) {
543
+ return { lens, status: 'error', childId: activation.childId, reason: error instanceof Error ? error.message : String(error), findings: [] }
544
+ }
545
+ }))
546
+
547
+ const findings = mergeFindings(settled.filter((review) => review.status === 'completed'))
548
+ const report = {
549
+ mode,
550
+ document: doc.path,
551
+ files: files.map((file) => file.path),
552
+ reviewers: settled.map(({ lens, status, childId, reason, findings: own }) => ({
553
+ lens,
554
+ status,
555
+ ...(childId === undefined ? {} : { childId: String(childId) }),
556
+ ...(reason === undefined ? {} : { reason }),
557
+ count: own.length,
558
+ })),
559
+ findings,
560
+ }
561
+
562
+ // The log record the Mac thread draws as finding cards. It is ignorable and never model-visible.
563
+ try {
564
+ const append = deps.appendPluginRecord ?? (await engineAppendPluginRecord())
565
+ if (typeof append === 'function') append(agent.session, RECORD_TYPE, report)
566
+ } catch (error) {
567
+ ctx.logger?.warn?.(`picasso-commands: review record not written (${error instanceof Error ? error.message : String(error)})`)
568
+ }
569
+
570
+ const text = renderReview(report)
571
+ const anyFinished = settled.some((review) => review.status === 'completed')
572
+ return { kind: anyFinished ? 'success' : 'error', text }
573
+ }