@simonfestl/husky-cli 1.6.1 → 1.6.3

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.
@@ -842,6 +842,55 @@ chatCommand
842
842
  }
843
843
  });
844
844
  // ============================================
845
+ // GOOGLE CHAT SPACES
846
+ // ============================================
847
+ chatCommand
848
+ .command("spaces")
849
+ .description("List available Google Chat spaces")
850
+ .option("--json", "Output as JSON")
851
+ .action(async (options) => {
852
+ const config = getConfig();
853
+ const huskyApiUrl = getHuskyApiUrl();
854
+ if (!huskyApiUrl) {
855
+ console.error("Error: API URL not configured. Set husky-api-url or api-url.");
856
+ process.exit(1);
857
+ }
858
+ try {
859
+ const res = await fetch(`${huskyApiUrl}/api/google-chat/spaces`, {
860
+ headers: config.apiKey ? { "x-api-key": config.apiKey } : {},
861
+ });
862
+ if (!res.ok) {
863
+ throw new Error(`API error: ${res.status}`);
864
+ }
865
+ const data = await res.json();
866
+ if (options.json) {
867
+ console.log(JSON.stringify(data, null, 2));
868
+ return;
869
+ }
870
+ if (!data.spaces || data.spaces.length === 0) {
871
+ console.log("No Google Chat spaces found.");
872
+ console.log("Make sure the Husky bot is added to at least one space.");
873
+ return;
874
+ }
875
+ console.log("\n Google Chat Spaces");
876
+ console.log(" " + "─".repeat(60));
877
+ for (const space of data.spaces) {
878
+ const isDefault = space.name === data.defaultSpace ? " (default)" : "";
879
+ const typeIcon = space.type === "SPACE" ? "🏠" : space.type === "GROUP_CHAT" ? "👥" : "💬";
880
+ console.log(` ${typeIcon} ${space.displayName || "(unnamed)"}${isDefault}`);
881
+ console.log(` ID: ${space.name}`);
882
+ console.log("");
883
+ }
884
+ console.log(" Use --space <ID> with chat commands, e.g.:");
885
+ console.log(` husky chat ask --space "${data.spaces[0]?.name}" "Your question"`);
886
+ console.log("");
887
+ }
888
+ catch (error) {
889
+ console.error("Error fetching spaces:", error);
890
+ process.exit(1);
891
+ }
892
+ });
893
+ // ============================================
845
894
  // REVIEW COMMANDS (kept for backwards compatibility)
846
895
  // ============================================
847
896
  chatCommand
