@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,326 @@
1
+ // @picasso/instructions — the engine plugin that feeds Picasso's universal instruction discovery into a session.
2
+ //
3
+ // One resolver (resolve.js) for the CLI, the TUI and the Mac relay. The plugin:
4
+ //
5
+ // * Tier 1: on a session's first model step it injects the resolved always-on set once, as one sourced user message
6
+ // (`source.kind: 'agent-instructions'`, `resolver: 'picasso-instructions'`, `tier: 1`). Same workspace + same shared
7
+ // setting = the same bytes on every surface and every turn: the text depends only on the files, the display paths
8
+ // and the setting (no clock, no surface, no absolute paths). It is never re-emitted or edited mid-session.
9
+ // * Tier 2: scoped rules (globs) and nested folders' files activate when a read/write/edit touches a matching file;
10
+ // a rule loads by name on request (`instructions/activate`); always-on files that changed, appeared or disappeared
11
+ // are reported at the next turn start. Each enters as an appended reminder, never into the Tier-1 prefix.
12
+ // * It replaces the engine's own workspace-instruction loader: the engine row is disabled in both compositions, and
13
+ // any message that loader still produces (a shipped preset's own row) is dropped here, so instructions are never
14
+ // loaded twice and other tools' home-directory files never load unless switched on (globals.js).
15
+ // * `instructions/describe` and `instructions/activate` (Host Remote namespace `instructions`) back the TUI's
16
+ // /instructions and /context section and the Mac panel.
17
+ //
18
+ // Security: repository text is quoted project content in labelled <project-file> sections. Nothing here reads a
19
+ // permission, approval, sandbox or network setting, and nothing in a file can change one.
20
+
21
+ import { randomUUID } from 'node:crypto';
22
+ import { buildReport } from './report.js';
23
+ import { describeMode } from './modes.js';
24
+ import { modeLabel, readInstructionSettings } from './settings.js';
25
+ import { globalCandidates, globalSourcesReport } from './globals.js';
26
+ import {
27
+ activateByName, activateForPath, activationState, diffAlwaysOn, renderActivation, renderChanges, resolveInstructions,
28
+ } from './resolve.js';
29
+
30
+ export const name = 'picasso-instructions';
31
+ export const dshTarget = '0.2.2-rc.2';
32
+ export const RESOLVER = 'picasso-instructions';
33
+ export const SOURCE_KIND = 'agent-instructions';
34
+ export const SERVICE_KEY = 'instructions';
35
+ export const DESCRIBE_METHOD = 'describe';
36
+ export const ACTIVATE_METHOD = 'activate';
37
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
38
+
39
+ /** Tools whose successful call touches one file (`file_path` or `path` argument). */
40
+ export const FILE_TOUCH_TOOLS = Object.freeze(new Set(['read', 'write', 'edit', 'multi_edit', 'str_replace_editor', 'view']));
41
+
42
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
43
+
44
+ /** A message the engine's own workspace-instruction loader produced (not ours). */
45
+ export function isEngineInstructionMessage(message) {
46
+ return isRecord(message) && isRecord(message.source) && message.source.kind === SOURCE_KIND && message.source.resolver !== RESOLVER;
47
+ }
48
+
49
+ /** One of our messages. */
50
+ export function isPicassoInstructionMessage(message) {
51
+ return isRecord(message) && isRecord(message.source) && message.source.kind === SOURCE_KIND && message.source.resolver === RESOLVER;
52
+ }
53
+
54
+ function userMessage(text, source) {
55
+ return Object.freeze({
56
+ role: 'user',
57
+ content: Object.freeze([Object.freeze({ type: 'text', text })]),
58
+ source: Object.freeze({ kind: SOURCE_KIND, form: 'instructions', resolver: RESOLVER, changes: Object.freeze([]), ...source }),
59
+ id: randomUUID(),
60
+ });
61
+ }
62
+
63
+ function loadedRecords(resolution) {
64
+ return resolution.sources
65
+ .filter((s) => s.tier === 1 && (s.status === 'loaded' || s.status === 'truncated'))
66
+ .map((s) => Object.freeze({ id: s.id, digest: s.digest ?? '' }));
67
+ }
68
+
69
+ /** The Tier-1 message for a session-start resolution (undefined when there is nothing to load). */
70
+ export function baselineMessage(resolution) {
71
+ if (resolution.tier1.text === '') return undefined;
72
+ return userMessage(resolution.tier1.text, {
73
+ tier: 1,
74
+ digest: resolution.tier1.digest,
75
+ mode: resolution.mode.id,
76
+ sources: Object.freeze(loadedRecords(resolution)),
77
+ });
78
+ }
79
+
80
+ /** A Tier-2 message: scoped activations, a rule loaded on request, or a change notice. */
81
+ export function tier2Message(text, detail) {
82
+ return userMessage(text, { tier: 2, ...detail });
83
+ }
84
+
85
+ /** The file a successful tool call touched, or undefined. */
86
+ export function touchedPath(exec) {
87
+ if (!isRecord(exec) || !FILE_TOUCH_TOOLS.has(exec.name) || !isRecord(exec.arguments)) return undefined;
88
+ const raw = typeof exec.arguments.file_path === 'string' ? exec.arguments.file_path : typeof exec.arguments.path === 'string' ? exec.arguments.path : undefined;
89
+ const path = raw?.trim();
90
+ return path ? path : undefined;
91
+ }
92
+
93
+ /** The user messages of a session's visible history (engine session API; empty when unavailable). */
94
+ export function historyMessages(agent) {
95
+ const session = agent?.session;
96
+ const out = [];
97
+ try {
98
+ const nodes = session?.surface?.nodes;
99
+ if (nodes && typeof session.eventAt === 'function') {
100
+ for (const seq of nodes) {
101
+ const event = session.eventAt(seq);
102
+ if (event?.type === 'user/message' && isRecord(event.data)) out.push(event.data);
103
+ }
104
+ }
105
+ } catch {
106
+ // a session without a readable surface has no history to reuse
107
+ }
108
+ if (out.length === 0 && Array.isArray(agent?.history)) for (const message of agent.history) if (isRecord(message)) out.push(message);
109
+ return out;
110
+ }
111
+
112
+ function sessionIdOf(agent) {
113
+ const id = agent?.session?.id ?? agent?.sessionId;
114
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
115
+ }
116
+
117
+ /** A resolution with no workspace: what `describe` answers when neither a session nor a folder is given. */
118
+ export function emptyResolution(read) {
119
+ const settings = read.settings;
120
+ return {
121
+ version: 1,
122
+ cwd: '',
123
+ root: { path: '', kind: 'folder' },
124
+ mode: { id: modeLabel(settings), label: describeMode(settings) },
125
+ settings,
126
+ ...(read.error === undefined ? {} : { settingsError: read.error }),
127
+ sources: [],
128
+ docs: [],
129
+ conflicts: [],
130
+ tier1: { text: '', bytes: 0, tokens: 0, digest: '', budgetBytes: settings.budgetBytes },
131
+ };
132
+ }
133
+
134
+ export class InstructionsError extends Error {
135
+ constructor(code, message) {
136
+ super(message);
137
+ this.name = 'RemoteError';
138
+ this.code = `${SERVICE_KEY}/${code}`;
139
+ this.isDSHRemoteError = true;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * The read/act service behind /instructions (TUI), `picasso instructions` and the Mac panel.
145
+ * `describe({ sessionId?, cwd? })`: a live session's resolution with its activations, else a fresh one for `cwd`.
146
+ * `activate({ sessionId, name })`: load a manual / model-selected / scoped rule into that session (Tier 2).
147
+ */
148
+ export class InstructionsService {
149
+ constructor({ byId, resolve, globals, settings }) {
150
+ this.byId = byId;
151
+ this.resolveFresh = resolve;
152
+ this.globals = globals;
153
+ this.settings = settings ?? (() => readInstructionSettings(process.env));
154
+ }
155
+
156
+ async describe(params = {}) {
157
+ const sessionId = typeof params?.sessionId === 'string' && params.sessionId.length > 0 ? params.sessionId : undefined;
158
+ const state = sessionId === undefined ? undefined : this.byId.get(sessionId);
159
+ if (state !== undefined) return buildReport(state.activation.resolution, { sessionId, globals: this.globals() });
160
+ const cwd = typeof params?.cwd === 'string' && params.cwd.length > 0 ? params.cwd : undefined;
161
+ // No session and no folder (Settings): the same shape with no sources, so the mode, budget and the global
162
+ // sources' switches can still be shown.
163
+ if (cwd === undefined) return buildReport(emptyResolution(this.settings()), { globals: this.globals() });
164
+ return buildReport(this.resolveFresh(cwd, { includeDocs: true }), { globals: this.globals() });
165
+ }
166
+
167
+ async activate(params = {}) {
168
+ const sessionId = typeof params?.sessionId === 'string' ? params.sessionId : '';
169
+ const state = this.byId.get(sessionId);
170
+ if (state === undefined) throw new InstructionsError('unknown-session', 'That session has not started a turn in this engine yet.');
171
+ const query = typeof params?.name === 'string' ? params.name : '';
172
+ const result = activateByName(state.activation, query);
173
+ if (result.source === undefined) throw new InstructionsError('not-found', result.error ?? 'No such rule.');
174
+ state.pending.push(tier2Message(renderActivation([result.source], state.activation.resolution.settings.budgetBytes), { activated: Object.freeze([result.source.id]) }));
175
+ return { ok: true, path: result.source.path, tokens: result.source.tokens };
176
+ }
177
+ }
178
+
179
+ Object.defineProperty(InstructionsService.prototype, REMOTE_METHOD_DESCRIPTOR, {
180
+ configurable: true,
181
+ value: Object.freeze({
182
+ version: 1,
183
+ methods: Object.freeze([
184
+ Object.freeze({ method: DESCRIBE_METHOD, invocation: Object.freeze({ kind: 'direct' }) }),
185
+ Object.freeze({ method: ACTIVATE_METHOD, invocation: Object.freeze({ kind: 'direct' }) }),
186
+ ]),
187
+ }),
188
+ });
189
+
190
+ /**
191
+ * @param {any} ctx
192
+ * @param {{ resolve?: (cwd: string, options?: object) => import('./resolve.js').Resolution, globals?: () => any[] }} [config]
193
+ * `resolve` is a test seam; the mounted rows pass no config, so every surface resolves identically.
194
+ */
195
+ export function apply(ctx, config = {}) {
196
+ // Other tools' home-directory files: listed with their switches, read only when switched on (globals.js).
197
+ const globalsReport = typeof config.globals === 'function' ? config.globals : () => globalSourcesReport(readInstructionSettings(process.env).settings, process.env);
198
+ const resolveFresh = typeof config.resolve === 'function'
199
+ ? config.resolve
200
+ : (cwd, options = {}) => resolveInstructions({ cwd, env: process.env, globals: globalCandidates(process.env), ...options });
201
+ /** @type {WeakMap<object, any>} */
202
+ const states = new WeakMap();
203
+ /** @type {Map<string, any>} */
204
+ const byId = new Map();
205
+
206
+ const service = new InstructionsService({ byId, resolve: resolveFresh, globals: globalsReport });
207
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
208
+ try {
209
+ ctx.provide?.(SERVICE_KEY, service);
210
+ } catch {
211
+ // provided twice (a second load): the first instance answers
212
+ }
213
+ ctx.get?.('rpc')?.register?.('instructions/describe', (params) => service.describe(params));
214
+
215
+ const warn = (message, error) => {
216
+ try {
217
+ ctx.logger?.warn?.(`${message}: %o`, error);
218
+ } catch {
219
+ // logging never breaks a step
220
+ }
221
+ };
222
+
223
+ const startState = async (agent, signal, sessionKey) => {
224
+ let cwd;
225
+ try {
226
+ cwd = await ctx.get?.('workingDirectory')?.ensure?.(agent, signal);
227
+ } catch {
228
+ cwd = undefined;
229
+ }
230
+ if (typeof cwd !== 'string' && typeof agent?.cwd === 'string') cwd = agent.cwd;
231
+ if (typeof cwd !== 'string' || cwd.length === 0) return undefined;
232
+ const resolution = resolveFresh(cwd, { includeDocs: true });
233
+ const state = { cwd, activation: activationState(resolution), pending: [], tier1: undefined, sessionId: sessionIdOf(agent) };
234
+ const history = historyMessages(agent);
235
+ const recorded = history.filter(isPicassoInstructionMessage);
236
+ const baseline = recorded.find((message) => message.source.tier === 1);
237
+ if (baseline === undefined) {
238
+ state.tier1 = baselineMessage(resolution);
239
+ } else {
240
+ // A resumed session: its Tier 1 is already in the history. Re-deliver nothing; report what changed since.
241
+ for (const message of recorded) for (const id of Array.isArray(message.source.activated) ? message.source.activated : []) state.activation.active.add(id);
242
+ const recordedSources = Array.isArray(baseline.source.sources) ? baseline.source.sources : [];
243
+ const before = { sources: recordedSources.map((s) => ({ id: s.id, path: s.id, digest: s.digest, tier: 1, status: 'loaded' })) };
244
+ const diff = diffAlwaysOn(/** @type {any} */ (before), resolution);
245
+ const text = renderChanges(diff, resolution.settings.budgetBytes);
246
+ if (text !== '') state.pending.push(tier2Message(text, { changed: Object.freeze([...diff.changed, ...diff.added, ...diff.removed].map((s) => s.id)) }));
247
+ }
248
+ states.set(sessionKey, state);
249
+ if (state.sessionId !== undefined) byId.set(state.sessionId, state);
250
+ return state;
251
+ };
252
+
253
+ const refresh = (state) => {
254
+ const fresh = resolveFresh(state.cwd, { includeDocs: false });
255
+ const previous = state.activation.resolution;
256
+ const diff = diffAlwaysOn(previous, fresh);
257
+ if (diff.changed.length + diff.added.length + diff.removed.length === 0) return;
258
+ const text = renderChanges(diff, fresh.settings.budgetBytes);
259
+ // Carry the session's activations and docs into the fresh resolution, so later touches and the inspector see both.
260
+ for (const source of fresh.sources) {
261
+ if (!state.activation.active.has(source.id)) continue;
262
+ source.status = 'loaded';
263
+ source.tier = 2;
264
+ }
265
+ for (const source of previous.sources) if (state.activation.active.has(source.id) && !fresh.sources.some((s) => s.id === source.id)) fresh.sources.push(source);
266
+ fresh.docs = previous.docs;
267
+ state.activation.resolution = fresh;
268
+ for (const source of [...diff.changed, ...diff.added]) if (source.digest) state.activation.digests.add(source.digest);
269
+ if (text !== '') state.pending.push(tier2Message(text, { changed: Object.freeze([...diff.changed, ...diff.added, ...diff.removed].map((s) => s.id)) }));
270
+ };
271
+
272
+ ctx.on('agent/pre-step', async (payload, next) => {
273
+ const decision = typeof next === 'function' ? await next() : payload;
274
+ if (!isRecord(decision) || decision.kind === 'reject' || !Array.isArray(decision.messages)) return decision;
275
+ // The engine's own loader never reaches the model: its files are covered (or deliberately excluded) here.
276
+ let messages = decision.messages.some(isEngineInstructionMessage) ? decision.messages.filter((m) => !isEngineInstructionMessage(m)) : decision.messages;
277
+ const agent = payload?.agent;
278
+ const sessionKey = isRecord(agent) ? (isRecord(agent.session) ? agent.session : agent) : undefined;
279
+ if (sessionKey === undefined) return messages === decision.messages ? decision : { ...decision, messages };
280
+ const step = payload?.step;
281
+ try {
282
+ let state = states.get(sessionKey);
283
+ if (state === undefined) {
284
+ if (messages.length === 0) return messages === decision.messages ? decision : { ...decision, messages };
285
+ state = await startState(agent, payload?.signal, sessionKey);
286
+ } else if (step === 1 && messages.length > 0) {
287
+ refresh(state);
288
+ }
289
+ if (state !== undefined) {
290
+ const claimed = Array.isArray(payload?.messages) ? payload.messages : [];
291
+ const lastClaimed = messages.findLastIndex((message) => claimed.includes(message));
292
+ const additions = [];
293
+ if (state.tier1 !== undefined) {
294
+ additions.push(state.tier1);
295
+ state.tier1 = undefined;
296
+ }
297
+ const firstStepOfTurnWithoutInput = step === 1 && messages.length === 0;
298
+ if (!firstStepOfTurnWithoutInput && state.pending.length > 0) additions.push(...state.pending.splice(0));
299
+ if (additions.length > 0) messages = messages.toSpliced(lastClaimed + 1, 0, ...additions);
300
+ }
301
+ } catch (error) {
302
+ if (payload?.signal?.aborted) throw error;
303
+ warn('workspace instructions were not resolved', error);
304
+ }
305
+ return messages === decision.messages ? decision : { ...decision, messages };
306
+ }, { global: true, prepend: true });
307
+
308
+ ctx.on('tools/result', (exec, result) => {
309
+ try {
310
+ if (!isRecord(exec) || result?.isError || exec.signal?.aborted) return;
311
+ const path = touchedPath(exec);
312
+ if (path === undefined) return;
313
+ const agent = exec.agent;
314
+ const sessionKey = isRecord(agent) ? (isRecord(agent.session) ? agent.session : agent) : undefined;
315
+ const state = sessionKey === undefined ? undefined : states.get(sessionKey);
316
+ if (state === undefined) return;
317
+ const delivered = activateForPath(state.activation, path);
318
+ if (delivered.length === 0) return;
319
+ state.pending.push(tier2Message(renderActivation(delivered, state.activation.resolution.settings.budgetBytes), { activated: Object.freeze(delivered.map((s) => s.id)) }));
320
+ } catch (error) {
321
+ warn('scoped instructions were not activated', error);
322
+ }
323
+ });
324
+ }
325
+
326
+ export default { name, dshTarget, apply, RESOLVER, SOURCE_KIND, SERVICE_KEY };
@@ -0,0 +1,64 @@
1
+ // The three discovery modes (owner spec §7). One shared setting for the Mac and the CLI.
2
+ //
3
+ // * smart (default): every format, applicable rules loaded, duplicates merged, conflicts flagged.
4
+ // * agents-first: AGENTS.md is the canonical baseline. Where a directory has AGENTS.md (or its override), the other
5
+ // tools' always-on files in that directory are not loaded up front; they stay listed so the model can read them
6
+ // when relevant, and every scoped rule still activates on matching files. A directory without AGENTS.md behaves
7
+ // like smart.
8
+ // * native: replicate one harness's own discovery and precedence (Claude Code, Codex, Gemini CLI, Copilot, Cursor).
9
+ //
10
+ // PICASSO.md is Picasso's own file and is read in every mode.
11
+
12
+ /** Formats every mode reads (Picasso's own). */
13
+ const PICASSO_NATIVE = ['picasso-md'];
14
+
15
+ /** The AGENTS.md family: the portable baseline in agents-first mode. */
16
+ export const AGENTS_FAMILY = Object.freeze(['agents-md', 'agents-override-md', 'agents-local-md']);
17
+
18
+ /**
19
+ * @typedef {object} NativeProfile
20
+ * @property {string} label
21
+ * @property {readonly string[]} formats registry ids this harness reads
22
+ * @property {boolean} [ancestorsAboveRoot] also read hierarchical files in parent folders above the project root
23
+ * (never the home folder itself, which holds global files)
24
+ * @property {boolean} [followImports] expand `@path` imports
25
+ */
26
+
27
+ /** @type {Readonly<Record<string, NativeProfile>>} */
28
+ export const NATIVE_PROFILES = Object.freeze({
29
+ 'claude-code': { label: 'Claude Code', formats: ['claude-md', 'claude-dir-md', 'claude-local-md', 'claude-rules'], ancestorsAboveRoot: true, followImports: true },
30
+ codex: { label: 'Codex', formats: ['agents-override-md', 'agents-md'], followImports: false },
31
+ 'gemini-cli': { label: 'Gemini CLI', formats: ['gemini-md'], ancestorsAboveRoot: true, followImports: true },
32
+ copilot: { label: 'GitHub Copilot', formats: ['copilot-instructions', 'copilot-scoped', 'agents-md', 'claude-md', 'gemini-md'], followImports: false },
33
+ cursor: { label: 'Cursor', formats: ['cursor-rules', 'cursorrules', 'agents-md', 'claude-md'], followImports: false },
34
+ });
35
+
36
+ /**
37
+ * Whether a format is read under the settings, before per-directory rules (agents-first) apply.
38
+ * @param {string} formatId
39
+ * @param {{ mode: string, nativeAgent: string }} settings
40
+ */
41
+ export function formatEnabled(formatId, settings) {
42
+ if (PICASSO_NATIVE.includes(formatId)) return true;
43
+ if (settings.mode !== 'native') return true;
44
+ const profile = NATIVE_PROFILES[settings.nativeAgent];
45
+ return profile === undefined ? true : profile.formats.includes(formatId);
46
+ }
47
+
48
+ /** Whether `@path` imports are expanded under the settings (smart and agents-first always; native per harness). */
49
+ export function followsImports(settings) {
50
+ if (settings.mode !== 'native') return true;
51
+ return NATIVE_PROFILES[settings.nativeAgent]?.followImports === true;
52
+ }
53
+
54
+ /** Whether to read hierarchical files above the project root (native Claude Code / Gemini CLI). */
55
+ export function readsAncestorsAboveRoot(settings) {
56
+ return settings.mode === 'native' && NATIVE_PROFILES[settings.nativeAgent]?.ancestorsAboveRoot === true;
57
+ }
58
+
59
+ /** The human label of the active mode. */
60
+ export function describeMode(settings) {
61
+ if (settings.mode === 'agents-first') return 'AGENTS.md-first';
62
+ if (settings.mode === 'native') return `Native: ${NATIVE_PROFILES[settings.nativeAgent]?.label ?? settings.nativeAgent}`;
63
+ return 'Smart compatibility';
64
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@picasso/instructions",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Picasso's universal instruction discovery: one registry, resolver and renderer for every repository instruction format (AGENTS.md, CLAUDE.md, Copilot, Cursor, Windsurf, Cline, Roo, Continue, Kiro, Devin, Antigravity, Augment, Kilo, Zed…), shared by the CLI/TUI and the Mac relay, plus the engine plugin that feeds the resolved always-on set into Tier 1.",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./report": { "types": "./report.d.ts", "default": "./report.js" },
11
+ "./formats": "./formats.js",
12
+ "./frontmatter": "./frontmatter.js",
13
+ "./glob": "./glob.js",
14
+ "./parse": "./parse.js",
15
+ "./scan": "./scan.js",
16
+ "./imports": "./imports.js",
17
+ "./conflicts": "./conflicts.js",
18
+ "./modes": "./modes.js",
19
+ "./settings": { "types": "./settings.d.ts", "default": "./settings.js" },
20
+ "./resolve": { "types": "./resolve.d.ts", "default": "./resolve.js" },
21
+ "./skills": { "types": "./skills.d.ts", "default": "./skills.js" },
22
+ "./globals": { "types": "./globals.d.ts", "default": "./globals.js" },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "dshTarget": "0.2.2-rc.2",
26
+ "scripts": {
27
+ "test": "node --import ../../test/setup/hermetic-preload.mjs --test test/*.test.mjs"
28
+ },
29
+ "license": "UNLICENSED"
30
+ }
@@ -0,0 +1,134 @@
1
+ // Turn one discovered file into a classified instruction source: its body, its activation (always / glob /
2
+ // model-selected / manual / recognised) and the frontmatter that decided it. Zero dependencies.
3
+ //
4
+ // Frontmatter keys read (and only these): applyTo (Copilot), globs + alwaysApply + description (Cursor, Continue),
5
+ // paths (Claude, Cline), trigger (Windsurf, Devin, Antigravity), inclusion + fileMatchPattern (Kiro), type (Augment),
6
+ // name. Every other key is ignored: a rule file is project data and cannot set Picasso options.
7
+
8
+ import { createHash } from 'node:crypto';
9
+ import { asBoolean, asString, asStringList, parseFrontmatter } from './frontmatter.js';
10
+ import { isMatchAll } from './glob.js';
11
+
12
+ /** Frontmatter keys that decide activation; anything else is reported as ignored. */
13
+ export const ACTIVATION_KEYS = Object.freeze(['applyTo', 'globs', 'paths', 'alwaysApply', 'description', 'trigger', 'inclusion', 'fileMatchPattern', 'type', 'name']);
14
+
15
+ /** Approximate model tokens for UTF-8 text (4 bytes per token, rounded up): the inspector's cost column. */
16
+ export function estimateTokens(text) {
17
+ return Math.ceil(Buffer.byteLength(String(text ?? ''), 'utf8') / 4);
18
+ }
19
+
20
+ /** Whitespace-insensitive content identity: every run of whitespace (spaces, line endings, blank lines) counts as one space. */
21
+ export function normalizedDigest(text) {
22
+ const normalized = String(text ?? '').replace(/\s+/gu, ' ').trim();
23
+ return createHash('sha1').update(normalized).digest('hex');
24
+ }
25
+
26
+ /** Exact-bytes identity (change detection). */
27
+ export function exactDigest(text) {
28
+ return createHash('sha1').update(String(text ?? '')).digest('hex');
29
+ }
30
+
31
+ const TRIGGER_ALWAYS = /^(?:always|always_?on|always_?apply|alwaysapply)$/iu;
32
+ const TRIGGER_GLOB = /^(?:glob|globs|file_?match|filematch|auto_?attached|auto)$/iu;
33
+ const TRIGGER_MODEL = /^(?:model|model_?decision|agent_?requested|requested|intelligent|apply_?intelligently|description)$/iu;
34
+ const TRIGGER_MANUAL = /^(?:manual|manually|on_?request|never)$/iu;
35
+
36
+ /**
37
+ * @typedef {object} Activation
38
+ * @property {'always' | 'glob' | 'model' | 'manual' | 'index' | 'recognized'} kind
39
+ * @property {string[]} [globs] file patterns (kind `glob`)
40
+ * @property {string} [description] what a model-selected rule is for
41
+ * @property {string} [mode] Roo mode-specific rules
42
+ * @property {string} reason why: the frontmatter key or default that decided it
43
+ */
44
+
45
+ /**
46
+ * Decide a rule's activation from its frontmatter and the format default.
47
+ * @param {Record<string, unknown>} data parsed frontmatter
48
+ * @param {import('./formats.js').InstructionFormat} format
49
+ * @returns {Activation}
50
+ */
51
+ export function interpretActivation(data, format) {
52
+ const description = asString(data.description);
53
+ const globs = [
54
+ ...asStringList(data.applyTo),
55
+ ...asStringList(data.globs),
56
+ ...asStringList(data.paths),
57
+ ...asStringList(data.fileMatchPattern),
58
+ ];
59
+ const withDescription = (activation) => (description === undefined ? activation : { ...activation, description });
60
+ const globActivation = (reason) => {
61
+ if (globs.some(isMatchAll)) return withDescription({ kind: 'always', reason: `${reason} matches every file` });
62
+ return withDescription({ kind: 'glob', globs, reason });
63
+ };
64
+
65
+ // Explicit trigger words first (Windsurf/Devin/Antigravity `trigger`, Kiro `inclusion`, Augment `type`).
66
+ for (const key of ['trigger', 'inclusion', 'type']) {
67
+ const word = asString(data[key]);
68
+ if (word === undefined) continue;
69
+ if (TRIGGER_ALWAYS.test(word)) return withDescription({ kind: 'always', reason: `${key}: ${word}` });
70
+ if (TRIGGER_GLOB.test(word)) {
71
+ if (globs.length > 0) return globActivation(`${key}: ${word}`);
72
+ return withDescription({ kind: 'manual', reason: `${key}: ${word} without file patterns` });
73
+ }
74
+ if (TRIGGER_MODEL.test(word)) return withDescription({ kind: description === undefined ? 'manual' : 'model', reason: `${key}: ${word}` });
75
+ if (TRIGGER_MANUAL.test(word)) return withDescription({ kind: 'manual', reason: `${key}: ${word}` });
76
+ }
77
+
78
+ const alwaysApply = asBoolean(data.alwaysApply);
79
+ if (alwaysApply === true) return withDescription({ kind: 'always', reason: 'alwaysApply: true' });
80
+ if (globs.length > 0) {
81
+ const key = data.applyTo !== undefined ? 'applyTo' : data.globs !== undefined ? 'globs' : data.paths !== undefined ? 'paths' : 'fileMatchPattern';
82
+ return globActivation(key);
83
+ }
84
+ if (alwaysApply === false) {
85
+ return description === undefined
86
+ ? { kind: 'manual', reason: 'alwaysApply: false' }
87
+ : { kind: 'model', description, reason: 'alwaysApply: false with a description' };
88
+ }
89
+ // No activation keys: the format default. A rule folder whose default is `manual` (Cursor, Copilot) still lets a
90
+ // description make it model-selected.
91
+ if (format.activation === 'manual' && description !== undefined) return { kind: 'model', description, reason: 'description only' };
92
+ return withDescription({ kind: format.activation, reason: 'format default' });
93
+ }
94
+
95
+ /** A short title for a rule: its frontmatter name, else its file name without the rule suffixes. */
96
+ export function ruleName(relPath, data = {}) {
97
+ const fromFrontmatter = asString(data.name);
98
+ if (fromFrontmatter !== undefined) return fromFrontmatter;
99
+ const base = String(relPath).split('/').pop() ?? String(relPath);
100
+ return base.replace(/\.(?:instructions|agent|prompt)\.md$/u, '').replace(/\.(?:mdc|md|txt)$/u, '');
101
+ }
102
+
103
+ /**
104
+ * @typedef {object} ParsedSource
105
+ * @property {string} body content with frontmatter removed (what is rendered)
106
+ * @property {Activation} activation
107
+ * @property {string} name
108
+ * @property {string} [description]
109
+ * @property {string[]} ignoredKeys frontmatter keys Picasso does not act on (reported, never applied)
110
+ * @property {string} [error] frontmatter problem (the body is still used)
111
+ */
112
+
113
+ /**
114
+ * Classify a file's text for one format.
115
+ * @param {string} text
116
+ * @param {import('./formats.js').InstructionFormat} format
117
+ * @param {{ relPath: string, mode?: string }} where path inside the format folder; Roo mode for mode rules
118
+ * @returns {ParsedSource}
119
+ */
120
+ export function parseSource(text, format, where) {
121
+ const parsed = format.frontmatter ? parseFrontmatter(text) : { data: {}, body: String(text ?? ''), hasFrontmatter: false };
122
+ let activation = interpretActivation(parsed.data, format);
123
+ if (where.mode !== undefined) activation = { ...activation, kind: 'manual', mode: where.mode, reason: `mode rule (${where.mode})` };
124
+ const ignoredKeys = Object.keys(parsed.data).filter((key) => !ACTIVATION_KEYS.includes(key)).sort();
125
+ const description = asString(parsed.data.description);
126
+ return {
127
+ body: parsed.body,
128
+ activation,
129
+ name: ruleName(where.relPath, parsed.data),
130
+ ...(description === undefined ? {} : { description }),
131
+ ignoredKeys,
132
+ ...(parsed.error === undefined ? {} : { error: parsed.error }),
133
+ };
134
+ }