Repository navigation
Expand file tree
/
Copy pathcode.go
More file actions
426 lines (392 loc) · 14.4 KB
/
Copy pathcode.go
File metadata and controls
426 lines (392 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/codefly-dev/core/agents"
corecode "github.com/codefly-dev/core/code"
"github.com/codefly-dev/core/code/semantic"
basev0 "github.com/codefly-dev/core/generated/go/codefly/base/v0"
codev0 "github.com/codefly-dev/core/generated/go/codefly/services/code/v0"
runners "github.com/codefly-dev/core/runners/base"
)
// ARCHITECTURE: Code implements the codefly Code gRPC service for NextJS/Node.
// It embeds TypeScriptCodeServer from core, which provides:
// - File operations: ReadFile, WriteFile, CreateFile, DeleteFile, MoveFile, ListFiles, Search
// - Git operations: GitLog, GitDiff, GitShow, GitBlame
// - ShellExec: bounded process execution
//
// Node-specific behavior is limited to project-local source fixing. Typed
// project inspection stays in Core so every TypeScript agent exposes the same
// dependency, package, import, and failure contract.
type Code struct {
*corecode.TypeScriptCodeServer
*Service
serverMu sync.Mutex
initializedSource string
}
func NewCode(svc *Service) *Code {
c := &Code{
Service: svc,
TypeScriptCodeServer: corecode.NewTypeScriptCodeServer(".", semanticOpts()),
}
return c
}
func (c *Code) sourceDir() string {
if source := c.currentSourceLocation(); source != "" {
return source
}
if wd := os.Getenv(agents.WorkDirEnvironment); wd != "" {
return filepath.Join(wd, c.Settings.NodeSourceDir())
}
return filepath.Join(c.Location, c.Settings.NodeSourceDir())
}
func (c *Code) InitServer() {
c.serverMu.Lock()
defer c.serverMu.Unlock()
c.initServer()
}
func (c *Code) initServer() {
source := c.sourceDir()
if c.TypeScriptCodeServer != nil && c.initializedSource == source {
return
}
previous := c.TypeScriptCodeServer
c.TypeScriptCodeServer = corecode.NewTypeScriptCodeServer(source, semanticOpts())
c.SetSourceFixer(c.fixTypeScript)
c.initializedSource = source
if previous != nil {
_ = previous.Close()
}
}
func (c *Code) Execute(ctx context.Context, req *codev0.CodeRequest) (*codev0.CodeResponse, error) {
c.serverMu.Lock()
defer c.serverMu.Unlock()
if _, err := c.resolveSourceLocation(ctx); err != nil {
return nil, fmt.Errorf("resolve Node source: %w", err)
}
c.initServer()
response, err := c.TypeScriptCodeServer.Execute(ctx, req)
if err != nil {
return nil, err
}
if project := response.GetGetProjectInfo(); project != nil {
project.Language = nodeProjectLanguage(project.GetSourceFiles())
}
return response, nil
}
// nodeProjectLanguage preserves TypeScript for mixed or TypeScript projects
// and reports JavaScript when the project contains only JavaScript sources.
// ARCHITECTURE: Core owns source discovery; this agent classifies the returned
// typed inventory instead of performing a second filesystem walk.
func nodeProjectLanguage(sourceFiles []*codev0.SourceFileInfo) string {
hasJavaScript := false
for _, source := range sourceFiles {
switch strings.ToLower(filepath.Ext(source.GetPath())) {
case ".ts", ".tsx", ".mts", ".cts":
return "typescript"
case ".js", ".jsx", ".mjs", ".cjs":
hasJavaScript = true
}
}
if hasJavaScript {
return "javascript"
}
return "typescript"
}
type nodePackageManifest struct {
Scripts map[string]string `json:"scripts"`
OptionalDependencies map[string]string `json:"optionalDependencies"`
PeerDependencies map[string]string `json:"peerDependencies"`
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}
type nodeProjectKind string
type nodeTestRunner string
const (
nodeProjectGeneric nodeProjectKind = "node"
nodeProjectNextJS nodeProjectKind = "nextjs"
nodeTestGeneric nodeTestRunner = "npm"
nodeTestJest nodeTestRunner = "jest"
nodeTestPlaywright nodeTestRunner = "playwright"
nodeTestVitest nodeTestRunner = "vitest"
)
type eslintJSONResult struct {
Output *string `json:"output"`
Messages []struct {
RuleID *string `json:"ruleId"`
Severity int `json:"severity"`
Message string `json:"message"`
Line int `json:"line"`
Column int `json:"column"`
} `json:"messages"`
}
// fixTypeScript selects only project-local tools. Biome is preferred because
// one stdin invocation performs formatting, safe lint fixes, and import
// organization. Existing ESLint/Prettier projects use their configured tools
// without downloading executables during an agent edit.
func (c *Code) fixTypeScript(ctx context.Context, input corecode.FixInput) (corecode.FixResult, error) {
manifest, err := c.readNodePackageManifest()
if err != nil {
return corecode.FixResult{}, err
}
env := c.runnerEnvironment(ctx)
if manifest.hasDependency("@biomejs/biome") {
args := []string{"exec", "--offline", "--", "biome", "check", "--stdin-file-path", input.Path, "--write"}
if input.Mode == basev0.FixMode_FIX_MODE_AGGRESSIVE {
args = append(args, "--unsafe")
}
fixed, diagnostics, runErr := runners.RunInput(ctx, env, c.sourceDir(), input.Content, "npm", args...)
if runErr != nil && len(fixed) == 0 {
return corecode.FixResult{}, fmt.Errorf("biome check: %w: %s", runErr, strings.TrimSpace(string(diagnostics)))
}
if err := rejectEmptySourceFix("biome", input.Content, fixed); err != nil {
return corecode.FixResult{}, err
}
return corecode.FixResult{
Content: fixed,
Actions: []string{"biome check --write"},
Output: strings.TrimSpace(string(diagnostics)),
}, nil
}
fixed := input.Content
var actions []string
var output []string
if manifest.hasDependency("eslint") || manifest.Scripts["lint"] != "" {
args := []string{"exec", "--offline", "--", "eslint", "--fix-dry-run", "--stdin", "--stdin-filename", input.Path, "--format", "json"}
jsonOutput, diagnostics, runErr := runners.RunInput(ctx, env, c.sourceDir(), fixed, "npm", args...)
parsed, parseErr := parseESLintFix(jsonOutput, fixed)
if parseErr != nil {
return corecode.FixResult{}, fmt.Errorf("eslint --fix-dry-run: %w (run error: %v): %s", parseErr, runErr, strings.TrimSpace(string(diagnostics)))
}
fixed = parsed.Content
actions = append(actions, "eslint --fix-dry-run")
output = append(output, parsed.Diagnostics...)
if text := strings.TrimSpace(string(diagnostics)); text != "" {
output = append(output, text)
}
}
if manifest.hasDependency("prettier") {
formatted, diagnostics, runErr := runners.RunInput(ctx, env, c.sourceDir(), fixed, "npm", "exec", "--offline", "--", "prettier", "--stdin-filepath", input.Path)
if runErr != nil {
return corecode.FixResult{}, fmt.Errorf("prettier: %w: %s", runErr, strings.TrimSpace(string(diagnostics)))
}
if err := rejectEmptySourceFix("prettier", fixed, formatted); err != nil {
return corecode.FixResult{}, err
}
fixed = formatted
actions = append(actions, "prettier")
if text := strings.TrimSpace(string(diagnostics)); text != "" {
output = append(output, text)
}
}
if len(actions) == 0 {
return corecode.FixResult{}, fmt.Errorf("no project-local Biome, ESLint, or Prettier fixer is configured")
}
return corecode.FixResult{Content: fixed, Actions: actions, Output: strings.Join(output, "\n")}, nil
}
// A formatter/linter is never allowed to turn a substantive source file into
// an empty file. This invariant is deliberately independent of process exit
// status: a broken stdin/stdout integration can exit successfully with no
// output, which must fail closed instead of being reported as a valid fix.
func rejectEmptySourceFix(tool string, original, fixed []byte) error {
if len(bytes.TrimSpace(original)) > 0 && len(bytes.TrimSpace(fixed)) == 0 {
return fmt.Errorf("%s returned empty output for a non-empty source file; refusing destructive fix", tool)
}
return nil
}
func (c *Code) readNodePackageManifest() (*nodePackageManifest, error) {
return readNodePackageManifest(c.sourceDir())
}
func readNodePackageManifest(sourceDir string) (*nodePackageManifest, error) {
data, err := os.ReadFile(filepath.Join(sourceDir, "package.json"))
if err != nil {
return nil, fmt.Errorf("read package.json: %w", err)
}
var manifest nodePackageManifest
if err := json.Unmarshal(data, &manifest); err != nil {
return nil, fmt.Errorf("parse package.json: %w", err)
}
return &manifest, nil
}
// nodePackageLock is the resolved half of the dependency contract. package.json
// declares what is acceptable; package-lock.json records what npm actually
// selected, and it is what `npm ci` reinstalls byte-for-byte in development, CI
// and the container build. A newer agent therefore never implies a newer
// framework: this file does.
type nodePackageLock struct {
LockfileVersion int `json:"lockfileVersion"`
Packages map[string]struct {
Version string `json:"version"`
Resolved string `json:"resolved"`
Link bool `json:"link"`
} `json:"packages"`
}
// readNodePackageLock returns a nil lock and no error when the project has no
// lockfile: an unpinned project is a reportable state, not a failure.
func readNodePackageLock(sourceDir string) (*nodePackageLock, error) {
data, err := os.ReadFile(filepath.Join(sourceDir, "package-lock.json"))
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("read package-lock.json: %w", err)
}
var lock nodePackageLock
if err := json.Unmarshal(data, &lock); err != nil {
return nil, fmt.Errorf("parse package-lock.json: %w", err)
}
return &lock, nil
}
// resolvedVersion reports the version npm selected for a top-level dependency,
// or "" when the project is unpinned or the package is absent.
func (l *nodePackageLock) resolvedVersion(name string) string {
if l == nil {
return ""
}
return l.Packages["node_modules/"+name].Version
}
// externalLinks returns, in order, the directories the lock links from
// outside sourceDir (a `file:` dependency on a sibling package), as the lock
// records them: npm writes a relative path, and a `file:` prefix is dropped so
// a lock that spells the same link `file:../remote` names the same directory.
// npm installs a linked package's own dependencies only when it sits inside
// the project (a workspace); one outside gets a symlink and nothing else, so
// its source resolves none of its imports until its own lock is installed
// where it lives. Where the link may point is the runtime's call, not this
// reader's: see Runtime.linkedPackageTarget.
func (l *nodePackageLock) externalLinks() []string {
if l == nil {
return nil
}
seen := map[string]bool{}
var links []string
for _, entry := range l.Packages {
if !entry.Link || entry.Resolved == "" {
continue
}
relative := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(entry.Resolved, "file:")))
if filepath.IsLocal(relative) || seen[relative] {
continue
}
seen[relative] = true
links = append(links, relative)
}
sort.Strings(links)
return links
}
// declaredVersion reports the constraint package.json states for a dependency,
// across the runtime and development scopes.
func (m *nodePackageManifest) declaredVersion(name string) string {
if m == nil {
return ""
}
if version := m.Dependencies[name]; version != "" {
return version
}
return m.DevDependencies[name]
}
func (m *nodePackageManifest) hasDependency(name string) bool {
return m.declaredVersion(name) != ""
}
func (m *nodePackageManifest) projectKind() nodeProjectKind {
if m != nil && m.hasDependency("next") {
return nodeProjectNextJS
}
return nodeProjectGeneric
}
func (m *nodePackageManifest) hasScript(name string) bool {
return m != nil && strings.TrimSpace(m.Scripts[name]) != ""
}
func (m *nodePackageManifest) testRunner(scriptName string) nodeTestRunner {
if m == nil {
return nodeTestGeneric
}
// The script command is authoritative. A package that installs @playwright/test
// for a separate e2e script still runs its unit `test` script through Vitest, so
// an installed dependency must never override the runner the command itself names.
command := strings.ToLower(m.Scripts[scriptName])
switch {
case strings.Contains(command, "playwright"):
return nodeTestPlaywright
case strings.Contains(command, "vitest"):
return nodeTestVitest
case strings.Contains(command, "jest"):
return nodeTestJest
}
// The command names no runner (e.g. a bare wrapper script): fall back to the
// installed test dependency.
switch {
case m.hasDependency("@playwright/test"):
return nodeTestPlaywright
case m.hasDependency("vitest"):
return nodeTestVitest
case m.hasDependency("jest"):
return nodeTestJest
default:
return nodeTestGeneric
}
}
func (m *nodePackageManifest) validationScripts() []string {
var scripts []string
for _, name := range []string{"typecheck", "build"} {
if m.hasScript(name) {
scripts = append(scripts, name)
}
}
return scripts
}
type eslintFix struct {
Content []byte
Diagnostics []string
}
func parseESLintFix(data, original []byte) (eslintFix, error) {
var results []eslintJSONResult
if err := json.Unmarshal(data, &results); err != nil {
return eslintFix{}, err
}
if len(results) != 1 {
return eslintFix{}, fmt.Errorf("expected one ESLint result, got %d", len(results))
}
result := eslintFix{Content: original}
if results[0].Output != nil {
result.Content = []byte(*results[0].Output)
}
if err := rejectEmptySourceFix("eslint", original, result.Content); err != nil {
return eslintFix{}, err
}
for _, message := range results[0].Messages {
rule := "eslint"
if message.RuleID != nil && *message.RuleID != "" {
rule = *message.RuleID
}
result.Diagnostics = append(result.Diagnostics, fmt.Sprintf("%s:%d:%d: %s: %s", rule, message.Line, message.Column, eslintSeverity(message.Severity), message.Message))
}
return result, nil
}
func eslintSeverity(value int) string {
if value >= 2 {
return "error"
}
return "warning"
}
func (c *Code) runnerEnvironment(ctx context.Context) runners.RunnerEnvironment {
var runtimeContext *basev0.RuntimeContext
if c.Service.Base != nil && c.Service.Base.Runtime != nil {
runtimeContext = c.Service.Base.Runtime.RuntimeContext
}
return runners.ResolveStandaloneEnvironment(ctx, c.sourceDir(), runtimeContext)
}
// semanticOpts installs the tree-sitter source analyzer that core omits by
// default (so Go agents can build CGO-free). This agent forwards a semantic
// index through its Tooling and already releases with CGO_ENABLED=1, so it
// opts back in explicitly. See core/code.WithSemanticAnalyzer.
func semanticOpts() []corecode.ServerOption {
return []corecode.ServerOption{corecode.WithSemanticAnalyzer(semantic.New())}
}