@ai-sdlc/orchestrator 0.4.0 → 0.6.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.
- package/dist/action-enforcement.d.ts +26 -0
- package/dist/action-enforcement.js +70 -0
- package/dist/adapters.d.ts +18 -3
- package/dist/adapters.js +92 -2
- package/dist/admission-score.d.ts +58 -0
- package/dist/admission-score.js +164 -0
- package/dist/cli/commands/init.js +4 -8
- package/dist/cli/commands/run.js +2 -2
- package/dist/config.d.ts +3 -0
- package/dist/config.js +14 -5
- package/dist/cycle-utils.d.ts +51 -0
- package/dist/cycle-utils.js +77 -0
- package/dist/defaults.d.ts +5 -0
- package/dist/defaults.js +5 -0
- package/dist/execute.d.ts +5 -2
- package/dist/execute.js +212 -62
- package/dist/fix-ci.js +45 -13
- package/dist/fix-review.d.ts +66 -0
- package/dist/fix-review.js +441 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.js +18 -3
- package/dist/orchestrator.d.ts +1 -1
- package/dist/orchestrator.js +31 -9
- package/dist/pipeline-cycle-detector.d.ts +70 -0
- package/dist/pipeline-cycle-detector.js +111 -0
- package/dist/plugin.d.ts +9 -3
- package/dist/priority.d.ts +28 -0
- package/dist/priority.js +230 -0
- package/dist/review.d.ts +31 -0
- package/dist/review.js +74 -0
- package/dist/runners/claude-code.js +367 -35
- package/dist/runners/codex.js +15 -4
- package/dist/runners/copilot.js +15 -4
- package/dist/runners/cursor.js +15 -4
- package/dist/runners/generic-llm.js +1 -1
- package/dist/runners/index.d.ts +3 -1
- package/dist/runners/index.js +2 -0
- package/dist/runners/review-agent.d.ts +47 -0
- package/dist/runners/review-agent.js +220 -0
- package/dist/runners/security-triage.d.ts +43 -0
- package/dist/runners/security-triage.js +158 -0
- package/dist/runners/types.d.ts +24 -1
- package/dist/security.d.ts +8 -3
- package/dist/security.js +13 -2
- package/dist/shared.d.ts +17 -0
- package/dist/shared.js +27 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/state/schema.d.ts +4 -1
- package/dist/state/schema.js +89 -1
- package/dist/state/store.d.ts +31 -1
- package/dist/state/store.js +208 -13
- package/dist/state/types.d.ts +52 -0
- package/dist/triage.d.ts +36 -0
- package/dist/triage.js +133 -0
- package/dist/types.d.ts +1 -1
- package/dist/watch.d.ts +6 -2
- package/dist/watch.js +34 -6
- package/dist/workflow-patterns/artifact-writer.d.ts +16 -0
- package/dist/workflow-patterns/artifact-writer.js +34 -0
- package/dist/workflow-patterns/classifiers.d.ts +10 -0
- package/dist/workflow-patterns/classifiers.js +72 -0
- package/dist/workflow-patterns/detector.d.ts +27 -0
- package/dist/workflow-patterns/detector.js +186 -0
- package/dist/workflow-patterns/index.d.ts +8 -0
- package/dist/workflow-patterns/index.js +7 -0
- package/dist/workflow-patterns/proposal-generator.d.ts +15 -0
- package/dist/workflow-patterns/proposal-generator.js +183 -0
- package/dist/workflow-patterns/telemetry-ingest.d.ts +27 -0
- package/dist/workflow-patterns/telemetry-ingest.js +103 -0
- package/dist/workflow-patterns/types.d.ts +61 -0
- package/dist/workflow-patterns/types.js +11 -0
- package/package.json +4 -2
package/dist/triage.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security triage pipeline — lightweight entry point that fetches an issue,
|
|
3
|
+
* runs the SecurityTriageRunner, posts findings as a comment, and applies
|
|
4
|
+
* a `rejected` or `triage-passed` label.
|
|
5
|
+
*
|
|
6
|
+
* **Asymmetric by design**: the triage agent can auto-reject issues above the
|
|
7
|
+
* risk threshold, but NEVER auto-approves (no `ai-ready` label). A human
|
|
8
|
+
* must review the triage analysis and manually apply `ai-ready`.
|
|
9
|
+
*/
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { loadConfigAsync } from './config.js';
|
|
12
|
+
import { resolveIssueTrackerFromConfig } from './adapters.js';
|
|
13
|
+
import { getGitHubConfig } from './shared.js';
|
|
14
|
+
import { DEFAULT_CONFIG_DIR_NAME } from './defaults.js';
|
|
15
|
+
import { SecurityTriageRunner, } from './runners/security-triage.js';
|
|
16
|
+
import { createLogger } from './logger.js';
|
|
17
|
+
// ── Labels ──────────────────────────────────────────────────────────
|
|
18
|
+
const LABEL_REJECTED = 'security-rejected';
|
|
19
|
+
const LABEL_TRIAGE_PASSED = 'triage-passed';
|
|
20
|
+
// ── Comment formatting ──────────────────────────────────────────────
|
|
21
|
+
function formatTriageComment(verdict, rejected) {
|
|
22
|
+
const icon = rejected ? '🚨' : verdict.riskScore >= 3 ? '⚠️' : '✅';
|
|
23
|
+
const status = rejected ? 'REJECTED' : 'PASSED';
|
|
24
|
+
const lines = [
|
|
25
|
+
`## ${icon} Security Triage: ${status}`,
|
|
26
|
+
'',
|
|
27
|
+
`**Risk Score:** ${verdict.riskScore}/10`,
|
|
28
|
+
`**Safe:** ${verdict.safe}`,
|
|
29
|
+
'',
|
|
30
|
+
];
|
|
31
|
+
if (verdict.findings.length > 0) {
|
|
32
|
+
lines.push('### Findings', '');
|
|
33
|
+
for (const finding of verdict.findings) {
|
|
34
|
+
lines.push(`- ${finding}`);
|
|
35
|
+
}
|
|
36
|
+
lines.push('');
|
|
37
|
+
}
|
|
38
|
+
lines.push('### Rationale', '', verdict.rationale, '');
|
|
39
|
+
if (rejected) {
|
|
40
|
+
lines.push('---', '> This issue has been automatically rejected due to a high risk score.', '> A maintainer may override this by removing the `security-rejected` label', '> and manually applying `ai-ready` after review.');
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
lines.push('---', '> This issue passed automated security triage.', '> A maintainer must still manually apply the `ai-ready` label to enable AI processing.');
|
|
44
|
+
}
|
|
45
|
+
lines.push('', '*Analyzed by [AI-SDLC Security Triage](https://github.com/ai-sdlc-framework/ai-sdlc)*');
|
|
46
|
+
return lines.join('\n');
|
|
47
|
+
}
|
|
48
|
+
// ── Pipeline ────────────────────────────────────────────────────────
|
|
49
|
+
export async function executeTriage(issueId, options = {}) {
|
|
50
|
+
const workDir = options.workDir ?? process.cwd();
|
|
51
|
+
const log = options.logger ?? createLogger();
|
|
52
|
+
log.info(`[triage] Starting security triage for issue ${issueId}`);
|
|
53
|
+
// ── Resolve issue tracker ───────────────────────────────────────
|
|
54
|
+
let tracker;
|
|
55
|
+
if (options.tracker) {
|
|
56
|
+
tracker = options.tracker;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
const configDir = join(workDir, DEFAULT_CONFIG_DIR_NAME);
|
|
60
|
+
const config = await loadConfigAsync(configDir);
|
|
61
|
+
const ghConfig = getGitHubConfig();
|
|
62
|
+
tracker = resolveIssueTrackerFromConfig(config, {
|
|
63
|
+
org: ghConfig.org,
|
|
64
|
+
repo: ghConfig.repo,
|
|
65
|
+
token: { secretRef: 'GITHUB_TOKEN' },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// ── Fetch issue ─────────────────────────────────────────────────
|
|
69
|
+
const issue = await tracker.getIssue(issueId);
|
|
70
|
+
log.info(`[triage] Fetched issue: "${issue.title}"`);
|
|
71
|
+
// ── Run triage ──────────────────────────────────────────────────
|
|
72
|
+
const runner = new SecurityTriageRunner(options.triageConfig);
|
|
73
|
+
const agentResult = await runner.run({
|
|
74
|
+
issueId,
|
|
75
|
+
issueTitle: issue.title,
|
|
76
|
+
issueBody: issue.description ?? '',
|
|
77
|
+
workDir,
|
|
78
|
+
branch: 'main',
|
|
79
|
+
constraints: {
|
|
80
|
+
maxFilesPerChange: 0,
|
|
81
|
+
requireTests: false,
|
|
82
|
+
blockedPaths: ['**/*'],
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
if (!agentResult.success) {
|
|
86
|
+
log.error(`[triage] Triage failed: ${agentResult.error}`);
|
|
87
|
+
return {
|
|
88
|
+
issueId,
|
|
89
|
+
verdict: {
|
|
90
|
+
safe: false,
|
|
91
|
+
riskScore: 7,
|
|
92
|
+
findings: ['Triage pipeline error — treating as suspicious'],
|
|
93
|
+
sanitizedDescription: '',
|
|
94
|
+
rationale: agentResult.error ?? 'Unknown error',
|
|
95
|
+
},
|
|
96
|
+
rejected: true,
|
|
97
|
+
error: agentResult.error,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
// ── Parse verdict ───────────────────────────────────────────────
|
|
101
|
+
const verdict = JSON.parse(agentResult.summary);
|
|
102
|
+
const rejected = verdict.riskScore >= runner.rejectThreshold;
|
|
103
|
+
log.info(`[triage] Verdict: riskScore=${verdict.riskScore}, safe=${verdict.safe}, rejected=${rejected}`);
|
|
104
|
+
// ── Post comment & apply label ──────────────────────────────────
|
|
105
|
+
if (!options.dryRun) {
|
|
106
|
+
const comment = formatTriageComment(verdict, rejected);
|
|
107
|
+
try {
|
|
108
|
+
await tracker.addComment(issueId, comment);
|
|
109
|
+
log.info(`[triage] Posted triage comment on issue ${issueId}`);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
log.error(`[triage] Failed to post comment: ${err}`);
|
|
113
|
+
}
|
|
114
|
+
const label = rejected ? LABEL_REJECTED : LABEL_TRIAGE_PASSED;
|
|
115
|
+
try {
|
|
116
|
+
const existingLabels = issue.labels ?? [];
|
|
117
|
+
await tracker.updateIssue(issueId, {
|
|
118
|
+
labels: [
|
|
119
|
+
...existingLabels.filter((l) => l !== LABEL_REJECTED && l !== LABEL_TRIAGE_PASSED),
|
|
120
|
+
label,
|
|
121
|
+
],
|
|
122
|
+
});
|
|
123
|
+
log.info(`[triage] Applied label "${label}" to issue ${issueId}`);
|
|
124
|
+
return { issueId, verdict, rejected, labelApplied: label };
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
log.error(`[triage] Failed to apply label: ${err}`);
|
|
128
|
+
return { issueId, verdict, rejected, error: `Label application failed: ${err}` };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { issueId, verdict, rejected };
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=triage.js.map
|
package/dist/types.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Ensures all reference types are accessible through the orchestrator package
|
|
4
4
|
* for downstream consumers without direct reference dependency.
|
|
5
5
|
*/
|
|
6
|
-
export type { ApiVersion, Metadata, Condition, SecretRef, MetricCondition, Duration, Resource, TriggerFilter, Trigger, Provider, RoutingStrategy, ComplexityThreshold, Routing, Stage, PipelineSpec, PipelinePhase, PipelineStatus, Pipeline, AgentConstraints, HandoffContractRef, Handoff, SkillExample, Skill, AgentCard, AgentRoleSpec, AgentRoleStatus, AgentRole, GateScope, MetricRule, ToolRule, ReviewerRule, DocumentationRule, ProvenanceRule, ExpressionRule, GateRule, EnforcementLevel, Override, RetryPolicy, Evaluation, Gate, QualityGateSpec, QualityGateStatus, QualityGate, Permissions, ApprovalRequirement, Guardrails, MonitoringLevel, AutonomyLevel, PromotionCriteria, DemotionTrigger, AgentAutonomyStatus, AutonomyPolicySpec, AutonomyPolicyStatus, AutonomyPolicy, AdapterInterface, HealthCheck, AdapterBindingSpec, AdapterBindingStatus, AdapterBinding, AnyResource, ResourceKind, ValidationError, } from '@ai-sdlc/reference';
|
|
6
|
+
export type { ApiVersion, Metadata, Condition, SecretRef, MetricCondition, Duration, Resource, TriggerFilter, Trigger, Provider, RoutingStrategy, ComplexityThreshold, Routing, Stage, PipelineSpec, PipelinePhase, PipelineStatus, Pipeline, AgentConstraints, HandoffContractRef, Handoff, SkillExample, Skill, AgentCard, AgentRoleSpec, AgentRoleStatus, AgentRole, GateScope, MetricRule, ToolRule, ReviewerRule, DocumentationRule, ProvenanceRule, ExpressionRule, GateRule, EnforcementLevel, Override, RetryPolicy, Evaluation, Gate, QualityGateSpec, QualityGateStatus, QualityGate, Permissions, ApprovalRequirement, Guardrails, MonitoringLevel, AutonomyLevel, PromotionCriteria, DemotionTrigger, AgentAutonomyStatus, AutonomyPolicySpec, AutonomyPolicyStatus, AutonomyPolicy, AdapterInterface, HealthCheck, AdapterBindingSpec, AdapterBindingStatus, AdapterBinding, AnyResource, ResourceKind, PriorityPolicy, PriorityDimensionConfig, PriorityDimensionsConfig, PriorityCalibrationConfig, PriorityAdaptersConfig, ValidationError, } from '@ai-sdlc/reference';
|
|
7
7
|
export type { GateVerdict, DemotionResult, ComplexityFactor, AuthorizationContext, AuthorizationResult, AuthIdentity, AuthenticationResult, Authenticator, MutatingGateContext, ExpressionEvaluator, ExpressionVerdict, LLMEvaluationDimension, LLMEvaluationResult, LLMGateVerdict, } from '@ai-sdlc/reference';
|
|
8
8
|
export type { AgentExecutionState, HandoffValidationError, SchemaResolver, SchemaValidationError, MemoryTier, MemoryEntry, WorkingMemory, ShortTermMemory, LongTermMemory, SharedMemory, EpisodicMemory, } from '@ai-sdlc/reference';
|
|
9
9
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/watch.d.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { type ReconcilerConfig, type ReconcileResult, type Pipeline, type QualityGate, type AutonomyPolicy, type AgentRole, type MetricStore } from '@ai-sdlc/reference';
|
|
8
8
|
import { type ExecuteOptions } from './execute.js';
|
|
9
|
+
import { type PriorityInput } from './priority.js';
|
|
10
|
+
import type { PriorityPolicy } from '@ai-sdlc/reference';
|
|
9
11
|
export interface WatchOptions {
|
|
10
12
|
/** Override the reconciler config (poll interval, concurrency, backoff). */
|
|
11
13
|
reconcilerConfig?: Partial<ReconcilerConfig>;
|
|
@@ -21,10 +23,12 @@ export interface WatchOptions {
|
|
|
21
23
|
qualityGates?: QualityGate[];
|
|
22
24
|
/** Optional autonomy policies for autonomy reconciler evaluation. */
|
|
23
25
|
autonomyPolicies?: AutonomyPolicy[];
|
|
26
|
+
/** Priority scoring policy configuration. */
|
|
27
|
+
priorityPolicy?: PriorityPolicy;
|
|
24
28
|
}
|
|
25
29
|
export interface WatchHandle {
|
|
26
|
-
/** Enqueue a pipeline resource for reconciliation. */
|
|
27
|
-
enqueue(pipeline: Pipeline,
|
|
30
|
+
/** Enqueue a pipeline resource for reconciliation. Optionally provide PriorityInput for scoring. */
|
|
31
|
+
enqueue(pipeline: Pipeline, issueId: string, priorityInput?: PriorityInput): void;
|
|
28
32
|
/** Enqueue a quality gate resource for reconciliation. */
|
|
29
33
|
enqueueGate(gate: QualityGate): void;
|
|
30
34
|
/** Enqueue an autonomy policy resource for reconciliation. */
|
package/dist/watch.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { ReconcilerLoop, createResourceCache, instrumentReconciler, } from '@ai-sdlc/reference';
|
|
8
8
|
import { executePipeline } from './execute.js';
|
|
9
9
|
import { createPipelineReconciler, createGateReconciler, createAutonomyReconciler, } from './reconcilers.js';
|
|
10
|
+
import { computePriority } from './priority.js';
|
|
10
11
|
/**
|
|
11
12
|
* Start a reconciler watch loop that continuously processes pipeline resources.
|
|
12
13
|
*/
|
|
@@ -30,15 +31,15 @@ export function startWatch(options = {}) {
|
|
|
30
31
|
switch (resource.kind) {
|
|
31
32
|
case 'Pipeline': {
|
|
32
33
|
const pipeline = resource;
|
|
33
|
-
const
|
|
34
|
-
if (!
|
|
34
|
+
const issueId = issueMap.get(pipeline.metadata.name);
|
|
35
|
+
if (!issueId) {
|
|
35
36
|
return {
|
|
36
37
|
type: 'error',
|
|
37
|
-
error: new Error(`No issue
|
|
38
|
+
error: new Error(`No issue ID for pipeline ${pipeline.metadata.name}`),
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
41
|
try {
|
|
41
|
-
await executePipeline(
|
|
42
|
+
await executePipeline(issueId, {
|
|
42
43
|
...options.executeOptions,
|
|
43
44
|
});
|
|
44
45
|
const result = { type: 'success' };
|
|
@@ -68,9 +69,36 @@ export function startWatch(options = {}) {
|
|
|
68
69
|
}
|
|
69
70
|
const loop = new ReconcilerLoop(reconcileFn, options.reconcilerConfig);
|
|
70
71
|
loop.start();
|
|
72
|
+
// Map to hold priority scores for pipelines
|
|
73
|
+
const priorityScores = new Map();
|
|
71
74
|
return {
|
|
72
|
-
enqueue(pipeline,
|
|
73
|
-
issueMap.set(pipeline.metadata.name,
|
|
75
|
+
enqueue(pipeline, issueId, priorityInput) {
|
|
76
|
+
issueMap.set(pipeline.metadata.name, issueId);
|
|
77
|
+
// Priority scoring when policy is enabled
|
|
78
|
+
if (options.priorityPolicy?.enabled && priorityInput) {
|
|
79
|
+
const config = options.priorityPolicy.dimensions?.humanCurveWeights
|
|
80
|
+
? { humanCurveWeights: options.priorityPolicy.dimensions.humanCurveWeights }
|
|
81
|
+
: undefined;
|
|
82
|
+
const score = computePriority(priorityInput, config);
|
|
83
|
+
// Skip items below minimum score
|
|
84
|
+
if (options.priorityPolicy.minimumScore !== undefined &&
|
|
85
|
+
score.composite < options.priorityPolicy.minimumScore) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
// Flag items below minimum confidence (still enqueue, but mark)
|
|
89
|
+
if (options.priorityPolicy.minimumConfidence !== undefined &&
|
|
90
|
+
score.confidence < options.priorityPolicy.minimumConfidence) {
|
|
91
|
+
// Store the score with a low-confidence flag for downstream consumers
|
|
92
|
+
priorityScores.set(pipeline.metadata.name, score);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
priorityScores.set(pipeline.metadata.name, score);
|
|
96
|
+
}
|
|
97
|
+
if (cache.shouldReconcile(pipeline)) {
|
|
98
|
+
loop.enqueue(pipeline, score.composite);
|
|
99
|
+
}
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
74
102
|
if (cache.shouldReconcile(pipeline)) {
|
|
75
103
|
loop.enqueue(pipeline);
|
|
76
104
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifact writer — generates files for approved pattern proposals.
|
|
3
|
+
* Never overwrites existing files.
|
|
4
|
+
*/
|
|
5
|
+
export interface WriteResult {
|
|
6
|
+
success: boolean;
|
|
7
|
+
filePath: string;
|
|
8
|
+
error?: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Write a proposal artifact to the filesystem.
|
|
12
|
+
* Creates parent directories if needed.
|
|
13
|
+
* Returns error if file already exists (never overwrites).
|
|
14
|
+
*/
|
|
15
|
+
export declare function writeArtifact(projectDir: string, relativePath: string, content: string): WriteResult;
|
|
16
|
+
//# sourceMappingURL=artifact-writer.d.ts.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifact writer — generates files for approved pattern proposals.
|
|
3
|
+
* Never overwrites existing files.
|
|
4
|
+
*/
|
|
5
|
+
import { writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
6
|
+
import { join, dirname } from 'node:path';
|
|
7
|
+
/**
|
|
8
|
+
* Write a proposal artifact to the filesystem.
|
|
9
|
+
* Creates parent directories if needed.
|
|
10
|
+
* Returns error if file already exists (never overwrites).
|
|
11
|
+
*/
|
|
12
|
+
export function writeArtifact(projectDir, relativePath, content) {
|
|
13
|
+
const fullPath = join(projectDir, relativePath);
|
|
14
|
+
if (existsSync(fullPath)) {
|
|
15
|
+
return {
|
|
16
|
+
success: false,
|
|
17
|
+
filePath: fullPath,
|
|
18
|
+
error: `File already exists: ${relativePath}`,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
mkdirSync(dirname(fullPath), { recursive: true });
|
|
23
|
+
writeFileSync(fullPath, content, 'utf-8');
|
|
24
|
+
return { success: true, filePath: fullPath };
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
return {
|
|
28
|
+
success: false,
|
|
29
|
+
filePath: fullPath,
|
|
30
|
+
error: err instanceof Error ? err.message : String(err),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=artifact-writer.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pattern type classifiers — refine detected patterns into
|
|
3
|
+
* specific automation types based on their structure.
|
|
4
|
+
*/
|
|
5
|
+
import type { DetectedPattern } from './types.js';
|
|
6
|
+
/**
|
|
7
|
+
* Classify a detected pattern into a specific type and suggest an artifact.
|
|
8
|
+
*/
|
|
9
|
+
export declare function classifyPattern(pattern: DetectedPattern): DetectedPattern;
|
|
10
|
+
//# sourceMappingURL=classifiers.d.ts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pattern type classifiers — refine detected patterns into
|
|
3
|
+
* specific automation types based on their structure.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Classify a detected pattern into a specific type and suggest an artifact.
|
|
7
|
+
*/
|
|
8
|
+
export function classifyPattern(pattern) {
|
|
9
|
+
// Check classifiers in priority order
|
|
10
|
+
if (isCopyPasteCycle(pattern.steps)) {
|
|
11
|
+
return {
|
|
12
|
+
...pattern,
|
|
13
|
+
patternType: 'copy-paste-cycle',
|
|
14
|
+
suggestedArtifactType: 'skill',
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
if (isPeriodicTask(pattern)) {
|
|
18
|
+
return {
|
|
19
|
+
...pattern,
|
|
20
|
+
patternType: 'periodic-task',
|
|
21
|
+
suggestedArtifactType: 'workflow',
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
// Default: command sequence
|
|
25
|
+
return {
|
|
26
|
+
...pattern,
|
|
27
|
+
patternType: 'command-sequence',
|
|
28
|
+
suggestedArtifactType: 'command',
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Copy-paste cycle: Read from one file, then Write/Edit a different file type.
|
|
33
|
+
* Suggests the user is copying boilerplate or scaffolding from templates.
|
|
34
|
+
*/
|
|
35
|
+
function isCopyPasteCycle(steps) {
|
|
36
|
+
let hasRead = false;
|
|
37
|
+
let hasWriteAfterRead = false;
|
|
38
|
+
for (const step of steps) {
|
|
39
|
+
if (step.category === 'read') {
|
|
40
|
+
hasRead = true;
|
|
41
|
+
}
|
|
42
|
+
else if (hasRead && step.category === 'write') {
|
|
43
|
+
hasWriteAfterRead = true;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// Must have at least one read→write transition
|
|
47
|
+
if (!hasWriteAfterRead)
|
|
48
|
+
return false;
|
|
49
|
+
// The write should target a different file than the read
|
|
50
|
+
const readActions = steps.filter((s) => s.category === 'read').map((s) => s.action);
|
|
51
|
+
const writeActions = steps.filter((s) => s.category === 'write').map((s) => s.action);
|
|
52
|
+
// If reads and writes target different extensions, it's likely scaffolding
|
|
53
|
+
const readExts = new Set(readActions.map((a) => a.split(':').pop()));
|
|
54
|
+
const writeExts = new Set(writeActions.map((a) => a.split(':').pop()));
|
|
55
|
+
// Different file types or at least some diversity
|
|
56
|
+
const hasDistinctTargets = readExts.size > 0 && writeExts.size > 0 && ![...readExts].every((e) => writeExts.has(e));
|
|
57
|
+
return hasDistinctTargets || (readActions.length > 0 && writeActions.length > 1);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Periodic task: same pattern occurs with regular time spacing.
|
|
61
|
+
* Requires firstSeen and lastSeen spanning 7+ days.
|
|
62
|
+
*/
|
|
63
|
+
function isPeriodicTask(pattern) {
|
|
64
|
+
if (!pattern.firstSeen || !pattern.lastSeen)
|
|
65
|
+
return false;
|
|
66
|
+
const first = new Date(pattern.firstSeen).getTime();
|
|
67
|
+
const last = new Date(pattern.lastSeen).getTime();
|
|
68
|
+
const spanDays = (last - first) / (1000 * 60 * 60 * 24);
|
|
69
|
+
// Must span at least 7 days with regular occurrence
|
|
70
|
+
return spanDays >= 7 && pattern.sessionCount >= 3;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=classifiers.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow pattern detector — mines frequent n-gram sequences
|
|
3
|
+
* from tool call histories across Claude Code sessions.
|
|
4
|
+
*/
|
|
5
|
+
import type { ToolSequenceEvent } from '../state/types.js';
|
|
6
|
+
import type { CanonicalStep, NGram, DetectedPattern, DetectionOptions } from './types.js';
|
|
7
|
+
/**
|
|
8
|
+
* Convert a raw tool event to a canonical step.
|
|
9
|
+
*/
|
|
10
|
+
export declare function canonicalizeStep(event: ToolSequenceEvent): CanonicalStep;
|
|
11
|
+
/**
|
|
12
|
+
* Hash a sequence of canonical steps for grouping.
|
|
13
|
+
*/
|
|
14
|
+
export declare function hashSequence(steps: CanonicalStep[]): string;
|
|
15
|
+
/**
|
|
16
|
+
* Group tool sequence events by session, ordered by timestamp.
|
|
17
|
+
*/
|
|
18
|
+
export declare function extractSessionSequences(events: ToolSequenceEvent[]): Map<string, CanonicalStep[]>;
|
|
19
|
+
/**
|
|
20
|
+
* Generate all contiguous n-grams from a sequence.
|
|
21
|
+
*/
|
|
22
|
+
export declare function generateNGrams(sequence: CanonicalStep[], sessionId: string, minN: number, maxN: number): NGram[];
|
|
23
|
+
/**
|
|
24
|
+
* Mine frequent patterns from tool sequence events.
|
|
25
|
+
*/
|
|
26
|
+
export declare function mineFrequentPatterns(events: ToolSequenceEvent[], opts?: Partial<DetectionOptions>): DetectedPattern[];
|
|
27
|
+
//# sourceMappingURL=detector.d.ts.map
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow pattern detector — mines frequent n-gram sequences
|
|
3
|
+
* from tool call histories across Claude Code sessions.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { categorizeAction } from './telemetry-ingest.js';
|
|
7
|
+
import { DEFAULT_DETECTION_OPTIONS } from './types.js';
|
|
8
|
+
/**
|
|
9
|
+
* Convert a raw tool event to a canonical step.
|
|
10
|
+
*/
|
|
11
|
+
export function canonicalizeStep(event) {
|
|
12
|
+
return {
|
|
13
|
+
tool: event.toolName,
|
|
14
|
+
action: event.actionCanonical,
|
|
15
|
+
category: categorizeAction(event.toolName, event.actionCanonical),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Hash a sequence of canonical steps for grouping.
|
|
20
|
+
*/
|
|
21
|
+
export function hashSequence(steps) {
|
|
22
|
+
const key = steps.map((s) => `${s.tool}:${s.action}`).join('|');
|
|
23
|
+
return createHash('sha256').update(key).digest('hex').slice(0, 16);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Group tool sequence events by session, ordered by timestamp.
|
|
27
|
+
*/
|
|
28
|
+
export function extractSessionSequences(events) {
|
|
29
|
+
const sessions = new Map();
|
|
30
|
+
for (const event of events) {
|
|
31
|
+
const existing = sessions.get(event.sessionId) ?? [];
|
|
32
|
+
existing.push(event);
|
|
33
|
+
sessions.set(event.sessionId, existing);
|
|
34
|
+
}
|
|
35
|
+
const result = new Map();
|
|
36
|
+
for (const [sessionId, sessionEvents] of sessions) {
|
|
37
|
+
const sorted = sessionEvents.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
|
|
38
|
+
result.set(sessionId, sorted.map(canonicalizeStep));
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Generate all contiguous n-grams from a sequence.
|
|
44
|
+
*/
|
|
45
|
+
export function generateNGrams(sequence, sessionId, minN, maxN) {
|
|
46
|
+
const ngrams = [];
|
|
47
|
+
for (let n = minN; n <= Math.min(maxN, sequence.length); n++) {
|
|
48
|
+
for (let i = 0; i <= sequence.length - n; i++) {
|
|
49
|
+
const steps = sequence.slice(i, i + n);
|
|
50
|
+
ngrams.push({
|
|
51
|
+
steps,
|
|
52
|
+
hash: hashSequence(steps),
|
|
53
|
+
sessionId,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return ngrams;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Mine frequent patterns from tool sequence events.
|
|
61
|
+
*/
|
|
62
|
+
export function mineFrequentPatterns(events, opts) {
|
|
63
|
+
const options = { ...DEFAULT_DETECTION_OPTIONS, ...opts };
|
|
64
|
+
// Filter by project and time
|
|
65
|
+
let filtered = events;
|
|
66
|
+
if (options.projectFilter) {
|
|
67
|
+
filtered = filtered.filter((e) => e.projectPath === options.projectFilter);
|
|
68
|
+
}
|
|
69
|
+
if (options.since) {
|
|
70
|
+
const sinceDate = new Date(options.since).getTime();
|
|
71
|
+
filtered = filtered.filter((e) => new Date(e.timestamp).getTime() >= sinceDate);
|
|
72
|
+
}
|
|
73
|
+
if (filtered.length === 0)
|
|
74
|
+
return [];
|
|
75
|
+
// Group by session
|
|
76
|
+
const sessions = extractSessionSequences(filtered);
|
|
77
|
+
const totalSessions = sessions.size;
|
|
78
|
+
if (totalSessions < options.minSessionCount)
|
|
79
|
+
return [];
|
|
80
|
+
// Generate n-grams across all sessions
|
|
81
|
+
const aggregates = new Map();
|
|
82
|
+
for (const [sessionId, sequence] of sessions) {
|
|
83
|
+
const ngrams = generateNGrams(sequence, sessionId, options.minSequenceLength, options.maxSequenceLength);
|
|
84
|
+
// Deduplicate within a session (same hash counted once per session)
|
|
85
|
+
const seenInSession = new Set();
|
|
86
|
+
for (const ngram of ngrams) {
|
|
87
|
+
if (seenInSession.has(ngram.hash))
|
|
88
|
+
continue;
|
|
89
|
+
seenInSession.add(ngram.hash);
|
|
90
|
+
const existing = aggregates.get(ngram.hash);
|
|
91
|
+
if (existing) {
|
|
92
|
+
existing.frequency++;
|
|
93
|
+
existing.sessionIds.add(sessionId);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
aggregates.set(ngram.hash, {
|
|
97
|
+
steps: ngram.steps,
|
|
98
|
+
hash: ngram.hash,
|
|
99
|
+
frequency: 1,
|
|
100
|
+
sessionIds: new Set([sessionId]),
|
|
101
|
+
timestamps: [],
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
// Filter by minimum frequency and session count
|
|
107
|
+
let patterns = [];
|
|
108
|
+
for (const agg of aggregates.values()) {
|
|
109
|
+
if (agg.frequency >= options.minFrequency && agg.sessionIds.size >= options.minSessionCount) {
|
|
110
|
+
patterns.push(agg);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Compute confidence and find max frequency for normalization
|
|
114
|
+
const maxFrequency = Math.max(1, ...patterns.map((p) => p.frequency));
|
|
115
|
+
// Remove subsumed patterns (shorter patterns contained in longer ones with similar frequency)
|
|
116
|
+
patterns = removeSubsumedPatterns(patterns);
|
|
117
|
+
// Build detected patterns with confidence scoring
|
|
118
|
+
const detected = [];
|
|
119
|
+
for (const p of patterns) {
|
|
120
|
+
const confidence = Math.min(1.0, (p.sessionIds.size / totalSessions) * (p.frequency / maxFrequency));
|
|
121
|
+
if (confidence < options.minConfidence)
|
|
122
|
+
continue;
|
|
123
|
+
detected.push({
|
|
124
|
+
hash: p.hash,
|
|
125
|
+
steps: p.steps,
|
|
126
|
+
frequency: p.frequency,
|
|
127
|
+
sessionCount: p.sessionIds.size,
|
|
128
|
+
confidence,
|
|
129
|
+
patternType: 'command-sequence', // Default — classifiers refine this
|
|
130
|
+
suggestedArtifactType: 'command',
|
|
131
|
+
firstSeen: '', // Populated by caller from event timestamps
|
|
132
|
+
lastSeen: '',
|
|
133
|
+
exampleSessionIds: Array.from(p.sessionIds).slice(0, 5),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
// Sort by confidence * length descending
|
|
137
|
+
detected.sort((a, b) => b.confidence * b.steps.length - a.confidence * a.steps.length);
|
|
138
|
+
return detected;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Remove patterns that are subsumed by longer patterns with similar frequency.
|
|
142
|
+
* A 3-gram is subsumed by a 5-gram if the 3-gram's steps appear contiguously
|
|
143
|
+
* in the 5-gram and the 5-gram has >= 70% of the 3-gram's frequency.
|
|
144
|
+
*/
|
|
145
|
+
function removeSubsumedPatterns(patterns) {
|
|
146
|
+
// Sort by length descending so longer patterns take priority
|
|
147
|
+
const sorted = [...patterns].sort((a, b) => b.steps.length - a.steps.length);
|
|
148
|
+
const kept = [];
|
|
149
|
+
const removed = new Set();
|
|
150
|
+
for (const pattern of sorted) {
|
|
151
|
+
if (removed.has(pattern.hash))
|
|
152
|
+
continue;
|
|
153
|
+
kept.push(pattern);
|
|
154
|
+
// Mark shorter patterns that are subsumed
|
|
155
|
+
for (const other of sorted) {
|
|
156
|
+
if (other.hash === pattern.hash || removed.has(other.hash))
|
|
157
|
+
continue;
|
|
158
|
+
if (other.steps.length >= pattern.steps.length)
|
|
159
|
+
continue;
|
|
160
|
+
if (isSubsequence(other.steps, pattern.steps) && pattern.frequency >= other.frequency * 0.7) {
|
|
161
|
+
removed.add(other.hash);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return kept;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Check if `short` appears as a contiguous subsequence in `long`.
|
|
169
|
+
*/
|
|
170
|
+
function isSubsequence(short, long) {
|
|
171
|
+
if (short.length > long.length)
|
|
172
|
+
return false;
|
|
173
|
+
for (let i = 0; i <= long.length - short.length; i++) {
|
|
174
|
+
let match = true;
|
|
175
|
+
for (let j = 0; j < short.length; j++) {
|
|
176
|
+
if (short[j].tool !== long[i + j].tool || short[j].action !== long[i + j].action) {
|
|
177
|
+
match = false;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (match)
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=detector.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { readToolSequenceJSONL, readSessionMetaFiles, sessionMetaToEvents, categorizeAction, } from './telemetry-ingest.js';
|
|
2
|
+
export { canonicalizeStep, hashSequence, extractSessionSequences, generateNGrams, mineFrequentPatterns, } from './detector.js';
|
|
3
|
+
export { classifyPattern } from './classifiers.js';
|
|
4
|
+
export { generateProposal, generateName } from './proposal-generator.js';
|
|
5
|
+
export { writeArtifact, type WriteResult } from './artifact-writer.js';
|
|
6
|
+
export type { CanonicalStep, NGram, DetectedPattern, DetectionOptions, RawToolSequenceEntry, SessionMeta, } from './types.js';
|
|
7
|
+
export { DEFAULT_DETECTION_OPTIONS } from './types.js';
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { readToolSequenceJSONL, readSessionMetaFiles, sessionMetaToEvents, categorizeAction, } from './telemetry-ingest.js';
|
|
2
|
+
export { canonicalizeStep, hashSequence, extractSessionSequences, generateNGrams, mineFrequentPatterns, } from './detector.js';
|
|
3
|
+
export { classifyPattern } from './classifiers.js';
|
|
4
|
+
export { generateProposal, generateName } from './proposal-generator.js';
|
|
5
|
+
export { writeArtifact } from './artifact-writer.js';
|
|
6
|
+
export { DEFAULT_DETECTION_OPTIONS } from './types.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proposal generator — creates draft automation artifacts from detected patterns.
|
|
3
|
+
* Each pattern type maps to a specific artifact: command, skill, hook, or workflow.
|
|
4
|
+
*/
|
|
5
|
+
import type { DetectedPattern } from './types.js';
|
|
6
|
+
import type { PatternProposal } from '../state/types.js';
|
|
7
|
+
/**
|
|
8
|
+
* Generate an automation proposal from a detected pattern.
|
|
9
|
+
*/
|
|
10
|
+
export declare function generateProposal(pattern: DetectedPattern): Omit<PatternProposal, 'patternId'>;
|
|
11
|
+
/**
|
|
12
|
+
* Generate a kebab-case name from the pattern's steps.
|
|
13
|
+
*/
|
|
14
|
+
export declare function generateName(pattern: DetectedPattern): string;
|
|
15
|
+
//# sourceMappingURL=proposal-generator.d.ts.map
|