agentic-sdlc-mcp 1.3.1 → 1.5.0

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.
@@ -2,17 +2,34 @@
2
2
  * Tool: plan_from_context
3
3
  *
4
4
  * Handler extracted as `buildPlan` and `handlePlanFromContext` for testing.
5
+ *
6
+ * Supports `workType` (docs/feature/bugfix/refactor/security/release/infra):
7
+ * each type gets a distinct phase-by-phase template rather than one
8
+ * one-size-fits-all plan -- a docs-only task should not default to requiring
9
+ * code unit tests, while a bugfix task must always include repro + regression
10
+ * tests. When the caller does not pass `workType` explicitly, it is inferred
11
+ * from `goal` + `acceptanceCriteria` via a conservative keyword heuristic
12
+ * (see `inferWorkType`), and the inference itself (confidence, reasoning,
13
+ * whether clarification is needed) is surfaced in the output rather than
14
+ * hidden -- callers should not have to trust a silent guess.
5
15
  */
6
16
  import { z } from "zod";
7
- import { resolveRepo, handleGitHubError } from "../github/client.js";
17
+ import { resolveRepo, getOctokit, paginateAll, handleGitHubError } from "../github/client.js";
8
18
  import { fetchRepoContext } from "../github/context.js";
9
19
  // ---------------------------------------------------------------------------
10
20
  // Schema
11
21
  // ---------------------------------------------------------------------------
