@forumviriumhelsinki/podio-mcp 2.7.0 → 2.7.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.
@@ -7,7 +7,30 @@
7
7
  import type { PodioApiClient } from '../api/podio-api-client.js';
8
8
  import type { FieldMapper } from '../fields/field-mapper.js';
9
9
  import type { CacheManager } from '../cache/cache-manager.js';
10
+ import type { ProjectEpicService } from './project-epic-service.js';
10
11
  import type { PodioItem, AppCoordinates, PodioItemRevision, PodioItemRevisionDiff } from '../types/index.js';
12
+ /**
13
+ * Fields that can be written when creating or updating an item.
14
+ */
15
+ interface ItemWriteData {
16
+ title?: string;
17
+ description?: string;
18
+ status?: string;
19
+ responsible?: string;
20
+ project?: string;
21
+ epic?: string;
22
+ }
23
+ /**
24
+ * Context needed to resolve reference fields (project/epic/responsible).
25
+ *
26
+ * `appId` scopes the project/epic caches; `spaceId` scopes (and, when cold,
27
+ * populates) the space-members cache used for `responsible`.
28
+ */
29
+ export interface ItemWriteContext {
30
+ appId?: number;
31
+ spaceId?: number;
32
+ coordinates?: AppCoordinates;
33
+ }
11
34
  /**
12
35
  * Service class for handling item operations.
13
36
  *
@@ -17,7 +40,8 @@ import type { PodioItem, AppCoordinates, PodioItemRevision, PodioItemRevisionDif
17
40
  export declare class ItemService {
18
41
  private readonly apiClient;
19
42
  private readonly cacheManager;
20
- constructor(apiClient: PodioApiClient, cacheManager: CacheManager);
43
+ private readonly projectEpicService;
44
+ constructor(apiClient: PodioApiClient, cacheManager: CacheManager, projectEpicService: ProjectEpicService);
21
45
  /**
22
46
  * List items with optional filtering
23
47
  */
@@ -30,58 +54,55 @@ export declare class ItemService {
30
54
  filteredItems: PodioItem[];
31
55
  }>;
32
56
  /**
33
- * Create a new item
57
+ * Create a new item.
58
+ *
59
+ * Reference fields (`responsible`, `project`, `epic`) are resolved before the
60
+ * item is created and an unresolvable value throws, so a create either sets
61
+ * every field it was given or fails loudly — it never reports success with a
62
+ * silently dropped field (issues #89, #142).
34
63
  */
35
- createItem(appId: number, fieldMapper: FieldMapper, itemData: {
36
- title?: string;
37
- description?: string;
38
- status?: string;
39
- responsible?: string;
40
- project?: string;
41
- epic?: string;
42
- }, coordinates?: AppCoordinates): Promise<PodioItem>;
64
+ createItem(appId: number, fieldMapper: FieldMapper, itemData: ItemWriteData, context?: ItemWriteContext): Promise<PodioItem>;
43
65
  /**
44
66
  * Apply title/description/status text and category fields to the payload.
45
67
  * Used by both createItem and updateItem.
46
68
  */
47
69
  private applyBasicFields;
48
70
  /**
49
- * Resolve and add the responsible user for createItem.
50
- *
51
- * Throws when the contact cannot be resolved so the caller learns the
52
- * assignment failed instead of getting a successful create with the field
53
- * silently dropped (issue #89). Mirrors {@link applyResponsibleForUpdate}.
71
+ * Update an existing item
54
72
  */
55
- private applyResponsibleForCreate;
73
+ updateItem(itemId: number, fieldMapper: FieldMapper, updateData: ItemWriteData, context?: ItemWriteContext): Promise<void>;
56
74
  /**
57
- * Resolve and add a project/epic reference for createItem (warn on miss).
75
+ * Resolve and add the responsible contact (throws on miss).
76
+ *
77
+ * Shared by create and update: both must fail loudly rather than write an
78
+ * item with the assignee dropped. Returns true if the field was added.
58
79
  */
59
- private applyReferenceForCreate;
80
+ private applyResponsible;
60
81
  /**
61
- * Update an existing item
82
+ * Resolve and add a project/epic reference (throws on miss).
83
+ *
84
+ * Shared by create and update. Previously createItem only logged a warning
85
+ * here, so a create reported success while silently dropping the reference
86
+ * (issue #142). Returns true if the field was added.
62
87
  */