@@ -11,9 +11,10 @@ workerCommand
11
11
  .action(async (options) => {
12
12
  const config = getConfig();
13
13
  const identity = getWorkerIdentity();
14
- // Fetch role from API
15
- let role = "unknown";
16
- let permissions = [];
14
+ // Fetch role from API, fallback to cached config
15
+ let role = config.role || "unknown";
16
+ let permissions = config.permissions || [];
17
+ let roleSource = "cached";
17
18
  if (config.apiUrl && config.apiKey) {
18
19
  try {
19
20
  const res = await fetch(`${config.apiUrl}/api/auth/whoami`, {
@@ -21,16 +22,17 @@ workerCommand
21
22
  });
22
23
  if (res.ok) {
23
24
  const data = await res.json();
24
- role = data.role || "unknown";
25
- permissions = data.permissions || [];
25
+ role = data.role || role;
26
+ permissions = data.permissions || permissions;
27
+ roleSource = "api";
26
28
  }
27
29
  }
28
30
  catch {
29
- // Silently fail - role will show as "unknown"
31
+ // Fallback to cached role from config
30
32
  }
31
33
  }
32
34
  if (options.json) {
33
- console.log(JSON.stringify({ ...identity, role, permissions }, null, 2));
35
+ console.log(JSON.stringify({ ...identity, role, permissions, roleSource }, null, 2));
34
36
  }
35
37
  else {
36
38
  console.log("\n Worker Identity");
@@ -42,7 +44,7 @@ workerCommand
42
44
  console.log(` Platform: ${identity.platform}`);
43
45
  console.log(` Version: ${identity.agentVersion}`);
44
46
  console.log(" " + "─".repeat(40));
45
- console.log(` Role: ${role}`);
47
+ console.log(` Role: ${role}${roleSource === "cached" ? " (cached)" : ""}`);
46
48
  if (permissions.length > 0) {
47
49
  console.log(` Perms: ${permissions.join(", ")}`);
48
50
  }
@@ -11,11 +11,11 @@ function ensureConfig() {
11
11
  }
12
12
  return config;
13
13
  }
14
- // husky workflow list
15
14
  workflowCommand
16
15
  .command("list")
17
16
  .description("List all workflows")
18
17
  .option("--value-stream <valueStream>", "Filter by value stream")
18
+ .option("-l, --limit <num>", "Max results")
19
19
  .option("--json", "Output as JSON")
20
20
  .action(async (options) => {
21
21
  const config = ensureConfig();
@@ -30,7 +30,10 @@ workflowCommand
30
30
  if (!res.ok) {
31
31
  throw new Error(`API error: ${res.status}`);
32
32
  }
33
- const workflows = await res.json();
33
+ let workflows = await res.json();
34
+ if (options.limit) {
35
+ workflows = workflows.slice(0, parseInt(options.limit, 10));
36
+ }
34
37
  if (options.json) {
35
38
  console.log(JSON.stringify(workflows, null, 2));
36
39
  }
@@ -49,5 +49,13 @@ export declare class QdrantClient {
49
49
  getPoint(collectionName: string, id: string | number): Promise<Point | null>;
50
50
  deletePoints(collectionName: string, ids: (string | number)[]): Promise<void>;
51
51
  count(collectionName: string): Promise<number>;
52
+ scroll(collectionName: string, options?: {
53
+ filter?: Record<string, unknown>;
54
+ limit?: number;
55
+ with_payload?: boolean;
56
+ }): Promise<Array<{
57
+ id: string | number;
58
+ payload: Record<string, unknown>;
59
+ }>>;
52
60
  }
53
61
  export default QdrantClient;
@@ -157,5 +157,19 @@ export class QdrantClient {
157
157
  const info = await this.getCollection(collectionName);
158
158
  return info.pointsCount;
159
159
  }
160
+ async scroll(collectionName, options = {}) {
161
+ const response = await this.request(`/collections/${collectionName}/points/scroll`, {
162
+ method: 'POST',
163
+ body: JSON.stringify({
164
+ filter: options.filter,
165
+ limit: options.limit || 50,
166
+ with_payload: options.with_payload ?? true,
167
+ }),
168
+ });
169
+ return response.result.points.map(p => ({
170
+ id: p.id,
171
+ payload: p.payload || {},
172
+ }));
173
+ }
160
174
  }
161
175
  export default QdrantClient;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * SOP (Standard Operating Procedure) Service
3
+ *
4
+ * Manages SOPs in Qdrant with semantic search capabilities.
5
+ * SOPs are auto-generated from resolved ticket patterns and can be
6
+ * approved/deprecated by humans.
7
+ */
8
+ export declare const SOP_STATUSES: readonly ["draft", "approved", "deprecated"];
9
+ export type SOPStatus = typeof SOP_STATUSES[number];
10
+ export interface SOPStep {
11
+ order: number;
12
+ action: string;
13
+ description: string;
14
+ tool?: string;
15
+ required?: boolean;
16
+ conditions?: string;
17
+ }
18
+ export interface SOP {
19
+ id: string;
20
+ title: string;
21
+ description: string;
22
+ trigger: string;
23
+ category: string;
24
+ steps: SOPStep[];
25
+ source_tickets: number[];
26
+ status: SOPStatus;
27
+ tags: string[];
28
+ created_at: string;
29
+ updated_at: string;
30
+ approved_by?: string;
31
+ approved_at?: string;
32
+ deprecated_by?: string;
33
+ deprecated_at?: string;
34
+ version: number;
35
+ confidence_score?: number;
36
+ }
37
+ export interface CreateSOPInput {
38
+ title: string;
39
+ description: string;
40
+ trigger: string;
41
+ category: string;
42
+ steps: SOPStep[];
43
+ source_tickets?: number[];
44
+ tags?: string[];
45
+ confidence_score?: number;
46
+ }
47
+ export interface UpdateSOPInput {
48
+ title?: string;
49
+ description?: string;
50
+ trigger?: string;
51
+ category?: string;
52
+ steps?: SOPStep[];
53
+ tags?: string[];
54
+ }
55
+ export interface SOPSearchResult {
56
+ sop: SOP;
57
+ score: number;
58
+ }
59
+ export declare class SOPService {
60
+ private qdrant;
61
+ private embeddings;
62
+ constructor();
63
+ create(input: CreateSOPInput): Promise<SOP>;
64
+ get(id: string): Promise<SOP | null>;
65
+ update(id: string, input: UpdateSOPInput): Promise<SOP | null>;
66
+ approve(id: string, approver: string): Promise<SOP | null>;
67
+ deprecate(id: string, deprecator: string): Promise<SOP | null>;
68
+ delete(id: string): Promise<void>;
69
+ list(options?: {
70
+ status?: SOPStatus;
71
+ category?: string;
72
+ limit?: number;
73
+ }): Promise<SOP[]>;
74
+ search(query: string, options?: {
75
+ limit?: number;
76
+ status?: SOPStatus;
77
+ minScore?: number;
78
+ }): Promise<SOPSearchResult[]>;
79
+ findByTrigger(trigger: string, options?: {
80
+ status?: SOPStatus;
81
+ minScore?: number;
82
+ }): Promise<SOPSearchResult | null>;
83
+ getByCategory(category: string, status?: SOPStatus): Promise<SOP[]>;
84
+ getCategories(): Promise<{
85
+ category: string;
86
+ count: number;
87
+ }[]>;
88
+ stats(): Promise<{
89
+ total: number;
90
+ byStatus: Record<SOPStatus, number>;
91
+ byCategory: Record<string, number>;
92
+ }>;
93
+ private buildEmbeddingText;
94
+ private sopToPayload;
95
+ private payloadToSOP;
96
+ private scrollPoints;
97
+ }
98
+ export default SOPService;
@@ -0,0 +1,307 @@
1
+ /**
2
+ * SOP (Standard Operating Procedure) Service
3
+ *
4
+ * Manages SOPs in Qdrant with semantic search capabilities.
5
+ * SOPs are auto-generated from resolved ticket patterns and can be
6
+ * approved/deprecated by humans.
7
+ */
8
+ import { QdrantClient } from './qdrant.js';
9
+ import { EmbeddingService } from './embeddings.js';
10
+ import { v4 as uuidv4 } from 'uuid';
11
+ // ============================================================================
12
+ // Types
13
+ // ============================================================================
14
+ export const SOP_STATUSES = ['draft', 'approved', 'deprecated'];
15
+ // ============================================================================
16
+ // Constants
17
+ // ============================================================================
18
+ const SOP_COLLECTION = 'knowledge';
19
+ const VECTOR_DIM = 768;
20
+ // ============================================================================
21
+ // SOP Service
22
+ // ============================================================================
23
+ export class SOPService {
24
+ qdrant;
25
+ embeddings;
26
+ constructor() {
27
+ this.qdrant = QdrantClient.fromConfig();
28
+ this.embeddings = EmbeddingService.fromConfig();
29
+ }
30
+ async create(input) {
31
+ const id = `sop_${uuidv4().slice(0, 8)}`;
32
+ const now = new Date().toISOString();
33
+ const sop = {
34
+ id,
35
+ title: input.title,
36
+ description: input.description,
37
+ trigger: input.trigger,
38
+ category: input.category,
39
+ steps: input.steps.map((s, i) => ({
40
+ ...s,
41
+ order: s.order || i + 1,
42
+ required: s.required ?? true,
43
+ })),
44
+ source_tickets: input.source_tickets || [],
45
+ status: 'draft',
46
+ tags: input.tags || [],
47
+ created_at: now,
48
+ updated_at: now,
49
+ version: 1,
50
+ confidence_score: input.confidence_score,
51
+ };
52
+ const embeddingText = this.buildEmbeddingText(sop);
53
+ const vector = await this.embeddings.embed(embeddingText);
54
+ await this.qdrant.upsertOne(SOP_COLLECTION, id, vector, {
55
+ type: 'sop',
56
+ ...this.sopToPayload(sop),
57
+ });
58
+ return sop;
59
+ }
60
+ async get(id) {
61
+ const point = await this.qdrant.getPoint(SOP_COLLECTION, id);
62
+ if (!point || !point.payload)
63
+ return null;
64
+ const payload = point.payload;
65
+ if (payload.type !== 'sop')
66
+ return null;
67
+ return this.payloadToSOP(payload);
68
+ }
69
+ async update(id, input) {
70
+ const existing = await this.get(id);
71
+ if (!existing)
72
+ return null;
73
+ const now = new Date().toISOString();
74
+ const updated = {
75
+ ...existing,
76
+ title: input.title ?? existing.title,
77
+ description: input.description ?? existing.description,
78
+ trigger: input.trigger ?? existing.trigger,
79
+ category: input.category ?? existing.category,
80
+ steps: input.steps ?? existing.steps,
81
+ tags: input.tags ?? existing.tags,
82
+ updated_at: now,
83
+ version: existing.version + 1,
84
+ };
85
+ const embeddingText = this.buildEmbeddingText(updated);
86
+ const vector = await this.embeddings.embed(embeddingText);
87
+ await this.qdrant.upsertOne(SOP_COLLECTION, id, vector, {
88
+ type: 'sop',
89
+ ...this.sopToPayload(updated),
90
+ });
91
+ return updated;
92
+ }
93
+ async approve(id, approver) {
94
+ const existing = await this.get(id);
95
+ if (!existing)
96
+ return null;
97
+ if (existing.status !== 'draft') {
98
+ throw new Error(`Cannot approve SOP with status '${existing.status}'. Only draft SOPs can be approved.`);
99
+ }
100
+ const now = new Date().toISOString();
101
+ const updated = {
102
+ ...existing,
103
+ status: 'approved',
104
+ approved_by: approver,
105
+ approved_at: now,
106
+ updated_at: now,
107
+ };
108
+ const embeddingText = this.buildEmbeddingText(updated);
109
+ const vector = await this.embeddings.embed(embeddingText);
110
+ await this.qdrant.upsertOne(SOP_COLLECTION, id, vector, {
111
+ type: 'sop',
112
+ ...this.sopToPayload(updated),
113
+ });
114
+ return updated;
115
+ }
116
+ async deprecate(id, deprecator) {
117
+ const existing = await this.get(id);
118
+ if (!existing)
119
+ return null;
120
+ const now = new Date().toISOString();
121
+ const updated = {
122
+ ...existing,
123
+ status: 'deprecated',
124
+ deprecated_by: deprecator,
125
+ deprecated_at: now,
126
+ updated_at: now,
127
+ };
128
+ const embeddingText = this.buildEmbeddingText(updated);
129
+ const vector = await this.embeddings.embed(embeddingText);
130
+ await this.qdrant.upsertOne(SOP_COLLECTION, id, vector, {
131
+ type: 'sop',
132
+ ...this.sopToPayload(updated),
133
+ });
134
+ return updated;
135
+ }
136
+ async delete(id) {
137
+ await this.qdrant.deletePoints(SOP_COLLECTION, [id]);
138
+ }
139
+ async list(options = {}) {
140
+ const limit = options.limit || 50;
141
+ const mustConditions = [
142
+ { key: 'type', match: { value: 'sop' } }
143
+ ];
144
+ if (options.status) {
145
+ mustConditions.push({ key: 'status', match: { value: options.status } });
146
+ }
147
+ if (options.category) {
148
+ mustConditions.push({ key: 'category', match: { value: options.category } });
149
+ }
150
+ const response = await this.scrollPoints(SOP_COLLECTION, {
151
+ filter: { must: mustConditions },
152
+ limit,
153
+ with_payload: true,
154
+ });
155
+ return response
156
+ .map(p => this.payloadToSOP(p.payload))
157
+ .filter((sop) => sop !== null);
158
+ }
159
+ async search(query, options = {}) {
160
+ const limit = options.limit || 5;
161
+ const minScore = options.minScore || 0.5;
162
+ const vector = await this.embeddings.embed(query);
163
+ const mustConditions = [
164
+ { key: 'type', match: { value: 'sop' } }
165
+ ];
166
+ if (options.status) {
167
+ mustConditions.push({ key: 'status', match: { value: options.status } });
168
+ }
169
+ const results = await this.qdrant.search(SOP_COLLECTION, vector, limit, {
170
+ filter: { must: mustConditions },
171
+ scoreThreshold: minScore,
172
+ });
173
+ return results
174
+ .map(r => {
175
+ const sop = this.payloadToSOP(r.payload);
176
+ if (!sop)
177
+ return null;
178
+ return { sop, score: r.score };
179
+ })
180
+ .filter((r) => r !== null);
181
+ }
182
+ async findByTrigger(trigger, options = {}) {
183
+ const results = await this.search(trigger, {
184
+ limit: 1,
185
+ status: options.status || 'approved',
186
+ minScore: options.minScore || 0.7,
187
+ });
188
+ return results[0] || null;
189
+ }
190
+ async getByCategory(category, status) {
191
+ return this.list({ category, status });
192
+ }
193
+ async getCategories() {
194
+ const sops = await this.list();
195
+ const categoryMap = new Map();
196
+ for (const sop of sops) {
197
+ const count = categoryMap.get(sop.category) || 0;
198
+ categoryMap.set(sop.category, count + 1);
199
+ }
200
+ return Array.from(categoryMap.entries())
201
+ .map(([category, count]) => ({ category, count }))
202
+ .sort((a, b) => b.count - a.count);
203
+ }
204
+ async stats() {
205
+ const sops = await this.list({ limit: 1000 });
206
+ const byStatus = {
207
+ draft: 0,
208
+ approved: 0,
209
+ deprecated: 0,
210
+ };
211
+ const byCategory = {};
212
+ for (const sop of sops) {
213
+ byStatus[sop.status]++;
214
+ byCategory[sop.category] = (byCategory[sop.category] || 0) + 1;
215
+ }
216
+ return {
217
+ total: sops.length,
218
+ byStatus,
219
+ byCategory,
220
+ };
221
+ }
222
+ buildEmbeddingText(sop) {
223
+ const stepsText = sop.steps
224
+ .map(s => `Step ${s.order}: ${s.action} - ${s.description}`)
225
+ .join('\n');
226
+ return `${sop.title}\n${sop.description}\nTrigger: ${sop.trigger}\nCategory: ${sop.category}\n${stepsText}`;
227
+ }
228
+ sopToPayload(sop) {
229
+ return {
230
+ id: sop.id,
231
+ title: sop.title,
232
+ description: sop.description,
233
+ trigger: sop.trigger,
234
+ category: sop.category,
235
+ steps: JSON.stringify(sop.steps),
236
+ source_tickets: sop.source_tickets,
237
+ status: sop.status,
238
+ tags: sop.tags,
239
+ created_at: sop.created_at,
240
+ updated_at: sop.updated_at,
241
+ approved_by: sop.approved_by || null,
242
+ approved_at: sop.approved_at || null,
243
+ deprecated_by: sop.deprecated_by || null,
244
+ deprecated_at: sop.deprecated_at || null,
245
+ version: sop.version,
246
+ confidence_score: sop.confidence_score || null,
247
+ };
248
+ }
249
+ payloadToSOP(payload) {
250
+ if (!payload || payload.type !== 'sop')
251
+ return null;
252
+ let steps = [];
253
+ try {
254
+ if (typeof payload.steps === 'string') {
255
+ steps = JSON.parse(payload.steps);
256
+ }
257
+ else if (Array.isArray(payload.steps)) {
258
+ steps = payload.steps;
259
+ }
260
+ }
261
+ catch {
262
+ steps = [];
263
+ }
264
+ return {
265
+ id: String(payload.id),
266
+ title: String(payload.title || ''),
267
+ description: String(payload.description || ''),
268
+ trigger: String(payload.trigger || ''),
269
+ category: String(payload.category || 'general'),
270
+ steps,
271
+ source_tickets: payload.source_tickets || [],
272
+ status: payload.status || 'draft',
273
+ tags: payload.tags || [],
274
+ created_at: String(payload.created_at || new Date().toISOString()),
275
+ updated_at: String(payload.updated_at || new Date().toISOString()),
276
+ approved_by: payload.approved_by ? String(payload.approved_by) : undefined,
277
+ approved_at: payload.approved_at ? String(payload.approved_at) : undefined,
278
+ deprecated_by: payload.deprecated_by ? String(payload.deprecated_by) : undefined,
279
+ deprecated_at: payload.deprecated_at ? String(payload.deprecated_at) : undefined,
280
+ version: Number(payload.version) || 1,
281
+ confidence_score: payload.confidence_score ? Number(payload.confidence_score) : undefined,
282
+ };
283
+ }
284
+ async scrollPoints(collection, options) {
285
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
+ const qdrantAny = this.qdrant;
287
+ try {
288
+ const response = await qdrantAny.request(`/collections/${collection}/points/scroll`, {
289
+ method: 'POST',
290
+ body: JSON.stringify({
291
+ filter: options.filter,
292
+ limit: options.limit || 50,
293
+ with_payload: options.with_payload ?? true,
294
+ }),
295
+ });
296
+ return response.result.points.map((p) => ({
297
+ id: p.id,
298
+ payload: p.payload || {},
299
+ }));
300
+ }
301
+ catch (error) {
302
+ console.error('Scroll failed:', error);
303
+ return [];
304
+ }
305
+ }
306
+ }
307
+ export default SOPService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simonfestl/husky-cli",
3
- "version": "1.6.1",
3
+ "version": "1.6.3",
4
4
  "description": "CLI for Huskyv0 Task Orchestration with Claude Agent SDK",
5
5
  "type": "module",
6
6
  "bin": {