@mayder/devibe 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # DeVibe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Vibe code checker.** Entiende qué escribió tu IA y revisa sus cambios en tu repo local. Elige un punto de entrada, sigue el recorrido y abre el fragmento que explica cada paso.
4
+
5
+ [Sitio de DeVibe](https://devibe-xi.vercel.app/) · [Demo pública](https://devibe-xi.vercel.app/demo/)
6
+
7
+ ## Probar la demo
8
+
9
+ Requiere Node.js 24 o posterior.
10
+
11
+ ```sh
12
+ npx @mayder/devibe demo
13
+ ```
14
+
15
+ La demo de Support Desk compara dos versiones de `POST /tickets`. Un título de solo espacios pasa de guardarse a devolver `422`. Puedes ver el antes y el después, la línea que evita la escritura y el recorrido desde el mapa isométrico.
16
+
17
+ ## Así se ve
18
+
19
+ **Entender** muestra la acción, las piezas del recorrido y el código que respalda el paso seleccionado.
20
+
21
+ ![Vista Entender de DeVibe en modo claro, con el mapa isométrico y el código de la validación](https://raw.githubusercontent.com/MayderC/devibe/main/docs/learn.png)
22
+
23
+ **Ver cambios** sitúa el código anterior y el actual junto al efecto observado.
24
+
25
+ ![Vista Ver cambios de DeVibe en modo oscuro, con la condición nueva y el código resaltado](https://raw.githubusercontent.com/MayderC/devibe/main/docs/diff.png)
26
+
27
+ ## Abrir un repositorio
28
+
29
+ Desde la carpeta del repo, con Git y la CLI de Graphify Labs disponibles:
30
+
31
+ ```sh
32
+ npx @mayder/devibe open .
33
+ ```
34
+
35
+ DeVibe ejecuta Graphify con `--code-only` o puede reutilizar un grafo existente de la misma versión con `--graph graphify-out/graph.json`. **Entender** muestra las llamadas extraídas e inferidas con sus referencias cuando están disponibles. **Ver cambios** compara `HEAD` con el árbol de trabajo. Usa `--base <ref>` para elegir otra base y `--no-browser` para imprimir la URL sin abrir el navegador. [Graphify Labs](https://github.com/Graphify-Labs/graphify)
36
+
37
+ ```sh
38
+ npx @mayder/devibe open . --base main
39
+ ```
40
+
41
+ DeVibe se sirve en `127.0.0.1`. Graphify y Git se ejecutan localmente. La demo funciona con Node.js y npm, y el análisis automático de un proyecto requiere Graphify. Para usar un ejecutable en otra ubicación, define `ATLAS_GRAPHIFY` con su ruta.
42
+
43
+ El visor ofrece tema claro verde lima y tema oscuro. El tema de código **DeVibe** viene seleccionado y se puede cambiar por un tema claro u oscuro. El resaltado funciona localmente en fragmentos y diffs. [Highlight.js](https://highlightjs.org/)
44
+
45
+ ## Estado
46
+
47
+ La primera versión explora llamadas estáticas y cambios locales. El mapa isométrico está disponible en la demo de Support Desk. La agrupación automática y las explicaciones gráficas de funciones están en el plan de Learn.
package/bin/devibe.mjs ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../dist/cli.js'
3
+
4
+ runCli().catch(error => {
5
+ console.error(error instanceof Error ? error.message : error)
6
+ process.exitCode = 1
7
+ })
package/dist/cli.js ADDED
@@ -0,0 +1,50 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { parseArgs } from 'node:util'
3
+ import { openGraphProject } from './graphify.js'
4
+ import { startServer, } from './server.js'
5
+ import { supportDesk } from './support-desk.js'
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+ function openBrowser(url ) {
14
+ const options = process.platform === 'win32'
15
+ ? { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] }
16
+ : { command: process.platform === 'darwin' ? 'open' : 'xdg-open', args: [url] }
17
+ const child = spawn(options.command, options.args, { stdio: 'ignore', windowsHide: true })
18
+ child.on('error', () => console.error(`Abre DeVibe en ${url}`))
19
+ child.unref()
20
+ }
21
+
22
+ export async function runCli(preset ) {
23
+ const usage = `Uso:
24
+ devibe demo [--no-browser]
25
+ devibe open [ruta] [--graph archivo.json] [--base ref] [--no-browser]${preset ? `\n devibe ${preset.name} <ruta> [--no-browser]` : ''}`
26
+ const { positionals, values } = parseArgs({
27
+ allowPositionals: true,
28
+ options: { help: { type: 'boolean', short: 'h' }, 'no-browser': { type: 'boolean' }, graph: { type: 'string' }, base: { type: 'string' } },
29
+ })
30
+ if (values.help) {
31
+ console.log(usage)
32
+ return
33
+ }
34
+ const [command = 'demo', path = '.'] = positionals
35
+ if (!['demo', 'open', preset?.name].includes(command) || positionals.length > 2 || (command === 'demo' && positionals.length > 1)
36
+ || (command !== 'open' && (values.graph !== undefined || values.base !== undefined))) {
37
+ throw new Error(usage)
38
+ }
39
+ if (command === 'open') console.log(values.graph ? 'DeVibe · Leyendo grafo y cambios locales…' : 'DeVibe · Extrayendo llamadas con Graphify…')
40
+ const inspection = command === 'open' ? await openGraphProject(path, values)
41
+ : command === preset?.name ? await preset.open(path) : { atlasCase: await supportDesk() }
42
+ const { atlasCase, ...routes } = inspection
43
+ const { server, url } = await startServer(atlasCase, routes)
44
+ console.log(`DeVibe · ${atlasCase.project}`)
45
+ console.log(url)
46
+ console.log('Ctrl+C para cerrar DeVibe.')
47
+ process.once('SIGINT', () => server.close())
48
+ process.once('SIGTERM', () => server.close())
49
+ if (!values['no-browser']) openBrowser(url)
50
+ }
package/dist/diff.js ADDED
@@ -0,0 +1,61 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ export function parseChangedFiles(output ) {
21
+ const parts = output.split('\0')
22
+ const entries = []
23
+ for (let i = 0; i < parts.length && parts[i];) {
24
+ const status = parts[i++]
25
+ const first = parts[i++]
26
+ if (/^[RC]/.test(status)) {
27
+ entries.push({ status, previous: first, path: parts[i++] })
28
+ } else {
29
+ entries.push({ status, path: first })
30
+ }
31
+ }
32
+ return entries
33
+ }
34
+
35
+ export function parsePatch(file , output ) {
36
+ const patch = { file, hunks: [], summary: [] }
37
+ let hunk
38
+ let before = 0
39
+ let after = 0
40
+ for (const line of output.replace(/\n$/, '').split('\n')) {
41
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
42
+ if (header) {
43
+ hunk = { header: line, lines: [] }
44
+ patch.hunks.push(hunk)
45
+ before = Number(header[1])
46
+ after = Number(header[2])
47
+ } else if (!hunk || line.startsWith('diff --git ')) {
48
+ hunk = undefined
49
+ if (/^(Binary files|old mode|new mode|similarity index|rename (?:from|to) )/.test(line)) patch.summary.push(line)
50
+ } else if (line.startsWith('+')) {
51
+ hunk.lines.push({ kind: 'add', after: after++, text: line.slice(1) })
52
+ } else if (line.startsWith('-')) {
53
+ hunk.lines.push({ kind: 'remove', before: before++, text: line.slice(1) })
54
+ } else if (line.startsWith(' ')) {
55
+ hunk.lines.push({ kind: 'context', before: before++, after: after++, text: line.slice(1) })
56
+ } else if (line.startsWith('\\')) {
57
+ hunk.lines.push({ kind: 'note', text: line })
58
+ }
59
+ }
60
+ return patch
61
+ }
@@ -0,0 +1,141 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { access, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'
3
+ import { homedir, tmpdir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+
7
+ import { excerpt, LocalGitSource } from './source.js'
8
+
9
+ const exec = promisify(execFile)
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+ export function parseGraph(value ) {
26
+ if (!value || typeof value !== 'object' || !('nodes' in value) || !('links' in value) || !Array.isArray(value.nodes) || !Array.isArray(value.links)) {
27
+ throw new Error('El grafo debe contener los campos nodes y links de Graphify.')
28
+ }
29
+ const nodes = new Map ()
30
+ for (const node of value.nodes) {
31
+ if (!node || typeof node.id !== 'string' || typeof node.label !== 'string') continue
32
+ nodes.set(node.id, { id: node.id, label: node.label, file: typeof node.source_file === 'string' ? node.source_file : undefined })
33
+ }
34
+ const outgoing = new Map ()
35
+ for (const edge of value.links) {
36
+ if (!edge || edge.relation !== 'calls' || !nodes.has(edge.source) || !nodes.has(edge.target)) continue
37
+ const location = typeof edge.source_location === 'string' ? /^L(\d+)\b/.exec(edge.source_location) : null
38
+ const provenance = edge.confidence === 'EXTRACTED' ? 'extracted' : edge.confidence === 'INFERRED' ? 'inferred' : 'unknown'
39
+ const entry = { source: edge.source, target: edge.target, file: typeof edge.source_file === 'string' ? edge.source_file : undefined, line: location ? Number(location[1]) : undefined, provenance }
40
+ const relations = outgoing.get(entry.source) ?? []
41
+ relations.push(entry)
42
+ outgoing.set(entry.source, relations)
43
+ }
44
+ return { nodes, outgoing }
45
+ }
46
+
47
+ async function extract(root ) {
48
+ const installed = join(homedir(), '.local', 'bin', process.platform === 'win32' ? 'graphify.exe' : 'graphify')
49
+ const executable = process.env.ATLAS_GRAPHIFY || await access(installed).then(() => installed, () => process.platform === 'win32' ? 'graphify.exe' : 'graphify')
50
+ const tempRoot = resolve(tmpdir())
51
+ const temp = await mkdtemp(join(tempRoot, 'atlas-graph-'))
52
+ try {
53
+ await exec(executable, ['extract', '.', '--code-only', '--out', temp], {
54
+ cwd: root, env: { ...process.env, GRAPHIFY_BACKEND: 'none' }, windowsHide: true, maxBuffer: 4 * 1024 * 1024,
55
+ })
56
+ return await readFile(join(temp, 'graphify-out', 'graph.json'), 'utf8')
57
+ } catch (cause) {
58
+ const detail = cause instanceof Error ? ` ${cause.message}` : ''
59
+ throw new Error(`Graphify Labs no pudo extraer el código. Instala la CLI con uv tool install graphifyy, indica ATLAS_GRAPHIFY o usa --graph con un grafo existente.${detail}`, { cause })
60
+ } finally {
61
+ if (dirname(temp) === tempRoot && basename(temp).startsWith('atlas-graph-')) await rm(temp, { recursive: true, force: true })
62
+ }
63
+ }
64
+
65
+ function inside(root , file ) {
66
+ const path = relative(root, resolve(root, file))
67
+ return path && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path.replaceAll(sep, '/') : undefined
68
+ }
69
+
70
+ export async function openGraphProject(path , options = {}) {
71
+ const root = await realpath(await new LocalGitSource(path).topLevel())
72
+ const git = new LocalGitSource(root)
73
+ const base = await git.resolve(options.base ?? 'HEAD')
74
+ const graphFile = options.graph ? resolve(options.graph) : undefined
75
+ const graphFolder = graphFile ? dirname(graphFile) : undefined
76
+ const referenceRoot = graphFolder && basename(graphFolder) === 'graphify-out' ? dirname(graphFolder) : root
77
+ const sourcePath = (file ) => inside(root, resolve(referenceRoot, file)) ?? inside(root, file)
78
+ const [raw, comparison] = await Promise.all([
79
+ graphFile ? readFile(graphFile, 'utf8') : extract(root), git.comparison(base),
80
+ ])
81
+ const { nodes, outgoing } = parseGraph(JSON.parse(raw.replace(/^\uFEFF/, '')))
82
+ const changed = new Map(comparison.files.map(file => [file.path, file]))
83
+ const entries = [...outgoing].map(([id, edges]) => {
84
+ const node = nodes.get(id)
85
+ const file = node.file ? sourcePath(node.file) ?? '' : ''
86
+ return { id, label: node.label, file, count: edges.length }
87
+ }).sort((a, b) => Number(changed.has(b.file)) - Number(changed.has(a.file)) || b.count - a.count || a.label.localeCompare(b.label))
88
+ const snapshots = new Map ()
89
+
90
+ async function readWorkingFile(file ) {
91
+ const real = await realpath(resolve(root, file))
92
+ if (!inside(root, real)) return undefined
93
+ const info = await stat(real)
94
+ if (!info.isFile() || info.size > 2 * 1024 * 1024) return undefined
95
+ const content = await readFile(real, 'utf8')
96
+ return content.includes('\0') ? undefined : content
97
+ }
98
+
99
+ async function evidence(edge ) {
100
+ const file = edge.file && sourcePath(edge.file)
101
+ if (!file || !edge.line) return undefined
102
+ if (!snapshots.has(file)) snapshots.set(file, readWorkingFile(file).catch(() => undefined))
103
+ const content = await snapshots.get(file)
104
+ if (!content) return undefined
105
+ const lines = content.replace(/\r?\n$/, '').split(/\r?\n/)
106
+ const focus = edge.line
107
+ if (focus > lines.length) return undefined
108
+ return excerpt(file, content, focus, Math.max(1, focus - 1), Math.min(lines.length, focus + 2))
109
+ }
110
+
111
+ async function flow(entry ) {
112
+ const direct = outgoing.get(entry)
113
+ if (!direct) return undefined
114
+ const next = direct.flatMap(edge => edge.target === entry ? [] : outgoing.get(edge.target) ?? [])
115
+ const sketch = [...new Set([...direct, ...next])].slice(0, 8)
116
+ return Promise.all(sketch.map(async edge => {
117
+ const from = nodes.get(edge.source)
118
+ const to = nodes.get(edge.target)
119
+ const after = await evidence(edge)
120
+ const file = after && changed.get(after.file)
121
+ const patch = file ? await comparison.read(file.path)?.catch(() => undefined) : undefined
122
+ const changedLine = patch?.hunks.some(hunk => hunk.lines.some(line => line.kind === 'add' && line.after === after?.focus))
123
+ const change = changedLine ? 'Línea añadida o editada' : file ? 'Archivo en el diff' : after ? 'Fuera del diff' : 'Sin ubicación verificada'
124
+ const description = `Graphify relaciona ${from.label} con ${to.label}.`
125
+ return { title: to.label, symbol: `${from.label} → ${to.label}`, icon: 'arrow-right-left', change, explanation: description, effect: `${description} ${change}.`, after, provenance: edge.provenance }
126
+ }))
127
+ }
128
+
129
+ const selected = entries[0]?.id ?? ''
130
+ const atlasCase = {
131
+ project: basename(root), area: options.graph ? 'Grafo importado' : 'Graphify local', title: 'Explorar llamadas del repo', environment: 'local',
132
+ summary: 'Hasta ocho conexiones de dos niveles. El grafo muestra relaciones estáticas.', base, head: 'árbol de trabajo',
133
+ diff: { title: 'Cambios locales', explanation: 'Git compara la revisión base con el árbol de trabajo. Cada archivo se puede abrir por separado.', files: comparison.files.map(file => file.path) },
134
+ review: { title: 'Revisión local', description: 'Selecciona una llamada y abre el diff del archivo.', criteria: [] },
135
+ labels: { request: '', database: '', response: '' },
136
+ places: { web: { title: '', role: '', change: '' }, api: { title: '', role: '', change: '' }, data: { title: '', role: '', change: '' }, error: { title: '', role: '', change: '' } },
137
+ flow: (await flow(selected)) ?? [], error: { title: '', explanation: '', effect: '' }, details: { symbol: [], call: [] },
138
+ graph: { entries, selected }, hasPatches: true,
139
+ }
140
+ return { atlasCase, flow, patch: comparison.read }
141
+ }
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2006, Ivan Sagalaev.
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.