63
- updateItem(itemId: number, fieldMapper: FieldMapper, updateData: {
64
- title?: string;
65
- description?: string;
66
- status?: string;
67
- responsible?: string;
68
- project?: string;
69
- epic?: string;
70
- }, appId?: number, coordinates?: AppCoordinates): Promise<void>;
88
+ private applyReference;
71
89
  /**
72
- * Resolve and add the responsible user for updateItem (throws on miss).
73
- * Returns true if the field was added.
90
+ * Build the "could not be found" message for project/epic resolution
91
+ * failures, with fuzzy-ranked near misses as a hint.
92
+ *
93
+ * The fuzzy matcher is only trusted this far: to suggest, never to decide.
74
94
  */
75
- private applyResponsibleForUpdate;
95
+ private referenceNotFoundMessage;
76
96
  /**
77
- * Resolve and add a project/epic reference for updateItem (throws on miss).
78
- * Returns true if the field was added.
97
+ * Build the "could not be resolved" message for a responsible lookup, with
98
+ * the closest member name as a hint when one exists.
79
99
  */
80
- private applyReferenceForUpdate;
100
+ private userNotFoundMessage;
81
101
  /**
82
- * Build the "could not be found" error message for project/epic resolution failures.
102
+ * Throw the "ambiguous" validation error for a field whose value matched
103
+ * several records.
83
104
  */
84
- private referenceNotFoundMessage;
105
+ private ambiguousMatch;
85
106
  /**
86
107
  * Delete an item
87
108
  */
@@ -119,12 +140,36 @@ export declare class ItemService {
119
140
  */
120
141
  getItemRevisionDiff(itemId: number, fromRevision: number, toRevision: number): Promise<PodioItemRevisionDiff>;
121
142
  /**
122
- * Resolve user by name or email to user ID
143
+ * Look up a space member by numeric ID first (user_id, then profile_id),
144
+ * then by exact-or-unique name/email.
145
+ *
146
+ * Accepts the numeric ID printed by `list_space_members` (which is the
147
+ * `user_id`) as well as a `profile_id`, a name, or an email. Matching is
148
+ * strict — see {@link matchByLabels} for why a near miss must not silently
149
+ * pick a different colleague.
150
+ *
151
+ * @throws PodioValidationError when the value matches several members.
123
152
  */
124
- private resolveUser;
153
+ private findMember;
125
154
  /**
126
- * Resolve project or epic by name to item ID
127
- * This method ensures the cache is populated before searching
155
+ * Fetch and cache the space's members when nothing is cached for that space.
156
+ *
157
+ * Failures are logged and swallowed: the caller then reports an unresolved
158
+ * user, which is a clearer error than an API stack trace.
159
+ */
160
+ private ensureSpaceMembersCached;
161
+ /**
162
+ * Resolve a project or epic to the referenced item's ID.
163
+ *
164
+ * Accepts either the exact title (or an unambiguous substring of it) or the
165
+ * numeric item ID printed by `list_projects` / `list_epics`. The ID is
166
+ * checked first for numeric input so a value the server emits is always a
167
+ * value it accepts, while a project whose title *is* digits still resolves
168
+ * by title.
169
+ *
170
+ * Populates the reference cache on demand when it is cold.
171
+ *
172
+ * @throws PodioValidationError when the value matches several records.
128
173
  */
129
174
  private resolveProjectEpic;
130
175
  /**
@@ -136,10 +181,21 @@ export declare class ItemService {
136
181
  */
137
182
  private findCachedReferencesByTitle;
138
183
  /**
139
- * Populate the project/epic cache for an app by fetching items from the referenced app.
140
- * Returns silently when the field is missing, not an app reference, or has no referenced apps.
141
- * Logs a warning and continues if the API call fails (preserves prior behavior).
184
+ * Populate the project/epic cache for an app by fetching items from the
185
+ * referenced app.
186
+ *
187
+ * Delegates to {@link ProjectEpicService}, which is the single implementation
188
+ * of "find the referenced app and fetch its items". ItemService used to carry
189
+ * its own copy that read `field.config.referenced_apps` — a key the
190
+ * `/app/{id}` response does not have (it nests the reference under
191
+ * `config.settings`), so the cache never populated and every project/epic
192
+ * assignment failed while `list_projects` worked (issue #142). The duplicate
193
+ * also fetched a different number of items and extracted titles differently.
194
+ *
195
+ * Logs a warning and continues if the fetch fails; the caller then reports an
196
+ * unresolved reference.
142
197
  */
143
198
  private populateReferenceCache;
144
199
  }