22
+ const WORK_TYPES = ["docs", "feature", "bugfix", "refactor", "security", "release", "infra"];
12
23
  export const PlanFromContextInputSchema = z.object({
13
24
  goal: z.string().min(5).describe("The user goal or feature request to plan around."),
14
25
  owner: z.string().optional().describe("GitHub owner. Falls back to GITHUB_OWNER."),
15
26
  repo: z.string().optional().describe("GitHub repo. Falls back to GITHUB_REPO."),
27
+ workType: z
28
+ .enum(WORK_TYPES)
29
+ .optional()
30
+ .describe("Explicit task category: docs, feature, bugfix, refactor, security, release, or infra. " +
31
+ "If omitted, it is inferred from `goal` + `acceptanceCriteria` -- check the output's " +
32
+ "`confidence` and `needsClarification` fields rather than assuming the guess is correct."),
16
33
  constraints: z.array(z.string()).optional()
17
34
  .describe("Technical or business constraints."),
18
35
  acceptanceCriteria: z.array(z.string()).optional()
@@ -21,11 +38,24 @@ export const PlanFromContextInputSchema = z.object({
21
38
  // ---------------------------------------------------------------------------
22
39
  // Output schema
23
40
  // ---------------------------------------------------------------------------
41
+ const IssueDraftShape = z.object({
42
+ title: z.string(),
43
+ body: z.string(),
44
+ labels: z.array(z.string()),
45
+ phase: z.string(),
46
+ acceptanceCriteria: z.array(z.string()),
47
+ riskLevel: z.enum(["low", "medium", "high"]),
48
+ goal: z.string(),
49
+ });
24
50
  export const PlanFromContextOutputSchema = {
25
51
  goal: z.string(),
26
52
  repo: z.string(),
27
53
  defaultBranch: z.string(),
28
54
  language: z.string().nullable(),
55
+ workType: z.enum(WORK_TYPES),
56
+ confidence: z.enum(["high", "medium", "low"]),
57
+ reasoning: z.string(),
58
+ needsClarification: z.boolean(),
29
59
  constraints: z.array(z.string()),
30
60
  acceptanceCriteria: z.array(z.string()),
31
61
  phases: z.array(z.object({
@@ -34,87 +64,667 @@ export const PlanFromContextOutputSchema = {
34
64
  tasks: z.array(z.string()),
35
65
  })),
36
66
  suggestedIssues: z.array(z.string()),
67
+ issueDrafts: z.array(IssueDraftShape),
37
68
  risks: z.array(z.string()),
38
69
  };
39
70
  // ---------------------------------------------------------------------------
40
- // Phase templates (pure data)
71
+ // workType inference (pure, exported for testing)
41
72
  // ---------------------------------------------------------------------------
42
- const PHASE_TEMPLATES = {
43
- plan: {
44
- tasks: [
45
- "Clarify requirements and acceptance criteria",
46
- "Identify affected components and files",
47
- "Define API contracts or data model changes",
48
- "Review existing tests and coverage",
49
- "List risks and unknowns",
50
- ],
73
+ /**
74
+ * Keyword signals per non-`feature` work type, English + Chinese (this project
75
+ * ships bilingual docs, and goals are often phrased in either language). `feature`
76
+ * has no keyword list -- it is the fallback when no other category matches,
77
+ * since "add"/"implement"-style phrasing is too generic to score reliably.
78
+ *
79
+ * English entries are matched as whole words/phrases (see `hasWholeWordMatch`),
80
+ * so common inflections ("fix" -> "fixes"/"fixed", "permission" -> "permissions")
81
+ * are listed explicitly rather than relying on a bare stem match, which would
82
+ * also match unrelated words like "prefix" or "fixed-price".
83
+ */
84
+ const WORK_TYPE_KEYWORDS = {
85
+ docs: ["document", "documents", "documentation", "docs", "readme", "guide", "文档", "说明文档", "教程", "指南"],
86
+ bugfix: [
87
+ "bugfix",
88
+ "bug",
89
+ "bugs",
90
+ "fix",
91
+ "fixes",
92
+ "broken",
93
+ "regression",
94
+ "crash",
95
+ "crashes",
96
+ "not working",
97
+ "修复",
98
+ "缺陷",
99
+ "报错",
100
+ "崩溃",
101
+ "回归",
102
+ ],
103
+ refactor: ["refactor", "refactoring", "restructure", "cleanup", "simplify", "reorganize", "重构", "简化", "整理"],
104
+ security: [
105
+ "security",
106
+ "secure",
107
+ "vulnerable",
108
+ "vulnerability",
109
+ "vulnerabilities",
110
+ "secrets",
111
+ "secret leak",
112
+ "secret leakage",
113
+ "leaked secret",
114
+ "exposed secret",
115
+ "hardcoded secret",
116
+ "credential",
117
+ "credentials",
118
+ "permission",
119
+ "permissions",
120
+ "audit",
121
+ "exploit",
122
+ "cve",
123
+ "安全",
124
+ "漏洞",
125
+ "权限",
126
+ "密钥",
127
+ "审计",
128
+ ],
129
+ release: ["release", "changelog", "rollback", "发布", "版本", "回滚", "变更日志"],
130
+ infra: [
131
+ "workflow",
132
+ "workflows",
133
+ "pipeline",
134
+ "ci/cd",
135
+ "infrastructure",
136
+ "deploy",
137
+ "deployment",
138
+ "docker",
139
+ "terraform",
140
+ "github actions",
141
+ "工作流",
142
+ "基础设施",
143
+ "部署",
144
+ "流水线",
145
+ ],
146
+ };
147
+ /** Keywords made up entirely of CJK ideographs -- matched as a plain substring (see `hasWholeWordMatch`). */
148
+ const CJK_KEYWORD_PATTERN = /^[一-鿿]+$/;
149
+ /** Tie-break priority when multiple categories score equally (first wins), matching the ROADMAP's listed order. */
150
+ const WORK_TYPE_PRIORITY = [
151
+ "docs",
152
+ "bugfix",
153
+ "refactor",
154
+ "security",
155
+ "release",
156
+ "infra",
157
+ ];
158
+ /** Characters that count as "word-ish" for the purposes of an English word-boundary check. */
159
+ function isWordChar(ch) {
160
+ if (!ch)
161
+ return false;
162
+ return /[a-z0-9]/i.test(ch);
163
+ }
164
+ /**
165
+ * True if `keyword` occurs in `text` as a whole word/phrase -- i.e. not
166
+ * immediately preceded or followed by another word character. Plain
167
+ * `String.includes` would let short English keywords like "fix" or "secret"
168
+ * match inside unrelated words ("prefix", "fixed-price", "secret santa"),
169
+ * silently mis-categorising ordinary feature requests as bugfix/security.
170
+ *
171
+ * Pure-CJK keywords (e.g. "修复") are matched as a plain substring instead:
172
+ * Chinese text has no whitespace between words, so every character adjacent
173
+ * to a CJK match is itself a "word character" and a Latin-style boundary
174
+ * check would never succeed. Multi-character CJK keywords are specific
175
+ * enough on their own that substring matching does not meaningfully
176
+ * increase the false-positive rate here.
177
+ */
178
+ function hasWholeWordMatch(text, keyword) {
179
+ if (CJK_KEYWORD_PATTERN.test(keyword)) {
180
+ return text.includes(keyword);
181
+ }
182
+ let fromIndex = 0;
183
+ while (true) {
184
+ const idx = text.indexOf(keyword, fromIndex);
185
+ if (idx === -1)
186
+ return false;
187
+ const before = idx > 0 ? text[idx - 1] : undefined;
188
+ const after = idx + keyword.length < text.length ? text[idx + keyword.length] : undefined;
189
+ if (!isWordChar(before) && !isWordChar(after))
190
+ return true;
191
+ fromIndex = idx + 1;
192
+ }
193
+ }
194
+ function countKeywordMatches(text, keywords) {
195
+ return keywords.reduce((n, kw) => (hasWholeWordMatch(text, kw) ? n + 1 : n), 0);
196
+ }
197
+ /**
198
+ * Infer a `workType` from free-text goal + acceptance criteria when the caller
199
+ * did not pass one explicitly. Conservative by design: ties or zero signal
200
+ * fall back to `feature` with `needsClarification: true` rather than guessing
201
+ * confidently, so callers know to double-check rather than trust a silent
202
+ * default.
203
+ */
204
+ export function inferWorkType(goal, acceptanceCriteria, explicit) {
205
+ if (explicit) {
206
+ return {
207
+ workType: explicit,
208
+ confidence: "high",
209
+ reasoning: "workType was explicitly provided by the caller.",
210
+ needsClarification: false,
211
+ };
212
+ }
213
+ const text = [goal, ...acceptanceCriteria].join(" ").toLowerCase();
214
+ const scored = WORK_TYPE_PRIORITY.map((wt) => ({
215
+ workType: wt,
216
+ score: countKeywordMatches(text, WORK_TYPE_KEYWORDS[wt]),
217
+ }));
218
+ const maxScore = Math.max(...scored.map((s) => s.score));
219
+ if (maxScore === 0) {
220
+ return {
221
+ workType: "feature",
222
+ confidence: "low",
223
+ reasoning: "No docs/bugfix/refactor/security/release/infra keyword signals were found in the goal or " +
224
+ "acceptance criteria; defaulting to \"feature\". Pass `workType` explicitly if this is wrong.",
225
+ needsClarification: true,
226
+ };
227
+ }
228
+ const topMatches = scored.filter((s) => s.score === maxScore);
229
+ const picked = topMatches[0].workType;
230
+ if (topMatches.length > 1) {
231
+ return {
232
+ workType: picked,
233
+ confidence: "low",
234
+ reasoning: `Multiple work types matched with equal signal (${topMatches.map((m) => m.workType).join(", ")}); ` +
235
+ `defaulting to "${picked}". Pass \`workType\` explicitly to disambiguate.`,
236
+ needsClarification: true,
237
+ };
238
+ }
239
+ return {
240
+ workType: picked,
241
+ confidence: maxScore >= 2 ? "high" : "medium",
242
+ reasoning: `Matched ${maxScore} keyword(s) associated with "${picked}" in the goal/acceptance criteria.`,
243
+ needsClarification: false,
244
+ };
245
+ }
246
+ const PHASE_TEMPLATES_BY_WORK_TYPE = {
247
+ feature: {
248
+ plan: {
249
+ tasks: [
250
+ "Clarify requirements and acceptance criteria",
251
+ "Identify affected components and files",
252
+ "Define API contracts or data model changes",
253
+ "Review existing tests and coverage",
254
+ "List risks and unknowns",
255
+ ],
256
+ },
257
+ create: {
258
+ tasks: [
259
+ "Create a feature branch from the default branch",
260
+ "Implement the required changes",
261
+ "Add unit tests for new logic",
262
+ "Update inline documentation and comments",
263
+ ],
264
+ },
265
+ test: {
266
+ tasks: [
267
+ "Run the full test suite locally",
268
+ "Verify no regression in existing tests",
269
+ "Write integration tests if applicable",
270
+ "Test edge cases and error paths",
271
+ ],
272
+ },
273
+ review: {
274
+ tasks: [
275
+ "Create a pull request with a clear description",
276
+ "Self-review the diff for unintended changes",
277
+ "Request review from at least one team member",
278
+ "Address all review comments",
279
+ ],
280
+ },
281
+ optimize: {
282
+ tasks: [
283
+ "Profile the affected code path if performance-sensitive",
284
+ "Look for obvious algorithmic improvements",
285
+ "Ensure no unnecessary dependencies were added",
286
+ ],
287
+ },
288
+ secure: {
289
+ tasks: [
290
+ "Run Dependabot or dependency audit",
291
+ "Check for secret leakage in diffs",
292
+ "Verify input validation and error handling",
293
+ "Review access control changes if any",
294
+ ],
295
+ },
296
+ },
297
+ docs: {
298
+ plan: {
299
+ tasks: [
300
+ "Read existing README/docs and identify gaps",
301
+ "Clarify terminology and target audience",
302
+ "List acceptance criteria for the documentation change",
303
+ ],
304
+ },
305
+ create: {
306
+ tasks: [
307
+ "Write or update the documentation",
308
+ "Add or update examples",
309
+ "Check terminology consistency across docs",
310
+ ],
311
+ },
312
+ test: {
313
+ tasks: [
314
+ "Verify all code snippets and commands in the docs are runnable",
315
+ "Check for broken links and outdated references",
316
+ "Run a diff/lint check for formatting issues (e.g. `git diff --check`)",
317
+ ],
318
+ },
319
+ review: {
320
+ tasks: [
321
+ "Open a PR describing what changed and why",
322
+ "Self-review rendered markdown for formatting issues",
323
+ "Confirm no unrelated content changes were bundled in",
324
+ ],
325
+ },
326
+ optimize: {
327
+ tasks: ["Trim redundant sections", "Ensure consistent heading structure"],
328
+ },
329
+ secure: {
330
+ tasks: [
331
+ "Confirm no secrets, tokens, or credentials appear in the docs",
332
+ "Verify no internal-only URLs or private information are exposed",
333
+ ],
334
+ },
51
335
  },
52
- create: {
53
- tasks: [
54
- "Create a feature branch from the default branch",
55
- "Implement the required changes",
56
- "Add unit tests for new logic",
57
- "Update inline documentation and comments",
58
- ],
336
+ bugfix: {
337
+ plan: {
338
+ tasks: [
339
+ "Reproduce the bug reliably and document exact repro steps",
340
+ "Identify the root cause, not just the symptom",
341
+ "Determine blast radius: what else might be affected",
342
+ ],
343
+ },
344
+ create: {
345
+ tasks: [
346
+ "Implement the minimal fix for the root cause",
347
+ "Avoid unrelated refactors in the same change",
348
+ "Add a regression test that fails before the fix and passes after",
349
+ ],
350
+ },
351
+ test: {
352
+ tasks: [
353
+ "Run the new regression test plus the full existing suite",
354
+ "Verify the original repro steps no longer reproduce the bug",
355
+ "Check related edge cases the same root cause might affect",
356
+ ],
357
+ },
358
+ review: {
359
+ tasks: [
360
+ "Explain the root cause and fix approach in the PR description",
361
+ "Link the bug report / issue",
362
+ "Confirm the regression test is included in the diff",
363
+ ],
364
+ },
365
+ optimize: {
366
+ tasks: ["Confirm the fix does not introduce a performance regression"],
367
+ },
368
+ secure: {
369
+ tasks: [
370
+ "Confirm the bug was not itself a security issue (escalate if it was)",
371
+ "Check whether the same root cause exists elsewhere in the codebase",
372
+ ],
373
+ },
59
374
  },
60
- test: {
61
- tasks: [
62
- "Run the full test suite locally",
63
- "Verify no regression in existing tests",
64
- "Write integration tests if applicable",
65
- "Test edge cases and error paths",
66
- ],
375
+ refactor: {
376
+ plan: {
377
+ tasks: [
378
+ "Confirm current behaviour is fully covered by existing tests before changing anything",
379
+ "Define the target structure and why it is better",
380
+ "Confirm no public API / contract changes are intended",
381
+ ],
382
+ },
383
+ create: {
384
+ tasks: [
385
+ "Make the change in small, reviewable, incremental commits",
386
+ "Keep behaviour identical -- no functional changes bundled in",
387
+ ],
388
+ },
389
+ test: {
390
+ tasks: [
391
+ "Run the full existing test suite after every incremental commit",
392
+ "Add characterization tests first if coverage is insufficient",
393
+ "Confirm no observable behaviour changed",
394
+ ],
395
+ },
396
+ review: {
397
+ tasks: [
398
+ "Explain in the PR why the refactor is worth the risk",
399
+ "Highlight any public API surface touched, even if unchanged in behaviour",
400
+ "Call out anything intentionally left out of scope",
401
+ ],
402
+ },
403
+ optimize: {
404
+ tasks: ["Check whether the refactor incidentally improves or regresses performance"],
405
+ },
406
+ secure: {
407
+ tasks: ["Confirm no access-control or validation logic was silently altered"],
408
+ },
67
409
  },
68
- review: {
69
- tasks: [
70
- "Create a pull request with a clear description",
71
- "Self-review the diff for unintended changes",
72
- "Request review from at least one team member",
73
- "Address all review comments",
74
- ],
410
+ security: {
411
+ plan: {
412
+ tasks: [
413
+ "Define the threat model: what is being protected, from whom",
414
+ "Identify affected permissions, secrets, and trust boundaries",
415
+ "List the specific attack scenarios this change should close",
416
+ ],
417
+ },
418
+ create: {
419
+ tasks: [
420
+ "Implement the fix with least-privilege as the default",
421
+ "Avoid introducing new secrets or credentials in code or config",
422
+ "Add input validation at trust boundaries",
423
+ ],
424
+ },
425
+ test: {
426
+ tasks: [
427
+ "Add tests for the specific attack scenarios identified in Plan",
428
+ "Test both the vulnerable-input and legitimate-input paths",
429
+ "Run a dependency audit (npm audit or equivalent) for related packages",
430
+ ],
431
+ },
432
+ review: {
433
+ tasks: [
434
+ "Request a security-focused review, not just a functional one",
435
+ "Confirm no secrets or credentials appear in the diff",
436
+ "Document the before/after risk in the PR description",
437
+ ],
438
+ },
439
+ optimize: {
440
+ tasks: ["Confirm the fix does not degrade performance in a way that invites a new DoS vector"],
441
+ },
442
+ secure: {
443
+ tasks: [
444
+ "Re-run security_triage / workflow_permissions_audit as applicable",
445
+ "Confirm the fix is deployed with least-privilege permissions",
446
+ "Verify no other code path shares the same vulnerable pattern",
447
+ ],
448
+ },
75
449
  },
76
- optimize: {
77
- tasks: [
78
- "Profile the affected code path if performance-sensitive",
79
- "Look for obvious algorithmic improvements",
80
- "Ensure no unnecessary dependencies were added",
81
- ],
450
+ release: {
451
+ plan: {
452
+ tasks: [
453
+ "Confirm scope: what is included in this release and what is deferred",
454
+ "Identify breaking changes and required migration notes",
455
+ "Draft the version bump (semver) and rationale",
456
+ ],
457
+ },
458
+ create: {
459
+ tasks: [
460
+ "Update CHANGELOG.md with all notable changes",
461
+ "Bump the version in package.json / relevant manifests",
462
+ "Prepare a release notes draft",
463
+ ],
464
+ },
465
+ test: {
466
+ tasks: [
467
+ "Confirm CI is green on the release commit (quality_gate_status)",
468
+ "Run the full test suite and smoke test on the release artifact",
469
+ "Verify no open release-blocking issues remain",
470
+ ],
471
+ },
472
+ review: {
473
+ tasks: [
474
+ "Get release approval from the designated release manager",
475
+ "Confirm the rollback plan is documented and understood",
476
+ "Verify tag naming matches the project convention",
477
+ ],
478
+ },
479
+ optimize: {
480
+ tasks: ["Confirm no debug/dev-only code paths are enabled in the release build"],
481
+ },
482
+ secure: {
483
+ tasks: [
484
+ "Run security_triage for open critical/high alerts before tagging",
485
+ "Confirm no secrets are embedded in the release artifact",
486
+ "Document the rollback plan (release_readiness_check template)",
487
+ ],
488
+ },
82
489
  },
83
- secure: {
84
- tasks: [
85
- "Run Dependabot or dependency audit",
86
- "Check for secret leakage in diffs",
87
- "Verify input validation and error handling",
88
- "Review access control changes if any",
89
- ],
490
+ infra: {
491
+ plan: {
492
+ tasks: [
493
+ "Identify affected workflows, environments, and permissions",
494
+ "Define least-privilege target permissions for any token/credential involved",
495
+ "Plan a rollback path before making the change",
496
+ ],
497
+ },
498
+ create: {
499
+ tasks: [
500
+ "Implement the infra/workflow change with least-privilege permissions",
501
+ "Avoid `write-all` or overly broad scopes",
502
+ "Document any new environment variables or secrets required",
503
+ ],
504
+ },
505
+ test: {
506
+ tasks: [
507
+ "Test the workflow change on a branch/PR before merging to the default branch",
508
+ "Verify the change behaves correctly under both success and failure paths",
509
+ "Confirm no secrets are printed to logs",
510
+ ],
511
+ },
512
+ review: {
513
+ tasks: [
514
+ "Run workflow_permissions_audit on the changed workflow files",
515
+ "Explain the blast radius if this workflow is compromised or misconfigured",
516
+ "Confirm the rollback plan in the PR description",
517
+ ],
518
+ },
519
+ optimize: {
520
+ tasks: ["Confirm the change does not needlessly increase CI runtime or cost"],
521
+ },
522
+ secure: {
523
+ tasks: [
524
+ "Re-run workflow_permissions_audit after the change",
525
+ "Confirm `pull_request_target` is not combined with write permissions",
526
+ "Verify branch protection still enforces required checks after the change",
527
+ ],
528
+ },
90
529
  },
91
530
  };
531
+ /** Capitalise a single lower-case word (all SdlcPhase/bracket-tag values are single words). */
532
+ function capitalize(word) {
533
+ return word.charAt(0).toUpperCase() + word.slice(1);
534
+ }
535
+ const GITHUB_ISSUE_TITLE_MAX_CHARS = 256;
536
+ const ISSUE_TITLE_TRUNCATION_MARKER = "...(truncated)";
537
+ function boundIssueTitle(title) {
538
+ if (title.length <= GITHUB_ISSUE_TITLE_MAX_CHARS)
539
+ return title;
540
+ const prefixChars = GITHUB_ISSUE_TITLE_MAX_CHARS - ISSUE_TITLE_TRUNCATION_MARKER.length;
541
+ let prefix = title.slice(0, prefixChars);
542
+ const finalCodeUnit = prefix.charCodeAt(prefix.length - 1);
543
+ if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
544
+ prefix = prefix.slice(0, -1);
545
+ }
546
+ return prefix + ISSUE_TITLE_TRUNCATION_MARKER;
547
+ }
548
+ function buildIssueTitle(spec, goal) {
549
+ return boundIssueTitle(`[${capitalize(spec.phase)}] ${spec.action(goal)}`);
550
+ }
551
+ const ISSUE_SPECS_BY_WORK_TYPE = {
552
+ feature: [
553
+ { phase: "plan", action: (g) => `Define acceptance criteria and technical approach for: ${g}`, riskLevel: "low" },
554
+ { phase: "create", action: (g) => `Implement: ${g}`, riskLevel: "medium" },
555
+ { phase: "test", action: (g) => `Add tests for: ${g}`, riskLevel: "low" },
556
+ { phase: "secure", action: (g) => `Security review for: ${g}`, riskLevel: "medium" },
557
+ ],
558
+ docs: [
559
+ { phase: "plan", action: (g) => `Identify documentation gaps and audience for: ${g}`, riskLevel: "low" },
560
+ { phase: "create", action: (g) => `Write/update documentation for: ${g}`, riskLevel: "low" },
561
+ { phase: "test", action: (g) => `Verify examples and links for: ${g}`, riskLevel: "low" },
562
+ { phase: "review", action: (g) => `Proofread and confirm no sensitive info leaked for: ${g}`, riskLevel: "medium" },
563
+ ],
564
+ bugfix: [
565
+ { phase: "plan", action: (g) => `Reproduce and identify root cause for: ${g}`, riskLevel: "medium" },
566
+ { phase: "create", action: (g) => `Implement minimal fix for: ${g}`, riskLevel: "medium" },
567
+ { phase: "test", action: (g) => `Add regression test for: ${g}`, riskLevel: "low" },
568
+ { phase: "review", action: (g) => `Explain root cause and fix in the PR for: ${g}`, riskLevel: "low" },
569
+ ],
570
+ refactor: [
571
+ { phase: "plan", action: (g) => `Confirm existing test coverage before refactor: ${g}`, riskLevel: "medium" },
572
+ { phase: "create", action: (g) => `Refactor incrementally with no behaviour change: ${g}`, riskLevel: "medium" },
573
+ { phase: "test", action: (g) => `Confirm full suite passes after each commit: ${g}`, riskLevel: "low" },
574
+ { phase: "review", action: (g) => `Explain refactor rationale and API impact: ${g}`, riskLevel: "medium" },
575
+ ],
576
+ security: [
577
+ { phase: "plan", action: (g) => `Define threat model for: ${g}`, riskLevel: "high" },
578
+ { phase: "create", action: (g) => `Implement least-privilege fix for: ${g}`, riskLevel: "high" },
579
+ { phase: "test", action: (g) => `Add attack-scenario tests for: ${g}`, riskLevel: "high" },
580
+ { phase: "secure", action: (g) => `Security review and re-audit for: ${g}`, riskLevel: "high" },
581
+ ],
582
+ release: [
583
+ { phase: "plan", action: (g) => `Confirm release scope and breaking changes for: ${g}`, riskLevel: "medium" },
584
+ { phase: "create", action: (g) => `Update CHANGELOG and bump version for: ${g}`, riskLevel: "medium" },
585
+ { phase: "test", action: (g) => `Confirm CI green and smoke test for: ${g}`, riskLevel: "medium" },
586
+ { phase: "secure", action: (g) => `Run security triage before tagging: ${g}`, riskLevel: "high" },
587
+ ],
588
+ infra: [
589
+ { phase: "plan", action: (g) => `Identify affected workflows/permissions for: ${g}`, riskLevel: "medium" },
590
+ { phase: "create", action: (g) => `Implement least-privilege infra change for: ${g}`, riskLevel: "high" },
591
+ { phase: "test", action: (g) => `Test workflow on a branch before merge for: ${g}`, riskLevel: "medium" },
592
+ { phase: "review", action: (g) => `Run workflow_permissions_audit for: ${g}`, riskLevel: "high" },
593
+ ],
594
+ };
595
+ /**
596
+ * Candidate labels per workType -- conservative, generic names likely to
597
+ * exist on many repos (GitHub's own default label set covers docs/feature/
598
+ * bugfix; the rest are common but not universal conventions). These are
599
+ * never applied blindly: `buildIssueDrafts` intersects them against the
600
+ * target repo's *actual* labels, so a repo without a "security" label never
601
+ * gets one invented for it -- GitHub silently auto-creates unknown labels
602
+ * when an issue is created with them, which would otherwise pollute the
603
+ * repo's label list on a live (non-dry-run) `create_issue_set` call.
604
+ */
605
+ const CANDIDATE_LABELS_BY_WORK_TYPE = {
606
+ docs: ["documentation"],
607
+ feature: ["enhancement"],
608
+ bugfix: ["bug"],
609
+ refactor: ["enhancement"],
610
+ security: ["security"],
611
+ release: ["release"],
612
+ infra: ["infrastructure"],
613
+ };
614
+ /** Per-workType suggested issue titles. The `feature` case matches the pre-workType default wording. */
615
+ function buildSuggestedIssues(goal, workType) {
616
+ const specs = ISSUE_SPECS_BY_WORK_TYPE[workType] ?? ISSUE_SPECS_BY_WORK_TYPE.feature;
617
+ return specs.map((spec) => buildIssueTitle(spec, goal));
618
+ }
619
+ /**
620
+ * Build the body for a single issue draft: background (reusing the phase's
621
+ * own summary), a merged acceptance-criteria checklist (phase tasks plus
622
+ * caller-provided criteria), and a pointer to the full Definition of Done
623
+ * template rather than repeating all 7 of its sections in every draft.
624
+ */
625
+ function buildIssueDraftBody(phaseData, acceptanceCriteria) {
626
+ return [
627
+ "### Background",
628
+ phaseData.summary,
629
+ "",
630
+ "### Acceptance Criteria",
631
+ ...acceptanceCriteria.map((criterion) => `- [ ] ${criterion}`),
632
+ "",
633
+ "### Definition of Done",
634
+ "See `sdlc://templates/issue` for the full checklist this issue should satisfy before closing.",
635
+ ].join("\n");
636
+ }
637
+ /**
638
+ * Build structured issue drafts directly usable as `create_issue_set`'s
639
+ * `issues` input (the planning metadata is accepted but not sent to GitHub).
640
+ * One draft per `ISSUE_SPECS_BY_WORK_TYPE[workType]` entry --
641
+ * titles are identical to `buildSuggestedIssues`' output, in the same order,
642
+ * since both are derived from the same table.
643
+ */
644
+ export function buildIssueDrafts(goal, workType, plan, repoLabelNames, userAcceptanceCriteria = []) {
645
+ const specs = ISSUE_SPECS_BY_WORK_TYPE[workType] ?? ISSUE_SPECS_BY_WORK_TYPE.feature;
646
+ const candidateLabels = CANDIDATE_LABELS_BY_WORK_TYPE[workType] ?? [];
647
+ const repoLabelsByNormalizedName = new Map(repoLabelNames.map((label) => [label.toLowerCase(), label]));
648
+ const confirmedLabels = candidateLabels.flatMap((label) => {
649
+ const repositoryLabel = repoLabelsByNormalizedName.get(label.toLowerCase());
650
+ return repositoryLabel ? [repositoryLabel] : [];
651
+ });
652
+ return specs.map((spec) => {
653
+ const phaseData = plan.find((p) => p.phase === spec.phase);
654
+ const tasks = phaseData?.tasks ?? [];
655
+ const acceptanceCriteria = Array.from(new Set([...tasks, ...userAcceptanceCriteria]));
656
+ return {
657
+ title: buildIssueTitle(spec, goal),
658
+ body: phaseData
659
+ ? buildIssueDraftBody(phaseData, acceptanceCriteria)
660
+ : [
661
+ "### Background",
662
+ `${capitalize(spec.phase)} phase for: ${goal}`,
663
+ "",
664
+ "### Acceptance Criteria",
665
+ ...acceptanceCriteria.map((criterion) => `- [ ] ${criterion}`),
666
+ ].join("\n"),
667
+ labels: confirmedLabels,
668
+ phase: spec.phase,
669
+ acceptanceCriteria,
670
+ riskLevel: spec.riskLevel,
671
+ goal,
672
+ };
673
+ });
674
+ }
675
+ /**
676
+ * Fetch a repo's actual label names (paginated, capped at 200 -- repos
677
+ * rarely define anywhere near that many). Degrades to `[]` on any error
678
+ * (missing scope, repo with issues disabled, rate limit, etc.) rather than
679
+ * failing the whole plan: an issue draft with no labels is always valid,
680
+ * an invented label that doesn't exist yet is not.
681
+ */
682
+ async function fetchRepoLabelNames(ref) {
683
+ try {
684
+ const octokit = getOctokit();
685
+ const labels = await paginateAll((page, perPage) => octokit.issues
686
+ .listLabelsForRepo({ owner: ref.owner, repo: ref.repo, per_page: perPage, page })
687
+ .then((r) => r.data), 200);
688
+ return labels.map((l) => l.name);
689
+ }
690
+ catch {
691
+ return [];
692
+ }
693
+ }
92
694
  // ---------------------------------------------------------------------------
93
695
  // Pure helpers (exported for testing)
94
696
  // ---------------------------------------------------------------------------
95
- /** Build the phase-by-phase plan. Pure — no I/O. */
96
- export function buildPlan(goal, repoName) {
97
- return Object.keys(PHASE_TEMPLATES).map((phase) => ({
697
+ /** Build the phase-by-phase plan for a given workType (defaults to "feature" for backward compatibility). Pure -- no I/O. */
698
+ export function buildPlan(goal, repoName, workType = "feature") {
699
+ const template = PHASE_TEMPLATES_BY_WORK_TYPE[workType] ?? PHASE_TEMPLATES_BY_WORK_TYPE.feature;
700
+ return Object.keys(template).map((phase) => ({
98
701
  phase,
99
- summary: `${phase.charAt(0).toUpperCase() + phase.slice(1)} phase for: ${goal} (${repoName})`,
100
- tasks: PHASE_TEMPLATES[phase].tasks,
702
+ summary: `${capitalize(phase)} phase for: ${goal} (${repoName})`,
703
+ tasks: template[phase].tasks,
101
704
  }));
102
705
  }
103
706
  // ---------------------------------------------------------------------------
104
707
  // Core handler (exported for testing)
105
708
  // ---------------------------------------------------------------------------
106
- export async function handlePlanFromContext(params, fetchContext) {
709
+ export async function handlePlanFromContext(params, fetchContext, fetchLabels = fetchRepoLabelNames) {
107
710
  const constraints = params.constraints ?? [];
108
711
  const acceptance = params.acceptanceCriteria ?? [];
109
712
  const ref = resolveRepo(params.owner, params.repo);
110
713
  const ctx = await fetchContext({ ...ref });
111
- const plan = buildPlan(params.goal, ctx.fullName);
112
- const suggestedIssues = [
113
- `[Plan] Define acceptance criteria and technical approach for: ${params.goal}`,
114
- `[Create] Implement: ${params.goal}`,
115
- `[Test] Add tests for: ${params.goal}`,
116
- `[Secure] Security review for: ${params.goal}`,
117
- ];
714
+ const inference = inferWorkType(params.goal, acceptance, params.workType);
715
+ const plan = buildPlan(params.goal, ctx.fullName, inference.workType);
716
+ const suggestedIssues = buildSuggestedIssues(params.goal, inference.workType);
717
+ let repoLabelNames = [];
718
+ try {
719
+ repoLabelNames = await fetchLabels(ref);
720
+ }
721
+ catch {
722
+ // Belt-and-braces: fetchRepoLabelNames already catches internally, but a
723
+ // caller-supplied `fetchLabels` (e.g. in tests) might not -- either way,
724
+ // "no confirmed labels" is always a safe fallback.
725
+ repoLabelNames = [];
726
+ }
727
+ const issueDrafts = buildIssueDrafts(params.goal, inference.workType, plan, repoLabelNames, acceptance);
118
728
  const risks = [
119
729
  "Unknown scope may expand during implementation",
120
730
  "Existing tests may need updating",
@@ -125,10 +735,15 @@ export async function handlePlanFromContext(params, fetchContext) {
125
735
  repo: ctx.fullName,
126
736
  defaultBranch: ctx.defaultBranch,
127
737
  language: ctx.language ?? null,
738
+ workType: inference.workType,
739
+ confidence: inference.confidence,
740
+ reasoning: inference.reasoning,
741
+ needsClarification: inference.needsClarification,
128
742
  constraints,
129
743
  acceptanceCriteria: acceptance,
130
744
  phases: plan,
131
745
  suggestedIssues,
746
+ issueDrafts,
132
747
  risks,
133
748
  };
134
749
  const lines = [
@@ -137,10 +752,14 @@ export async function handlePlanFromContext(params, fetchContext) {
137
752
  `**Repository:** ${ctx.fullName}`,
138
753
  `**Default branch:** \`${ctx.defaultBranch}\``,
139
754
  `**Language:** ${ctx.language ?? "unknown"}`,
140
- "",
141
- "## Background",
142
- `Goal: **${params.goal}**`,
755
+ `**Work type:** ${inference.workType} (confidence: ${inference.confidence})`,
756
+ `**Reasoning:** ${inference.reasoning}`,
143
757
  ];
758
+ if (inference.needsClarification) {
759
+ lines.push("", `> [NEEDS CLARIFICATION] Low confidence in the inferred work type ("${inference.workType}"). ` +
760
+ "Consider passing `workType` explicitly, or confirm this categorisation before proceeding.");
761
+ }
762
+ lines.push("", "## Background", `Goal: **${params.goal}**`);
144
763
  if (constraints.length > 0) {
145
764
  lines.push("", "### Constraints");
146
765
  constraints.forEach((c) => lines.push(`- ${c}`));
@@ -151,10 +770,13 @@ export async function handlePlanFromContext(params, fetchContext) {
151
770
  }
152
771
  lines.push("", "## Phase-by-Phase Plan");
153
772
  for (const phase of plan) {
154
- lines.push("", `### ${phase.phase.charAt(0).toUpperCase() + phase.phase.slice(1)}`, `*${phase.summary}*`, "");
773
+ lines.push("", `### ${capitalize(phase.phase)}`, `*${phase.summary}*`, "");
155
774
  phase.tasks.forEach((t) => lines.push(`- [ ] ${t}`));
156
775
  }
157
- lines.push("", "## Suggested Issues to Create", "", "Use `create_issue_set` with these suggested issues:", ...suggestedIssues.map((s) => `- ${s}`), "", "## Risks", ...risks.map((r) => `- ${r}`), "", "## Human Approval Gates", "- PR review must be approved before merge", "- Security review required for auth/data-handling changes", "- Release checklist must pass before deployment");
776
+ lines.push("", "## Suggested Issues to Create", "", "Use `create_issue_set` with these suggested issues:", ...suggestedIssues.map((s) => `- ${s}`), "", "## Issue Drafts (ready for create_issue_set)", "", `${issueDrafts.length} structured draft(s) available in this response's \`issueDrafts\` field -- ` +
777
+ "each has a full body, labels (only ones confirmed to already exist in this repo), phase, " +
778
+ "acceptanceCriteria, and riskLevel. Pass `issueDrafts` directly as `create_issue_set`'s `issues` " +
779
+ "input (dryRun defaults to true, so preview before creating anything real):", "", ...issueDrafts.map((d) => `- **${d.title}** (risk: ${d.riskLevel}, labels: ${d.labels.length > 0 ? d.labels.join(", ") : "none confirmed in this repo"})`), "", "## Risks", ...risks.map((r) => `- ${r}`), "", "## Human Approval Gates", "- PR review must be approved before merge", "- Security review required for auth/data-handling changes", "- Release checklist must pass before deployment");
158
780
  return { text: lines.join("\n"), structured };
159
781
  }
160
782
  // ---------------------------------------------------------------------------
@@ -163,17 +785,18 @@ export async function handlePlanFromContext(params, fetchContext) {
163
785
  export function registerPlanFromContextTool(server) {
164
786
  server.registerTool("plan_from_context", {
165
787
  title: "Generate SDLC Plan from Context",
166
- description: `Generate a structured Agentic SDLC plan (Plan->Create->Test->Review->Optimize->Secure) from a goal and repo context.
788
+ description: `Generate a structured Agentic SDLC plan (Plan->Create->Test->Review->Optimize->Secure) from a goal and repo context. The plan is tailored to a \`workType\` (docs/feature/bugfix/refactor/security/release/infra) -- e.g. docs tasks do not default to requiring code unit tests, while bugfix tasks always include repro + regression tests.
167
789
 
168
- Template-based — no LLM call needed. Reads basic repo metadata to enrich the plan.
790
+ Template-based -- no LLM call needed. Reads basic repo metadata (and the repo's actual label list, to avoid inventing labels that don't exist) to enrich the plan.
169
791
 
170
792
  Args:
171
793
  - goal (string): The user's goal or feature description (required).
172
794
  - owner, repo: Repo coordinates (fall back to env vars).
795
+ - workType (string?): Explicit task category. If omitted, inferred from goal + acceptanceCriteria -- check the output's \`confidence\`/\`needsClarification\` rather than assuming the guess is correct.
173
796
  - constraints (string[]?): Technical or business constraints.
174
797
  - acceptanceCriteria (string[]?): Explicit acceptance criteria.
175
798
 
176
- Returns: Phase-by-phase SDLC plan + structured output.`,
799
+ Returns: Phase-by-phase SDLC plan tailored to the (inferred or explicit) work type, plus structured output including workType/confidence/reasoning/needsClarification, and \`issueDrafts\` -- structured issue drafts (title/body/labels/phase/acceptanceCriteria/riskLevel) directly usable as \`create_issue_set\`'s \`issues\` input.`,
177
800
  inputSchema: PlanFromContextInputSchema,
178
801
  outputSchema: PlanFromContextOutputSchema,
179
802
  annotations: {