200
+ export {};
145
201
  //# sourceMappingURL=item-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"item-service.d.ts","sourceRoot":"","sources":["../../src/services/item-service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EACV,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,mBAAmB,CAAC;AAG3B;;;;;GAKG;AACH,qBAAa,WAAW;IAEpB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,YAAY;gBADZ,SAAS,EAAE,cAAc,EACzB,YAAY,EAAE,YAAY;I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d,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,UAAU,EAAE,aAAa,EACzB,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC;IAoChB;;;;;OAKG;YACW,gBAAgB;IAgC9B;;;;;;OAMG;YACW,cAAc;IAoB5B;;;;;OAKG;YACW,wBAAwB;IAqBtC;;;OAGG;YACW,mBAAmB;IAajC;;;OAGG;IACH,OAAO,CAAC,cAAc;IAStB;;OAEG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/C;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAIjD;;OAEG;IACG,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAQ9E;;;;;OAKG;IACG,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAYnE;;;;;;OAMG;IACG,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAgBrF;;;;;;;OAOG;IACG,mBAAmB,CACvB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,qBAAqB,CAAC;IAgCjC;;;;;;;;;;OAUG;YACW,UAAU;IAoCxB;;;;;OAKG;YACW,wBAAwB;IActC;;;;;;;;;;;;OAYG;YACW,kBAAkB;IAiChC;;OAEG;YACW,mBAAmB;IASjC;;OAEG;YACW,2BAA2B;IAUzC;;;;;;;;;;;;;;OAcG;YACW,sBAAsB;CAmBrC"}
@@ -5,6 +5,65 @@
5
5
  * field payload building, and data transformation.
6
6
  */
7
7
  import { PodioValidationError, PodioErrorFactory, isPodioApiError } from '../errors/index.js';
8
+ import { debug } from '../utils/debug.js';
9
+ /**
10
+ * Parse a caller-supplied reference as a bare numeric ID.
11
+ *
12
+ * `list_projects` / `list_epics` / `list_space_members` all print numeric IDs,
13
+ * so those IDs must be accepted as input. Returns `null` for anything that is
14
+ * not purely digits, which keeps a project literally named "2024" resolvable by
15
+ * title.
16
+ */
17
+ function parseNumericId(value) {
18
+ const trimmed = value.trim();
19
+ return /^\d+$/.test(trimmed) ? Number(trimmed) : null;
20
+ }
21
+ /**
22
+ * Match a query against records by exact label, then by *unique* substring.
23
+ *
24
+ * Deliberately strict. The caches also expose a Levenshtein-based fuzzy search
25
+ * (min score 0.3), which is fine for ranking suggestions but catastrophic as a
26
+ * write path: measured against the live workspace it resolved "Definitely Not
27
+ * A Project" to "The Six City Strategy Coordination Project", the epic name
28
+ * "Gateway API Migration" to the unrelated project "Climate KIC /
29
+ * Demonstrator", and the misremembered person "Sami Salminen" to a *different
30
+ * real colleague*, "Aki Salminen". Silently linking the wrong record is worse
31
+ * than the dropped field this whole change set exists to fix, so resolution
32
+ * only ever accepts an unambiguous match and fuzzy scoring is demoted to
33
+ * generating "did you mean" hints.
34
+ */
35
+ function matchByLabels(records, query, labelsOf) {
36
+ const needle = query.trim().toLowerCase();
37
+ if (!needle) {
38
+ return { kind: 'none' };
39
+ }
40
+ const labels = (record) => labelsOf(record)
41
+ .filter((label) => Boolean(label))
42
+ .map((label) => label.trim().toLowerCase());
43
+ const exact = records.filter((record) => labels(record).includes(needle));
44
+ if (exact.length === 1) {
45
+ return { kind: 'match', record: exact[0] };
46
+ }
47
+ // Two records sharing a label is a coin flip, not a match — say so and let
48
+ // the caller disambiguate with a numeric ID.
49
+ if (exact.length > 1) {
50
+ return { kind: 'ambiguous', records: exact };
51
+ }
52
+ const partial = records.filter((record) => labels(record).some((l) => l.includes(needle)));
53
+ if (partial.length === 1) {
54
+ return { kind: 'match', record: partial[0] };
55
+ }
56
+ if (partial.length > 1) {
57
+ return { kind: 'ambiguous', records: partial };
58
+ }
59
+ return { kind: 'none' };
60
+ }
61
+ /** Render up to `limit` candidate labels for an error message. */
62
+ function formatCandidates(labels, limit = 5) {
63
+ const shown = labels.slice(0, limit).map((label) => `"${label}"`);
64
+ const rest = labels.length - shown.length;
65
+ return rest > 0 ? `${shown.join(', ')} (+${rest} more)` : shown.join(', ');
66
+ }
8
67
  /**
9
68
  * Service class for handling item operations.
10
69
  *
@@ -14,9 +73,11 @@ import { PodioValidationError, PodioErrorFactory, isPodioApiError } from '../err
14
73
  export class ItemService {
15
74
  apiClient;
16
75
  cacheManager;
17
- constructor(apiClient, cacheManager) {
76
+ projectEpicService;
77
+ constructor(apiClient, cacheManager, projectEpicService) {
18
78
  this.apiClient = apiClient;
19
79
  this.cacheManager = cacheManager;
80
+ this.projectEpicService = projectEpicService;
20
81
  }
21
82
  /**
22
83
  * List items with optional filtering
@@ -60,20 +121,26 @@ export class ItemService {
60
121
  }
61
122
  }
62
123
  /**
63
- * Create a new item
124
+ * Create a new item.
125
+ *
126
+ * Reference fields (`responsible`, `project`, `epic`) are resolved before the
127
+ * item is created and an unresolvable value throws, so a create either sets
128
+ * every field it was given or fails loudly — it never reports success with a
129
+ * silently dropped field (issues #89, #142).
64
130
  */
65
- async createItem(appId, fieldMapper, itemData, coordinates) {
131
+ async createItem(appId, fieldMapper, itemData, context = {}) {
132
+ const writeContext = { ...context, appId };
66
133
  try {
67
134
  const payload = fieldMapper.createPayload();
68
135
  this.applyBasicFields(payload, fieldMapper, itemData);
69
- await this.applyResponsibleForCreate(payload, fieldMapper, itemData.responsible);
70
- await this.applyReferenceForCreate(payload, fieldMapper, 'project', itemData.project, appId);
71
- await this.applyReferenceForCreate(payload, fieldMapper, 'epic', itemData.epic, appId);
136
+ await this.applyResponsible(payload, fieldMapper, itemData.responsible, writeContext);
137
+ await this.applyReference(payload, fieldMapper, 'project', itemData.project, writeContext);
138
+ await this.applyReference(payload, fieldMapper, 'epic', itemData.epic, writeContext);
72
139
  return await this.apiClient.createItem(appId, payload);
73
140
  }
74
141
  catch (error) {
75
- if (isPodioApiError(error) && coordinates) {
76
- await this.cacheManager.handleApiErrorWithCacheRefresh(error, coordinates, 'create item');
142
+ if (isPodioApiError(error) && writeContext.coordinates) {
143
+ await this.cacheManager.handleApiErrorWithCacheRefresh(error, writeContext.coordinates, 'create item');
77
144
  }
78
145
  throw error;
79
146
  }
@@ -98,98 +165,114 @@ export class ItemService {
98
165
  }
99
166
  return touched;
100
167
  }
101
- /**
102
- * Resolve and add the responsible user for createItem.
103
- *
104
- * Throws when the contact cannot be resolved so the caller learns the
105
- * assignment failed instead of getting a successful create with the field
106
- * silently dropped (issue #89). Mirrors {@link applyResponsibleForUpdate}.
107
- */
108
- async applyResponsibleForCreate(payload, fieldMapper, responsible) {
109
- if (!responsible)
110
- return;
111
- const userId = await this.resolveUser(responsible);
112
- if (!userId) {
113
- throw PodioValidationError.invalidFieldValue('responsible', responsible, `User '${responsible}' could not be resolved. Verify the username or email exists in Podio.`);
114
- }
115
- fieldMapper.addContactField(payload, 'responsible', userId, { validateField: false });
116
- }
117
- /**
118
- * Resolve and add a project/epic reference for createItem (warn on miss).
119
- */
120
- async applyReferenceForCreate(payload, fieldMapper, type, name, appId) {
121
- if (!name)
122
- return;
123
- const referenceId = await this.resolveProjectEpic(type, name, appId, fieldMapper);
124
- if (referenceId) {
125
- fieldMapper.addAppReferenceField(payload, type, referenceId, { validateField: false });
126
- }
127
- else {
128
- console.warn(`[ItemService] Warning: Could not find ${type} "${name}" in referenced app`);
129
- }
130
- }
131
168
  /**
132
169
  * Update an existing item
133
170
  */
134
- async updateItem(itemId, fieldMapper, updateData, appId, coordinates) {
171
+ async updateItem(itemId, fieldMapper, updateData, context = {}) {
135
172
  try {
136
173
  const payload = fieldMapper.createPayload();
137
174
  let hasUpdates = this.applyBasicFields(payload, fieldMapper, updateData);
138
175
  hasUpdates =
139
- (await this.applyResponsibleForUpdate(payload, fieldMapper, updateData.responsible)) ||
176
+ (await this.applyResponsible(payload, fieldMapper, updateData.responsible, context)) ||
140
177
  hasUpdates;
141
178
  hasUpdates =
142
- (await this.applyReferenceForUpdate(payload, fieldMapper, 'project', updateData.project, appId)) || hasUpdates;
179
+ (await this.applyReference(payload, fieldMapper, 'project', updateData.project, context)) ||
180
+ hasUpdates;
143
181
  hasUpdates =
144
- (await this.applyReferenceForUpdate(payload, fieldMapper, 'epic', updateData.epic, appId)) || hasUpdates;
182
+ (await this.applyReference(payload, fieldMapper, 'epic', updateData.epic, context)) ||
183
+ hasUpdates;
145
184
  if (!hasUpdates) {
146
185
  throw PodioValidationError.invalidFieldValue('No fields', 'provided for update', 'At least one field must be provided');
147
186
  }
148
187
  await this.apiClient.updateItem(itemId, payload);
149
188
  }
150
189
  catch (error) {
151
- if (isPodioApiError(error) && coordinates) {
152
- await this.cacheManager.handleApiErrorWithCacheRefresh(error, coordinates, 'update item');
190
+ if (isPodioApiError(error) && context.coordinates) {
191
+ await this.cacheManager.handleApiErrorWithCacheRefresh(error, context.coordinates, 'update item');
153
192
  }
154
193
  throw error;
155
194
  }
156
195
  }
157
196
  /**
158
- * Resolve and add the responsible user for updateItem (throws on miss).
159
- * Returns true if the field was added.
197
+ * Resolve and add the responsible contact (throws on miss).
198
+ *
199
+ * Shared by create and update: both must fail loudly rather than write an
200
+ * item with the assignee dropped. Returns true if the field was added.
160
201
  */
161
- async applyResponsibleForUpdate(payload, fieldMapper, responsible) {
202
+ async applyResponsible(payload, fieldMapper, responsible, context) {
162
203
  if (!responsible)
163
204
  return false;
164
- const userId = await this.resolveUser(responsible);
165
- if (!userId) {
166
- throw PodioValidationError.invalidFieldValue('responsible', responsible, `User '${responsible}' could not be resolved. Verify the username or email exists in Podio.`);
205
+ const member = await this.findMember(responsible, context.spaceId);
206
+ if (!member) {
207
+ throw PodioValidationError.invalidFieldValue('responsible', responsible, await this.userNotFoundMessage(responsible, context.spaceId));
208
+ }
209
+ // Deliberately no `?? user_id` fallback: Podio contact fields take a
210
+ // profile ID, and a user ID there references an unrelated profile.
211
+ const profileId = member.user.profile_id;
212
+ if (!profileId) {
213
+ throw PodioValidationError.invalidFieldValue('responsible', responsible, `User '${responsible}' was found but has no contact profile ID, which Podio requires to assign a contact field. Re-run 'list_space_members' with refresh_cache=true to refetch the member.`);
167
214
  }
168
- fieldMapper.addContactField(payload, 'responsible', userId, { validateField: false });
215
+ fieldMapper.addContactField(payload, 'responsible', profileId, { validateField: false });
169
216
  return true;
170
217
  }
171
218
  /**
172
- * Resolve and add a project/epic reference for updateItem (throws on miss).
173
- * Returns true if the field was added.
219
+ * Resolve and add a project/epic reference (throws on miss).
220
+ *
221
+ * Shared by create and update. Previously createItem only logged a warning
222
+ * here, so a create reported success while silently dropping the reference
223
+ * (issue #142). Returns true if the field was added.
174
224
  */
175
- async applyReferenceForUpdate(payload, fieldMapper, type, name, appId) {
225
+ async applyReference(payload, fieldMapper, type, name, context) {
176
226
  if (!name)
177
227
  return false;
178
- const referenceId = await this.resolveProjectEpic(type, name, appId, fieldMapper);
228
+ const referenceId = await this.resolveProjectEpic(type, name, context.appId, fieldMapper);
179
229
  if (!referenceId) {
180
- throw PodioValidationError.invalidFieldValue(type, name, this.referenceNotFoundMessage(type, name));
230
+ throw PodioValidationError.invalidFieldValue(type, name, await this.referenceNotFoundMessage(type, name, context.appId));
181
231
  }
182
232
  fieldMapper.addAppReferenceField(payload, type, referenceId, { validateField: false });
183
233
  return true;
184
234
  }
185
235
  /**
186
- * Build the "could not be found" error message for project/epic resolution failures.
236
+ * Build the "could not be found" message for project/epic resolution
237
+ * failures, with fuzzy-ranked near misses as a hint.
238
+ *
239
+ * The fuzzy matcher is only trusted this far: to suggest, never to decide.
187
240
  */
188
- referenceNotFoundMessage(type, name) {
189
- if (type === 'project') {
190
- return `Project '${name}' could not be found. Use 'list_projects' to see available projects or ensure the project cache is populated.`;
241
+ async referenceNotFoundMessage(type, name, appId) {
242
+ const listTool = type === 'project' ? 'list_projects' : 'list_epics';
243
+ const label = type === 'project' ? 'Project' : 'Epic';
244
+ let message = `${label} '${name}' could not be found. Pass the exact ${type} title or the numeric ID ` +
245
+ `shown by '${listTool}'; run '${listTool}' with refresh_cache=true if the ${type} was ` +
246
+ 'added recently.';
247
+ if (appId) {
248
+ const near = await this.findCachedReferencesByTitle(type, name, appId);
249
+ if (near.length > 0) {
250
+ message += ` Closest titles: ${formatCandidates(near.map((item) => item.title))}.`;
251
+ }
191
252
  }
192
- return `Epic '${name}' could not be found. Use 'list_epics' to see available epics or ensure the epic cache is populated.`;
253
+ return message;
254
+ }
255
+ /**
256
+ * Build the "could not be resolved" message for a responsible lookup, with
257
+ * the closest member name as a hint when one exists.
258
+ */
259
+ async userNotFoundMessage(responsible, spaceId) {
260
+ let message = `User '${responsible}' could not be resolved. Pass the exact name, the email, or the ` +
261
+ "numeric ID shown by 'list_space_members' (run it with refresh_cache=true if the member " +
262
+ 'joined recently).';
263
+ const near = await this.cacheManager.findUser(responsible, spaceId);
264
+ if (near) {
265
+ message += ` Closest member: "${near.member.user.name}".`;
266
+ }
267
+ return message;
268
+ }
269
+ /**
270
+ * Throw the "ambiguous" validation error for a field whose value matched
271
+ * several records.
272
+ */
273
+ ambiguousMatch(field, value, candidates, listTool) {
274
+ return PodioValidationError.invalidFieldValue(field, value, `'${value}' matches ${candidates.length} records: ${formatCandidates(candidates)}. ` +
275
+ `Pass the exact value or the numeric ID shown by '${listTool}'.`);
193
276
  }
194
277
  /**
195
278
  * Delete an item
@@ -282,28 +365,89 @@ export class ItemService {
282
365
  // HELPER METHODS
283
366
  // ===============================
284
367
  /**
285
- * Resolve user by name or email to user ID
368
+ * Look up a space member by numeric ID first (user_id, then profile_id),
369
+ * then by exact-or-unique name/email.
370
+ *
371
+ * Accepts the numeric ID printed by `list_space_members` (which is the
372
+ * `user_id`) as well as a `profile_id`, a name, or an email. Matching is
373
+ * strict — see {@link matchByLabels} for why a near miss must not silently
374
+ * pick a different colleague.
375
+ *
376
+ * @throws PodioValidationError when the value matches several members.
377
+ */
378
+ async findMember(nameOrEmail, spaceId) {
379
+ await this.ensureSpaceMembersCached(spaceId);
380
+ const members = spaceId ? await this.cacheManager.getSpaceMembers(spaceId) : [];
381
+ const numericId = parseNumericId(nameOrEmail);
382
+ if (numericId !== null) {
383
+ const byId = members.find((member) => member.user.user_id === numericId || member.user.profile_id === numericId);
384
+ if (byId) {
385
+ return byId;
386
+ }
387
+ const acrossSpaces = await this.cacheManager.findUserById(numericId, spaceId);
388
+ if (acrossSpaces) {
389
+ return acrossSpaces;
390
+ }
391
+ }
392
+ const result = matchByLabels(members, nameOrEmail, (member) => [
393
+ member.user.name,
394
+ member.user.mail,
395
+ ]);
396
+ if (result.kind === 'ambiguous') {
397
+ throw this.ambiguousMatch('responsible', nameOrEmail, result.records.map((member) => member.user.name), 'list_space_members');
398
+ }
399
+ return result.kind === 'match' ? result.record : undefined;
400
+ }
401
+ /**
402
+ * Fetch and cache the space's members when nothing is cached for that space.
403
+ *
404
+ * Failures are logged and swallowed: the caller then reports an unresolved
405
+ * user, which is a clearer error than an API stack trace.
286
406
  */
287
- async resolveUser(nameOrEmail) {
288
- // This would need access to space ID - we'll pass it through in a future refactor
289
- // For now, delegate to cache manager's method
290
- const user = await this.cacheManager.findUser(nameOrEmail);
291
- return user ? user.member.user.user_id : null;
407
+ async ensureSpaceMembersCached(spaceId) {
408
+ if (!spaceId || (await this.cacheManager.hasSpaceMembers(spaceId))) {
409
+ return;
410
+ }
411
+ try {
412
+ const members = await this.apiClient.getSpaceMembers(spaceId);
413
+ await this.cacheManager.setSpaceMembers(spaceId, members);
414
+ debug.info('ItemService', `Auto-populated ${members.length} members for space ${spaceId}`);
415
+ }
416
+ catch (error) {
417
+ debug.warn('ItemService', `Failed to fetch members for space ${spaceId}:`, error);
418
+ }
292
419
  }
293
420
  /**
294
- * Resolve project or epic by name to item ID
295
- * This method ensures the cache is populated before searching
421
+ * Resolve a project or epic to the referenced item's ID.
422
+ *
423
+ * Accepts either the exact title (or an unambiguous substring of it) or the
424
+ * numeric item ID printed by `list_projects` / `list_epics`. The ID is
425
+ * checked first for numeric input so a value the server emits is always a
426
+ * value it accepts, while a project whose title *is* digits still resolves
427
+ * by title.
428
+ *
429
+ * Populates the reference cache on demand when it is cold.
430
+ *
431
+ * @throws PodioValidationError when the value matches several records.
296
432
  */
297
- async resolveProjectEpic(type, name, appId, fieldMapper) {
433
+ async resolveProjectEpic(type, nameOrId, appId, fieldMapper) {
298
434
  if (!appId) {
299
435
  return null;
300
436
  }
301
- const cachedItems = await this.getCachedReferences(type, appId);
302
- if ((!cachedItems || cachedItems.length === 0) && fieldMapper) {
437
+ let cachedItems = await this.getCachedReferences(type, appId);
438
+ if (cachedItems.length === 0 && fieldMapper) {
303
439
  await this.populateReferenceCache(type, appId, fieldMapper);
440
+ cachedItems = await this.getCachedReferences(type, appId);
441
+ }
442
+ const numericId = parseNumericId(nameOrId);
443
+ if (numericId !== null && cachedItems.some((item) => item.item_id === numericId)) {
444
+ return numericId;
304
445
  }
305
- const items = await this.findCachedReferencesByTitle(type, name, appId);
306
- return items.length > 0 ? items[0].item_id : null;
446
+ const result = matchByLabels(cachedItems, nameOrId, (item) => [item.title]);
447
+ if (result.kind === 'ambiguous') {
448
+ throw this.ambiguousMatch(type, nameOrId, result.records.map((item) => item.title), type === 'project' ? 'list_projects' : 'list_epics');
449
+ }
450
+ return result.kind === 'match' ? result.record.item_id : null;
307
451
  }
308
452
  /**
309
453
  * Read cached project or epic references for the given app from the cache manager.
@@ -322,40 +466,29 @@ export class ItemService {
322
466
  : await this.cacheManager.findEpicsByTitle(name, appId);
323
467
  }
324
468
  /**
325
- * Populate the project/epic cache for an app by fetching items from the referenced app.
326
- * Returns silently when the field is missing, not an app reference, or has no referenced apps.
327
- * Logs a warning and continues if the API call fails (preserves prior behavior).
469
+ * Populate the project/epic cache for an app by fetching items from the
470
+ * referenced app.
471
+ *
472
+ * Delegates to {@link ProjectEpicService}, which is the single implementation
473
+ * of "find the referenced app and fetch its items". ItemService used to carry
474
+ * its own copy that read `field.config.referenced_apps` — a key the
475
+ * `/app/{id}` response does not have (it nests the reference under
476
+ * `config.settings`), so the cache never populated and every project/epic
477
+ * assignment failed while `list_projects` worked (issue #142). The duplicate
478
+ * also fetched a different number of items and extracted titles differently.
479
+ *
480
+ * Logs a warning and continues if the fetch fails; the caller then reports an
481
+ * unresolved reference.
328
482
  */
329
483
  async populateReferenceCache(type, appId, fieldMapper) {
330
- const field = fieldMapper.findField(type);
331
- if (!field || field.type !== 'app') {
332
- return;
333
- }
334
- const referencedApp = field.config?.referenced_apps?.[0];
335
- if (!referencedApp) {
336
- return;
337
- }
338
484
  try {
339
- const response = await this.apiClient.filterItems(referencedApp.app_id, {}, 100);
340
- const items = response.items.map((item) => ({
341
- item_id: item.item_id,
342
- title: fieldMapper.extractTitle(item),
343
- link: item.link,
344
- app: {
345
- app_id: referencedApp.app_id,
346
- name: `${type.charAt(0).toUpperCase() + type.slice(1)} App`,
347
- },
348
- }));
349
- if (type === 'project') {
350
- await this.cacheManager.setProjects(appId, items);
351
- }
352
- else {
353
- await this.cacheManager.setEpics(appId, items);
354
- }
355
- console.info(`[ItemService] Auto-populated ${type} cache with ${items.length} items from referenced app`);
485
+ const items = type === 'project'
486
+ ? await this.projectEpicService.listProjects(appId, fieldMapper, true)
487
+ : await this.projectEpicService.listEpics(appId, fieldMapper, true);
488
+ debug.info('ItemService', `Auto-populated ${type} cache with ${items.length} items from referenced app`);
356
489
  }
357
490
  catch (error) {
358
- console.warn(`[ItemService] Failed to fetch ${type}s from referenced app:`, error);
491
+ debug.warn('ItemService', `Failed to fetch ${type}s from referenced app:`, error);
359
492
  }
360
493
  }
361
494
  }